app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
+24
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "rune-motion"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Rune's animation runtime: analytic springs, retargetable tracks, presence, layout and matched-geometry animation, driven by a render thread."
|
||||
publish = false
|
||||
autotests = false
|
||||
|
||||
[features]
|
||||
default = []
|
||||
serde = ["dep:serde"]
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, features = ["derive"], optional = true }
|
||||
|
||||
[[test]]
|
||||
name = "integration"
|
||||
|
||||
[[test]]
|
||||
name = "alloc"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
# rune-motion
|
||||
|
||||
Rune's animation runtime: springs, tweens, decay, keyframes, retargeting, presence and
|
||||
transitions (blur-replace included), layout animation, matched geometry and choreography. It is
|
||||
plain math and data structures with no renderer dependency and no required dependencies (the
|
||||
optional `serde` feature covers the config types). App code states targets. The render thread
|
||||
samples them once per frame and gets back what to draw.
|
||||
|
||||
```rust
|
||||
use rune_motion::prelude::*;
|
||||
|
||||
let mut scene = Scene::new();
|
||||
let card = NodeId(1);
|
||||
|
||||
// The first build never animates.
|
||||
scene.insert(card, NodeSpec::new(Rect::new(0.0, 0.0, 320.0, 80.0)).radius(12.0), Mount::Initial);
|
||||
|
||||
// Later: a new row blurs in place, the card reflows with width leading, then something leaves.
|
||||
let row = NodeId(2);
|
||||
scene.insert(row, NodeSpec::new(Rect::new(0.0, 96.0, 320.0, 44.0))
|
||||
.parent(card)
|
||||
.transition(Transition::blur_replace()), Mount::Animated);
|
||||
scene.set_frame(card, Rect::new(0.0, 0.0, 360.0, 160.0), LayoutAnim::new(motion::MORPH).width_leads());
|
||||
scene.remove(NodeId(3)); // stays drawn until its exit settles
|
||||
|
||||
let out = scene.frame_at(1.0 / 120.0); // render thread, once per frame
|
||||
for p in out.changed { /* draw p.rect, p.opacity, p.affine(), p.blur, p.mask … */ }
|
||||
```
|
||||
|
||||
Without a scene graph, the store animates any property directly:
|
||||
|
||||
```rust
|
||||
let mut store = AnimationStore::new();
|
||||
store.set(id, prop::OPACITY, 0.0);
|
||||
store.animate(id, prop::OPACITY, 1.0, motion::SETTLE); // spring, bounce 0
|
||||
store.animate(id, prop::FRAME, rect, motion::MORPH.delay(0.05)); // edges, delayed
|
||||
store.animate(id, X, 40.0, Curve::ease_in_out(0.3).completion(7)); // tween, Completed{token: 7}
|
||||
store.release(id, X, fling_v, Release::DecayClamped { decay: Decay::IOS_NORMAL, min: 0.0, max, spring: motion::SNAP });
|
||||
store.tick_at(now);
|
||||
let x = store.get(id, X);
|
||||
```
|
||||
|
||||
## API overview
|
||||
|
||||
| Piece | What it is |
|
||||
|---|---|
|
||||
| `Spring` | SwiftUI `Spring(duration:bounce:)`, bounce 0 by default, closed form in every damping regime. `sample`, `settling_duration`, `css_linear` (WAAPI export), plus constructors from response/damping fraction, ω/ζ, stiffness/damping/mass and Motion `visualDuration`. |
|
||||
| `Curve` / `Anim` | `Spring`, `Tween` (CSS cubic-bezier, steps, linear), `Decay` (iOS rates), `Keyframes` (Hermite cubics that keep velocity across keys), `Instant`. `Anim` adds `.delay()`, `.additive()`/`.merge()`, `.velocity()` and `.completion(token)`. |
|
||||
| `motion::*` tokens | `INSTANT SNAP SETTLE REFLOW GLIDE MORPH POP DRIFT CAMERA`, each with an `_EXIT` partner 10–25 % shorter (copied from Kit's motion presets), plus `motion::pair::*` `SpringPair`s and SwiftUI presets. |
|
||||
| `Animatable` | `f32`, `Vec2`, `Rect` (four edges), `Color` (premultiplied OKLab), `Corners`, `Sides`, `Transform`, `Blur`, tuples and arrays. Up to `MAX_LANES` f32 lanes. |
|
||||
| `AnimationStore` | Every animated value is a track. Retargeting keeps position and velocity. Also delays, settle and completion events, gesture `release` (spring, decay, decay-into-bounds), `retune` for live token edits, and reduced motion per `PropClass`. |
|
||||
| `Scene` | Keyed nodes with presence (exits stay mounted, revive mid-exit without a jump), `Transition`s (`opacity scale offset move push slide blur_replace reveal asymmetric combined`), layout by edges (`Travel::Parent`) or one straight screen path (`Travel::Screen`), `match_geometry`, popLayout. |
|
||||
| Choreography | `Choreography` steps cue on `Cue::now/at/started/arrived/settled(step).after(s).not_before(t)`. Also `Stagger` (from start, end, centre or an index, eased), `PhaseAnimator` and `Keyframes`. |
|
||||
| Gestures | `VelocityTracker`, `project`, `rubber_band*`, `deceleration`. |
|
||||
| `Animated<T>` | A single value outside any store, for one-off widgets. |
|
||||
| `Clock` | A display clock with pause, scale and seek, or a manual clock for tests and offline renders. |
|
||||
| `LoopTrack` / `LoopSpec` | Periodic eased opacity or clockwise rotation, sampled at clock time. `retime` preserves phase; `enabled` springs the pulse amplitude toward rest. The renderer owns visibility and scheduling. |
|
||||
| `MotionTrace` | motion-trace JSONL. `MotionTrace::from_env` opens `$RUNE_MOTION_TRACE`. |
|
||||
|
||||
### Kit's motion rules are the defaults
|
||||
|
||||
- Springs are duration plus bounce, with bounce 0 by default. Exits run 10–25 % shorter than entrances.
|
||||
- Interrupting a motion keeps its position and velocity.
|
||||
- Nothing animates on first mount. A track's first `animate` acts as `set`, and setting an unchanged target does nothing.
|
||||
- The user's direct manipulation is never animated. Gestures write values with `set` and animate only on `release`.
|
||||
- Under reduced motion, travel, scale, shape and blur change instantly, and opacity, colour and presence take a 0.18 s ease-in-out fade (`REDUCED_FADE`). Gesture values keep their curve. `match_geometry` turns into a crossfade in place.
|
||||
- Both edges of a rect snap to 1/64 device px, and settle thresholds scale with the pixel density.
|
||||
- Blur is limited to 4 px and only applies to things entering or leaving in place. A transition that travels drops its blur. Scale stays within [0.9, 1.1] and never goes to 0; `Transition::allow_small_scale()` lowers the floor to 0.5 for small glyphs. A removed node always fades out (`Effect::kit_rules`).
|
||||
- Width leads: `.width_leads()` runs the X spring at 0.78× the duration (taken from a launcher app).
|
||||
- A stationary edge gets no motion at all.
|
||||
- A node given `Scene::set_ride_trailing` keeps its place against its parent's trailing edge while the parent's width animates; its frame is still given in parent space.
|
||||
|
||||
## Design
|
||||
|
||||
**Analytic tracks.** Each value lane is `target + Σ offset layers`. A layer is a closed-form
|
||||
segment: an underdamped, critical or overdamped spring, a decay, a tween or a Hermite cubic. Each
|
||||
one is evaluated directly at the frame's timestamp. Nothing is integrated step by step, so
|
||||
results are the same at any frame rate. Sampling at the display link's *target* timestamp is
|
||||
exact, frames can be skipped, and tests can jump to any `t`. Each layer stores its own settle
|
||||
time, an upper bound that holds for the whole tail (spring envelopes, or bisection for the
|
||||
critical and overdamped cases). Once that time passes, the track snaps to `(target, 0)`, leaves
|
||||
the active list and costs nothing.
|
||||
|
||||
**Merge vs additive.** Springs, decay and keyframes *merge* by default: the store samples
|
||||
`(x, v)` and starts one new segment from there, like SwiftUI spring merging or Compose
|
||||
`animateTo`. That keeps one layer per lane and O(1) sampling. Tweens *add* by default, Core
|
||||
Animation style: the running curves continue, and a new layer animates the target delta to 0, so
|
||||
every curve keeps its shape. A test checks that additive springs give exactly the same result as
|
||||
merged springs. A lane holds at most 8 additive layers. Past that, they collapse into one merged
|
||||
segment.
|
||||
|
||||
**Struct of arrays.** Track data lives in flat lane arrays (layer, target, value, velocity), with
|
||||
generational `TrackId`s, a dense `active` list, free-list pools for extra layers and delayed
|
||||
starts, and an Fx-style hash map from `(node, prop)` to track. A tick walks only the active
|
||||
tracks, reads contiguous memory and does not allocate. `tests/alloc.rs` checks this with a
|
||||
counting allocator.
|
||||
|
||||
**Deterministic math.** `math::exp` and `math::sin_cos` are custom polynomial versions (Estrin's
|
||||
scheme, FMA on aarch64 or `+fma`, branchless quadrant fix-up). They don't depend on the
|
||||
platform's libm, so traces and goldens stay stable, and they're cheap: 5 ns for `exp` and 7.6 ns
|
||||
for `sin_cos`.
|
||||
|
||||
**Presence.** One `PRESENCE` progress (0 means absent, 1 means present) drives the insertion and
|
||||
removal effects. If a node is reversed mid-flight (it comes back while exiting, or leaves while
|
||||
entering), the effect endpoints are re-solved at the current visual state so nothing jumps.
|
||||
`Travel::Screen` interpolates root-space start and end edges with a separate progress per axis.
|
||||
`match_geometry` starts the target node at the source's exact presented rect, velocity, radius
|
||||
and fill, then removes the source immediately.
|
||||
|
||||
## Name mapping
|
||||
|
||||
| SwiftUI | Motion (motion.dev) | rune-motion |
|
||||
|---|---|---|
|
||||
| `Spring(duration:bounce:)`, `.smooth/.snappy/.bouncy` | `{ type: "spring", visualDuration, bounce }` | `Spring::new(d, b)`, `Spring::SMOOTH/SNAPPY/BOUNCY`, `Spring::from_motion(vd, b)` (Motion `visualDuration` = `duration / 1.2`) |
|
||||
| `.spring(response:dampingFraction:)` | `{ stiffness, damping, mass }` | `Spring::from_response`, `Spring::from_stiffness_damping` |
|
||||
| `.easeInOut(duration:)`, `.timingCurve` | `ease: [x1,y1,x2,y2]` | `Curve::ease_in_out(d)`, `Curve::tween(d, Easing::cubic(..))` |
|
||||
| `withAnimation(_:completion:)` | `animate(...).then` | `.completion(token)` → `MotionEvent::Completed` |
|
||||
| `.animation(..).delay(s)` | `delay` | `.delay(s)` |
|
||||
| `.transition(.opacity/.scale/.move(edge:)/.push(from:)/.blurReplace)` | `initial/animate/exit` | `Transition::opacity/scale/move_edge/push/blur_replace` |
|
||||
| `.asymmetric(insertion:removal:)`, `.combined(with:)` | separate `initial`/`exit` | `Transition::asymmetric`, `.combined` |
|
||||
| `if`/`ForEach` removal | `AnimatePresence` (`mode="popLayout"`) | `Scene::remove`, `Transition { pop_layout: true }` (the default) |
|
||||
| implicit layout animation | `layout` | `Scene::set_frame(id, rect, anim)` |
|
||||
| `matchedGeometryEffect(id:in:)` | `layoutId` | `Scene::match_geometry(from, to, anim)` |
|
||||
| `keyframeAnimator`, `KeyframeTrack` | keyframes `[a, b, c]` + `times` | `Keyframes`, `Curve::Keyframes` |
|
||||
| `phaseAnimator` | `repeat` variants | `PhaseAnimator` |
|
||||
| `ScrollView` deceleration | `inertia` | `Release::Decay` / `DecayClamped`, `Decay::IOS_NORMAL/IOS_FAST` |
|
||||
| `accessibilityReduceMotion` | `useReducedMotion` | `set_reduced_motion(true)` |
|
||||
| — | `stagger(gap, { from })` | `Stagger::new(gap).from(..)`, `Choreography::stagger` |
|
||||
|
||||
## Benchmarks
|
||||
|
||||
`cargo run --profile perf --example bench`. Every track stays active for all 120 ticks at 120 Hz.
|
||||
Each figure is the best of 9 runs on an Apple M4 build machine, which was busy with other
|
||||
jobs at the time, so treat these as upper bounds.
|
||||
|
||||
| Scenario | 10k tracks | 100k tracks |
|
||||
|---|---|---|
|
||||
| scalar spring, critical (bounce 0) | **16.8 ns** | 17.6 ns |
|
||||
| scalar spring, underdamped (bounce 0.3) | 23.6 ns | 25.0 ns |
|
||||
| scalar tween (bezier ease-in-out) | 45.6 ns | 47.0 ns |
|
||||
| colour (4 OKLab lanes) | 37.1 ns | 38.6 ns |
|
||||
| rect frame (4 edge lanes, MORPH) | 75.5 ns | 77.7 ns |
|
||||
| mixed (spring, tween, 2× additive) | 34.3 ns | 35.3 ns |
|
||||
| scene node, layout reflow → `Presented` | 132 ns (1k nodes) | 144 ns (10k nodes) |
|
||||
| `Spring::sample` standalone | 27.8 ns/call | |
|
||||
|
||||
At these speeds, 10k simultaneously moving rects take 0.76 ms per frame and a 1k-node scene
|
||||
reflow takes 0.13 ms. A steady-state tick allocates nothing. The kernel micro-bench
|
||||
(`cargo test --profile perf -- --ignored bench_layer_kinds`) measures one underdamped lane at 17 ns,
|
||||
one critical lane at 10 ns, `exp` at 5 ns and `sin_cos` at 7.6 ns.
|
||||
|
||||
## Renderer integration contract
|
||||
|
||||
Run this on the render thread once per display-link callback:
|
||||
|
||||
1. `scene.set_time(target_timestamp)`. Use the timestamp the frame will be *shown* at, not the
|
||||
current time. `Clock::frame(host)` handles pause, slow motion and seek.
|
||||
2. Apply the commits that arrived since the last frame: `insert(id, spec, mount)`, `remove(id)`,
|
||||
`set_frame(id, rect, anim)`, `animate(id, prop, target, anim)`, `set(...)` and
|
||||
`match_geometry(from, to, anim)`. Pass `Mount::Initial` for the first build.
|
||||
3. `let out = scene.frame()`, which returns a `FrameOutput`:
|
||||
- `changed: &[Presented]`: only the nodes whose presented values changed, parents before
|
||||
children.
|
||||
- `exited: &[NodeId]`: nodes whose exit settled. Stop drawing them and free their resources.
|
||||
- `events: &[MotionEvent]`: `Settled` and `Completed { token, finished }`, for app callbacks.
|
||||
- `animating: bool`: when false, pause the display link until the next commit.
|
||||
|
||||
`Presented` holds everything needed to draw one node:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `rect` | Root-space rect. It already includes every ancestor's translation and this node's own, and both edges are snapped to 1/64 device px. Draw shapes, borders and shadows at this size. |
|
||||
| `opacity` | This node's own opacity (presence × property). Apply ancestors' opacity as group opacity. |
|
||||
| `transform`, `anchor` | Scale and rotation about the root-space `anchor`, composed down the tree like `CALayer`. `affine()` returns the 2×3 matrix. |
|
||||
| `blur` | Own plus presence Gaussian sigma in points. 0 means attach no filter. Presence effects clamp to ≤ 4 pt; `blur_replace` peaks at 1.5 pt. Explicit property blur can remain at rest. |
|
||||
| `radius`, `fill` | Animated corner radii, and the fill as sRGB with straight alpha (interpolated in premultiplied OKLab). |
|
||||
| `mask` | `Mask { inset: Sides, feather: Sides }` in the node's own coordinates: how far each side is pulled in, and the gradient width on that side. Evaluate it as an SDF ramp. `mask.is_none()` means no clip. |
|
||||
| `phase` | `Entering`, `Present` or `Exiting { generation }`. |
|
||||
| `in_flow` | Turns false as soon as a popLayout exit starts. App layout should stop reserving space for the node. |
|
||||
| `flags` | motion-trace bits (`flags::ANIMATED`, `ANCESTOR_ANIMATED`, `CLIPPED`, `FILTERED`) and intent bits (own `<< 8`, ancestor `<< 16`). |
|
||||
|
||||
Call `scene.set_pixel_scale(scale)` on display changes and `scene.set_reduced_motion(on)` when the
|
||||
system setting changes. Setting `RUNE_MOTION_TRACE=/path.jsonl` and calling
|
||||
`scene.set_trace(MotionTrace::from_env(&header))` writes motion traces.
|
||||
|
||||
## Examples and tests
|
||||
|
||||
- `cargo run --example curves [dir]` writes SVG plots of the tokens, SwiftUI
|
||||
presets, curve kinds, retargeting and presence/travel paths. The current plots are in
|
||||
`demo/motion/`.
|
||||
- `cargo run --profile perf --example bench` prints the numbers above.
|
||||
- `cargo test` runs 53 tests and 1 doctest. They check the spring closed form against ODE
|
||||
integration in every regime, C¹ continuity under random retargets, that additive and merged
|
||||
springs match, delays, decay into bounds, generational reuse, zero allocation, presence revive,
|
||||
blur-replace, screen travel, matched geometry, reduced motion, choreography cues and trace
|
||||
output.
|
||||
|
||||
## Not yet
|
||||
|
||||
- `Travel::Screen` uses a separate progress per axis, so a width-leading screen path is not perfectly straight.
|
||||
- Not implemented: resize modes (mask, scale, relayout), a live token table and `tune.json`,
|
||||
live `Bound` expressions, growth caps, flight-layer z-order, and scroll physics for platforms
|
||||
other than iOS.
|
||||
- `Animated<T>` has no delay and no additive blending.
|
||||
- Multi-lane values (rects, colours) cost more than the ~20 ns target per track. The cost is
|
||||
roughly per lane.
|
||||
|
||||
Trace diagnostics: `Scene::sampling_error()` compares presented scene edges with unsnapped
|
||||
analytic samples in device pixels. `AnimationStore::audit_retargets(true)` enables inherited
|
||||
spatial spring velocity checks; `take_retarget_audit()` drains the counters. These diagnostics
|
||||
exclude renderer-owned growth/scroll and explicit velocity changes or instant cuts.
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Per-frame sampling cost. `cargo run --profile perf --example bench`
|
||||
//!
|
||||
//! Every scenario keeps all tracks active for the whole measurement (long, bouncy springs that
|
||||
//! can't settle in time) and reports the best of several runs (robust to a busy machine).
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{Prop, PropClass};
|
||||
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Spatial);
|
||||
const FRAMES: usize = 120;
|
||||
const RUNS: usize = 9;
|
||||
|
||||
// Standalone benchmark for rune-motion (which has no Rune dependencies).
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn now() -> Instant { Instant::now() }
|
||||
|
||||
fn best(v: Vec<f64>) -> f64 {
|
||||
v.into_iter().fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Builds a store, then times `FRAMES` ticks at 120 Hz. Returns ns per track per tick.
|
||||
fn bench_store(label: &str, tracks: usize, setup: impl Fn(&mut AnimationStore, NodeId, usize)) -> f64 {
|
||||
let mut runs = Vec::new();
|
||||
for _ in 0..RUNS {
|
||||
let mut st = AnimationStore::with_capacity(tracks, 4);
|
||||
for i in 0..tracks {
|
||||
setup(&mut st, NodeId(i as u64), i);
|
||||
}
|
||||
st.tick_at(0.0);
|
||||
let t0 = now();
|
||||
for f in 1..=FRAMES {
|
||||
st.tick_at(f as f64 / 120.0);
|
||||
black_box(st.events());
|
||||
}
|
||||
let el = t0.elapsed().as_nanos() as f64;
|
||||
assert_eq!(st.active_len(), tracks, "{label}: every track must still be active");
|
||||
runs.push(el / (FRAMES * tracks) as f64);
|
||||
}
|
||||
let ns = best(runs);
|
||||
println!("{label:<44} {tracks:>7} tracks {ns:>7.2} ns/track {:>7.3} ms/frame", ns * tracks as f64 / 1e6);
|
||||
ns
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("rune-motion bench ({FRAMES} frames at 120 Hz, best of {RUNS})\n");
|
||||
for &n in &[10_000usize, 100_000] {
|
||||
bench_store("scalar springs, underdamped (bounce .3)", n, |st, id, i| {
|
||||
st.set(id, X, 0.0);
|
||||
st.animate(id, X, 100.0 + (i % 13) as f32, Spring::new(3.0, 0.3));
|
||||
});
|
||||
bench_store("scalar springs, critical (bounce 0)", n, |st, id, i| {
|
||||
st.set(id, X, 0.0);
|
||||
st.animate(id, X, 100.0 + (i % 13) as f32, Spring::new(3.0, 0.0));
|
||||
});
|
||||
bench_store("scalar tweens (ease-in-out bezier)", n, |st, id, i| {
|
||||
st.set(id, X, 0.0);
|
||||
st.animate(id, X, 100.0 + (i % 13) as f32, Curve::ease_in_out(5.0));
|
||||
});
|
||||
bench_store("rect frames (4 edge lanes, MORPH)", n, |st, id, i| {
|
||||
st.set(id, prop::FRAME, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let f = (i % 17) as f32;
|
||||
st.animate(id, prop::FRAME, Rect::new(100.0 + f, 50.0, 300.0, 200.0), Spring::new(3.0, 0.16));
|
||||
});
|
||||
bench_store("colors (4 OKLab lanes)", n, |st, id, _| {
|
||||
st.set(id, prop::FILL, Color::hex(0xff3b30));
|
||||
st.animate(id, prop::FILL, Color::hex(0x007aff), Spring::new(3.0, 0.0));
|
||||
});
|
||||
bench_store("mixed: 1/3 spring, 1/3 tween, 1/3 additive x2", n, |st, id, i| {
|
||||
st.set(id, X, 0.0);
|
||||
match i % 3 {
|
||||
0 => {
|
||||
st.animate(id, X, 50.0, Spring::new(3.0, 0.2));
|
||||
}
|
||||
1 => {
|
||||
st.animate(id, X, 50.0, Curve::ease_in_out(5.0));
|
||||
}
|
||||
_ => {
|
||||
st.animate(id, X, 50.0, Spring::new(3.0, 0.0));
|
||||
st.animate(id, X, 80.0, Spring::new(3.0, 0.0).additive());
|
||||
}
|
||||
}
|
||||
});
|
||||
println!();
|
||||
}
|
||||
|
||||
// Scene: every node's frame animating, presented values out.
|
||||
for &n in &[1_000usize, 10_000] {
|
||||
let mut runs = Vec::new();
|
||||
for _ in 0..RUNS {
|
||||
let mut s = Scene::new();
|
||||
for i in 0..n {
|
||||
s.insert(NodeId(i as u64), NodeSpec::new(Rect::new(0.0, i as f32 * 20.0, 300.0, 20.0)), Mount::Initial);
|
||||
}
|
||||
s.frame_at(0.0);
|
||||
for i in 0..n {
|
||||
s.set_frame(NodeId(i as u64), Rect::new(10.0, i as f32 * 24.0, 300.0, 24.0), Spring::new(3.0, 0.0));
|
||||
}
|
||||
s.frame_at(1.0 / 120.0);
|
||||
let t0 = now();
|
||||
for f in 2..FRAMES + 2 {
|
||||
let out = s.frame_at(f as f64 / 120.0);
|
||||
black_box(out.changed.len());
|
||||
}
|
||||
runs.push(t0.elapsed().as_nanos() as f64 / (FRAMES * n) as f64);
|
||||
}
|
||||
let ns = best(runs);
|
||||
println!("{:<44} {n:>7} nodes {ns:>7.2} ns/node {:>7.3} ms/frame", "scene: layout reflow → Presented", ns * n as f64 / 1e6);
|
||||
}
|
||||
|
||||
// Raw closed-form sample, no store.
|
||||
let s = Spring::new(0.5, 0.3);
|
||||
let iters = 2_000_000;
|
||||
let runs = (0..RUNS)
|
||||
.map(|_| {
|
||||
let t0 = now();
|
||||
let mut acc = 0.0;
|
||||
for i in 0..iters {
|
||||
let (x, v) = s.sample(0.0, 0.0, 1.0, black_box((i % 1000) as f32 * 1e-3));
|
||||
acc += x + v;
|
||||
}
|
||||
black_box(acc);
|
||||
t0.elapsed().as_nanos() as f64 / iters as f64
|
||||
})
|
||||
.collect();
|
||||
println!("\nSpring::sample (closed form, standalone) {:>7.2} ns/call", best(runs));
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! Writes SVG plots of every preset (position and velocity over time), a retarget scenario, a
|
||||
//! presence enter/exit/revive, and screen-space vs parent-space paths into `demo/motion/`.
|
||||
//!
|
||||
//! `cargo run --example curves [out-dir]`
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{Keyframes, Prop, PropClass, Transition};
|
||||
|
||||
const BLUE: &str = "#2f6fec";
|
||||
const ORANGE: &str = "#e8833a";
|
||||
const GREY: &str = "#9aa3ad";
|
||||
const GREEN: &str = "#2fa35a";
|
||||
const RED: &str = "#d64545";
|
||||
const PURPLE: &str = "#8a5cd6";
|
||||
|
||||
struct Series {
|
||||
points: Vec<(f32, f32)>,
|
||||
color: &'static str,
|
||||
dashed: bool,
|
||||
label: &'static str,
|
||||
}
|
||||
|
||||
struct Panel {
|
||||
title: String,
|
||||
x: (f32, f32),
|
||||
y: (f32, f32),
|
||||
series: Vec<Series>,
|
||||
marks: Vec<f32>,
|
||||
equal_axes: bool,
|
||||
}
|
||||
|
||||
fn svg(panels: &[Panel], cols: usize, pw: f32, ph: f32, title: &str) -> String {
|
||||
let rows = panels.len().div_ceil(cols);
|
||||
// Square canvas so Quick Look thumbnails (qlmanage -t) don't crop it.
|
||||
let side = (cols as f32 * pw).max(rows as f32 * ph + 40.0);
|
||||
let (w, h) = (side, side);
|
||||
let mut s = String::new();
|
||||
write!(
|
||||
s,
|
||||
r##"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}" font-family="-apple-system, Helvetica, sans-serif"><rect width="100%" height="100%" fill="white"/><text x="16" y="26" font-size="16" font-weight="600" fill="#222">{title}</text>"##
|
||||
).ok();
|
||||
for (i, p) in panels.iter().enumerate() {
|
||||
let (ox, oy) = ((i % cols) as f32 * pw, (i / cols) as f32 * ph + 40.0);
|
||||
let (l, t, r, b) = (ox + 44.0, oy + 28.0, ox + pw - 14.0, oy + ph - 26.0);
|
||||
let (x0, mut x1, y0, mut y1) = (p.x.0, p.x.1, p.y.0, p.y.1);
|
||||
if p.equal_axes {
|
||||
let span = (x1 - x0).max(y1 - y0);
|
||||
x1 = x0 + span;
|
||||
y1 = y0 + span;
|
||||
}
|
||||
let px = |x: f32| l + (x - x0) / (x1 - x0) * (r - l);
|
||||
let py = |y: f32| if p.equal_axes { t + (y - y0) / (y1 - y0) * (b - t) } else { b - (y - y0) / (y1 - y0) * (b - t) };
|
||||
write!(s, r##"<rect x="{l}" y="{t}" width="{}" height="{}" fill="#fafbfc" stroke="#e3e6ea"/>"##, r - l, b - t).ok();
|
||||
write!(s, r##"<text x="{l}" y="{}" font-size="12" font-weight="600" fill="#333">{}</text>"##, t - 9.0, p.title).ok();
|
||||
if !p.equal_axes {
|
||||
for v in [0.0f32, 1.0] {
|
||||
if v >= y0 && v <= y1 {
|
||||
write!(s, r##"<line x1="{l}" x2="{r}" y1="{0}" y2="{0}" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="{1}" y="{2}" font-size="9" fill="#888" text-anchor="end">{v}</text>"##, py(v), l - 4.0, py(v) + 3.0).ok();
|
||||
}
|
||||
}
|
||||
write!(s, r##"<text x="{r}" y="{}" font-size="9" fill="#888" text-anchor="end">{:.2} s</text>"##, b + 14.0, x1).ok();
|
||||
}
|
||||
for m in &p.marks {
|
||||
write!(s, r##"<line x1="{0}" x2="{0}" y1="{t}" y2="{b}" stroke="{RED}" stroke-width="1" stroke-dasharray="2 3"/>"##, px(*m)).ok();
|
||||
}
|
||||
for (k, se) in p.series.iter().enumerate() {
|
||||
let mut d = String::new();
|
||||
for (j, &(x, y)) in se.points.iter().enumerate() {
|
||||
write!(d, "{}{:.2},{:.2} ", if j == 0 { "M" } else { "L" }, px(x), py(y)).ok();
|
||||
}
|
||||
let dash = if se.dashed { r#" stroke-dasharray="4 3""# } else { "" };
|
||||
write!(s, r#"<path d="{d}" fill="none" stroke="{}" stroke-width="1.8"{dash}/>"#, se.color).ok();
|
||||
if !se.label.is_empty() {
|
||||
let ly = t + 12.0 + k as f32 * 12.0;
|
||||
write!(s, r#"<text x="{}" y="{ly}" font-size="9" fill="{}" text-anchor="end">{}</text>"#, r - 4.0, se.color, se.label).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
s.push_str("</svg>");
|
||||
s
|
||||
}
|
||||
|
||||
fn normalized(v: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
|
||||
let m = v.iter().map(|p| p.1.abs()).fold(1e-6, f32::max);
|
||||
v.into_iter().map(|(t, y)| (t, y / m)).collect()
|
||||
}
|
||||
|
||||
fn spring_panel(name: &str, s: Spring, t_max: f32) -> Panel {
|
||||
let n = 300;
|
||||
let (mut x, mut v) = (Vec::new(), Vec::new());
|
||||
for i in 0..=n {
|
||||
let t = t_max * i as f32 / n as f32;
|
||||
let (p, q) = s.sample(0.0, 0.0, 1.0, t);
|
||||
x.push((t, p));
|
||||
v.push((t, q));
|
||||
}
|
||||
Panel {
|
||||
title: format!("{name} {}/{}", s.duration, s.bounce),
|
||||
x: (0.0, t_max),
|
||||
y: (-0.45, 1.25),
|
||||
series: vec![
|
||||
Series { points: x, color: BLUE, dashed: false, label: "position" },
|
||||
Series { points: normalized(v), color: ORANGE, dashed: true, label: "velocity (norm.)" },
|
||||
],
|
||||
marks: vec![s.duration],
|
||||
equal_axes: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn curve_panel(name: &str, anim: Anim, from: f32, to: f32, t_max: f32) -> Panel {
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Other);
|
||||
let mut st = AnimationStore::new();
|
||||
let id = NodeId(1);
|
||||
st.set(id, X, from);
|
||||
st.animate(id, X, to, anim);
|
||||
let (mut x, mut v) = (Vec::new(), Vec::new());
|
||||
for i in 0..=300 {
|
||||
let t = t_max * i as f32 / 300.0;
|
||||
st.set_time(t as f64);
|
||||
x.push((t, st.sample(id, X).unwrap()));
|
||||
v.push((t, st.sample_velocity(id, X).unwrap()));
|
||||
}
|
||||
Panel {
|
||||
title: name.to_string(),
|
||||
x: (0.0, t_max),
|
||||
y: (-0.45, 1.25),
|
||||
series: vec![
|
||||
Series { points: x, color: BLUE, dashed: false, label: "position" },
|
||||
Series { points: normalized(v), color: ORANGE, dashed: true, label: "velocity (norm.)" },
|
||||
],
|
||||
marks: vec![],
|
||||
equal_axes: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let out = std::env::args().nth(1).unwrap_or_else(|| concat!(env!("CARGO_MANIFEST_DIR"), "/../../demo/motion").into());
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let write = |name: &str, s: String| {
|
||||
let path = format!("{out}/{name}");
|
||||
std::fs::write(&path, s).unwrap();
|
||||
println!("wrote {path}");
|
||||
};
|
||||
|
||||
// 1. Kit's tokens (enter and exit) and SwiftUI's presets.
|
||||
let mut panels = Vec::new();
|
||||
for (name, pair) in motion::ALL {
|
||||
panels.push(spring_panel(name, pair.enter, 1.2));
|
||||
panels.push(spring_panel(&format!("{name} exit"), pair.exit, 1.2));
|
||||
}
|
||||
write("tokens.svg", svg(&panels, 4, 300.0, 170.0, "Kit motion tokens: position (blue), velocity (orange), duration (red)"));
|
||||
|
||||
let panels = vec![
|
||||
spring_panel(".smooth", Spring::SMOOTH, 1.5),
|
||||
spring_panel(".snappy", Spring::SNAPPY, 1.5),
|
||||
spring_panel(".bouncy", Spring::BOUNCY, 1.5),
|
||||
spring_panel("overdamped", Spring::new(0.5, -0.5), 1.5),
|
||||
spring_panel("interactive", Spring::interactive(), 1.5),
|
||||
spring_panel("very bouncy", Spring::new(0.5, 0.7), 1.5),
|
||||
];
|
||||
write("swiftui.svg", svg(&panels, 3, 300.0, 170.0, "SwiftUI springs"));
|
||||
|
||||
// 2. Other curves.
|
||||
let panels = vec![
|
||||
curve_panel("CSS ease", Curve::tween(0.6, Easing::EASE).into(), 0.0, 1.0, 0.8),
|
||||
curve_panel("Kit CSS enter 150 ms", motion::CSS_ENTER.into(), 0.0, 1.0, 0.3),
|
||||
curve_panel("Kit CSS exit 110 ms", motion::CSS_EXIT.into(), 0.0, 1.0, 0.3),
|
||||
curve_panel("overshoot bezier", Curve::tween(0.5, Easing::OVERSHOOT).into(), 0.0, 1.0, 0.7),
|
||||
curve_panel("steps(4)", Curve::tween(0.6, Easing::Steps(4, rune_motion::StepPosition::End)).into(), 0.0, 1.0, 0.8),
|
||||
curve_panel("linear() piecewise", Curve::tween(0.6, Easing::Piecewise(&[[0.0, 0.0], [0.3, 0.7], [0.6, 0.9], [1.0, 1.0]])).into(), 0.0, 1.0, 0.8),
|
||||
{
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Gesture);
|
||||
let mut st = AnimationStore::new();
|
||||
st.set(NodeId(1), X, 0.0);
|
||||
st.release(NodeId(1), X, 2.0, Release::Decay(Decay::IOS_NORMAL));
|
||||
let (mut x, mut v) = (Vec::new(), Vec::new());
|
||||
for i in 0..=300 {
|
||||
let t = 3.0 * i as f32 / 300.0;
|
||||
st.set_time(t as f64);
|
||||
x.push((t, st.sample(NodeId(1), X).unwrap()));
|
||||
v.push((t, st.sample_velocity(NodeId(1), X).unwrap()));
|
||||
}
|
||||
Panel {
|
||||
title: "decay 0.998/ms (fling v=2)".into(),
|
||||
x: (0.0, 3.0),
|
||||
y: (-0.1, 1.25),
|
||||
series: vec![
|
||||
Series { points: x, color: BLUE, dashed: false, label: "position" },
|
||||
Series { points: normalized(v), color: ORANGE, dashed: true, label: "velocity" },
|
||||
],
|
||||
marks: vec![],
|
||||
equal_axes: false,
|
||||
}
|
||||
},
|
||||
{
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Other);
|
||||
let mut st = AnimationStore::new();
|
||||
st.set(NodeId(1), X, 0.0);
|
||||
let kf = Keyframes::new().linear(0.4, 0.15).cubic(1.1, 0.2).cubic(0.8, 0.15).spring(1.0, motion::POP);
|
||||
st.play_keyframes(NodeId(1), X, &kf);
|
||||
let (mut x, mut v) = (Vec::new(), Vec::new());
|
||||
for i in 0..=300 {
|
||||
let t = 1.0 * i as f32 / 300.0;
|
||||
st.tick_at(t as f64);
|
||||
x.push((t, st.get(NodeId(1), X).unwrap()));
|
||||
v.push((t, st.velocity(NodeId(1), X).unwrap()));
|
||||
}
|
||||
Panel {
|
||||
title: "keyframes: linear, cubic, cubic, spring".into(),
|
||||
x: (0.0, 1.0),
|
||||
y: (-0.45, 1.25),
|
||||
series: vec![
|
||||
Series { points: x, color: BLUE, dashed: false, label: "position" },
|
||||
Series { points: normalized(v), color: ORANGE, dashed: true, label: "velocity" },
|
||||
],
|
||||
marks: vec![0.15, 0.35, 0.5],
|
||||
equal_axes: false,
|
||||
}
|
||||
},
|
||||
];
|
||||
write("curves.svg", svg(&panels, 4, 300.0, 170.0, "Tweens, decay and keyframes"));
|
||||
|
||||
// 3. Retargeting mid-flight: merge (springs) and additive (tweens), with the naive restart.
|
||||
let retarget = |anim: Anim, naive: bool| {
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Other);
|
||||
let mut st = AnimationStore::new();
|
||||
st.set(NodeId(1), X, 0.0);
|
||||
st.animate(NodeId(1), X, 1.0, anim);
|
||||
let plan = [(0.15f64, 0.2f32), (0.32, 1.1), (0.55, 0.6)];
|
||||
let (mut x, mut v) = (Vec::new(), Vec::new());
|
||||
let mut k = 0;
|
||||
for i in 0..=480 {
|
||||
let t = i as f64 / 400.0;
|
||||
st.set_time(t);
|
||||
if k < plan.len() && t >= plan[k].0 {
|
||||
if naive {
|
||||
let cur = st.sample(NodeId(1), X).unwrap();
|
||||
st.set(NodeId(1), X, cur);
|
||||
}
|
||||
st.animate(NodeId(1), X, plan[k].1, anim);
|
||||
k += 1;
|
||||
}
|
||||
x.push((t as f32, st.sample(NodeId(1), X).unwrap()));
|
||||
v.push((t as f32, st.sample_velocity(NodeId(1), X).unwrap()));
|
||||
}
|
||||
(x, normalized(v))
|
||||
};
|
||||
let mut panels = Vec::new();
|
||||
for (name, anim) in [
|
||||
("spring merge (SwiftUI): keeps x and v", Anim::from(motion::REFLOW)),
|
||||
("tween additive (Core Animation)", Curve::ease_in_out(0.35).into()),
|
||||
("spring, bounce .3", Anim::from(Spring::new(0.4, 0.3))),
|
||||
] {
|
||||
let (x, v) = retarget(anim, false);
|
||||
let (nx, nv) = retarget(anim, true);
|
||||
panels.push(Panel {
|
||||
title: name.into(),
|
||||
x: (0.0, 1.2),
|
||||
y: (-1.1, 1.3),
|
||||
series: vec![
|
||||
Series { points: nx, color: GREY, dashed: false, label: "naive restart (v = 0)" },
|
||||
Series { points: nv, color: GREY, dashed: true, label: "" },
|
||||
Series { points: x, color: BLUE, dashed: false, label: "position" },
|
||||
Series { points: v, color: ORANGE, dashed: true, label: "velocity" },
|
||||
],
|
||||
marks: vec![0.15, 0.32, 0.55],
|
||||
equal_axes: false,
|
||||
});
|
||||
}
|
||||
write("retarget.svg", svg(&panels, 3, 380.0, 220.0, "Retargeting at the red lines: position and velocity stay continuous"));
|
||||
|
||||
// 4. Presence: blur-replace enter, exit, revive mid-exit.
|
||||
let mut scene = Scene::new();
|
||||
scene.insert(NodeId(9), NodeSpec::new(Rect::new(0.0, 0.0, 1.0, 1.0)), Mount::Initial);
|
||||
scene.frame_at(0.0);
|
||||
let id = NodeId(1);
|
||||
let spec = NodeSpec::new(Rect::new(0.0, 0.0, 200.0, 40.0)).transition(Transition::blur_replace());
|
||||
scene.insert(id, spec, Mount::Animated);
|
||||
let (mut op, mut bl, mut sc) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut last = None;
|
||||
for i in 0..=480 {
|
||||
let t = i as f64 / 240.0;
|
||||
scene.set_time(t);
|
||||
if i == 168 {
|
||||
scene.remove(id);
|
||||
}
|
||||
if i == 220 {
|
||||
scene.insert(id, spec, Mount::Animated);
|
||||
}
|
||||
if i == 400 {
|
||||
scene.remove(id);
|
||||
}
|
||||
let out = scene.frame();
|
||||
if let Some(p) = out.changed.iter().find(|p| p.node == id) {
|
||||
last = Some(*p);
|
||||
}
|
||||
if out.exited.contains(&id) {
|
||||
last = None;
|
||||
}
|
||||
if let Some(p) = last {
|
||||
op.push((t as f32, p.opacity));
|
||||
bl.push((t as f32, p.blur / Transition::blur_replace().insertion.blur));
|
||||
sc.push((t as f32, (p.transform.scale.x - 0.96) / 0.04));
|
||||
}
|
||||
}
|
||||
let presence = Panel {
|
||||
title: "blurReplace: enter, exit, revive mid-exit, exit".into(),
|
||||
x: (0.0, 2.0),
|
||||
y: (-0.1, 1.15),
|
||||
series: vec![
|
||||
Series { points: op, color: BLUE, dashed: false, label: "opacity" },
|
||||
Series { points: bl, color: PURPLE, dashed: false, label: "blur / 4 px" },
|
||||
Series { points: sc, color: GREEN, dashed: true, label: "(scale − .96) / .04" },
|
||||
],
|
||||
marks: vec![0.7, 220.0 / 240.0, 400.0 / 240.0],
|
||||
equal_axes: false,
|
||||
};
|
||||
|
||||
// 5. Paths: a child moving inside a moving parent.
|
||||
let path = |screen: bool| {
|
||||
let mut s = Scene::new();
|
||||
let (p, c) = (NodeId(10), NodeId(11));
|
||||
s.insert(p, NodeSpec::new(Rect::new(0.0, 0.0, 400.0, 400.0)), Mount::Initial);
|
||||
s.insert(c, NodeSpec::new(Rect::new(10.0, 10.0, 50.0, 50.0)).parent(p), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.set_frame(p, Rect::new(200.0, 100.0, 400.0, 400.0), motion::GLIDE);
|
||||
let la = LayoutAnim::new(motion::DRIFT);
|
||||
s.set_frame(c, Rect::new(100.0, 200.0, 50.0, 50.0), if screen { la.screen() } else { la });
|
||||
let mut pts = Vec::new();
|
||||
for i in 0..=360 {
|
||||
let out = s.frame_at(i as f64 / 120.0);
|
||||
if let Some(q) = out.changed.iter().find(|q| q.node == c) {
|
||||
pts.push((q.rect.x, q.rect.y));
|
||||
}
|
||||
}
|
||||
pts
|
||||
};
|
||||
let paths = Panel {
|
||||
title: "child path in root space (parent GLIDE, child DRIFT)".into(),
|
||||
x: (0.0, 320.0),
|
||||
y: (0.0, 320.0),
|
||||
series: vec![
|
||||
Series { points: path(false), color: GREY, dashed: false, label: "parent space: dog-leg" },
|
||||
Series { points: path(true), color: BLUE, dashed: false, label: "Travel::Screen: straight" },
|
||||
],
|
||||
marks: vec![],
|
||||
equal_axes: true,
|
||||
};
|
||||
write("presence-and-paths.svg", svg(&[presence, paths], 2, 420.0, 330.0, "Presence and travel"));
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
//! A single animated value you own directly, like Compose's `Animatable` or Motion's
|
||||
//! `MotionValue`. Same math as the store, no ids. Handy for tests, tools and one-off values.
|
||||
|
||||
use crate::curve::{Anim, Curve, Velocity};
|
||||
use crate::layer::{Eps, Kind, Layer};
|
||||
use crate::props::PropClass;
|
||||
use crate::value::{Animatable, MAX_LANES, lanes};
|
||||
|
||||
/// One retargetable value of type `T`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Animated<T: Animatable> {
|
||||
target: [f32; MAX_LANES],
|
||||
layers: [Layer; MAX_LANES],
|
||||
curve: Curve,
|
||||
eps: Eps,
|
||||
_t: core::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: Animatable> Animated<T> {
|
||||
/// At rest at `value`. Settle thresholds default to `PropClass::Other`.
|
||||
pub fn new(value: T) -> Self {
|
||||
Animated {
|
||||
target: lanes(&value),
|
||||
layers: [Layer::REST; MAX_LANES],
|
||||
curve: Curve::Instant,
|
||||
eps: PropClass::Other.eps(2.0),
|
||||
_t: core::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses `class`'s settle thresholds (at 2× pixel scale).
|
||||
pub fn with_class(mut self, class: PropClass) -> Self {
|
||||
self.eps = class.eps(2.0);
|
||||
self
|
||||
}
|
||||
|
||||
/// Jumps to `value` (direct manipulation).
|
||||
pub fn set(&mut self, value: T) {
|
||||
self.target = lanes(&value);
|
||||
self.layers = [Layer::REST; MAX_LANES];
|
||||
self.curve = Curve::Instant;
|
||||
}
|
||||
|
||||
/// Animates to `target` from the exact state at `now`. An unchanged target is a no-op.
|
||||
/// Always merges; `anim.delay` and additive blending need the store.
|
||||
pub fn animate_to(&mut self, target: T, anim: impl Into<Anim>, now: f64) {
|
||||
let anim = anim.into();
|
||||
debug_assert!(anim.delay == 0.0, "Animated doesn't schedule delays; use AnimationStore");
|
||||
let tg = lanes(&target);
|
||||
let velocity = match anim.velocity {
|
||||
Velocity::Inherit => None,
|
||||
Velocity::Zero => Some(0.0),
|
||||
Velocity::Uniform(u) => Some(u),
|
||||
};
|
||||
if velocity.is_none() && tg[..T::LANES] == self.target[..T::LANES] {
|
||||
return;
|
||||
}
|
||||
self.curve = anim.curve;
|
||||
for (i, &t) in tg.iter().enumerate().take(T::LANES) {
|
||||
let (o, v) = self.layers[i].sample(now);
|
||||
self.restart_lane(i, self.target[i] + o, velocity.unwrap_or(v), t, anim.curve, now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Restarts lane `i` at `x` with velocity `v`. One layer per lane here, so every curve
|
||||
/// merges from the exact (x, v); decay picks its own target.
|
||||
fn restart_lane(&mut self, i: usize, x: f32, v: f32, target: f32, curve: Curve, now: f64) {
|
||||
if let Curve::Decay(d) = curve {
|
||||
self.target[i] = x + v / d.k();
|
||||
self.layers[i] = Layer::decay(d.k(), now, v, self.eps);
|
||||
} else {
|
||||
self.target[i] = target;
|
||||
self.layers[i] = Layer::start(&curve, now, x - target, v, self.eps);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the animation onto a clock reading `delta` more, at the same place.
|
||||
pub(crate) fn shift(&mut self, delta: f64) {
|
||||
for l in &mut self.layers {
|
||||
l.t0 += delta;
|
||||
l.end += delta;
|
||||
}
|
||||
}
|
||||
|
||||
/// Retargets on the curve last used.
|
||||
pub fn retarget(&mut self, target: T, now: f64) {
|
||||
let curve = self.curve;
|
||||
self.animate_to(target, curve, now);
|
||||
}
|
||||
|
||||
/// Gesture handoff: continue from the current position with `velocity` on `curve`.
|
||||
pub fn release(&mut self, velocity: T, target: T, curve: impl Into<Curve>, now: f64) {
|
||||
let v = lanes(&velocity);
|
||||
let tg = lanes(&target);
|
||||
let curve = curve.into();
|
||||
self.curve = curve;
|
||||
for i in 0..T::LANES {
|
||||
let x = self.target[i] + self.layers[i].sample(now).0;
|
||||
self.restart_lane(i, x, v[i], tg[i], curve, now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Value at `now`.
|
||||
pub fn sample(&self, now: f64) -> T {
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
for (i, slot) in out.iter_mut().enumerate().take(T::LANES) {
|
||||
*slot = self.target[i] + self.layers[i].sample(now).0;
|
||||
}
|
||||
T::read_lanes(&out[..T::LANES])
|
||||
}
|
||||
|
||||
/// Velocity at `now`, units per second.
|
||||
pub fn velocity(&self, now: f64) -> T {
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
for (i, slot) in out.iter_mut().enumerate().take(T::LANES) {
|
||||
*slot = self.layers[i].sample(now).1;
|
||||
}
|
||||
T::read_lanes(&out[..T::LANES])
|
||||
}
|
||||
|
||||
pub fn target(&self) -> T {
|
||||
T::read_lanes(&self.target[..T::LANES])
|
||||
}
|
||||
|
||||
/// When every lane is within its settle thresholds for good.
|
||||
pub fn settle_time(&self) -> f64 {
|
||||
self.layers[..T::LANES]
|
||||
.iter()
|
||||
.filter(|l| l.kind != Kind::Rest)
|
||||
.map(|l| l.end)
|
||||
.fold(f64::NEG_INFINITY, f64::max)
|
||||
}
|
||||
|
||||
pub fn is_settled(&self, now: f64) -> bool {
|
||||
now >= self.settle_time()
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
//! What a frame reports, kept readable until the next one.
|
||||
|
||||
/// Items a frame reports (settle events, unmounted nodes). [`begin`](Self::begin) drops what the
|
||||
/// previous frame reported and [`end`](Self::end) marks what this one did, so an item pushed
|
||||
/// between frames is reported by the next one, and every item by exactly one.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Carry<T> {
|
||||
items: Vec<T>,
|
||||
reported: usize,
|
||||
}
|
||||
|
||||
impl<T> Carry<T> {
|
||||
pub(crate) const fn new() -> Self {
|
||||
Carry { items: Vec::new(), reported: 0 }
|
||||
}
|
||||
|
||||
pub(crate) fn reserve(&mut self, n: usize) {
|
||||
self.items.reserve(n);
|
||||
}
|
||||
|
||||
/// Starts a frame: drops what the last one reported, keeps what came after it.
|
||||
pub(crate) fn begin(&mut self) {
|
||||
self.items.drain(..self.reported);
|
||||
self.reported = 0;
|
||||
}
|
||||
|
||||
/// Ends a frame: everything so far is what it reports.
|
||||
pub(crate) fn end(&mut self) {
|
||||
self.reported = self.items.len();
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, item: T) {
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// What the last frame reported, and anything pushed since.
|
||||
pub(crate) fn as_slice(&self) -> &[T] {
|
||||
&self.items
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Carry;
|
||||
|
||||
#[test]
|
||||
fn each_item_is_reported_by_exactly_one_frame() {
|
||||
let mut c = Carry::new();
|
||||
c.push(1);
|
||||
c.begin();
|
||||
c.push(2);
|
||||
c.end();
|
||||
assert_eq!(c.as_slice(), [1, 2], "pushed before or during a frame");
|
||||
c.push(3);
|
||||
assert_eq!(c.as_slice(), [1, 2, 3], "readable until the next frame");
|
||||
c.begin();
|
||||
assert_eq!(c.as_slice(), [3], "pushed between frames: the next one reports it");
|
||||
c.end();
|
||||
c.begin();
|
||||
c.end();
|
||||
assert!(c.as_slice().is_empty());
|
||||
}
|
||||
}
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
//! Choreography: stagger, cue-based sequences and phase cycling, run by the render thread.
|
||||
//!
|
||||
//! Beats start on *events*, not on summed durations: "when that one arrives", "when it settles",
|
||||
//! "not before 0.3 s". A spring's physical tail is not its choreographic span (psychopomp
|
||||
//! `DSL.md`: `settle_in` is ready after 500 ms while its spring is still settling). Cue times
|
||||
//! that are known in advance (a start, a logical arrival) are scheduled exactly through the
|
||||
//! store's delays, so a sequence lands on the same frames at any frame rate.
|
||||
|
||||
use crate::curve::Anim;
|
||||
use crate::easing::Easing;
|
||||
use crate::props::{NodeId, Prop, PropClass, PropId};
|
||||
use crate::store::{AnimationStore, TrackId};
|
||||
use crate::value::{Animatable, lanes};
|
||||
|
||||
/// Where a stagger ripples from (Motion's `stagger(gap, { from })`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum StaggerFrom {
|
||||
First,
|
||||
Last,
|
||||
Center,
|
||||
Index(usize),
|
||||
}
|
||||
|
||||
/// Delays for a ripple across `count` items.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Stagger {
|
||||
pub gap: f32,
|
||||
pub from: StaggerFrom,
|
||||
pub start: f32,
|
||||
/// Optional easing of delays across the ripple (Motion's `ease` option).
|
||||
pub ease: Option<Easing>,
|
||||
}
|
||||
|
||||
impl Stagger {
|
||||
pub fn new(gap: f32) -> Stagger {
|
||||
Stagger { gap, from: StaggerFrom::First, start: 0.0, ease: None }
|
||||
}
|
||||
pub fn from(mut self, from: StaggerFrom) -> Stagger {
|
||||
self.from = from;
|
||||
self
|
||||
}
|
||||
pub fn start(mut self, seconds: f32) -> Stagger {
|
||||
self.start = seconds;
|
||||
self
|
||||
}
|
||||
pub fn ease(mut self, easing: Easing) -> Stagger {
|
||||
self.ease = Some(easing);
|
||||
self
|
||||
}
|
||||
|
||||
/// The delay of item `index` out of `count`.
|
||||
pub fn delay(&self, index: usize, count: usize) -> f32 {
|
||||
let count = count.max(1);
|
||||
let origin = match self.from {
|
||||
StaggerFrom::First => 0.0,
|
||||
StaggerFrom::Last => (count - 1) as f32,
|
||||
StaggerFrom::Center => (count - 1) as f32 / 2.0,
|
||||
StaggerFrom::Index(i) => i.min(count - 1) as f32,
|
||||
};
|
||||
let distance = (index as f32 - origin).abs();
|
||||
let max = (0..count).map(|i| (i as f32 - origin).abs()).fold(0.0, f32::max);
|
||||
let d = match self.ease {
|
||||
Some(e) if max > 0.0 => e.eval(distance / max) * max,
|
||||
_ => distance,
|
||||
};
|
||||
self.start + d * self.gap
|
||||
}
|
||||
}
|
||||
|
||||
/// Shorthand for [`Stagger::delay`].
|
||||
pub fn stagger(index: usize, count: usize, gap: f32, from: StaggerFrom) -> f32 {
|
||||
Stagger::new(gap).from(from).delay(index, count)
|
||||
}
|
||||
|
||||
/// A handle to a step of a [`Choreography`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct StepId(u32);
|
||||
|
||||
/// What a cue waits for on another step.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum When {
|
||||
/// The step started.
|
||||
Started,
|
||||
/// The step's animations logically completed (springs: their duration; tweens: their end).
|
||||
Arrived,
|
||||
/// Every track the step animated is physically at rest (or was taken over).
|
||||
Settled,
|
||||
}
|
||||
|
||||
/// When a step may start.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Cue {
|
||||
after: Option<(StepId, When)>,
|
||||
delay: f32,
|
||||
not_before: f32,
|
||||
}
|
||||
|
||||
impl Cue {
|
||||
/// As soon as the choreography starts.
|
||||
pub fn now() -> Cue {
|
||||
Cue { after: None, delay: 0.0, not_before: 0.0 }
|
||||
}
|
||||
/// `t` seconds after the choreography starts.
|
||||
pub fn at(t: f32) -> Cue {
|
||||
Cue { delay: t, ..Cue::now() }
|
||||
}
|
||||
pub fn started(step: StepId) -> Cue {
|
||||
Cue { after: Some((step, When::Started)), ..Cue::now() }
|
||||
}
|
||||
pub fn arrived(step: StepId) -> Cue {
|
||||
Cue { after: Some((step, When::Arrived)), ..Cue::now() }
|
||||
}
|
||||
pub fn settled(step: StepId) -> Cue {
|
||||
Cue { after: Some((step, When::Settled)), ..Cue::now() }
|
||||
}
|
||||
/// Wait a further `seconds` after the cue.
|
||||
pub fn after(mut self, seconds: f32) -> Cue {
|
||||
self.delay += seconds;
|
||||
self
|
||||
}
|
||||
/// Never earlier than `t` seconds after the choreography starts (a causal guard).
|
||||
pub fn not_before(mut self, t: f32) -> Cue {
|
||||
self.not_before = self.not_before.max(t);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Op {
|
||||
node: NodeId,
|
||||
prop: PropId,
|
||||
class: PropClass,
|
||||
first: u32,
|
||||
lanes: u8,
|
||||
anim: Anim,
|
||||
}
|
||||
|
||||
/// A list of property animations, recorded typed and applied untyped.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ops {
|
||||
ops: Vec<Op>,
|
||||
targets: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Ops {
|
||||
/// Animate `prop` of `node` to `target`. (If the property has never been set, it is set:
|
||||
/// set starting values with `store.set` first.)
|
||||
pub fn animate<T: Animatable>(&mut self, node: NodeId, prop: Prop<T>, target: T, anim: impl Into<Anim>) -> &mut Self {
|
||||
let l = lanes(&target);
|
||||
let first = self.targets.len() as u32;
|
||||
self.targets.extend_from_slice(&l[..T::LANES]);
|
||||
self.ops.push(Op { node, prop: prop.id, class: prop.class, first, lanes: T::LANES as u8, anim: anim.into() });
|
||||
self
|
||||
}
|
||||
|
||||
fn apply(&self, store: &mut AnimationStore, delay: f32, set: bool, out: &mut Vec<(TrackId, u32)>) {
|
||||
for op in &self.ops {
|
||||
let tg = &self.targets[op.first as usize..op.first as usize + op.lanes as usize];
|
||||
let t = store.ensure(op.node, op.prop, op.class, tg) as usize;
|
||||
if set {
|
||||
store.set_raw(t as u32, tg);
|
||||
} else {
|
||||
// `delay` is store time; the op's node may run on a scaled clock.
|
||||
let k = store.node_time_scale(op.node);
|
||||
let delay = if k > 0.0 { delay * k } else { delay };
|
||||
let anim = Anim { delay: op.anim.delay + delay, ..op.anim };
|
||||
store.animate_raw(t, tg, anim, None);
|
||||
}
|
||||
let id = store.id_of(t);
|
||||
out.push((id, store.epoch(id).unwrap_or(0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum State {
|
||||
Waiting,
|
||||
/// Started (possibly with a scheduled delay) at absolute `start`; its tracks are `tracks`.
|
||||
Running { start: f64, first: u32, count: u32 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Step {
|
||||
cue: Cue,
|
||||
ops: Ops,
|
||||
state: State,
|
||||
}
|
||||
|
||||
/// A set of steps that start on cues. Call [`tick`](Self::tick) each frame after setting the
|
||||
/// store's time and before `store.tick()`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Choreography {
|
||||
steps: Vec<Step>,
|
||||
tracks: Vec<(TrackId, u32)>,
|
||||
t0: Option<f64>,
|
||||
}
|
||||
|
||||
impl Choreography {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Adds a step: `c.step(Cue::arrived(a).after(0.05), |s| { s.animate(id, prop::OPACITY, 1.0, SETTLE); })`.
|
||||
pub fn step(&mut self, cue: Cue, build: impl FnOnce(&mut Ops)) -> StepId {
|
||||
let mut ops = Ops::default();
|
||||
build(&mut ops);
|
||||
self.steps.push(Step { cue, ops, state: State::Waiting });
|
||||
StepId((self.steps.len() - 1) as u32)
|
||||
}
|
||||
|
||||
/// A ripple: one step per item, each `stagger.delay(i, n)` after `cue`. Returns the steps.
|
||||
pub fn stagger<I>(&mut self, cue: Cue, stagger: Stagger, items: I, mut each: impl FnMut(&mut Ops, I::Item)) -> Vec<StepId>
|
||||
where
|
||||
I: IntoIterator,
|
||||
I::IntoIter: ExactSizeIterator,
|
||||
{
|
||||
let it = items.into_iter();
|
||||
let n = it.len();
|
||||
it.enumerate()
|
||||
.map(|(i, item)| {
|
||||
let c = cue.after(stagger.delay(i, n));
|
||||
self.step(c, |ops| each(ops, item))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// When a step started (or will start, if scheduled with a delay).
|
||||
pub fn start_time(&self, step: StepId) -> Option<f64> {
|
||||
match self.steps.get(step.0 as usize)?.state {
|
||||
State::Running { start, .. } => Some(start),
|
||||
State::Waiting => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every step started and every track it animated has settled.
|
||||
pub fn is_done(&self, store: &AnimationStore) -> bool {
|
||||
self.steps.iter().all(|s| matches!(s.state, State::Running { .. }))
|
||||
&& all_settled(store, &self.tracks)
|
||||
}
|
||||
|
||||
/// Starts every step whose cue is due or now known. Cheap when nothing is waiting.
|
||||
pub fn tick(&mut self, store: &mut AnimationStore) {
|
||||
let now = store.now();
|
||||
let t0 = *self.t0.get_or_insert(now);
|
||||
loop {
|
||||
let mut progressed = false;
|
||||
for k in 0..self.steps.len() {
|
||||
if self.steps[k].state != State::Waiting {
|
||||
continue;
|
||||
}
|
||||
let cue = self.steps[k].cue;
|
||||
let base = match cue.after {
|
||||
None => Some(t0),
|
||||
Some((s, when)) => self.cue_time(store, s, when, now),
|
||||
};
|
||||
let Some(base) = base else { continue };
|
||||
let at = (base + cue.delay as f64).max(t0 + cue.not_before as f64);
|
||||
let delay = (at - now).max(0.0) as f32;
|
||||
let first = self.tracks.len() as u32;
|
||||
self.steps[k].ops.apply(store, delay, false, &mut self.tracks);
|
||||
let count = self.tracks.len() as u32 - first;
|
||||
self.steps[k].state = State::Running { start: now + delay as f64, first, count };
|
||||
progressed = true;
|
||||
}
|
||||
if !progressed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cue_time(&self, store: &AnimationStore, s: StepId, when: When, now: f64) -> Option<f64> {
|
||||
let State::Running { start, first, count } = self.steps.get(s.0 as usize)?.state else { return None };
|
||||
let tracks = &self.tracks[first as usize..(first + count) as usize];
|
||||
match when {
|
||||
When::Started => Some(start),
|
||||
// A frozen step hasn't a known arrival yet: keep waiting.
|
||||
When::Arrived => Some(arrival(store, tracks, start)).filter(|t| t.is_finite()),
|
||||
When::Settled => all_settled(store, tracks).then_some(now),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every track is at rest, or was taken over (its epoch moved on).
|
||||
fn all_settled(store: &AnimationStore, tracks: &[(TrackId, u32)]) -> bool {
|
||||
tracks.iter().all(|&(t, epoch)| store.is_settled(t) || store.epoch(t) != Some(epoch))
|
||||
}
|
||||
|
||||
/// The latest logical end among `tracks`, and never before `from`.
|
||||
fn arrival(store: &AnimationStore, tracks: &[(TrackId, u32)], from: f64) -> f64 {
|
||||
tracks.iter().filter_map(|&(t, _)| store.logical_end(t)).fold(from, f64::max)
|
||||
}
|
||||
|
||||
/// SwiftUI `PhaseAnimator`: cycles through phases, animating each from wherever the last one is,
|
||||
/// advancing when the current phase arrives (or settles). The first phase is the resting pose and
|
||||
/// is shown without animation. Under Reduce Motion it holds that pose.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PhaseAnimator {
|
||||
phases: Vec<Ops>,
|
||||
current: usize,
|
||||
advance: When,
|
||||
repeat: bool,
|
||||
hold: f32,
|
||||
tracks: Vec<(TrackId, u32)>,
|
||||
next: Next,
|
||||
}
|
||||
|
||||
/// When a [`PhaseAnimator`] moves on from its current phase.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Next {
|
||||
/// The first phase isn't shown yet.
|
||||
Unstarted,
|
||||
/// At store time `at`: the phase's arrival plus the hold.
|
||||
At(f64),
|
||||
/// The phase started on a stopped clock, so its arrival isn't known yet: asked each tick.
|
||||
Frozen,
|
||||
/// Once every track the phase started has settled (`When::Settled`).
|
||||
Settled,
|
||||
/// A [`once`](PhaseAnimator::once) animator is on its last phase.
|
||||
Done,
|
||||
}
|
||||
|
||||
impl Next {
|
||||
fn at(t: f64) -> Next {
|
||||
if t == f64::INFINITY { Next::Frozen } else { Next::At(t) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PhaseAnimator {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl PhaseAnimator {
|
||||
pub fn new() -> Self {
|
||||
PhaseAnimator {
|
||||
phases: Vec::new(),
|
||||
current: 0,
|
||||
advance: When::Arrived,
|
||||
repeat: true,
|
||||
hold: 0.0,
|
||||
tracks: Vec::new(),
|
||||
next: Next::Unstarted,
|
||||
}
|
||||
}
|
||||
pub fn phase(mut self, build: impl FnOnce(&mut Ops)) -> Self {
|
||||
let mut ops = Ops::default();
|
||||
build(&mut ops);
|
||||
self.phases.push(ops);
|
||||
self
|
||||
}
|
||||
/// Advance on `When::Arrived` (default) or `When::Settled`.
|
||||
pub fn advance_on(mut self, when: When) -> Self {
|
||||
self.advance = when;
|
||||
self
|
||||
}
|
||||
/// Pause on each phase for `seconds` after it arrives.
|
||||
pub fn hold(mut self, seconds: f32) -> Self {
|
||||
self.hold = seconds;
|
||||
self
|
||||
}
|
||||
/// Stop after the last phase instead of cycling back to the first.
|
||||
pub fn once(mut self) -> Self {
|
||||
self.repeat = false;
|
||||
self
|
||||
}
|
||||
pub fn current(&self) -> usize {
|
||||
self.current
|
||||
}
|
||||
|
||||
pub fn tick(&mut self, store: &mut AnimationStore) {
|
||||
if self.phases.is_empty() {
|
||||
return;
|
||||
}
|
||||
let now = store.now();
|
||||
let hold = self.hold as f64;
|
||||
if self.next == Next::Unstarted {
|
||||
self.tracks.clear();
|
||||
self.phases[0].apply(store, 0.0, true, &mut self.tracks);
|
||||
self.next = Next::At(now);
|
||||
}
|
||||
if store.reduced_motion() {
|
||||
return;
|
||||
}
|
||||
let at = match self.next {
|
||||
Next::At(at) => at,
|
||||
// The phase was frozen when it started (`set_node_time_scale(_, 0.0)`): ask again.
|
||||
Next::Frozen => match Next::at(arrival(store, &self.tracks, now) + hold) {
|
||||
Next::At(at) => {
|
||||
self.next = Next::At(at);
|
||||
at
|
||||
}
|
||||
_ => return,
|
||||
},
|
||||
Next::Settled => {
|
||||
if all_settled(store, &self.tracks) {
|
||||
self.next = Next::At(now + hold);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Next::Unstarted | Next::Done => return,
|
||||
};
|
||||
if now < at {
|
||||
return;
|
||||
}
|
||||
let next = self.current + 1;
|
||||
if next >= self.phases.len() && !self.repeat {
|
||||
self.next = Next::Done;
|
||||
return;
|
||||
}
|
||||
self.current = next % self.phases.len();
|
||||
self.tracks.clear();
|
||||
self.phases[self.current].apply(store, 0.0, false, &mut self.tracks);
|
||||
self.next = match self.advance {
|
||||
When::Arrived | When::Started => Next::at(arrival(store, &self.tracks, now) + hold),
|
||||
When::Settled => Next::Settled,
|
||||
};
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
//! One animation clock for everything: tracks, presence, choreography and traces read it, so slow
|
||||
//! motion is truthful.
|
||||
|
||||
/// Animation time `τ = base + (host − anchor) · scale`, re-anchored whenever the scale changes so
|
||||
/// running animations continue from where they are.
|
||||
///
|
||||
/// - Display mode: call [`Clock::frame`] with the display link's **target presentation timestamp**,
|
||||
/// so a late frame still lands on the right pose.
|
||||
/// - Manual mode: [`Clock::step`] advances exactly one frame at `hz`; [`Clock::seek`] jumps. Tests
|
||||
/// and frame traces are bit-identical run to run.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Clock {
|
||||
base: f64,
|
||||
source: Source,
|
||||
scale: f64,
|
||||
paused: bool,
|
||||
frame: u64,
|
||||
now: f64,
|
||||
}
|
||||
|
||||
/// What moves the clock.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Source {
|
||||
/// Host timestamps: τ runs from `base` at host time `anchor`. No anchor until the first
|
||||
/// frame after creation or a seek, so that frame shows `base` exactly.
|
||||
Host { anchor: Option<f64> },
|
||||
/// [`Clock::step`], `1/hz` seconds a frame.
|
||||
Manual { hz: f64 },
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
/// Driven by host timestamps (seconds, any epoch).
|
||||
pub fn display() -> Clock {
|
||||
Clock { base: 0.0, source: Source::Host { anchor: None }, scale: 1.0, paused: false, frame: 0, now: 0.0 }
|
||||
}
|
||||
|
||||
/// Driven by `step()` at a fixed rate, starting at τ = 0.
|
||||
pub fn manual(hz: f64) -> Clock {
|
||||
assert!(hz > 0.0);
|
||||
Clock { source: Source::Manual { hz }, ..Clock::display() }
|
||||
}
|
||||
|
||||
/// Animation time for a host timestamp, without advancing.
|
||||
pub fn time_at(&self, host: f64) -> f64 {
|
||||
match self.source {
|
||||
Source::Host { anchor: Some(anchor) } if !self.paused => self.base + (host - anchor) * self.scale,
|
||||
_ => self.base,
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances to the frame presented at host time `host` and returns τ.
|
||||
pub fn frame(&mut self, host: f64) -> f64 {
|
||||
if let Source::Host { anchor: anchor @ None } = &mut self.source {
|
||||
*anchor = Some(host);
|
||||
}
|
||||
self.now = self.time_at(host);
|
||||
self.frame += 1;
|
||||
self.now
|
||||
}
|
||||
|
||||
/// Manual mode: one frame (`1/hz` seconds × scale, or nothing while paused). Returns τ.
|
||||
pub fn step(&mut self) -> f64 {
|
||||
let Source::Manual { hz } = self.source else { panic!("Clock::step needs Clock::manual") };
|
||||
self.frame += 1;
|
||||
if !self.paused {
|
||||
self.base += self.scale / hz;
|
||||
}
|
||||
self.now = self.base;
|
||||
self.now
|
||||
}
|
||||
|
||||
/// Jumps to τ = `t` (scrubbing, deterministic tests).
|
||||
pub fn seek(&mut self, t: f64) {
|
||||
self.base = t;
|
||||
self.now = t;
|
||||
if let Source::Host { anchor } = &mut self.source {
|
||||
*anchor = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Slow motion (< 1) or fast-forward (> 1), clamped to [0.02, 4]. Re-anchors at `host`.
|
||||
pub fn set_scale(&mut self, scale: f64, host: f64) {
|
||||
let scale = scale.clamp(0.02, 4.0);
|
||||
if let Source::Host { anchor: Some(_) } = self.source {
|
||||
self.base = self.time_at(host);
|
||||
self.source = Source::Host { anchor: Some(host) };
|
||||
}
|
||||
self.scale = scale;
|
||||
}
|
||||
|
||||
pub fn pause(&mut self, host: f64) {
|
||||
if !self.paused {
|
||||
self.base = self.time_at(host);
|
||||
self.paused = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resume(&mut self, host: f64) {
|
||||
if self.paused {
|
||||
self.paused = false;
|
||||
if let Source::Host { anchor } = &mut self.source {
|
||||
*anchor = Some(host);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now(&self) -> f64 {
|
||||
self.now
|
||||
}
|
||||
pub fn scale(&self) -> f64 {
|
||||
self.scale
|
||||
}
|
||||
pub fn is_paused(&self) -> bool {
|
||||
self.paused
|
||||
}
|
||||
pub fn frame_count(&self) -> u64 {
|
||||
self.frame
|
||||
}
|
||||
/// The manual frame interval, if any.
|
||||
pub fn frame_interval(&self) -> Option<f64> {
|
||||
match self.source {
|
||||
Source::Manual { hz } => Some(1.0 / hz),
|
||||
Source::Host { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scale_reanchors_without_a_jump() {
|
||||
let mut c = Clock::display();
|
||||
assert_eq!(c.frame(100.0), 0.0);
|
||||
assert!((c.frame(101.0) - 1.0).abs() < 1e-12);
|
||||
c.set_scale(0.5, 101.0);
|
||||
assert!((c.frame(101.0) - 1.0).abs() < 1e-12);
|
||||
assert!((c.frame(103.0) - 2.0).abs() < 1e-12);
|
||||
c.pause(103.0);
|
||||
assert!((c.frame(110.0) - 2.0).abs() < 1e-12);
|
||||
c.resume(110.0);
|
||||
assert!((c.frame(112.0) - 3.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeks_and_pauses_hold_until_a_frame_anchors_them() {
|
||||
let mut c = Clock::display();
|
||||
// Paused before any frame: the first frame anchors, and time holds.
|
||||
c.pause(5.0);
|
||||
assert_eq!(c.frame(7.0), 0.0);
|
||||
c.resume(9.0);
|
||||
assert!((c.frame(10.0) - 1.0).abs() < 1e-12);
|
||||
c.seek(4.0);
|
||||
assert_eq!(c.time_at(50.0), 4.0, "a seek shows its time until a frame anchors it");
|
||||
assert_eq!(c.frame(50.0), 4.0);
|
||||
assert!((c.frame(50.5) - 4.5).abs() < 1e-12);
|
||||
// A seek while paused shows at once and runs from there on resume.
|
||||
c.pause(50.5);
|
||||
c.seek(2.0);
|
||||
assert_eq!(c.frame(60.0), 2.0);
|
||||
c.resume(60.0);
|
||||
assert!((c.frame(61.0) - 3.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manual_clock_never_reads_host_time() {
|
||||
let mut c = Clock::manual(60.0);
|
||||
assert_eq!(c.frame(100.0), 0.0);
|
||||
assert_eq!(c.frame(101.0), 0.0, "only step moves a manual clock");
|
||||
c.set_scale(0.5, 102.0);
|
||||
c.pause(103.0);
|
||||
c.resume(200.0);
|
||||
assert!((c.step() - 0.5 / 60.0).abs() < 1e-12);
|
||||
assert_eq!(c.time_at(300.0), c.now());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_steps_are_exact() {
|
||||
let mut c = Clock::manual(120.0);
|
||||
for _ in 0..120 {
|
||||
c.step();
|
||||
}
|
||||
assert!((c.now() - 1.0).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
//! What a value animates on, and how a new animation meets the one already running.
|
||||
|
||||
use crate::easing::Easing;
|
||||
use crate::spring::{Spring, SpringPair};
|
||||
|
||||
/// The shape of one animation segment.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Curve {
|
||||
/// Physics. Retargets merge (SwiftUI): the new spring starts from the exact position and velocity.
|
||||
Spring(Spring),
|
||||
/// A fixed-duration eased tween (CSS transition). Retargets add (Core Animation).
|
||||
Tween { duration: f32, easing: Easing },
|
||||
/// Fling inertia: velocity decays exponentially toward the projected rest point.
|
||||
Decay(Decay),
|
||||
/// Jump to the target this frame.
|
||||
Instant,
|
||||
/// Internal: a cubic Hermite keyframe segment. Built by [`crate::Keyframes`].
|
||||
#[doc(hidden)]
|
||||
Hermite { duration: f32, end_velocity: f32 },
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
pub const fn tween(duration: f32, easing: Easing) -> Curve {
|
||||
Curve::Tween { duration, easing }
|
||||
}
|
||||
pub const fn linear(duration: f32) -> Curve {
|
||||
Curve::Tween { duration, easing: Easing::Linear }
|
||||
}
|
||||
pub const fn ease_in_out(duration: f32) -> Curve {
|
||||
Curve::Tween { duration, easing: Easing::EASE_IN_OUT }
|
||||
}
|
||||
|
||||
/// When the animation "logically" completes (SwiftUI `.logicallyComplete`): a spring's
|
||||
/// perceptual duration, a tween's duration. Choreography cues on this, not on physical rest.
|
||||
pub fn logical_duration(&self) -> f32 {
|
||||
match *self {
|
||||
Curve::Spring(s) => s.duration,
|
||||
Curve::Tween { duration, .. } | Curve::Hermite { duration, .. } => duration,
|
||||
Curve::Decay(d) => 1.0 / d.k(),
|
||||
Curve::Instant => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_blend(&self) -> Blend {
|
||||
match self {
|
||||
Curve::Tween { .. } => Blend::Additive,
|
||||
_ => Blend::Merge,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Spring> for Curve {
|
||||
/// [`Spring::NONE`] is [`Curve::Instant`].
|
||||
fn from(s: Spring) -> Curve {
|
||||
if s == Spring::NONE { Curve::Instant } else { Curve::Spring(s) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Exponential velocity decay, `v(t) = v0 · e^{−k t}`; the value comes to rest at `x0 + v0 / k`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Decay {
|
||||
/// Rate constant k in 1/s.
|
||||
pub rate: f32,
|
||||
}
|
||||
|
||||
impl Decay {
|
||||
/// iOS `UIScrollView.DecelerationRate.normal`: 0.998 per ms (k ≈ 2.002/s).
|
||||
pub const IOS_NORMAL: Decay = Decay { rate: 2.002_002 };
|
||||
/// iOS `UIScrollView.DecelerationRate.fast`: 0.99 per ms (k ≈ 10.05/s).
|
||||
pub const IOS_FAST: Decay = Decay { rate: 10.050_336 };
|
||||
|
||||
/// From a per-millisecond deceleration rate `r` (UIKit): k = −1000 · ln r.
|
||||
pub fn per_ms(r: f32) -> Decay {
|
||||
assert!(r > 0.0 && r < 1.0, "deceleration rate must be in (0, 1)");
|
||||
Decay { rate: -1000.0 * r.ln() }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn k(self) -> f32 {
|
||||
self.rate.max(1e-3)
|
||||
}
|
||||
}
|
||||
|
||||
/// How a new animation combines with what's already moving on the same value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Blend {
|
||||
/// Springs, decay and keyframes merge; tweens add.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Sample `(x, v)` now and start one new segment from there (SwiftUI spring merging,
|
||||
/// Compose `animateTo`). One segment per lane, O(1) sampling.
|
||||
Merge,
|
||||
/// Keep running segments and add a new one that animates the target delta to 0
|
||||
/// (Core Animation additive animations). Each curve keeps its own shape.
|
||||
Additive,
|
||||
}
|
||||
|
||||
/// Starting velocity for a new segment.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub enum Velocity {
|
||||
/// Keep the current velocity (the default: interruptible motion).
|
||||
#[default]
|
||||
Inherit,
|
||||
/// Start from rest.
|
||||
Zero,
|
||||
/// The same velocity on every lane, in property units per second.
|
||||
Uniform(f32),
|
||||
}
|
||||
|
||||
/// A curve plus how and when to apply it: what `animate` takes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Anim {
|
||||
pub curve: Curve,
|
||||
/// Seconds before the new target takes effect. A newer animate on the same value cancels it.
|
||||
pub delay: f32,
|
||||
pub blend: Blend,
|
||||
pub velocity: Velocity,
|
||||
/// Non-zero: a `MotionEvent::Completed { token }` fires when this animation settles (or is
|
||||
/// replaced, with `finished: false`). SwiftUI's `withAnimation(_:completion:)`.
|
||||
pub token: u64,
|
||||
}
|
||||
|
||||
impl Anim {
|
||||
pub const fn new(curve: Curve) -> Anim {
|
||||
Anim { curve, delay: 0.0, blend: Blend::Auto, velocity: Velocity::Inherit, token: 0 }
|
||||
}
|
||||
pub const INSTANT: Anim = Anim::new(Curve::Instant);
|
||||
|
||||
pub(crate) fn resolved_blend(&self) -> Blend {
|
||||
match self.blend {
|
||||
Blend::Auto => self.curve.default_blend(),
|
||||
b => b,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Curve> for Anim {
|
||||
fn from(c: Curve) -> Anim {
|
||||
Anim::new(c)
|
||||
}
|
||||
}
|
||||
impl From<Spring> for Anim {
|
||||
fn from(s: Spring) -> Anim {
|
||||
Anim::new(s.into())
|
||||
}
|
||||
}
|
||||
/// A pair used where no direction is known animates on `enter`.
|
||||
impl From<SpringPair> for Anim {
|
||||
fn from(p: SpringPair) -> Anim {
|
||||
Anim::new(p.enter.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder methods on anything that converts to an [`Anim`]: `SETTLE.delay(0.05)`.
|
||||
pub trait AnimExt: Into<Anim> + Sized {
|
||||
fn delay(self, seconds: f32) -> Anim {
|
||||
Anim { delay: seconds, ..self.into() }
|
||||
}
|
||||
fn blend(self, blend: Blend) -> Anim {
|
||||
Anim { blend, ..self.into() }
|
||||
}
|
||||
fn additive(self) -> Anim {
|
||||
self.blend(Blend::Additive)
|
||||
}
|
||||
fn merge(self) -> Anim {
|
||||
self.blend(Blend::Merge)
|
||||
}
|
||||
fn velocity(self, velocity: Velocity) -> Anim {
|
||||
Anim { velocity, ..self.into() }
|
||||
}
|
||||
fn completion(self, token: u64) -> Anim {
|
||||
Anim { token, ..self.into() }
|
||||
}
|
||||
}
|
||||
impl<T: Into<Anim>> AnimExt for T {}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
//! Wall-clock opacity curve used by `LoopSpec::cycle` and Rune's `.cycle()` sugar.
|
||||
|
||||
/// A looping opacity curve sampled from the wall clock: `stops` are (loop fraction 0–1, opacity)
|
||||
/// pairs interpolated linearly; this element is at `frac(t / period - phase)`. Every cycle with
|
||||
/// the same period stays in phase. Reduced motion holds `still`. Use [`Cycle::DISPLAY_RATE`]
|
||||
/// for a continuous sweep, or a positive `fps` for an intentionally stepped indicator.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Cycle {
|
||||
pub period: f32,
|
||||
pub phase: f32,
|
||||
pub stops: &'static [(f32, f32)],
|
||||
pub still: f32,
|
||||
pub fps: f32,
|
||||
}
|
||||
|
||||
impl Cycle {
|
||||
/// Sample on the host's display frames, without arming an independent timer.
|
||||
pub const DISPLAY_RATE: f32 = 0.0;
|
||||
|
||||
pub(crate) fn frame_interval(self) -> Option<f64> {
|
||||
(self.fps != Self::DISPLAY_RATE).then(|| f64::from(1.0 / self.fps.max(1.0)))
|
||||
}
|
||||
|
||||
pub fn sample(&self, t: f64) -> f32 {
|
||||
let x = (t / f64::from(self.period) - f64::from(self.phase)).rem_euclid(1.0) as f32;
|
||||
let s = self.stops;
|
||||
let Some(k) = s.iter().position(|&(at, _)| at >= x) else { return s.last().map_or(1.0, |p| p.1) };
|
||||
if k == 0 {
|
||||
return s[0].1;
|
||||
}
|
||||
let ((x0, v0), (x1, v1)) = (s[k - 1], s[k]);
|
||||
v0 + (v1 - v0) * (x - x0) / (x1 - x0).max(1e-6)
|
||||
}
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
//! Timing curves for tweens: CSS `cubic-bezier()`, `steps()` and `linear()`.
|
||||
|
||||
/// A CSS timing function: maps progress `x ∈ [0, 1]` to eased progress.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Easing {
|
||||
Linear,
|
||||
/// `cubic-bezier(x1, y1, x2, y2)`, solved exactly like browsers do.
|
||||
CubicBezier(CubicBezier),
|
||||
/// `steps(n, position)`.
|
||||
Steps(u16, StepPosition),
|
||||
/// CSS `linear(...)`: piecewise-linear stops `[x, y]`, sorted by `x`, from `x = 0` to `x = 1`.
|
||||
/// Use [`crate::Spring::css_linear`] to bake a spring for the web.
|
||||
Piecewise(&'static [[f32; 2]]),
|
||||
}
|
||||
|
||||
/// Where a `steps()` jump happens (CSS `jump-start`, `jump-end`, `jump-none`, `jump-both`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StepPosition {
|
||||
Start,
|
||||
End,
|
||||
None,
|
||||
Both,
|
||||
}
|
||||
|
||||
impl Easing {
|
||||
pub const LINEAR: Easing = Easing::Linear;
|
||||
pub const EASE: Easing = Easing::cubic(0.25, 0.1, 0.25, 1.0);
|
||||
pub const EASE_IN: Easing = Easing::cubic(0.42, 0.0, 1.0, 1.0);
|
||||
pub const EASE_OUT: Easing = Easing::cubic(0.0, 0.0, 0.58, 1.0);
|
||||
pub const EASE_IN_OUT: Easing = Easing::cubic(0.42, 0.0, 0.58, 1.0);
|
||||
/// Kit's CSS enter: `cubic-bezier(.2,.8,.2,1)`, 150 ms.
|
||||
pub const ENTER: Easing = Easing::cubic(0.2, 0.8, 0.2, 1.0);
|
||||
/// Kit's CSS exit: `cubic-bezier(.4,0,1,1)`, 110 ms.
|
||||
pub const EXIT: Easing = Easing::cubic(0.4, 0.0, 1.0, 1.0);
|
||||
/// Kit's overshoot for marks: `cubic-bezier(.34,1.45,.64,1)`.
|
||||
pub const OVERSHOOT: Easing = Easing::cubic(0.34, 1.45, 0.64, 1.0);
|
||||
/// Kit's draw-on: `cubic-bezier(.45,0,.2,1)`.
|
||||
pub const DRAW_ON: Easing = Easing::cubic(0.45, 0.0, 0.2, 1.0);
|
||||
|
||||
/// `cubic-bezier(x1, y1, x2, y2)`. `x1` and `x2` are clamped to `[0, 1]` like CSS requires.
|
||||
pub const fn cubic(x1: f32, y1: f32, x2: f32, y2: f32) -> Easing {
|
||||
Easing::CubicBezier(CubicBezier::new(x1, y1, x2, y2))
|
||||
}
|
||||
|
||||
/// Eased progress at `x`.
|
||||
#[inline]
|
||||
pub fn eval(&self, x: f32) -> f32 {
|
||||
self.eval_with_slope(x).0
|
||||
}
|
||||
|
||||
/// `(y, dy/dx)` at `x`. The slope turns into velocity when a tween is retargeted.
|
||||
#[inline]
|
||||
pub fn eval_with_slope(&self, x: f32) -> (f32, f32) {
|
||||
match self {
|
||||
Easing::Linear => (x, 1.0),
|
||||
Easing::CubicBezier(b) => b.eval_with_slope(x),
|
||||
Easing::Steps(n, pos) => (steps(x, *n, *pos), 0.0),
|
||||
Easing::Piecewise(stops) => piecewise(x, stops),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit cubic Bézier through (0,0), (x1,y1), (x2,y2), (1,1), stored as polynomial coefficients.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CubicBezier {
|
||||
pub x1: f32,
|
||||
pub y1: f32,
|
||||
pub x2: f32,
|
||||
pub y2: f32,
|
||||
}
|
||||
|
||||
impl CubicBezier {
|
||||
pub const fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
|
||||
let x1 = if x1 < 0.0 { 0.0 } else if x1 > 1.0 { 1.0 } else { x1 };
|
||||
let x2 = if x2 < 0.0 { 0.0 } else if x2 > 1.0 { 1.0 } else { x2 };
|
||||
CubicBezier { x1, y1, x2, y2 }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn coefficients(a1: f32, a2: f32) -> (f32, f32, f32) {
|
||||
let c = 3.0 * a1;
|
||||
let b = 3.0 * (a2 - a1) - c;
|
||||
let a = 1.0 - c - b;
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
/// Solves `x(t) = x` the way WebKit's `UnitBezier` does (Newton, then bisection), then returns
|
||||
/// `y(t)` and `dy/dx`.
|
||||
pub fn eval_with_slope(&self, x: f32) -> (f32, f32) {
|
||||
if x <= 0.0 {
|
||||
return (0.0, self.slope_at(0.0));
|
||||
}
|
||||
if x >= 1.0 {
|
||||
return (1.0, self.slope_at(1.0));
|
||||
}
|
||||
let t = self.solve_t(x);
|
||||
let (ay, by, cy) = Self::coefficients(self.y1, self.y2);
|
||||
let y = ((ay * t + by) * t + cy) * t;
|
||||
(y, self.slope_at(t))
|
||||
}
|
||||
|
||||
fn slope_at(&self, t: f32) -> f32 {
|
||||
let (ax, bx, cx) = Self::coefficients(self.x1, self.x2);
|
||||
let (ay, by, cy) = Self::coefficients(self.y1, self.y2);
|
||||
let dx = (3.0 * ax * t + 2.0 * bx) * t + cx;
|
||||
let dy = (3.0 * ay * t + 2.0 * by) * t + cy;
|
||||
if dx.abs() < 1e-6 {
|
||||
// Vertical tangent (x1 = 0 at t = 0): report a steep but finite slope.
|
||||
return if dy == 0.0 { 0.0 } else { dy.signum() * 1e3 };
|
||||
}
|
||||
dy / dx
|
||||
}
|
||||
|
||||
fn solve_t(&self, x: f32) -> f32 {
|
||||
const EPS: f32 = 1e-7;
|
||||
let (ax, bx, cx) = Self::coefficients(self.x1, self.x2);
|
||||
let sample = |t: f32| ((ax * t + bx) * t + cx) * t;
|
||||
let mut t = x;
|
||||
for _ in 0..8 {
|
||||
let err = sample(t) - x;
|
||||
if err.abs() < EPS {
|
||||
return t;
|
||||
}
|
||||
let d = (3.0 * ax * t + 2.0 * bx) * t + cx;
|
||||
if d.abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
t -= err / d;
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f32, 1.0f32);
|
||||
t = x;
|
||||
for _ in 0..40 {
|
||||
let v = sample(t);
|
||||
if (v - x).abs() < EPS {
|
||||
break;
|
||||
}
|
||||
if x > v {
|
||||
lo = t;
|
||||
} else {
|
||||
hi = t;
|
||||
}
|
||||
t = (lo + hi) * 0.5;
|
||||
}
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
fn steps(x: f32, n: u16, pos: StepPosition) -> f32 {
|
||||
if x >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
if x <= 0.0 && !matches!(pos, StepPosition::Start | StepPosition::Both) {
|
||||
return 0.0;
|
||||
}
|
||||
let n = n.max(1) as f32;
|
||||
let mut step = (x.max(0.0) * n).floor();
|
||||
if matches!(pos, StepPosition::Start | StepPosition::Both) {
|
||||
step += 1.0;
|
||||
}
|
||||
let jumps = match pos {
|
||||
StepPosition::Start | StepPosition::End => n,
|
||||
StepPosition::Both => n + 1.0,
|
||||
StepPosition::None => (n - 1.0).max(1.0),
|
||||
};
|
||||
(step.min(jumps) / jumps).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
fn piecewise(x: f32, stops: &[[f32; 2]]) -> (f32, f32) {
|
||||
match stops {
|
||||
[] => (x, 1.0),
|
||||
[only] => (only[1], 0.0),
|
||||
_ => {
|
||||
let x = x.clamp(stops[0][0], stops[stops.len() - 1][0]);
|
||||
let i = stops.partition_point(|s| s[0] <= x).clamp(1, stops.len() - 1);
|
||||
let [x0, y0] = stops[i - 1];
|
||||
let [x1, y1] = stops[i];
|
||||
let dx = x1 - x0;
|
||||
if dx <= 0.0 {
|
||||
return (y1, 0.0);
|
||||
}
|
||||
let slope = (y1 - y0) / dx;
|
||||
(y0 + (x - x0) * slope, slope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn css_bezier_known_values() {
|
||||
// Chrome: getComputedTiming for `ease` at 50 % progress is ~0.8024.
|
||||
let y = Easing::EASE.eval(0.5);
|
||||
assert!((y - 0.802_4).abs() < 1e-3, "{y}");
|
||||
let y = Easing::EASE_IN_OUT.eval(0.5);
|
||||
assert!((y - 0.5).abs() < 1e-5);
|
||||
assert_eq!(Easing::EASE_OUT.eval(0.0), 0.0);
|
||||
assert_eq!(Easing::EASE_OUT.eval(1.0), 1.0);
|
||||
// The overshoot curve rises above 1.
|
||||
assert!((0..100).any(|i| Easing::OVERSHOOT.eval(i as f32 / 100.0) > 1.05));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bezier_is_monotone_in_x_and_solves_exactly() {
|
||||
let b = CubicBezier::new(0.2, 0.8, 0.2, 1.0);
|
||||
let (ax, bx, cx) = CubicBezier::coefficients(b.x1, b.x2);
|
||||
for i in 1..1000 {
|
||||
let x = i as f32 / 1000.0;
|
||||
let t = b.solve_t(x);
|
||||
let back = ((ax * t + bx) * t + cx) * t;
|
||||
assert!((back - x).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_follow_css() {
|
||||
assert_eq!(steps(0.0, 4, StepPosition::End), 0.0);
|
||||
assert_eq!(steps(0.3, 4, StepPosition::End), 0.25);
|
||||
assert_eq!(steps(0.3, 4, StepPosition::Start), 0.5);
|
||||
assert_eq!(steps(0.5, 2, StepPosition::None), 1.0);
|
||||
assert_eq!(steps(0.4, 2, StepPosition::Both), 1.0 / 3.0);
|
||||
assert_eq!(steps(1.0, 3, StepPosition::Both), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn piecewise_linear() {
|
||||
let e = Easing::Piecewise(&[[0.0, 0.0], [0.5, 0.8], [1.0, 1.0]]);
|
||||
assert!((e.eval(0.25) - 0.4).abs() < 1e-6);
|
||||
assert!((e.eval(0.75) - 0.9).abs() < 1e-6);
|
||||
assert_eq!(e.eval_with_slope(0.25).1, 1.6);
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
//! Direct manipulation helpers: velocity tracking, fling projection and rubber-banding.
|
||||
//!
|
||||
//! During a drag the value is `set` 1:1 (no animation on the user's own hand, Kit rule 5). On
|
||||
//! release, hand the tracked velocity to [`crate::AnimationStore::release`].
|
||||
|
||||
use crate::value::{Animatable, lanes};
|
||||
|
||||
/// iOS `UIScrollView` deceleration rates, per millisecond.
|
||||
pub mod deceleration {
|
||||
pub const NORMAL: f32 = 0.998;
|
||||
pub const FAST: f32 = 0.99;
|
||||
}
|
||||
|
||||
/// Where a fling released at `x` with velocity `v` (units/s) comes to rest under UIKit's
|
||||
/// per-millisecond deceleration `rate` (WWDC18 "Designing Fluid Interfaces"):
|
||||
/// `x + (v / 1000) · rate / (1 − rate)`.
|
||||
pub fn project(x: f32, v: f32, rate: f32) -> f32 {
|
||||
x + (v / 1000.0) * rate / (1.0 - rate)
|
||||
}
|
||||
|
||||
/// iOS rubber-band: how far content moves when dragged `overshoot` points past its edge, in a
|
||||
/// viewport `dimension` points long. `f(x) = (1 − 1 / (x·c/d + 1)) · d`, c = 0.55.
|
||||
pub fn rubber_band(overshoot: f32, dimension: f32) -> f32 {
|
||||
rubber_band_with(overshoot, dimension, 0.55)
|
||||
}
|
||||
|
||||
/// [`rubber_band`] with an explicit constant `c`. Odd in `overshoot`, so it works both ways.
|
||||
pub fn rubber_band_with(overshoot: f32, dimension: f32, c: f32) -> f32 {
|
||||
if dimension <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let x = overshoot.abs();
|
||||
let y = (1.0 - 1.0 / (x * c / dimension + 1.0)) * dimension;
|
||||
y.copysign(overshoot)
|
||||
}
|
||||
|
||||
/// Maps a raw drag position into `[min, max]`, rubber-banding whatever lies outside.
|
||||
pub fn rubber_band_clamp(x: f32, min: f32, max: f32, dimension: f32) -> f32 {
|
||||
if x < min {
|
||||
min + rubber_band(x - min, dimension)
|
||||
} else if x > max {
|
||||
max + rubber_band(x - max, dimension)
|
||||
} else {
|
||||
x
|
||||
}
|
||||
}
|
||||
|
||||
const SAMPLES: usize = 20;
|
||||
|
||||
/// Least-squares velocity over the last 100 ms of samples (at most 20), using the platform
|
||||
/// event timestamps. 40 ms without movement counts as stopped (Flutter `VelocityTracker`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VelocityTracker<T: Animatable> {
|
||||
t: [f64; SAMPLES],
|
||||
x: [[f32; 4]; SAMPLES],
|
||||
len: usize,
|
||||
head: usize,
|
||||
_t: core::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: Animatable> Default for VelocityTracker<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Animatable> VelocityTracker<T> {
|
||||
const HORIZON: f64 = 0.100;
|
||||
const STOP_GAP: f64 = 0.040;
|
||||
|
||||
pub fn new() -> Self {
|
||||
assert!(T::LANES <= 4, "VelocityTracker supports values of up to 4 lanes");
|
||||
VelocityTracker { t: [0.0; SAMPLES], x: [[0.0; 4]; SAMPLES], len: 0, head: 0, _t: core::marker::PhantomData }
|
||||
}
|
||||
|
||||
/// Records a position at event time `t` (seconds).
|
||||
pub fn add(&mut self, t: f64, value: T) {
|
||||
let l = lanes(&value);
|
||||
self.t[self.head] = t;
|
||||
self.x[self.head] = [l[0], l[1], l[2], l[3]];
|
||||
self.head = (self.head + 1) % SAMPLES;
|
||||
self.len = (self.len + 1).min(SAMPLES);
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.len = 0;
|
||||
}
|
||||
|
||||
/// Velocity in units per second at the newest sample.
|
||||
pub fn velocity(&self) -> T {
|
||||
let mut out = [0.0f32; 4];
|
||||
if self.len >= 2 {
|
||||
let newest = (self.head + SAMPLES - 1) % SAMPLES;
|
||||
let t_new = self.t[newest];
|
||||
// Collect samples within the horizon, stopping at a long pause.
|
||||
let mut idx = [0usize; SAMPLES];
|
||||
let mut n = 0;
|
||||
let mut prev_t = t_new;
|
||||
for k in 0..self.len {
|
||||
let i = (newest + SAMPLES - k) % SAMPLES;
|
||||
let t = self.t[i];
|
||||
if t_new - t > Self::HORIZON || prev_t - t > Self::STOP_GAP {
|
||||
break;
|
||||
}
|
||||
idx[n] = i;
|
||||
n += 1;
|
||||
prev_t = t;
|
||||
}
|
||||
if n >= 2 {
|
||||
let mean_t = idx[..n].iter().map(|&i| self.t[i] - t_new).sum::<f64>() / n as f64;
|
||||
let var: f64 = idx[..n].iter().map(|&i| (self.t[i] - t_new - mean_t).powi(2)).sum();
|
||||
if var > 1e-12 {
|
||||
for (lane, o) in out.iter_mut().enumerate().take(T::LANES) {
|
||||
let mean_x = idx[..n].iter().map(|&i| self.x[i][lane] as f64).sum::<f64>() / n as f64;
|
||||
let cov: f64 = idx[..n]
|
||||
.iter()
|
||||
.map(|&i| (self.t[i] - t_new - mean_t) * (self.x[i][lane] as f64 - mean_x))
|
||||
.sum();
|
||||
*o = (cov / var) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
T::read_lanes(&out[..T::LANES])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn projection_matches_uikit() {
|
||||
// 1000 pt/s at the normal rate coasts 499 pt.
|
||||
assert!((project(0.0, 1000.0, deceleration::NORMAL) - 499.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rubber_band_is_sublinear_and_odd() {
|
||||
let d = 800.0;
|
||||
assert!(rubber_band(100.0, d) < 55.0 + 1e-3);
|
||||
assert!(rubber_band(100.0, d) > 0.0);
|
||||
assert_eq!(rubber_band(-100.0, d), -rubber_band(100.0, d));
|
||||
// Small overshoot ≈ 0.55 × overshoot.
|
||||
assert!((rubber_band(1.0, d) - 0.55).abs() < 1e-3);
|
||||
assert_eq!(rubber_band_clamp(50.0, 0.0, 100.0, d), 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracker_recovers_constant_velocity() {
|
||||
let mut tr = VelocityTracker::<f32>::new();
|
||||
for i in 0..30 {
|
||||
let t = i as f64 / 120.0;
|
||||
tr.add(t, 300.0 * t as f32);
|
||||
}
|
||||
assert!((tr.velocity() - 300.0).abs() < 0.5);
|
||||
// A pause longer than 40 ms means stopped.
|
||||
tr.add(30.0 / 120.0 + 0.2, 75.0);
|
||||
assert_eq!(tr.velocity(), 0.0);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
//! SwiftUI `KeyframeAnimator`-style keyframe tracks: linear, cubic (Catmull-Rom, C¹), spring and
|
||||
//! move keyframes, played back as scheduled segments on a store track.
|
||||
|
||||
use crate::curve::{Blend, Curve};
|
||||
use crate::easing::Easing;
|
||||
use crate::props::Prop;
|
||||
use crate::spring::Spring;
|
||||
use crate::store::{AnimationStore, TrackId};
|
||||
use crate::value::{Animatable, lanes};
|
||||
|
||||
/// One keyframe: where to be at the end of its slot and how to get there.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Keyframe<T> {
|
||||
/// `LinearKeyframe`: interpolate from the previous value with `easing` (linear by default).
|
||||
Linear { value: T, duration: f32, easing: Easing },
|
||||
/// `SpringKeyframe`: spring toward `value` for `duration` seconds, then hand the exact
|
||||
/// position and velocity to the next keyframe (it needn't have arrived).
|
||||
Spring { value: T, duration: f32, spring: Spring },
|
||||
/// `CubicKeyframe`: a Catmull-Rom spline through consecutive cubic keyframes. Velocity is
|
||||
/// continuous across keyframes.
|
||||
Cubic { value: T, duration: f32 },
|
||||
/// `MoveKeyframe`: jump to `value` with no duration.
|
||||
Move { value: T },
|
||||
}
|
||||
|
||||
/// An ordered keyframe track for one property (`KeyframeTrack`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Keyframes<T> {
|
||||
frames: Vec<Keyframe<T>>,
|
||||
delay: f32,
|
||||
repeat: u32,
|
||||
}
|
||||
|
||||
impl<T: Animatable> Default for Keyframes<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Animatable> Keyframes<T> {
|
||||
/// Starts from the property's current value.
|
||||
pub fn new() -> Self {
|
||||
Keyframes { frames: Vec::new(), delay: 0.0, repeat: 1 }
|
||||
}
|
||||
pub fn linear(mut self, value: T, duration: f32) -> Self {
|
||||
self.frames.push(Keyframe::Linear { value, duration, easing: Easing::Linear });
|
||||
self
|
||||
}
|
||||
pub fn eased(mut self, value: T, duration: f32, easing: Easing) -> Self {
|
||||
self.frames.push(Keyframe::Linear { value, duration, easing });
|
||||
self
|
||||
}
|
||||
/// A spring keyframe lasting the spring's own duration.
|
||||
pub fn spring(mut self, value: T, spring: Spring) -> Self {
|
||||
self.frames.push(Keyframe::Spring { value, duration: spring.duration, spring });
|
||||
self
|
||||
}
|
||||
pub fn spring_for(mut self, value: T, duration: f32, spring: Spring) -> Self {
|
||||
self.frames.push(Keyframe::Spring { value, duration, spring });
|
||||
self
|
||||
}
|
||||
pub fn cubic(mut self, value: T, duration: f32) -> Self {
|
||||
self.frames.push(Keyframe::Cubic { value, duration });
|
||||
self
|
||||
}
|
||||
pub fn move_to(mut self, value: T) -> Self {
|
||||
self.frames.push(Keyframe::Move { value });
|
||||
self
|
||||
}
|
||||
pub fn delay(mut self, seconds: f32) -> Self {
|
||||
self.delay = seconds;
|
||||
self
|
||||
}
|
||||
/// Plays the whole track `times` times (≥ 1). Endless loops belong to [`crate::PhaseAnimator`].
|
||||
pub fn repeat(mut self, times: u32) -> Self {
|
||||
self.repeat = times.max(1);
|
||||
self
|
||||
}
|
||||
/// One pass, in seconds.
|
||||
pub fn duration(&self) -> f32 {
|
||||
self.frames.iter().map(Keyframe::duration).sum()
|
||||
}
|
||||
pub fn frames(&self) -> &[Keyframe<T>] {
|
||||
&self.frames
|
||||
}
|
||||
fn last_value(&self) -> Option<T> {
|
||||
self.frames.last().map(Keyframe::value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Animatable> Keyframe<T> {
|
||||
pub fn value(&self) -> T {
|
||||
match *self {
|
||||
Keyframe::Linear { value, .. }
|
||||
| Keyframe::Spring { value, .. }
|
||||
| Keyframe::Cubic { value, .. }
|
||||
| Keyframe::Move { value } => value,
|
||||
}
|
||||
}
|
||||
pub fn duration(&self) -> f32 {
|
||||
match *self {
|
||||
Keyframe::Linear { duration, .. } | Keyframe::Spring { duration, .. } | Keyframe::Cubic { duration, .. } => {
|
||||
duration.max(0.0)
|
||||
}
|
||||
Keyframe::Move { .. } => 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationStore {
|
||||
/// Plays `keyframes` on a property from its current value (cancels anything scheduled on it).
|
||||
/// Under Reduce Motion, spatial tracks jump to the final value and fades take the short fade.
|
||||
pub fn play_keyframes<T: Animatable>(&mut self, node: crate::NodeId, prop: Prop<T>, kf: &Keyframes<T>) -> TrackId {
|
||||
let Some(last) = kf.last_value() else {
|
||||
return self.track_id(node, prop).unwrap_or_else(|| panic!("empty keyframes on a new property"));
|
||||
};
|
||||
let first = kf.frames[0].value();
|
||||
let start = if self.has(node, prop) { self.sample(node, prop).unwrap() } else { first };
|
||||
let init = lanes(&start);
|
||||
let t = self.ensure(node, prop.id, prop.class, &init[..T::LANES]) as usize;
|
||||
let n = T::LANES;
|
||||
if self.reduced_motion() && prop.class.reduce(Curve::Spring(Spring::SMOOTH)) != Curve::Spring(Spring::SMOOTH) {
|
||||
let target = lanes(&last);
|
||||
let anim = crate::Anim { delay: kf.delay, ..crate::Anim::new(Curve::Spring(Spring::SMOOTH)) };
|
||||
self.animate_raw(t, &target[..n], anim, None);
|
||||
return self.id_of(t);
|
||||
}
|
||||
self.cancel_track_pending(t);
|
||||
let mut at = self.time_of(t) + kf.delay as f64;
|
||||
let mut prev = init;
|
||||
let frames = &kf.frames;
|
||||
for _ in 0..kf.repeat {
|
||||
for (k, frame) in frames.iter().enumerate() {
|
||||
let v = lanes(&frame.value());
|
||||
let dur = frame.duration();
|
||||
for i in 0..n {
|
||||
let (curve, vel) = match *frame {
|
||||
Keyframe::Linear { duration, easing, .. } => (Curve::Tween { duration, easing }, Some(0.0)),
|
||||
Keyframe::Spring { spring, .. } => (Curve::Spring(spring), None),
|
||||
Keyframe::Move { .. } => (Curve::Instant, None),
|
||||
Keyframe::Cubic { duration, .. } => {
|
||||
// Catmull-Rom tangent at this keyframe's end, if the next one is cubic too.
|
||||
let next = frames.get(k + 1).or(if kf.repeat > 1 { frames.first() } else { None });
|
||||
let m = match next {
|
||||
Some(Keyframe::Cubic { value, duration: d2 }) => {
|
||||
let nv = lanes(value);
|
||||
(nv[i] - prev[i]) / (duration + d2).max(1e-6)
|
||||
}
|
||||
_ => 0.0,
|
||||
};
|
||||
(Curve::Hermite { duration, end_velocity: m }, None)
|
||||
}
|
||||
};
|
||||
self.schedule(t, i, at, v[i], curve, Blend::Merge, vel);
|
||||
}
|
||||
at += dur as f64;
|
||||
prev = v;
|
||||
}
|
||||
}
|
||||
// Final segment: a spring keyframe may not have arrived when its slot ends; let it finish.
|
||||
self.commit_scheduled(t, at, 0);
|
||||
self.id_of(t)
|
||||
}
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
//! One analytic segment of motion for one scalar lane.
|
||||
//!
|
||||
//! Every curve is written as `value(t) = target + offset(t − t0)` where the offset decays to 0.
|
||||
//! A lane's presented value is its target plus the sum of its layers' offsets. Sample-and-restart
|
||||
//! retargeting ("merge", SwiftUI springs) keeps one layer; Core-Animation-style additive retargeting
|
||||
//! pushes another. Both start from exact `(x, v)`, so position and velocity stay continuous.
|
||||
|
||||
use crate::curve::Curve;
|
||||
use crate::easing::Easing;
|
||||
use crate::math::{exp, sin_cos};
|
||||
use crate::spring::Spring;
|
||||
|
||||
/// Settle thresholds: below these the residual offset and speed are invisible, so the lane can
|
||||
/// snap to `(target, 0)` and go dormant.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Eps {
|
||||
pub pos: f32,
|
||||
pub vel: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub(crate) enum Kind {
|
||||
/// Contributes nothing.
|
||||
Rest,
|
||||
/// ζ < 1: e^{−στ}(A cos ωd τ + B sin ωd τ). c = [A, B, C, D, σ, ωd], v = e^{−στ}(C cos + D sin).
|
||||
Under,
|
||||
/// ζ = 1: (A + Bτ) e^{−ωτ}. c = [A, B, C, D, ω, _], v = (C + Dτ) e^{−ωτ}.
|
||||
Critical,
|
||||
/// ζ > 1: c1 e^{r1 τ} + c2 e^{r2 τ}. c = [c1, c2, r1, r2, _, _].
|
||||
Over,
|
||||
/// Exponential decay (fling): A e^{−kτ}. c = [A, k, ..].
|
||||
Decay,
|
||||
/// Eased tween from offset Δ to 0, plus a carried velocity that fades out. c = [Δ, d, 1/d, carry, ..].
|
||||
Tween,
|
||||
/// Cubic polynomial a + bτ + cτ² + dτ³ until τ = dur (Hermite keyframes). c = [a, b, c, d, dur, _].
|
||||
Poly,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Layer {
|
||||
pub t0: f64,
|
||||
/// Absolute time after which the offset and its velocity are below `Eps` (or exactly 0).
|
||||
pub end: f64,
|
||||
pub c: [f32; 6],
|
||||
pub kind: Kind,
|
||||
pub easing: Easing,
|
||||
}
|
||||
|
||||
/// Longest any single layer may run before it is considered settled.
|
||||
const MAX_SETTLE: f64 = 120.0;
|
||||
|
||||
impl Layer {
|
||||
pub const REST: Layer =
|
||||
Layer { t0: 0.0, end: f64::NEG_INFINITY, c: [0.0; 6], kind: Kind::Rest, easing: Easing::Linear };
|
||||
|
||||
/// A layer for `curve` that starts at `t0` with `offset` (= position − target) and `velocity`.
|
||||
pub fn start(curve: &Curve, t0: f64, offset: f32, velocity: f32, eps: Eps) -> Layer {
|
||||
match *curve {
|
||||
Curve::Spring(s) => Layer::spring(s, t0, offset, velocity, eps),
|
||||
Curve::Tween { duration, easing } => Layer::tween(duration, easing, t0, offset, velocity),
|
||||
Curve::Decay(d) => Layer::decay(d.k(), t0, velocity, eps),
|
||||
Curve::Hermite { duration, end_velocity } => {
|
||||
Layer::hermite(duration, t0, offset, velocity, end_velocity)
|
||||
}
|
||||
Curve::Instant => Layer::REST,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spring(s: Spring, t0: f64, offset: f32, v0: f32, eps: Eps) -> Layer {
|
||||
let mut layer = Layer::spring_unbounded(s, t0, offset, v0);
|
||||
if layer.kind != Kind::Rest {
|
||||
layer.end = t0 + layer.settle_after(eps);
|
||||
}
|
||||
layer
|
||||
}
|
||||
|
||||
/// A spring layer that never ends; for one-off sampling where no settle bound is needed.
|
||||
pub fn spring_unbounded(s: Spring, t0: f64, offset: f32, v0: f32) -> Layer {
|
||||
if offset == 0.0 && v0 == 0.0 {
|
||||
return Layer::REST;
|
||||
}
|
||||
let omega = s.omega();
|
||||
let zeta = s.zeta();
|
||||
let a = offset;
|
||||
let (kind, c) = if (zeta - 1.0).abs() < 1e-4 {
|
||||
let b = v0 + omega * a;
|
||||
(Kind::Critical, [a, b, b - omega * a, -omega * b, omega, 0.0])
|
||||
} else if zeta < 1.0 {
|
||||
let sigma = zeta * omega;
|
||||
let wd = omega * (1.0 - zeta * zeta).sqrt();
|
||||
let b = (v0 + sigma * a) / wd;
|
||||
(Kind::Under, [a, b, b * wd - sigma * a, -a * wd - sigma * b, sigma, wd])
|
||||
} else {
|
||||
let root = (zeta * zeta - 1.0).sqrt();
|
||||
let r1 = -omega * (zeta - root);
|
||||
let r2 = -omega * (zeta + root);
|
||||
let c1 = (v0 - r2 * a) / (r1 - r2);
|
||||
(Kind::Over, [c1, a - c1, r1, r2, 0.0, 0.0])
|
||||
};
|
||||
Layer { t0, end: f64::INFINITY, c, kind, easing: Easing::Linear }
|
||||
}
|
||||
|
||||
/// `velocity` is the motion carried in from before the tween; it fades out by the end.
|
||||
pub fn tween(duration: f32, easing: Easing, t0: f64, offset: f32, velocity: f32) -> Layer {
|
||||
if duration <= 0.0 || (offset == 0.0 && velocity == 0.0) {
|
||||
return Layer::REST;
|
||||
}
|
||||
Layer {
|
||||
t0,
|
||||
end: t0 + duration as f64,
|
||||
c: [offset, duration, 1.0 / duration, velocity, 0.0, 0.0],
|
||||
kind: Kind::Tween,
|
||||
easing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exponential decay with rate `k` (1/s). The lane's target is the projected rest point
|
||||
/// `x + v/k`, and the offset starts at `−v/k`.
|
||||
pub fn decay(k: f32, t0: f64, v0: f32, eps: Eps) -> Layer {
|
||||
if v0 == 0.0 {
|
||||
return Layer::REST;
|
||||
}
|
||||
let a = -v0 / k;
|
||||
let mut layer = Layer { t0, end: 0.0, c: [a, k, 0.0, 0.0, 0.0, 0.0], kind: Kind::Decay, easing: Easing::Linear };
|
||||
let tp = ((a.abs() / eps.pos) as f64).ln();
|
||||
let tv = ((v0.abs() / eps.vel) as f64).ln();
|
||||
layer.end = t0 + (tp.max(tv) / k as f64).clamp(0.0, MAX_SETTLE);
|
||||
layer
|
||||
}
|
||||
|
||||
/// Cubic Hermite from `(offset, v0)` to `(0, v1)` over `duration`: C¹ keyframe splines.
|
||||
pub fn hermite(duration: f32, t0: f64, offset: f32, v0: f32, v1: f32) -> Layer {
|
||||
if duration <= 0.0 {
|
||||
return Layer::REST;
|
||||
}
|
||||
let d = duration;
|
||||
let a = offset;
|
||||
let b = v0;
|
||||
let cc = (-3.0 * a - (2.0 * b + v1) * d) / (d * d);
|
||||
let dd = (2.0 * a + (v1 + b) * d) / (d * d * d);
|
||||
Layer { t0, end: t0 + d as f64, c: [a, b, cc, dd, d, 0.0], kind: Kind::Poly, easing: Easing::Linear }
|
||||
}
|
||||
|
||||
/// `(offset, velocity)` at absolute time `now`. Physics layers return exactly `(0, 0)` once
|
||||
/// `now ≥ end`; timed layers (tweens, keyframe cubics) hold their end state, so the velocity
|
||||
/// a keyframe ends with is handed to the next one.
|
||||
#[inline(always)]
|
||||
pub fn sample(&self, now: f64) -> (f32, f32) {
|
||||
if self.kind == Kind::Rest
|
||||
|| (now >= self.end && !matches!(self.kind, Kind::Tween | Kind::Poly))
|
||||
{
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
let tau = (now - self.t0).max(0.0) as f32;
|
||||
let c = &self.c;
|
||||
match self.kind {
|
||||
Kind::Under => {
|
||||
let e = exp(-c[4] * tau);
|
||||
let (s, co) = sin_cos(c[5] * tau);
|
||||
(e * (c[0] * co + c[1] * s), e * (c[2] * co + c[3] * s))
|
||||
}
|
||||
Kind::Critical => {
|
||||
let e = exp(-c[4] * tau);
|
||||
((c[0] + c[1] * tau) * e, (c[2] + c[3] * tau) * e)
|
||||
}
|
||||
Kind::Over => {
|
||||
let e1 = exp(c[2] * tau);
|
||||
let e2 = exp(c[3] * tau);
|
||||
(c[0] * e1 + c[1] * e2, c[0] * c[2] * e1 + c[1] * c[3] * e2)
|
||||
}
|
||||
Kind::Decay => {
|
||||
let e = exp(-c[1] * tau);
|
||||
(c[0] * e, -c[1] * c[0] * e)
|
||||
}
|
||||
Kind::Tween => {
|
||||
let tau = tau.min(c[1]);
|
||||
let u = (tau * c[2]).min(1.0);
|
||||
let (y, dy) = self.easing.eval_with_slope(u);
|
||||
let w = 1.0 - u;
|
||||
let g = tau * w * w;
|
||||
let dg = w * (1.0 - 3.0 * u);
|
||||
(c[0] * (1.0 - y) + c[3] * g, -c[0] * dy * c[2] + c[3] * dg)
|
||||
}
|
||||
Kind::Poly => {
|
||||
let tau = tau.min(c[4]);
|
||||
let (a, b, cc, d) = (c[0], c[1], c[2], c[3]);
|
||||
(a + tau * (b + tau * (cc + tau * d)), b + tau * (2.0 * cc + tau * 3.0 * d))
|
||||
}
|
||||
Kind::Rest => (0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds after `t0` until both |offset| ≤ eps.pos and |velocity| ≤ eps.vel for good.
|
||||
fn settle_after(&self, eps: Eps) -> f64 {
|
||||
let c = self.c.map(f64::from);
|
||||
let (ep, ev) = (eps.pos as f64, eps.vel as f64);
|
||||
let t = match self.kind {
|
||||
Kind::Under => {
|
||||
// Envelopes: |offset| ≤ hypot(A, B) e^{−στ}, |v| ≤ hypot(C, D) e^{−στ}.
|
||||
let sigma = c[4];
|
||||
let tp = (c[0].hypot(c[1]) / ep).ln();
|
||||
let tv = (c[2].hypot(c[3]) / ev).ln();
|
||||
tp.max(tv) / sigma
|
||||
}
|
||||
Kind::Critical => {
|
||||
// Each of offset and velocity is (a + bτ) e^{−ωτ}: its remaining maximum is at τ or
|
||||
// at its single extremum (psychopomp `settling_time`).
|
||||
let omega = c[4];
|
||||
let tail = |a: f64, b: f64, t: f64| {
|
||||
let at = |t: f64| ((a + b * t) * (-omega * t).exp()).abs();
|
||||
let ext = if b == 0.0 { -1.0 } else { 1.0 / omega - a / b };
|
||||
at(t).max(if ext > t { at(ext) } else { 0.0 })
|
||||
};
|
||||
let ok = |t: f64| tail(c[0], c[1], t) <= ep && tail(c[2], c[3], t) <= ev;
|
||||
bisect(ok, 1.0 / omega)
|
||||
}
|
||||
Kind::Over => {
|
||||
let env = |t: f64| c[0].abs() * (c[2] * t).exp() + c[1].abs() * (c[3] * t).exp();
|
||||
let envv = |t: f64| {
|
||||
(c[0] * c[2]).abs() * (c[2] * t).exp() + (c[1] * c[3]).abs() * (c[3] * t).exp()
|
||||
};
|
||||
bisect(|t| env(t) <= ep && envv(t) <= ev, -1.0 / c[2])
|
||||
}
|
||||
_ => 0.0,
|
||||
};
|
||||
if t.is_finite() { t.clamp(0.0, MAX_SETTLE) } else { MAX_SETTLE }
|
||||
}
|
||||
}
|
||||
|
||||
/// Smallest `t ≥ 0` with `ok(t)` for a predicate that stays true once true.
|
||||
fn bisect(ok: impl Fn(f64) -> bool, scale: f64) -> f64 {
|
||||
if ok(0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
let mut hi = scale.max(1e-3);
|
||||
while !ok(hi) {
|
||||
hi *= 2.0;
|
||||
if hi > MAX_SETTLE {
|
||||
return MAX_SETTLE;
|
||||
}
|
||||
}
|
||||
let mut lo = 0.0;
|
||||
for _ in 0..40 {
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if ok(mid) {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
}
|
||||
}
|
||||
hi
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bench {
|
||||
use super::*;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
// rune-motion has no Rune dependencies; this benchmark runs natively.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn now() -> Instant { Instant::now() }
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_layer_kinds() {
|
||||
let n = 100_000;
|
||||
for (name, s) in [("under", Spring::new(3.0, 0.3)), ("critical", Spring::new(3.0, 0.0))] {
|
||||
let layers: Vec<Layer> = (0..n)
|
||||
.map(|i| Layer::spring(s, 0.0, -100.0 - (i % 13) as f32, 0.0, Eps { pos: 1e-3, vel: 1e-2 }))
|
||||
.collect();
|
||||
let mut out = vec![0.0f32; n];
|
||||
let t0 = now();
|
||||
for f in 0..120 {
|
||||
let now = f as f64 / 120.0;
|
||||
for (o, l) in out.iter_mut().zip(&layers) {
|
||||
let (a, b) = l.sample(now);
|
||||
*o = a + b;
|
||||
}
|
||||
black_box(&out);
|
||||
}
|
||||
println!("{name}: {:.2} ns/lane", t0.elapsed().as_nanos() as f64 / (120 * n) as f64);
|
||||
}
|
||||
let xs: Vec<f32> = (0..n).map(|i| -(i as f32) * 1e-4).collect();
|
||||
let t0 = now();
|
||||
let mut acc = 0.0;
|
||||
for _ in 0..120 {
|
||||
for &x in &xs {
|
||||
acc += exp(black_box(x));
|
||||
}
|
||||
}
|
||||
black_box(acc);
|
||||
println!("exp: {:.2} ns", t0.elapsed().as_nanos() as f64 / (120 * n) as f64);
|
||||
let t0 = now();
|
||||
for _ in 0..120 {
|
||||
for &x in &xs {
|
||||
let (s, c) = sin_cos(black_box(x * 100.0));
|
||||
acc += s + c;
|
||||
}
|
||||
}
|
||||
black_box(acc);
|
||||
println!("sin_cos: {:.2} ns", t0.elapsed().as_nanos() as f64 / (120 * n) as f64);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
//! # rune-motion
|
||||
//!
|
||||
//! Rune's animation runtime: pure math and data structures the render thread drives once per
|
||||
//! frame. App code states targets; this crate turns them into presented values with no app work
|
||||
//! per frame (PLAN.md §3, §4.9; research 06).
|
||||
//!
|
||||
//! - [`Spring`]: SwiftUI's `Spring(duration:bounce:)`, closed form for every damping regime.
|
||||
//! - [`Curve`]: springs, CSS tweens ([`Easing`]), decay (fling), keyframes.
|
||||
//! - [`Animatable`]: f32, [`Vec2`], [`Rect`] (as edges), [`Color`] (premultiplied OKLab),
|
||||
//! [`Corners`], [`Transform`], [`Blur`], tuples, arrays.
|
||||
//! - [`AnimationStore`]: struct-of-arrays tracks, retargeting that keeps position and velocity,
|
||||
//! merge or additive blending, delays, settle events, zero allocation per frame.
|
||||
//! - [`Scene`]: presence (exits that stay mounted), [`Transition`]s incl. blur-replace, layout
|
||||
//! animation by edges, screen-space travel, matched geometry, per-frame [`Presented`] output.
|
||||
//! - [`Choreography`], [`Stagger`], [`PhaseAnimator`], [`Keyframes`]; [`Clock`]; motion-lint
|
||||
//! [`MotionTrace`]s.
|
||||
//!
|
||||
//! ```
|
||||
//! use rune_motion::prelude::*;
|
||||
//!
|
||||
//! let mut store = AnimationStore::new();
|
||||
//! let card = NodeId(1);
|
||||
//! store.set(card, prop::OPACITY, 0.0);
|
||||
//! store.animate(card, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
//! store.tick_at(0.15);
|
||||
//! let o = store.get(card, prop::OPACITY).unwrap();
|
||||
//! assert!(o > 0.5 && o < 1.0);
|
||||
//! ```
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod animated;
|
||||
mod carry;
|
||||
mod choreo;
|
||||
mod clock;
|
||||
mod curve;
|
||||
mod cycle;
|
||||
mod easing;
|
||||
mod gesture;
|
||||
mod keyframes;
|
||||
mod layer;
|
||||
mod looping;
|
||||
pub mod math;
|
||||
mod props;
|
||||
mod scene;
|
||||
mod sequence;
|
||||
pub mod snap;
|
||||
mod spring;
|
||||
mod store;
|
||||
pub mod tokens;
|
||||
mod trace;
|
||||
mod transition;
|
||||
mod value;
|
||||
|
||||
pub use animated::Animated;
|
||||
pub use choreo::Choreography;
|
||||
pub use choreo::Cue;
|
||||
pub use choreo::Ops;
|
||||
pub use choreo::PhaseAnimator;
|
||||
pub use choreo::Stagger;
|
||||
pub use choreo::StaggerFrom;
|
||||
pub use choreo::StepId;
|
||||
pub use choreo::When;
|
||||
pub use choreo::stagger;
|
||||
pub use clock::Clock;
|
||||
pub use curve::Anim;
|
||||
pub use curve::AnimExt;
|
||||
pub use curve::Blend;
|
||||
pub use curve::Curve;
|
||||
pub use curve::Decay;
|
||||
pub use curve::Velocity;
|
||||
pub use cycle::Cycle;
|
||||
pub use easing::CubicBezier;
|
||||
pub use easing::Easing;
|
||||
pub use easing::StepPosition;
|
||||
pub use gesture::VelocityTracker;
|
||||
pub use gesture::deceleration;
|
||||
pub use gesture::project;
|
||||
pub use gesture::rubber_band;
|
||||
pub use gesture::rubber_band_clamp;
|
||||
pub use gesture::rubber_band_with;
|
||||
pub use keyframes::Keyframe;
|
||||
pub use keyframes::Keyframes;
|
||||
pub use layer::Eps;
|
||||
pub use looping::LoopKind;
|
||||
pub use looping::LoopSpec;
|
||||
pub use looping::LoopTrack;
|
||||
pub use props::NodeId;
|
||||
pub use props::Prop;
|
||||
pub use props::PropClass;
|
||||
pub use props::PropId;
|
||||
pub use props::REDUCED_FADE;
|
||||
pub use props::prop;
|
||||
pub use scene::FrameOutput;
|
||||
pub use scene::LayoutAnim;
|
||||
pub use scene::Mask;
|
||||
pub use scene::Mount;
|
||||
pub use scene::NodeSpec;
|
||||
pub use scene::Phase;
|
||||
pub use scene::Presented;
|
||||
pub use scene::Scene;
|
||||
pub use scene::Travel;
|
||||
pub use scene::WIDTH_LEAD;
|
||||
pub use sequence::Beat;
|
||||
pub use sequence::Sequence;
|
||||
pub use spring::Spring;
|
||||
pub use spring::SpringPair;
|
||||
pub use store::AnimationStore;
|
||||
#[doc(hidden)]
|
||||
pub use store::Fx;
|
||||
pub use store::MotionEvent;
|
||||
pub use store::Release;
|
||||
pub use store::RetargetAudit;
|
||||
pub use store::TrackId;
|
||||
pub use tokens as motion;
|
||||
pub use trace::Intent;
|
||||
pub use trace::MotionTrace;
|
||||
pub use trace::SharedBuffer;
|
||||
pub use trace::TraceChannels;
|
||||
pub use trace::TraceHeader;
|
||||
pub use trace::flags;
|
||||
pub use transition::Edge;
|
||||
pub use transition::Effect;
|
||||
pub use transition::Reveal;
|
||||
pub use transition::SMALL_SCALE_FLOOR;
|
||||
pub use transition::Transition;
|
||||
pub use value::Animatable;
|
||||
pub use value::Blur;
|
||||
pub use value::Color;
|
||||
pub use value::Corners;
|
||||
pub use value::MAX_LANES;
|
||||
pub use value::Rect;
|
||||
pub use value::Sides;
|
||||
pub use value::Transform;
|
||||
pub use value::Vec2;
|
||||
pub use value::linear_to_oklab;
|
||||
pub use value::oklab_to_linear;
|
||||
pub use value::srgb_decode;
|
||||
pub use value::srgb_encode;
|
||||
|
||||
/// Everything an animation call site needs.
|
||||
pub mod prelude {
|
||||
pub use crate::Anim;
|
||||
pub use crate::AnimExt;
|
||||
pub use crate::Animatable;
|
||||
pub use crate::Animated;
|
||||
pub use crate::AnimationStore;
|
||||
pub use crate::Blend;
|
||||
pub use crate::Clock;
|
||||
pub use crate::Color;
|
||||
pub use crate::Corners;
|
||||
pub use crate::Cue;
|
||||
pub use crate::Curve;
|
||||
pub use crate::Decay;
|
||||
pub use crate::Easing;
|
||||
pub use crate::Edge;
|
||||
pub use crate::Keyframes;
|
||||
pub use crate::LayoutAnim;
|
||||
pub use crate::Mount;
|
||||
pub use crate::NodeId;
|
||||
pub use crate::NodeSpec;
|
||||
pub use crate::Presented;
|
||||
pub use crate::Rect;
|
||||
pub use crate::Release;
|
||||
pub use crate::Scene;
|
||||
pub use crate::Spring;
|
||||
pub use crate::SpringPair;
|
||||
pub use crate::Stagger;
|
||||
pub use crate::StaggerFrom;
|
||||
pub use crate::Transition;
|
||||
pub use crate::Travel;
|
||||
pub use crate::Vec2;
|
||||
pub use crate::Velocity;
|
||||
pub use crate::motion;
|
||||
pub use crate::prop;
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
//! Clock-driven periodic and finite motion. Visibility is a renderer decision, not a second clock.
|
||||
use crate::{Animated, Beat, Cycle, Easing, Sequence, PropClass, Spring};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum LoopKind {
|
||||
Opacity { low: f32, high: f32 },
|
||||
/// Piecewise-linear, wall-clock opacity sampled at display rate or a fixed cadence.
|
||||
OpacityCycle(Cycle),
|
||||
/// Finite opacity/scale choreography; holds its last pose at rest.
|
||||
Sequence(Sequence),
|
||||
Rotation,
|
||||
/// An eased one-way sweep that wraps, in fractions of the node's own size (an
|
||||
/// indeterminate progress segment). Descendants and hit tests follow it.
|
||||
Slide { from: [f32; 2], to: [f32; 2] },
|
||||
/// A `Slide` swept along `easing` instead of ease-in-out ([`LoopSpec::easing`]).
|
||||
SlideEased { from: [f32; 2], to: [f32; 2], easing: Easing },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct LoopSpec {
|
||||
pub period: f64,
|
||||
pub delay: f64,
|
||||
pub kind: LoopKind,
|
||||
}
|
||||
|
||||
impl LoopSpec {
|
||||
pub fn sequence(frames: Sequence) -> Self {
|
||||
Self { period: frames.duration(), delay: frames.delay, kind: LoopKind::Sequence(frames) }
|
||||
}
|
||||
pub fn cycle(cycle: Cycle) -> Self {
|
||||
Self { period: f64::from(cycle.period), delay: 0.0, kind: LoopKind::OpacityCycle(cycle) }
|
||||
}
|
||||
pub const fn opacity(period: f64, delay: f64, low: f32, high: f32) -> Self {
|
||||
Self { period, delay, kind: LoopKind::Opacity { low, high } }
|
||||
}
|
||||
pub const fn rotation(period: f64) -> Self {
|
||||
Self { period, delay: 0.0, kind: LoopKind::Rotation }
|
||||
}
|
||||
/// Reduced motion holds the sweep's midpoint; removal cools it back to no offset.
|
||||
pub const fn slide(period: f64, from: [f32; 2], to: [f32; 2]) -> Self {
|
||||
Self { period, delay: 0.0, kind: LoopKind::Slide { from, to } }
|
||||
}
|
||||
/// The curve a slide sweeps along each period, ease-in-out by default; `Easing::LINEAR`
|
||||
/// sweeps at a constant speed (a shimmer). Only slides take a curve; other kinds keep theirs.
|
||||
pub const fn easing(mut self, easing: Easing) -> Self {
|
||||
if let LoopKind::Slide { from, to } | LoopKind::SlideEased { from, to, .. } = self.kind {
|
||||
self.kind = LoopKind::SlideEased { from, to, easing };
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct LoopTrack {
|
||||
spec: LoopSpec,
|
||||
phase: Phase,
|
||||
phase0: f64,
|
||||
amplitude: Animated<f32>,
|
||||
}
|
||||
|
||||
/// Where a track is in its play. A periodic loop only ever plays (its cooling lives on
|
||||
/// `amplitude`); a finite sequence can also be done.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Phase {
|
||||
/// Playing, with phase 0 landing on `since`. A delayed start is a `since` still ahead.
|
||||
Playing { since: f64 },
|
||||
/// A finite sequence that played out: it holds its last pose, and enabling it again leaves
|
||||
/// it there. It does not replay.
|
||||
Done,
|
||||
}
|
||||
|
||||
impl LoopTrack {
|
||||
pub fn new(spec: LoopSpec, now: f64) -> Self {
|
||||
assert!(spec.period.is_finite() && spec.period > 0.0);
|
||||
assert!(spec.delay.is_finite() && spec.delay >= 0.0);
|
||||
Self { spec, phase: Phase::Playing { since: now + spec.delay }, phase0: 0.0,
|
||||
amplitude: Animated::new(1.0).with_class(PropClass::Opacity) }
|
||||
}
|
||||
/// Whether this track has an end: a finite sequence plays once and then rests.
|
||||
fn finite(&self) -> bool {
|
||||
matches!(self.spec.kind, LoopKind::Sequence(_))
|
||||
}
|
||||
pub fn phase(&self, now: f64) -> f64 {
|
||||
let since = match self.phase {
|
||||
Phase::Playing { since } => since,
|
||||
// A played-out sequence rests at its last pose.
|
||||
Phase::Done => return 1.0,
|
||||
};
|
||||
if self.finite() {
|
||||
return ((now - since) / self.spec.period).clamp(0.0, 1.0);
|
||||
}
|
||||
(self.phase0 + (now - since).max(0.0) / self.spec.period).rem_euclid(1.0)
|
||||
}
|
||||
/// Preserve the presented phase when changing speed. An unchanged spec is a no-op.
|
||||
pub fn retime(&mut self, spec: LoopSpec, now: f64) {
|
||||
assert!(spec.period.is_finite() && spec.period > 0.0);
|
||||
if self.spec == spec { return; }
|
||||
if self.finite() || matches!(spec.kind, LoopKind::Sequence(_)) {
|
||||
*self = Self::new(spec, now);
|
||||
return;
|
||||
}
|
||||
self.phase0 = self.phase(now);
|
||||
match &mut self.phase {
|
||||
Phase::Playing { since } => *since = now.max(*since),
|
||||
// Only a finite sequence is `Done`, and those restarted above.
|
||||
Phase::Done => {}
|
||||
}
|
||||
self.spec = spec;
|
||||
}
|
||||
/// Cool to rest without stopping or resetting phase. Reversal inherits envelope velocity.
|
||||
/// A finite sequence that cooled mid-play carries on from where its phase had reached; one
|
||||
/// that played out stays `Done` and does not replay.
|
||||
pub fn enabled(&mut self, enabled: bool, now: f64) {
|
||||
self.amplitude.animate_to(if enabled { 1.0 } else { 0.0 }, Spring::new(0.18, 0.0), now);
|
||||
}
|
||||
/// Moves the track onto a clock reading `delta` more, at the same place.
|
||||
pub fn shift(&mut self, delta: f64) {
|
||||
if let Phase::Playing { since } = &mut self.phase { *since += delta; }
|
||||
self.amplitude.shift(delta);
|
||||
}
|
||||
/// Moves a periodic loop `dt` further along its rhythm, for time its clock didn't see; a
|
||||
/// loop still waiting starts `dt` sooner. Finite sequences keep their place.
|
||||
pub fn advance(&mut self, dt: f64) {
|
||||
if !self.finite() && let Phase::Playing { since } = &mut self.phase { *since -= dt; }
|
||||
}
|
||||
/// Explicit settle/reduced motion lands finite sequences; periodic loops keep their phase.
|
||||
pub fn finish(&mut self) {
|
||||
if self.finite() { self.phase = Phase::Done; }
|
||||
}
|
||||
pub fn active(&self, now: f64) -> bool {
|
||||
match self.phase {
|
||||
Phase::Done => false,
|
||||
// A cooled sequence keeps its phase clock but draws nothing, so it asks for no
|
||||
// frames.
|
||||
Phase::Playing { since } if self.finite() => {
|
||||
self.amplitude.target() > 0.0 && now >= since && now < since + self.spec.period
|
||||
}
|
||||
Phase::Playing { since } => {
|
||||
(self.amplitude.target() > 0.0 && now >= since) || !self.amplitude.is_settled(now)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The animation-clock instant to wake at; no frames are needed before it.
|
||||
pub fn pending_start(&self, now: f64) -> Option<f64> {
|
||||
match self.phase {
|
||||
Phase::Playing { since } if self.amplitude.target() > 0.0 && now < since => Some(since),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A stepped cycle's timer interval. Continuous tracks use the host's frame request.
|
||||
pub fn frame_interval(&self) -> Option<f64> {
|
||||
match self.spec.kind {
|
||||
LoopKind::OpacityCycle(c) => c.frame_interval(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Opacity multiplier or clockwise radians. Reduced motion uses the calm first pose.
|
||||
pub fn sample(&self, now: f64, reduced: bool) -> f32 {
|
||||
self.sample_at(now, now, reduced)
|
||||
}
|
||||
pub fn sample_at(&self, now: f64, wall: f64, reduced: bool) -> f32 {
|
||||
let phase = if reduced { 0.0 } else { self.phase(now) as f32 };
|
||||
match self.spec.kind {
|
||||
LoopKind::Sequence(_) => self.pose(now, reduced).unwrap().opacity,
|
||||
LoopKind::OpacityCycle(c) => if reduced { c.still } else { c.sample(wall) },
|
||||
LoopKind::Rotation => phase * core::f32::consts::TAU,
|
||||
LoopKind::Slide { .. } | LoopKind::SlideEased { .. } => 1.0,
|
||||
LoopKind::Opacity { low, high } => {
|
||||
let triangle = if phase < 0.5 { phase * 2.0 } else { (1.0 - phase) * 2.0 };
|
||||
low + (high - low) * Easing::EASE_IN_OUT.eval(triangle) * self.amplitude.sample(now)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A `Slide`'s offset in fractions of the node's own size.
|
||||
pub fn offset(&self, now: f64, reduced: bool) -> Option<[f32; 2]> {
|
||||
let (from, to, easing) = match self.spec.kind {
|
||||
LoopKind::Slide { from, to } => (from, to, Easing::EASE_IN_OUT),
|
||||
LoopKind::SlideEased { from, to, easing } => (from, to, easing),
|
||||
_ => return None,
|
||||
};
|
||||
let t = if reduced { 0.5 } else { easing.eval(self.phase(now) as f32) };
|
||||
let a = self.amplitude.sample(now);
|
||||
Some([0, 1].map(|i| (from[i] + (to[i] - from[i]) * t) * a))
|
||||
}
|
||||
pub fn pose(&self, now: f64, reduced: bool) -> Option<Beat> {
|
||||
let LoopKind::Sequence(frames) = self.spec.kind else { return None };
|
||||
let at = if reduced || self.phase == Phase::Done { frames.duration() } else { self.phase(now) * frames.duration() };
|
||||
Some(frames.sample(at))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "looping_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,221 @@
|
||||
use super::*;
|
||||
#[test]
|
||||
fn sequence_delays_interpolates_holds_and_finishes_without_restarting() {
|
||||
const BEATS: &[Beat] = &[
|
||||
Beat::new(0.0).opacity(0.0).scale(0.8),
|
||||
Beat::new(0.3).easing(Easing::LINEAR),
|
||||
Beat::new(0.6).opacity(0.5).scale(1.1).easing(Easing::LINEAR),
|
||||
Beat::new(0.9).easing(Easing::LINEAR),
|
||||
];
|
||||
let spec = LoopSpec::sequence(Sequence::new(BEATS).delay(0.2));
|
||||
let mut track = LoopTrack::new(spec, 4.0);
|
||||
assert_eq!(track.pending_start(4.0), Some(4.2));
|
||||
assert!(!track.active(4.1));
|
||||
let pose = track.pose(4.35, false).unwrap();
|
||||
assert!((pose.opacity - 0.5).abs() < 1e-5 && (pose.scale - 0.9).abs() < 1e-5);
|
||||
track.retime(spec, 4.35);
|
||||
assert_eq!(track.pose(4.35, false).unwrap(), pose);
|
||||
assert!(track.active(4.35));
|
||||
assert!(!track.active(5.2));
|
||||
assert_eq!(track.pose(5.2, false).unwrap().opacity, 1.0);
|
||||
assert_eq!(track.pose(4.35, true).unwrap().scale, 1.0);
|
||||
track.finish();
|
||||
assert!(!track.active(4.35));
|
||||
assert_eq!(track.pending_start(4.0), None);
|
||||
assert_eq!(track.pose(4.35, false).unwrap().scale, 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn a_finished_sequence_stays_done_when_enabled_again() {
|
||||
const BEATS: &[Beat] = &[Beat::new(0.0).opacity(0.0), Beat::new(0.5).opacity(1.0)];
|
||||
let spec = LoopSpec::sequence(Sequence::new(BEATS).delay(0.2));
|
||||
let mut t = LoopTrack::new(spec, 0.0);
|
||||
t.finish();
|
||||
assert!(!t.active(0.3), "a finished sequence asks for no frames");
|
||||
assert_eq!(t.pending_start(0.3), None);
|
||||
assert_eq!(t.pose(0.3, false).unwrap().opacity, 1.0, "and holds its last pose");
|
||||
t.advance(1.0);
|
||||
assert_eq!(t.pose(0.3, false).unwrap().opacity, 1.0, "a sequence keeps its place");
|
||||
t.enabled(false, 1.0);
|
||||
assert!(!t.active(10.0), "cooled to rest");
|
||||
t.enabled(true, 2.0);
|
||||
assert_eq!(t.pending_start(2.0), None, "enabling again doesn't wait on a delay");
|
||||
assert!(!t.active(2.1), "and asks for no frames");
|
||||
assert_eq!(t.pose(2.1, false).unwrap().opacity, 1.0, "holding its last pose");
|
||||
assert_eq!(t.pose(0.3, false).unwrap().opacity, 1.0, "it never replays");
|
||||
}
|
||||
#[test]
|
||||
fn a_sequence_that_ran_out_while_cooled_rests_instead_of_replaying() {
|
||||
const BEATS: &[Beat] = &[Beat::new(0.0).opacity(0.0), Beat::new(0.5).opacity(1.0)];
|
||||
let spec = LoopSpec::sequence(Sequence::new(BEATS).delay(0.2));
|
||||
let mut t = LoopTrack::new(spec, 0.0);
|
||||
assert!(t.active(0.5), "playing until 0.7");
|
||||
t.enabled(false, 0.5);
|
||||
assert!(!t.active(0.5), "cooled to rest");
|
||||
t.enabled(true, 2.0);
|
||||
assert_eq!(t.pending_start(2.0), None, "the delay is not paid again");
|
||||
assert!(!t.active(2.1));
|
||||
assert_eq!(t.pose(2.1, false).unwrap().opacity, 1.0, "it rests where it ran out");
|
||||
}
|
||||
#[test]
|
||||
fn enabling_a_cooled_sequence_carries_on_from_its_presented_phase() {
|
||||
const BEATS: &[Beat] = &[
|
||||
Beat::new(0.0).opacity(0.0).easing(Easing::LINEAR),
|
||||
Beat::new(1.0).opacity(1.0).easing(Easing::LINEAR),
|
||||
];
|
||||
let spec = LoopSpec::sequence(Sequence::new(BEATS).delay(0.2));
|
||||
let mut t = LoopTrack::new(spec, 0.0);
|
||||
let cooled = t.phase(0.7);
|
||||
assert!((cooled - 0.5).abs() < 1e-9, "mid-run, half way");
|
||||
t.enabled(false, 0.7);
|
||||
assert!(!t.active(0.7), "cooled to rest");
|
||||
t.enabled(true, 0.9);
|
||||
assert!(t.active(0.9), "it warms back up and asks for frames");
|
||||
assert_eq!(t.pending_start(0.9), None, "it does not wait out the delay again");
|
||||
assert!((t.phase(0.9) - 0.7).abs() < 1e-9, "it carries on from where it had reached");
|
||||
assert!(
|
||||
(t.pose(0.9, false).unwrap().opacity - 0.7).abs() < 1e-5,
|
||||
"presenting the pose its phase reached, not its first pose"
|
||||
);
|
||||
assert!(!t.active(1.3), "and still ends where its own clock does");
|
||||
assert_eq!(t.pose(1.3, false).unwrap().opacity, 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn enabling_leaves_a_looping_tracks_phase_alone() {
|
||||
let specs = [
|
||||
LoopSpec::opacity(1.0, 0.0, 0.2, 0.8),
|
||||
LoopSpec::rotation(0.9),
|
||||
LoopSpec::slide(2.0, [-1.0, 0.0], [3.0, 0.0]),
|
||||
];
|
||||
for spec in specs {
|
||||
let mut cooled = LoopTrack::new(spec, 0.0);
|
||||
let plain = LoopTrack::new(spec, 0.0);
|
||||
cooled.enabled(false, 0.4);
|
||||
assert!(cooled.active(0.41), "cooling keeps its settle frames");
|
||||
cooled.enabled(true, 1.1);
|
||||
for i in 0..50 {
|
||||
let now = 1.1 + i as f64 * 0.037;
|
||||
assert_eq!(cooled.phase(now), plain.phase(now), "{spec:?} keeps its phase");
|
||||
assert_eq!(cooled.active(now), plain.active(now));
|
||||
assert_eq!(cooled.pending_start(now), plain.pending_start(now));
|
||||
}
|
||||
assert!((cooled.sample(5.0, false) - plain.sample(5.0, false)).abs() < 1e-6);
|
||||
match (cooled.offset(5.0, false), plain.offset(5.0, false)) {
|
||||
(Some(warmed), Some(never)) => {
|
||||
assert!((warmed[0] - never[0]).abs() < 1e-6, "its amplitude warms back to full");
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => panic!("the same spec asks for the same offsets"),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn a_delayed_loop_shifts_and_advances_its_start() {
|
||||
let mut t = LoopTrack::new(LoopSpec::opacity(1.0, 2.0, 0.0, 1.0), 3.0);
|
||||
assert_eq!(t.pending_start(3.0), Some(5.0));
|
||||
t.shift(0.5);
|
||||
assert_eq!(t.pending_start(3.0), Some(5.5), "a clock shift moves the start with it");
|
||||
t.advance(0.25);
|
||||
assert_eq!(t.pending_start(3.0), Some(5.25), "time the clock didn't see starts it sooner");
|
||||
assert!(!t.active(5.0));
|
||||
assert!(t.active(5.25));
|
||||
}
|
||||
#[test]
|
||||
fn cycle_preserves_wall_phase_stops_still_and_cadence() {
|
||||
let c = Cycle { period: 1.7, phase: 0.3, stops: &[(0.0, 0.2), (0.2, 1.0), (0.7, 0.1), (1.0, 0.2)], still: 0.4, fps: 30.0 };
|
||||
let track = LoopTrack::new(LoopSpec::cycle(c), 4.0);
|
||||
for i in 0..200 {
|
||||
let wall = i as f64 * 0.037;
|
||||
assert_eq!(track.sample_at(4.0, wall, false), c.sample(wall));
|
||||
assert_eq!(track.sample_at(4.0, wall, true), c.still);
|
||||
}
|
||||
assert_eq!(track.frame_interval(), Some(f64::from(1.0 / 30.0_f32)));
|
||||
}
|
||||
#[test]
|
||||
fn delay_has_one_wake_and_no_active_frames() {
|
||||
let track = LoopTrack::new(LoopSpec::opacity(1.0, 2.0, 0.0, 1.0), 3.0);
|
||||
assert_eq!(track.pending_start(3.0), Some(5.0));
|
||||
assert!(!track.active(4.999));
|
||||
assert_eq!(track.sample(4.999, false), 0.0);
|
||||
assert_eq!(track.pending_start(5.0), None);
|
||||
assert!(track.active(5.0));
|
||||
assert_eq!(track.phase(5.0), 0.0);
|
||||
}
|
||||
#[test]
|
||||
fn phase_continuity_and_clock_sampling() {
|
||||
let mut t = LoopTrack::new(LoopSpec::rotation(0.9), 4.0);
|
||||
for i in 0..200 {
|
||||
let now = 4.0 + i as f64 * 0.037;
|
||||
let before = t.phase(now);
|
||||
t.retime(LoopSpec::rotation(0.2 + (i % 9) as f64 * 0.1), now);
|
||||
assert!((before - t.phase(now)).abs() < 1e-12);
|
||||
assert_eq!(t.sample(now, false), t.sample(now, false));
|
||||
}
|
||||
assert_eq!(t.sample(100.0, true), 0.0);
|
||||
}
|
||||
#[test]
|
||||
fn slide_sweeps_wraps_holds_midpoint_reduced_and_cools_to_rest() {
|
||||
let mut t = LoopTrack::new(LoopSpec::slide(2.0, [-1.0, 0.0], [3.0, 0.0]), 0.0);
|
||||
assert_eq!(t.offset(0.0, false), Some([-1.0, 0.0]));
|
||||
assert_eq!(t.offset(1.0, false), Some([1.0, 0.0]));
|
||||
assert_eq!(t.offset(2.0, false), t.offset(0.0, false));
|
||||
let xs: Vec<f32> = (0..200).map(|i| t.offset(i as f64 * 0.01, false).unwrap()[0]).collect();
|
||||
assert!(xs.windows(2).all(|w| w[1] >= w[0]), "a sweep only moves forward within a period");
|
||||
assert_eq!(t.offset(0.37, true), Some([1.0, 0.0]));
|
||||
assert_eq!(t.sample(0.37, false), 1.0, "a slide never changes opacity");
|
||||
assert_eq!(LoopTrack::new(LoopSpec::rotation(1.0), 0.0).offset(0.5, false), None);
|
||||
t.enabled(false, 1.0);
|
||||
assert!(t.active(1.01));
|
||||
assert!(!t.active(10.0));
|
||||
assert_eq!(t.offset(10.0, false), Some([0.0, 0.0]));
|
||||
}
|
||||
#[test]
|
||||
fn a_linear_slide_sweeps_at_a_constant_speed_and_holds_its_midpoint_reduced() {
|
||||
let spec = LoopSpec::slide(2.0, [-1.0, 0.0], [3.0, 0.0]).easing(Easing::LINEAR);
|
||||
let t = LoopTrack::new(spec, 0.0);
|
||||
// 240 frames at 120 Hz: one period, each frame the same step forward.
|
||||
let xs: Vec<f32> = (0..240).map(|i| t.offset(i as f64 / 120.0, false).unwrap()[0]).collect();
|
||||
assert_eq!(xs[0], -1.0);
|
||||
for pair in xs.windows(2) {
|
||||
assert!((pair[1] - pair[0] - 4.0 / 240.0).abs() < 1e-4, "step {} -> {}", pair[0], pair[1]);
|
||||
}
|
||||
assert_eq!(t.offset(2.0, false), Some([-1.0, 0.0]), "wraps after a period");
|
||||
assert_eq!(t.offset(0.37, true), Some([1.0, 0.0]), "reduced motion holds the midpoint");
|
||||
assert_eq!(t.sample(0.37, false), 1.0);
|
||||
// The default stays ease-in-out, and naming it is the same spec.
|
||||
let eased = LoopSpec::slide(2.0, [-1.0, 0.0], [3.0, 0.0]);
|
||||
assert_eq!(eased.easing(Easing::LINEAR).easing(Easing::EASE_IN_OUT).kind,
|
||||
LoopKind::SlideEased { from: [-1.0, 0.0], to: [3.0, 0.0], easing: Easing::EASE_IN_OUT });
|
||||
let e = LoopTrack::new(eased, 0.0);
|
||||
let steps: Vec<f32> = (0..121).map(|i| e.offset(i as f64 / 120.0, false).unwrap()[0]).collect::<Vec<_>>()
|
||||
.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
assert!(steps[60] > steps[0] * 4.0, "ease-in-out starts slow");
|
||||
assert_eq!(LoopSpec::rotation(1.0).easing(Easing::LINEAR), LoopSpec::rotation(1.0), "only slides take a curve");
|
||||
}
|
||||
#[test]
|
||||
fn cooling_keeps_phase_and_settles() {
|
||||
let mut t = LoopTrack::new(LoopSpec::opacity(1.0, 0.0, 0.15, 0.65), 0.0);
|
||||
let before = t.sample(0.3, false);
|
||||
t.enabled(false, 0.3);
|
||||
assert_eq!(t.sample(0.3, false), before);
|
||||
assert!(t.active(0.31));
|
||||
assert!(!t.active(10.0));
|
||||
assert_eq!(t.sample(10.0, false), 0.15);
|
||||
}
|
||||
#[test]
|
||||
fn clock_pause_scale_step_and_seek_match_reference() {
|
||||
let spec = LoopSpec::rotation(0.9);
|
||||
let t = LoopTrack::new(spec, 0.0);
|
||||
let mut clock = crate::Clock::manual(120.0);
|
||||
for _ in 0..17 { clock.step(); }
|
||||
let first = t.sample(clock.now(), false);
|
||||
clock.pause(0.0);
|
||||
for _ in 0..40 { clock.step(); }
|
||||
assert_eq!(t.sample(clock.now(), false), first);
|
||||
clock.resume(0.0);
|
||||
clock.set_scale(0.25, 0.0);
|
||||
clock.step();
|
||||
let reference = ((17.0 / 120.0 + 0.25 / 120.0) / 0.9) as f32 * core::f32::consts::TAU;
|
||||
assert!((t.sample(clock.now(), false) - reference).abs() < 1e-6);
|
||||
clock.seek(0.45);
|
||||
assert!((t.sample(clock.now(), false) - core::f32::consts::PI).abs() < 1e-6);
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
//! Deterministic `exp`, `sin` and `cos`.
|
||||
//!
|
||||
//! Built only from IEEE-754 operations (`+ − × /`, `round`, and fused multiply-add where the
|
||||
//! target has it), so the same inputs give bit-identical outputs on every machine of the same
|
||||
//! kind: Apple silicon, aarch64 Linux and x86-64 with FMA (x86-64-v3) agree with each other;
|
||||
//! x86-64 without FMA takes an equally accurate non-fused path. Platform `libm`s differ in the
|
||||
//! last bits, which makes golden motion traces flaky across CI hosts (research 06 §1.7). These
|
||||
//! are also several times faster than libm for the ranges a spring needs: polynomials are
|
||||
//! evaluated with Estrin's scheme so a frame's lanes overlap in the pipeline.
|
||||
|
||||
#[cfg(any(target_arch = "aarch64", target_feature = "fma"))]
|
||||
const FUSED: bool = true;
|
||||
#[cfg(not(any(target_arch = "aarch64", target_feature = "fma")))]
|
||||
const FUSED: bool = false;
|
||||
|
||||
/// `a·b + c`, fused (one rounding) where the hardware has it.
|
||||
#[inline(always)]
|
||||
fn fma(a: f32, b: f32, c: f32) -> f32 {
|
||||
if FUSED { a.mul_add(b, c) } else { a * b + c }
|
||||
}
|
||||
|
||||
const LOG2_E: f32 = core::f32::consts::LOG2_E;
|
||||
// fdlibm's split of ln 2: the high part has zero low bits so `k · LN2_HI` is exact for |k| < 2^12.
|
||||
const LN2_HI: f32 = 6.931_457_5e-1;
|
||||
const LN2_LO: f32 = 1.428_606_8e-6;
|
||||
|
||||
/// `e^x` with a relative error under 3e-7 for x in [−87, 88]. Below that it returns 0; above, ∞.
|
||||
#[inline(always)]
|
||||
pub fn exp(x: f32) -> f32 {
|
||||
let xc = x.clamp(-87.0, 88.0);
|
||||
let k = (xc * LOG2_E).round();
|
||||
let r = fma(-k, LN2_LO, fma(-k, LN2_HI, xc));
|
||||
// e^r on |r| ≤ ln2/2, Taylor to degree 6 (truncation 1.2e-7), Estrin's scheme.
|
||||
let r2 = r * r;
|
||||
let a = 1.0 + r;
|
||||
let b = fma(r, 1.0 / 6.0, 0.5);
|
||||
let c = fma(r, 1.0 / 120.0, 1.0 / 24.0);
|
||||
let p = fma(r2, fma(r2, fma(r2, 1.0 / 720.0, c), b), a);
|
||||
let bits = ((k as i32 + 127) as u32) << 23;
|
||||
let y = p * f32::from_bits(bits);
|
||||
if x < -87.0 { 0.0 } else if x > 88.0 { f32::INFINITY } else { y }
|
||||
}
|
||||
|
||||
/// `(sin x, cos x)` with an absolute error under 3e-7 for |x| < 1e5.
|
||||
#[inline(always)]
|
||||
pub fn sin_cos(x: f32) -> (f32, f32) {
|
||||
let (q, r) = reduce_pio2(x);
|
||||
let z = r * r;
|
||||
let z2 = z * z;
|
||||
// Taylor on |r| ≤ π/4: sin to degree 9 (error 2e-9), cos to degree 10 (error 1e-10).
|
||||
let s_hi = fma(z, 1.0 / 120.0, -1.0 / 6.0);
|
||||
let s_lo = fma(z, 1.0 / 362_880.0, -1.0 / 5040.0);
|
||||
let s = fma(r * z, fma(z2, s_lo, s_hi), r);
|
||||
let c_hi = fma(z, 1.0 / 24.0, -0.5);
|
||||
let c_mid = fma(z, -1.0 / 3_628_800.0, 1.0 / 40_320.0);
|
||||
let c_lo = fma(z, c_mid, -1.0 / 720.0);
|
||||
let c = fma(z, fma(z2, c_lo, c_hi), 1.0);
|
||||
// Quadrant fix-up without branches (the quadrant is unpredictable across lanes):
|
||||
// q0 (s, c) q1 (c, −s) q2 (−s, −c) q3 (−c, s).
|
||||
let swap = q & 1 != 0;
|
||||
let (sb, cb) = if swap { (c, s) } else { (s, c) };
|
||||
let sin_sign = (q & 2) << 30;
|
||||
let cos_sign = (q.wrapping_add(1) & 2) << 30;
|
||||
(f32::from_bits(sb.to_bits() ^ sin_sign), f32::from_bits(cb.to_bits() ^ cos_sign))
|
||||
}
|
||||
|
||||
/// `x = q·π/2 + r` with |r| ≤ π/4; returns the low bits of q and r.
|
||||
#[inline(always)]
|
||||
#[allow(clippy::approx_constant)]
|
||||
fn reduce_pio2(x: f32) -> (u32, f32) {
|
||||
if FUSED {
|
||||
// Two-part Cody–Waite in f32; exact enough with fused steps for |q| < 2^20.
|
||||
const HI: f32 = 1.570_796_4; // f32 nearest π/2
|
||||
const LO: f32 = -4.371_139e-8; // π/2 − HI
|
||||
let q = (x * core::f32::consts::FRAC_2_PI).round();
|
||||
let r = fma(-q, LO, fma(-q, HI, x));
|
||||
(q as i32 as u32, r)
|
||||
} else {
|
||||
// No FMA: reduce in f64, where the products are exact enough.
|
||||
const PIO2_HI: f64 = 1.570_796_326_734_125_6;
|
||||
const PIO2_LO: f64 = 6.077_100_506_506_192e-11;
|
||||
let xd = x as f64;
|
||||
let q = (xd * core::f64::consts::FRAC_2_PI).round();
|
||||
let r = ((xd - q * PIO2_HI) - q * PIO2_LO) as f32;
|
||||
(q as i64 as u32, r)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn exp_matches_std() {
|
||||
let mut x = -87.0f32;
|
||||
while x < 88.0 {
|
||||
let ours = exp(x) as f64;
|
||||
let theirs = (x as f64).exp();
|
||||
assert!(((ours - theirs) / theirs).abs() < 4e-7, "exp({x}) = {ours}, std {theirs}");
|
||||
x += 0.0137;
|
||||
}
|
||||
assert_eq!(exp(0.0), 1.0);
|
||||
assert_eq!(exp(-100.0), 0.0);
|
||||
assert_eq!(exp(100.0), f32::INFINITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sin_cos_match_std() {
|
||||
let mut x = -2000.0f32;
|
||||
while x < 2000.0 {
|
||||
let (s, c) = sin_cos(x);
|
||||
let xd = x as f64;
|
||||
assert!((s as f64 - xd.sin()).abs() < 4e-7, "sin({x}) {s} vs {}", xd.sin());
|
||||
assert!((c as f64 - xd.cos()).abs() < 4e-7, "cos({x}) {c} vs {}", xd.cos());
|
||||
x += 0.0731;
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
//! Typed property keys and the classes the runtime applies policy by.
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use crate::curve::Curve;
|
||||
use crate::easing::Easing;
|
||||
use crate::layer::Eps;
|
||||
use crate::value::{Animatable, Color, Corners, Rect, Sides, Vec2};
|
||||
|
||||
/// A stable node key from the app side (a hash of the keyed path, a row id, …).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct NodeId(pub u64);
|
||||
|
||||
/// An untyped property id, as it appears in events and traces.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct PropId(pub u16);
|
||||
|
||||
/// What kind of quantity a property is. The runtime picks settle thresholds and reduced-motion
|
||||
/// behaviour from this, so authors can't forget either.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PropClass {
|
||||
/// Positions, edges, offsets, sizes (points).
|
||||
Spatial,
|
||||
Scale,
|
||||
/// Radians.
|
||||
Rotation,
|
||||
Opacity,
|
||||
/// Blur radius (points).
|
||||
Blur,
|
||||
/// Colours (premultiplied OKLab lanes).
|
||||
Color,
|
||||
/// Corner radii, borders, feathers (points).
|
||||
Shape,
|
||||
/// A 0…1 presence progress that fades content in and out.
|
||||
Presence,
|
||||
/// Values the user's own hand drives (scroll offset, drag position). Never reduced.
|
||||
Gesture,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// The fade that replaces travel under Reduce Motion (OpenCode `reducedFade` .20, 75 ms in a native app;
|
||||
/// Kit: ≈ .15–.2 s).
|
||||
pub const REDUCED_FADE: Curve = Curve::Tween { duration: 0.18, easing: Easing::EASE_IN_OUT };
|
||||
|
||||
impl PropClass {
|
||||
/// Settle thresholds, set below the 1/64 px snap quantum so the final snap is invisible
|
||||
/// (research 06 §2.3). `pixel_scale` is device pixels per point.
|
||||
pub fn eps(self, pixel_scale: f32) -> Eps {
|
||||
let px = 1.0 / (128.0 * pixel_scale.max(1.0));
|
||||
let pos = match self {
|
||||
PropClass::Spatial | PropClass::Shape | PropClass::Gesture | PropClass::Blur => px,
|
||||
PropClass::Scale | PropClass::Rotation | PropClass::Presence => 1e-5,
|
||||
PropClass::Opacity | PropClass::Color => 1.0 / 1024.0,
|
||||
PropClass::Other => 1e-4,
|
||||
};
|
||||
Eps { pos, vel: pos * 10.0 }
|
||||
}
|
||||
|
||||
/// What Reduce Motion turns `curve` into for this class (research 06 §2.12): travel, scale,
|
||||
/// rotation, shape and blur jump; opacity, colour and presence take a short fade; the user's
|
||||
/// own gestures are untouched.
|
||||
pub fn reduce(self, curve: Curve) -> Curve {
|
||||
if matches!(curve, Curve::Instant | Curve::Decay(_)) {
|
||||
return curve;
|
||||
}
|
||||
match self {
|
||||
PropClass::Spatial
|
||||
| PropClass::Scale
|
||||
| PropClass::Rotation
|
||||
| PropClass::Shape
|
||||
| PropClass::Blur => Curve::Instant,
|
||||
PropClass::Opacity | PropClass::Color | PropClass::Presence => REDUCED_FADE,
|
||||
PropClass::Gesture | PropClass::Other => curve,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed property key: `prop::OPACITY` is a `Prop<f32>`, `prop::FRAME` a `Prop<Rect>`.
|
||||
pub struct Prop<T> {
|
||||
pub id: PropId,
|
||||
pub class: PropClass,
|
||||
_t: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Clone for Prop<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
impl<T> Copy for Prop<T> {}
|
||||
impl<T> core::fmt::Debug for Prop<T> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "Prop({}, {:?})", self.id.0, self.class)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Animatable> Prop<T> {
|
||||
/// A custom property. Ids below 64 are reserved for the built-ins.
|
||||
pub const fn custom(id: u16, class: PropClass) -> Prop<T> {
|
||||
assert!(id >= 64, "custom property ids start at 64");
|
||||
Prop { id: PropId(id), class, _t: PhantomData }
|
||||
}
|
||||
const fn builtin(id: u16, class: PropClass) -> Prop<T> {
|
||||
Prop { id: PropId(id), class, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
/// Built-in properties the scene and renderer understand.
|
||||
pub mod prop {
|
||||
use super::*;
|
||||
|
||||
pub const OPACITY: Prop<f32> = Prop::builtin(0, PropClass::Opacity);
|
||||
/// The layout frame in parent space, animated as four edges.
|
||||
pub const FRAME: Prop<Rect> = Prop::builtin(1, PropClass::Spatial);
|
||||
pub const OFFSET: Prop<Vec2> = Prop::builtin(2, PropClass::Spatial);
|
||||
pub const SCALE: Prop<f32> = Prop::builtin(3, PropClass::Scale);
|
||||
pub const ROTATION: Prop<f32> = Prop::builtin(4, PropClass::Rotation);
|
||||
pub const BLUR: Prop<f32> = Prop::builtin(5, PropClass::Blur);
|
||||
pub const RADIUS: Prop<Corners> = Prop::builtin(6, PropClass::Shape);
|
||||
pub const FILL: Prop<Color> = Prop::builtin(7, PropClass::Color);
|
||||
/// Soft-mask insets (left, top, right, bottom) in points.
|
||||
pub const MASK: Prop<Sides> = Prop::builtin(8, PropClass::Shape);
|
||||
/// Scroll or drag offset owned by the render thread.
|
||||
pub const SCROLL: Prop<Vec2> = Prop::builtin(9, PropClass::Gesture);
|
||||
/// Presence progress: 0 absent, 1 present. Driven by the scene.
|
||||
pub const PRESENCE: Prop<f32> = Prop::builtin(10, PropClass::Presence);
|
||||
/// Screen-space travel progress (x, y) for matched geometry and `Travel::Screen`. A
|
||||
/// fraction of the path, so it settles like a scale: a point-sized threshold would end a
|
||||
/// long flight a few points short and snap.
|
||||
pub const TRAVEL: Prop<Vec2> = Prop::builtin(11, PropClass::Scale);
|
||||
|
||||
/// Number of built-in property ids (the scene caches these per node).
|
||||
pub const BUILTIN_COUNT: usize = 12;
|
||||
}
|
||||
+522
@@ -0,0 +1,522 @@
|
||||
//! The presented tree the render thread owns: presence (exits that stay mounted), layout animation
|
||||
//! by edges, screen-space travel, matched geometry, and the per-frame [`Presented`] output.
|
||||
|
||||
use crate::carry::Carry;
|
||||
use crate::curve::{Anim, Curve};
|
||||
use crate::props::{NodeId, Prop, PropId, prop};
|
||||
use crate::snap::snap_rect;
|
||||
use crate::spring::{Spring, SpringPair};
|
||||
use crate::store::{AnimationStore, FxMap, MotionEvent, TrackId};
|
||||
use crate::trace::{Intent, MotionTrace, flags};
|
||||
use crate::transition::{Effect, Reveal, Transition};
|
||||
use crate::value::{Animatable, Color, Corners, MAX_LANES, Rect, Sides, Transform, Vec2, lanes};
|
||||
|
||||
mod frame;
|
||||
mod layout;
|
||||
mod phase;
|
||||
mod presence;
|
||||
mod props;
|
||||
mod trailing;
|
||||
mod travel;
|
||||
|
||||
use layout::D;
|
||||
use phase::{Act, Event as PhaseEvent, Presence, lerp_fx};
|
||||
|
||||
const NONE: u32 = u32::MAX;
|
||||
const B: usize = prop::BUILTIN_COUNT;
|
||||
|
||||
/// Width-leads ratio for the X axis spring (native morph: `width_vd = 0.78 · vd`).
|
||||
pub const WIDTH_LEAD: f32 = 0.78;
|
||||
|
||||
/// Where a node is in its life.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
Entering,
|
||||
Present,
|
||||
/// Removed by the app; still drawn until its exit settles. `generation` guards against stale exits.
|
||||
Exiting { generation: u32 },
|
||||
}
|
||||
|
||||
/// Whether an insert is part of the first build (no animation, Kit rule 6) or a later change.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mount {
|
||||
Initial,
|
||||
Animated,
|
||||
}
|
||||
|
||||
/// The coordinate space layout motion is tracked in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Travel {
|
||||
/// Edges animate in parent space; an unchanged child rides its parent.
|
||||
#[default]
|
||||
Parent,
|
||||
/// The node travels one straight screen-space path from where it was seen to where it lands,
|
||||
/// whatever its ancestors do (Kit rule 12). Interpolates start and end root-space rects with
|
||||
/// one progress per axis.
|
||||
Screen,
|
||||
}
|
||||
|
||||
/// How a frame change animates: per-axis curves, directional edge lead, and travel space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct LayoutAnim {
|
||||
pub x: Anim,
|
||||
pub y: Anim,
|
||||
pub lead: Option<(Anim, Anim)>,
|
||||
pub travel: Travel,
|
||||
}
|
||||
|
||||
impl LayoutAnim {
|
||||
pub fn new(anim: impl Into<Anim>) -> LayoutAnim {
|
||||
let a = anim.into();
|
||||
LayoutAnim { x: a, y: a, lead: None, travel: Travel::Parent }
|
||||
}
|
||||
pub fn axes(x: impl Into<Anim>, y: impl Into<Anim>) -> LayoutAnim {
|
||||
LayoutAnim { x: x.into(), y: y.into(), lead: None, travel: Travel::Parent }
|
||||
}
|
||||
/// The X axis springs faster (duration × 0.78), so a widening surface fits its content first
|
||||
/// (Kit rule 9: "the width should animate much faster").
|
||||
pub fn width_leads(mut self) -> LayoutAnim {
|
||||
if let Curve::Spring(s) = self.x.curve {
|
||||
self.x.curve = Curve::Spring(s.with_duration(s.duration * WIDTH_LEAD));
|
||||
}
|
||||
self
|
||||
}
|
||||
/// When an axis travels, its leading edge in the direction of travel uses `lead` and its
|
||||
/// trailing edge uses `trail` (width leads along the travel direction).
|
||||
pub fn lead(mut self, lead: impl Into<Anim>, trail: impl Into<Anim>) -> LayoutAnim {
|
||||
self.lead = Some((lead.into(), trail.into()));
|
||||
self
|
||||
}
|
||||
pub fn screen(mut self) -> LayoutAnim {
|
||||
self.travel = Travel::Screen;
|
||||
self
|
||||
}
|
||||
pub const INSTANT: LayoutAnim =
|
||||
LayoutAnim { x: Anim::INSTANT, y: Anim::INSTANT, lead: None, travel: Travel::Parent };
|
||||
}
|
||||
|
||||
impl From<Spring> for LayoutAnim {
|
||||
fn from(s: Spring) -> Self {
|
||||
LayoutAnim::new(s)
|
||||
}
|
||||
}
|
||||
impl From<Anim> for LayoutAnim {
|
||||
fn from(a: Anim) -> Self {
|
||||
LayoutAnim::new(a)
|
||||
}
|
||||
}
|
||||
impl From<SpringPair> for LayoutAnim {
|
||||
fn from(p: SpringPair) -> Self {
|
||||
LayoutAnim::new(p.enter)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app side sends when a keyed node appears.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct NodeSpec {
|
||||
pub parent: Option<NodeId>,
|
||||
/// Layout frame in parent space, at the target state.
|
||||
pub frame: Rect,
|
||||
pub opacity: f32,
|
||||
pub radius: Corners,
|
||||
pub fill: Color,
|
||||
pub transition: Transition,
|
||||
}
|
||||
|
||||
impl NodeSpec {
|
||||
pub fn new(frame: Rect) -> NodeSpec {
|
||||
NodeSpec {
|
||||
parent: None,
|
||||
frame,
|
||||
opacity: 1.0,
|
||||
radius: Corners::ZERO,
|
||||
fill: Color::TRANSPARENT,
|
||||
transition: Transition::opacity(),
|
||||
}
|
||||
}
|
||||
pub fn parent(mut self, parent: NodeId) -> Self {
|
||||
self.parent = Some(parent);
|
||||
self
|
||||
}
|
||||
pub fn opacity(mut self, o: f32) -> Self {
|
||||
self.opacity = o;
|
||||
self
|
||||
}
|
||||
pub fn radius(mut self, r: impl Into<Corners>) -> Self {
|
||||
self.radius = r.into();
|
||||
self
|
||||
}
|
||||
pub fn fill(mut self, c: Color) -> Self {
|
||||
self.fill = c;
|
||||
self
|
||||
}
|
||||
pub fn transition(mut self, t: Transition) -> Self {
|
||||
self.transition = t;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f32> for Corners {
|
||||
fn from(r: f32) -> Corners {
|
||||
Corners::all(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// A soft clip in the node's own coordinates: how far each side is pulled in, and how wide the
|
||||
/// gradient ramp on that side is. The renderer evaluates it as an SDF ramp (Kit rule 11).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Mask {
|
||||
pub inset: Sides,
|
||||
pub feather: Sides,
|
||||
}
|
||||
|
||||
impl Mask {
|
||||
pub fn is_none(&self) -> bool {
|
||||
self.inset == Sides::ZERO && self.feather == Sides::ZERO
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the renderer needs to draw one node this frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Presented {
|
||||
pub node: NodeId,
|
||||
pub parent: Option<NodeId>,
|
||||
/// Root-space rect including every ancestor's (and this node's) translation, both edges
|
||||
/// snapped to 1/64 device px. Shapes, borders and shadows are drawn at this size.
|
||||
pub rect: Rect,
|
||||
/// This node's own opacity (presence × property). Ancestors apply theirs as group opacity.
|
||||
pub opacity: f32,
|
||||
/// Scale and rotation about `anchor` (translation is already in `rect`). Ancestors' scale and
|
||||
/// rotation compose down the tree, like `CALayer`.
|
||||
pub transform: Transform,
|
||||
/// Root-space pivot for `transform`.
|
||||
pub anchor: Vec2,
|
||||
/// Own plus presence Gaussian blur sigma in points. Zero means "attach no filter".
|
||||
pub blur: f32,
|
||||
pub radius: Corners,
|
||||
pub fill: Color,
|
||||
pub mask: Mask,
|
||||
pub phase: Phase,
|
||||
/// False while exiting with `pop_layout`: the app's layout should no longer reserve space.
|
||||
pub in_flow: bool,
|
||||
/// motion-lint flags (animated, ancestorAnimated, clipped, filtered) and intent bits
|
||||
/// (own `<< 8`, ancestor `<< 16`).
|
||||
pub flags: u32,
|
||||
/// How much of this node's own shape is drawn, 0 to 1 ([`crate::Transition::draw`]).
|
||||
pub draw: f32,
|
||||
}
|
||||
|
||||
impl Presented {
|
||||
/// The 2×3 affine for `transform` about `anchor`.
|
||||
pub fn affine(&self) -> [f32; 6] {
|
||||
self.transform.to_affine(self.anchor)
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame's output.
|
||||
pub struct FrameOutput<'a> {
|
||||
/// Nodes whose presented values changed, parents before children.
|
||||
pub changed: &'a [Presented],
|
||||
/// Nodes whose exit settled this frame: draw nothing for them from now on.
|
||||
pub exited: &'a [NodeId],
|
||||
pub events: &'a [MotionEvent],
|
||||
/// Anything still moving? If not, the display link can pause.
|
||||
pub animating: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Path {
|
||||
start: Rect,
|
||||
end_local: Rect,
|
||||
/// Its parent's root-space target origin as the last frame drew it.
|
||||
origin: Vec2,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Node {
|
||||
id: NodeId,
|
||||
parent: u32,
|
||||
first_child: u32,
|
||||
last_child: u32,
|
||||
next_sibling: u32,
|
||||
prev_sibling: u32,
|
||||
alive: bool,
|
||||
frame: Rect,
|
||||
opacity: f32,
|
||||
radius: Corners,
|
||||
fill: Color,
|
||||
transition: Transition,
|
||||
presence: Presence,
|
||||
/// How many exits this node has been through, reported with an exiting phase.
|
||||
generation: u32,
|
||||
/// Pivot for the presented transform. Set by the effect each phase entered from, and kept:
|
||||
/// a removal that scales moves it, and a static node still reports it.
|
||||
anchor: Vec2,
|
||||
/// Soft clip a reveal hides behind, or none. Kept across phases for the same reason.
|
||||
reveal: Option<Reveal>,
|
||||
path: Option<Path>,
|
||||
/// `set_ride_trailing`: x is kept against the parent's trailing edge while its width moves.
|
||||
ride_trailing: bool,
|
||||
tracks: [Option<TrackId>; B],
|
||||
dirty: bool,
|
||||
/// Root-space layout rect this frame (unsnapped) and the origin children ride (with offsets).
|
||||
world: Rect,
|
||||
origin: Vec2,
|
||||
last: Option<Presented>,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Moves this node's presence one event on, and asks for what the scene should do about it.
|
||||
fn phase_step(&mut self, event: PhaseEvent) -> phase::Acts {
|
||||
phase::step(&mut self.presence, &mut self.generation, event)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a node comes to rest (see [`Scene::rest`]), beside `Scene::nodes` so the nodes the
|
||||
/// renderer reads every frame stay the same size.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Rest {
|
||||
/// Root-space presented rect with every track at its target, and the origin children rest on.
|
||||
rect: Rect,
|
||||
origin: Vec2,
|
||||
/// `rect` differs from where the node is this frame.
|
||||
moving: bool,
|
||||
}
|
||||
|
||||
const REST_ZERO: Rest = Rest { rect: Rect::ZERO, origin: Vec2::ZERO, moving: false };
|
||||
|
||||
/// The render thread's animated tree.
|
||||
pub struct Scene {
|
||||
store: AnimationStore,
|
||||
nodes: Vec<Node>,
|
||||
rests: Vec<Rest>,
|
||||
free: Vec<u32>,
|
||||
index: FxMap<u64, u32>,
|
||||
root_head: u32,
|
||||
root_tail: u32,
|
||||
order: Vec<u32>,
|
||||
order_dirty: bool,
|
||||
out: Vec<Presented>,
|
||||
/// What [`Scene::present`] presented after the motion trace wrote its frame, for the next.
|
||||
late: Vec<Presented>,
|
||||
exited: Carry<NodeId>,
|
||||
to_remove: Vec<u32>,
|
||||
/// Who is on a screen path, in the order the paths started. It only says who travels and in
|
||||
/// what order; the path itself is the node's.
|
||||
travelling: Vec<u32>,
|
||||
trace: Option<MotionTrace>,
|
||||
intents: Vec<(NodeId, u32, f32)>,
|
||||
/// `keep_flights`: landings leave motion already on its way to the same value.
|
||||
keep: bool,
|
||||
}
|
||||
|
||||
impl Default for Scene {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
pub fn new() -> Scene {
|
||||
Scene {
|
||||
store: AnimationStore::new(),
|
||||
nodes: Vec::new(),
|
||||
rests: Vec::new(),
|
||||
free: Vec::new(),
|
||||
index: FxMap::default(),
|
||||
root_head: NONE,
|
||||
root_tail: NONE,
|
||||
order: Vec::new(),
|
||||
order_dirty: false,
|
||||
out: Vec::new(),
|
||||
late: Vec::new(),
|
||||
exited: Carry::new(),
|
||||
to_remove: Vec::new(),
|
||||
travelling: Vec::new(),
|
||||
trace: None,
|
||||
intents: Vec::new(),
|
||||
keep: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// While on, landing a property ([`Scene::set`], or [`Scene::set_frame`] with
|
||||
/// [`LayoutAnim::INSTANT`]) on the value it's already moving to leaves that motion running:
|
||||
/// an instant change lands what it changes, not what an earlier change set going. Off, a
|
||||
/// landing ends any motion, as settling needs.
|
||||
pub fn keep_flights(&mut self, on: bool) {
|
||||
self.keep = on;
|
||||
}
|
||||
|
||||
/// `prop` is moving and its target is `value`, so a landing under `keep_flights` leaves it.
|
||||
fn in_flight_to<T: Animatable>(&self, id: NodeId, prop: Prop<T>, value: T) -> bool {
|
||||
if !self.keep || !self.store.is_animating(id, prop) {
|
||||
return false;
|
||||
}
|
||||
let Some(to) = self.store.target(id, prop) else { return false };
|
||||
let (mut a, mut b) = ([0.0; MAX_LANES], [0.0; MAX_LANES]);
|
||||
to.write_lanes(&mut a[..T::LANES]);
|
||||
value.write_lanes(&mut b[..T::LANES]);
|
||||
a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 1e-3)
|
||||
}
|
||||
|
||||
pub fn store(&self) -> &AnimationStore {
|
||||
&self.store
|
||||
}
|
||||
/// For choreography and custom properties. Tracks of scene nodes are picked up automatically.
|
||||
pub fn store_mut(&mut self) -> &mut AnimationStore {
|
||||
&mut self.store
|
||||
}
|
||||
|
||||
pub fn set_time(&mut self, t: f64) {
|
||||
self.store.set_time(t);
|
||||
}
|
||||
/// Runs the node's animations at `scale` times the scene's speed; see
|
||||
/// [`AnimationStore::set_node_time_scale`].
|
||||
pub fn set_time_scale(&mut self, id: NodeId, scale: f32) {
|
||||
self.store.set_node_time_scale(id, scale);
|
||||
}
|
||||
pub fn now(&self) -> f64 {
|
||||
self.store.now()
|
||||
}
|
||||
pub fn set_pixel_scale(&mut self, s: f32) {
|
||||
let previous = self.store.pixel_scale();
|
||||
self.store.set_pixel_scale(s);
|
||||
if self.store.pixel_scale() != previous {
|
||||
for node in self.nodes.iter_mut().filter(|n| n.alive) { node.dirty = true; }
|
||||
}
|
||||
}
|
||||
pub fn set_reduced_motion(&mut self, on: bool) {
|
||||
self.store.set_reduced_motion(on);
|
||||
for n in self.nodes.iter_mut().filter(|n| n.alive) {
|
||||
n.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Records every frame as motion-lint JSONL.
|
||||
pub fn set_trace(&mut self, trace: Option<MotionTrace>) {
|
||||
self.trace = trace;
|
||||
for node in self.nodes.iter_mut().filter(|n| n.alive) { node.dirty = true; }
|
||||
}
|
||||
pub fn tracing(&self) -> bool { self.trace.is_some() }
|
||||
pub fn trace_mut(&mut self) -> Option<&mut MotionTrace> { self.trace.as_mut() }
|
||||
/// Updates metadata even if the node's geometry has not changed.
|
||||
pub fn trace_name(&mut self, id: NodeId, name: Option<&'static str>) {
|
||||
if self.trace.as_mut().is_some_and(|trace| trace.name(id, name)) {
|
||||
if let Some(i) = self.slot(id) { self.nodes[i].dirty = true; }
|
||||
}
|
||||
}
|
||||
pub fn trace_namespace(&mut self, id: NodeId, namespace: Option<(&'static str, &'static str)>) {
|
||||
if self.trace.as_mut().is_some_and(|trace| trace.namespace(id, namespace)) {
|
||||
if let Some(i) = self.slot(id) { self.nodes[i].dirty = true; }
|
||||
}
|
||||
}
|
||||
pub fn take_trace(&mut self) -> Option<MotionTrace> {
|
||||
self.trace.take()
|
||||
}
|
||||
|
||||
pub fn contains(&self, id: NodeId) -> bool {
|
||||
self.index.contains_key(&id.0)
|
||||
}
|
||||
pub fn phase(&self, id: NodeId) -> Option<Phase> {
|
||||
let i = self.slot(id)?;
|
||||
Some(self.nodes[i].presence.public(self.nodes[i].generation))
|
||||
}
|
||||
/// The last presented snapshot (hit-test against what the user sees). Not tracked.
|
||||
pub fn presented(&self, id: NodeId) -> Option<Presented> {
|
||||
self.slot(id).and_then(|i| self.nodes[i].last)
|
||||
}
|
||||
/// The rect the node comes to rest at once every track (its own and its ancestors') reaches
|
||||
/// its target, snapped like [`Presented::rect`], while that differs from where it is: the
|
||||
/// difference from [`presented`](Self::presented) is the motion still in flight. Only a
|
||||
/// node whose [`Presented::flags`] has `ANIMATED` or `ANCESTOR_ANIMATED` can be moving.
|
||||
pub fn rest(&self, id: NodeId) -> Option<Rect> {
|
||||
let r = &self.rests[self.slot(id)?];
|
||||
r.moving.then(|| snap_rect(r.rect, self.store.pixel_scale()))
|
||||
}
|
||||
/// Root-space layout rect this frame (without this node's own offset or presence offset),
|
||||
/// snapped to the same 1/64 device-px grid as [`Presented::rect`].
|
||||
pub fn world(&self, id: NodeId) -> Option<Rect> {
|
||||
self.slot(id).map(|i| snap_rect(self.nodes[i].world, self.store.pixel_scale()))
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.index.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.index.is_empty()
|
||||
}
|
||||
|
||||
fn slot(&self, id: NodeId) -> Option<usize> {
|
||||
self.index.get(&id.0).map(|&i| i as usize)
|
||||
}
|
||||
|
||||
/// Lane values and velocities of track `t`, sampled exactly at `now()`.
|
||||
fn sample(&self, t: TrackId) -> Option<([f32; MAX_LANES], [f32; MAX_LANES])> {
|
||||
let mut x = [0.0; MAX_LANES];
|
||||
let mut v = [0.0; MAX_LANES];
|
||||
self.store.sample_exact(t, &mut x, &mut v).then_some((x, v))
|
||||
}
|
||||
|
||||
/// Unmounts a node and its subtree now (no exit), reporting them in `exited`.
|
||||
fn remove_now(&mut self, i: usize) {
|
||||
// Children first.
|
||||
let mut c = self.nodes[i].first_child;
|
||||
while c != NONE {
|
||||
let next = self.nodes[c as usize].next_sibling;
|
||||
self.remove_now(c as usize);
|
||||
c = next;
|
||||
}
|
||||
let id = self.nodes[i].id;
|
||||
// Unlink from the parent's (or root) child list.
|
||||
let parent = self.nodes[i].parent;
|
||||
let next = self.nodes[i].next_sibling;
|
||||
let prev = self.nodes[i].prev_sibling;
|
||||
if prev == NONE {
|
||||
if parent == NONE {
|
||||
self.root_head = next;
|
||||
} else {
|
||||
self.nodes[parent as usize].first_child = next;
|
||||
}
|
||||
} else {
|
||||
self.nodes[prev as usize].next_sibling = next;
|
||||
}
|
||||
if next == NONE {
|
||||
if parent == NONE { self.root_tail = prev; } else { self.nodes[parent as usize].last_child = prev; }
|
||||
} else {
|
||||
self.nodes[next as usize].prev_sibling = prev;
|
||||
}
|
||||
self.travelling.retain(|&x| x as usize != i);
|
||||
self.store.remove_node(id);
|
||||
self.index.remove(&id.0);
|
||||
let n = &mut self.nodes[i];
|
||||
n.alive = false;
|
||||
n.dirty = false;
|
||||
n.first_child = NONE;
|
||||
n.last_child = NONE;
|
||||
n.next_sibling = NONE;
|
||||
n.prev_sibling = NONE;
|
||||
n.last = None;
|
||||
self.free.push(i as u32);
|
||||
self.exited.push(id);
|
||||
self.order_dirty = true;
|
||||
}
|
||||
|
||||
fn rebuild_order(&mut self) {
|
||||
self.order.clear();
|
||||
let mut r = self.root_head;
|
||||
while r != NONE {
|
||||
self.order.push(r);
|
||||
r = self.nodes[r as usize].next_sibling;
|
||||
}
|
||||
let mut k = 0;
|
||||
while k < self.order.len() {
|
||||
let mut c = self.nodes[self.order[k] as usize].first_child;
|
||||
while c != NONE {
|
||||
self.order.push(c);
|
||||
c = self.nodes[c as usize].next_sibling;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
self.order_dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Per-frame stepping, presence retirement, screen-travel handoff, and [`Presented`] output.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Scene {
|
||||
/// `set_time(t)`, then [`frame`](Self::frame).
|
||||
pub fn frame_at(&mut self, t: f64) -> FrameOutput<'_> {
|
||||
self.set_time(t);
|
||||
self.frame()
|
||||
}
|
||||
|
||||
/// Samples every active track at `now()`, finishes exits, and returns the presented values of
|
||||
/// every node that changed. Apply this frame's commits (insert/remove/set_frame/animate)
|
||||
/// between `set_time` and `frame`.
|
||||
pub fn frame(&mut self) -> FrameOutput<'_> {
|
||||
self.store.tick();
|
||||
// Keep removals made since the last frame (matched geometry), drop last frame's.
|
||||
self.exited.begin();
|
||||
self.to_remove.clear();
|
||||
|
||||
// Presence settles: finish entrances, retire an exit that is still the node's own (a
|
||||
// node that revived and left again is a different exit, and its settle retires it then).
|
||||
for ev in self.store.events() {
|
||||
if let MotionEvent::Settled { node, prop: p, .. } = *ev {
|
||||
if p != prop::PRESENCE.id {
|
||||
continue;
|
||||
}
|
||||
let Some(&i) = self.index.get(&node.0) else { continue };
|
||||
let acts = self.nodes[i as usize].phase_step(PhaseEvent::Settle);
|
||||
for act in acts {
|
||||
if let Act::Retire = act {
|
||||
self.to_remove.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// An exit nobody can see is over. Presence settles at 1e-5, ~40 frames after the node
|
||||
// fades below one 8-bit step; retire it there so whatever waits on the unmount (focus,
|
||||
// hit-testing, the next layer) doesn't wait on an invisible tail.
|
||||
let mut retire = core::mem::take(&mut self.to_remove);
|
||||
for (t, node, p) in self.store.touched_tracks() {
|
||||
if p != prop::PRESENCE.id {
|
||||
continue;
|
||||
}
|
||||
let Some(&i) = self.index.get(&node.0) else { continue };
|
||||
if !self.nodes[i as usize].presence.exiting() || retire.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
let Some(&[presence, ..]) = self.store.values_of(t) else { continue };
|
||||
let acts = self.nodes[i as usize].phase_step(PhaseEvent::Faded { p: presence });
|
||||
for act in acts {
|
||||
if let Act::Retire = act {
|
||||
retire.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.to_remove = retire;
|
||||
// Mark what moved; refresh the track cache from the store.
|
||||
for (tid, node, p) in self.store.touched_tracks() {
|
||||
if let Some(&i) = self.index.get(&node.0) {
|
||||
let n = &mut self.nodes[i as usize];
|
||||
n.dirty = true;
|
||||
if (p.0 as usize) < B {
|
||||
n.tracks[p.0 as usize] = Some(tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Screen travel ends once it has arrived and no ancestor is still moving or transitioning.
|
||||
// `travelling` is the order the paths started in, not the tree's: a child whose path
|
||||
// started first is checked before its parent, as dev checked it.
|
||||
let mut k = 0;
|
||||
while k < self.travelling.len() {
|
||||
let i = self.travelling[k] as usize;
|
||||
let travel = self.nodes[i].tracks[prop::TRAVEL.id.0 as usize];
|
||||
let arrived = travel.is_none_or(|t| !self.store.is_active(t));
|
||||
if arrived && !self.ancestor_moving(i) {
|
||||
let end_local = self.nodes[i].path.map(|p| p.end_local).unwrap_or(self.nodes[i].frame);
|
||||
self.end_path(i);
|
||||
self.track_set(i, prop::FRAME, end_local);
|
||||
continue;
|
||||
}
|
||||
let po = self.parent_target_origin(i);
|
||||
if let Some(path) = &mut self.nodes[i].path {
|
||||
path.origin = po;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
if self.order_dirty {
|
||||
self.rebuild_order();
|
||||
}
|
||||
self.out.clear();
|
||||
// Written first, so this frame's own values for the same nodes win.
|
||||
self.out.append(&mut self.late);
|
||||
self.present_dirty();
|
||||
for k in 0..self.to_remove.len() {
|
||||
let i = self.to_remove[k] as usize;
|
||||
if self.nodes[i].alive {
|
||||
self.remove_now(i);
|
||||
}
|
||||
}
|
||||
self.exited.end();
|
||||
// A node still travelling waits on an active track of its own or an ancestor's, so this
|
||||
// covers it, and a frozen one doesn't keep the frames coming.
|
||||
let animating = self.store.running();
|
||||
if let Some(trace) = self.trace.as_mut() {
|
||||
trace.frame(self.store.now(), &self.out, self.exited.as_slice(), self.store.events(), &self.intents);
|
||||
self.intents.clear();
|
||||
}
|
||||
FrameOutput { changed: &self.out, exited: self.exited.as_slice(), events: self.store.events(), animating }
|
||||
}
|
||||
|
||||
/// What [`frame`](Self::frame) and any [`present`](Self::present) since presented.
|
||||
pub fn changed(&self) -> &[Presented] {
|
||||
&self.out
|
||||
}
|
||||
|
||||
/// Presents what was set or animated since [`frame`](Self::frame), without stepping time,
|
||||
/// so a value worked out from something that frame moved afterwards (a scroll offset)
|
||||
/// shows in the same frame. The motion trace, already written for that frame, records them
|
||||
/// with the next.
|
||||
pub fn present(&mut self) {
|
||||
if self.order_dirty {
|
||||
self.rebuild_order();
|
||||
}
|
||||
let from = self.out.len();
|
||||
self.present_dirty();
|
||||
if self.trace.is_some() {
|
||||
self.late.extend_from_slice(&self.out[from..]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Recomputes the presented values of dirty nodes and their subtrees, into `out`.
|
||||
fn present_dirty(&mut self) {
|
||||
let scale = self.store.pixel_scale();
|
||||
let reduced = self.store.reduced_motion();
|
||||
for k in 0..self.order.len() {
|
||||
let i = self.order[k] as usize;
|
||||
let parent = self.nodes[i].parent;
|
||||
let parent_dirty = parent != NONE && self.nodes[parent as usize].dirty;
|
||||
let own = self.nodes[i].dirty;
|
||||
if parent_dirty {
|
||||
self.nodes[i].dirty = true;
|
||||
}
|
||||
if self.nodes[i].dirty {
|
||||
let p = self.compute(i, scale, reduced, own, parent_dirty);
|
||||
self.nodes[i].last = Some(p);
|
||||
self.out.push(p);
|
||||
}
|
||||
}
|
||||
for k in 0..self.order.len() {
|
||||
let i = self.order[k] as usize;
|
||||
self.nodes[i].dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// An ancestor still moving or changing how it draws its subtree: a node ending screen travel
|
||||
/// under it would jump onto its mid-transition offset, scale, opacity or blur.
|
||||
fn ancestor_moving(&self, i: usize) -> bool {
|
||||
let mut p = self.nodes[i].parent;
|
||||
while p != NONE {
|
||||
let n = &self.nodes[p as usize];
|
||||
for prop in [prop::FRAME.id, prop::TRAVEL.id, prop::OFFSET.id, prop::PRESENCE.id, prop::SCALE.id, prop::OPACITY.id, prop::BLUR.id] {
|
||||
if n.tracks[prop.0 as usize].is_some_and(|t| self.store.is_active(t)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
p = n.parent;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn values(&self, i: usize, p: PropId) -> Option<&[f32]> {
|
||||
self.nodes[i].tracks[p.0 as usize].and_then(|t| self.store.values_of(t))
|
||||
}
|
||||
|
||||
fn targets<const N: usize>(&self, i: usize, p: PropId) -> Option<[f32; N]> {
|
||||
let mut out = [0.0; N];
|
||||
let t = self.nodes[i].tracks[p.0 as usize]?;
|
||||
self.store.targets_of(t, &mut out).then_some(out)
|
||||
}
|
||||
|
||||
/// Where `compute` would put node `i` with every track at its target. It repeats the same
|
||||
/// arithmetic so that, at rest, the two rects are bit-identical.
|
||||
fn rest_of(&self, i: usize, reduced: bool) -> Rect {
|
||||
let n = &self.nodes[i];
|
||||
let parent = n.parent;
|
||||
let world = match n.path {
|
||||
Some(path) => {
|
||||
let p = self.targets::<2>(i, prop::TRAVEL.id).unwrap_or([1.0, 1.0]);
|
||||
let s = path.start.edges();
|
||||
let e = path.end_local.translated(self.parent_target_origin(i)).edges();
|
||||
let ed: [f32; 4] = core::array::from_fn(|k| s[k] + (e[k] - s[k]) * p[k % 2]);
|
||||
Rect::from_edges(ed[0], ed[1], ed[2], ed[3])
|
||||
}
|
||||
None => {
|
||||
let origin = if parent == NONE { Vec2::ZERO } else { self.rests[parent as usize].origin };
|
||||
let local = self.targets::<4>(i, prop::FRAME.id).map_or(n.frame, |v| Rect::read_lanes(&v));
|
||||
local.translated(origin)
|
||||
}
|
||||
};
|
||||
let p = self.targets::<1>(i, prop::PRESENCE.id).map_or(1.0, |v| v[0]);
|
||||
let (at0, at1) = n.presence.pair();
|
||||
let s = lerp_fx(at0, at1, p);
|
||||
let s = if reduced { [s[0], 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] } else { s };
|
||||
let own = self.targets::<2>(i, prop::OFFSET.id).map_or(Vec2::ZERO, |v| Vec2::read_lanes(&v));
|
||||
world.translated(Vec2::new(own.x + s[2] + s[4] * world.w, own.y + s[3] + s[5] * world.h))
|
||||
}
|
||||
|
||||
fn compute(&mut self, i: usize, scale: f32, reduced: bool, own_dirty: bool, parent_dirty: bool) -> Presented {
|
||||
let parent = self.nodes[i].parent;
|
||||
let parent_origin = if parent == NONE { Vec2::ZERO } else { self.nodes[parent as usize].origin };
|
||||
let n = &self.nodes[i];
|
||||
let world = match n.path {
|
||||
Some(path) => {
|
||||
let p = self.values(i, prop::TRAVEL.id).map_or([1.0, 1.0], |v| [v[0], v[1]]);
|
||||
let s = path.start.edges();
|
||||
let e = path.end_local.translated(self.parent_target_origin(i)).edges();
|
||||
let ed: [f32; 4] = core::array::from_fn(|k| s[k] + (e[k] - s[k]) * p[k % 2]);
|
||||
Rect::from_edges(ed[0], ed[1], ed[2], ed[3])
|
||||
}
|
||||
None => {
|
||||
let local = self.values(i, prop::FRAME.id).map_or(n.frame, Rect::read_lanes);
|
||||
let mut world = local.translated(parent_origin);
|
||||
if n.ride_trailing && parent != NONE {
|
||||
let p = &self.nodes[parent as usize];
|
||||
world.x += p.world.w - p.frame.w;
|
||||
}
|
||||
world
|
||||
}
|
||||
};
|
||||
let p = self.values(i, prop::PRESENCE.id).map_or(1.0, |v| v[0]);
|
||||
let (at0, at1) = n.presence.pair();
|
||||
let s = lerp_fx(at0, at1, p);
|
||||
let s = if reduced { [s[0], 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] } else { s };
|
||||
let own_opacity = self.values(i, prop::OPACITY.id).map_or(n.opacity, |v| v[0]);
|
||||
let own_scale = self.values(i, prop::SCALE.id).map_or(1.0, |v| v[0]);
|
||||
let own_offset = self.values(i, prop::OFFSET.id).map_or(Vec2::ZERO, Vec2::read_lanes);
|
||||
let rotation = self.values(i, prop::ROTATION.id).map_or(0.0, |v| v[0]);
|
||||
let own_blur = self.values(i, prop::BLUR.id).map_or(0.0, |v| v[0]);
|
||||
let radius = self.values(i, prop::RADIUS.id).map_or(n.radius, Corners::read_lanes);
|
||||
let fill = self.values(i, prop::FILL.id).map_or(n.fill, Color::read_lanes);
|
||||
let own_mask = self.values(i, prop::MASK.id).map_or(Sides::ZERO, Sides::read_lanes);
|
||||
|
||||
let offset = Vec2::new(
|
||||
own_offset.x + s[2] + s[4] * world.w,
|
||||
own_offset.y + s[3] + s[5] * world.h,
|
||||
);
|
||||
let shown = world.translated(offset);
|
||||
let sc = (own_scale * s[1]).max(0.0);
|
||||
let mut blur = (own_blur + s[6]).max(0.0);
|
||||
if blur < 1.0 / 64.0 {
|
||||
blur = 0.0;
|
||||
}
|
||||
let mut mask = Mask { inset: own_mask, feather: Sides::ZERO };
|
||||
if let Some(rv) = n.reveal {
|
||||
let hidden = s[7].clamp(0.0, 1.0);
|
||||
if hidden > 0.0 {
|
||||
let (side, len) = match rv.edge {
|
||||
crate::Edge::Leading => (0, shown.w),
|
||||
crate::Edge::Top => (1, shown.h),
|
||||
crate::Edge::Trailing => (2, shown.w),
|
||||
crate::Edge::Bottom => (3, shown.h),
|
||||
};
|
||||
// The content is hidden behind `edge`: the opposite side's inset grows.
|
||||
let opposite = (side + 2) % 4;
|
||||
mask.inset.0[opposite] += hidden * len;
|
||||
// The ramp fades in with the wipe instead of popping (min(1, travel / feather)).
|
||||
mask.feather.0[opposite] = rv.feather * (hidden * len / rv.feather.max(1e-3)).min(1.0);
|
||||
}
|
||||
}
|
||||
let anchor = Vec2::new(shown.x + n.anchor.x * shown.w, shown.y + n.anchor.y * shown.h);
|
||||
let mut fl = 0u32;
|
||||
let mut own_bits = 0u32;
|
||||
for (k, t) in n.tracks.iter().enumerate() {
|
||||
if t.is_some_and(|t| self.store.is_active(t)) {
|
||||
own_bits |= Intent::for_prop(PropId(k as u16));
|
||||
}
|
||||
}
|
||||
if n.path.is_some() {
|
||||
own_bits |= Intent::POSITION | Intent::SIZE;
|
||||
}
|
||||
if own_bits != 0 || (own_dirty && !parent_dirty) {
|
||||
fl |= flags::ANIMATED;
|
||||
}
|
||||
if parent_dirty {
|
||||
fl |= flags::ANCESTOR_ANIMATED;
|
||||
let pb = self.nodes[parent as usize].last.map_or(0, |p| (p.flags >> 8) & 0xff | (p.flags >> 16) & 0xff);
|
||||
fl |= pb << 16;
|
||||
}
|
||||
fl |= own_bits << 8;
|
||||
if !mask.is_none() {
|
||||
fl |= flags::CLIPPED;
|
||||
}
|
||||
if blur > 0.0 {
|
||||
fl |= flags::FILTERED;
|
||||
}
|
||||
let in_flow = !n.presence.exiting() || !n.transition.pop_layout;
|
||||
let out = Presented {
|
||||
node: n.id,
|
||||
parent: (parent != NONE).then(|| self.nodes[parent as usize].id),
|
||||
rect: snap_rect(shown, scale),
|
||||
opacity: (own_opacity * s[0]).clamp(0.0, 1.0),
|
||||
transform: Transform { translate: Vec2::ZERO, scale: Vec2::new(sc, sc), rotate: rotation },
|
||||
anchor,
|
||||
blur,
|
||||
radius,
|
||||
fill,
|
||||
mask,
|
||||
phase: n.presence.public(n.generation),
|
||||
in_flow,
|
||||
flags: fl,
|
||||
draw: s[8].clamp(0.0, 1.0),
|
||||
};
|
||||
// Where it is is where it rests while nothing that places it is in flight. A node riding
|
||||
// its parent's trailing edge also moves with the parent's width.
|
||||
let still = !self.nodes[i].ride_trailing
|
||||
&& (parent == NONE || self.rests[parent as usize].origin == self.nodes[parent as usize].origin) && [prop::TRAVEL.id, prop::FRAME.id, prop::PRESENCE.id, prop::OFFSET.id]
|
||||
.iter()
|
||||
.all(|p| self.nodes[i].tracks[p.0 as usize].is_none_or(|t| self.store.is_settled(t)));
|
||||
let rest = if still { shown } else { self.rest_of(i, reduced) };
|
||||
let n = &mut self.nodes[i];
|
||||
n.world = world;
|
||||
n.origin = Vec2::new(shown.x, shown.y);
|
||||
self.rests[i] = Rest { rect: rest, origin: Vec2::new(rest.x, rest.y), moving: rest != shown };
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Layout frame animation and dual-number kinematics (exact root-space edges and velocities).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A small dual number: value and time derivative, for exact velocity of composed geometry.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(super) struct D {
|
||||
pub(super) x: f32,
|
||||
pub(super) v: f32,
|
||||
}
|
||||
impl D {
|
||||
pub(super) fn c(x: f32) -> D {
|
||||
D { x, v: 0.0 }
|
||||
}
|
||||
pub(super) fn add(self, o: D) -> D {
|
||||
D { x: self.x + o.x, v: self.v + o.v }
|
||||
}
|
||||
pub(super) fn sub(self, o: D) -> D {
|
||||
D { x: self.x - o.x, v: self.v - o.v }
|
||||
}
|
||||
pub(super) fn mul(self, o: D) -> D {
|
||||
D { x: self.x * o.x, v: self.v * o.x + self.x * o.v }
|
||||
}
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
/// The node's layout frame (parent space) changed. Each moving edge animates; a stationary
|
||||
/// edge gets no motion at all. With `Travel::Screen` the node takes one straight root-space
|
||||
/// path instead, whatever its ancestors do.
|
||||
pub fn set_frame(&mut self, id: NodeId, frame: Rect, anim: impl Into<LayoutAnim>) {
|
||||
self.set_frame_drawn(id, frame, anim.into(), [Vec2::ZERO; 2]);
|
||||
}
|
||||
|
||||
/// [`set_frame`](Self::set_frame) for a node drawn `drawn[0]` away from its scene rect,
|
||||
/// moving `drawn[1]` faster: a screen path starts there, at that speed.
|
||||
pub(super) fn set_frame_drawn(&mut self, id: NodeId, frame: Rect, anim: LayoutAnim, drawn: [Vec2; 2]) {
|
||||
let Some(i) = self.slot(id) else { return };
|
||||
let old = self.nodes[i].frame;
|
||||
if old == frame && self.nodes[i].path.is_none() && self.nodes[i].tracks[prop::FRAME.id.0 as usize].is_none() {
|
||||
return;
|
||||
}
|
||||
if frame.w != old.w {
|
||||
self.rebase_trailing(i, frame.w - old.w);
|
||||
}
|
||||
let had_path = self.nodes[i].path.is_some();
|
||||
// An explicit landing also cancels motion toward an unchanged target. Comparing only
|
||||
// target frames here used to leave a spring running after Runtime::settle_all().
|
||||
if anim == LayoutAnim::INSTANT && !had_path && self.in_flight_to(id, prop::FRAME, frame) {
|
||||
return;
|
||||
}
|
||||
if anim == LayoutAnim::INSTANT && (had_path || self.store.is_animating(id, prop::FRAME)) {
|
||||
self.end_path(i);
|
||||
self.nodes[i].frame = frame;
|
||||
self.track_set(i, prop::FRAME, frame);
|
||||
self.nodes[i].dirty = true;
|
||||
return;
|
||||
}
|
||||
if old == frame && !had_path {
|
||||
return;
|
||||
}
|
||||
let ms = match anim.x.curve {
|
||||
Curve::Spring(s) => s.duration,
|
||||
c => c.logical_duration(),
|
||||
};
|
||||
self.intent(id, Intent::POSITION | Intent::SIZE, ms);
|
||||
if anim.travel == Travel::Screen && !self.store.reduced_motion() {
|
||||
// A path restarts from where it was drawn: under the origin the last frame drew it
|
||||
// against, which an ancestor laid out elsewhere in this commit has already moved.
|
||||
let (mut start, mut vel) = match self.nodes[i].path {
|
||||
Some(path) => {
|
||||
let e = self.path_dual(i, path, path.origin);
|
||||
(e.map(|d| d.x), e.map(|d| d.v))
|
||||
}
|
||||
None => self.exact_world(i),
|
||||
};
|
||||
for k in 0..4 {
|
||||
let [offset, speed] = drawn.map(|v| if k % 2 == 0 { v.x } else { v.y });
|
||||
start[k] += offset;
|
||||
vel[k] += speed;
|
||||
}
|
||||
self.nodes[i].frame = frame;
|
||||
self.start_path(i, start, vel, anim);
|
||||
return;
|
||||
}
|
||||
if had_path {
|
||||
// Leave screen travel: continue in parent space from the exact current place.
|
||||
let (w, wv) = self.exact_world(i);
|
||||
let (mut po, mut pv) = self.parent_origin_exact(i);
|
||||
let trail = self.trail_dual(i);
|
||||
po.x += trail.x;
|
||||
pv.x += trail.v;
|
||||
let local = Rect::from_edges(w[0] - po.x, w[1] - po.y, w[2] - po.x, w[3] - po.y);
|
||||
let lv = [wv[0] - pv.x, wv[1] - pv.y, wv[2] - pv.x, wv[3] - pv.y];
|
||||
self.end_path(i);
|
||||
self.track_set(i, prop::FRAME, local);
|
||||
let t = self.nodes[i].tracks[prop::FRAME.id.0 as usize].unwrap();
|
||||
// Give the lanes their velocity, then retarget per axis.
|
||||
let tid = t.index_usize();
|
||||
self.store.animate_raw(tid, &local.edges(), Anim::new(Curve::Spring(Spring::SMOOTH)), Some(&lv));
|
||||
} else if self.nodes[i].tracks[prop::FRAME.id.0 as usize].is_none() {
|
||||
self.track_set(i, prop::FRAME, old);
|
||||
}
|
||||
self.nodes[i].frame = frame;
|
||||
let t = self.nodes[i].tracks[prop::FRAME.id.0 as usize].unwrap().index_usize();
|
||||
let mut cur = self.store.lane_targets_4(t);
|
||||
let e = frame.edges();
|
||||
if let Some((lead, trail)) = anim.lead {
|
||||
for axis in 0..2 {
|
||||
let (a, b) = (axis, axis + 2);
|
||||
let (sa, sb) = if e[a] + e[b] > cur[a] + cur[b] { (trail, lead) } else { (lead, trail) };
|
||||
let mut tg = cur;
|
||||
tg[a] = e[a];
|
||||
self.store.animate_raw(t, &tg, sa, None);
|
||||
cur[a] = e[a];
|
||||
let mut tg = cur;
|
||||
tg[b] = e[b];
|
||||
self.store.animate_raw(t, &tg, sb, None);
|
||||
cur[b] = e[b];
|
||||
}
|
||||
} else {
|
||||
// X edges on the X curve, Y edges on the Y curve; unchanged lanes are skipped.
|
||||
self.store.animate_raw(t, &[e[0], cur[1], e[2], cur[3]], anim.x, None);
|
||||
self.store.animate_raw(t, &e, anim.y, None);
|
||||
}
|
||||
self.nodes[i].dirty = true;
|
||||
}
|
||||
|
||||
pub(super) fn parent_target_origin(&self, i: usize) -> Vec2 {
|
||||
let mut o = Vec2::ZERO;
|
||||
let mut p = self.nodes[i].parent;
|
||||
while p != NONE {
|
||||
let f = self.nodes[p as usize].frame;
|
||||
o.x += f.x;
|
||||
o.y += f.y;
|
||||
p = self.nodes[p as usize].parent;
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Root-space layout edges of node `i` at `now()`, with velocities, sampled exactly.
|
||||
pub(super) fn exact_world(&self, i: usize) -> ([f32; 4], [f32; 4]) {
|
||||
let e = self.world_dual(i);
|
||||
(e.map(|d| d.x), e.map(|d| d.v))
|
||||
}
|
||||
|
||||
/// Trace-only check of presented scene edges against unsnapped analytic tracks at `now`.
|
||||
/// Returns (edge samples, maximum device-pixel error). Renderer-owned growth/scroll and
|
||||
/// post-layout scale transforms are outside this metric.
|
||||
pub fn sampling_error(&self) -> (usize, f32) {
|
||||
let mut count = 0;
|
||||
let mut error = 0.0f32;
|
||||
for &slot in &self.order {
|
||||
let i = slot as usize;
|
||||
let Some(p) = self.nodes[i].last else { continue };
|
||||
if !self.nodes[i].alive { continue; }
|
||||
let w = self.world_dual(i);
|
||||
let o = self.origin_dual(i);
|
||||
let ideal = [o[0].x, o[1].x, o[0].x + w[2].x - w[0].x, o[1].x + w[3].x - w[1].x];
|
||||
for (shown, exact) in p.rect.edges().into_iter().zip(ideal) {
|
||||
error = error.max((shown - exact).abs() * self.store.pixel_scale());
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
(count, error)
|
||||
}
|
||||
|
||||
fn parent_origin_exact(&self, i: usize) -> (Vec2, Vec2) {
|
||||
let p = self.nodes[i].parent;
|
||||
if p == NONE {
|
||||
return (Vec2::ZERO, Vec2::ZERO);
|
||||
}
|
||||
let o = self.origin_dual(p as usize);
|
||||
(Vec2::new(o[0].x, o[1].x), Vec2::new(o[0].v, o[1].v))
|
||||
}
|
||||
|
||||
/// Overwrites `out` with the property's exact lanes, if its track has a sample.
|
||||
pub(super) fn lanes_dual(&self, i: usize, p: PropId, out: &mut [D]) {
|
||||
let Some((x, v)) = self.nodes[i].tracks[p.0 as usize].and_then(|t| self.sample(t)) else { return };
|
||||
for (k, o) in out.iter_mut().enumerate() {
|
||||
*o = D { x: x[k], v: v[k] };
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn world_dual(&self, i: usize) -> [D; 4] {
|
||||
let n = &self.nodes[i];
|
||||
if let Some(path) = n.path {
|
||||
return self.path_dual(i, path, self.parent_target_origin(i));
|
||||
}
|
||||
self.laid_dual(i)
|
||||
}
|
||||
|
||||
/// Where node `i` is on its screen path, ending at its layout under parent origin `origin`.
|
||||
pub(super) fn path_dual(&self, i: usize, path: Path, origin: Vec2) -> [D; 4] {
|
||||
let mut p = [D::c(1.0); 2];
|
||||
self.lanes_dual(i, prop::TRAVEL.id, &mut p);
|
||||
let s = path.start.edges();
|
||||
let end = path.end_local.translated(origin).edges();
|
||||
core::array::from_fn(|k| D::c(s[k]).add(D::c(end[k] - s[k]).mul(p[k % 2])))
|
||||
}
|
||||
|
||||
/// The origin children of `i` ride: layout origin plus offsets (own and presence).
|
||||
pub(super) fn origin_dual(&self, i: usize) -> [D; 2] {
|
||||
let w = self.world_dual(i);
|
||||
let mut off = [D::c(0.0); 2];
|
||||
self.lanes_dual(i, prop::OFFSET.id, &mut off);
|
||||
let mut p = [D::c(1.0)];
|
||||
self.lanes_dual(i, prop::PRESENCE.id, &mut p);
|
||||
let n = &self.nodes[i];
|
||||
let (at0, at1) = n.presence.pair();
|
||||
let fx = |k: usize| D::c(at0[k]).mul(D::c(1.0).sub(p[0])).add(D::c(at1[k]).mul(p[0]));
|
||||
let size = [w[2].sub(w[0]), w[3].sub(w[1])];
|
||||
let reduced = self.store.reduced_motion();
|
||||
core::array::from_fn(|a| {
|
||||
let mut o = w[a].add(off[a]);
|
||||
if !reduced {
|
||||
o = o.add(fx(2 + a)).add(fx(4 + a).mul(size[a]));
|
||||
}
|
||||
o
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Where a node is in its life: present, entering, or exiting, with the two looks its presence
|
||||
//! blends between. Each variant carries its own effect data, so a node can't be, say, exiting
|
||||
//! while an entrance's look is still installed beside it.
|
||||
//!
|
||||
//! [`step`] moves the phase and returns what the scene should do, in order, instead of doing it.
|
||||
//! The scene carries the acts out (`presence::Scene::apply`), so a phase change is plain data in
|
||||
//! and out, and the one place that reads the effect pair can't disagree with the one that writes
|
||||
//! it.
|
||||
//!
|
||||
//! This crate doesn't depend on rune, so the effects list here is its own small one.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Effect lanes: opacity, scale, offset x/y, size-fraction offset x/y, blur, hidden reveal,
|
||||
/// drawn shape (dev's `fx_a`/`fx_b`).
|
||||
pub(super) type Fx = [f32; 9];
|
||||
pub(super) const FX_ID: Fx = [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0];
|
||||
|
||||
pub(super) fn fx_of(e: &Effect) -> Fx {
|
||||
let hidden = if e.reveal.is_some() { 1.0 } else { 0.0 };
|
||||
[e.opacity, e.scale, e.offset.x, e.offset.y, e.offset_fraction.x, e.offset_fraction.y, e.blur, hidden, e.draw]
|
||||
}
|
||||
|
||||
/// Exact at both ends: `a` at p = 0, `b` at p = 1.
|
||||
pub(super) fn lerp_fx(a: &Fx, b: &Fx, p: f32) -> Fx {
|
||||
core::array::from_fn(|k| a[k] * (1.0 - p) + b[k] * p)
|
||||
}
|
||||
|
||||
/// Where a node is in its life, with the looks its presence blends between: `at0` at presence 0
|
||||
/// (absent) and `at1` at presence 1 (present).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) enum Presence {
|
||||
/// On screen. `at0` is the look it arrived from, still blended in by the presence tail a
|
||||
/// settled entrance leaves behind.
|
||||
Present { at0: Fx, at1: Fx },
|
||||
/// Entering: drawn at `at0` at presence 0, arriving at `at1` at presence 1.
|
||||
Entering { at0: Fx, at1: Fx },
|
||||
/// Removed and still drawn until its presence settles: leaving `at1` for `at0`.
|
||||
Exiting { at0: Fx, at1: Fx },
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
/// A node that has not entered yet: the placeholder a new node is built with, before its
|
||||
/// first [`step`].
|
||||
pub(super) const LANDED: Presence = Presence::Present { at0: FX_ID, at1: FX_ID };
|
||||
|
||||
/// The looks at presence 0 and at presence 1.
|
||||
pub(super) fn pair(&self) -> (&Fx, &Fx) {
|
||||
let (Presence::Present { at0, at1 }
|
||||
| Presence::Entering { at0, at1 }
|
||||
| Presence::Exiting { at0, at1 }) = self;
|
||||
(at0, at1)
|
||||
}
|
||||
|
||||
/// Both looks, by value.
|
||||
pub(super) fn looks(&self) -> (Fx, Fx) {
|
||||
(*self.pair().0, *self.pair().1)
|
||||
}
|
||||
|
||||
pub(super) fn entering(&self) -> bool {
|
||||
matches!(self, Presence::Entering { .. })
|
||||
}
|
||||
|
||||
pub(super) fn exiting(&self) -> bool {
|
||||
matches!(self, Presence::Exiting { .. })
|
||||
}
|
||||
|
||||
/// Entered and on screen: no entrance or exit in flight.
|
||||
pub(super) fn resting(&self) -> bool {
|
||||
matches!(self, Presence::Present { .. })
|
||||
}
|
||||
|
||||
/// The phase apps read, tagged with how many exits the node has had.
|
||||
pub(super) fn public(&self, generation: u32) -> Phase {
|
||||
match self {
|
||||
Presence::Present { .. } => Phase::Present,
|
||||
Presence::Entering { .. } => Phase::Entering,
|
||||
Presence::Exiting { .. } => Phase::Exiting { generation },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What asks a node's phase to change.
|
||||
pub(super) enum Event {
|
||||
/// A keyed node appears: entering from `ins` when `animate`, else landing present.
|
||||
Mount { ins: Effect, animate: bool, entrance: Anim },
|
||||
/// The app brought it back at presence `p` (a re-inserted key, or `reenter`).
|
||||
Revive { p: f32, ins: Effect, entrance: Anim },
|
||||
/// The app made it present at once, with its insertion look.
|
||||
Land { ins: Effect },
|
||||
/// The app started it fully present from somewhere else (a launch, matched geometry).
|
||||
Appear,
|
||||
/// The app made it enter in place from the look it already has (Reduce Motion's fade).
|
||||
FadeIn { entrance: Anim },
|
||||
/// The app removed it at presence `p`, leaving with `rem`.
|
||||
Exit { p: f32, rem: Effect, exit: Anim },
|
||||
/// Its presence reached its target: an entrance has arrived, an exit is over.
|
||||
Settle,
|
||||
/// How faded it is: `p` is its presence this frame, so an exit nobody can see is over.
|
||||
Faded { p: f32 },
|
||||
}
|
||||
|
||||
/// What a phase change asks the scene to do, in order.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) enum Act {
|
||||
/// Land the presence track on this value.
|
||||
Land(f32),
|
||||
/// Land it only when the node keeps no track and already shows this value.
|
||||
LandIfNeeded(f32),
|
||||
/// Make sure a presence track holds the node's current look before it runs.
|
||||
Ensure,
|
||||
/// Run the presence track to its target.
|
||||
Run { target: f32, anim: Anim },
|
||||
/// The node presents again.
|
||||
Dirty,
|
||||
/// Its transform pivots here (a removal that scales).
|
||||
Anchor(Vec2),
|
||||
/// What it hides behind while it leaves.
|
||||
Reveal(Option<Reveal>),
|
||||
/// Report it in this frame's `exited` and unmount it. `Scene::frame` carries this one out
|
||||
/// itself, as it collects the list.
|
||||
Retire,
|
||||
/// Unmount it now, with no exit to play. Nothing follows it.
|
||||
Unmount,
|
||||
/// Record a motion-trace intent.
|
||||
Intent { bits: u32, seconds: f32 },
|
||||
}
|
||||
|
||||
/// The acts a step asks for, in order. An exit asks for at most six, so they fit inline and
|
||||
/// nothing here allocates.
|
||||
pub(super) struct Acts {
|
||||
items: [Act; 6],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl Acts {
|
||||
fn none() -> Acts {
|
||||
Acts { items: [Act::Dirty; 6], len: 0 }
|
||||
}
|
||||
|
||||
fn push(&mut self, act: Act) {
|
||||
if let Some(slot) = self.items.get_mut(self.len) {
|
||||
*slot = act;
|
||||
self.len += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn extend<const N: usize>(&mut self, acts: [Act; N]) {
|
||||
for act in acts {
|
||||
self.push(act);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for Acts {
|
||||
type Item = Act;
|
||||
type IntoIter = core::iter::Take<core::array::IntoIter<Act, 6>>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.items.into_iter().take(self.len)
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves `state` one event on, bumping `generation` where a new exit begins, and returns what the
|
||||
/// scene should do about it.
|
||||
pub(super) fn step(state: &mut Presence, generation: &mut u32, event: Event) -> Acts {
|
||||
use Presence::{Entering, Exiting, Present};
|
||||
let mut acts = Acts::none();
|
||||
match event {
|
||||
Event::Mount { ins, animate, entrance } => {
|
||||
let look = fx_of(&ins);
|
||||
if animate {
|
||||
acts.extend([
|
||||
Act::Land(0.0),
|
||||
Act::Run { target: 1.0, anim: entrance },
|
||||
Act::Intent { bits: Intent::TRANSITION | Intent::OPACITY, seconds: entrance.curve.logical_duration() },
|
||||
]);
|
||||
*state = Entering { at0: look, at1: FX_ID };
|
||||
} else {
|
||||
acts.push(Act::LandIfNeeded(1.0));
|
||||
*state = Present { at0: look, at1: FX_ID };
|
||||
}
|
||||
}
|
||||
Event::Revive { p, ins, entrance } => {
|
||||
let (old0, old1) = state.looks();
|
||||
// Keep the current look at p, land exactly on identity at 1. The last lane (drawn
|
||||
// shape) is kept as it was, as an entrance never re-solves it.
|
||||
let mut at0 = old0;
|
||||
if p <= 0.001 {
|
||||
at0 = fx_of(&ins);
|
||||
} else {
|
||||
let cur = lerp_fx(&old0, &old1, p);
|
||||
let q = (1.0 - p).max(1e-3);
|
||||
for k in 0..8 {
|
||||
at0[k] = (cur[k] - FX_ID[k] * p) / q;
|
||||
}
|
||||
}
|
||||
*generation += 1;
|
||||
*state = Entering { at0, at1: FX_ID };
|
||||
acts.extend([
|
||||
Act::Dirty,
|
||||
Act::Run { target: 1.0, anim: entrance },
|
||||
Act::Intent { bits: Intent::TRANSITION | Intent::OPACITY, seconds: entrance.curve.logical_duration() },
|
||||
]);
|
||||
}
|
||||
Event::Land { ins } => {
|
||||
*generation += 1;
|
||||
*state = Present { at0: fx_of(&ins), at1: FX_ID };
|
||||
acts.extend([Act::Anchor(ins.anchor), Act::Reveal(ins.reveal), Act::Land(1.0)]);
|
||||
}
|
||||
Event::Appear => {
|
||||
// Fully present, no presence effect. Only the absent look is replaced: an exit that
|
||||
// was under way keeps the look it was leaving from.
|
||||
let at1 = state.looks().1;
|
||||
*state = Present { at0: FX_ID, at1 };
|
||||
acts.push(Act::Land(1.0));
|
||||
}
|
||||
Event::FadeIn { entrance } => {
|
||||
let (at0, at1) = state.looks();
|
||||
*state = Entering { at0, at1 };
|
||||
acts.extend([Act::Land(0.0), Act::Run { target: 1.0, anim: entrance }]);
|
||||
}
|
||||
Event::Exit { p, rem, exit } => {
|
||||
if state.exiting() {
|
||||
return acts;
|
||||
}
|
||||
let (old0, old1) = state.looks();
|
||||
let unplayed = p < 1e-3;
|
||||
if unplayed && lerp_fx(&old0, &old1, p)[0] < 1.0 / 512.0 {
|
||||
// An entrance that hasn't shown anything yet (a delayed one still waiting) has
|
||||
// no exit to play.
|
||||
acts.push(Act::Unmount);
|
||||
return acts;
|
||||
}
|
||||
let target = fx_of(&rem);
|
||||
let mut at1 = old1;
|
||||
if p >= 0.999 {
|
||||
at1 = FX_ID;
|
||||
} else if unplayed {
|
||||
// None of the entrance has played, but its insertion effect shows: leave from
|
||||
// there, as a whole exit from it.
|
||||
at1 = lerp_fx(&old0, &old1, p);
|
||||
} else {
|
||||
// Mid-entrance: keep the current look at p, land exactly on the removal effect
|
||||
// at 0. The last lane (drawn shape) stays as it was.
|
||||
let cur = lerp_fx(&old0, &old1, p);
|
||||
for k in 0..8 {
|
||||
at1[k] = target[k] + (cur[k] - target[k]) / p.max(1e-3);
|
||||
}
|
||||
}
|
||||
*generation += 1;
|
||||
*state = Exiting { at0: target, at1 };
|
||||
if rem.scale != 1.0 {
|
||||
acts.push(Act::Anchor(rem.anchor));
|
||||
}
|
||||
if rem.reveal.is_some() {
|
||||
acts.push(Act::Reveal(rem.reveal));
|
||||
}
|
||||
acts.push(Act::Dirty);
|
||||
if unplayed {
|
||||
acts.push(Act::Land(1.0));
|
||||
} else {
|
||||
acts.push(Act::Ensure);
|
||||
}
|
||||
acts.extend([
|
||||
Act::Run { target: 0.0, anim: exit },
|
||||
Act::Intent { bits: Intent::TRANSITION | Intent::OPACITY, seconds: exit.curve.logical_duration() },
|
||||
]);
|
||||
}
|
||||
Event::Settle => match state {
|
||||
Present { .. } => {}
|
||||
Entering { at0, at1 } => *state = Present { at0: *at0, at1: *at1 },
|
||||
Exiting { .. } => acts.push(Act::Retire),
|
||||
},
|
||||
Event::Faded { p } => {
|
||||
// An exit nobody can see is over: presence has faded below one 8-bit step.
|
||||
if state.exiting() {
|
||||
let (at0, at1) = state.pair();
|
||||
if at0[0] + (at1[0] - at0[0]) * p < 1.0 / 255.0 {
|
||||
acts.push(Act::Retire);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
acts
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! Structure and presence: nodes mount, enter, leave and revive, and the presence progress
|
||||
//! that blends a node's transition effect toward identity. Each change is one `phase::step`,
|
||||
//! carried out here in the order it asks for.
|
||||
use super::*;
|
||||
|
||||
impl Scene {
|
||||
/// A keyed node appears. On `Mount::Animated` it enters with its transition's insertion
|
||||
/// effect; on `Mount::Initial` (or under an entering parent, which it rides) it just appears.
|
||||
/// If the key is still exiting, `Mount::Animated` revives it from exactly where it is and
|
||||
/// `Mount::Initial` lands it present, at rest on `spec.frame`.
|
||||
pub fn insert(&mut self, id: NodeId, spec: NodeSpec, mount: Mount) {
|
||||
self.insert_delayed(id, spec, mount, 0.0);
|
||||
}
|
||||
|
||||
/// [`insert`](Self::insert), with a new node's entrance held `delay` seconds of its own
|
||||
/// clock: it waits whole at its insertion effect (offset, scale, blur, opacity and reveal
|
||||
/// together), then plays the entrance on the transition's enter spring. A node that mounts
|
||||
/// at once, rides an entering parent or revives mid-exit ignores the delay, and
|
||||
/// [`land_waiting`](Self::land_waiting) lands it. Removed while it waits, it unmounts at
|
||||
/// once if its insertion effect is invisible, or else leaves from that effect.
|
||||
pub fn insert_delayed(&mut self, id: NodeId, spec: NodeSpec, mount: Mount, delay: f32) {
|
||||
if let Some(i) = self.slot(id) {
|
||||
self.nodes[i].transition = spec.transition;
|
||||
let exiting = self.nodes[i].presence.exiting();
|
||||
if exiting && mount == Mount::Initial {
|
||||
self.present_now(i);
|
||||
// Also lands motion toward an unchanged frame and ends screen travel.
|
||||
self.set_frame(id, spec.frame, LayoutAnim::INSTANT);
|
||||
return;
|
||||
}
|
||||
if exiting {
|
||||
self.revive(i);
|
||||
}
|
||||
if self.nodes[i].frame != spec.frame && self.nodes[i].path.is_none() {
|
||||
self.set_frame(id, spec.frame, LayoutAnim::new(crate::tokens::REFLOW));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let parent = match spec.parent {
|
||||
Some(p) => self.slot(p).unwrap_or_else(|| panic!("insert {id:?}: parent {p:?} isn't in the scene")) as u32,
|
||||
None => NONE,
|
||||
};
|
||||
// A child rides an ancestor that is still mostly to come. Past half its entrance (and in
|
||||
// the ~0.7 s presence tail after it has visibly arrived), riding would show the child at
|
||||
// once at most of its opacity, so it enters on its own instead of popping in. A parent
|
||||
// that rode in itself is present at once, so the entering ancestor above it is the one
|
||||
// to ask for a plain fade: otherwise each level of a subtree mounting together fades on
|
||||
// its own, and the fades multiply until its deep rows show long after it has arrived.
|
||||
// An entrance of its own (anything beyond the plain fade, or a delay) asks only its parent,
|
||||
// so a list staggering its rows in under an entering surface keeps its stagger.
|
||||
let plain = delay <= 0.0 && spec.transition.insertion == Transition::opacity().insertion;
|
||||
let rides_parent = {
|
||||
let mut a = parent;
|
||||
loop {
|
||||
if a == NONE { break false; }
|
||||
match self.nodes[a as usize].presence {
|
||||
Presence::Present { .. } if plain => a = self.nodes[a as usize].parent,
|
||||
Presence::Present { .. } => break false,
|
||||
Presence::Entering { .. } => break self.presence_now(a as usize) < 0.5,
|
||||
Presence::Exiting { .. } => break true,
|
||||
}
|
||||
}
|
||||
};
|
||||
let ins = spec.transition.insertion.kit_rules(false);
|
||||
// An entrance that changes nothing on screen (an identity insertion) has nothing to play.
|
||||
let animate = mount == Mount::Animated && !rides_parent && !ins.shows_nothing();
|
||||
let delay = if delay.is_finite() { delay.max(0.0) } else { 0.0 };
|
||||
let entrance = Anim { delay, ..Anim::from(spec.transition.springs.enter) };
|
||||
let mut generation = 0;
|
||||
let mut presence = Presence::LANDED;
|
||||
let acts = phase::step(&mut presence, &mut generation, PhaseEvent::Mount { ins, animate, entrance });
|
||||
let node = Node {
|
||||
id,
|
||||
parent,
|
||||
first_child: NONE,
|
||||
last_child: NONE,
|
||||
next_sibling: NONE,
|
||||
prev_sibling: NONE,
|
||||
alive: true,
|
||||
frame: spec.frame,
|
||||
opacity: spec.opacity,
|
||||
radius: spec.radius,
|
||||
fill: spec.fill,
|
||||
transition: spec.transition,
|
||||
presence,
|
||||
generation,
|
||||
anchor: ins.anchor,
|
||||
reveal: ins.reveal,
|
||||
path: None,
|
||||
ride_trailing: false,
|
||||
tracks: [None; B],
|
||||
dirty: true,
|
||||
world: Rect::ZERO,
|
||||
origin: Vec2::ZERO,
|
||||
last: None,
|
||||
};
|
||||
let i = match self.free.pop() {
|
||||
Some(i) => {
|
||||
self.nodes[i as usize] = node;
|
||||
self.rests[i as usize] = REST_ZERO;
|
||||
i
|
||||
}
|
||||
None => {
|
||||
self.nodes.push(node);
|
||||
self.rests.push(REST_ZERO);
|
||||
(self.nodes.len() - 1) as u32
|
||||
}
|
||||
};
|
||||
// Link as the last child (siblings keep insertion order).
|
||||
let tail = if parent == NONE { self.root_tail } else { self.nodes[parent as usize].last_child };
|
||||
self.nodes[i as usize].prev_sibling = tail;
|
||||
if tail == NONE {
|
||||
if parent == NONE { self.root_head = i; } else { self.nodes[parent as usize].first_child = i; }
|
||||
} else {
|
||||
self.nodes[tail as usize].next_sibling = i;
|
||||
}
|
||||
if parent == NONE { self.root_tail = i; } else { self.nodes[parent as usize].last_child = i; }
|
||||
self.index.insert(id.0, i);
|
||||
self.order_dirty = true;
|
||||
self.apply(i as usize, acts);
|
||||
}
|
||||
|
||||
/// A present node's transition from its latest render: the removal effect and exit spring it
|
||||
/// leaves with, and how it enters if it revives. An entrance already running keeps its look;
|
||||
/// an exiting node keeps the transition it is leaving with.
|
||||
pub fn set_transition(&mut self, id: NodeId, transition: Transition) {
|
||||
if let Some(i) = self.slot(id)
|
||||
&& !self.nodes[i].presence.exiting()
|
||||
{
|
||||
self.nodes[i].transition = transition;
|
||||
}
|
||||
}
|
||||
|
||||
/// The app removed a keyed node. It stays drawn, plays its removal effect on the exit spring,
|
||||
/// and is reported in `exited` only once its presence has settled at 0 (opacity 0).
|
||||
pub fn remove(&mut self, id: NodeId) {
|
||||
let Some(i) = self.slot(id) else { return };
|
||||
if self.nodes[i].presence.exiting() {
|
||||
return;
|
||||
}
|
||||
let p = self.presence_now(i);
|
||||
let (rem, exit) = {
|
||||
let n = &self.nodes[i];
|
||||
(n.transition.removal.kit_rules(true), Anim::from(n.transition.springs.exit))
|
||||
};
|
||||
let acts = self.nodes[i].phase_step(PhaseEvent::Exit { p, rem, exit });
|
||||
self.apply(i, acts);
|
||||
}
|
||||
|
||||
/// The app removed a keyed node with no exit: it and its subtree unmount now and are reported
|
||||
/// in the next frame's `exited`.
|
||||
pub fn unmount(&mut self, id: NodeId) {
|
||||
if let Some(i) = self.slot(id) {
|
||||
self.remove_now(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// An entering node is present at once, its entrance landed: one nobody saw run.
|
||||
pub fn enter_now(&mut self, id: NodeId) {
|
||||
if let Some(i) = self.slot(id)
|
||||
&& self.nodes[i].presence.entering()
|
||||
{
|
||||
self.present_now(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// An entering node that hasn't started to show (a delayed entrance still waiting) is
|
||||
/// present at once. One already under way keeps going.
|
||||
pub fn land_waiting(&mut self, id: NodeId) {
|
||||
if let Some(i) = self.slot(id)
|
||||
&& self.nodes[i].presence.entering()
|
||||
&& self.presence_now(i) < 1e-3
|
||||
{
|
||||
self.present_now(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// A present node enters again from nothing, as if just mounted: one nobody saw that a
|
||||
/// change brings into view.
|
||||
pub fn reenter(&mut self, id: NodeId) {
|
||||
if let Some(i) = self.slot(id)
|
||||
&& self.nodes[i].presence.resting()
|
||||
{
|
||||
self.track_set(i, prop::PRESENCE, 0.0);
|
||||
self.revive(i);
|
||||
}
|
||||
}
|
||||
|
||||
fn revive(&mut self, i: usize) {
|
||||
let p = self.presence_now(i);
|
||||
let (ins, entrance) = {
|
||||
let n = &self.nodes[i];
|
||||
(n.transition.insertion.kit_rules(false), Anim::from(n.transition.springs.enter))
|
||||
};
|
||||
let acts = self.nodes[i].phase_step(PhaseEvent::Revive { p, ins, entrance });
|
||||
self.apply(i, acts);
|
||||
}
|
||||
|
||||
/// An exiting node is present again at once: no presence effect, nothing left to settle.
|
||||
fn present_now(&mut self, i: usize) {
|
||||
let ins = self.nodes[i].transition.insertion.kit_rules(false);
|
||||
let acts = self.nodes[i].phase_step(PhaseEvent::Land { ins });
|
||||
self.apply(i, acts);
|
||||
}
|
||||
|
||||
fn presence_now(&self, i: usize) -> f32 {
|
||||
self.nodes[i].tracks[prop::PRESENCE.id.0 as usize].and_then(|t| self.sample(t)).map_or(1.0, |(x, _)| x[0])
|
||||
}
|
||||
|
||||
/// Carries out what a phase change asked for, in order.
|
||||
pub(super) fn apply(&mut self, i: usize, acts: phase::Acts) {
|
||||
let id = self.nodes[i].id;
|
||||
for act in acts {
|
||||
match act {
|
||||
Act::Land(v) => self.track_set(i, prop::PRESENCE, v),
|
||||
Act::LandIfNeeded(v) => {
|
||||
if !self.at_base(i, prop::PRESENCE, v) {
|
||||
self.track_set(i, prop::PRESENCE, v);
|
||||
}
|
||||
}
|
||||
Act::Ensure => self.ensure_prop(i, prop::PRESENCE),
|
||||
Act::Run { target, anim } => self.track_animate(i, prop::PRESENCE, target, anim),
|
||||
Act::Dirty => self.nodes[i].dirty = true,
|
||||
Act::Anchor(a) => self.nodes[i].anchor = a,
|
||||
Act::Reveal(r) => self.nodes[i].reveal = r,
|
||||
Act::Retire => {
|
||||
if !self.to_remove.contains(&(i as u32)) {
|
||||
self.to_remove.push(i as u32);
|
||||
}
|
||||
}
|
||||
Act::Unmount => self.remove_now(i),
|
||||
Act::Intent { bits, seconds } => self.intent(id, bits, seconds),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Node properties: animating and setting one property of a scene node, and the tracks it keeps.
|
||||
use super::*;
|
||||
|
||||
impl Scene {
|
||||
/// Animates one of the node's properties (`prop::OPACITY`, `prop::RADIUS`, …, or a custom one).
|
||||
/// The first animation starts from the node's base value, so `.opacity(1)` → `animate(0)`
|
||||
/// fades.
|
||||
pub fn animate<T: Animatable>(&mut self, id: NodeId, prop: Prop<T>, target: T, anim: impl Into<Anim>) {
|
||||
let Some(i) = self.slot(id) else { return };
|
||||
let anim = anim.into();
|
||||
if !self.at_base(i, prop, target) {
|
||||
self.ensure_prop(i, prop);
|
||||
self.track_animate(i, prop, target, anim);
|
||||
}
|
||||
let bits = Intent::for_prop(prop.id);
|
||||
self.intent(id, bits, anim.curve.logical_duration());
|
||||
}
|
||||
|
||||
/// Puts the node at `frame` now, ending any motion toward another: a frame a live value
|
||||
/// drives, set after this frame stepped, still draws in it.
|
||||
pub fn land_frame(&mut self, id: NodeId, frame: Rect) {
|
||||
let Some(i) = self.slot(id) else { return };
|
||||
let old = self.nodes[i].frame;
|
||||
if old == frame && self.nodes[i].path.is_none() && !self.store.is_animating(id, prop::FRAME) { return; }
|
||||
if frame.w != old.w { self.rebase_trailing(i, frame.w - old.w); }
|
||||
self.end_path(i);
|
||||
self.nodes[i].frame = frame;
|
||||
self.track_set(i, prop::FRAME, frame);
|
||||
self.nodes[i].dirty = true;
|
||||
}
|
||||
|
||||
/// Sets a property immediately (direct manipulation).
|
||||
pub fn set<T: Animatable>(&mut self, id: NodeId, prop: Prop<T>, value: T) {
|
||||
if self.in_flight_to(id, prop, value) {
|
||||
return;
|
||||
}
|
||||
if let Some(i) = self.slot(id)
|
||||
&& !self.at_base(i, prop, value)
|
||||
{
|
||||
self.track_set(i, prop, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// The property's presented value (last frame), falling back to the node's base value.
|
||||
pub fn get<T: Animatable>(&self, id: NodeId, prop: Prop<T>) -> Option<T> {
|
||||
let i = self.slot(id)?;
|
||||
self.store.get(id, prop).or_else(|| self.base::<T>(i, prop.id))
|
||||
}
|
||||
|
||||
/// True when `id` is [`Phase::Present`] at `frame` with no screen-space path and no active track.
|
||||
#[inline]
|
||||
pub fn is_resting_at(&self, id: NodeId, frame: Rect) -> bool {
|
||||
let Some(i) = self.slot(id) else { return false };
|
||||
let n = &self.nodes[i];
|
||||
n.presence.resting()
|
||||
&& n.path.is_none()
|
||||
&& self.values(i, prop::FRAME.id).map_or(n.frame, Rect::read_lanes) == frame
|
||||
&& (self.store.active_len() == 0 || !self.store.is_node_animating(id))
|
||||
}
|
||||
|
||||
pub(super) fn ensure_prop<T: Animatable>(&mut self, i: usize, p: Prop<T>) {
|
||||
if !self.has_track(i, p)
|
||||
&& let Some(base) = self.base::<T>(i, p.id)
|
||||
{
|
||||
self.track_set(i, p, base);
|
||||
}
|
||||
}
|
||||
|
||||
fn has_track<T: Animatable>(&self, i: usize, p: Prop<T>) -> bool {
|
||||
self.nodes[i].tracks.get(p.id.0 as usize).copied().flatten().is_some() || self.store.has(self.nodes[i].id, p)
|
||||
}
|
||||
|
||||
/// The property has no track and `value` is its base value: it shows `value` already, and
|
||||
/// a node that never moves keeps no track for it.
|
||||
pub(super) fn at_base<T: Animatable>(&self, i: usize, p: Prop<T>, value: T) -> bool {
|
||||
!self.has_track(i, p) && self.base::<T>(i, p.id).is_some_and(|b| lanes(&b)[..T::LANES] == lanes(&value)[..T::LANES])
|
||||
}
|
||||
|
||||
pub(super) fn base<T: Animatable>(&self, i: usize, p: PropId) -> Option<T> {
|
||||
let n = &self.nodes[i];
|
||||
let mut l = [0.0; MAX_LANES];
|
||||
match p {
|
||||
x if x == prop::OPACITY.id => l[0] = n.opacity,
|
||||
x if x == prop::SCALE.id || x == prop::PRESENCE.id => l[0] = 1.0,
|
||||
x if x == prop::FRAME.id => l[..4].copy_from_slice(&n.frame.edges()),
|
||||
x if x == prop::RADIUS.id => l[..4].copy_from_slice(&n.radius.0),
|
||||
x if x == prop::FILL.id => l = lanes(&n.fill),
|
||||
x if x == prop::OFFSET.id || x == prop::ROTATION.id || x == prop::BLUR.id || x == prop::MASK.id => {}
|
||||
_ => return None,
|
||||
}
|
||||
Some(T::read_lanes(&l[..T::LANES]))
|
||||
}
|
||||
|
||||
pub(super) fn current<T: Animatable>(&self, i: usize, p: Prop<T>) -> Option<T> {
|
||||
let t = self.nodes[i].tracks.get(p.id.0 as usize).copied().flatten()?;
|
||||
self.sample(t).map(|(x, _)| T::read_lanes(&x[..T::LANES]))
|
||||
}
|
||||
|
||||
pub(super) fn track_set<T: Animatable>(&mut self, i: usize, p: Prop<T>, value: T) {
|
||||
let (id, changed) = self.store.set_changed(self.nodes[i].id, p, value);
|
||||
self.record_track(i, p.id, id, changed);
|
||||
}
|
||||
|
||||
pub(super) fn track_animate<T: Animatable>(&mut self, i: usize, p: Prop<T>, target: T, anim: Anim) {
|
||||
let (id, changed) = self.store.animate_changed(self.nodes[i].id, p, target, anim);
|
||||
self.record_track(i, p.id, id, changed);
|
||||
}
|
||||
|
||||
/// Remembers built-in props' tracks on the node (custom props live only in the store), and
|
||||
/// marks it to present again if the track changed.
|
||||
fn record_track(&mut self, i: usize, p: PropId, id: TrackId, changed: bool) {
|
||||
if let Some(slot) = self.nodes[i].tracks.get_mut(p.0 as usize) {
|
||||
*slot = Some(id);
|
||||
}
|
||||
self.nodes[i].dirty |= changed;
|
||||
}
|
||||
|
||||
pub(super) fn intent(&mut self, id: NodeId, bits: u32, seconds: f32) {
|
||||
if self.trace.is_some() {
|
||||
self.intents.push((id, bits, seconds));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn is_resting_at_tracks_presence_frame_and_active_animations() {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(1);
|
||||
let r0 = Rect::new(0.0, 0.0, 40.0, 20.0);
|
||||
let r1 = Rect::new(10.0, 0.0, 40.0, 20.0);
|
||||
assert!(!s.is_resting_at(id, r0));
|
||||
|
||||
s.insert(id, NodeSpec::new(r0), Mount::Initial);
|
||||
assert!(s.is_resting_at(id, r0));
|
||||
assert!(!s.is_resting_at(id, r1));
|
||||
|
||||
s.set_frame(id, r1, Spring::SMOOTH);
|
||||
assert!(!s.is_resting_at(id, r0));
|
||||
assert!(!s.is_resting_at(id, r1), "still springing toward r1");
|
||||
s.frame_at(5.0);
|
||||
assert!(s.is_resting_at(id, r1));
|
||||
|
||||
s.animate(id, prop::OPACITY, 0.5, Spring::SMOOTH);
|
||||
assert!(!s.is_resting_at(id, r1), "active property track blocks resting fast path");
|
||||
s.frame_at(10.0);
|
||||
assert!(s.is_resting_at(id, r1));
|
||||
|
||||
s.remove(id);
|
||||
assert!(!s.is_resting_at(id, r1), "exiting node is not resting");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Nodes that keep their place against the parent's trailing edge while its width moves: a
|
||||
//! right-aligned counter's digits hold still whichever spring the parent's edges move on.
|
||||
use super::*;
|
||||
|
||||
impl Scene {
|
||||
/// While its parent's width animates, `id` keeps its place against the parent's trailing
|
||||
/// (right) edge instead of its leading one. Its frame is still given in parent space; when the
|
||||
/// parent's width changes, a child that kept its distance from that edge doesn't move at all,
|
||||
/// and one that moved relative to it travels only that difference, on its own curve. Exiting
|
||||
/// children hold their distance too.
|
||||
pub fn set_ride_trailing(&mut self, id: NodeId, on: bool) {
|
||||
if let Some(i) = self.slot(id)
|
||||
&& self.nodes[i].ride_trailing != on
|
||||
{
|
||||
self.nodes[i].ride_trailing = on;
|
||||
self.nodes[i].dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Node `i`'s width target changed by `dw`. Its children that ride the trailing edge are
|
||||
/// drawn `drawn width − target width` right of the leading origin, so the change would move
|
||||
/// them; their local x (target, value and anything scheduled) moves by `dw` to cancel it.
|
||||
pub(super) fn rebase_trailing(&mut self, i: usize, dw: f32) {
|
||||
let mut c = self.nodes[i].first_child;
|
||||
while c != NONE {
|
||||
let k = c as usize;
|
||||
if self.nodes[k].ride_trailing {
|
||||
let n = &mut self.nodes[k];
|
||||
n.frame.x += dw;
|
||||
if let Some(path) = &mut n.path {
|
||||
path.end_local.x += dw;
|
||||
}
|
||||
n.dirty = true;
|
||||
if let Some(t) = n.tracks[prop::FRAME.id.0 as usize] {
|
||||
self.store.translate(t.index_usize(), &[dw, 0.0, dw, 0.0]);
|
||||
}
|
||||
}
|
||||
c = self.nodes[k].next_sibling;
|
||||
}
|
||||
}
|
||||
|
||||
/// How far right of its parent's leading origin node `i` rides now, with its velocity: the
|
||||
/// parent's drawn width less its target width, for a node riding the trailing edge.
|
||||
pub(super) fn trail_dual(&self, i: usize) -> D {
|
||||
let n = &self.nodes[i];
|
||||
if !n.ride_trailing || n.parent == NONE {
|
||||
return D::c(0.0);
|
||||
}
|
||||
let p = n.parent as usize;
|
||||
let w = self.world_dual(p);
|
||||
w[2].sub(w[0]).sub(D::c(self.nodes[p].frame.w))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Screen travel: a node starts at a rect in root space and follows one straight path to its own
|
||||
//! layout (matched geometry, launches).
|
||||
use super::*;
|
||||
|
||||
impl Scene {
|
||||
/// Hands one node's presented geometry, corner radius and fill to another, which then morphs
|
||||
/// to its own layout (SwiftUI `matchedGeometryEffect`, Motion `layoutId`). `from` disappears
|
||||
/// at once; `to` starts exactly where `from` was seen, with its velocity, and travels a
|
||||
/// straight root-space path. Under Reduce Motion it's a crossfade in place.
|
||||
pub fn match_geometry(&mut self, from: NodeId, to: NodeId, anim: impl Into<LayoutAnim>) {
|
||||
self.match_geometry_offset(from, to, Vec2::ZERO, anim);
|
||||
}
|
||||
|
||||
/// [`match_geometry`](Self::match_geometry) for a `from` that was seen `offset` away from its
|
||||
/// scene rect, measured in `to`'s root space: a scroll offset the renderer applies outside the
|
||||
/// scene, which differs between the two places.
|
||||
pub fn match_geometry_offset(&mut self, from: NodeId, to: NodeId, offset: Vec2, anim: impl Into<LayoutAnim>) {
|
||||
let (Some(a), Some(b)) = (self.slot(from), self.slot(to)) else { return };
|
||||
let anim = anim.into();
|
||||
if self.store.reduced_motion() {
|
||||
self.remove(from);
|
||||
let entrance = Anim::from(self.nodes[b].transition.springs.enter);
|
||||
let acts = self.nodes[b].phase_step(PhaseEvent::FadeIn { entrance });
|
||||
self.apply(b, acts);
|
||||
return;
|
||||
}
|
||||
let (mut start, vel) = self.exact_world(a);
|
||||
for (k, edge) in start.iter_mut().enumerate() {
|
||||
*edge += if k % 2 == 0 { offset.x } else { offset.y };
|
||||
}
|
||||
let radius = self.current::<Corners>(a, prop::RADIUS).unwrap_or(self.nodes[a].radius);
|
||||
let fill = self.current::<Color>(a, prop::FILL).unwrap_or(self.nodes[a].fill);
|
||||
let (to_radius, to_fill) = (self.nodes[b].radius, self.nodes[b].fill);
|
||||
// `to` is the one surface from now on: fully present, no presence effect.
|
||||
let acts = self.nodes[b].phase_step(PhaseEvent::Appear);
|
||||
self.apply(b, acts);
|
||||
self.start_path(b, start, vel, anim);
|
||||
self.track_set(b, prop::RADIUS, radius);
|
||||
self.track_animate(b, prop::RADIUS, to_radius, anim.x);
|
||||
self.track_set(b, prop::FILL, fill);
|
||||
self.track_animate(b, prop::FILL, to_fill, anim.y);
|
||||
self.intent(to, Intent::POSITION | Intent::SIZE | Intent::SHAPE, anim.y.curve.logical_duration());
|
||||
self.remove_now(a);
|
||||
}
|
||||
|
||||
/// Starts `id`, fully present, at `start` (root space) on one straight root-space path to
|
||||
/// its own layout: [`match_geometry`](Self::match_geometry) from a place no node was.
|
||||
/// Under Reduce Motion it keeps its own entrance.
|
||||
pub fn launch(&mut self, id: NodeId, start: Rect, anim: impl Into<LayoutAnim>) {
|
||||
let Some(i) = self.slot(id) else { return };
|
||||
if self.store.reduced_motion() { return; }
|
||||
let anim = anim.into();
|
||||
let acts = self.nodes[i].phase_step(PhaseEvent::Appear);
|
||||
self.apply(i, acts);
|
||||
self.start_path(i, start.edges(), [0.0; 4], anim);
|
||||
self.intent(id, Intent::POSITION, anim.y.curve.logical_duration());
|
||||
}
|
||||
|
||||
/// [`set_frame`](Self::set_frame) with screen travel for a node the renderer draws `offset`
|
||||
/// away from its scene rect, moving `velocity` faster (root space), by offsets it applies
|
||||
/// outside the scene: the new path starts where the node is drawn, at the speed it's drawn
|
||||
/// moving, so a re-aim keeps its speed. The renderer then stops adding them.
|
||||
pub fn retarget_drawn(&mut self, id: NodeId, frame: Rect, anim: impl Into<LayoutAnim>, offset: Vec2, velocity: Vec2) {
|
||||
self.set_frame_drawn(id, frame, anim.into(), [offset, velocity]);
|
||||
}
|
||||
|
||||
/// How far node `id`'s screen path draws its top-left corner from where its layout under
|
||||
/// its parent's presented origin would, and how much faster it moves it (root space). None
|
||||
/// without a path, or while the path still draws it at another size.
|
||||
pub fn path_lead(&self, id: NodeId) -> Option<[Vec2; 2]> {
|
||||
let i = self.slot(id)?;
|
||||
let path = self.nodes[i].path?;
|
||||
let (on, laid) = (self.path_dual(i, path, path.origin), self.laid_dual(i));
|
||||
// The presented snap step: 1/64 of a device pixel.
|
||||
let q = 1.0 / (64.0 * self.store.pixel_scale());
|
||||
let size = |e: [D; 4], k: usize| e[k + 2].x - e[k].x;
|
||||
if (0..2).any(|k| (size(on, k) - size(laid, k)).abs() > q) {
|
||||
return None;
|
||||
}
|
||||
Some([Vec2::new(on[0].x - laid[0].x, on[1].x - laid[1].x), Vec2::new(on[0].v - laid[0].v, on[1].v - laid[1].v)])
|
||||
}
|
||||
|
||||
/// Ends node `id`'s screen travel at its layout, as a path that has arrived ends: it then
|
||||
/// shows under its parent's presented origin.
|
||||
pub fn land_path(&mut self, id: NodeId) {
|
||||
let Some(i) = self.slot(id) else { return };
|
||||
let Some(path) = self.nodes[i].path else { return };
|
||||
self.end_path(i);
|
||||
self.track_set(i, prop::FRAME, path.end_local);
|
||||
self.nodes[i].dirty = true;
|
||||
}
|
||||
|
||||
/// Node `i`'s root-space edges from its layout under its parent's presented origin, as if
|
||||
/// it had no screen path.
|
||||
pub(super) fn laid_dual(&self, i: usize) -> [D; 4] {
|
||||
let n = &self.nodes[i];
|
||||
let mut local = n.frame.edges().map(D::c);
|
||||
self.lanes_dual(i, prop::FRAME.id, &mut local);
|
||||
if n.parent == NONE {
|
||||
return local;
|
||||
}
|
||||
let mut o = self.origin_dual(n.parent as usize);
|
||||
o[0] = o[0].add(self.trail_dual(i));
|
||||
core::array::from_fn(|k| local[k].add(o[k % 2]))
|
||||
}
|
||||
|
||||
pub(super) fn start_path(&mut self, i: usize, start: [f32; 4], vel: [f32; 4], anim: LayoutAnim) {
|
||||
let end_local = self.nodes[i].frame;
|
||||
let po = self.parent_target_origin(i);
|
||||
let end = end_local.translated(po).edges();
|
||||
// Project the current edge velocity onto each axis' path to keep it moving the same way.
|
||||
let px = axis_progress_velocity(start[0], start[2], end[0], end[2], vel[0], vel[2]);
|
||||
let py = axis_progress_velocity(start[1], start[3], end[1], end[3], vel[1], vel[3]);
|
||||
self.nodes[i].path = Some(Path { start: Rect::from_edges(start[0], start[1], start[2], start[3]), end_local, origin: po });
|
||||
if !self.travelling.contains(&(i as u32)) {
|
||||
self.travelling.push(i as u32);
|
||||
}
|
||||
self.track_set(i, prop::TRAVEL, Vec2::ZERO);
|
||||
let t = self.nodes[i].tracks[prop::TRAVEL.id.0 as usize].unwrap().index_usize();
|
||||
self.store.animate_raw(t, &[1.0, 0.0], anim.x, Some(&[px, 0.0]));
|
||||
self.store.animate_raw(t, &[1.0, 1.0], anim.y, Some(&[px, py]));
|
||||
if self.nodes[i].tracks[prop::FRAME.id.0 as usize].is_some() {
|
||||
self.track_set(i, prop::FRAME, end_local);
|
||||
}
|
||||
self.nodes[i].dirty = true;
|
||||
}
|
||||
|
||||
pub(super) fn end_path(&mut self, i: usize) {
|
||||
self.nodes[i].path = None;
|
||||
self.travelling.retain(|&x| x as usize != i);
|
||||
let id = self.nodes[i].id;
|
||||
self.store.remove(id, prop::TRAVEL);
|
||||
self.nodes[i].tracks[prop::TRAVEL.id.0 as usize] = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The progress velocity that best continues edge velocities `(v0, v1)` along the path from
|
||||
/// `(s0, s1)` to `(e0, e1)`.
|
||||
fn axis_progress_velocity(s0: f32, s1: f32, e0: f32, e1: f32, v0: f32, v1: f32) -> f32 {
|
||||
let (d0, d1) = (e0 - s0, e1 - s1);
|
||||
let len2 = d0 * d0 + d1 * d1;
|
||||
if len2 < 1e-6 { 0.0 } else { (v0 * d0 + v1 * d1) / len2 }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Finite presentation poses, sampled by the shared LoopTrack clock.
|
||||
use crate::Easing;
|
||||
|
||||
/// A full pose at elapsed seconds. Easing belongs to the segment arriving here.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Beat {
|
||||
pub at: f64,
|
||||
pub opacity: f32,
|
||||
pub scale: f32,
|
||||
pub easing: Easing,
|
||||
}
|
||||
|
||||
impl Beat {
|
||||
pub const fn new(at: f64) -> Self { Self { at, opacity: 1.0, scale: 1.0, easing: Easing::EASE_IN_OUT } }
|
||||
pub const fn opacity(mut self, value: f32) -> Self { self.opacity = value; self }
|
||||
pub const fn scale(mut self, value: f32) -> Self { self.scale = value; self }
|
||||
pub const fn easing(mut self, easing: Easing) -> Self { self.easing = easing; self }
|
||||
}
|
||||
|
||||
/// A one-shot sequence. Starts at zero, holds its final pose, and has no app callbacks.
|
||||
/// Static slices keep specs Copy, like Cycle; use a new element key to replay.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sequence {
|
||||
frames: &'static [Beat],
|
||||
pub(crate) delay: f64,
|
||||
}
|
||||
|
||||
impl Sequence {
|
||||
pub fn new(frames: &'static [Beat]) -> Self {
|
||||
assert!(frames.len() >= 2 && frames[0].at == 0.0, "keyframes need at least two poses, starting at zero");
|
||||
assert!(frames.windows(2).all(|p| p[1].at.is_finite() && p[1].at > p[0].at), "keyframe times must increase");
|
||||
assert!(frames.iter().all(|p| p.opacity.is_finite() && p.scale.is_finite() && p.scale >= 0.0), "invalid keyframe pose");
|
||||
Self { frames, delay: 0.0 }
|
||||
}
|
||||
pub fn delay(mut self, seconds: f64) -> Self {
|
||||
assert!(seconds.is_finite() && seconds >= 0.0);
|
||||
self.delay = seconds; self
|
||||
}
|
||||
pub fn duration(self) -> f64 { self.frames.last().unwrap().at }
|
||||
pub(crate) fn sample(self, elapsed: f64) -> Beat {
|
||||
if elapsed <= 0.0 { return self.frames[0]; }
|
||||
let Some(pair) = self.frames.windows(2).find(|p| elapsed < p[1].at) else { return *self.frames.last().unwrap() };
|
||||
let [a, b] = [pair[0], pair[1]];
|
||||
let t = b.easing.eval(((elapsed - a.at) / (b.at - a.at)) as f32);
|
||||
Beat { at: elapsed, opacity: a.opacity + (b.opacity - a.opacity) * t,
|
||||
scale: (a.scale + (b.scale - a.scale) * t).max(0.0), easing: b.easing }
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
//! Two-edge 1/64 device-pixel snapping.
|
||||
//!
|
||||
//! Snap both edges, then derive the size. Snapping origin and size separately makes a stationary
|
||||
//! edge flicker by one quantum as the other edge moves.
|
||||
|
||||
use crate::value::Rect;
|
||||
|
||||
/// Rounds `v` points to the 1/64 device-pixel grid at `scale` device pixels per point.
|
||||
#[inline]
|
||||
pub fn grid(v: f32, scale: f32) -> f32 {
|
||||
let q = 64.0 * scale;
|
||||
(v * q).round() / q
|
||||
}
|
||||
|
||||
/// Snaps a rectangle's four edges to the 1/64 px grid and derives its size from them.
|
||||
#[inline]
|
||||
pub fn snap_rect(r: Rect, scale: f32) -> Rect {
|
||||
snap_edges(r.edges(), scale)
|
||||
}
|
||||
|
||||
/// Snaps edges given directly (left, top, right, bottom).
|
||||
#[inline]
|
||||
pub fn snap_edges(e: [f32; 4], scale: f32) -> Rect {
|
||||
Rect::from_edges(grid(e[0], scale), grid(e[1], scale), grid(e[2], scale), grid(e[3], scale))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stationary_bottom_edge_never_moves() {
|
||||
// Top edge animates continuously; bottom stays at 200.3. Two-edge snapping keeps the bottom
|
||||
// exactly fixed, where snapping (y, h) separately would wobble it.
|
||||
let bottom = 200.3f32;
|
||||
let fixed = grid(bottom, 2.0);
|
||||
let mut separate = std::collections::HashSet::new();
|
||||
for i in 0..1000 {
|
||||
let top = 10.0 + i as f32 * 0.0137;
|
||||
let r = snap_rect(Rect::from_edges(0.0, top, 10.0, bottom), 2.0);
|
||||
assert_eq!(r.y + r.h, fixed);
|
||||
let (y, h) = (grid(top, 2.0), grid(bottom - top, 2.0));
|
||||
separate.insert((y + h).to_bits());
|
||||
}
|
||||
assert!(separate.len() > 1, "the naive way should wobble, proving the test bites");
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
//! Springs parameterised by perceptual duration and bounce, exactly like SwiftUI.
|
||||
|
||||
use crate::layer::{Eps, Layer};
|
||||
|
||||
/// A critically/under/over-damped spring with mass 1, described the way people tune it.
|
||||
///
|
||||
/// `Spring::new(duration, bounce)` maps exactly like SwiftUI's `Spring(duration:bounce:)`,
|
||||
/// Flutter's `SpringDescription.withDurationAndBounce`, knobs and `kit_motion.rs`:
|
||||
///
|
||||
/// ```text
|
||||
/// ω = 2π / duration stiffness k = ω² (mass 1)
|
||||
/// ζ = 1 − bounce (bounce ≥ 0) damping c = 2ζω
|
||||
/// ζ = 1 / (1 + bounce) (bounce < 0, overdamped)
|
||||
/// ```
|
||||
///
|
||||
/// Motion (motion.dev) uses a *different* number for the same feel: its `visualDuration` is this
|
||||
/// duration ÷ 1.2. Use [`Spring::from_motion`] / [`Spring::motion_visual_duration`] at that boundary.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Spring {
|
||||
/// Perceptual duration in seconds (SwiftUI `duration`, the undamped period).
|
||||
pub duration: f32,
|
||||
/// −1 < bounce < 1. 0 is critically damped (Kit's default), > 0 overshoots, < 0 is overdamped.
|
||||
pub bounce: f32,
|
||||
}
|
||||
|
||||
impl Spring {
|
||||
/// `Spring(duration:bounce:)`. Panics (also in `const` contexts) on a non-positive duration or
|
||||
/// a bounce outside (−1, 1).
|
||||
pub const fn new(duration: f32, bounce: f32) -> Spring {
|
||||
assert!(duration > 0.0 && duration < 1e4, "spring duration must be positive seconds");
|
||||
assert!(bounce > -1.0 && bounce < 1.0, "spring bounce must be in (-1, 1)");
|
||||
Spring { duration, bounce }
|
||||
}
|
||||
|
||||
/// SwiftUI `.spring(response:dampingFraction:)`: ω = 2π/response, ζ = dampingFraction.
|
||||
pub fn from_response(response: f32, damping_fraction: f32) -> Spring {
|
||||
Spring::from_omega_zeta(core::f32::consts::TAU / response, damping_fraction)
|
||||
}
|
||||
|
||||
/// From angular frequency ω (rad/s) and damping ratio ζ (> 0).
|
||||
pub fn from_omega_zeta(omega: f32, zeta: f32) -> Spring {
|
||||
assert!(omega > 0.0 && zeta > 0.0, "omega and zeta must be positive");
|
||||
let bounce = if zeta <= 1.0 { 1.0 - zeta } else { 1.0 / zeta - 1.0 };
|
||||
Spring::new(core::f32::consts::TAU / omega, bounce.clamp(-0.999, 0.999))
|
||||
}
|
||||
|
||||
/// SwiftUI `Spring(mass:stiffness:damping:)` / CSS-physics / Motion `{ stiffness, damping, mass }`.
|
||||
pub fn from_stiffness_damping(stiffness: f32, damping: f32, mass: f32) -> Spring {
|
||||
let omega = (stiffness / mass).sqrt();
|
||||
let zeta = damping / (2.0 * (stiffness * mass).sqrt());
|
||||
Spring::from_omega_zeta(omega, zeta)
|
||||
}
|
||||
|
||||
/// Motion's `{ visualDuration, bounce }`: Motion uses ω = 2π / (1.2 · visualDuration).
|
||||
/// So Motion `visualDuration: 0.45` is `Spring::new(0.54, ..)`. Psychopomp's
|
||||
/// `SpringPlan::visual(d, b)` uses the same 1.2 factor.
|
||||
pub fn from_motion(visual_duration: f32, bounce: f32) -> Spring {
|
||||
Spring::new(visual_duration * 1.2, bounce)
|
||||
}
|
||||
|
||||
/// The `visualDuration` to hand Motion for the same physical spring.
|
||||
pub fn motion_visual_duration(self) -> f32 {
|
||||
self.duration / 1.2
|
||||
}
|
||||
|
||||
/// Angular frequency ω = 2π / duration (rad/s).
|
||||
#[inline]
|
||||
pub fn omega(self) -> f32 {
|
||||
core::f32::consts::TAU / self.duration
|
||||
}
|
||||
|
||||
/// Damping ratio ζ.
|
||||
#[inline]
|
||||
pub fn zeta(self) -> f32 {
|
||||
if self.bounce >= 0.0 { 1.0 - self.bounce } else { 1.0 / (1.0 + self.bounce) }
|
||||
}
|
||||
|
||||
/// k = ω² (mass 1).
|
||||
pub fn stiffness(self) -> f32 {
|
||||
let w = self.omega();
|
||||
w * w
|
||||
}
|
||||
|
||||
/// c = 2ζω (mass 1).
|
||||
pub fn damping(self) -> f32 {
|
||||
2.0 * self.zeta() * self.omega()
|
||||
}
|
||||
|
||||
/// SwiftUI's `response` (the same number as `duration`).
|
||||
pub fn response(self) -> f32 {
|
||||
self.duration
|
||||
}
|
||||
|
||||
/// A copy with a different duration (keeps bounce).
|
||||
pub fn with_duration(self, duration: f32) -> Spring {
|
||||
Spring::new(duration, self.bounce)
|
||||
}
|
||||
|
||||
/// Position and velocity at `t` seconds after leaving `x0` with velocity `v0` toward `target`.
|
||||
/// Closed form for every damping regime; exact at any `t`, so it can be sampled at the display
|
||||
/// link's target timestamp and retargeted from there.
|
||||
pub fn sample(self, x0: f32, v0: f32, target: f32, t: f32) -> (f32, f32) {
|
||||
let layer = Layer::spring_unbounded(self, 0.0, x0 - target, v0);
|
||||
let (o, v) = layer.sample(t as f64);
|
||||
(target + o, v)
|
||||
}
|
||||
|
||||
/// Seconds until a unit step (0 → 1 from rest) stays within `epsilon` of the target, in both
|
||||
/// position and velocity (velocity threshold `10·epsilon` per second).
|
||||
pub fn settling_duration(self, epsilon: f32) -> f32 {
|
||||
let layer = Layer::spring(self, 0.0, -1.0, 0.0, Eps { pos: epsilon, vel: epsilon * 10.0 });
|
||||
layer.end as f32
|
||||
}
|
||||
|
||||
/// Tail bound for an arbitrary retarget, using the same thresholds and 120 s cap as the store.
|
||||
pub fn settling_duration_from(self, from: f32, velocity: f32, target: f32, epsilon: f32) -> f32 {
|
||||
assert!(epsilon.is_finite() && epsilon > 0.0);
|
||||
let layer = Layer::spring(self, 0.0, from - target, velocity, Eps { pos: epsilon, vel: epsilon * 10.0 });
|
||||
layer.end.max(0.0) as f32
|
||||
}
|
||||
|
||||
/// Bakes the unit step response into a CSS `linear()` easing plus its duration in ms,
|
||||
/// like knobs' `springEasing`. For web backends that offload to WAAPI.
|
||||
pub fn css_linear(self) -> (String, u32) {
|
||||
let total = self.settling_duration(0.002).max(1.0 / 60.0);
|
||||
let n = ((total * 60.0).ceil() as usize).clamp(2, 240);
|
||||
let mut s = String::from("linear(0");
|
||||
for i in 1..n {
|
||||
let t = total * i as f32 / n as f32;
|
||||
let (x, _) = self.sample(0.0, 0.0, 1.0, t);
|
||||
s.push_str(&format!(",{}", (x * 1000.0).round() / 1000.0));
|
||||
}
|
||||
s.push_str(",1)");
|
||||
(s, (total * 1000.0).round() as u32)
|
||||
}
|
||||
|
||||
/// No motion: as a [`crate::Curve`] or [`crate::Anim`] (a transition's presence, a layout
|
||||
/// change) it is `Curve::Instant`, which Reduce Motion leaves instant where it turns a short
|
||||
/// spring into a fade. [`SpringPair::NONE`] and [`crate::Transition::none`] build on it.
|
||||
pub const NONE: Spring = Spring::new(1e-6, 0.0);
|
||||
|
||||
// SwiftUI's named springs (iOS 17+). Duration 0.5 by default.
|
||||
|
||||
/// SwiftUI `.smooth`: duration 0.5, bounce 0.
|
||||
pub const SMOOTH: Spring = Spring::new(0.5, 0.0);
|
||||
/// SwiftUI `.snappy`: duration 0.5, bounce 0.15.
|
||||
pub const SNAPPY: Spring = Spring::new(0.5, 0.15);
|
||||
/// SwiftUI `.bouncy`: duration 0.5, bounce 0.3.
|
||||
pub const BOUNCY: Spring = Spring::new(0.5, 0.3);
|
||||
/// SwiftUI `.spring` (the iOS 17 default): duration 0.5, bounce 0.
|
||||
pub const DEFAULT: Spring = Spring::new(0.5, 0.0);
|
||||
|
||||
/// SwiftUI `.smooth(duration:extraBounce:)`.
|
||||
pub const fn smooth(duration: f32, extra_bounce: f32) -> Spring {
|
||||
Spring::new(duration, extra_bounce)
|
||||
}
|
||||
/// SwiftUI `.snappy(duration:extraBounce:)`.
|
||||
pub const fn snappy(duration: f32, extra_bounce: f32) -> Spring {
|
||||
Spring::new(duration, 0.15 + extra_bounce)
|
||||
}
|
||||
/// SwiftUI `.bouncy(duration:extraBounce:)`.
|
||||
pub const fn bouncy(duration: f32, extra_bounce: f32) -> Spring {
|
||||
Spring::new(duration, 0.3 + extra_bounce)
|
||||
}
|
||||
/// SwiftUI `.interactiveSpring()`: response 0.15, damping fraction 0.86.
|
||||
pub fn interactive() -> Spring {
|
||||
Spring::from_response(0.15, 0.86)
|
||||
}
|
||||
}
|
||||
|
||||
/// An enter/exit pair. Exits run 10–25 % shorter (Kit rule 4); presence and `open → closed`
|
||||
/// toggles use `exit`, everything else `enter`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct SpringPair {
|
||||
pub enter: Spring,
|
||||
pub exit: Spring,
|
||||
}
|
||||
|
||||
impl SpringPair {
|
||||
pub const fn new(enter: Spring, exit: Spring) -> SpringPair {
|
||||
SpringPair { enter, exit }
|
||||
}
|
||||
/// [`Spring::NONE`] both ways: enters and leaves in the frame it starts.
|
||||
pub const NONE: SpringPair = SpringPair::new(Spring::NONE, Spring::NONE);
|
||||
/// A pair whose exit is `enter` shortened by `ratio` (Kit: 0.75–0.9).
|
||||
pub fn with_exit_ratio(enter: Spring, ratio: f32) -> SpringPair {
|
||||
SpringPair { enter, exit: Spring::new(enter.duration * ratio, enter.bounce * 0.5) }
|
||||
}
|
||||
}
|
||||
+640
@@ -0,0 +1,640 @@
|
||||
//! The animation store: every animated property of every node, in flat arrays the render thread
|
||||
//! samples once per frame.
|
||||
//!
|
||||
//! - **Struct of arrays.** Lane targets, values, velocities and segments live in parallel `Vec`s;
|
||||
//! a track (one property of one node) is a contiguous run of lanes.
|
||||
//! - **Only active tracks cost anything.** `tick` walks a dense list of active track indices.
|
||||
//! Settled tracks snap to `(target, 0)`, leave the list and cost nothing until retargeted.
|
||||
//! - **No allocation per frame.** Pools for additive layers and delayed events use intrusive free
|
||||
//! lists, and the event and touched buffers keep their capacity.
|
||||
//! - **Ids, not references.** `NodeId` + `Prop<T>` or a generational `TrackId`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
|
||||
use crate::carry::Carry;
|
||||
use crate::curve::{Anim, Blend, Curve, Decay, Velocity};
|
||||
use crate::layer::{Kind, Layer};
|
||||
use crate::props::{NodeId, Prop, PropClass, PropId};
|
||||
use crate::spring::Spring;
|
||||
use crate::value::{Animatable, MAX_LANES, lanes};
|
||||
|
||||
mod clock;
|
||||
mod lanes;
|
||||
mod started;
|
||||
mod tracks;
|
||||
mod typed;
|
||||
|
||||
use self::tracks::Mode;
|
||||
|
||||
const NONE: u32 = u32::MAX;
|
||||
|
||||
/// A generational handle to one track.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct TrackId {
|
||||
index: u32,
|
||||
generation: u32,
|
||||
}
|
||||
|
||||
impl TrackId {
|
||||
pub(crate) fn index_usize(self) -> usize {
|
||||
self.index as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened during a tick (or since the last one).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum MotionEvent {
|
||||
/// The track reached `(target, 0)` and went dormant.
|
||||
Settled { track: TrackId, node: NodeId, prop: PropId },
|
||||
/// An animation started with `.completion(token)` finished (`finished`), or was replaced by a
|
||||
/// newer animation before it did (`!finished`).
|
||||
Completed { token: u64, node: NodeId, prop: PropId, finished: bool },
|
||||
}
|
||||
|
||||
/// How a released gesture continues.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Release<T> {
|
||||
/// Spring to a target, starting from the release velocity.
|
||||
Spring { target: T, spring: Spring },
|
||||
/// Coast with exponential decay to the projected rest point.
|
||||
Decay(Decay),
|
||||
/// Coast, but if the projection leaves `[min, max]`, spring onto the bound with the velocity
|
||||
/// the value has when it reaches it (scroll views). If it is already out of bounds
|
||||
/// (rubber-banded), spring straight back.
|
||||
DecayClamped { decay: Decay, min: T, max: T, spring: Spring },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Extra {
|
||||
layer: Layer,
|
||||
next: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Pending {
|
||||
at: f64,
|
||||
target: f32,
|
||||
/// NaN: inherit.
|
||||
velocity: f32,
|
||||
curve: Curve,
|
||||
blend: Blend,
|
||||
next: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Meta {
|
||||
node: NodeId,
|
||||
prop: PropId,
|
||||
class: PropClass,
|
||||
generation: u32,
|
||||
alive: bool,
|
||||
epoch: u32,
|
||||
token: u64,
|
||||
logical_at: f64,
|
||||
node_next: u32,
|
||||
}
|
||||
|
||||
/// A fast, unkeyed hasher for small fixed-size keys (ids, glyph keys) that no input chooses.
|
||||
#[derive(Default)]
|
||||
pub struct Fx(u64);
|
||||
impl Hasher for Fx {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for &b in bytes {
|
||||
self.add(b as u64);
|
||||
}
|
||||
}
|
||||
fn write_u16(&mut self, i: u16) {
|
||||
self.add(i as u64)
|
||||
}
|
||||
fn write_u32(&mut self, i: u32) {
|
||||
self.add(i as u64)
|
||||
}
|
||||
fn write_u64(&mut self, i: u64) {
|
||||
self.add(i)
|
||||
}
|
||||
fn write_usize(&mut self, i: usize) {
|
||||
self.add(i as u64)
|
||||
}
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl Fx {
|
||||
#[inline]
|
||||
fn add(&mut self, i: u64) {
|
||||
self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95);
|
||||
}
|
||||
}
|
||||
pub(crate) type FxMap<K, V> = HashMap<K, V, BuildHasherDefault<Fx>>;
|
||||
|
||||
/// A clock some nodes' tracks run on instead of the store's: it advances by `dt × scale` each
|
||||
/// time the store's time moves. Nodes at the same scale share one; `nodes == 0` marks it free.
|
||||
#[derive(Clone, Copy)]
|
||||
struct SubClock {
|
||||
time: f64,
|
||||
scale: f32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
/// Optional diagnostics for inherited spatial spring retargets (points per second).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct RetargetAudit {
|
||||
pub lanes: u64,
|
||||
pub max_velocity_error: f32,
|
||||
}
|
||||
|
||||
/// All animated properties, sampled together at one presentation time.
|
||||
pub struct AnimationStore {
|
||||
now: f64,
|
||||
pixel_scale: f32,
|
||||
reduced_motion: bool,
|
||||
|
||||
l_target: Vec<f32>,
|
||||
l_value: Vec<f32>,
|
||||
l_vel: Vec<f32>,
|
||||
l_layer: Vec<Layer>,
|
||||
l_more: Vec<u32>,
|
||||
l_pending: Vec<u32>,
|
||||
l_curve: Vec<Curve>,
|
||||
lane_free: Vec<Vec<u32>>,
|
||||
|
||||
t_lane0: Vec<u32>,
|
||||
t_n: Vec<u8>,
|
||||
t_settle_at: Vec<f64>,
|
||||
t_next_due: Vec<f64>,
|
||||
t_slot: Vec<u32>,
|
||||
t_meta: Vec<Meta>,
|
||||
/// The track's clock: 0 is the store's own, otherwise an index into `clocks`.
|
||||
t_clock: Vec<u32>,
|
||||
/// Sampled at its held pose by the last tick (in whichever [`Mode`] it holds), so `tick`
|
||||
/// can skip it until [`mode`](Self::mode) says it moves. [`resample`](Self::resample)
|
||||
/// clears it wherever a track's timing or pose changes.
|
||||
t_held: Vec<bool>,
|
||||
track_free: Vec<u32>,
|
||||
|
||||
/// Index 0 stands for the store's own clock and is never read.
|
||||
clocks: Vec<SubClock>,
|
||||
clock_free: Vec<u32>,
|
||||
node_clock: FxMap<u64, u32>,
|
||||
|
||||
active: Vec<u32>,
|
||||
/// With the generation they had, so a track freed (or its slot reused) since drops out
|
||||
/// where these are read, and freeing a track never scans them.
|
||||
touched: Vec<TrackId>,
|
||||
set_touched: Vec<TrackId>,
|
||||
/// Tracks started or retargeted since the last tick, and between the two before (`started`).
|
||||
starts: Vec<TrackId>,
|
||||
ticked_starts: Vec<TrackId>,
|
||||
|
||||
extra: Vec<Extra>,
|
||||
extra_free: u32,
|
||||
pending: Vec<Pending>,
|
||||
pending_free: u32,
|
||||
|
||||
index: FxMap<(u64, u16), u32>,
|
||||
node_head: FxMap<u64, u32>,
|
||||
|
||||
events: Carry<MotionEvent>,
|
||||
retarget_audit: Option<RetargetAudit>,
|
||||
}
|
||||
|
||||
impl Default for AnimationStore {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationStore {
|
||||
pub fn new() -> Self {
|
||||
AnimationStore {
|
||||
now: 0.0,
|
||||
pixel_scale: 2.0,
|
||||
reduced_motion: false,
|
||||
l_target: Vec::new(),
|
||||
l_value: Vec::new(),
|
||||
l_vel: Vec::new(),
|
||||
l_layer: Vec::new(),
|
||||
l_more: Vec::new(),
|
||||
l_pending: Vec::new(),
|
||||
l_curve: Vec::new(),
|
||||
lane_free: (0..=MAX_LANES).map(|_| Vec::new()).collect(),
|
||||
t_lane0: Vec::new(),
|
||||
t_n: Vec::new(),
|
||||
t_settle_at: Vec::new(),
|
||||
t_next_due: Vec::new(),
|
||||
t_slot: Vec::new(),
|
||||
t_meta: Vec::new(),
|
||||
t_clock: Vec::new(),
|
||||
t_held: Vec::new(),
|
||||
track_free: Vec::new(),
|
||||
clocks: Vec::new(),
|
||||
clock_free: Vec::new(),
|
||||
node_clock: FxMap::default(),
|
||||
active: Vec::new(),
|
||||
touched: Vec::new(),
|
||||
set_touched: Vec::new(),
|
||||
starts: Vec::new(),
|
||||
ticked_starts: Vec::new(),
|
||||
extra: Vec::new(),
|
||||
extra_free: NONE,
|
||||
pending: Vec::new(),
|
||||
pending_free: NONE,
|
||||
index: FxMap::default(),
|
||||
node_head: FxMap::default(),
|
||||
events: Carry::new(),
|
||||
retarget_audit: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-sizes for `tracks` tracks of about `lanes_per_track` lanes, so even the first frames
|
||||
/// don't allocate.
|
||||
pub fn with_capacity(tracks: usize, lanes_per_track: usize) -> Self {
|
||||
let mut s = Self::new();
|
||||
let lanes = tracks * lanes_per_track;
|
||||
s.l_target.reserve(lanes);
|
||||
s.l_value.reserve(lanes);
|
||||
s.l_vel.reserve(lanes);
|
||||
s.l_layer.reserve(lanes);
|
||||
s.l_more.reserve(lanes);
|
||||
s.l_pending.reserve(lanes);
|
||||
s.l_curve.reserve(lanes);
|
||||
s.t_lane0.reserve(tracks);
|
||||
s.t_n.reserve(tracks);
|
||||
s.t_settle_at.reserve(tracks);
|
||||
s.t_next_due.reserve(tracks);
|
||||
s.t_slot.reserve(tracks);
|
||||
s.t_meta.reserve(tracks);
|
||||
s.t_clock.reserve(tracks);
|
||||
s.t_held.reserve(tracks);
|
||||
s.active.reserve(tracks);
|
||||
s.touched.reserve(tracks);
|
||||
s.events.reserve(tracks * 2);
|
||||
s.index.reserve(tracks);
|
||||
s.node_head.reserve(tracks);
|
||||
s
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
// Time and policy
|
||||
|
||||
/// The presentation time animations are applied at and sampled for (seconds, from a [`crate::Clock`]).
|
||||
pub fn now(&self) -> f64 {
|
||||
self.now
|
||||
}
|
||||
|
||||
/// Opt-in trace diagnostics; disabled in normal rendering. Measures inherited spatial
|
||||
/// spring velocity at actual retarget boundaries, excluding deliberate instant cuts.
|
||||
pub fn audit_retargets(&mut self, enabled: bool) {
|
||||
self.retarget_audit = enabled.then(RetargetAudit::default);
|
||||
}
|
||||
|
||||
pub fn take_retarget_audit(&mut self) -> RetargetAudit {
|
||||
self.retarget_audit.as_mut().map(std::mem::take).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Sets the frame's target presentation time. Apply this frame's commits after this, then `tick`.
|
||||
pub fn set_time(&mut self, t: f64) {
|
||||
let dt = t - self.now;
|
||||
self.now = t;
|
||||
for c in self.clocks.iter_mut().skip(1).filter(|c| c.nodes > 0 && c.scale != 0.0) {
|
||||
c.time += dt * c.scale as f64;
|
||||
}
|
||||
}
|
||||
|
||||
/// `set_time(t)` then `tick()`.
|
||||
pub fn tick_at(&mut self, t: f64) {
|
||||
self.set_time(t);
|
||||
self.tick();
|
||||
}
|
||||
|
||||
/// Device pixels per point; sets settle thresholds below the 1/64 px snap quantum.
|
||||
pub fn set_pixel_scale(&mut self, scale: f32) {
|
||||
self.pixel_scale = scale.max(1.0);
|
||||
}
|
||||
|
||||
pub fn pixel_scale(&self) -> f32 {
|
||||
self.pixel_scale
|
||||
}
|
||||
|
||||
/// The OS Reduce Motion setting. Applied per property class to every new animation.
|
||||
pub fn set_reduced_motion(&mut self, on: bool) {
|
||||
self.reduced_motion = on;
|
||||
}
|
||||
|
||||
pub fn reduced_motion(&self) -> bool {
|
||||
self.reduced_motion
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
// The frame
|
||||
|
||||
/// Samples every active track at `now()`, applies due delayed animations, settles finished
|
||||
/// tracks. Allocation-free once buffers have grown to the working-set size.
|
||||
pub fn tick(&mut self) {
|
||||
self.events.begin();
|
||||
self.touched.clear();
|
||||
let meta = &self.t_meta;
|
||||
let live = |id: &&TrackId| meta[id.index as usize].alive && meta[id.index as usize].generation == id.generation;
|
||||
self.touched.extend(self.set_touched.iter().filter(live));
|
||||
self.set_touched.clear();
|
||||
std::mem::swap(&mut self.starts, &mut self.ticked_starts);
|
||||
self.starts.clear();
|
||||
let clocked = !self.node_clock.is_empty();
|
||||
let mut i = 0;
|
||||
while i < self.active.len() {
|
||||
let t = self.active[i] as usize;
|
||||
let now = if clocked { self.time_of(t) } else { self.now };
|
||||
// Nothing moves on a stopped clock, or on a track that only waits for a delayed
|
||||
// start: once sampled where it holds, it isn't touched again until it moves.
|
||||
let mode = self.mode(t);
|
||||
if mode.holds() && self.t_held[t] {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
self.touched.push(TrackId { index: t as u32, generation: self.t_meta[t].generation });
|
||||
if self.t_next_due[t] <= now {
|
||||
self.apply_due(t, now);
|
||||
}
|
||||
self.t_held[t] = mode.holds();
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let n = self.t_n[t] as usize;
|
||||
let range = l0..l0 + n;
|
||||
let mut stacked = false;
|
||||
{
|
||||
// One bounds check per track, then straight-line lane sampling.
|
||||
let layers = &self.l_layer[range.clone()];
|
||||
let more = &self.l_more[range.clone()];
|
||||
let targets = &self.l_target[range.clone()];
|
||||
let values = &mut self.l_value[range.clone()];
|
||||
let vels = &mut self.l_vel[range.clone()];
|
||||
for k in 0..n {
|
||||
let (o, v) = layers[k].sample(now);
|
||||
values[k] = targets[k] + o;
|
||||
vels[k] = v;
|
||||
stacked |= more[k] != NONE;
|
||||
}
|
||||
}
|
||||
if stacked {
|
||||
for l in range {
|
||||
if self.l_more[l] != NONE {
|
||||
let (o2, v2) = self.sample_extra(l, now);
|
||||
self.l_value[l] += o2;
|
||||
self.l_vel[l] += v2;
|
||||
}
|
||||
}
|
||||
}
|
||||
if now >= self.t_settle_at[t] && self.t_next_due[t] == f64::INFINITY {
|
||||
self.settle(t);
|
||||
self.deactivate(t, i);
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
self.events.end();
|
||||
}
|
||||
|
||||
/// Events since the previous tick (settles, completions).
|
||||
pub fn events(&self) -> &[MotionEvent] {
|
||||
self.events.as_slice()
|
||||
}
|
||||
|
||||
/// The values presented at the last tick for a track, as raw lanes.
|
||||
pub fn values_of(&self, id: TrackId) -> Option<&[f32]> {
|
||||
self.contains(id).then(|| self.lane_values(id.index as usize))
|
||||
}
|
||||
|
||||
/// Where each lane of a track comes to rest (its latest target, delayed ones included),
|
||||
/// into `out`. False when the track is gone.
|
||||
pub(crate) fn targets_of(&self, id: TrackId, out: &mut [f32]) -> bool {
|
||||
if !self.contains(id) {
|
||||
return false;
|
||||
}
|
||||
let t = id.index as usize;
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
for (k, slot) in out.iter_mut().enumerate().take(self.t_n[t] as usize) {
|
||||
*slot = self.final_target(l0 + k);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Is the track currently animating?
|
||||
pub fn is_active(&self, id: TrackId) -> bool {
|
||||
self.contains(id) && self.t_slot[id.index as usize] != NONE
|
||||
}
|
||||
|
||||
/// Exact `(value, velocity)` lanes of a track at `now()`, into `x` and `v`.
|
||||
pub(crate) fn sample_exact(&self, id: TrackId, x: &mut [f32], v: &mut [f32]) -> bool {
|
||||
if !self.contains(id) {
|
||||
return false;
|
||||
}
|
||||
let t = id.index as usize;
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let now = self.time_of(t);
|
||||
for i in 0..self.t_n[t] as usize {
|
||||
let (a, b) = self.sample_lane(l0 + i, now);
|
||||
x[i] = a;
|
||||
v[i] = b;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn active_len(&self) -> usize {
|
||||
self.active.len()
|
||||
}
|
||||
|
||||
/// Some track is animating on a clock that moves. Tracks held by a stopped clock don't count.
|
||||
pub fn running(&self) -> bool {
|
||||
if self.node_clock.is_empty() {
|
||||
return !self.active.is_empty();
|
||||
}
|
||||
self.active.iter().any(|&t| !matches!(self.mode(t as usize), Mode::Frozen))
|
||||
}
|
||||
|
||||
pub fn track_len(&self) -> usize {
|
||||
self.t_meta.iter().filter(|m| m.alive).count()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
// Untyped core (used by the scene, keyframes and choreography)
|
||||
|
||||
pub(crate) fn ensure(&mut self, node: NodeId, prop: PropId, class: PropClass, init: &[f32]) -> u32 {
|
||||
if let Some(&t) = self.index.get(&(node.0, prop.0)) {
|
||||
self.check_lanes(t as usize, init.len());
|
||||
return t;
|
||||
}
|
||||
let n = init.len();
|
||||
assert!(n > 0 && n <= MAX_LANES);
|
||||
let l0 = self.lane_free[n].pop().unwrap_or_else(|| {
|
||||
let l0 = self.l_target.len();
|
||||
let end = l0 + n;
|
||||
self.l_target.resize(end, 0.0);
|
||||
self.l_value.resize(end, 0.0);
|
||||
self.l_vel.resize(end, 0.0);
|
||||
self.l_layer.resize(end, Layer::REST);
|
||||
self.l_more.resize(end, NONE);
|
||||
self.l_pending.resize(end, NONE);
|
||||
self.l_curve.resize(end, Curve::Instant);
|
||||
l0 as u32
|
||||
});
|
||||
for (i, &x) in init.iter().enumerate() {
|
||||
let l = l0 as usize + i;
|
||||
self.l_target[l] = x;
|
||||
self.l_value[l] = x;
|
||||
self.l_vel[l] = 0.0;
|
||||
self.l_layer[l] = Layer::REST;
|
||||
self.l_more[l] = NONE;
|
||||
self.l_pending[l] = NONE;
|
||||
self.l_curve[l] = Curve::Instant;
|
||||
}
|
||||
let head = self.node_head.get(&node.0).copied().unwrap_or(NONE);
|
||||
let clock = if self.node_clock.is_empty() { 0 } else { self.node_clock.get(&node.0).copied().unwrap_or(0) };
|
||||
let t = match self.track_free.pop() {
|
||||
Some(t) => {
|
||||
let t = t as usize;
|
||||
let generation = self.t_meta[t].generation.wrapping_add(1);
|
||||
self.t_meta[t] = Meta::new(node, prop, class, generation, head);
|
||||
self.t_lane0[t] = l0;
|
||||
self.t_n[t] = n as u8;
|
||||
self.t_settle_at[t] = f64::NEG_INFINITY;
|
||||
self.t_next_due[t] = f64::INFINITY;
|
||||
self.t_slot[t] = NONE;
|
||||
self.t_clock[t] = clock;
|
||||
self.resample(t);
|
||||
t as u32
|
||||
}
|
||||
None => {
|
||||
self.t_meta.push(Meta::new(node, prop, class, 0, head));
|
||||
self.t_lane0.push(l0);
|
||||
self.t_n.push(n as u8);
|
||||
self.t_settle_at.push(f64::NEG_INFINITY);
|
||||
self.t_next_due.push(f64::INFINITY);
|
||||
self.t_slot.push(NONE);
|
||||
self.t_clock.push(clock);
|
||||
self.t_held.push(false);
|
||||
(self.t_meta.len() - 1) as u32
|
||||
}
|
||||
};
|
||||
self.index.insert((node.0, prop.0), t);
|
||||
self.node_head.insert(node.0, t);
|
||||
t
|
||||
}
|
||||
|
||||
pub(crate) fn id_of(&self, t: usize) -> TrackId {
|
||||
TrackId { index: t as u32, generation: self.t_meta[t].generation }
|
||||
}
|
||||
|
||||
fn check_lanes(&self, t: usize, n: usize) {
|
||||
assert_eq!(
|
||||
self.t_n[t] as usize, n,
|
||||
"property {:?} of {:?} was created with {} lanes, used with {}",
|
||||
self.t_meta[t].prop, self.t_meta[t].node, self.t_n[t], n
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn lane_targets_4(&self, t: usize) -> [f32; 4] {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
core::array::from_fn(|i| self.final_target(l0 + i))
|
||||
}
|
||||
|
||||
fn lane_values(&self, t: usize) -> &[f32] {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
&self.l_value[l0..l0 + self.t_n[t] as usize]
|
||||
}
|
||||
|
||||
pub(crate) fn set_raw(&mut self, t: u32, values: &[f32]) {
|
||||
let t = t as usize;
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
for (i, &x) in values.iter().enumerate() {
|
||||
let l = l0 + i;
|
||||
self.cancel_pending(l);
|
||||
self.free_extra(l);
|
||||
self.l_layer[l] = Layer::REST;
|
||||
self.l_target[l] = x;
|
||||
self.l_value[l] = x;
|
||||
self.l_vel[l] = 0.0;
|
||||
self.l_curve[l] = Curve::Instant;
|
||||
}
|
||||
self.t_next_due[t] = f64::INFINITY;
|
||||
self.t_settle_at[t] = f64::NEG_INFINITY;
|
||||
self.take_token(t, false);
|
||||
self.t_meta[t].epoch = self.t_meta[t].epoch.wrapping_add(1);
|
||||
if self.t_slot[t] != NONE {
|
||||
let slot = self.t_slot[t] as usize;
|
||||
self.deactivate(t, slot);
|
||||
}
|
||||
self.set_touched.push(TrackId { index: t as u32, generation: self.t_meta[t].generation });
|
||||
}
|
||||
|
||||
/// Animates lanes of track `t` toward `targets`. `lane_vel` overrides per-lane start velocity.
|
||||
/// False when no lane's target changed, so nothing moves.
|
||||
pub(crate) fn animate_raw(&mut self, t: usize, targets: &[f32], mut anim: Anim, lane_vel: Option<&[f32]>) -> bool {
|
||||
let now = self.time_of(t);
|
||||
if self.t_next_due[t] <= now {
|
||||
self.apply_due(t, now);
|
||||
}
|
||||
let class = self.t_meta[t].class;
|
||||
if self.reduced_motion {
|
||||
anim.curve = class.reduce(anim.curve);
|
||||
}
|
||||
let eps = class.eps(self.pixel_scale);
|
||||
let blend = anim.resolved_blend();
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let mut changed = false;
|
||||
for (i, &target) in targets.iter().enumerate() {
|
||||
let l = l0 + i;
|
||||
let vel = match (lane_vel, anim.velocity) {
|
||||
(Some(v), _) => Some(v[i]),
|
||||
(None, Velocity::Inherit) => None,
|
||||
(None, Velocity::Zero) => Some(0.0),
|
||||
(None, Velocity::Uniform(u)) => Some(u),
|
||||
};
|
||||
let decay = matches!(anim.curve, Curve::Decay(_));
|
||||
if vel.is_none() && !decay && self.final_target(l) == target {
|
||||
continue; // unchanged target: keep the running trajectory and any pending due time
|
||||
}
|
||||
changed = true;
|
||||
self.cancel_pending(l);
|
||||
if anim.delay > 0.0 {
|
||||
self.push_pending(l, Pending {
|
||||
at: now + anim.delay as f64,
|
||||
target,
|
||||
velocity: vel.unwrap_or(f32::NAN),
|
||||
curve: anim.curve,
|
||||
blend,
|
||||
next: NONE,
|
||||
});
|
||||
} else {
|
||||
let before = (self.retarget_audit.is_some() && class == PropClass::Spatial
|
||||
&& matches!(anim.curve, Curve::Spring(_)) && vel.is_none()
|
||||
&& self.l_layer[l].end > now).then(|| self.sample_lane(l, now).1);
|
||||
self.start_lane(l, now, target, anim.curve, blend, vel, eps);
|
||||
if let Some(before) = before {
|
||||
let error = (self.sample_lane(l, now).1 - before).abs();
|
||||
let audit = self.retarget_audit.as_mut().unwrap();
|
||||
audit.lanes += 1;
|
||||
audit.max_velocity_error = audit.max_velocity_error.max(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
let end = now + anim.delay as f64 + anim.curve.logical_duration() as f64;
|
||||
self.commit_scheduled(t, end, anim.token);
|
||||
} else if anim.token != 0 {
|
||||
if self.t_slot[t] == NONE {
|
||||
let m = self.t_meta[t];
|
||||
self.events.push(MotionEvent::Completed { token: anim.token, node: m.node, prop: m.prop, finished: true });
|
||||
} else {
|
||||
self.take_token(t, false);
|
||||
self.t_meta[t].token = anim.token;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
impl Meta {
|
||||
fn new(node: NodeId, prop: PropId, class: PropClass, generation: u32, node_next: u32) -> Meta {
|
||||
Meta { node, prop, class, generation, alive: true, epoch: 0, token: 0, logical_at: f64::NEG_INFINITY, node_next }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Per-node sub-clocks: scaled or paused time domains that tracks can run on independently of
|
||||
//! the store's own clock.
|
||||
|
||||
use super::{AnimationStore, NONE, SubClock};
|
||||
use crate::props::NodeId;
|
||||
|
||||
impl AnimationStore {
|
||||
/// Runs every track of `node`, and any it creates later, at `scale` times the store's speed:
|
||||
/// each `set_time` advances them by `dt × scale`. At 0 they hold exactly where they are,
|
||||
/// pending delays included, and [`running`](Self::running) ignores them. Changing the scale
|
||||
/// keeps every running animation at its exact place. 1 is the store's own clock.
|
||||
pub fn set_node_time_scale(&mut self, node: NodeId, scale: f32) {
|
||||
let scale = if scale.is_finite() { scale.max(0.0) } else { 1.0 };
|
||||
let old = self.node_clock.get(&node.0).copied().unwrap_or(0);
|
||||
if self.clock_scale(old) == scale {
|
||||
return;
|
||||
}
|
||||
let new = if scale == 1.0 { 0 } else { self.clock_at(scale) };
|
||||
let delta = self.clock_time(new) - self.clock_time(old);
|
||||
if new == 0 {
|
||||
self.node_clock.remove(&node.0);
|
||||
} else {
|
||||
self.clocks[new as usize].nodes += 1;
|
||||
self.node_clock.insert(node.0, new);
|
||||
}
|
||||
let mut t = self.node_head.get(&node.0).copied().unwrap_or(NONE);
|
||||
while t != NONE {
|
||||
self.rebase(t as usize, delta);
|
||||
self.t_clock[t as usize] = new;
|
||||
t = self.t_meta[t as usize].node_next;
|
||||
}
|
||||
self.release_clock(old);
|
||||
}
|
||||
|
||||
/// The scale `node`'s tracks run at relative to the store's (1 unless set).
|
||||
pub fn node_time_scale(&self, node: NodeId) -> f32 {
|
||||
if self.node_clock.is_empty() {
|
||||
return 1.0;
|
||||
}
|
||||
self.clock_scale(self.node_clock.get(&node.0).copied().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// The time `node`'s tracks are sampled at: `now()` unless its time is scaled.
|
||||
pub fn node_time(&self, node: NodeId) -> f64 {
|
||||
if self.node_clock.is_empty() {
|
||||
return self.now;
|
||||
}
|
||||
self.clock_time(self.node_clock.get(&node.0).copied().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// The live clock running at `scale`, or a new one reading `now`.
|
||||
fn clock_at(&mut self, scale: f32) -> u32 {
|
||||
if let Some(c) = self.clocks.iter().skip(1).position(|c| c.nodes > 0 && c.scale == scale) {
|
||||
return c as u32 + 1;
|
||||
}
|
||||
if self.clocks.is_empty() {
|
||||
self.clocks.push(SubClock { time: 0.0, scale: 1.0, nodes: 0 });
|
||||
}
|
||||
let clock = SubClock { time: self.now, scale, nodes: 0 };
|
||||
match self.clock_free.pop() {
|
||||
Some(c) => {
|
||||
self.clocks[c as usize] = clock;
|
||||
c
|
||||
}
|
||||
None => {
|
||||
self.clocks.push(clock);
|
||||
self.clocks.len() as u32 - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn release_clock(&mut self, c: u32) {
|
||||
if c == 0 {
|
||||
return;
|
||||
}
|
||||
let clock = &mut self.clocks[c as usize];
|
||||
clock.nodes -= 1;
|
||||
if clock.nodes == 0 {
|
||||
self.clock_free.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clock_scale(&self, c: u32) -> f32 {
|
||||
if c == 0 { 1.0 } else { self.clocks[c as usize].scale }
|
||||
}
|
||||
|
||||
pub(super) fn clock_time(&self, c: u32) -> f64 {
|
||||
if c == 0 { self.now } else { self.clocks[c as usize].time }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn time_of(&self, t: usize) -> f64 {
|
||||
self.clock_time(self.t_clock[t])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn frozen(&self, t: usize) -> bool {
|
||||
let c = self.t_clock[t];
|
||||
c != 0 && self.clocks[c as usize].scale == 0.0
|
||||
}
|
||||
|
||||
/// Shifts every absolute time of track `t` by `delta`.
|
||||
pub(super) fn rebase(&mut self, t: usize, delta: f64) {
|
||||
self.resample(t);
|
||||
if delta == 0.0 {
|
||||
return;
|
||||
}
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
for l in l0..l0 + self.t_n[t] as usize {
|
||||
self.l_layer[l].t0 += delta;
|
||||
self.l_layer[l].end += delta;
|
||||
let mut m = self.l_more[l];
|
||||
while m != NONE {
|
||||
let e = &mut self.extra[m as usize];
|
||||
e.layer.t0 += delta;
|
||||
e.layer.end += delta;
|
||||
m = e.next;
|
||||
}
|
||||
let mut p = self.l_pending[l];
|
||||
while p != NONE {
|
||||
self.pending[p as usize].at += delta;
|
||||
p = self.pending[p as usize].next;
|
||||
}
|
||||
}
|
||||
self.t_settle_at[t] += delta;
|
||||
self.t_next_due[t] += delta;
|
||||
self.t_meta[t].logical_at += delta;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Lane segments, additive layer stacks, delayed pending queues, settling and track lifecycle.
|
||||
|
||||
use super::{AnimationStore, Extra, MotionEvent, NONE, Pending};
|
||||
use crate::curve::{Blend, Curve};
|
||||
use crate::layer::{Eps, Kind, Layer};
|
||||
use crate::props::NodeId;
|
||||
|
||||
/// Most additive layers a lane keeps before it collapses them into one merged segment.
|
||||
const MAX_ADDITIVE: usize = 8;
|
||||
|
||||
impl AnimationStore {
|
||||
/// Starts a new segment on lane `l` at time `at` from its exact state there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn start_lane(
|
||||
&mut self,
|
||||
l: usize,
|
||||
at: f64,
|
||||
target: f32,
|
||||
curve: Curve,
|
||||
blend: Blend,
|
||||
vel: Option<f32>,
|
||||
eps: Eps,
|
||||
) {
|
||||
let (x, v) = self.sample_lane(l, at);
|
||||
self.l_curve[l] = curve;
|
||||
match curve {
|
||||
Curve::Instant => {
|
||||
self.free_extra(l);
|
||||
self.l_layer[l] = Layer::REST;
|
||||
self.l_target[l] = target;
|
||||
}
|
||||
Curve::Decay(d) => {
|
||||
let v = vel.unwrap_or(v);
|
||||
self.free_extra(l);
|
||||
self.l_target[l] = x + v / d.k();
|
||||
self.l_layer[l] = Layer::decay(d.k(), at, v, eps);
|
||||
}
|
||||
_ if blend == Blend::Additive => {
|
||||
let old = self.l_target[l];
|
||||
self.l_target[l] = target;
|
||||
let layer = Layer::start(&curve, at, old - target, vel.map_or(0.0, |u| u - v), eps);
|
||||
self.push_layer(l, layer, at);
|
||||
}
|
||||
_ => {
|
||||
self.free_extra(l);
|
||||
self.l_target[l] = target;
|
||||
self.l_layer[l] = Layer::start(&curve, at, x - target, vel.unwrap_or(v), eps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_layer(&mut self, l: usize, layer: Layer, at: f64) {
|
||||
if layer.kind == Kind::Rest {
|
||||
return;
|
||||
}
|
||||
if self.l_layer[l].kind == Kind::Rest || self.l_layer[l].end <= at {
|
||||
self.l_layer[l] = layer;
|
||||
return;
|
||||
}
|
||||
let mut count = 1;
|
||||
let mut m = self.l_more[l];
|
||||
while m != NONE {
|
||||
count += 1;
|
||||
m = self.extra[m as usize].next;
|
||||
}
|
||||
if count >= MAX_ADDITIVE {
|
||||
// Too many stacked layers: collapse into one merged segment on the new curve. Exact in
|
||||
// position and velocity at `at`.
|
||||
// The lane's target already moved; the new layer carries the difference.
|
||||
let (x, v) = self.sample_lane(l, at);
|
||||
let (o, ov) = layer.sample(at);
|
||||
let (x, v) = (x + o, v + ov);
|
||||
self.free_extra(l);
|
||||
let target = self.l_target[l];
|
||||
let curve = self.l_curve[l];
|
||||
self.l_layer[l] = Layer::start(&curve, at, x - target, v, Eps { pos: 1e-4, vel: 1e-3 });
|
||||
return;
|
||||
}
|
||||
let idx = self.alloc_extra(Extra { layer, next: self.l_more[l] });
|
||||
self.l_more[l] = idx;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn sample_lane(&self, l: usize, at: f64) -> (f32, f32) {
|
||||
let (mut o, mut v) = self.l_layer[l].sample(at);
|
||||
let mut m = self.l_more[l];
|
||||
while m != NONE {
|
||||
let e = &self.extra[m as usize];
|
||||
let (a, b) = e.layer.sample(at);
|
||||
o += a;
|
||||
v += b;
|
||||
m = e.next;
|
||||
}
|
||||
(self.l_target[l] + o, v)
|
||||
}
|
||||
|
||||
/// Sums extra layers and frees the ones that have ended.
|
||||
pub(super) fn sample_extra(&mut self, l: usize, now: f64) -> (f32, f32) {
|
||||
let (mut o, mut v) = (0.0, 0.0);
|
||||
let mut prev = NONE;
|
||||
let mut m = self.l_more[l];
|
||||
while m != NONE {
|
||||
let e = self.extra[m as usize];
|
||||
if now >= e.layer.end {
|
||||
if prev == NONE {
|
||||
self.l_more[l] = e.next;
|
||||
} else {
|
||||
self.extra[prev as usize].next = e.next;
|
||||
}
|
||||
self.extra[m as usize].next = self.extra_free;
|
||||
self.extra_free = m;
|
||||
} else {
|
||||
let (a, b) = e.layer.sample(now);
|
||||
o += a;
|
||||
v += b;
|
||||
prev = m;
|
||||
}
|
||||
m = e.next;
|
||||
}
|
||||
(o, v)
|
||||
}
|
||||
|
||||
pub(super) fn final_target(&self, l: usize) -> f32 {
|
||||
let mut p = self.l_pending[l];
|
||||
let mut target = self.l_target[l];
|
||||
while p != NONE {
|
||||
target = self.pending[p as usize].target;
|
||||
p = self.pending[p as usize].next;
|
||||
}
|
||||
target
|
||||
}
|
||||
|
||||
pub(super) fn apply_due(&mut self, t: usize, now: f64) {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let n = self.t_n[t] as usize;
|
||||
let eps = self.t_meta[t].class.eps(self.pixel_scale);
|
||||
for l in l0..l0 + n {
|
||||
loop {
|
||||
let p = self.l_pending[l];
|
||||
if p == NONE || self.pending[p as usize].at > now {
|
||||
break;
|
||||
}
|
||||
let ev = self.pending[p as usize];
|
||||
self.l_pending[l] = ev.next;
|
||||
self.pending[p as usize].next = self.pending_free;
|
||||
self.pending_free = p;
|
||||
let vel = if ev.velocity.is_nan() { None } else { Some(ev.velocity) };
|
||||
self.start_lane(l, ev.at, ev.target, ev.curve, ev.blend, vel, eps);
|
||||
}
|
||||
}
|
||||
self.recompute(t);
|
||||
}
|
||||
|
||||
/// Recomputes the track's next due time and settle time from its lanes.
|
||||
pub(super) fn recompute(&mut self, t: usize) {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let n = self.t_n[t] as usize;
|
||||
let mut due = f64::INFINITY;
|
||||
let mut settle = f64::NEG_INFINITY;
|
||||
for l in l0..l0 + n {
|
||||
let p = self.l_pending[l];
|
||||
if p != NONE {
|
||||
due = due.min(self.pending[p as usize].at);
|
||||
}
|
||||
if self.l_layer[l].kind != Kind::Rest {
|
||||
settle = settle.max(self.l_layer[l].end);
|
||||
}
|
||||
let mut m = self.l_more[l];
|
||||
while m != NONE {
|
||||
settle = settle.max(self.extra[m as usize].layer.end);
|
||||
m = self.extra[m as usize].next;
|
||||
}
|
||||
}
|
||||
self.t_next_due[t] = due;
|
||||
self.t_settle_at[t] = settle;
|
||||
self.resample(t);
|
||||
}
|
||||
|
||||
pub(super) fn settle(&mut self, t: usize) {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let n = self.t_n[t] as usize;
|
||||
for l in l0..l0 + n {
|
||||
self.free_extra(l);
|
||||
self.l_layer[l] = Layer::REST;
|
||||
self.l_value[l] = self.l_target[l];
|
||||
self.l_vel[l] = 0.0;
|
||||
}
|
||||
let m = self.t_meta[t];
|
||||
self.events.push(MotionEvent::Settled { track: self.id_of(t), node: m.node, prop: m.prop });
|
||||
self.take_token(t, true);
|
||||
}
|
||||
|
||||
pub(super) fn take_token(&mut self, t: usize, finished: bool) {
|
||||
let m = &mut self.t_meta[t];
|
||||
if m.token != 0 {
|
||||
let token = core::mem::take(&mut m.token);
|
||||
let (node, prop) = (m.node, m.prop);
|
||||
self.events.push(MotionEvent::Completed { token, node, prop, finished });
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(&mut self, t: usize) {
|
||||
if self.t_slot[t] == NONE {
|
||||
self.t_slot[t] = self.active.len() as u32;
|
||||
self.active.push(t as u32);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn deactivate(&mut self, t: usize, slot: usize) {
|
||||
self.active.swap_remove(slot);
|
||||
if slot < self.active.len() {
|
||||
let moved = self.active[slot] as usize;
|
||||
self.t_slot[moved] = slot as u32;
|
||||
}
|
||||
self.t_slot[t] = NONE;
|
||||
}
|
||||
|
||||
pub(super) fn push_pending(&mut self, l: usize, mut ev: Pending) {
|
||||
// Keep the lane's list sorted by time.
|
||||
let mut prev = NONE;
|
||||
let mut cur = self.l_pending[l];
|
||||
while cur != NONE && self.pending[cur as usize].at <= ev.at {
|
||||
prev = cur;
|
||||
cur = self.pending[cur as usize].next;
|
||||
}
|
||||
ev.next = cur;
|
||||
let idx = if self.pending_free != NONE {
|
||||
let i = self.pending_free;
|
||||
self.pending_free = self.pending[i as usize].next;
|
||||
self.pending[i as usize] = ev;
|
||||
i
|
||||
} else {
|
||||
self.pending.push(ev);
|
||||
(self.pending.len() - 1) as u32
|
||||
};
|
||||
if prev == NONE {
|
||||
self.l_pending[l] = idx;
|
||||
} else {
|
||||
self.pending[prev as usize].next = idx;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::too_many_arguments,
|
||||
reason = "Internal lane scheduler takes a track/lane address and the pending animation fields"
|
||||
)]
|
||||
pub(crate) fn schedule(
|
||||
&mut self,
|
||||
t: usize,
|
||||
lane: usize,
|
||||
at: f64,
|
||||
target: f32,
|
||||
curve: Curve,
|
||||
blend: Blend,
|
||||
velocity: Option<f32>,
|
||||
) {
|
||||
let l = self.t_lane0[t] as usize + lane;
|
||||
self.push_pending(l, Pending { at, target, velocity: velocity.unwrap_or(f32::NAN), curve, blend, next: NONE });
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_track_pending(&mut self, t: usize) {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
for l in l0..l0 + self.t_n[t] as usize {
|
||||
self.cancel_pending(l);
|
||||
}
|
||||
}
|
||||
|
||||
/// After `schedule` calls: recompute timing and wake the track.
|
||||
pub(crate) fn commit_scheduled(&mut self, t: usize, logical_at: f64, token: u64) {
|
||||
self.take_token(t, false);
|
||||
let m = &mut self.t_meta[t];
|
||||
m.token = token;
|
||||
m.logical_at = logical_at;
|
||||
m.epoch = m.epoch.wrapping_add(1);
|
||||
self.recompute(t);
|
||||
self.activate(t);
|
||||
self.starts.push(self.id_of(t));
|
||||
}
|
||||
|
||||
pub(super) fn cancel_pending(&mut self, l: usize) {
|
||||
let mut p = self.l_pending[l];
|
||||
while p != NONE {
|
||||
let next = self.pending[p as usize].next;
|
||||
self.pending[p as usize].next = self.pending_free;
|
||||
self.pending_free = p;
|
||||
p = next;
|
||||
}
|
||||
self.l_pending[l] = NONE;
|
||||
}
|
||||
|
||||
fn alloc_extra(&mut self, e: Extra) -> u32 {
|
||||
if self.extra_free != NONE {
|
||||
let i = self.extra_free;
|
||||
self.extra_free = self.extra[i as usize].next;
|
||||
self.extra[i as usize] = e;
|
||||
i
|
||||
} else {
|
||||
self.extra.push(e);
|
||||
(self.extra.len() - 1) as u32
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn free_extra(&mut self, l: usize) {
|
||||
let mut m = self.l_more[l];
|
||||
while m != NONE {
|
||||
let next = self.extra[m as usize].next;
|
||||
self.extra[m as usize].next = self.extra_free;
|
||||
self.extra_free = m;
|
||||
m = next;
|
||||
}
|
||||
self.l_more[l] = NONE;
|
||||
}
|
||||
|
||||
pub(super) fn unlink_node(&mut self, node: NodeId, t: u32) {
|
||||
let head = self.node_head.get(&node.0).copied().unwrap_or(NONE);
|
||||
if head == t {
|
||||
let next = self.t_meta[t as usize].node_next;
|
||||
if next == NONE {
|
||||
self.node_head.remove(&node.0);
|
||||
} else {
|
||||
self.node_head.insert(node.0, next);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut cur = head;
|
||||
while cur != NONE {
|
||||
let next = self.t_meta[cur as usize].node_next;
|
||||
if next == t {
|
||||
self.t_meta[cur as usize].node_next = self.t_meta[t as usize].node_next;
|
||||
return;
|
||||
}
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn free_track(&mut self, t: usize) {
|
||||
if !self.t_meta[t].alive {
|
||||
return;
|
||||
}
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let n = self.t_n[t] as usize;
|
||||
for l in l0..l0 + n {
|
||||
self.cancel_pending(l);
|
||||
self.free_extra(l);
|
||||
}
|
||||
if self.t_slot[t] != NONE {
|
||||
let slot = self.t_slot[t] as usize;
|
||||
self.deactivate(t, slot);
|
||||
}
|
||||
let m = self.t_meta[t];
|
||||
self.index.remove(&(m.node.0, m.prop.0));
|
||||
self.lane_free[n].push(l0 as u32);
|
||||
// Removal cancels the animation: whoever waits on its completion hears so.
|
||||
self.take_token(t, false);
|
||||
self.t_meta[t].alive = false;
|
||||
self.track_free.push(t as u32);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Tracks the last tick sampled first, so a frame that presents late can start its new motion
|
||||
//! from when it showed rather than from when it was due.
|
||||
use super::{AnimationStore, NONE, TrackId};
|
||||
|
||||
impl AnimationStore {
|
||||
/// The tracks started or retargeted between the last two ticks: the motion the last frame
|
||||
/// showed the first pose of.
|
||||
pub fn started(&self) -> &[TrackId] {
|
||||
&self.ticked_starts
|
||||
}
|
||||
|
||||
/// Moves every time on tracks `ids` `secs` later on their own clock, so they sample from
|
||||
/// now on where they would have `secs` sooner: motion they started holds its first pose
|
||||
/// that much longer. Each live track moves once, however often `ids` lists it.
|
||||
pub fn delay(&mut self, ids: &mut [TrackId], secs: f64) {
|
||||
if secs <= 0.0 { return; }
|
||||
ids.sort_unstable_by_key(|id| id.index);
|
||||
let mut last = NONE;
|
||||
for id in ids.iter() {
|
||||
let t = id.index_usize();
|
||||
let m = self.t_meta[t];
|
||||
if id.index == last || !m.alive || m.generation != id.generation { continue; }
|
||||
last = id.index;
|
||||
self.rebase(t, secs * f64::from(self.clock_scale(self.t_clock[t])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{AnimationStore, NodeId, Prop, PropClass, Spring};
|
||||
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Spatial);
|
||||
|
||||
#[test]
|
||||
fn a_delayed_start_holds_its_first_pose_for_the_delay_and_running_motion_keeps_time() {
|
||||
let spring = Spring::new(0.4, 0.0);
|
||||
let (old, new) = (NodeId(1), NodeId(2));
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(old, X, 0.0);
|
||||
s.set(new, X, 0.0);
|
||||
s.animate(old, X, 100.0, spring);
|
||||
s.tick_at(0.1);
|
||||
s.animate(new, X, 100.0, spring);
|
||||
s.tick_at(0.11);
|
||||
let first = s.get(new, X).unwrap();
|
||||
let mut started = s.started().to_vec();
|
||||
assert_eq!(started.len(), 1, "only what the last tick sampled first");
|
||||
started.extend(started.clone());
|
||||
s.delay(&mut started, 0.05);
|
||||
s.tick_at(0.17);
|
||||
assert!(s.started().is_empty());
|
||||
let mut reference = AnimationStore::new();
|
||||
reference.set(new, X, 0.0);
|
||||
reference.set_time(0.1);
|
||||
reference.animate(new, X, 100.0, spring);
|
||||
reference.tick_at(0.12);
|
||||
assert!((s.get(new, X).unwrap() - reference.get(new, X).unwrap()).abs() < 1e-4,
|
||||
"new motion moved 10 ms on from its first pose {first}, not 60 ms");
|
||||
let mut steady = AnimationStore::new();
|
||||
steady.set(old, X, 0.0);
|
||||
steady.animate(old, X, 100.0, spring);
|
||||
steady.tick_at(0.17);
|
||||
assert!((s.get(old, X).unwrap() - steady.get(old, X).unwrap()).abs() < 1e-4, "running motion keeps real time");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Which tracks moved in the last tick, and which are set to move.
|
||||
use super::{AnimationStore, TrackId};
|
||||
use crate::props::{NodeId, PropId};
|
||||
|
||||
/// What a track is doing at this frame's time. The one place a hold is decided, so the tick,
|
||||
/// [`running`](AnimationStore::running) and
|
||||
/// [`waiting_until`](AnimationStore::waiting_until) can't disagree about whether frames are
|
||||
/// needed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum Mode {
|
||||
/// It moves now: sample it.
|
||||
Moving,
|
||||
/// Its delayed start is due, but the tick that applies it hasn't run: it moves now, and
|
||||
/// still wants frames this instant.
|
||||
Due,
|
||||
/// It holds until a delayed start comes due at `due`, on its own clock's time.
|
||||
Waiting { due: f64 },
|
||||
/// It holds with nothing due: settled, and the tick retires it.
|
||||
Settled,
|
||||
/// It holds because its clock is stopped. It moves again when the clock does.
|
||||
Frozen,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// Nothing on screen changes until something moves it, so no sample is needed.
|
||||
pub(super) fn holds(self) -> bool {
|
||||
matches!(self, Mode::Waiting { .. } | Mode::Settled | Mode::Frozen)
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationStore {
|
||||
/// What track `t` is doing at this frame's time: the one derivation of its hold.
|
||||
#[inline]
|
||||
pub(super) fn mode(&self, t: usize) -> Mode {
|
||||
if self.frozen(t) {
|
||||
return Mode::Frozen;
|
||||
}
|
||||
let now = self.time_of(t);
|
||||
let due = self.t_next_due[t];
|
||||
if self.t_settle_at[t] > now {
|
||||
return Mode::Moving;
|
||||
}
|
||||
if due > now {
|
||||
return if due.is_finite() { Mode::Waiting { due } } else { Mode::Settled };
|
||||
}
|
||||
Mode::Due
|
||||
}
|
||||
|
||||
/// The track's timing or pose just changed, so the next tick samples it again even though
|
||||
/// it holds.
|
||||
pub(super) fn resample(&mut self, t: usize) {
|
||||
self.t_held[t] = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationStore {
|
||||
/// Tracks sampled (or `set`) in the last tick: what changed on screen.
|
||||
pub fn touched(&self) -> impl Iterator<Item = (NodeId, PropId)> + '_ {
|
||||
self.touched_tracks().map(|(_, node, prop)| (node, prop))
|
||||
}
|
||||
|
||||
/// Tracks animating now, ticked yet or not: what's set to move.
|
||||
pub fn active(&self) -> impl Iterator<Item = (NodeId, PropId)> + '_ {
|
||||
self.active.iter().map(|&t| {
|
||||
let m = &self.t_meta[t as usize];
|
||||
(m.node, m.prop)
|
||||
})
|
||||
}
|
||||
|
||||
/// When everything running only waits for a delayed start, holding still until then: the
|
||||
/// store time the first of them starts. `None` while anything moves, or nothing waits. A
|
||||
/// host can sleep until then rather than draw frames that show nothing new. Tracks on a
|
||||
/// stopped clock don't count, as in [`running`](Self::running).
|
||||
pub fn waiting_until(&self) -> Option<f64> {
|
||||
let mut first = f64::INFINITY;
|
||||
for &t in &self.active {
|
||||
let t = t as usize;
|
||||
match self.mode(t) {
|
||||
Mode::Waiting { due } => {
|
||||
let now = self.time_of(t);
|
||||
let k = self.clock_scale(self.t_clock[t]) as f64;
|
||||
first = first.min(self.now + (due - now).max(0.0) / k);
|
||||
}
|
||||
// Due but not yet applied: wake now, as a delayed start that came due.
|
||||
Mode::Due => first = first.min(self.now),
|
||||
// A stopped clock never comes due on its own.
|
||||
Mode::Frozen => {}
|
||||
// Moving, or settled and about to be retired: frames are needed now.
|
||||
Mode::Moving | Mode::Settled => return None,
|
||||
}
|
||||
}
|
||||
first.is_finite().then_some(first)
|
||||
}
|
||||
|
||||
/// Like [`touched`](Self::touched), with track ids.
|
||||
pub fn touched_tracks(&self) -> impl Iterator<Item = (TrackId, NodeId, PropId)> + '_ {
|
||||
self.touched.iter().filter(|&&id| self.contains(id)).map(|&id| {
|
||||
let m = &self.t_meta[id.index as usize];
|
||||
(id, m.node, m.prop)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationStore {
|
||||
/// Moves track `t`'s lanes by `d` (value, target and anything scheduled) and leaves the motion
|
||||
/// on them as it is: the same motion in coordinates shifted under it.
|
||||
pub(crate) fn translate(&mut self, t: usize, d: &[f32]) {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
for (i, &d) in d.iter().enumerate().take(self.t_n[t] as usize) {
|
||||
if d == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let l = l0 + i;
|
||||
self.l_target[l] += d;
|
||||
self.l_value[l] += d;
|
||||
let mut p = self.l_pending[l];
|
||||
while p != super::NONE {
|
||||
self.pending[p as usize].target += d;
|
||||
p = self.pending[p as usize].next;
|
||||
}
|
||||
}
|
||||
self.set_touched.push(TrackId { index: t as u32, generation: self.t_meta[t].generation });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! The typed API: set, animate, release and read one property of one node.
|
||||
use super::*;
|
||||
|
||||
impl AnimationStore {
|
||||
/// Sets a value immediately: direct manipulation, no animation, cancels anything running.
|
||||
/// The first `set` or `animate` of a property creates its track.
|
||||
pub fn set<T: Animatable>(&mut self, node: NodeId, prop: Prop<T>, value: T) -> TrackId {
|
||||
self.set_changed(node, prop, value).0
|
||||
}
|
||||
|
||||
/// [`set`](Self::set), and whether it changed anything: setting a track already at rest on
|
||||
/// `value` leaves it, and what it last presented, as they are.
|
||||
pub(crate) fn set_changed<T: Animatable>(&mut self, node: NodeId, prop: Prop<T>, value: T) -> (TrackId, bool) {
|
||||
let v = lanes(&value);
|
||||
let v = &v[..T::LANES];
|
||||
if let Some(&t) = self.index.get(&(node.0, prop.id.0)) {
|
||||
self.check_lanes(t as usize, T::LANES);
|
||||
if self.at_rest_on(t as usize, v) {
|
||||
return (self.id_of(t as usize), false);
|
||||
}
|
||||
}
|
||||
let t = self.ensure(node, prop.id, prop.class, v);
|
||||
self.set_raw(t, v);
|
||||
(self.id_of(t as usize), true)
|
||||
}
|
||||
|
||||
/// Track `t` is settled exactly on `v`: nothing running, scheduled or stacked on any lane.
|
||||
fn at_rest_on(&self, t: usize, v: &[f32]) -> bool {
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
self.t_slot[t] == NONE && self.t_meta[t].token == 0 && v.iter().enumerate().all(|(i, &x)| {
|
||||
let l = l0 + i;
|
||||
self.l_target[l] == x && self.l_value[l] == x && self.l_vel[l] == 0.0
|
||||
&& self.l_pending[l] == NONE && self.l_more[l] == NONE && self.l_layer[l].kind == Kind::Rest
|
||||
})
|
||||
}
|
||||
|
||||
/// Animates a property to `target`. Retargets from the exact current position and velocity.
|
||||
/// The first time a property is seen it is *set* instead: nothing animates on first mount.
|
||||
/// An unchanged target is a no-op (the running trajectory is kept).
|
||||
pub fn animate<T: Animatable>(
|
||||
&mut self,
|
||||
node: NodeId,
|
||||
prop: Prop<T>,
|
||||
target: T,
|
||||
anim: impl Into<Anim>,
|
||||
) -> TrackId {
|
||||
self.animate_changed(node, prop, target, anim.into()).0
|
||||
}
|
||||
|
||||
/// [`animate`](Self::animate), and whether it changed anything (an unchanged target doesn't).
|
||||
pub(crate) fn animate_changed<T: Animatable>(&mut self, node: NodeId, prop: Prop<T>, target: T, anim: Anim) -> (TrackId, bool) {
|
||||
match self.index.get(&(node.0, prop.id.0)).copied() {
|
||||
None => self.set_changed(node, prop, target),
|
||||
Some(t) => {
|
||||
self.check_lanes(t as usize, T::LANES);
|
||||
let v = lanes(&target);
|
||||
let changed = self.animate_raw(t as usize, &v[..T::LANES], anim, None);
|
||||
(self.id_of(t as usize), changed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Animates with an explicit per-lane starting velocity (gesture handoff).
|
||||
pub fn animate_with_velocity<T: Animatable>(
|
||||
&mut self,
|
||||
node: NodeId,
|
||||
prop: Prop<T>,
|
||||
target: T,
|
||||
velocity: T,
|
||||
anim: impl Into<Anim>,
|
||||
) -> TrackId {
|
||||
let v = lanes(&target);
|
||||
let vel = lanes(&velocity);
|
||||
let t = self.ensure(node, prop.id, prop.class, &v[..T::LANES]) as usize;
|
||||
self.animate_raw(t, &v[..T::LANES], anim.into(), Some(&vel[..T::LANES]));
|
||||
self.id_of(t)
|
||||
}
|
||||
|
||||
/// Hands a released gesture to physics, from its current value and the given velocity.
|
||||
pub fn release<T: Animatable>(&mut self, node: NodeId, prop: Prop<T>, velocity: T, how: Release<T>) -> TrackId {
|
||||
let vel = lanes(&velocity);
|
||||
let cur = lanes(&self.sample(node, prop).expect("release: set the value before releasing it"));
|
||||
let t = self.index[&(node.0, prop.id.0)] as usize;
|
||||
let n = T::LANES;
|
||||
match how {
|
||||
Release::Spring { target, spring } => {
|
||||
let tg = lanes(&target);
|
||||
self.animate_raw(t, &tg[..n], Anim::new(Curve::Spring(spring)), Some(&vel[..n]));
|
||||
}
|
||||
Release::Decay(d) => {
|
||||
// The decay's target is computed per lane from (x, v); pass the current values.
|
||||
self.animate_raw(t, &cur[..n], Anim::new(Curve::Decay(d)), Some(&vel[..n]));
|
||||
}
|
||||
Release::DecayClamped { decay, min, max, spring } => {
|
||||
let (lo, hi) = (lanes(&min), lanes(&max));
|
||||
let k = decay.k();
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let now = self.time_of(t);
|
||||
let eps = self.t_meta[t].class.eps(self.pixel_scale);
|
||||
for i in 0..n {
|
||||
let l = l0 + i;
|
||||
let (x, v) = (cur[i], vel[i]);
|
||||
self.cancel_pending(l);
|
||||
if x < lo[i] || x > hi[i] {
|
||||
let bound = x.clamp(lo[i], hi[i]);
|
||||
self.start_lane(l, now, bound, Curve::Spring(spring), Blend::Merge, Some(v), eps);
|
||||
continue;
|
||||
}
|
||||
let proj = x + v / k;
|
||||
self.start_lane(l, now, x, Curve::Decay(decay), Blend::Merge, Some(v), eps);
|
||||
let bound = if proj > hi[i] { Some(hi[i]) } else if proj < lo[i] { Some(lo[i]) } else { None };
|
||||
if let Some(b) = bound {
|
||||
// x + (v/k)(1 − e^{−kτ}) = b → τ = −ln(1 − (b − x)k/v) / k
|
||||
let tau = -((1.0 - (b - x) * k / v) as f64).ln() / k as f64;
|
||||
self.push_pending(l, Pending {
|
||||
at: now + tau.max(0.0),
|
||||
target: b,
|
||||
velocity: f32::NAN,
|
||||
curve: Curve::Spring(spring),
|
||||
blend: Blend::Merge,
|
||||
next: NONE,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.commit_scheduled(t, now, 0);
|
||||
}
|
||||
}
|
||||
self.id_of(t)
|
||||
}
|
||||
|
||||
/// The value presented at the last `tick` (what's on screen).
|
||||
pub fn get<T: Animatable>(&self, node: NodeId, prop: Prop<T>) -> Option<T> {
|
||||
let t = *self.index.get(&(node.0, prop.id.0))? as usize;
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
Some(T::read_lanes(&self.l_value[l0..l0 + T::LANES]))
|
||||
}
|
||||
|
||||
/// The velocity at the last `tick`, in units per second.
|
||||
pub fn velocity<T: Animatable>(&self, node: NodeId, prop: Prop<T>) -> Option<T> {
|
||||
let t = *self.index.get(&(node.0, prop.id.0))? as usize;
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
Some(T::read_lanes(&self.l_vel[l0..l0 + T::LANES]))
|
||||
}
|
||||
|
||||
/// The exact value at the current `now()` (may be between ticks).
|
||||
pub fn sample<T: Animatable>(&self, node: NodeId, prop: Prop<T>) -> Option<T> {
|
||||
let t = *self.index.get(&(node.0, prop.id.0))? as usize;
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let now = self.time_of(t);
|
||||
for (i, slot) in out.iter_mut().enumerate().take(T::LANES) {
|
||||
*slot = self.sample_lane(l0 + i, now).0;
|
||||
}
|
||||
Some(T::read_lanes(&out[..T::LANES]))
|
||||
}
|
||||
|
||||
/// The exact velocity at the current `now()`.
|
||||
pub fn sample_velocity<T: Animatable>(&self, node: NodeId, prop: Prop<T>) -> Option<T> {
|
||||
let t = *self.index.get(&(node.0, prop.id.0))? as usize;
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let now = self.time_of(t);
|
||||
for (i, slot) in out.iter_mut().enumerate().take(T::LANES) {
|
||||
*slot = self.sample_lane(l0 + i, now).1;
|
||||
}
|
||||
Some(T::read_lanes(&out[..T::LANES]))
|
||||
}
|
||||
|
||||
/// Where the property is going (the latest target, including delayed ones).
|
||||
pub fn target<T: Animatable>(&self, node: NodeId, prop: Prop<T>) -> Option<T> {
|
||||
let t = *self.index.get(&(node.0, prop.id.0))? as usize;
|
||||
let l0 = self.t_lane0[t] as usize;
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
for (i, slot) in out.iter_mut().enumerate().take(T::LANES) {
|
||||
*slot = self.final_target(l0 + i);
|
||||
}
|
||||
Some(T::read_lanes(&out[..T::LANES]))
|
||||
}
|
||||
|
||||
pub fn has<T>(&self, node: NodeId, prop: Prop<T>) -> bool {
|
||||
self.index.contains_key(&(node.0, prop.id.0))
|
||||
}
|
||||
|
||||
pub fn is_animating<T>(&self, node: NodeId, prop: Prop<T>) -> bool {
|
||||
self.index.get(&(node.0, prop.id.0)).is_some_and(|&t| self.t_slot[t as usize] != NONE)
|
||||
}
|
||||
|
||||
/// True when any property track on `node` is currently active.
|
||||
pub fn is_node_animating(&self, node: NodeId) -> bool {
|
||||
let mut t = self.node_head.get(&node.0).copied().unwrap_or(NONE);
|
||||
while t != NONE {
|
||||
if self.t_slot[t as usize] != NONE {
|
||||
return true;
|
||||
}
|
||||
t = self.t_meta[t as usize].node_next;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn track_id<T>(&self, node: NodeId, prop: Prop<T>) -> Option<TrackId> {
|
||||
self.index.get(&(node.0, prop.id.0)).map(|&t| self.id_of(t as usize))
|
||||
}
|
||||
|
||||
/// Is this exact track (not a reused slot) alive?
|
||||
pub fn contains(&self, id: TrackId) -> bool {
|
||||
self.t_meta.get(id.index as usize).is_some_and(|m| m.alive && m.generation == id.generation)
|
||||
}
|
||||
|
||||
/// True once the track is at rest (or gone).
|
||||
pub fn is_settled(&self, id: TrackId) -> bool {
|
||||
!self.contains(id) || self.t_slot[id.index as usize] == NONE
|
||||
}
|
||||
|
||||
/// Bumps every time the track gets a new animation; choreography uses it to tell whether a
|
||||
/// track it started was taken over by something else.
|
||||
pub fn epoch(&self, id: TrackId) -> Option<u32> {
|
||||
self.contains(id).then(|| self.t_meta[id.index as usize].epoch)
|
||||
}
|
||||
|
||||
/// When the track's latest animation logically completes (SwiftUI `.logicallyComplete`), in
|
||||
/// the store's time. On a scaled clock it's projected at the clock's current scale; a stopped
|
||||
/// clock never gets there.
|
||||
pub fn logical_end(&self, id: TrackId) -> Option<f64> {
|
||||
let t = id.index as usize;
|
||||
self.contains(id).then(|| {
|
||||
let at = self.t_meta[t].logical_at;
|
||||
if self.t_clock[t] == 0 {
|
||||
return at;
|
||||
}
|
||||
let rem = at - self.time_of(t);
|
||||
let scale = self.clocks[self.t_clock[t] as usize].scale as f64;
|
||||
if rem <= 0.0 { self.now + rem } else if scale == 0.0 { f64::INFINITY } else { self.now + rem / scale }
|
||||
})
|
||||
}
|
||||
|
||||
/// The node and property a track belongs to.
|
||||
pub fn owner(&self, id: TrackId) -> Option<(NodeId, PropId)> {
|
||||
self.contains(id).then(|| {
|
||||
let m = &self.t_meta[id.index as usize];
|
||||
(m.node, m.prop)
|
||||
})
|
||||
}
|
||||
|
||||
/// Removes one property's track.
|
||||
pub fn remove<T>(&mut self, node: NodeId, prop: Prop<T>) {
|
||||
if let Some(t) = self.index.get(&(node.0, prop.id.0)).copied() {
|
||||
self.unlink_node(node, t);
|
||||
self.free_track(t as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every track of a node.
|
||||
pub fn remove_node(&mut self, node: NodeId) {
|
||||
if let Some(c) = self.node_clock.remove(&node.0) {
|
||||
self.release_clock(c);
|
||||
}
|
||||
let mut t = self.node_head.remove(&node.0).unwrap_or(NONE);
|
||||
while t != NONE {
|
||||
let next = self.t_meta[t as usize].node_next;
|
||||
self.free_track(t as usize);
|
||||
t = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Live tuning: every lane currently springing on `old` re-springs on `new` from where it is,
|
||||
/// at the same target (research 06 §2.6). Smooth because the swap keeps `(x, v)`.
|
||||
pub fn retune(&mut self, old: Spring, new: Spring) {
|
||||
for i in 0..self.active.len() {
|
||||
let t = self.active[i] as usize;
|
||||
let now = self.time_of(t);
|
||||
let (l0, n) = (self.t_lane0[t] as usize, self.t_n[t] as usize);
|
||||
let eps = self.t_meta[t].class.eps(self.pixel_scale);
|
||||
let mut hit = false;
|
||||
for l in l0..l0 + n {
|
||||
if self.l_curve[l] == Curve::Spring(old) {
|
||||
let target = self.l_target[l];
|
||||
self.start_lane(l, now, target, Curve::Spring(new), Blend::Merge, None, eps);
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
if hit {
|
||||
self.recompute(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! The shared motion tokens, from the motion presets (generated as
|
||||
//! `presets/generated/kit_motion.rs`). Every spring is duration + bounce, bounce 0 by default.
|
||||
//!
|
||||
//! Plain names are the enter springs; `*_EXIT` the exit springs; [`pair`] holds both.
|
||||
//! Aliases follow the JSON's `aka` lists (old palette names).
|
||||
|
||||
use crate::curve::Curve;
|
||||
use crate::easing::Easing;
|
||||
use crate::spring::{Spring, SpringPair};
|
||||
|
||||
/// Pointer-tied. Barely a spring: takes the edge off a jump without lagging the hand.
|
||||
pub const INSTANT: Spring = Spring::new(0.1, 0.0);
|
||||
pub const INSTANT_EXIT: Spring = Spring::new(0.1, 0.0);
|
||||
/// Small controls answering a click: indicators, widths that lead, exits.
|
||||
pub const SNAP: Spring = Spring::new(0.25, 0.0);
|
||||
pub const SNAP_EXIT: Spring = Spring::new(0.2, 0.0);
|
||||
/// The default state change. Arrives and stops, no drama.
|
||||
pub const SETTLE: Spring = Spring::new(0.3, 0.0);
|
||||
pub const SETTLE_EXIT: Spring = Spring::new(0.24, 0.0);
|
||||
/// Layout moving out of the way: siblings sliding into a gap, containers resizing.
|
||||
pub const REFLOW: Spring = Spring::new(0.4, 0.0);
|
||||
pub const REFLOW_EXIT: Spring = Spring::new(0.32, 0.0);
|
||||
/// Big surfaces travelling: drawers, sheets, pages.
|
||||
pub const GLIDE: Spring = Spring::new(0.32, 0.0);
|
||||
pub const GLIDE_EXIT: Spring = Spring::new(0.26, 0.0);
|
||||
/// One shape becoming another: a chip opening into its panel, a menu out of its button.
|
||||
pub const MORPH: Spring = Spring::new(0.3, 0.16);
|
||||
pub const MORPH_EXIT: Spring = Spring::new(0.27, 0.08);
|
||||
/// A release with a little life in it. Keep it to presses and confirmations.
|
||||
pub const POP: Spring = Spring::new(0.25, 0.15);
|
||||
pub const POP_EXIT: Spring = Spring::new(0.2, 0.05);
|
||||
/// Slow reveals and wipes the eye should follow, never utility UI.
|
||||
pub const DRIFT: Spring = Spring::new(0.85, 0.0);
|
||||
pub const DRIFT_EXIT: Spring = Spring::new(0.6, 0.0);
|
||||
/// Explainer camera moves (motion palette: 1.0–1.8 / 0).
|
||||
pub const CAMERA: Spring = Spring::new(1.2, 0.0);
|
||||
|
||||
// Old palette names (the JSON's `aka`).
|
||||
pub const SNAPPY: Spring = SNAP;
|
||||
pub const QUICK: Spring = SNAP;
|
||||
pub const DEFAULT: Spring = SETTLE;
|
||||
pub const CALM: Spring = REFLOW;
|
||||
pub const SMOOTH: Spring = GLIDE;
|
||||
pub const PLAYFUL: Spring = POP;
|
||||
pub const SLOW: Spring = DRIFT;
|
||||
|
||||
/// The fade that replaces travel under Reduce Motion.
|
||||
pub const REDUCED_FADE: Curve = crate::props::REDUCED_FADE;
|
||||
/// Kit's CSS enter: 150 ms `cubic-bezier(.2,.8,.2,1)`.
|
||||
pub const CSS_ENTER: Curve = Curve::Tween { duration: 0.15, easing: Easing::ENTER };
|
||||
/// Kit's CSS exit: 110 ms `cubic-bezier(.4,0,1,1)`.
|
||||
pub const CSS_EXIT: Curve = Curve::Tween { duration: 0.11, easing: Easing::EXIT };
|
||||
|
||||
/// Drag-follow lead (ω 34, ζ .86): only for opt-in follow, never the user's own hand.
|
||||
pub fn follow_lead() -> Spring {
|
||||
Spring::from_omega_zeta(34.0, 0.86)
|
||||
}
|
||||
/// Drag-follow trail (ω 25, ζ 1).
|
||||
pub fn follow_trail() -> Spring {
|
||||
Spring::from_omega_zeta(25.0, 1.0)
|
||||
}
|
||||
|
||||
/// Enter/exit pairs.
|
||||
pub mod pair {
|
||||
use super::*;
|
||||
pub const INSTANT: SpringPair = SpringPair::new(super::INSTANT, INSTANT_EXIT);
|
||||
pub const SNAP: SpringPair = SpringPair::new(super::SNAP, SNAP_EXIT);
|
||||
pub const SETTLE: SpringPair = SpringPair::new(super::SETTLE, SETTLE_EXIT);
|
||||
pub const REFLOW: SpringPair = SpringPair::new(super::REFLOW, REFLOW_EXIT);
|
||||
pub const GLIDE: SpringPair = SpringPair::new(super::GLIDE, GLIDE_EXIT);
|
||||
pub const MORPH: SpringPair = SpringPair::new(super::MORPH, MORPH_EXIT);
|
||||
pub const POP: SpringPair = SpringPair::new(super::POP, POP_EXIT);
|
||||
pub const DRIFT: SpringPair = SpringPair::new(super::DRIFT, DRIFT_EXIT);
|
||||
}
|
||||
|
||||
/// SwiftUI's named springs.
|
||||
pub mod swiftui {
|
||||
use super::Spring;
|
||||
pub const SMOOTH: Spring = Spring::SMOOTH;
|
||||
pub const SNAPPY: Spring = Spring::SNAPPY;
|
||||
pub const BOUNCY: Spring = Spring::BOUNCY;
|
||||
pub const SPRING: Spring = Spring::DEFAULT;
|
||||
}
|
||||
|
||||
/// Every token by name, for tuning panels, traces and tests.
|
||||
pub const ALL: &[(&str, SpringPair)] = &[
|
||||
("instant", pair::INSTANT),
|
||||
("snap", pair::SNAP),
|
||||
("settle", pair::SETTLE),
|
||||
("reflow", pair::REFLOW),
|
||||
("glide", pair::GLIDE),
|
||||
("morph", pair::MORPH),
|
||||
("pop", pair::POP),
|
||||
("drift", pair::DRIFT),
|
||||
];
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
//! motion-lint JSONL traces, written from what was actually presented (post-snap, post-mask), with
|
||||
//! exact "this was animated on purpose" intent bits. Same format apps write
|
||||
//! and `motion-lint analyze` reads.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::{self, Write};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::props::{NodeId, PropId, prop};
|
||||
use crate::scene::Presented;
|
||||
use crate::store::{FxMap, MotionEvent};
|
||||
|
||||
/// Delta-encoded motion-lint scalar channels. Values hold until sampled again or removed.
|
||||
#[derive(Default)]
|
||||
pub struct TraceChannels {
|
||||
ids: FxMap<String, usize>,
|
||||
channels: Vec<Channel>,
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
name: String,
|
||||
kind: String,
|
||||
value: Option<f64>,
|
||||
previous: Option<f64>,
|
||||
described: bool,
|
||||
owner: Option<(u32, &'static str)>,
|
||||
}
|
||||
|
||||
impl TraceChannels {
|
||||
/// `kind` is motion-lint's `position`, `level`, or `phase`. Non-finite samples are ignored.
|
||||
pub fn sample(&mut self, name: &str, kind: &str, value: f32) {
|
||||
if !value.is_finite() { return; }
|
||||
assert!(matches!(kind, "position" | "level" | "phase"), "unknown trace channel kind");
|
||||
let i = if let Some(&i) = self.ids.get(name) { i } else {
|
||||
let i = self.channels.len();
|
||||
self.ids.insert(name.to_owned(), i);
|
||||
self.channels.push(Channel { name: name.to_owned(), kind: kind.to_owned(), value: None, previous: None, described: false, owner: None });
|
||||
i
|
||||
};
|
||||
let channel = &mut self.channels[i];
|
||||
if channel.kind != kind { channel.kind = kind.to_owned(); channel.described = false; }
|
||||
channel.value = Some((f64::from(value) * 1e4).round() / 1e4);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, name: &str) {
|
||||
if let Some(&i) = self.ids.get(name) { self.channels[i].value = None; }
|
||||
}
|
||||
|
||||
/// Associates an effect channel with its element for visibility gating.
|
||||
pub fn owner(&mut self, name: &str, owner: u32, unit: &'static str) {
|
||||
if let Some(&i) = self.ids.get(name) {
|
||||
let channel = &mut self.channels[i];
|
||||
if channel.owner != Some((owner, unit)) { channel.owner = Some((owner, unit)); channel.described = false; }
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends optional `cm`, `c`, and `cg` fields to an open JSON object.
|
||||
pub fn write_json(&mut self, line: &mut String) {
|
||||
let mut metas = String::new();
|
||||
let mut values = String::new();
|
||||
let mut gone = String::new();
|
||||
for (i, channel) in self.channels.iter_mut().enumerate() {
|
||||
let id = i + 1;
|
||||
if let Some(value) = channel.value {
|
||||
if !channel.described {
|
||||
if !metas.is_empty() { metas.push(','); }
|
||||
write!(metas, r#"{{"id":{id},"name":{},"kind":{}"#, json_str(&channel.name), json_str(&channel.kind)).ok();
|
||||
if let Some((owner, unit)) = channel.owner { write!(metas, r#", "owner":{owner},"unit":{}"#, json_str(unit)).ok(); }
|
||||
metas.push('}');
|
||||
channel.described = true;
|
||||
}
|
||||
if channel.previous != Some(value) {
|
||||
if !values.is_empty() { values.push(','); }
|
||||
write!(values, "[{id},{value}]").ok();
|
||||
}
|
||||
} else if channel.previous.is_some() {
|
||||
if !gone.is_empty() { gone.push(','); }
|
||||
write!(gone, "{id}").ok();
|
||||
}
|
||||
channel.previous = channel.value;
|
||||
}
|
||||
for (key, values) in [("cm", metas), ("c", values), ("cg", gone)] {
|
||||
if !values.is_empty() { write!(line, r#",{key:?}:[{values}]"#).ok(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// motion-lint element flag bits (motion-lint's `Flags`).
|
||||
pub mod flags {
|
||||
pub const ANIMATED: u32 = 1;
|
||||
pub const ANCESTOR_ANIMATED: u32 = 2;
|
||||
pub const SCROLLING: u32 = 4;
|
||||
pub const CLIPPED: u32 = 8;
|
||||
pub const FILTERED: u32 = 16;
|
||||
/// Runs a loop of its own (`El::looping`: a spinner, a sheen, a busy ring's dots), whose
|
||||
/// wraps and turns are its design, however briefly it shows.
|
||||
pub const LOOPING: u32 = 32;
|
||||
/// Draws nothing and holds nothing: a hit or hover zone, a spacer.
|
||||
pub const BLANK: u32 = 64;
|
||||
}
|
||||
|
||||
/// motion-lint intent classes (motion-lint's `Intent`): in flags at `<< 8` (own) and `<< 16`
|
||||
/// (ancestor), and in `ai` intent records.
|
||||
pub struct Intent;
|
||||
|
||||
impl Intent {
|
||||
pub const POSITION: u32 = 1;
|
||||
pub const SIZE: u32 = 2;
|
||||
pub const OPACITY: u32 = 4;
|
||||
pub const SHAPE: u32 = 8;
|
||||
pub const TRANSITION: u32 = 16;
|
||||
pub const REVEAL: u32 = 32;
|
||||
pub const CONTENTS: u32 = 64;
|
||||
|
||||
/// The intent class a built-in property's animation declares.
|
||||
pub fn for_prop(p: PropId) -> u32 {
|
||||
match p {
|
||||
x if x == prop::FRAME.id || x == prop::TRAVEL.id => Self::POSITION | Self::SIZE,
|
||||
x if x == prop::OFFSET.id || x == prop::ROTATION.id || x == prop::SCROLL.id => Self::POSITION,
|
||||
x if x == prop::OPACITY.id => Self::OPACITY,
|
||||
x if x == prop::SCALE.id => Self::SIZE | Self::TRANSITION,
|
||||
x if x == prop::BLUR.id => Self::TRANSITION,
|
||||
x if x == prop::RADIUS.id => Self::SHAPE,
|
||||
x if x == prop::FILL.id => Self::CONTENTS,
|
||||
x if x == prop::MASK.id => Self::REVEAL,
|
||||
x if x == prop::PRESENCE.id => Self::TRANSITION | Self::OPACITY,
|
||||
_ => Self::CONTENTS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace's header line.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TraceHeader {
|
||||
pub launch: String,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub hz: f32,
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
/// A `Write` that keeps everything in shared memory, for tests (`trace.contents()`).
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SharedBuffer(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl SharedBuffer {
|
||||
pub fn contents(&self) -> String {
|
||||
String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for SharedBuffer {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one JSONL line per frame. Only elements whose presented state changed are written;
|
||||
/// unmounted ones go in `g`.
|
||||
pub struct MotionTrace {
|
||||
out: Box<dyn Write + Send>,
|
||||
ids: FxMap<u64, u32>,
|
||||
states: FxMap<u32, [f32; 12]>,
|
||||
last_t: Option<f64>,
|
||||
hz: f64,
|
||||
time_scale: f32,
|
||||
line: String,
|
||||
names: FxMap<u64, &'static str>,
|
||||
described: FxMap<u64, (Option<&'static str>, Option<(&'static str, &'static str)>)>,
|
||||
namespaces: FxMap<u64, (&'static str, &'static str)>,
|
||||
class: String,
|
||||
host: String,
|
||||
channels: TraceChannels,
|
||||
events: Vec<String>,
|
||||
}
|
||||
|
||||
impl MotionTrace {
|
||||
pub fn new(out: impl Write + Send + 'static, header: &TraceHeader) -> io::Result<MotionTrace> {
|
||||
let mut out: Box<dyn Write + Send> = Box::new(io::BufWriter::new(out));
|
||||
writeln!(
|
||||
out,
|
||||
r#"{{"type":"header","launch":{},"width":{},"height":{},"hz":{},"scale":{},"platform":"rune","units":"pt","clock":"virtual"}}"#,
|
||||
json_str(&header.launch),
|
||||
header.width,
|
||||
header.height,
|
||||
header.hz,
|
||||
header.scale
|
||||
)?;
|
||||
Ok(MotionTrace {
|
||||
out,
|
||||
ids: FxMap::default(),
|
||||
states: FxMap::default(),
|
||||
last_t: None,
|
||||
hz: header.hz.max(1.0) as f64,
|
||||
time_scale: 1.0,
|
||||
line: String::new(),
|
||||
names: FxMap::default(),
|
||||
described: FxMap::default(),
|
||||
namespaces: FxMap::default(),
|
||||
class: "rune".into(),
|
||||
host: "scene".into(),
|
||||
channels: TraceChannels::default(),
|
||||
events: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens `$RUNE_MOTION_TRACE` if it is set (one env read).
|
||||
pub fn from_env(header: &TraceHeader) -> Option<MotionTrace> {
|
||||
let path = std::env::var_os("RUNE_MOTION_TRACE")?;
|
||||
let file = std::fs::File::create(path).ok()?;
|
||||
MotionTrace::new(file, header).ok()
|
||||
}
|
||||
|
||||
/// An in-memory trace and a handle to read it back.
|
||||
pub fn in_memory(header: &TraceHeader) -> (MotionTrace, SharedBuffer) {
|
||||
let buf = SharedBuffer::default();
|
||||
(MotionTrace::new(buf.clone(), header).expect("in-memory write"), buf)
|
||||
}
|
||||
|
||||
/// The clock's time scale, written as `sc` so motion-lint counts the app's own frames.
|
||||
pub fn set_time_scale(&mut self, sc: f32) {
|
||||
self.time_scale = sc;
|
||||
}
|
||||
|
||||
/// Set before the first frame when comparing against another host (for example `pill`).
|
||||
pub fn host(mut self, host: impl Into<String>) -> Self {
|
||||
self.host = host.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// The comparison class. motion-lint pairs named elements by both `nm` and `cls`.
|
||||
/// Use the reference writer's class (e.g. `gpui`) for cross-renderer comparisons.
|
||||
pub fn class(mut self, class: impl Into<String>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Overrides this node's class and host; None restores the writer's defaults.
|
||||
pub fn namespace(&mut self, node: NodeId, namespace: Option<(&'static str, &'static str)>) -> bool {
|
||||
if let Some(namespace) = namespace { self.namespaces.insert(node.0, namespace) != Some(namespace) }
|
||||
else { self.namespaces.remove(&node.0).is_some() }
|
||||
}
|
||||
|
||||
/// Stable display name, independent of reconciliation identity. None restores the NodeId.
|
||||
pub fn name(&mut self, node: NodeId, name: Option<&'static str>) -> bool {
|
||||
if let Some(name) = name { self.names.insert(node.0, name) != Some(name) }
|
||||
else { self.names.remove(&node.0).is_some() }
|
||||
}
|
||||
|
||||
pub fn channel(&mut self, name: &str, kind: &str, value: f32) {
|
||||
self.channels.sample(name, kind, value);
|
||||
}
|
||||
|
||||
pub fn remove_channel(&mut self, name: &str) { self.channels.remove(name); }
|
||||
|
||||
/// Recorded once, on the next frame. `format_args!` avoids eager string allocation.
|
||||
pub fn event(&mut self, event: impl std::fmt::Display) { self.events.push(event.to_string()); }
|
||||
|
||||
fn id(&mut self, node: NodeId) -> u32 {
|
||||
let next = self.ids.len() as u32 + 1;
|
||||
*self.ids.entry(node.0).or_insert(next)
|
||||
}
|
||||
|
||||
/// Writes one frame. `t` is animation time in seconds.
|
||||
pub fn frame(
|
||||
&mut self,
|
||||
t: f64,
|
||||
presented: &[Presented],
|
||||
gone: &[NodeId],
|
||||
events: &[MotionEvent],
|
||||
intents: &[(NodeId, u32, f32)],
|
||||
) {
|
||||
let t_ms = t * 1000.0;
|
||||
let n = self.last_t.map_or(1, |last| (((t_ms - last) / (1000.0 / self.hz)).round().max(1.0)) as u64);
|
||||
self.last_t = Some(t_ms);
|
||||
let mut line = std::mem::take(&mut self.line);
|
||||
line.clear();
|
||||
write!(line, r#"{{"t":{},"n":{},"sc":{}"#, r3(t_ms), n, self.time_scale).ok();
|
||||
if !events.is_empty() || !self.events.is_empty() {
|
||||
line.push_str(r#","ev":["#);
|
||||
for (k, e) in events.iter().enumerate() {
|
||||
if k > 0 {
|
||||
line.push(',');
|
||||
}
|
||||
let s = match *e {
|
||||
MotionEvent::Settled { node, prop, .. } => format!("settled {}:{}", node.0, prop.0),
|
||||
MotionEvent::Completed { token, finished, .. } => {
|
||||
format!("completed #{token}{}", if finished { "" } else { " (replaced)" })
|
||||
}
|
||||
};
|
||||
line.push_str(&json_str(&s));
|
||||
}
|
||||
for (k, event) in self.events.drain(..).enumerate() {
|
||||
if k > 0 || !events.is_empty() { line.push(','); }
|
||||
line.push_str(&json_str(&event));
|
||||
}
|
||||
line.push(']');
|
||||
}
|
||||
let mut metas = String::new();
|
||||
let mut elems = String::new();
|
||||
for p in presented {
|
||||
let id = self.id(p.node);
|
||||
let name = self.names.get(&p.node.0).copied();
|
||||
let namespace = self.namespaces.get(&p.node.0).copied();
|
||||
if self.described.insert(p.node.0, (name, namespace)) != Some((name, namespace)) {
|
||||
if !metas.is_empty() {
|
||||
metas.push(',');
|
||||
}
|
||||
let name = name.map_or_else(|| p.node.0.to_string(), str::to_owned);
|
||||
let (class, host) = namespace.unwrap_or((&self.class, &self.host));
|
||||
write!(metas, r#"{{"id":{id},"cls":{},"nm":{},"host":{}"#, json_str(class), json_str(&name), json_str(host)).ok();
|
||||
if let Some(parent) = p.parent {
|
||||
let pv = self.id(parent);
|
||||
write!(metas, r#","pv":{pv}"#).ok();
|
||||
}
|
||||
metas.push('}');
|
||||
}
|
||||
let r = p.rect;
|
||||
let ins = p.mask.inset.0;
|
||||
let mut s = [r.x, r.y, r.w, r.h, p.opacity, p.radius.0[0], p.flags as f32, f32::NAN, 0.0, 0.0, 0.0, 0.0];
|
||||
if ins.iter().any(|&v| v > 0.25) {
|
||||
s[7] = r.x + ins[0];
|
||||
s[8] = r.y + ins[1];
|
||||
s[9] = (r.w - ins[0] - ins[2]).max(0.0);
|
||||
s[10] = (r.h - ins[1] - ins[3]).max(0.0);
|
||||
}
|
||||
let rounded = s.map(|v| if v.is_nan() { v } else { (v * 100.0).round() / 100.0 });
|
||||
if self.states.get(&id).is_some_and(|old| same(old, &rounded)) {
|
||||
continue;
|
||||
}
|
||||
self.states.insert(id, rounded);
|
||||
if !elems.is_empty() {
|
||||
elems.push(',');
|
||||
}
|
||||
write!(
|
||||
elems,
|
||||
"[{id},{},{},{},{},{},{},{}",
|
||||
r2(r.x),
|
||||
r2(r.y),
|
||||
r2(r.w),
|
||||
r2(r.h),
|
||||
r3(p.opacity as f64),
|
||||
r2(p.radius.0[0]),
|
||||
p.flags
|
||||
).ok();
|
||||
if !s[7].is_nan() {
|
||||
write!(elems, ",{},{},{},{}", r2(s[7]), r2(s[8]), r2(s[9]), r2(s[10])).ok();
|
||||
}
|
||||
elems.push(']');
|
||||
}
|
||||
if !intents.is_empty() {
|
||||
line.push_str(r#","ai":["#);
|
||||
for (k, &(node, bits, secs)) in intents.iter().enumerate() {
|
||||
let id = self.id(node);
|
||||
let rect = presented.iter().find(|p| p.node == node).map(|p| p.rect).unwrap_or_default();
|
||||
if k > 0 {
|
||||
line.push(',');
|
||||
}
|
||||
write!(
|
||||
line,
|
||||
"[{id},{},{},{},{},{bits},{}]",
|
||||
r2(rect.x),
|
||||
r2(rect.y),
|
||||
r2(rect.w),
|
||||
r2(rect.h),
|
||||
(secs * 1000.0).round()
|
||||
).ok();
|
||||
}
|
||||
line.push(']');
|
||||
}
|
||||
if !metas.is_empty() {
|
||||
write!(line, r#","m":[{metas}]"#).ok();
|
||||
}
|
||||
if !elems.is_empty() {
|
||||
write!(line, r#","e":[{elems}]"#).ok();
|
||||
}
|
||||
if !gone.is_empty() {
|
||||
line.push_str(r#","g":["#);
|
||||
for (k, node) in gone.iter().enumerate() {
|
||||
let id = self.id(*node);
|
||||
self.states.remove(&id);
|
||||
if k > 0 {
|
||||
line.push(',');
|
||||
}
|
||||
write!(line, "{id}").ok();
|
||||
}
|
||||
line.push(']');
|
||||
}
|
||||
self.channels.write_json(&mut line);
|
||||
line.push('}');
|
||||
writeln!(self.out, "{line}").ok();
|
||||
self.line = line;
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) -> io::Result<()> {
|
||||
self.out.flush()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MotionTrace {
|
||||
fn drop(&mut self) {
|
||||
self.out.flush().ok();
|
||||
}
|
||||
}
|
||||
|
||||
fn same(a: &[f32; 12], b: &[f32; 12]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| x == y || (x.is_nan() && y.is_nan()))
|
||||
}
|
||||
|
||||
fn r2(v: f32) -> f64 {
|
||||
(v as f64 * 100.0).round() / 100.0
|
||||
}
|
||||
|
||||
fn r3(v: f64) -> f64 {
|
||||
(v * 1000.0).round() / 1000.0
|
||||
}
|
||||
|
||||
fn json_str(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() + 2);
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
c if (c as u32) < 0x20 => {
|
||||
write!(out, "\\u{:04x}", c as u32).ok();
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
//! SwiftUI-style composable transitions, as data the scene evaluates and the renderer draws.
|
||||
//!
|
||||
//! An [`Effect`] is what a node looks like when fully *absent*; presence progress `p` blends it
|
||||
//! toward identity (`p = 1`). Transitions pair an insertion and a removal effect.
|
||||
|
||||
use crate::spring::SpringPair;
|
||||
use crate::tokens;
|
||||
use crate::value::Vec2;
|
||||
|
||||
/// A side of a node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Edge {
|
||||
Leading,
|
||||
Trailing,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
/// Unit direction pointing out of the node through this edge (LTR).
|
||||
pub fn direction(self) -> Vec2 {
|
||||
match self {
|
||||
Edge::Leading => Vec2::new(-1.0, 0.0),
|
||||
Edge::Trailing => Vec2::new(1.0, 0.0),
|
||||
Edge::Top => Vec2::new(0.0, -1.0),
|
||||
Edge::Bottom => Vec2::new(0.0, 1.0),
|
||||
}
|
||||
}
|
||||
pub fn opposite(self) -> Edge {
|
||||
match self {
|
||||
Edge::Leading => Edge::Trailing,
|
||||
Edge::Trailing => Edge::Leading,
|
||||
Edge::Top => Edge::Bottom,
|
||||
Edge::Bottom => Edge::Top,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A soft-edged wipe: the mask's `edge` side is inset by `(1 − p) ×` the node's size, with a
|
||||
/// `feather`-point gradient ramp (Kit rule 11: no hard edges).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Reveal {
|
||||
/// The side the content is hidden behind when absent (it grows away from the opposite side).
|
||||
pub edge: Edge,
|
||||
pub feather: f32,
|
||||
}
|
||||
|
||||
/// What an absent node looks like. Every field's identity value means "no change".
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Effect {
|
||||
/// Opacity multiplier when absent (identity 1).
|
||||
pub opacity: f32,
|
||||
/// Uniform scale when absent (identity 1). Kept within [0.9, 1.1], or
|
||||
/// [[`SMALL_SCALE_FLOOR`], 1.1] with `small_scale`: never scale to or from 0.
|
||||
pub scale: f32,
|
||||
/// Scale anchor in unit coordinates of the node (0.5, 0.5 = centre).
|
||||
pub anchor: Vec2,
|
||||
/// Offset in points when absent.
|
||||
pub offset: Vec2,
|
||||
/// Offset in fractions of the node's own size when absent (`.move(edge)`, `.push`).
|
||||
pub offset_fraction: Vec2,
|
||||
/// Gaussian blur sigma in points when absent (identity 0). At most 4; in-place replacement only.
|
||||
pub blur: f32,
|
||||
pub reveal: Option<Reveal>,
|
||||
/// Lets `scale` go down to [`SMALL_SCALE_FLOOR`] instead of 0.9, for small glyphs
|
||||
/// ([`Transition::allow_small_scale`]).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub small_scale: bool,
|
||||
/// How much of the node's own shape is drawn when absent (identity 1): its strokes trace on
|
||||
/// along their length in order, and each fill fades in as the drawing reaches it
|
||||
/// ([`Transition::draw`]). Under Reduce Motion it is drawn whole.
|
||||
#[cfg_attr(feature = "serde", serde(default = "drawn_whole"))]
|
||||
pub draw: f32,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn drawn_whole() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
/// The smallest scale a transition with [`Transition::allow_small_scale`] starts or ends at.
|
||||
/// Below it a glyph reads as appearing from a point, which the scale rule exists to avoid.
|
||||
pub const SMALL_SCALE_FLOOR: f32 = 0.5;
|
||||
|
||||
impl Default for Effect {
|
||||
fn default() -> Self {
|
||||
Effect::IDENTITY
|
||||
}
|
||||
}
|
||||
|
||||
impl Effect {
|
||||
pub const IDENTITY: Effect = Effect {
|
||||
opacity: 1.0,
|
||||
scale: 1.0,
|
||||
anchor: Vec2 { x: 0.5, y: 0.5 },
|
||||
offset: Vec2::ZERO,
|
||||
offset_fraction: Vec2::ZERO,
|
||||
blur: 0.0,
|
||||
reveal: None,
|
||||
small_scale: false,
|
||||
draw: 1.0,
|
||||
};
|
||||
|
||||
pub fn opacity(opacity: f32) -> Effect {
|
||||
Effect { opacity, ..Effect::IDENTITY }
|
||||
}
|
||||
pub fn scale(scale: f32) -> Effect {
|
||||
Effect { scale, ..Effect::IDENTITY }
|
||||
}
|
||||
pub fn blur(sigma: f32) -> Effect {
|
||||
Effect { blur: sigma, ..Effect::IDENTITY }
|
||||
}
|
||||
|
||||
/// Both effects at once: opacities and scales multiply, offsets add, blur takes the max.
|
||||
pub fn combined(self, o: Effect) -> Effect {
|
||||
Effect {
|
||||
opacity: self.opacity * o.opacity,
|
||||
scale: self.scale * o.scale,
|
||||
anchor: if self.scale != 1.0 { self.anchor } else { o.anchor },
|
||||
offset: Vec2::new(self.offset.x + o.offset.x, self.offset.y + o.offset.y),
|
||||
offset_fraction: Vec2::new(
|
||||
self.offset_fraction.x + o.offset_fraction.x,
|
||||
self.offset_fraction.y + o.offset_fraction.y,
|
||||
),
|
||||
blur: self.blur.max(o.blur),
|
||||
reveal: self.reveal.or(o.reveal),
|
||||
small_scale: self.small_scale || o.small_scale,
|
||||
draw: self.draw * o.draw,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn travels(&self) -> bool {
|
||||
self.offset != Vec2::ZERO || self.offset_fraction != Vec2::ZERO
|
||||
}
|
||||
|
||||
/// Kit's rules, enforced: scale in [0.9, 1.1] (never to or from 0; down to
|
||||
/// [`SMALL_SCALE_FLOOR`] with `small_scale`), blur sigma ≤ 4 pt, no blur on anything that
|
||||
/// travels (sliding content stays sharp), and nothing leaves at full opacity.
|
||||
/// Whether the node looks the same absent as present: no fade, scale, offset, blur, reveal
|
||||
/// or drawing (the anchor alone moves nothing).
|
||||
pub fn shows_nothing(&self) -> bool {
|
||||
Effect { anchor: Effect::IDENTITY.anchor, small_scale: false, ..*self } == Effect::IDENTITY
|
||||
}
|
||||
|
||||
pub fn kit_rules(mut self, removal: bool) -> Effect {
|
||||
let floor = if self.small_scale { SMALL_SCALE_FLOOR } else { 0.9 };
|
||||
self.scale = self.scale.clamp(floor, 1.1);
|
||||
self.blur = if self.travels() { 0.0 } else { self.blur.clamp(0.0, 4.0) };
|
||||
self.opacity = self.opacity.clamp(0.0, 1.0);
|
||||
self.draw = self.draw.clamp(0.0, 1.0);
|
||||
if removal {
|
||||
self.opacity = 0.0;
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Insertion and removal effects plus how the node behaves while it leaves.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Transition {
|
||||
pub insertion: Effect,
|
||||
pub removal: Effect,
|
||||
/// Motion's `AnimatePresence mode="popLayout"`: an exiting node leaves layout flow at once
|
||||
/// (siblings reflow while it fades in place). The default.
|
||||
pub pop_layout: bool,
|
||||
/// Enter and exit springs. Exits run 10–25 % shorter.
|
||||
pub springs: SpringPair,
|
||||
}
|
||||
|
||||
impl Default for Transition {
|
||||
fn default() -> Self {
|
||||
Transition::opacity()
|
||||
}
|
||||
}
|
||||
|
||||
impl Transition {
|
||||
fn symmetric(e: Effect) -> Transition {
|
||||
Transition { insertion: e, removal: e, pop_layout: true, springs: tokens::pair::SETTLE }
|
||||
}
|
||||
|
||||
/// No visual change (presence still holds removal until its fade settles).
|
||||
pub fn identity() -> Transition {
|
||||
Transition::symmetric(Effect::IDENTITY)
|
||||
}
|
||||
/// No motion at all: a node shows whole the frame it mounts and is gone the frame it's
|
||||
/// removed, through the usual presence lifecycle (it exits invisible and inert, then
|
||||
/// unmounts, and focus returns as for any transition). Unlike `Tx::instant`, the rest of
|
||||
/// the change still animates; unlike a very short spring, Reduce Motion doesn't stretch it
|
||||
/// into a fade that keeps the node on screen.
|
||||
pub fn none() -> Transition {
|
||||
Transition::identity().springs(SpringPair::NONE)
|
||||
}
|
||||
/// `.opacity`.
|
||||
pub fn opacity() -> Transition {
|
||||
Transition::symmetric(Effect::opacity(0.0))
|
||||
}
|
||||
/// `.scale(s)` about the centre, plus a fade.
|
||||
pub fn scale(scale: f32) -> Transition {
|
||||
Transition::symmetric(Effect { scale, opacity: 0.0, ..Effect::IDENTITY })
|
||||
}
|
||||
/// `.scale(s, anchor:)`.
|
||||
pub fn scale_anchor(scale: f32, anchor: Vec2) -> Transition {
|
||||
Transition::symmetric(Effect { scale, anchor, opacity: 0.0, ..Effect::IDENTITY })
|
||||
}
|
||||
/// `.offset(x:y:)`.
|
||||
pub fn offset(x: f32, y: f32) -> Transition {
|
||||
Transition::symmetric(Effect { offset: Vec2::new(x, y), ..Effect::IDENTITY })
|
||||
}
|
||||
/// `.move(edge:)`: in from and out to `edge`, by the node's full size.
|
||||
pub fn move_edge(edge: Edge) -> Transition {
|
||||
Transition::symmetric(Effect { offset_fraction: edge.direction(), ..Effect::IDENTITY })
|
||||
}
|
||||
/// `.push(from:)`: in from `edge`, out through the opposite edge, fading.
|
||||
pub fn push(edge: Edge) -> Transition {
|
||||
let e = |d: Edge| Effect { offset_fraction: d.direction(), opacity: 0.0, ..Effect::IDENTITY };
|
||||
Transition { insertion: e(edge), removal: e(edge.opposite()), ..Transition::symmetric(Effect::IDENTITY) }
|
||||
}
|
||||
/// `.slide`: in from the leading edge, out through the trailing edge.
|
||||
pub fn slide() -> Transition {
|
||||
let e = |d: Edge| Effect { offset_fraction: d.direction(), ..Effect::IDENTITY };
|
||||
Transition { insertion: e(Edge::Leading), removal: e(Edge::Trailing), ..Transition::symmetric(Effect::IDENTITY) }
|
||||
}
|
||||
/// `.blurReplace`: whole-element in-place replacement: sigma 1.5 pt, scale .96, fade.
|
||||
/// The old 4 pt shape-edge ramp left glyphs sharp; it is not equivalent to sigma 4.
|
||||
/// This preset stays within the two-pass Gaussian path at 1×/2×. Explicit `blur(sigma)`
|
||||
/// remains available for stronger effects.
|
||||
pub fn blur_replace() -> Transition {
|
||||
Transition::symmetric(Effect { opacity: 0.0, scale: 0.96, blur: 1.5, ..Effect::IDENTITY })
|
||||
}
|
||||
/// Gaussian blur (sigma in points) and fade only.
|
||||
pub fn blur(sigma: f32) -> Transition {
|
||||
Transition::symmetric(Effect { opacity: 0.0, blur: sigma, ..Effect::IDENTITY })
|
||||
}
|
||||
/// A shape that draws itself on, as a connector draws from its source to its target: its
|
||||
/// strokes trace from their first point to their last, one after another, and each fill (an
|
||||
/// arrowhead) fades in as the line reaches it. Applies to the node's own shape (`canvas`)
|
||||
/// only; children enter by their own transitions.
|
||||
pub fn draw() -> Transition {
|
||||
Transition::symmetric(Effect { draw: 0.0, ..Effect::IDENTITY })
|
||||
}
|
||||
/// A soft-edged wipe from `edge` (mask reveal), 24 pt feather.
|
||||
pub fn reveal(edge: Edge) -> Transition {
|
||||
Transition::symmetric(Effect { reveal: Some(Reveal { edge, feather: 24.0 }), ..Effect::IDENTITY })
|
||||
}
|
||||
/// `.asymmetric(insertion:removal:)`.
|
||||
pub fn asymmetric(insertion: Transition, removal: Transition) -> Transition {
|
||||
Transition { insertion: insertion.insertion, removal: removal.removal, ..insertion }
|
||||
}
|
||||
/// `.combined(with:)`.
|
||||
pub fn combined(self, other: Transition) -> Transition {
|
||||
Transition {
|
||||
insertion: self.insertion.combined(other.insertion),
|
||||
removal: self.removal.combined(other.removal),
|
||||
..self
|
||||
}
|
||||
}
|
||||
pub fn springs(mut self, springs: SpringPair) -> Transition {
|
||||
self.springs = springs;
|
||||
self
|
||||
}
|
||||
/// Lets this transition's scale go below 0.9, down to [`SMALL_SCALE_FLOOR`] (0.5), for a
|
||||
/// small glyph such as an icon in a button, which barely seems to move at 0.9:
|
||||
/// `Transition::scale(0.6).allow_small_scale()`. Larger elements keep the default range, and
|
||||
/// nothing scales to or from 0.
|
||||
pub fn allow_small_scale(mut self) -> Transition {
|
||||
self.insertion.small_scale = true;
|
||||
self.removal.small_scale = true;
|
||||
self
|
||||
}
|
||||
/// Keep the exiting node in flow (its slot collapses as it leaves) instead of popping it out.
|
||||
pub fn hold_layout(mut self) -> Transition {
|
||||
self.pop_layout = false;
|
||||
self
|
||||
}
|
||||
}
|
||||
+432
@@ -0,0 +1,432 @@
|
||||
//! Values that can animate: anything that maps to a fixed number of independent `f32` lanes.
|
||||
//!
|
||||
//! Each lane springs independently on the same timing, so a `Rect` is four edge springs and a
|
||||
//! `Color` is four premultiplied-OKLab springs. Lanes are what the store keeps in its flat arrays.
|
||||
|
||||
/// Most lanes a single animated value may have.
|
||||
pub const MAX_LANES: usize = 16;
|
||||
|
||||
/// A value made of `LANES` independent scalar lanes (a vector space).
|
||||
pub trait Animatable: Copy {
|
||||
const LANES: usize;
|
||||
fn write_lanes(&self, out: &mut [f32]);
|
||||
fn read_lanes(lanes: &[f32]) -> Self;
|
||||
|
||||
fn add(self, other: Self) -> Self {
|
||||
zip(self, other, |a, b| a + b)
|
||||
}
|
||||
fn sub(self, other: Self) -> Self {
|
||||
zip(self, other, |a, b| a - b)
|
||||
}
|
||||
fn scale(self, k: f32) -> Self {
|
||||
zip(self, self, |a, _| a * k)
|
||||
}
|
||||
/// Euclidean distance in lane space.
|
||||
fn distance(self, other: Self) -> f32 {
|
||||
let (a, b) = (lanes(&self), lanes(&other));
|
||||
(0..Self::LANES).map(|i| (a[i] - b[i]) * (a[i] - b[i])).sum::<f32>().sqrt()
|
||||
}
|
||||
/// `self + (other − self) · t` in lane space.
|
||||
fn lerp(self, other: Self, t: f32) -> Self {
|
||||
zip(self, other, |a, b| a + (b - a) * t)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lanes<T: Animatable>(v: &T) -> [f32; MAX_LANES] {
|
||||
assert!(T::LANES <= MAX_LANES, "at most {MAX_LANES} lanes");
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
v.write_lanes(&mut out[..T::LANES]);
|
||||
out
|
||||
}
|
||||
|
||||
fn zip<T: Animatable>(a: T, b: T, f: impl Fn(f32, f32) -> f32) -> T {
|
||||
let (x, y) = (lanes(&a), lanes(&b));
|
||||
let mut out = [0.0; MAX_LANES];
|
||||
for i in 0..T::LANES {
|
||||
out[i] = f(x[i], y[i]);
|
||||
}
|
||||
T::read_lanes(&out[..T::LANES])
|
||||
}
|
||||
|
||||
impl Animatable for f32 {
|
||||
const LANES: usize = 1;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[0] = *self;
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
l[0]
|
||||
}
|
||||
}
|
||||
|
||||
/// A 2D point, size or offset in points.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Vec2 {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
impl Vec2 {
|
||||
pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
|
||||
pub const fn new(x: f32, y: f32) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
impl Animatable for Vec2 {
|
||||
const LANES: usize = 2;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[0] = self.x;
|
||||
out[1] = self.y;
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
Vec2 { x: l[0], y: l[1] }
|
||||
}
|
||||
}
|
||||
|
||||
/// An axis-aligned rectangle. It animates as its four **edges** (left, top, right, bottom), so an
|
||||
/// edge that doesn't move has no motion at all and can't jiggle (research 06 §2.7).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
pub const ZERO: Rect = Rect { x: 0.0, y: 0.0, w: 0.0, h: 0.0 };
|
||||
pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Rect {
|
||||
Rect { x, y, w, h }
|
||||
}
|
||||
pub fn from_edges(left: f32, top: f32, right: f32, bottom: f32) -> Rect {
|
||||
Rect { x: left, y: top, w: right - left, h: bottom - top }
|
||||
}
|
||||
pub fn right(&self) -> f32 {
|
||||
self.x + self.w
|
||||
}
|
||||
pub fn bottom(&self) -> f32 {
|
||||
self.y + self.h
|
||||
}
|
||||
pub fn edges(&self) -> [f32; 4] {
|
||||
[self.x, self.y, self.right(), self.bottom()]
|
||||
}
|
||||
pub fn origin(&self) -> Vec2 {
|
||||
Vec2::new(self.x, self.y)
|
||||
}
|
||||
pub fn size(&self) -> Vec2 {
|
||||
Vec2::new(self.w, self.h)
|
||||
}
|
||||
pub fn center(&self) -> Vec2 {
|
||||
Vec2::new(self.x + self.w * 0.5, self.y + self.h * 0.5)
|
||||
}
|
||||
pub fn translated(&self, d: Vec2) -> Rect {
|
||||
Rect { x: self.x + d.x, y: self.y + d.y, ..*self }
|
||||
}
|
||||
pub fn inflate(self, m: f32) -> Rect {
|
||||
Rect { x: self.x - m, y: self.y - m, w: self.w + 2.0 * m, h: self.h + 2.0 * m }
|
||||
}
|
||||
pub fn union(self, o: Rect) -> Rect {
|
||||
let x0 = self.x.min(o.x);
|
||||
let y0 = self.y.min(o.y);
|
||||
let x1 = (self.x + self.w).max(o.x + o.w);
|
||||
let y1 = (self.y + self.h).max(o.y + o.h);
|
||||
Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||
}
|
||||
pub fn from_points(a: [f32; 2], b: [f32; 2]) -> Rect {
|
||||
let x0 = a[0].min(b[0]);
|
||||
let y0 = a[1].min(b[1]);
|
||||
Rect { x: x0, y: y0, w: (a[0] - b[0]).abs(), h: (a[1] - b[1]).abs() }
|
||||
}
|
||||
pub fn xywh(self) -> [f32; 4] {
|
||||
[self.x, self.y, self.w, self.h]
|
||||
}
|
||||
}
|
||||
|
||||
impl Animatable for Rect {
|
||||
const LANES: usize = 4;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[..4].copy_from_slice(&self.edges());
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
Rect::from_edges(l[0], l[1], l[2], l[3])
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-corner radii: top-left, top-right, bottom-right, bottom-left.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Corners(pub [f32; 4]);
|
||||
|
||||
impl Corners {
|
||||
pub const ZERO: Corners = Corners([0.0; 4]);
|
||||
pub const fn all(r: f32) -> Corners {
|
||||
Corners([r; 4])
|
||||
}
|
||||
}
|
||||
|
||||
impl Animatable for Corners {
|
||||
const LANES: usize = 4;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[..4].copy_from_slice(&self.0);
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
Corners([l[0], l[1], l[2], l[3]])
|
||||
}
|
||||
}
|
||||
|
||||
/// Insets per side (left, top, right, bottom): mask insets and feathers.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Sides(pub [f32; 4]);
|
||||
|
||||
impl Sides {
|
||||
pub const ZERO: Sides = Sides([0.0; 4]);
|
||||
pub const fn all(v: f32) -> Sides {
|
||||
Sides([v; 4])
|
||||
}
|
||||
}
|
||||
|
||||
impl Animatable for Sides {
|
||||
const LANES: usize = 4;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[..4].copy_from_slice(&self.0);
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
Sides([l[0], l[1], l[2], l[3]])
|
||||
}
|
||||
}
|
||||
|
||||
/// A Gaussian blur sigma (standard deviation) in points.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Blur(pub f32);
|
||||
|
||||
impl Animatable for Blur {
|
||||
const LANES: usize = 1;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[0] = self.0;
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
Blur(l[0])
|
||||
}
|
||||
}
|
||||
|
||||
/// A decomposed 2D transform: translate, then scale and rotate about the node's anchor.
|
||||
/// Decomposed parts animate independently, so a spinning, growing card never shears.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Transform {
|
||||
pub translate: Vec2,
|
||||
pub scale: Vec2,
|
||||
/// Radians, unwrapped: animating 0 → 4π spins twice, always the same way.
|
||||
pub rotate: f32,
|
||||
}
|
||||
|
||||
impl Default for Transform {
|
||||
fn default() -> Self {
|
||||
Transform::IDENTITY
|
||||
}
|
||||
}
|
||||
|
||||
impl Transform {
|
||||
pub const IDENTITY: Transform =
|
||||
Transform { translate: Vec2::ZERO, scale: Vec2 { x: 1.0, y: 1.0 }, rotate: 0.0 };
|
||||
|
||||
/// The 2×3 affine matrix `[a, b, c, d, tx, ty]` (column-major like CGAffineTransform) that
|
||||
/// applies this transform about `anchor` (in the same space as the translate).
|
||||
pub fn to_affine(&self, anchor: Vec2) -> [f32; 6] {
|
||||
let (s, c) = crate::math::sin_cos(self.rotate);
|
||||
let (a, b) = (c * self.scale.x, s * self.scale.x);
|
||||
let (cc, d) = (-s * self.scale.y, c * self.scale.y);
|
||||
// p' = M (p − anchor) + anchor + translate
|
||||
let tx = anchor.x + self.translate.x - (a * anchor.x + cc * anchor.y);
|
||||
let ty = anchor.y + self.translate.y - (b * anchor.x + d * anchor.y);
|
||||
[a, b, cc, d, tx, ty]
|
||||
}
|
||||
}
|
||||
|
||||
impl Animatable for Transform {
|
||||
const LANES: usize = 5;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
out[..5].copy_from_slice(&[self.translate.x, self.translate.y, self.scale.x, self.scale.y, self.rotate]);
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
Transform { translate: Vec2::new(l[0], l[1]), scale: Vec2::new(l[2], l[3]), rotate: l[4] }
|
||||
}
|
||||
}
|
||||
|
||||
/// An sRGB colour with straight (unpremultiplied) alpha, components in 0…1.
|
||||
///
|
||||
/// It animates in **premultiplied OKLab** (`[L·α, a·α, b·α, α]`): hue changes don't pass through
|
||||
/// grey, and fading to transparent doesn't drag the colour toward black.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Color {
|
||||
pub r: f32,
|
||||
pub g: f32,
|
||||
pub b: f32,
|
||||
pub a: f32,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
pub const TRANSPARENT: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
|
||||
pub const BLACK: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
|
||||
pub const WHITE: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
|
||||
|
||||
pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color {
|
||||
Color { r, g, b, a }
|
||||
}
|
||||
|
||||
/// `0xRRGGBB` with alpha 1.
|
||||
pub const fn hex(rgb: u32) -> Color {
|
||||
Color {
|
||||
r: ((rgb >> 16) & 0xff) as f32 / 255.0,
|
||||
g: ((rgb >> 8) & 0xff) as f32 / 255.0,
|
||||
b: (rgb & 0xff) as f32 / 255.0,
|
||||
a: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_alpha(self, a: f32) -> Color {
|
||||
Color { a, ..self }
|
||||
}
|
||||
|
||||
/// `[L, a, b]` in OKLab (Björn Ottosson's matrices).
|
||||
pub fn to_oklab(self) -> [f32; 3] {
|
||||
linear_to_oklab(srgb_decode(self.r), srgb_decode(self.g), srgb_decode(self.b))
|
||||
}
|
||||
|
||||
pub fn from_oklab(lab: [f32; 3], alpha: f32) -> Color {
|
||||
let [r, g, b] = oklab_to_linear(lab).map(|c| srgb_encode(c.clamp(0.0, 1.0)));
|
||||
Color { r, g, b, a: alpha }
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear sRGB `[r, g, b]` to OKLab `[L, a, b]` (Björn Ottosson's matrices).
|
||||
pub fn linear_to_oklab(r: f32, g: f32, b: f32) -> [f32; 3] {
|
||||
let l = (0.412_221_47 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
|
||||
let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
|
||||
let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();
|
||||
[
|
||||
0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
|
||||
1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
|
||||
0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
|
||||
]
|
||||
}
|
||||
|
||||
/// OKLab `[L, a, b]` to unclamped linear sRGB `[r, g, b]`.
|
||||
pub fn oklab_to_linear([ll, a, b]: [f32; 3]) -> [f32; 3] {
|
||||
let l = ll + 0.396_337_78 * a + 0.215_803_76 * b;
|
||||
let m = ll - 0.105_561_346 * a - 0.063_854_17 * b;
|
||||
let s = ll - 0.089_484_18 * a - 1.291_485_5 * b;
|
||||
let (l, m, s) = (l * l * l, m * m * m, s * s * s);
|
||||
[
|
||||
4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
|
||||
-1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
|
||||
-0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
|
||||
]
|
||||
}
|
||||
|
||||
pub fn srgb_decode(c: f32) -> f32 {
|
||||
if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
pub fn srgb_encode(c: f32) -> f32 {
|
||||
if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
impl Animatable for Color {
|
||||
const LANES: usize = 4;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
let [l, a, b] = self.to_oklab();
|
||||
let al = self.a;
|
||||
out[..4].copy_from_slice(&[l * al, a * al, b * al, al]);
|
||||
}
|
||||
fn read_lanes(x: &[f32]) -> Self {
|
||||
let alpha = x[3].clamp(0.0, 1.0);
|
||||
if x[3] <= 1e-6 {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
Color::from_oklab([x[0] / x[3], x[1] / x[3], x[2] / x[3]], alpha)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Animatable, B: Animatable> Animatable for (A, B) {
|
||||
const LANES: usize = A::LANES + B::LANES;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
self.0.write_lanes(&mut out[..A::LANES]);
|
||||
self.1.write_lanes(&mut out[A::LANES..A::LANES + B::LANES]);
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
(A::read_lanes(&l[..A::LANES]), B::read_lanes(&l[A::LANES..A::LANES + B::LANES]))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Animatable, B: Animatable, C: Animatable> Animatable for (A, B, C) {
|
||||
const LANES: usize = A::LANES + B::LANES + C::LANES;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
let (a, b) = (A::LANES, A::LANES + B::LANES);
|
||||
self.0.write_lanes(&mut out[..a]);
|
||||
self.1.write_lanes(&mut out[a..b]);
|
||||
self.2.write_lanes(&mut out[b..b + C::LANES]);
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
let (a, b) = (A::LANES, A::LANES + B::LANES);
|
||||
(A::read_lanes(&l[..a]), B::read_lanes(&l[a..b]), C::read_lanes(&l[b..b + C::LANES]))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Animatable, const N: usize> Animatable for [T; N] {
|
||||
const LANES: usize = T::LANES * N;
|
||||
fn write_lanes(&self, out: &mut [f32]) {
|
||||
for (i, v) in self.iter().enumerate() {
|
||||
v.write_lanes(&mut out[i * T::LANES..(i + 1) * T::LANES]);
|
||||
}
|
||||
}
|
||||
fn read_lanes(l: &[f32]) -> Self {
|
||||
core::array::from_fn(|i| T::read_lanes(&l[i * T::LANES..(i + 1) * T::LANES]))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn oklab_round_trips() {
|
||||
for c in [Color::hex(0xff3b30), Color::hex(0x34c759), Color::hex(0x007aff), Color::WHITE] {
|
||||
let back = Color::read_lanes(&lanes(&c)[..4]);
|
||||
for (x, y) in [(c.r, back.r), (c.g, back.g), (c.b, back.b), (c.a, back.a)] {
|
||||
assert!((x - y).abs() < 1e-3, "{c:?} → {back:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_lanes_are_edges() {
|
||||
let r = Rect::new(10.0, 20.0, 100.0, 50.0);
|
||||
assert_eq!(&lanes(&r)[..4], &[10.0, 20.0, 110.0, 70.0]);
|
||||
assert_eq!(Rect::read_lanes(&[10.0, 20.0, 110.0, 70.0]), r);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tuples_and_arrays() {
|
||||
let v = (1.0f32, Vec2::new(2.0, 3.0));
|
||||
assert_eq!(<(f32, Vec2)>::LANES, 3);
|
||||
assert_eq!(v.add(v), (2.0, Vec2::new(4.0, 6.0)));
|
||||
let a = [Vec2::new(1.0, 1.0); 3];
|
||||
assert_eq!(<[Vec2; 3]>::LANES, 6);
|
||||
assert!((a.distance([Vec2::ZERO; 3]) - 6f32.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affine_rotates_about_anchor() {
|
||||
let t = Transform { rotate: core::f32::consts::FRAC_PI_2, ..Transform::IDENTITY };
|
||||
let [a, b, c, d, tx, ty] = t.to_affine(Vec2::new(10.0, 10.0));
|
||||
// The anchor stays put.
|
||||
let (x, y) = (a * 10.0 + c * 10.0 + tx, b * 10.0 + d * 10.0 + ty);
|
||||
assert!((x - 10.0).abs() < 1e-4 && (y - 10.0).abs() < 1e-4);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
//! The steady-state frame allocates nothing: proven with a counting global allocator.
|
||||
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{NodeSpec, Prop, PropClass};
|
||||
|
||||
struct Counting;
|
||||
// Per thread: tests run in parallel and must not count each other's allocations.
|
||||
thread_local! {
|
||||
static ALLOCS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn bump() {
|
||||
ALLOCS.try_with(|c| c.set(c.get() + 1)).ok();
|
||||
}
|
||||
|
||||
// SAFETY: forwards every allocation call to `System`, only counting allocations on this thread.
|
||||
unsafe impl GlobalAlloc for Counting {
|
||||
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
|
||||
bump();
|
||||
// SAFETY: delegates allocation with the caller's layout to `System`.
|
||||
unsafe { System.alloc(l) }
|
||||
}
|
||||
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
|
||||
// SAFETY: delegates deallocation of `p` and `l` to `System`.
|
||||
unsafe { System.dealloc(p, l) }
|
||||
}
|
||||
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
|
||||
bump();
|
||||
// SAFETY: delegates reallocation of `p`, `l` and `n` to `System`.
|
||||
unsafe { System.realloc(p, l, n) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static A: Counting = Counting;
|
||||
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Spatial);
|
||||
|
||||
fn allocs() -> usize {
|
||||
ALLOCS.with(|c| c.get())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_tick_allocates_nothing_in_steady_state() {
|
||||
let n = 5000;
|
||||
let mut store = AnimationStore::with_capacity(2 * n as usize, 3);
|
||||
for i in 0..n {
|
||||
let id = NodeId(i);
|
||||
store.set(id, X, 0.0);
|
||||
store.set(id, prop::FRAME, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
// A spread of bounces and durations so tracks settle at different times.
|
||||
let s = Spring::new(0.3 + (i % 7) as f32 * 0.2, (i % 5) as f32 * 0.1);
|
||||
store.animate(id, X, 100.0 + i as f32, s);
|
||||
store.animate(id, prop::FRAME, Rect::new(5.0, 3.0, 20.0, 10.0), s.delay((i % 3) as f32 * 0.05));
|
||||
if i % 4 == 0 {
|
||||
store.animate(id, X, -50.0, Curve::tween(0.4, Easing::EASE_IN_OUT));
|
||||
}
|
||||
}
|
||||
// Warm up: the first frames grow the event and touched buffers to the working-set size.
|
||||
let mut t = 0.0;
|
||||
for _ in 0..4 {
|
||||
t += 1.0 / 120.0;
|
||||
store.tick_at(t);
|
||||
}
|
||||
let before = allocs();
|
||||
let mut ticks = 0;
|
||||
while store.active_len() > 0 && ticks < 2000 {
|
||||
t += 1.0 / 120.0;
|
||||
store.tick_at(t);
|
||||
ticks += 1;
|
||||
}
|
||||
let after = allocs();
|
||||
assert!(ticks > 100, "the animations should run for a while ({ticks})");
|
||||
assert_eq!(after - before, 0, "{} allocations over {ticks} ticks", after - before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scene_frame_allocates_nothing_while_animating() {
|
||||
let mut scene = Scene::new();
|
||||
for i in 0..500u64 {
|
||||
scene.insert(NodeId(i), NodeSpec::new(Rect::new(0.0, i as f32 * 10.0, 100.0, 10.0)), Mount::Initial);
|
||||
}
|
||||
scene.frame_at(0.0);
|
||||
for i in 0..500u64 {
|
||||
scene.set_frame(NodeId(i), Rect::new(10.0, i as f32 * 12.0, 100.0, 12.0), motion::REFLOW);
|
||||
scene.animate(NodeId(i), prop::OPACITY, 0.5, motion::SETTLE);
|
||||
}
|
||||
let mut t = 0.0;
|
||||
for _ in 0..3 {
|
||||
t += 1.0 / 120.0;
|
||||
scene.frame_at(t);
|
||||
}
|
||||
let before = allocs();
|
||||
for _ in 0..40 {
|
||||
t += 1.0 / 120.0;
|
||||
let out = scene.frame_at(t);
|
||||
assert!(out.animating && out.changed.len() == 500);
|
||||
}
|
||||
assert_eq!(allocs() - before, 0);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{Choreography, PhaseAnimator, When, stagger};
|
||||
|
||||
#[test]
|
||||
fn stagger_delays_ripple_from_the_origin() {
|
||||
let d: Vec<f32> = (0..5).map(|i| stagger(i, 5, 0.1, StaggerFrom::First)).collect();
|
||||
assert_eq!(d, vec![0.0, 0.1, 0.2, 0.3, 0.4]);
|
||||
let d: Vec<f32> = (0..5).map(|i| stagger(i, 5, 0.1, StaggerFrom::Last)).collect();
|
||||
assert_eq!(d, vec![0.4, 0.3, 0.2, 0.1, 0.0]);
|
||||
let d: Vec<f32> = (0..5).map(|i| stagger(i, 5, 0.1, StaggerFrom::Center)).collect();
|
||||
assert!((d[0] - 0.2).abs() < 1e-6 && d[2] == 0.0 && (d[4] - 0.2).abs() < 1e-6);
|
||||
let eased = Stagger::new(0.1).ease(Easing::EASE_IN);
|
||||
// Eased stagger keeps the ends and bunches the start.
|
||||
assert!(eased.delay(0, 5) == 0.0 && (eased.delay(4, 5) - 0.4).abs() < 1e-5);
|
||||
assert!(eased.delay(1, 5) < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_starts_on_arrival_not_on_physical_rest() {
|
||||
let mut store = AnimationStore::new();
|
||||
let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3));
|
||||
for n in [a, b, c] {
|
||||
store.set(n, prop::OPACITY, 0.0);
|
||||
}
|
||||
let mut ch = Choreography::new();
|
||||
let s1 = ch.step(Cue::now(), |s| {
|
||||
s.animate(a, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
});
|
||||
let s2 = ch.step(Cue::arrived(s1).after(0.05), |s| {
|
||||
s.animate(b, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
});
|
||||
let s3 = ch.step(Cue::settled(s2).not_before(1.5), |s| {
|
||||
s.animate(c, prop::OPACITY, 1.0, motion::SNAP);
|
||||
});
|
||||
let mut t = 0.0;
|
||||
while t < 4.0 {
|
||||
store.set_time(t);
|
||||
ch.tick(&mut store);
|
||||
store.tick();
|
||||
t += 1.0 / 120.0;
|
||||
}
|
||||
// Step 2 is scheduled exactly at s1's logical arrival (its 0.3 s duration) + 0.05.
|
||||
assert!((ch.start_time(s2).unwrap() - 0.35).abs() < 1e-6, "{:?}", ch.start_time(s2));
|
||||
// Step 3 waits for physical rest *and* the guard.
|
||||
assert!(ch.start_time(s3).unwrap() >= 1.5);
|
||||
assert!(ch.is_done(&store));
|
||||
for n in [a, b, c] {
|
||||
assert_eq!(store.get(n, prop::OPACITY), Some(1.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choreography_stagger_cascades_items() {
|
||||
let mut store = AnimationStore::new();
|
||||
let ids: Vec<NodeId> = (0..4).map(NodeId).collect();
|
||||
for &n in &ids {
|
||||
store.set(n, prop::OFFSET, Vec2::new(0.0, 12.0));
|
||||
}
|
||||
let mut ch = Choreography::new();
|
||||
let steps = ch.stagger(Cue::now(), Stagger::new(0.04), ids.clone(), |s, n| {
|
||||
s.animate(n, prop::OFFSET, Vec2::ZERO, motion::SETTLE);
|
||||
});
|
||||
store.set_time(0.0);
|
||||
ch.tick(&mut store);
|
||||
for (i, s) in steps.iter().enumerate() {
|
||||
assert!((ch.start_time(*s).unwrap() - 0.04 * i as f64).abs() < 1e-6);
|
||||
}
|
||||
store.tick_at(0.05);
|
||||
let y: Vec<f32> = ids.iter().map(|&n| store.get(n, prop::OFFSET).unwrap().y).collect();
|
||||
assert!(y[0] < y[1] && y[1] < y[2] && y[2] == 12.0 && y[3] == 12.0, "{y:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase_animator_cycles_and_holds_under_reduced_motion() {
|
||||
let pulse = |store: &mut AnimationStore, reduced: bool| {
|
||||
store.set_reduced_motion(reduced);
|
||||
let n = NodeId(1);
|
||||
let mut ph = PhaseAnimator::new()
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 1.0, motion::SETTLE);
|
||||
})
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 1.04, motion::SETTLE);
|
||||
})
|
||||
.advance_on(When::Arrived);
|
||||
let mut phases = Vec::new();
|
||||
let mut t = 0.0;
|
||||
while t < 2.0 {
|
||||
store.set_time(t);
|
||||
ph.tick(store);
|
||||
store.tick();
|
||||
phases.push(ph.current());
|
||||
t += 1.0 / 120.0;
|
||||
}
|
||||
phases
|
||||
};
|
||||
let phases = pulse(&mut AnimationStore::new(), false);
|
||||
let switches = phases.windows(2).filter(|w| w[0] != w[1]).count();
|
||||
// 0.3 s per phase for 2 s ≈ 6 switches.
|
||||
assert!((5..=7).contains(&switches), "{switches}");
|
||||
let held = pulse(&mut AnimationStore::new(), true);
|
||||
assert!(held.iter().all(|&p| p == 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cue_on_a_frozen_step_waits_and_scaled_steps_keep_one_clock() {
|
||||
// A frozen first step: the second waits for its arrival instead of never running.
|
||||
let mut store = AnimationStore::new();
|
||||
let (a, b) = (NodeId(1), NodeId(2));
|
||||
for n in [a, b] {
|
||||
store.set(n, prop::OPACITY, 0.0);
|
||||
}
|
||||
store.set_node_time_scale(a, 0.0);
|
||||
let mut ch = Choreography::new();
|
||||
let s1 = ch.step(Cue::now(), |s| {
|
||||
s.animate(a, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
});
|
||||
let s2 = ch.step(Cue::arrived(s1), |s| {
|
||||
s.animate(b, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
});
|
||||
for i in 0..=480 {
|
||||
store.set_time(i as f64 / 120.0);
|
||||
if i == 120 {
|
||||
store.set_node_time_scale(a, 1.0);
|
||||
}
|
||||
ch.tick(&mut store);
|
||||
store.tick();
|
||||
if i == 119 {
|
||||
assert_eq!(ch.start_time(s2), None, "waits while its cue is frozen");
|
||||
}
|
||||
}
|
||||
// Resumed at 1 s, `a` arrives 0.3 s later.
|
||||
assert!((ch.start_time(s2).unwrap() - 1.3).abs() < 1e-3, "{:?}", ch.start_time(s2));
|
||||
assert_eq!(store.get(b, prop::OPACITY), Some(1.0));
|
||||
|
||||
// Both at half speed: `b` starts when `a` arrives, 0.6 s in, and runs on the same curve.
|
||||
let mut store = AnimationStore::new();
|
||||
for n in [a, b] {
|
||||
store.set(n, prop::OPACITY, 0.0);
|
||||
store.set_node_time_scale(n, 0.5);
|
||||
}
|
||||
let mut ch = Choreography::new();
|
||||
let s1 = ch.step(Cue::now(), |s| {
|
||||
s.animate(a, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
});
|
||||
ch.step(Cue::arrived(s1), |s| {
|
||||
s.animate(b, prop::OPACITY, 1.0, motion::SETTLE);
|
||||
});
|
||||
let (mut a_at, mut b_at) = (0.0, 0.0);
|
||||
for i in 0..=120 {
|
||||
store.set_time(i as f64 / 120.0);
|
||||
ch.tick(&mut store);
|
||||
store.tick();
|
||||
if i == 24 {
|
||||
a_at = store.get(a, prop::OPACITY).unwrap();
|
||||
}
|
||||
if i == 96 {
|
||||
b_at = store.get(b, prop::OPACITY).unwrap();
|
||||
}
|
||||
}
|
||||
assert!(a_at > 0.05 && (a_at - b_at).abs() < 1e-3, "b at 0.8 s {b_at} vs a at 0.2 s {a_at}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_once_phase_animator_waits_for_rest_and_stops_on_its_last_phase() {
|
||||
let n = NodeId(1);
|
||||
let mut store = AnimationStore::new();
|
||||
let mut ph = PhaseAnimator::new()
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 1.0, motion::SETTLE);
|
||||
})
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 1.04, motion::SETTLE);
|
||||
})
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 0.98, motion::SETTLE);
|
||||
})
|
||||
.advance_on(When::Settled)
|
||||
.hold(0.1)
|
||||
.once();
|
||||
let (mut phases, mut moving) = (Vec::new(), Vec::new());
|
||||
for i in 0..=600 {
|
||||
store.set_time(i as f64 / 120.0);
|
||||
ph.tick(&mut store);
|
||||
store.tick();
|
||||
phases.push(ph.current());
|
||||
moving.push(store.is_animating(n, prop::SCALE));
|
||||
}
|
||||
let switches: Vec<usize> = (1..phases.len()).filter(|&i| phases[i] != phases[i - 1]).collect();
|
||||
assert_eq!(switches.len(), 1, "phase 1 starts on the first tick, then one switch: {switches:?}");
|
||||
let k = switches[0];
|
||||
assert_eq!(phases[k], 2);
|
||||
// `When::Settled` plus the hold: the track was at rest for 0.1 s before the switch.
|
||||
assert!(moving[..k - 12].iter().any(|&m| m) && moving[k - 12..k].iter().all(|&m| !m), "{moving:?}");
|
||||
assert_eq!(store.get(n, prop::SCALE), Some(0.98));
|
||||
assert_eq!(store.active_len(), 0, "a finished one-shot starts nothing more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_started_frozen_advances_after_resuming() {
|
||||
let mut store = AnimationStore::new();
|
||||
let n = NodeId(1);
|
||||
store.set_node_time_scale(n, 0.0);
|
||||
let mut ph = PhaseAnimator::new()
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 1.0, motion::SETTLE);
|
||||
})
|
||||
.phase(|p| {
|
||||
p.animate(n, prop::SCALE, 1.04, motion::SETTLE);
|
||||
});
|
||||
let mut phases = Vec::new();
|
||||
for i in 0..=480 {
|
||||
store.set_time(i as f64 / 120.0);
|
||||
if i == 120 {
|
||||
store.set_node_time_scale(n, 1.0);
|
||||
}
|
||||
ph.tick(&mut store);
|
||||
store.tick();
|
||||
phases.push(ph.current());
|
||||
}
|
||||
let switches = |p: &[usize]| p.windows(2).filter(|w| w[0] != w[1]).count();
|
||||
assert_eq!(switches(&phases[1..120]), 0, "frozen in its first animated phase");
|
||||
// 0.3 s per phase for 3 s ≈ 10 switches.
|
||||
assert!(switches(&phases[120..]) >= 8, "{}", switches(&phases[120..]));
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! A delayed entrance (`Scene::insert_delayed`) holds the whole insertion effect, then plays
|
||||
//! every part of it on one presence progress.
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::Phase;
|
||||
|
||||
const HZ: f64 = 120.0;
|
||||
const RISE: f32 = 12.0;
|
||||
|
||||
fn spec() -> NodeSpec {
|
||||
NodeSpec::new(Rect::new(0.0, 0.0, 100.0, 40.0)).transition(Transition::offset(0.0, RISE).combined(Transition::opacity()))
|
||||
}
|
||||
|
||||
fn scene() -> Scene {
|
||||
let mut s = Scene::new();
|
||||
s.set_pixel_scale(8.0);
|
||||
s.frame_at(0.0);
|
||||
s
|
||||
}
|
||||
|
||||
/// (time, offset progress, opacity) of `id` from `from` to `until`.
|
||||
fn trace(s: &mut Scene, from: f64, until: f64, id: NodeId) -> Vec<(f64, f32, f32)> {
|
||||
let mut out = Vec::new();
|
||||
let mut t = from;
|
||||
while t <= until + 1e-9 {
|
||||
s.frame_at(t);
|
||||
let p = s.presented(id).unwrap();
|
||||
out.push((t, 1.0 - p.rect.y / RISE, p.opacity));
|
||||
t += 1.0 / HZ;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_the_insertion_effect_then_moves_every_part_together() {
|
||||
let mut s = scene();
|
||||
let id = NodeId(1);
|
||||
s.insert_delayed(id, spec(), Mount::Animated, 0.3);
|
||||
for (t, offset, opacity) in trace(&mut s, 0.0, 0.29, id) {
|
||||
assert_eq!((offset, opacity), (0.0, 0.0), "t={t}: waits at the insertion effect");
|
||||
}
|
||||
let after = trace(&mut s, 0.3, 1.5, id);
|
||||
assert!(after.iter().any(|&(_, o, _)| o > 0.5), "it enters");
|
||||
for (t, offset, opacity) in after {
|
||||
assert!((offset - opacity).abs() < 2e-3, "t={t}: offset {offset} and opacity {opacity} share one progress");
|
||||
}
|
||||
assert_eq!(s.presented(id).unwrap().phase, Phase::Present);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_waiting_isnt_running() {
|
||||
let mut s = scene();
|
||||
s.insert_delayed(NodeId(1), spec(), Mount::Animated, 0.3);
|
||||
s.frame_at(0.1);
|
||||
assert!((s.store().waiting_until().unwrap() - 0.3).abs() < 1e-6);
|
||||
s.frame_at(0.31);
|
||||
assert_eq!(s.store().waiting_until(), None, "the entrance moves");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_clock_stretches_the_delay() {
|
||||
let mut s = scene();
|
||||
let id = NodeId(1);
|
||||
s.insert_delayed(id, spec(), Mount::Animated, 0.3);
|
||||
s.set_time_scale(id, 0.5);
|
||||
s.frame_at(0.1);
|
||||
assert!((s.store().waiting_until().unwrap() - 0.6).abs() < 1e-6, "0.3 s at half speed");
|
||||
s.frame_at(0.59);
|
||||
assert_eq!(s.presented(id).unwrap().opacity, 0.0);
|
||||
s.frame_at(0.7);
|
||||
assert!(s.presented(id).unwrap().opacity > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_while_waiting_unseen_goes_at_once() {
|
||||
let mut s = scene();
|
||||
let id = NodeId(1);
|
||||
s.insert_delayed(id, spec(), Mount::Animated, 0.3);
|
||||
s.frame_at(0.1);
|
||||
s.remove(id);
|
||||
assert!(s.frame_at(0.11).exited.contains(&id), "nothing showed, so there's no exit to play");
|
||||
assert!(!s.frame_at(0.5).animating, "the cancelled start never runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visible_insertion_effect_fades_out_from_where_it_waits() {
|
||||
let mut s = scene();
|
||||
let id = NodeId(1);
|
||||
let slide = NodeSpec::new(Rect::new(0.0, 0.0, 100.0, 40.0)).transition(Transition::offset(0.0, RISE));
|
||||
s.insert_delayed(id, slide, Mount::Animated, 0.3);
|
||||
s.frame_at(0.1);
|
||||
assert_eq!((s.presented(id).unwrap().rect.y, s.presented(id).unwrap().opacity), (RISE, 1.0));
|
||||
s.remove(id);
|
||||
let mut last = 1.0;
|
||||
for (t, offset, opacity) in trace(&mut s, 0.1, 0.25, id) {
|
||||
assert_eq!(offset, 0.0, "t={t}: it stays where it waited");
|
||||
assert!(opacity <= last, "t={t}: fades out, {opacity} after {last}");
|
||||
last = opacity;
|
||||
}
|
||||
assert!(last < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entering_now_lands_a_waiting_entrance() {
|
||||
let mut s = scene();
|
||||
let id = NodeId(1);
|
||||
s.insert_delayed(id, spec(), Mount::Animated, 0.3);
|
||||
s.frame_at(0.1);
|
||||
s.land_waiting(id);
|
||||
let out = s.frame_at(0.11);
|
||||
assert!(!out.animating);
|
||||
let p = s.presented(id).unwrap();
|
||||
assert_eq!((p.rect.y, p.opacity, p.phase), (0.0, 1.0, Phase::Present));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduce_motion_keeps_the_delay_and_only_fades() {
|
||||
let mut s = scene();
|
||||
s.set_reduced_motion(true);
|
||||
let id = NodeId(1);
|
||||
s.insert_delayed(id, spec(), Mount::Animated, 0.3);
|
||||
let steps = trace(&mut s, 0.0, 1.0, id);
|
||||
for &(t, offset, opacity) in &steps {
|
||||
assert_eq!(offset, 1.0, "t={t}: nothing travels");
|
||||
if t < 0.3 - 1e-9 {
|
||||
assert_eq!(opacity, 0.0, "t={t}: the fade waits");
|
||||
}
|
||||
}
|
||||
let shown = steps.iter().find(|s| s.2 >= 1.0).unwrap().0;
|
||||
assert!(shown > 0.3 && shown < 0.6, "the short fade, after the delay: {shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_staggered_list_of_five_enters_in_order() {
|
||||
let mut s = scene();
|
||||
let stagger = Stagger::new(0.05);
|
||||
for i in 0..5 {
|
||||
s.insert_delayed(NodeId(i + 1), spec(), Mount::Animated, stagger.delay(i as usize, 5));
|
||||
}
|
||||
let mut starts = [None; 5];
|
||||
let mut t = 0.0;
|
||||
while t < 1.5 {
|
||||
s.frame_at(t);
|
||||
for i in 0..5 {
|
||||
let p = s.presented(NodeId(i as u64 + 1)).unwrap();
|
||||
let (offset, opacity) = (1.0 - p.rect.y / RISE, p.opacity);
|
||||
assert!((offset - opacity).abs() < 2e-3, "row {i} t={t}: {offset} vs {opacity}");
|
||||
if opacity > 0.0 && starts[i].is_none() {
|
||||
starts[i] = Some(t);
|
||||
}
|
||||
}
|
||||
t += 1.0 / HZ;
|
||||
}
|
||||
let starts = starts.map(Option::unwrap);
|
||||
for (i, w) in starts.windows(2).enumerate() {
|
||||
assert!((w[1] - w[0] - 0.05).abs() < 1.5 / HZ, "row {} starts 50 ms after row {i}: {starts:?}", i + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
mod choreo;
|
||||
mod enter_delay;
|
||||
mod phase_walk;
|
||||
mod quality;
|
||||
mod scene;
|
||||
mod siblings;
|
||||
mod spring;
|
||||
mod store;
|
||||
@@ -0,0 +1,646 @@
|
||||
//! Every sequence of presence events, walked against dev's own logic.
|
||||
//!
|
||||
//! The reference below is a literal transcription of the code this branch replaces: the fields
|
||||
//! `Node` used to carry (`phase`, `generation`, `fx_a`, `fx_b`, `anchor`, `reveal`, `transition`)
|
||||
//! and every branch in `insert_delayed`, `remove`, `revive`, `present_now`, `enter_now`,
|
||||
//! `land_waiting` and `reenter` that wrote them. It never calls the scene's presence code.
|
||||
//!
|
||||
//! The side under test drives the real [`Scene`]; the reference is fed the facts it read out of
|
||||
//! the store (the presence value, the settle event), and the two are compared after every event
|
||||
//! and after every frame: the phase, whether the node is still in the scene, the exit the frame
|
||||
//! reports, and the whole presented look (opacity, scale, rect, blur, draw, mask, anchor and
|
||||
//! `in_flow`). A reordered write, a dropped early return or a look that jumps fails here.
|
||||
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{Effect, MotionEvent, Phase, Reveal, prop};
|
||||
|
||||
const ID: NodeId = NodeId(1);
|
||||
const DT: f64 = 1.0 / 120.0;
|
||||
|
||||
fn scene_frame() -> Rect {
|
||||
Rect::new(10.0, 20.0, 100.0, 40.0)
|
||||
}
|
||||
|
||||
fn spec(transition: Transition) -> NodeSpec {
|
||||
NodeSpec::new(scene_frame()).transition(transition)
|
||||
}
|
||||
|
||||
fn slow() -> SpringPair {
|
||||
SpringPair::new(Spring::new(0.12, 0.0), Spring::new(0.12, 0.0))
|
||||
}
|
||||
|
||||
/// Covers opacity, scale, blur and the reveal mask.
|
||||
fn blur_reveal(springs: SpringPair) -> Transition {
|
||||
Transition::blur_replace().combined(Transition::reveal(Edge::Leading)).springs(springs)
|
||||
}
|
||||
|
||||
/// Covers opacity, the size-fraction offset and the drawn-shape lane.
|
||||
fn push_draw(springs: SpringPair) -> Transition {
|
||||
Transition::push(Edge::Bottom).combined(Transition::draw()).springs(springs)
|
||||
}
|
||||
|
||||
/// An entrance that slides in without fading: its insertion look is still opaque at presence 0.
|
||||
fn slide(springs: SpringPair) -> Transition {
|
||||
Transition::move_edge(Edge::Leading).springs(springs)
|
||||
}
|
||||
|
||||
/// A removal that scales about its top-left corner and wipes, so it pivots and hides somewhere
|
||||
/// else than the insertion the node arrived on.
|
||||
fn corner_scale(springs: SpringPair) -> Transition {
|
||||
let removal = Transition::scale_anchor(0.9, Vec2::new(0.0, 0.0)).combined(Transition::reveal(Edge::Top));
|
||||
Transition::asymmetric(Transition::move_edge(Edge::Leading), removal).springs(springs)
|
||||
}
|
||||
|
||||
/// The two transitions a walk inserts and retransitions with, and the springs they asked for.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Cfg {
|
||||
mount: Transition,
|
||||
retarget: Transition,
|
||||
/// The literal pair the transitions were built from. The reference runs its own presence on
|
||||
/// it, so a scene that reads a different duration from the same transition fails the walk.
|
||||
springs: SpringPair,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The reference: dev's fields and branches.
|
||||
|
||||
const IDENTITY: [f32; 9] = [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0];
|
||||
|
||||
/// dev's `Phase`.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum DevPhase {
|
||||
Entering,
|
||||
Present,
|
||||
Exiting { generation: u32 },
|
||||
}
|
||||
|
||||
fn lanes(e: &Effect) -> [f32; 9] {
|
||||
let hidden = if e.reveal.is_some() { 1.0 } else { 0.0 };
|
||||
[e.opacity, e.scale, e.offset.x, e.offset.y, e.offset_fraction.x, e.offset_fraction.y, e.blur, hidden, e.draw]
|
||||
}
|
||||
|
||||
fn lerp(a: &[f32; 9], b: &[f32; 9], p: f32) -> [f32; 9] {
|
||||
core::array::from_fn(|k| a[k] * (1.0 - p) + b[k] * p)
|
||||
}
|
||||
|
||||
/// The presence value at the scene's clock, which is what dev read with `presence_now`.
|
||||
fn presence(scene: &Scene, node: NodeId) -> f32 {
|
||||
scene.store().sample(node, prop::PRESENCE).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
struct Dev {
|
||||
phase: DevPhase,
|
||||
generation: u32,
|
||||
fx_a: [f32; 9],
|
||||
fx_b: [f32; 9],
|
||||
anchor: Vec2,
|
||||
reveal: Option<Reveal>,
|
||||
transition: Transition,
|
||||
alive: bool,
|
||||
/// Removed, waiting for the next frame to report it in `exited`.
|
||||
pending_exit: bool,
|
||||
/// The presence track dev's own writes drive, on the same clock as the scene: the expected
|
||||
/// progress, settle and exit frames. A separate store, so a scene that runs the track on a
|
||||
/// different spring or for a different duration fails here instead of agreeing with itself.
|
||||
ref_store: AnimationStore,
|
||||
/// The springs a walk configured, which the reference's entrance and exit run on.
|
||||
springs: SpringPair,
|
||||
}
|
||||
|
||||
impl Dev {
|
||||
fn new(transition: Transition, springs: SpringPair) -> Dev {
|
||||
let mut ref_store = AnimationStore::new();
|
||||
ref_store.set(ID, prop::PRESENCE, 1.0);
|
||||
Dev {
|
||||
phase: DevPhase::Present,
|
||||
generation: 0,
|
||||
fx_a: IDENTITY,
|
||||
fx_b: IDENTITY,
|
||||
anchor: Vec2::new(0.5, 0.5),
|
||||
reveal: None,
|
||||
transition,
|
||||
alive: false,
|
||||
pending_exit: false,
|
||||
ref_store,
|
||||
springs,
|
||||
}
|
||||
}
|
||||
|
||||
/// The presence the reference's own track holds at the scene's clock.
|
||||
fn ref_presence(&self) -> f32 {
|
||||
self.ref_store.sample(ID, prop::PRESENCE).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
/// `insert_delayed`, with the node's frame unchanged: a new node, a revive, or a landing.
|
||||
fn insert(&mut self, transition: Transition, mount: Mount, delay: f32, p: f32) {
|
||||
self.transition = transition;
|
||||
if self.alive {
|
||||
let exiting = matches!(self.phase, DevPhase::Exiting { .. });
|
||||
if exiting && mount == Mount::Initial {
|
||||
self.present_now();
|
||||
return;
|
||||
}
|
||||
if exiting {
|
||||
self.revive(p);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let ins = transition.insertion.kit_rules(false);
|
||||
// A root node has no parent to ride, so `rides_parent` is false.
|
||||
let animate = mount == Mount::Animated && !ins.shows_nothing();
|
||||
self.phase = if animate { DevPhase::Entering } else { DevPhase::Present };
|
||||
self.generation = 0;
|
||||
self.fx_a = lanes(&ins);
|
||||
self.fx_b = IDENTITY;
|
||||
self.anchor = ins.anchor;
|
||||
self.reveal = ins.reveal;
|
||||
self.alive = true;
|
||||
if animate {
|
||||
self.land(0.0);
|
||||
self.run(1.0, Anim { delay, ..Anim::from(self.springs.enter) });
|
||||
} else {
|
||||
self.land(1.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_transition(&mut self, transition: Transition) {
|
||||
if !matches!(self.phase, DevPhase::Exiting { .. }) {
|
||||
self.transition = transition;
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, p: f32) {
|
||||
if !self.alive || matches!(self.phase, DevPhase::Exiting { .. }) {
|
||||
return;
|
||||
}
|
||||
let unplayed = p < 1e-3;
|
||||
if unplayed && lerp(&self.fx_a, &self.fx_b, p)[0] < 1.0 / 512.0 {
|
||||
// An entrance that hasn't shown anything yet has no exit to play.
|
||||
self.retire();
|
||||
return;
|
||||
}
|
||||
let rem = self.transition.removal.kit_rules(true);
|
||||
let target = lanes(&rem);
|
||||
self.generation += 1;
|
||||
self.phase = DevPhase::Exiting { generation: self.generation };
|
||||
if p >= 0.999 {
|
||||
self.fx_a = target;
|
||||
self.fx_b = IDENTITY;
|
||||
} else if unplayed {
|
||||
self.fx_b = lerp(&self.fx_a, &self.fx_b, p);
|
||||
self.fx_a = target;
|
||||
} else {
|
||||
let cur = lerp(&self.fx_a, &self.fx_b, p);
|
||||
self.fx_a = target;
|
||||
for k in 0..8 {
|
||||
self.fx_b[k] = target[k] + (cur[k] - target[k]) / p.max(1e-3);
|
||||
}
|
||||
}
|
||||
if rem.scale != 1.0 {
|
||||
self.anchor = rem.anchor;
|
||||
}
|
||||
if rem.reveal.is_some() {
|
||||
self.reveal = rem.reveal;
|
||||
}
|
||||
if unplayed {
|
||||
self.land(1.0);
|
||||
}
|
||||
self.run(0.0, Anim::from(self.springs.exit));
|
||||
}
|
||||
|
||||
fn unmount(&mut self) {
|
||||
if self.alive {
|
||||
self.retire();
|
||||
}
|
||||
}
|
||||
|
||||
fn enter_now(&mut self) {
|
||||
if self.phase == DevPhase::Entering {
|
||||
self.present_now();
|
||||
}
|
||||
}
|
||||
|
||||
fn land_waiting(&mut self, p: f32) {
|
||||
if self.phase == DevPhase::Entering && p < 1e-3 {
|
||||
self.present_now();
|
||||
}
|
||||
}
|
||||
|
||||
fn reenter(&mut self) {
|
||||
if self.alive && self.phase == DevPhase::Present {
|
||||
// `reenter` lands presence at 0, then revives from there.
|
||||
self.land(0.0);
|
||||
self.revive(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn revive(&mut self, p: f32) {
|
||||
self.generation += 1;
|
||||
self.phase = DevPhase::Entering;
|
||||
if p <= 0.001 {
|
||||
let ins = self.transition.insertion.kit_rules(false);
|
||||
self.fx_a = lanes(&ins);
|
||||
} else {
|
||||
// Keep the current look at p, land exactly on identity at 1. The last lane (drawn
|
||||
// shape) is kept: an entrance never re-solves it.
|
||||
let cur = lerp(&self.fx_a, &self.fx_b, p);
|
||||
let q = (1.0 - p).max(1e-3);
|
||||
for k in 0..8 {
|
||||
self.fx_a[k] = (cur[k] - IDENTITY[k] * p) / q;
|
||||
}
|
||||
}
|
||||
self.fx_b = IDENTITY;
|
||||
// A revive runs the entrance with no delay, whatever the mount was held for.
|
||||
self.run(1.0, Anim::from(self.springs.enter));
|
||||
}
|
||||
|
||||
fn present_now(&mut self) {
|
||||
self.generation += 1;
|
||||
self.phase = DevPhase::Present;
|
||||
let ins = self.transition.insertion.kit_rules(false);
|
||||
self.fx_a = lanes(&ins);
|
||||
self.fx_b = IDENTITY;
|
||||
self.anchor = ins.anchor;
|
||||
self.reveal = ins.reveal;
|
||||
self.land(1.0);
|
||||
}
|
||||
|
||||
/// The reference's `Land`: presence jumps, whatever it was doing.
|
||||
fn land(&mut self, v: f32) {
|
||||
self.ref_store.set(ID, prop::PRESENCE, v);
|
||||
}
|
||||
|
||||
/// The reference's `Run`: presence animates from where the reference's own track is.
|
||||
fn run(&mut self, target: f32, anim: Anim) {
|
||||
self.ref_store.animate(ID, prop::PRESENCE, target, anim);
|
||||
}
|
||||
|
||||
/// Moves the reference's store to `t` and samples it: the presence and the settle event the
|
||||
/// walk expects the scene to have this frame.
|
||||
fn reference_frame(&mut self, t: f64) -> (f32, bool) {
|
||||
self.ref_store.set_time(t);
|
||||
let p = self.ref_presence();
|
||||
self.ref_store.tick();
|
||||
let settled = self.ref_store.events().iter().any(|e| {
|
||||
matches!(*e, MotionEvent::Settled { node: n, prop: q, .. } if n == ID && q == prop::PRESENCE.id)
|
||||
});
|
||||
(p, settled)
|
||||
}
|
||||
|
||||
fn retire(&mut self) {
|
||||
self.alive = false;
|
||||
self.pending_exit = true;
|
||||
}
|
||||
|
||||
/// `match_geometry`'s `to`: present at once, with only the absent look replaced.
|
||||
fn matched(&mut self) {
|
||||
self.phase = DevPhase::Present;
|
||||
self.fx_a = IDENTITY;
|
||||
self.land(1.0);
|
||||
}
|
||||
|
||||
fn looks(&self) -> ([f32; 9], [f32; 9]) {
|
||||
(self.fx_a, self.fx_b)
|
||||
}
|
||||
|
||||
/// One frame's worth of dev's `Scene::frame`: presence settles, then an exit whose presence
|
||||
/// faded below one 8-bit step retires. `p` is the presence the frame's tick had, which is the
|
||||
/// value dev read from the store. Returns whether it reports the node in `exited`.
|
||||
fn frame(&mut self, settled: bool, p: f32) -> bool {
|
||||
let mut retired = false;
|
||||
if settled {
|
||||
match self.phase {
|
||||
DevPhase::Entering => self.phase = DevPhase::Present,
|
||||
DevPhase::Exiting { generation } if generation == self.generation => {
|
||||
self.retire();
|
||||
retired = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if self.alive && matches!(self.phase, DevPhase::Exiting { .. }) {
|
||||
if self.fx_a[0] + (self.fx_b[0] - self.fx_a[0]) * p < 1.0 / 255.0 {
|
||||
self.retire();
|
||||
retired = true;
|
||||
}
|
||||
}
|
||||
let reported = retired || self.pending_exit;
|
||||
self.pending_exit = false;
|
||||
reported
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The walk.
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Step {
|
||||
Insert { mount: Mount, delay: f32 },
|
||||
Retransition,
|
||||
Remove,
|
||||
Reenter,
|
||||
EnterNow,
|
||||
LandWaiting,
|
||||
Unmount,
|
||||
Tick,
|
||||
}
|
||||
|
||||
fn run(cfg: Cfg, steps: &[Step]) {
|
||||
let mut scene = Scene::new();
|
||||
let mut dev = Dev::new(cfg.mount, cfg.springs);
|
||||
let mut t = 0.0;
|
||||
for step in steps {
|
||||
// The presence the store has shown so far, which is what dev read before changing
|
||||
// anything: read before the call, for the same reason.
|
||||
let p = presence(&scene, ID);
|
||||
match *step {
|
||||
Step::Insert { mount, delay } => {
|
||||
if delay > 0.0 {
|
||||
scene.insert_delayed(ID, spec(cfg.mount), mount, delay);
|
||||
} else {
|
||||
scene.insert(ID, spec(cfg.mount), mount);
|
||||
}
|
||||
dev.insert(cfg.mount, mount, delay, p);
|
||||
}
|
||||
Step::Retransition => {
|
||||
scene.set_transition(ID, cfg.retarget);
|
||||
dev.set_transition(cfg.retarget);
|
||||
}
|
||||
Step::Remove => {
|
||||
scene.remove(ID);
|
||||
dev.remove(p);
|
||||
}
|
||||
Step::Reenter => {
|
||||
scene.reenter(ID);
|
||||
dev.reenter();
|
||||
}
|
||||
Step::EnterNow => {
|
||||
scene.enter_now(ID);
|
||||
dev.enter_now();
|
||||
}
|
||||
Step::LandWaiting => {
|
||||
scene.land_waiting(ID);
|
||||
dev.land_waiting(p);
|
||||
}
|
||||
Step::Unmount => {
|
||||
scene.unmount(ID);
|
||||
dev.unmount();
|
||||
}
|
||||
Step::Tick => {
|
||||
for _ in 0..24 {
|
||||
tick(&mut scene, &mut dev, ID, scene_frame(), &mut t, true, steps);
|
||||
}
|
||||
}
|
||||
}
|
||||
check_state(&scene, &dev, steps);
|
||||
}
|
||||
}
|
||||
|
||||
fn check_state(scene: &Scene, dev: &Dev, steps: &[Step]) {
|
||||
assert_eq!(scene.contains(ID), dev.alive, "in the scene after {steps:?}");
|
||||
if !dev.alive {
|
||||
assert_eq!(scene.phase(ID), None, "phase after {steps:?}");
|
||||
return;
|
||||
}
|
||||
let want = match dev.phase {
|
||||
DevPhase::Entering => Phase::Entering,
|
||||
DevPhase::Present => Phase::Present,
|
||||
DevPhase::Exiting { generation } => Phase::Exiting { generation },
|
||||
};
|
||||
assert_eq!(scene.phase(ID), Some(want), "phase after {steps:?}");
|
||||
}
|
||||
|
||||
fn check_presented(p: &Presented, dev: &Dev, presence: f32, frame: Rect, steps: &[Step]) {
|
||||
let look = lerp(&dev.fx_a, &dev.fx_b, presence);
|
||||
let shown = Vec2::new(
|
||||
frame.x + look[2] + look[4] * frame.w,
|
||||
frame.y + look[3] + look[5] * frame.h,
|
||||
);
|
||||
let close = |got: f32, want: f32, tol: f32, what: &str| {
|
||||
assert!((got - want).abs() <= tol, "{what} {got} vs {want} after {steps:?}");
|
||||
};
|
||||
close(p.opacity, look[0].clamp(0.0, 1.0), 1e-6, "opacity");
|
||||
close(p.transform.scale.x, look[1], 1e-6, "scale");
|
||||
// Presented rects snap to 1/64 device px.
|
||||
close(p.rect.x, shown.x, 2.0 / 64.0, "rect.x");
|
||||
close(p.rect.y, shown.y, 2.0 / 64.0, "rect.y");
|
||||
let blur = if look[6].max(0.0) < 1.0 / 64.0 { 0.0 } else { look[6].max(0.0) };
|
||||
close(p.blur, blur, 1e-6, "blur");
|
||||
close(p.draw, look[8].clamp(0.0, 1.0), 1e-6, "draw");
|
||||
close(p.anchor.x, shown.x + dev.anchor.x * frame.w, 2.0 / 64.0, "anchor.x");
|
||||
close(p.anchor.y, shown.y + dev.anchor.y * frame.h, 2.0 / 64.0, "anchor.y");
|
||||
let (mut inset, mut feather) = ([0.0f32; 4], [0.0f32; 4]);
|
||||
if let Some(rv) = dev.reveal {
|
||||
let hidden = look[7].clamp(0.0, 1.0);
|
||||
if hidden > 0.0 {
|
||||
let (side, len) = match rv.edge {
|
||||
Edge::Leading => (0, frame.w),
|
||||
Edge::Top => (1, frame.h),
|
||||
Edge::Trailing => (2, frame.w),
|
||||
Edge::Bottom => (3, frame.h),
|
||||
};
|
||||
let opposite = (side + 2) % 4;
|
||||
inset[opposite] += hidden * len;
|
||||
feather[opposite] = rv.feather * (hidden * len / rv.feather.max(1e-3)).min(1.0);
|
||||
}
|
||||
}
|
||||
for k in 0..4 {
|
||||
close(p.mask.inset.0[k], inset[k], 1e-4, "mask inset");
|
||||
close(p.mask.feather.0[k], feather[k], 1e-4, "mask feather");
|
||||
}
|
||||
assert_eq!(
|
||||
p.in_flow,
|
||||
!matches!(dev.phase, DevPhase::Exiting { .. }) || !dev.transition.pop_layout,
|
||||
"in_flow after {steps:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn enumerate(cfg: Cfg, alphabet: &[Step], depth: usize, path: &mut Vec<Step>) {
|
||||
if !path.is_empty() {
|
||||
run(cfg, path);
|
||||
}
|
||||
if path.len() == depth {
|
||||
return;
|
||||
}
|
||||
for step in alphabet {
|
||||
path.push(*step);
|
||||
enumerate(cfg, alphabet, depth, path);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Mounts, landings, retransitions, exits and revivals, every sequence up to five long.
|
||||
#[test]
|
||||
fn walk_entrances_and_exits() {
|
||||
let cfg = Cfg { mount: blur_reveal(slow()), retarget: push_draw(slow()), springs: slow() };
|
||||
let alphabet = [
|
||||
Step::Insert { mount: Mount::Animated, delay: 0.0 },
|
||||
Step::Insert { mount: Mount::Initial, delay: 0.0 },
|
||||
Step::Retransition,
|
||||
Step::Remove,
|
||||
Step::Reenter,
|
||||
Step::Tick,
|
||||
];
|
||||
enumerate(cfg, &alphabet, 5, &mut Vec::new());
|
||||
}
|
||||
|
||||
/// A held entrance, landed either way, and the paths that unmount without an exit.
|
||||
#[test]
|
||||
fn walk_held_entrances() {
|
||||
let cfg = Cfg { mount: blur_reveal(slow()), retarget: push_draw(slow()), springs: slow() };
|
||||
let alphabet = [
|
||||
Step::Insert { mount: Mount::Animated, delay: 0.05 },
|
||||
Step::EnterNow,
|
||||
Step::LandWaiting,
|
||||
Step::Remove,
|
||||
Step::Unmount,
|
||||
Step::Tick,
|
||||
];
|
||||
enumerate(cfg, &alphabet, 5, &mut Vec::new());
|
||||
}
|
||||
|
||||
/// A slide that doesn't fade: removed before it shows, it leaves from its insertion look instead
|
||||
/// of unmounting unseen. Its retarget pivots the exit somewhere else.
|
||||
#[test]
|
||||
fn walk_visible_entrances_that_never_played() {
|
||||
let cfg = Cfg { mount: slide(slow()), retarget: corner_scale(slow()), springs: slow() };
|
||||
let alphabet = [
|
||||
Step::Insert { mount: Mount::Animated, delay: 0.0 },
|
||||
Step::Insert { mount: Mount::Initial, delay: 0.0 },
|
||||
Step::Retransition,
|
||||
Step::Remove,
|
||||
Step::Reenter,
|
||||
Step::Tick,
|
||||
];
|
||||
enumerate(cfg, &alphabet, 5, &mut Vec::new());
|
||||
}
|
||||
|
||||
/// Presence that lands at once, so an exit settles on the frame it starts.
|
||||
#[test]
|
||||
fn walk_instant_presence() {
|
||||
let cfg = Cfg { mount: blur_reveal(SpringPair::NONE), retarget: push_draw(SpringPair::NONE), springs: SpringPair::NONE };
|
||||
let alphabet = [
|
||||
Step::Insert { mount: Mount::Animated, delay: 0.0 },
|
||||
Step::Retransition,
|
||||
Step::Remove,
|
||||
Step::Reenter,
|
||||
Step::EnterNow,
|
||||
Step::Tick,
|
||||
];
|
||||
enumerate(cfg, &alphabet, 5, &mut Vec::new());
|
||||
}
|
||||
|
||||
/// `match_geometry` onto a node that is exiting keeps the look that exit was leaving from: dev
|
||||
/// replaced only the absent look, so the exit's presence-1 look still shows at presence 1.
|
||||
#[test]
|
||||
fn matched_geometry_onto_an_exit_keeps_the_look_it_was_leaving_from() {
|
||||
let (from, to) = (NodeId(30), NodeId(1));
|
||||
let transition = push_draw(slow());
|
||||
let matched = |exit_first: bool| {
|
||||
let to_spec = NodeSpec::new(Rect::new(40.0, 20.0, 100.0, 40.0)).transition(transition);
|
||||
let mut scene = Scene::new();
|
||||
let mut dev = Dev::new(transition, slow());
|
||||
scene.insert(from, NodeSpec::new(Rect::new(0.0, 0.0, 20.0, 20.0)), Mount::Initial);
|
||||
scene.insert(to, to_spec, Mount::Animated);
|
||||
dev.insert(transition, Mount::Animated, 0.0, 1.0);
|
||||
let mut t = 0.0;
|
||||
advance(&mut scene, &mut dev, to, to_spec.frame, &mut t, 4, true);
|
||||
if exit_first {
|
||||
scene.remove(to);
|
||||
dev.remove(presence(&scene, to));
|
||||
advance(&mut scene, &mut dev, to, to_spec.frame, &mut t, 3, true);
|
||||
}
|
||||
scene.match_geometry(from, to, slow());
|
||||
dev.matched();
|
||||
// A screen path now places the node, so only the presence's own look is compared.
|
||||
advance(&mut scene, &mut dev, to, to_spec.frame, &mut t, 1, false);
|
||||
(scene.presented(to).unwrap(), dev)
|
||||
};
|
||||
let (kept, dev) = matched(true);
|
||||
let (plain, _) = matched(false);
|
||||
assert_eq!((kept.phase, plain.phase), (Phase::Present, Phase::Present));
|
||||
let (_, at1) = dev.looks();
|
||||
assert!(at1[5].abs() > 1.0, "the exit's solved look keeps an offset of its own ({})", at1[5]);
|
||||
// The offset is a fraction of the height it is drawn at, which the screen path is still
|
||||
// carrying from the node it matched from.
|
||||
assert!(
|
||||
((kept.rect.y - plain.rect.y) - at1[5] * kept.rect.h).abs() <= 2.0 / 64.0,
|
||||
"{} vs {} for an offset of {} of {}",
|
||||
kept.rect.y,
|
||||
plain.rect.y,
|
||||
at1[5],
|
||||
kept.rect.h
|
||||
);
|
||||
}
|
||||
|
||||
/// One frame of `node`: time moves, the scene frames at it, and the reference alone says whether
|
||||
/// dev would report the node as exited this frame.
|
||||
///
|
||||
/// The reference's own presence track runs the walk's configured springs on the same clock, and
|
||||
/// the scene's presence is compared against it every frame, so a scene that runs an exit for a
|
||||
/// different duration than the transition asked for fails here rather than agreeing with itself.
|
||||
fn tick(scene: &mut Scene, dev: &mut Dev, node: NodeId, frame: Rect, t: &mut f64, compare: bool, steps: &[Step]) {
|
||||
*t += DT;
|
||||
scene.set_time(*t);
|
||||
let p = presence(scene, node);
|
||||
let (settled, exited, changed) = {
|
||||
let out = scene.frame();
|
||||
let settled = out.events.iter().any(|e| {
|
||||
matches!(*e, MotionEvent::Settled { node: n, prop: q, .. } if n == node && q == prop::PRESENCE.id)
|
||||
});
|
||||
(settled, out.exited.contains(&node), out.changed.iter().find(|p| p.node == node).copied())
|
||||
};
|
||||
let (ref_p, ref_settled) = dev.reference_frame(*t);
|
||||
if dev.alive {
|
||||
assert!((p - ref_p).abs() <= 1e-6, "presence {p} vs {ref_p} after {steps:?}");
|
||||
assert_eq!(settled, ref_settled, "presence settles after {steps:?}");
|
||||
}
|
||||
let reported = dev.frame(dev.alive && ref_settled, ref_p);
|
||||
assert_eq!(exited, reported, "exited on this frame after {steps:?}");
|
||||
if compare && let Some(shown) = changed {
|
||||
// A delayed start only gets its layer on the tick that starts it, so a node still in the
|
||||
// scene is asked again after the frame; one that was unmounted keeps the value above.
|
||||
let shown_at = if scene.contains(node) { presence(scene, node) } else { p };
|
||||
check_presented(&shown, dev, shown_at, frame, steps);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `frames` frames of `node`, comparing what it presents against `dev` unless a screen path
|
||||
/// places it.
|
||||
fn advance(scene: &mut Scene, dev: &mut Dev, node: NodeId, frame: Rect, t: &mut f64, frames: usize, compare: bool) {
|
||||
for _ in 0..frames {
|
||||
tick(scene, dev, node, frame, t, compare, &[]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A child whose path started before its parent's is checked first, as dev's travelling list
|
||||
/// checked it: its arrival waits on the parent's own frame animation, which landing the parent
|
||||
/// ends, so it lands the frame after the parent. Scanning the tree would land the parent first
|
||||
/// and let the child land on that same frame, one early.
|
||||
#[test]
|
||||
fn a_child_that_started_travelling_first_lands_the_frame_after_its_parent() {
|
||||
let (p, c) = (NodeId(10), NodeId(11));
|
||||
let child_frame = Rect::new(10.0, 10.0, 50.0, 50.0);
|
||||
let mut s = Scene::new();
|
||||
s.insert(p, NodeSpec::new(Rect::new(0.0, 0.0, 400.0, 400.0)), Mount::Initial);
|
||||
s.insert(c, NodeSpec::new(child_frame).parent(p), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
let travel = LayoutAnim::new(Spring::new(0.3, 0.0));
|
||||
s.launch(c, Rect::new(300.0, 300.0, 50.0, 50.0), travel);
|
||||
s.launch(p, Rect::new(100.0, 100.0, 400.0, 400.0), travel);
|
||||
// The parent keeps animating its own frame while it travels, so its travel track arriving is
|
||||
// not what stops a child from landing on it.
|
||||
s.animate(p, prop::FRAME, Rect::new(20.0, 20.0, 400.0, 400.0), Spring::new(2.0, 0.0));
|
||||
let (mut parent, mut child) = (None, None);
|
||||
for k in 1..600 {
|
||||
s.frame_at(k as f64 / 120.0);
|
||||
parent = parent.or_else(|| s.is_resting_at(p, Rect::new(0.0, 0.0, 400.0, 400.0)).then_some(k));
|
||||
child = child.or_else(|| s.is_resting_at(c, child_frame).then_some(k));
|
||||
if parent.is_some() && child.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (parent, child) = (parent.expect("the parent lands"), child.expect("the child lands"));
|
||||
assert_eq!(child, parent + 1, "parent landed on {parent}, child on {child}");
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use rune_motion::{Scene, NodeId, NodeSpec, Rect, Mount, Spring};
|
||||
|
||||
#[test]
|
||||
fn jittered_sampling_and_retarget_audit_stay_bounded() {
|
||||
let mut scene = Scene::new();
|
||||
scene.store_mut().audit_retargets(true);
|
||||
scene.insert(NodeId(1), NodeSpec::new(Rect::new(0.0, 0.0, 200.0, 200.0)), Mount::Initial);
|
||||
scene.insert(NodeId(2), NodeSpec::new(Rect::new(10.0, 10.0, 50.0, 50.0)).parent(NodeId(1)), Mount::Initial);
|
||||
scene.frame_at(0.0);
|
||||
let mut now = 0.0;
|
||||
let mut seed = 7u32;
|
||||
for i in 0..300 {
|
||||
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
now += 1.0 / 120.0 + (seed % 12000) as f64 / 1e6;
|
||||
scene.set_time(now);
|
||||
if i % 7 == 0 {
|
||||
let x = (seed % 300) as f32;
|
||||
scene.set_frame(NodeId(1), Rect::new(x, x / 2.0, 200.0, 200.0), Spring::new(0.4, 0.0));
|
||||
scene.set_frame(NodeId(2), Rect::new(x / 4.0, x / 3.0, 50.0, 50.0), Spring::new(0.3, 0.0));
|
||||
}
|
||||
scene.frame();
|
||||
let (samples, error) = scene.sampling_error();
|
||||
assert_eq!(samples, 8);
|
||||
assert!(error < 0.016, "analytic edge error {error}px at {now}");
|
||||
}
|
||||
let audit = scene.store_mut().take_retarget_audit();
|
||||
assert!(audit.lanes > 100);
|
||||
assert!(audit.max_velocity_error < 0.001, "{audit:?}");
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{MotionTrace, Phase, SMALL_SCALE_FLOOR, TraceHeader, flags};
|
||||
|
||||
const HZ: f64 = 120.0;
|
||||
|
||||
#[test]
|
||||
fn pixel_scale_resnaps_settled_nodes_without_retargeting() {
|
||||
let make = |scale| {
|
||||
let mut scene = Scene::new();
|
||||
scene.set_pixel_scale(scale);
|
||||
scene.insert(NodeId(1), spec(0.123, 0.137, 30.123, 20.137), Mount::Initial);
|
||||
scene.frame_at(0.0);
|
||||
scene
|
||||
};
|
||||
let mut scene = make(1.0);
|
||||
for scale in [2.0, 1.5, 1.0] {
|
||||
scene.set_pixel_scale(scale);
|
||||
assert_eq!(scene.frame_at(0.0).changed.len(), 1, "scale changes invalidate settled poses");
|
||||
let fresh = make(scale);
|
||||
assert_eq!(scene.presented(NodeId(1)).unwrap().rect, fresh.presented(NodeId(1)).unwrap().rect);
|
||||
scene.set_pixel_scale(scale);
|
||||
assert!(scene.frame_at(0.0).changed.is_empty(), "an unchanged scale does no work");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_frame_lands_an_unchanged_target_mid_flight() {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(1);
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 40.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
let target = Rect::new(30.0, 60.0, 200.0, 120.0);
|
||||
s.set_frame(id, target, Spring::new(0.32, 0.0));
|
||||
assert!(s.frame_at(0.05).animating);
|
||||
s.set_frame(id, target, LayoutAnim::INSTANT);
|
||||
assert!(!s.frame_at(0.05).animating);
|
||||
assert_eq!(s.presented(id).unwrap().rect, target);
|
||||
}
|
||||
|
||||
fn find(out: &[Presented], id: NodeId) -> Option<Presented> {
|
||||
out.iter().find(|p| p.node == id).copied()
|
||||
}
|
||||
|
||||
fn spec(x: f32, y: f32, w: f32, h: f32) -> NodeSpec {
|
||||
NodeSpec::new(Rect::new(x, y, w, h))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_mount_does_not_animate() {
|
||||
let mut s = Scene::new();
|
||||
s.insert(NodeId(1), spec(0.0, 0.0, 100.0, 40.0).transition(Transition::blur_replace()), Mount::Initial);
|
||||
let out = s.frame_at(0.0);
|
||||
let p = find(out.changed, NodeId(1)).unwrap();
|
||||
assert_eq!((p.opacity, p.blur, p.transform.scale.x), (1.0, 0.0, 1.0));
|
||||
assert!(!out.animating);
|
||||
assert_eq!(p.phase, Phase::Present);
|
||||
}
|
||||
|
||||
/// Steps the scene at `HZ` until `until`, collecting every presented value of `id`.
|
||||
fn run(s: &mut Scene, from: f64, until: f64, id: NodeId) -> (Vec<(f64, Presented)>, Option<f64>) {
|
||||
let mut seen = Vec::new();
|
||||
let mut exited_at = None;
|
||||
let mut t = from;
|
||||
while t <= until + 1e-9 {
|
||||
let out = s.frame_at(t);
|
||||
if let Some(p) = find(out.changed, id) {
|
||||
seen.push((t, p));
|
||||
}
|
||||
if out.exited.contains(&id) && exited_at.is_none() {
|
||||
exited_at = Some(t);
|
||||
}
|
||||
t += 1.0 / HZ;
|
||||
}
|
||||
(seen, exited_at)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blur_replace_enters_and_exits_and_never_unmounts_visible() {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(2);
|
||||
s.insert(id, spec(0.0, 0.0, 200.0, 60.0).transition(Transition::blur_replace()), Mount::Animated);
|
||||
let (enter, _) = run(&mut s, 0.0, 1.0, id);
|
||||
let first = enter[0].1;
|
||||
assert!(first.opacity < 1e-3 && (first.blur - 1.5).abs() < 1e-3 && (first.transform.scale.x - 0.96).abs() < 1e-4);
|
||||
let last = enter.last().unwrap().1;
|
||||
assert_eq!((last.opacity, last.blur, last.transform.scale.x), (1.0, 0.0, 1.0), "rests exactly, no filter");
|
||||
assert_eq!(s.phase(id), Some(Phase::Present));
|
||||
let enter_time = enter.last().unwrap().0;
|
||||
|
||||
s.set_time(2.0);
|
||||
s.remove(id);
|
||||
let (exit, exited_at) = run(&mut s, 2.0, 3.0, id);
|
||||
let exited_at = exited_at.expect("exit finishes");
|
||||
// Drawn every frame until it's gone; the final presented frame is fully transparent.
|
||||
let final_frame = exit.iter().rev().find(|(t, _)| *t <= exited_at).unwrap().1;
|
||||
assert!(final_frame.opacity < 1.0 / 255.0, "unmounted at opacity {}", final_frame.opacity);
|
||||
for (_, p) in &exit {
|
||||
assert!(p.blur <= 1.5 + 1e-3 && p.transform.scale.x >= 0.9);
|
||||
assert!(!p.in_flow, "popLayout: exiting nodes leave flow");
|
||||
}
|
||||
assert!(!s.contains(id));
|
||||
// Exits run shorter than entrances.
|
||||
assert!(exited_at - 2.0 < enter_time, "exit {} vs enter {}", exited_at - 2.0, enter_time);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exit_unmounts_once_it_fades_out_of_sight() {
|
||||
for transition in [Transition::opacity(), Transition::push(Edge::Bottom), Transition::scale(0.9)] {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(4);
|
||||
s.insert(id, spec(0.0, 0.0, 120.0, 40.0).transition(transition), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.remove(id);
|
||||
let (exit, exited_at) = run(&mut s, 0.0, 1.0, id);
|
||||
let exited_at = exited_at.expect("exit finishes");
|
||||
let unseen = exit.iter().find(|(_, p)| p.opacity < 1.0 / 255.0).expect("fades out").0;
|
||||
assert_eq!(exited_at, unseen, "unmounts the frame it can no longer be seen");
|
||||
}
|
||||
}
|
||||
|
||||
fn same_look(a: &Presented, b: &Presented) {
|
||||
let close = |x: f32, y: f32| (x - y).abs() < 2e-3;
|
||||
assert!(close(a.opacity, b.opacity), "opacity {} → {}", a.opacity, b.opacity);
|
||||
assert!(close(a.blur, b.blur), "blur {} → {}", a.blur, b.blur);
|
||||
assert!(close(a.transform.scale.x, b.transform.scale.x));
|
||||
assert!(close(a.rect.x, b.rect.x) && close(a.rect.y, b.rect.y), "{:?} → {:?}", a.rect, b.rect);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_that_returns_mid_exit_revives_without_a_jump() {
|
||||
for transition in [Transition::blur_replace(), Transition::push(Edge::Bottom), Transition::scale(0.9)] {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(3);
|
||||
let sp = spec(0.0, 0.0, 120.0, 40.0).transition(transition);
|
||||
s.insert(id, sp, Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.remove(id);
|
||||
let (_, gone) = run(&mut s, 0.0, 0.1, id);
|
||||
assert!(gone.is_none());
|
||||
let t = 0.1 + 1.0 / HZ;
|
||||
let before = find(s.frame_at(t).changed, id).unwrap();
|
||||
s.insert(id, sp, Mount::Animated); // same key comes back
|
||||
let after = find(s.frame_at(t).changed, id).unwrap();
|
||||
same_look(&before, &after);
|
||||
assert_eq!(after.phase, Phase::Entering);
|
||||
// ... and lands exactly at rest.
|
||||
let (seen, gone) = run(&mut s, t, t + 1.5, id);
|
||||
assert!(gone.is_none());
|
||||
let rest = seen.last().unwrap().1;
|
||||
assert_eq!((rest.opacity, rest.blur, rest.transform.scale.x), (1.0, 0.0, 1.0));
|
||||
assert_eq!(rest.rect, Rect::new(0.0, 0.0, 120.0, 40.0));
|
||||
// The same, the other way round: removed mid-entrance.
|
||||
let mut s = Scene::new();
|
||||
s.insert(NodeId(9), spec(0.0, 0.0, 10.0, 10.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.insert(id, sp, Mount::Animated);
|
||||
run(&mut s, 0.0, 0.08, id);
|
||||
let t = 0.08 + 1.0 / HZ;
|
||||
let before = find(s.frame_at(t).changed, id).unwrap();
|
||||
s.remove(id);
|
||||
let after = find(s.frame_at(t).changed, id).unwrap();
|
||||
same_look(&before, &after);
|
||||
let (seen, gone) = run(&mut s, t, t + 1.0, id);
|
||||
assert!(gone.is_some());
|
||||
assert!(seen.last().unwrap().1.opacity < 1.0 / 255.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_that_returns_mid_exit_on_an_initial_mount_lands_at_rest() {
|
||||
for transition in [Transition::opacity(), Transition::blur_replace(), Transition::push(Edge::Bottom)] {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(5);
|
||||
let sp = spec(0.0, 0.0, 120.0, 40.0).transition(transition);
|
||||
s.insert(id, sp, Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.remove(id);
|
||||
// Deep in the exit tail.
|
||||
let (seen, gone) = run(&mut s, 0.0, 0.2, id);
|
||||
assert!(gone.is_none() && seen.last().unwrap().1.opacity < 0.2);
|
||||
let t = 0.2 + 1.0 / HZ;
|
||||
let moved = Rect::new(10.0, 30.0, 140.0, 40.0);
|
||||
s.insert(id, NodeSpec::new(moved).transition(transition), Mount::Initial);
|
||||
let out = s.frame_at(t);
|
||||
assert!(!out.animating, "nothing left to animate");
|
||||
let p = find(out.changed, id).unwrap();
|
||||
assert_eq!((p.opacity, p.blur, p.transform.scale.x, p.phase), (1.0, 0.0, 1.0, Phase::Present));
|
||||
assert_eq!(p.rect, moved, "at its final layout");
|
||||
// The stale exit never retires it.
|
||||
let (seen, gone) = run(&mut s, t, t + 1.0, id);
|
||||
assert!(gone.is_none() && s.contains(id));
|
||||
assert!(seen.iter().all(|(_, p)| p.opacity == 1.0 && p.rect == moved));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_initial_mount_revive_lands_motion_toward_the_same_frame_and_screen_travel() {
|
||||
for screen in [false, true] {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(6);
|
||||
let target = Rect::new(60.0, 80.0, 120.0, 40.0);
|
||||
s.insert(id, spec(0.0, 0.0, 120.0, 40.0).transition(Transition::opacity()), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
let slow = LayoutAnim::new(Spring::new(1.0, 0.0));
|
||||
s.set_frame(id, target, if screen { slow.screen() } else { slow });
|
||||
s.frame_at(0.05);
|
||||
s.remove(id);
|
||||
let (seen, gone) = run(&mut s, 0.05, 0.15, id);
|
||||
assert!(gone.is_none() && seen.last().unwrap().1.rect != target, "still travelling");
|
||||
let t = 0.15 + 1.0 / HZ;
|
||||
s.insert(id, NodeSpec::new(target).transition(Transition::opacity()), Mount::Initial);
|
||||
let out = s.frame_at(t);
|
||||
assert!(!out.animating, "nothing left to animate (screen: {screen})");
|
||||
let p = find(out.changed, id).unwrap();
|
||||
assert_eq!((p.opacity, p.rect, p.phase), (1.0, target, Phase::Present));
|
||||
let (seen, _) = run(&mut s, t, t + 1.0, id);
|
||||
assert!(seen.iter().all(|(_, p)| p.opacity == 1.0 && p.rect == target));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stationary_edges_never_move_and_width_leads() {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(4);
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 50.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.set_frame(id, Rect::new(0.0, 20.0, 300.0, 30.0), LayoutAnim::new(motion::REFLOW).width_leads());
|
||||
let (seen, _) = run(&mut s, 0.0, 1.5, id);
|
||||
assert!(seen.len() > 30);
|
||||
let mut x_ahead = 0;
|
||||
for (_, p) in &seen {
|
||||
assert_eq!(p.rect.x, 0.0, "left edge is stationary");
|
||||
assert_eq!(p.rect.y + p.rect.h, 50.0, "bottom edge is stationary");
|
||||
let xp = (p.rect.right() - 100.0) / 200.0;
|
||||
let yp = p.rect.y / 20.0;
|
||||
if xp > yp + 1e-3 {
|
||||
x_ahead += 1;
|
||||
}
|
||||
}
|
||||
assert!(x_ahead > 10, "width leads ({x_ahead} frames ahead)");
|
||||
assert_eq!(seen.last().unwrap().1.rect, Rect::new(0.0, 20.0, 300.0, 30.0));
|
||||
}
|
||||
|
||||
fn max_path_deviation(points: &[(f32, f32)], start: (f32, f32), end: (f32, f32)) -> f32 {
|
||||
let (dx, dy) = (end.0 - start.0, end.1 - start.1);
|
||||
let len = (dx * dx + dy * dy).sqrt();
|
||||
points
|
||||
.iter()
|
||||
.map(|&(x, y)| ((x - start.0) * dy - (y - start.1) * dx).abs() / len)
|
||||
.fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_travel_takes_one_straight_path() {
|
||||
let child_path = |screen: bool| {
|
||||
let mut s = Scene::new();
|
||||
let (p, c) = (NodeId(10), NodeId(11));
|
||||
s.insert(p, spec(0.0, 0.0, 400.0, 400.0), Mount::Initial);
|
||||
s.insert(c, spec(10.0, 10.0, 50.0, 50.0).parent(p), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
// One commit: the parent glides, the child moves inside it on a different spring.
|
||||
s.set_frame(p, Rect::new(200.0, 100.0, 400.0, 400.0), motion::GLIDE);
|
||||
let child = LayoutAnim::new(motion::DRIFT);
|
||||
s.set_frame(c, Rect::new(100.0, 200.0, 50.0, 50.0), if screen { child.screen() } else { child });
|
||||
let (seen, _) = run(&mut s, 0.0, 3.0, c);
|
||||
let pts: Vec<_> = seen.iter().map(|(_, q)| (q.rect.x, q.rect.y)).collect();
|
||||
let last = *pts.last().unwrap();
|
||||
(pts, last, s)
|
||||
};
|
||||
let (pts, last, mut s) = child_path(true);
|
||||
assert_eq!(last, (300.0, 300.0));
|
||||
let dev = max_path_deviation(&pts, (10.0, 10.0), (300.0, 300.0));
|
||||
assert!(dev < 0.05, "screen travel deviates {dev} pt from a straight line");
|
||||
// Monotone: never reverses.
|
||||
for w in pts.windows(2) {
|
||||
assert!(w[1].0 >= w[0].0 - 1e-3 && w[1].1 >= w[0].1 - 1e-3);
|
||||
}
|
||||
// Once there, the child rides its parent again.
|
||||
s.set_frame(NodeId(10), Rect::new(0.0, 0.0, 400.0, 400.0), Anim::INSTANT);
|
||||
let out = s.frame_at(3.1);
|
||||
assert_eq!(find(out.changed, NodeId(11)).unwrap().rect.origin(), Vec2::new(100.0, 200.0));
|
||||
|
||||
let (pts, _, _) = child_path(false);
|
||||
let dev = max_path_deviation(&pts, (10.0, 10.0), (300.0, 300.0));
|
||||
assert!(dev > 2.0, "parent-space travel with mixed springs dog-legs ({dev} pt): the test bites");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matched_geometry_morphs_one_surface() {
|
||||
let mut s = Scene::new();
|
||||
let (chip, panel) = (NodeId(20), NodeId(21));
|
||||
let red = Color::hex(0xff3b30);
|
||||
let white = Color::WHITE;
|
||||
s.insert(chip, spec(10.0, 10.0, 80.0, 30.0).radius(15.0).fill(red), Mount::Initial);
|
||||
let before = find(s.frame_at(0.0).changed, chip).unwrap();
|
||||
s.set_time(1.0 / HZ);
|
||||
s.insert(panel, spec(0.0, 100.0, 300.0, 200.0).radius(12.0).fill(white), Mount::Initial);
|
||||
s.match_geometry(chip, panel, LayoutAnim::new(motion::MORPH).width_leads());
|
||||
let out = s.frame_at(1.0 / HZ);
|
||||
assert!(out.exited.contains(&chip));
|
||||
let first = find(out.changed, panel).unwrap();
|
||||
assert_eq!(first.rect, before.rect, "starts exactly where the chip was seen");
|
||||
assert_eq!(first.radius, Corners::all(15.0));
|
||||
assert!((first.fill.r - red.r).abs() < 2e-3 && first.opacity == 1.0);
|
||||
let (seen, _) = run(&mut s, 2.0 / HZ, 2.0, panel);
|
||||
let last = seen.last().unwrap().1;
|
||||
assert_eq!(last.rect, Rect::new(0.0, 100.0, 300.0, 200.0));
|
||||
assert_eq!(last.radius, Corners::all(12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduced_motion_swaps_travel_for_a_short_fade() {
|
||||
let mut s = Scene::new();
|
||||
s.set_reduced_motion(true);
|
||||
let id = NodeId(30);
|
||||
s.insert(NodeId(31), spec(0.0, 0.0, 10.0, 10.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 40.0).transition(Transition::blur_replace().combined(Transition::push(Edge::Top))), Mount::Animated);
|
||||
let first = find(s.frame_at(0.0).changed, id).unwrap();
|
||||
assert_eq!((first.blur, first.transform.scale.x, first.rect.y), (0.0, 1.0, 0.0), "no blur, scale or travel");
|
||||
assert!(first.opacity < 1e-3);
|
||||
let mid = find(s.frame_at(0.09).changed, id).unwrap();
|
||||
assert!(mid.opacity > 0.3 && mid.opacity < 0.7, "{}", mid.opacity);
|
||||
assert_eq!(find(s.frame_at(0.18).changed, id).unwrap().opacity, 1.0);
|
||||
s.set_frame(id, Rect::new(50.0, 50.0, 100.0, 40.0), motion::GLIDE);
|
||||
assert_eq!(find(s.frame_at(0.2).changed, id).unwrap().rect.origin(), Vec2::new(50.0, 50.0), "layout jumps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn children_ride_their_parent_in_and_out() {
|
||||
let mut s = Scene::new();
|
||||
let (p, c) = (NodeId(40), NodeId(41));
|
||||
s.insert(NodeId(1), spec(0.0, 0.0, 1.0, 1.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.insert(p, spec(0.0, 0.0, 100.0, 100.0).transition(Transition::move_edge(Edge::Leading)), Mount::Animated);
|
||||
s.insert(c, spec(10.0, 10.0, 20.0, 20.0).parent(p), Mount::Animated);
|
||||
let out = s.frame_at(0.0);
|
||||
let (pp, cp) = (find(out.changed, p).unwrap(), find(out.changed, c).unwrap());
|
||||
assert_eq!(cp.phase, Phase::Present, "rides the entering parent instead of animating itself");
|
||||
assert_eq!(cp.rect.x, pp.rect.x + 10.0, "moves with the parent's presence offset");
|
||||
s.set_time(1.0);
|
||||
s.remove(p);
|
||||
let (_, gone) = run(&mut s, 1.0, 2.0, p);
|
||||
assert!(gone.is_some());
|
||||
assert!(!s.contains(c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_mounted_after_its_parent_visibly_arrives_enters_on_its_own() {
|
||||
let mut s = Scene::new();
|
||||
let (p, c) = (NodeId(42), NodeId(43));
|
||||
s.insert(NodeId(1), spec(0.0, 0.0, 1.0, 1.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.insert(p, spec(0.0, 0.0, 100.0, 100.0), Mount::Animated);
|
||||
let mut t = 0.0;
|
||||
loop {
|
||||
t += 1.0 / HZ;
|
||||
let out = s.frame_at(t);
|
||||
if find(out.changed, p).is_some_and(|pp| pp.opacity >= 1.0 - 1.0 / 255.0) { break; }
|
||||
assert!(t < 2.0, "the parent arrives");
|
||||
}
|
||||
assert_eq!(s.phase(p), Some(Phase::Entering), "its presence is still settling");
|
||||
s.set_time(t + 1.0 / HZ);
|
||||
s.insert(c, spec(10.0, 10.0, 20.0, 20.0).parent(p), Mount::Animated);
|
||||
let cp = find(s.frame().changed, c).unwrap();
|
||||
assert_eq!(cp.phase, Phase::Entering, "fades in instead of popping in on a finished entrance");
|
||||
assert!(cp.opacity < 0.5, "{}", cp.opacity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entrance_that_changes_nothing_lands_at_once() {
|
||||
let mut s = Scene::new();
|
||||
s.insert(NodeId(1), spec(0.0, 0.0, 1.0, 1.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
let id = NodeId(46);
|
||||
let spring = SpringPair::new(Spring::new(0.3, 0.0), Spring::new(0.3, 0.0));
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 40.0).transition(Transition::identity().springs(spring)), Mount::Animated);
|
||||
s.set_time(1.0 / HZ);
|
||||
let out = s.frame();
|
||||
assert!(!out.animating, "no presence spring runs for an identity insertion");
|
||||
assert_eq!(s.phase(id), Some(Phase::Present));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_mounted_late_in_its_parents_entrance_enters_on_its_own() {
|
||||
let mut s = Scene::new();
|
||||
let (p, c) = (NodeId(44), NodeId(45));
|
||||
s.insert(NodeId(1), spec(0.0, 0.0, 1.0, 1.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.insert(p, spec(0.0, 0.0, 100.0, 100.0), Mount::Animated);
|
||||
let mut t = 0.0;
|
||||
loop {
|
||||
t += 1.0 / HZ;
|
||||
let out = s.frame_at(t);
|
||||
if find(out.changed, p).is_some_and(|pp| pp.opacity >= 0.9) { break; }
|
||||
assert!(t < 2.0, "the parent arrives");
|
||||
}
|
||||
s.set_time(t + 1.0 / HZ);
|
||||
s.insert(c, spec(10.0, 10.0, 20.0, 20.0).parent(p), Mount::Animated);
|
||||
let cp = find(s.frame().changed, c).unwrap();
|
||||
assert_eq!(cp.phase, Phase::Entering, "fades in instead of appearing at the parent's 90%");
|
||||
assert!(cp.opacity < 0.5, "{}", cp.opacity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_mark_intent_for_motion_lint() {
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(50);
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 40.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.set_frame(id, Rect::new(0.0, 80.0, 100.0, 40.0), motion::SETTLE);
|
||||
let p = find(s.frame_at(0.05).changed, id).unwrap();
|
||||
assert!(p.flags & flags::ANIMATED != 0);
|
||||
assert!((p.flags >> 8) & rune_motion::Intent::POSITION != 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_writes_motion_lint_jsonl() {
|
||||
let mut s = Scene::new();
|
||||
let header = TraceHeader { launch: "test".into(), width: 400.0, height: 300.0, hz: 120.0, scale: 2.0 };
|
||||
let (trace, buf) = MotionTrace::in_memory(&header);
|
||||
s.set_trace(Some(trace));
|
||||
s.insert(NodeId(1), spec(0.0, 0.0, 10.0, 10.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.insert(NodeId(2), spec(0.0, 20.0, 100.0, 40.0).transition(Transition::blur_replace()), Mount::Animated);
|
||||
run(&mut s, 0.0, 0.6, NodeId(2));
|
||||
s.remove(NodeId(2));
|
||||
run(&mut s, 0.6, 1.4, NodeId(2));
|
||||
drop(s.take_trace());
|
||||
let text = buf.contents();
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
assert!(lines[0].starts_with(r#"{"type":"header","launch":"test""#));
|
||||
assert!(lines.iter().any(|l| l.contains(r#""e":[[2,"#)), "elements");
|
||||
assert!(lines.iter().any(|l| l.contains(r#""ai":[[2,"#)), "intents");
|
||||
assert!(lines.iter().any(|l| l.contains(r#""g":[2]"#)), "gone after exit");
|
||||
assert!(lines.iter().all(|l| l.starts_with('{') && l.ends_with('}')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_stays_above_point_nine_unless_a_small_glyph_opts_in() {
|
||||
let start = |t: Transition| {
|
||||
let mut s = Scene::new();
|
||||
s.insert(NodeId(9), spec(0.0, 0.0, 16.0, 16.0).transition(t), Mount::Animated);
|
||||
find(s.frame_at(0.0).changed, NodeId(9)).unwrap().transform.scale.x
|
||||
};
|
||||
assert!((start(Transition::scale(0.6)) - 0.9).abs() < 1e-4, "the default rule");
|
||||
assert!((start(Transition::scale(0.6).allow_small_scale()) - 0.6).abs() < 1e-4);
|
||||
assert!((start(Transition::scale(0.0).allow_small_scale()) - SMALL_SCALE_FLOOR).abs() < 1e-4, "never from 0");
|
||||
assert!((start(Transition::scale(0.6).allow_small_scale().combined(Transition::opacity())) - 0.6).abs() < 1e-4);
|
||||
|
||||
// The removal leaves at the small scale too, still fading out.
|
||||
let mut s = Scene::new();
|
||||
let id = NodeId(10);
|
||||
s.insert(id, spec(0.0, 0.0, 16.0, 16.0).transition(Transition::scale(0.6).allow_small_scale()), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.remove(id);
|
||||
let (exit, exited_at) = run(&mut s, 0.0, 1.0, id);
|
||||
let exited_at = exited_at.expect("exit finishes");
|
||||
let last = exit.iter().rev().find(|(t, _)| *t <= exited_at).unwrap().1;
|
||||
assert!(last.transform.scale.x < 0.65 && last.opacity < 1.0 / 255.0, "{:?}", (last.transform.scale.x, last.opacity));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frozen_ancestor_holds_screen_travel_without_frames() {
|
||||
let mut s = Scene::new();
|
||||
let (p, c) = (NodeId(10), NodeId(11));
|
||||
s.insert(p, spec(0.0, 0.0, 400.0, 400.0), Mount::Initial);
|
||||
s.insert(c, spec(10.0, 10.0, 50.0, 50.0).parent(p), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.set_frame(p, Rect::new(200.0, 100.0, 400.0, 400.0), motion::GLIDE);
|
||||
s.set_frame(c, Rect::new(100.0, 200.0, 50.0, 50.0), LayoutAnim::new(motion::DRIFT).screen());
|
||||
s.frame_at(0.05);
|
||||
s.set_time_scale(p, 0.0);
|
||||
let mut t = 0.05;
|
||||
while t < 3.0 {
|
||||
t += 1.0 / HZ;
|
||||
s.frame_at(t);
|
||||
}
|
||||
assert!(!s.frame_at(t).animating, "the child arrived and its frozen parent asks for no frames");
|
||||
s.set_time_scale(p, 1.0);
|
||||
let (seen, _) = run(&mut s, t, t + 3.0, c);
|
||||
assert!(!s.frame_at(t + 3.1).animating);
|
||||
assert_eq!(seen.last().unwrap().1.rect.origin(), Vec2::new(300.0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_child_rests_where_its_parent_does() {
|
||||
let (p, c) = (NodeId(1), NodeId(2));
|
||||
let mut s = Scene::new();
|
||||
s.insert(p, spec(0.0, 0.0, 40.0, 20.0), Mount::Initial);
|
||||
s.insert(c, spec(30.0, 4.0, 6.0, 6.0).parent(p), Mount::Initial);
|
||||
s.set_ride_trailing(c, true);
|
||||
s.frame_at(0.0);
|
||||
s.set_frame(p, Rect::new(0.0, 0.0, 70.0, 20.0), Spring::new(0.3, 0.0));
|
||||
s.frame_at(0.05);
|
||||
let (shown, rest) = (s.presented(c).unwrap(), s.rest(c));
|
||||
assert!(shown.rect.x > 30.0 && shown.rect.x < 60.0, "{:?}", shown.rect);
|
||||
assert_eq!(rest, Some(Rect::new(60.0, 4.0, 6.0, 6.0)), "the child comes to rest against the parent's new edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_static_node_keeps_no_tracks_and_an_unchanged_commit_leaves_it_clean() {
|
||||
let id = NodeId(1);
|
||||
let frame = Rect::new(0.0, 0.0, 100.0, 40.0);
|
||||
let mut s = Scene::new();
|
||||
s.insert(id, NodeSpec::new(frame).opacity(0.5).radius(Corners([4.0; 4])), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
assert_eq!(s.store().track_len(), 0, "a node that never moves keeps no tracks, presence included");
|
||||
for k in 1..3 {
|
||||
s.set_frame(id, frame, Spring::new(0.3, 0.0));
|
||||
s.animate(id, prop::OPACITY, 0.5, Spring::new(0.3, 0.0));
|
||||
s.set(id, prop::RADIUS, Corners([4.0; 4]));
|
||||
assert!(s.frame_at(k as f64 / HZ).changed.is_empty(), "nothing changed, so nothing presents again");
|
||||
}
|
||||
assert_eq!(s.store().track_len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_settled_track_set_to_its_value_stays_clean() {
|
||||
let id = NodeId(1);
|
||||
let mut s = Scene::new();
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 40.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.animate(id, prop::OPACITY, 0.2, Spring::new(0.2, 0.0));
|
||||
let half = s.frame_at(0.05);
|
||||
let o = find(half.changed, id).unwrap().opacity;
|
||||
assert!(o < 1.0 && o > 0.2, "the first animation starts from the base value: {o}");
|
||||
let mut t = 0.05;
|
||||
while s.frame_at(t).animating { t += 1.0 / HZ; }
|
||||
s.set(id, prop::OPACITY, 0.2);
|
||||
s.animate(id, prop::OPACITY, 0.2, Spring::new(0.2, 0.0));
|
||||
assert!(s.frame_at(t + 1.0 / HZ).changed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_without_a_presence_track_still_fades_out() {
|
||||
let id = NodeId(1);
|
||||
let mut s = Scene::new();
|
||||
s.insert(id, spec(0.0, 0.0, 100.0, 40.0), Mount::Initial);
|
||||
s.frame_at(0.0);
|
||||
s.remove(id);
|
||||
let o = find(s.frame_at(0.05).changed, id).unwrap().opacity;
|
||||
assert!(o > 0.0 && o < 1.0, "the exit plays: {o}");
|
||||
let mut t = 0.05;
|
||||
let mut gone = false;
|
||||
while t < 3.0 && !gone {
|
||||
t += 1.0 / HZ;
|
||||
gone = s.frame_at(t).exited.contains(&id);
|
||||
}
|
||||
assert!(gone);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use rune_motion::{Scene, NodeId, NodeSpec, Rect, Mount};
|
||||
|
||||
#[test]
|
||||
fn sibling_order_matches_reference_after_removal_and_slot_reuse() {
|
||||
for nested in [false, true] {
|
||||
let mut scene = Scene::new();
|
||||
let parent = NodeId(1000);
|
||||
if nested { scene.insert(parent, NodeSpec::new(Rect::ZERO), Mount::Initial); }
|
||||
let mut expected = Vec::new();
|
||||
let mut seed = 1u32;
|
||||
for step in 0..300u64 {
|
||||
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
if !expected.is_empty() && !seed.is_multiple_of(3) {
|
||||
let i = seed as usize % expected.len();
|
||||
scene.unmount(expected.remove(i));
|
||||
} else {
|
||||
let id = NodeId(step);
|
||||
let spec = NodeSpec::new(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
scene.insert(id, if nested { spec.parent(parent) } else { spec }, Mount::Initial);
|
||||
expected.push(id);
|
||||
}
|
||||
// Force every surviving node into the changed list to observe traversal order.
|
||||
for &id in &expected { scene.set(id, rune_motion::prop::OPACITY, if step % 2 == 0 { 0.8 } else { 1.0 }); }
|
||||
let out = scene.frame_at(step as f64 / 120.0);
|
||||
let actual: Vec<_> = out.changed.iter().filter(|p| p.node != parent).map(|p| p.node).collect();
|
||||
assert_eq!(actual, expected, "step {step}, nested {nested}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{Animated, Decay};
|
||||
|
||||
/// RK4 on x'' = −k(x − T) − c x' in f64 with a tiny step: the reference the closed form must match.
|
||||
fn integrate(s: Spring, x0: f64, v0: f64, target: f64, t_end: f64) -> (f64, f64) {
|
||||
let k = (s.stiffness()) as f64;
|
||||
let c = (s.damping()) as f64;
|
||||
let f = |x: f64, v: f64| (v, -k * (x - target) - c * v);
|
||||
let dt = 1e-5;
|
||||
let (mut x, mut v) = (x0, v0);
|
||||
let steps = (t_end / dt).round() as usize;
|
||||
for _ in 0..steps {
|
||||
let (a1, b1) = f(x, v);
|
||||
let (a2, b2) = f(x + 0.5 * dt * a1, v + 0.5 * dt * b1);
|
||||
let (a3, b3) = f(x + 0.5 * dt * a2, v + 0.5 * dt * b2);
|
||||
let (a4, b4) = f(x + dt * a3, v + dt * b3);
|
||||
x += dt / 6.0 * (a1 + 2.0 * a2 + 2.0 * a3 + a4);
|
||||
v += dt / 6.0 * (b1 + 2.0 * b2 + 2.0 * b3 + b4);
|
||||
}
|
||||
(x, v)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_form_matches_ode_integration_in_every_regime() {
|
||||
let springs = [
|
||||
Spring::new(0.3, 0.0), // critical (Kit's default)
|
||||
Spring::new(0.5, 0.3), // under (SwiftUI .bouncy)
|
||||
Spring::new(0.4, 0.7), // very bouncy
|
||||
Spring::new(0.35, -0.5), // over
|
||||
Spring::new(0.6, 0.0005), // near-critical, under
|
||||
Spring::new(0.25, -0.0005), // near-critical, over
|
||||
];
|
||||
let starts = [(0.0f32, 0.0f32), (0.0, 25.0), (0.7, -8.0)];
|
||||
for s in springs {
|
||||
for (x0, v0) in starts {
|
||||
for t in [0.01f32, 0.05, 0.13, 0.3, 0.71] {
|
||||
let (x, v) = s.sample(x0, v0, 1.0, t);
|
||||
let (rx, rv) = integrate(s, x0 as f64, v0 as f64, 1.0, t as f64);
|
||||
// Position within 1e-4 per unit of travel; velocity scaled by ω.
|
||||
assert!((x as f64 - rx).abs() < 1e-4, "{s:?} x0={x0} v0={v0} t={t}: x {x} vs {rx}");
|
||||
let vtol = 1e-4 * s.omega() as f64 + 1e-4 * v0.abs() as f64;
|
||||
assert!((v as f64 - rv).abs() < vtol, "{s:?} x0={x0} v0={v0} t={t}: v {v} vs {rv}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swiftui_parameter_mapping() {
|
||||
// Spring(duration: 0.5, bounce: 0): stiffness (2π/0.5)² ≈ 157.914, damping 4π ≈ 25.133.
|
||||
let s = Spring::new(0.5, 0.0);
|
||||
assert!((s.stiffness() - 157.913_67).abs() < 1e-2, "{}", s.stiffness());
|
||||
assert!((s.damping() - 25.132_74).abs() < 1e-3, "{}", s.damping());
|
||||
assert_eq!(Spring::BOUNCY.zeta(), 0.7);
|
||||
assert!((Spring::SNAPPY.zeta() - 0.85).abs() < 1e-6);
|
||||
assert_eq!(Spring::new(0.4, -0.5).zeta(), 2.0);
|
||||
// Round trips.
|
||||
let back = Spring::from_stiffness_damping(s.stiffness(), s.damping(), 1.0);
|
||||
assert!((back.duration - 0.5).abs() < 1e-5 && back.bounce.abs() < 1e-5);
|
||||
let r = Spring::from_response(0.55, 0.825);
|
||||
assert!((r.duration - 0.55).abs() < 1e-6 && (r.zeta() - 0.825).abs() < 1e-6);
|
||||
let over = Spring::from_omega_zeta(10.0, 2.0);
|
||||
assert!((over.bounce + 0.5).abs() < 1e-6 && (over.zeta() - 2.0).abs() < 1e-5);
|
||||
// Mass: k/m and c/(2√(km)).
|
||||
let m = Spring::from_stiffness_damping(400.0, 20.0, 2.0);
|
||||
assert!((m.omega() - (200.0f32).sqrt()).abs() < 1e-4);
|
||||
// Motion's visualDuration is ours / 1.2.
|
||||
assert!((Spring::from_motion(0.45, 0.0).duration - 0.54).abs() < 1e-6);
|
||||
assert!((motion::GLIDE.motion_visual_duration() - 0.32 / 1.2).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kit_tokens_match_kit_motion_json() {
|
||||
let expect = [
|
||||
("instant", 0.1, 0.0, 0.1, 0.0),
|
||||
("snap", 0.25, 0.0, 0.2, 0.0),
|
||||
("settle", 0.3, 0.0, 0.24, 0.0),
|
||||
("reflow", 0.4, 0.0, 0.32, 0.0),
|
||||
("glide", 0.32, 0.0, 0.26, 0.0),
|
||||
("morph", 0.3, 0.16, 0.27, 0.08),
|
||||
("pop", 0.25, 0.15, 0.2, 0.05),
|
||||
("drift", 0.85, 0.0, 0.6, 0.0),
|
||||
];
|
||||
for ((name, ed, eb, xd, xb), (n, pair)) in expect.iter().zip(motion::ALL) {
|
||||
assert_eq!(name, n);
|
||||
assert_eq!((pair.enter.duration, pair.enter.bounce), (*ed, *eb), "{name}");
|
||||
assert_eq!((pair.exit.duration, pair.exit.bounce), (*xd, *xb), "{name}");
|
||||
if *name != "instant" {
|
||||
// Exits run 10–25 % shorter (instant is already at the floor).
|
||||
let ratio = xd / ed;
|
||||
assert!((0.7..=0.9).contains(&ratio), "{name} exit ratio {ratio}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settle_time_bounds_the_whole_tail() {
|
||||
for s in [Spring::new(0.3, 0.0), Spring::new(0.5, 0.3), Spring::new(0.4, -0.4), Spring::new(0.3, 0.9)] {
|
||||
let ts = s.settling_duration(1e-3);
|
||||
assert!(ts > 0.0 && ts < 20.0, "{s:?} {ts}");
|
||||
for i in 0..2000 {
|
||||
let t = ts + i as f32 * 0.005;
|
||||
let (x, v) = s.sample(0.0, 0.0, 1.0, t);
|
||||
assert!((x - 1.0).abs() <= 1.01e-3, "{s:?} t={t} x={x}");
|
||||
assert!(v.abs() <= 1.01e-2, "{s:?} t={t} v={v}");
|
||||
}
|
||||
}
|
||||
// Critically damped at duration d settles in about d (SwiftUI's perceptual duration).
|
||||
let t = Spring::new(0.5, 0.0).settling_duration(1e-3);
|
||||
assert!(t > 0.4 && t < 1.0, "{t}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn critically_damped_from_rest_never_overshoots() {
|
||||
let s = motion::SETTLE;
|
||||
let mut prev = 0.0;
|
||||
for i in 1..400 {
|
||||
let (x, _) = s.sample(0.0, 0.0, 1.0, i as f32 / 400.0);
|
||||
assert!(x >= prev && x <= 1.0);
|
||||
prev = x;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn animated_value_retargets_keeping_velocity() {
|
||||
let mut a = Animated::new(0.0f32);
|
||||
a.animate_to(100.0, motion::GLIDE, 0.0);
|
||||
let (x1, v1) = (a.sample(0.1), a.velocity(0.1));
|
||||
a.animate_to(-50.0, motion::GLIDE, 0.1);
|
||||
assert!((a.sample(0.1) - x1).abs() < 1e-4);
|
||||
assert!((a.velocity(0.1) - v1).abs() < 1e-2);
|
||||
a.retarget(-50.0, 0.2); // unchanged: no-op
|
||||
assert!(a.is_settled(5.0));
|
||||
assert!((a.sample(5.0) + 50.0).abs() < 1e-3);
|
||||
// Decay coasts to x + v/k.
|
||||
let mut d = Animated::new(0.0f32);
|
||||
d.release(1000.0, 0.0, Curve::Decay(Decay::IOS_NORMAL), 0.0);
|
||||
assert!((d.target() - 1000.0 / Decay::IOS_NORMAL.rate).abs() < 1e-2);
|
||||
assert!((d.sample(30.0) - d.target()).abs() < 1e-2);
|
||||
}
|
||||
|
||||
/// Golden samples for `animate_to`/`release` across every curve kind, so a refactor of the
|
||||
/// lane restart can't drift the numbers.
|
||||
///
|
||||
/// Samples are pinned with a tight tolerance, not a bit hash. Springs and decay sample
|
||||
/// `exp`/`sin`/`cos` from the platform's libm, and glibc and Apple's libm disagree in the
|
||||
/// last bits: the same run at the same revision moves a value of ~400 by up to 3e-5. The
|
||||
/// tolerance below is about 20× that platform noise and still orders of magnitude below a
|
||||
/// real change to how a lane restarts.
|
||||
#[test]
|
||||
fn animated_retarget_golden() {
|
||||
const ANCHORS: [usize; 6] = [0, 1, 3, 9, 21, 39];
|
||||
/// Per curve, per anchor, `[x.x, x.y, v.x, v.y]`.
|
||||
const SAMPLES: [[[f32; 4]; 6]; 5] = [
|
||||
[
|
||||
[30.078003, 7.5296297, -800.0, 400.0],
|
||||
[15.205883, 12.992083, -426.75085, 80.23154],
|
||||
[3.2957265, 11.149232, -112.73632, -93.2812],
|
||||
[-0.20551914, 1.577376, 1.509766, -24.364733],
|
||||
[-0.0026638499, 0.009844182, 0.045319706, -0.1750176],
|
||||
[0.0, 0.0, 0.0, 0.0],
|
||||
],
|
||||
[
|
||||
[56.422695, -0.41329098, -800.0, 400.0],
|
||||
[38.957146, 7.563013, -600.40234, 244.27997],
|
||||
[17.499737, 14.067252, -277.22702, 37.680252],
|
||||
[11.163436, 5.5244317, 65.7598, -71.8772],
|
||||
[20.527206, -0.43597618, -1.4065659, 3.7947469],
|
||||
[19.988346, 0.0052623716, 0.1345897, -0.10417824],
|
||||
],
|
||||
[
|
||||
[48.35736, 7.3219295, -800.0, 400.0],
|
||||
[30.425076, 14.737576, -593.33307, 237.03568],
|
||||
[11.4471245, 21.428228, -188.11761, 41.604954],
|
||||
[29.531113, 6.3093452, 231.20714, -141.46454],
|
||||
[40.0, 0.0, 0.0, -0.0],
|
||||
[40.0, 0.0, 0.0, -0.0],
|
||||
],
|
||||
[
|
||||
[111.8616, -21.43715, -800.0, 400.0],
|
||||
[92.35385, -11.683273, -760.94543, 380.47272],
|
||||
[56.148865, 6.41922, -688.46295, 344.23148],
|
||||
[-33.05693, 51.022118, -509.8728, 254.9364],
|
||||
[-148.05019, 108.518745, -279.6561, 139.82805],
|
||||
[-230.99655, 149.99193, -113.5973, 56.79865],
|
||||
],
|
||||
[
|
||||
[80.0, 0.0, 0.0, 0.0],
|
||||
[80.0, 0.0, 0.0, 0.0],
|
||||
[80.0, 0.0, 0.0, 0.0],
|
||||
[80.0, 0.0, 0.0, 0.0],
|
||||
[80.0, 0.0, 0.0, 0.0],
|
||||
[80.0, 0.0, 0.0, 0.0],
|
||||
],
|
||||
];
|
||||
const TARGETS: [[f32; 2]; 5] = [[0.0, 0.0], [20.0, 0.0], [40.0, 0.0], [-287.7384, 178.36285], [80.0, 0.0]];
|
||||
let close = |got: f32, want: f32| (got - want).abs() <= 2e-6 + 1e-6 * want.abs();
|
||||
|
||||
let tween = Curve::Tween { duration: 0.3, easing: Easing::EASE_OUT };
|
||||
let curves = [Curve::Spring(motion::GLIDE), Curve::Spring(Spring::new(0.5, 0.3)), tween, Curve::Decay(Decay::IOS_NORMAL), Curve::Instant];
|
||||
for (n, &c) in curves.iter().enumerate() {
|
||||
let mut a = Animated::new(Vec2::new(0.0, 10.0));
|
||||
a.animate_to(Vec2::new(100.0, -40.0), Anim::new(Curve::Spring(motion::SNAP)), 0.0);
|
||||
a.animate_to(Vec2::new(-30.0, 60.0), Anim::new(c), 0.07);
|
||||
a.animate_to(Vec2::new(5.0, 5.0), Anim::new(c).velocity(Velocity::Uniform(250.0)), 0.13);
|
||||
a.release(Vec2::new(-800.0, 400.0), Vec2::new(20.0 * n as f32, 0.0), c, 0.2);
|
||||
for (i, &k) in ANCHORS.iter().enumerate() {
|
||||
let t = 0.2 + k as f64 * 0.025;
|
||||
let (x, v) = (a.sample(t), a.velocity(t));
|
||||
let got = [x.x, x.y, v.x, v.y];
|
||||
for (j, (&g, &w)) in got.iter().zip(&SAMPLES[n][i]).enumerate() {
|
||||
assert!(close(g, w), "curve {n} sample {k} field {j}: {g} vs {w}");
|
||||
}
|
||||
}
|
||||
let tg = a.target();
|
||||
assert!(close(tg.x, TARGETS[n][0]) && close(tg.y, TARGETS[n][1]), "curve {n} target: {tg:?} vs {:?}", TARGETS[n]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_linear_export() {
|
||||
let (css, ms) = motion::SETTLE.css_linear();
|
||||
assert!(css.starts_with("linear(0,") && css.ends_with(",1)"));
|
||||
assert!(ms > 200 && ms < 1000, "{ms}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_none_spring_is_an_instant_curve_everywhere_a_spring_converts() {
|
||||
use rune_motion::{Anim, Curve, Effect, PropClass, Spring, SpringPair, Transition};
|
||||
assert_eq!(Curve::from(Spring::NONE), Curve::Instant);
|
||||
assert_eq!(Anim::from(Spring::NONE).curve, Curve::Instant);
|
||||
assert_eq!(Anim::from(SpringPair::NONE).curve, Curve::Instant);
|
||||
// Reduce Motion keeps it instant; a short spring would become a fade.
|
||||
assert_eq!(PropClass::Presence.reduce(Spring::NONE.into()), Curve::Instant);
|
||||
let t = Transition::none();
|
||||
assert_eq!((t.insertion, t.removal, t.springs), (Effect::IDENTITY, Effect::IDENTITY, SpringPair::NONE));
|
||||
// Any other spring, however short, is still a spring.
|
||||
assert_eq!(Curve::from(Spring::new(0.001, 0.0)), Curve::Spring(Spring::new(0.001, 0.0)));
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
use rune_motion::prelude::*;
|
||||
use rune_motion::{Keyframes, MotionEvent, PropClass, Prop};
|
||||
|
||||
const X: Prop<f32> = Prop::custom(64, PropClass::Spatial);
|
||||
const N: NodeId = NodeId(7);
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> f32 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
((self.0 >> 40) as f32) / (1u64 << 24) as f32
|
||||
}
|
||||
fn range(&mut self, a: f32, b: f32) -> f32 {
|
||||
a + (b - a) * self.next()
|
||||
}
|
||||
}
|
||||
|
||||
fn state(s: &AnimationStore) -> (f32, f32) {
|
||||
(s.sample(N, X).unwrap(), s.sample_velocity(N, X).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomized_retargets_are_c1_continuous() {
|
||||
for seed in 1..=8u64 {
|
||||
let mut rng = Rng(seed);
|
||||
let mut store = AnimationStore::new();
|
||||
store.set(N, X, 0.0);
|
||||
let mut t = 0.0f64;
|
||||
for step in 0..1500 {
|
||||
t += rng.range(0.001, 0.06) as f64;
|
||||
store.set_time(t);
|
||||
if step % 3 == 0 {
|
||||
store.tick();
|
||||
// The tick's presented value is the exact sample.
|
||||
let (x, v) = state(&store);
|
||||
assert!((store.get(N, X).unwrap() - x).abs() < 1e-3);
|
||||
assert!((store.velocity(N, X).unwrap() - v).abs() < 1e-2);
|
||||
}
|
||||
let (x0, v0) = state(&store);
|
||||
let target = rng.range(-500.0, 500.0);
|
||||
let kind = rng.next();
|
||||
let anim: Anim = if kind < 0.6 {
|
||||
Spring::new(rng.range(0.1, 0.8), rng.range(-0.6, 0.7)).into()
|
||||
} else if kind < 0.85 {
|
||||
Curve::tween(rng.range(0.05, 0.5), Easing::EASE_IN_OUT).into()
|
||||
} else if kind < 0.93 {
|
||||
Curve::Decay(Decay::IOS_FAST).into()
|
||||
} else {
|
||||
Spring::new(rng.range(0.1, 0.8), 0.0).additive()
|
||||
};
|
||||
store.animate(N, X, target, anim);
|
||||
let (x1, v1) = state(&store);
|
||||
let scale = 1.0 + x0.abs().max(v0.abs()) * 1e-5;
|
||||
assert!((x1 - x0).abs() < 2e-3 * scale, "seed {seed} step {step}: position jumped {x0} → {x1}");
|
||||
assert!(
|
||||
(v1 - v0).abs() < 2e-2 * scale.max(1.0 + v0.abs() * 1e-4),
|
||||
"seed {seed} step {step} ({anim:?}): velocity jumped {v0} → {v1}"
|
||||
);
|
||||
}
|
||||
// Everything settles exactly on the last target, and the track goes dormant.
|
||||
store.tick_at(t + 200.0);
|
||||
store.tick_at(t + 200.1);
|
||||
assert_eq!(store.active_len(), 0);
|
||||
assert_eq!(store.velocity(N, X), Some(0.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additive_springs_equal_merged_springs() {
|
||||
// Springs are linear ODEs: stacking additive layers on one spring is the same motion as
|
||||
// sample-and-restart (research 06 §2.6). Prove it numerically.
|
||||
let s = motion::REFLOW;
|
||||
let mut merged = AnimationStore::new();
|
||||
let mut added = AnimationStore::new();
|
||||
for st in [&mut merged, &mut added] {
|
||||
st.set(N, X, 0.0);
|
||||
}
|
||||
let mut rng = Rng(42);
|
||||
let mut t = 0.0;
|
||||
for _ in 0..6 {
|
||||
let target = rng.range(-300.0, 300.0);
|
||||
merged.set_time(t);
|
||||
added.set_time(t);
|
||||
merged.animate(N, X, target, s.merge());
|
||||
added.animate(N, X, target, s.additive());
|
||||
for k in 0..40 {
|
||||
let tt = t + k as f64 * 0.002;
|
||||
merged.set_time(tt);
|
||||
added.set_time(tt);
|
||||
let (a, b) = (state(&merged), state(&added));
|
||||
assert!((a.0 - b.0).abs() < 2e-3, "{a:?} vs {b:?}");
|
||||
assert!((a.1 - b.1).abs() < 5e-2, "{a:?} vs {b:?}");
|
||||
}
|
||||
t += rng.range(0.03, 0.2) as f64;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_target_keeps_the_trajectory() {
|
||||
let mut a = AnimationStore::new();
|
||||
let mut b = AnimationStore::new();
|
||||
for s in [&mut a, &mut b] {
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 100.0, motion::SETTLE);
|
||||
}
|
||||
b.set_time(0.1);
|
||||
b.animate(N, X, 100.0, motion::DRIFT); // same target: no restart, curve ignored
|
||||
for k in 1..60 {
|
||||
let t = k as f64 / 120.0;
|
||||
a.set_time(t);
|
||||
b.set_time(t);
|
||||
assert_eq!(state(&a), state(&b));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delays_hold_then_start_exactly_and_newer_animations_cancel_them() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 100.0, motion::SETTLE.delay(0.1));
|
||||
s.tick_at(0.05);
|
||||
assert_eq!(s.get(N, X), Some(0.0));
|
||||
s.tick_at(0.1 + 0.15);
|
||||
let expect = motion::SETTLE.sample(0.0, 0.0, 100.0, 0.15).0;
|
||||
assert!((s.get(N, X).unwrap() - expect).abs() < 1e-3);
|
||||
// A delayed retarget, then an immediate one: the delayed one never happens.
|
||||
s.animate(N, X, -100.0, motion::SETTLE.delay(0.2));
|
||||
s.set_time(0.3);
|
||||
s.animate(N, X, 50.0, motion::SETTLE);
|
||||
s.tick_at(10.0);
|
||||
assert_eq!(s.get(N, X), Some(50.0));
|
||||
assert_eq!(s.target(N, X), Some(50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_due_delayed_start_keeps_its_immediate_wake_until_ticked() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 100.0, motion::SETTLE.delay(1.0));
|
||||
// Due, and the tick that would apply it hasn't run: an immediate wake, not motion.
|
||||
s.set_time(1.0);
|
||||
assert!(s.running());
|
||||
assert_eq!(s.waiting_until(), Some(1.0));
|
||||
s.set_time(1.25);
|
||||
assert_eq!(s.waiting_until(), Some(1.25), "and it stays due until a tick applies it");
|
||||
assert_eq!(s.get(N, X), Some(0.0), "nothing has moved yet");
|
||||
s.tick();
|
||||
assert!(s.get(N, X).unwrap() > 0.0, "the tick starts it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_is_immediate_and_first_animate_doesnt_animate() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.animate(N, X, 40.0, motion::SETTLE); // first sight: set, no motion
|
||||
s.tick_at(0.0);
|
||||
assert_eq!(s.get(N, X), Some(40.0));
|
||||
assert!(!s.is_animating(N, X));
|
||||
s.animate(N, X, 80.0, motion::SETTLE);
|
||||
s.tick_at(0.05);
|
||||
assert!(s.is_animating(N, X));
|
||||
s.set(N, X, 10.0); // the user's hand: 1:1, cancels
|
||||
s.tick_at(0.06);
|
||||
assert_eq!(s.get(N, X), Some(10.0));
|
||||
assert!(!s.is_animating(N, X));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settle_and_completion_events() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 1.0, motion::SNAP.completion(11));
|
||||
s.set_time(0.05);
|
||||
s.animate(N, X, 2.0, motion::SNAP.completion(12)); // replaces 11
|
||||
let mut events = Vec::new();
|
||||
for k in 0..400 {
|
||||
s.tick_at(0.05 + k as f64 / 120.0);
|
||||
events.extend_from_slice(s.events());
|
||||
}
|
||||
let completed: Vec<_> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
MotionEvent::Completed { token, finished, .. } => Some((*token, *finished)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(completed, vec![(11, false), (12, true)]);
|
||||
let settles = events.iter().filter(|e| matches!(e, MotionEvent::Settled { .. })).count();
|
||||
assert_eq!(settles, 1);
|
||||
assert_eq!(s.get(N, X), Some(2.0));
|
||||
// Settle snaps below the 1/64 px quantum: the last moving frame was already that close.
|
||||
assert_eq!(s.active_len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_an_animating_track_completes_it_unfinished() {
|
||||
let completions = |s: &AnimationStore| -> Vec<(u64, bool)> {
|
||||
s.events().iter().filter_map(|e| match e {
|
||||
MotionEvent::Completed { token, finished, .. } => Some((*token, *finished)),
|
||||
_ => None,
|
||||
}).collect()
|
||||
};
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 1.0, motion::SNAP.completion(21));
|
||||
s.tick_at(0.02);
|
||||
assert!(s.is_animating(N, X));
|
||||
s.remove_node(N);
|
||||
s.tick_at(0.03);
|
||||
assert_eq!(completions(&s), [(21, false)], "the node unmounted mid-animation");
|
||||
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 1.0, motion::SNAP.completion(22));
|
||||
s.tick_at(0.04);
|
||||
s.remove(N, X);
|
||||
s.tick_at(0.05);
|
||||
assert_eq!(completions(&s), [(22, false)], "the property's track went");
|
||||
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 1.0, motion::SNAP.completion(23));
|
||||
let mut done = Vec::new();
|
||||
for k in 0..400 {
|
||||
s.tick_at(0.06 + k as f64 / 120.0);
|
||||
done.extend(completions(&s));
|
||||
}
|
||||
s.remove_node(N);
|
||||
s.tick_at(10.0);
|
||||
done.extend(completions(&s));
|
||||
assert_eq!(done, [(23, true)], "a finished animation completes once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fling_into_a_bound_hands_off_velocity_smoothly() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.release(N, X, 3000.0, Release::DecayClamped { decay: Decay::IOS_NORMAL, min: 0.0, max: 500.0, spring: motion::GLIDE });
|
||||
// Find the handoff by walking finely; velocity must stay continuous across it.
|
||||
let mut prev = state(&s);
|
||||
let mut max_dv: f32 = 0.0;
|
||||
let dt = 1.0 / 2000.0;
|
||||
for k in 1..8000 {
|
||||
s.tick_at(k as f64 * dt);
|
||||
let cur = (s.get(N, X).unwrap(), s.velocity(N, X).unwrap());
|
||||
max_dv = max_dv.max((cur.1 - prev.1).abs());
|
||||
prev = cur;
|
||||
}
|
||||
// Decay deceleration is k·v ≈ 6000/s² → 3 per step; the spring's is larger but bounded.
|
||||
assert!(max_dv < 60.0, "velocity jumped by {max_dv}");
|
||||
assert_eq!(s.get(N, X), Some(500.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rubber_band_then_spring_back() {
|
||||
let mut s = AnimationStore::new();
|
||||
let over = rune_motion::rubber_band_clamp(-120.0, 0.0, 500.0, 800.0);
|
||||
assert!(over < 0.0 && over > -120.0 * 0.55);
|
||||
s.set(N, X, over);
|
||||
s.release(N, X, 0.0, Release::DecayClamped { decay: Decay::IOS_NORMAL, min: 0.0, max: 500.0, spring: motion::GLIDE });
|
||||
s.tick_at(5.0);
|
||||
s.tick_at(5.1);
|
||||
assert_eq!(s.get(N, X), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframes_hit_values_and_keep_velocity_through_cubics() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
let kf = Keyframes::new()
|
||||
.linear(10.0, 0.1)
|
||||
.cubic(30.0, 0.2)
|
||||
.cubic(20.0, 0.2)
|
||||
.cubic(40.0, 0.2)
|
||||
.spring(0.0, motion::SETTLE);
|
||||
s.play_keyframes(N, X, &kf);
|
||||
let at = |s: &mut AnimationStore, t: f64| {
|
||||
s.tick_at(t);
|
||||
(s.get(N, X).unwrap(), s.velocity(N, X).unwrap())
|
||||
};
|
||||
assert!((at(&mut s, 0.05).0 - 5.0).abs() < 1e-3, "linear halfway");
|
||||
assert!((at(&mut s, 0.1).0 - 10.0).abs() < 1e-3);
|
||||
assert!((at(&mut s, 0.3).0 - 30.0).abs() < 1e-3);
|
||||
// C¹ at the cubic joins: velocity just before and after 0.5 s agree.
|
||||
let before = at(&mut s, 0.5 - 1e-4).1;
|
||||
let after = at(&mut s, 0.5 + 1e-4).1;
|
||||
assert!((before - after).abs() < 0.5, "{before} vs {after}");
|
||||
assert!((at(&mut s, 0.7).0 - 40.0).abs() < 1e-3);
|
||||
at(&mut s, 3.0);
|
||||
assert_eq!(at(&mut s, 3.1).0, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduced_motion_maps_by_property_class() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set_reduced_motion(true);
|
||||
s.set(N, prop::OFFSET, Vec2::ZERO);
|
||||
s.set(N, prop::OPACITY, 0.0);
|
||||
s.set(N, prop::BLUR, 4.0);
|
||||
s.animate(N, prop::OFFSET, Vec2::new(100.0, 0.0), motion::GLIDE);
|
||||
s.animate(N, prop::OPACITY, 1.0, motion::GLIDE);
|
||||
s.animate(N, prop::BLUR, 0.0, motion::GLIDE);
|
||||
s.tick_at(0.0);
|
||||
assert_eq!(s.get(N, prop::OFFSET), Some(Vec2::new(100.0, 0.0)), "travel jumps");
|
||||
assert_eq!(s.get(N, prop::BLUR), Some(0.0), "blur jumps");
|
||||
s.tick_at(0.09);
|
||||
let o = s.get(N, prop::OPACITY).unwrap();
|
||||
assert!(o > 0.3 && o < 0.7, "opacity takes the short fade: {o}");
|
||||
s.tick_at(0.18);
|
||||
assert_eq!(s.get(N, prop::OPACITY), Some(1.0));
|
||||
// Gestures are the user's own motion and are untouched.
|
||||
s.set(N, prop::SCROLL, Vec2::ZERO);
|
||||
s.release(N, prop::SCROLL, Vec2::new(0.0, 1000.0), Release::Decay(Decay::IOS_NORMAL));
|
||||
s.tick_at(0.3);
|
||||
assert!(s.get(N, prop::SCROLL).unwrap().y > 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_lane_values_share_timing() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, prop::FILL, Color::hex(0xff0000));
|
||||
s.animate(N, prop::FILL, Color::hex(0x0000ff), motion::SETTLE);
|
||||
s.tick_at(0.15);
|
||||
let mid = s.get(N, prop::FILL).unwrap();
|
||||
// All four lanes ride one spring: the colour is the OKLab interpolation at that progress.
|
||||
let p = motion::SETTLE.sample(0.0, 0.0, 1.0, 0.15).0;
|
||||
let (a, b) = (Color::hex(0xff0000).to_oklab(), Color::hex(0x0000ff).to_oklab());
|
||||
let want = Color::from_oklab(core::array::from_fn(|k| a[k] + (b[k] - a[k]) * p), 1.0);
|
||||
for (x, y) in [(mid.r, want.r), (mid.g, want.g), (mid.b, want.b), (mid.a, want.a)] {
|
||||
assert!((x - y).abs() < 2e-3, "{mid:?} vs {want:?}");
|
||||
}
|
||||
s.tick_at(5.0);
|
||||
let end = s.get(N, prop::FILL).unwrap();
|
||||
assert!((end.b - 1.0).abs() < 1e-3 && end.r < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retune_respring_keeps_position_and_velocity() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.animate(N, X, 100.0, motion::DRIFT);
|
||||
s.set_time(0.2);
|
||||
let before = state(&s);
|
||||
s.tick();
|
||||
s.retune(motion::DRIFT, motion::SNAP);
|
||||
let after = state(&s);
|
||||
assert!((before.0 - after.0).abs() < 1e-3 && (before.1 - after.1).abs() < 1e-2);
|
||||
s.tick_at(0.2 + motion::SNAP.settling_duration(1e-4) as f64 + 0.1);
|
||||
assert_eq!(s.get(N, X), Some(100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_and_reusing_tracks_is_generational() {
|
||||
let mut s = AnimationStore::new();
|
||||
let a = s.set(NodeId(1), X, 1.0);
|
||||
s.remove_node(NodeId(1));
|
||||
assert!(!s.contains(a));
|
||||
let b = s.set(NodeId(2), X, 2.0);
|
||||
assert!(s.contains(b) && !s.contains(a));
|
||||
assert_eq!(s.get(NodeId(2), X), Some(2.0));
|
||||
assert_eq!(s.get(NodeId(1), X), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_track_leaves_touched_even_when_its_slot_is_reused() {
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(NodeId(1), X, 1.0);
|
||||
s.set(NodeId(3), X, 3.0);
|
||||
s.tick();
|
||||
let touched = |s: &AnimationStore| s.touched().map(|(n, _)| n.0).collect::<Vec<_>>();
|
||||
assert_eq!(touched(&s), [1, 3]);
|
||||
s.remove_node(NodeId(1));
|
||||
assert_eq!(touched(&s), [3]);
|
||||
s.set(NodeId(1), X, 1.0);
|
||||
s.remove_node(NodeId(1));
|
||||
// Node 2's track takes the freed slot; the old track's entry doesn't count for it.
|
||||
s.set(NodeId(2), X, 2.0);
|
||||
s.tick();
|
||||
assert_eq!(touched(&s), [2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_time_scale_holds_slows_and_resumes_in_place() {
|
||||
const M: NodeId = NodeId(8);
|
||||
let mut s = AnimationStore::new();
|
||||
s.set(N, X, 0.0);
|
||||
s.set(M, X, 0.0);
|
||||
s.set_node_time_scale(M, 0.5);
|
||||
s.animate(N, X, 100.0, motion::SETTLE);
|
||||
s.animate(M, X, 100.0, motion::SETTLE.delay(0.1));
|
||||
s.tick_at(0.1);
|
||||
let reference = s.get(N, X).unwrap();
|
||||
assert_eq!(s.get(M, X), Some(0.0), "the delay runs at half speed too");
|
||||
s.tick_at(0.4);
|
||||
assert!((s.get(M, X).unwrap() - reference).abs() < 1e-3);
|
||||
// Stopped: nothing moves and nothing counts as running, pending or not.
|
||||
s.set_node_time_scale(N, 0.0);
|
||||
s.set_node_time_scale(M, 0.0);
|
||||
let held = (s.get(N, X).unwrap(), s.get(M, X).unwrap());
|
||||
s.tick_at(5.0);
|
||||
assert_eq!((s.get(N, X).unwrap(), s.get(M, X).unwrap()), held);
|
||||
assert!(!s.running() && s.active_len() == 2);
|
||||
// Resumed: carries on from the same place on the same curve.
|
||||
s.set_node_time_scale(M, 1.0);
|
||||
s.tick();
|
||||
assert_eq!(s.get(M, X).unwrap(), held.1);
|
||||
assert!(s.running());
|
||||
s.tick_at(5.15);
|
||||
assert!((s.get(M, X).unwrap() - motion::SETTLE.sample(0.0, 0.0, 100.0, 0.25).0).abs() < 1e-3);
|
||||
assert_eq!(s.node_time_scale(N), 0.0);
|
||||
assert_eq!(s.node_time_scale(M), 1.0);
|
||||
}
|
||||
Reference in new issue
Block a user