//! Spring physics for all motion. `spring(id, target, preset)` is the immediate-mode form: call it //! each frame with where the value should be and it gives back where it is now. //! The presets are Material 3 Expressive's spatial tokens. use std::cell::{Cell, RefCell}; use std::collections::HashMap; #[derive(Clone, Copy, Debug)] pub struct Preset { pub stiffness: f32, pub damping: f32, } pub const FAST: Preset = Preset { stiffness: 1400.0, damping: 0.62 }; pub const DEFAULT: Preset = Preset { stiffness: 700.0, damping: 0.68 }; pub const SLOW: Preset = Preset { stiffness: 300.0, damping: 0.74 }; /// For colours, opacity and anything else that shouldn't overshoot. pub const EFFECT: Preset = Preset { stiffness: 900.0, damping: 1.0 }; thread_local! { static BUSY: Cell = const { Cell::new(false) }; static LEVEL: Cell = const { Cell::new(2) }; static DT: Cell = const { Cell::new(1.0 / 60.0) }; static MAP: RefCell> = RefCell::new(HashMap::new()); } struct Slot { s: Spring, frame: u64, } thread_local! { static FRAME: Cell = const { Cell::new(0) }; } /// Starts a frame; `level` is the Settings motion choice. pub fn begin_frame(dt: f32, level: u8) { DT.with(|d| d.set(dt.clamp(0.001, 0.05))); LEVEL.with(|l| l.set(level)); BUSY.with(|b| b.set(false)); FRAME.with(|f| f.set(f.get() + 1)); } /// Did anything move this frame? If so the next frame must be drawn. pub fn busy() -> bool { BUSY.with(|b| b.get()) } pub fn keep_alive() { BUSY.with(|b| b.set(true)); } pub fn dt() -> f32 { DT.with(|d| d.get()) } fn adjusted(p: Preset) -> Preset { match LEVEL.with(|l| l.get()) { 1 => Preset { stiffness: p.stiffness, damping: p.damping.max(1.0) }, 3 => Preset { stiffness: p.stiffness * 0.8, damping: (p.damping * 0.62).min(1.0) }, _ => p, } } #[derive(Clone, Copy, Debug)] pub struct Spring { pub x: f32, pub v: f32, pub target: f32, } impl Spring { pub fn new(x: f32) -> Spring { Spring { x, v: 0.0, target: x } } pub fn settled(&self) -> bool { self.x == self.target } pub fn snap(&mut self, x: f32) { *self = Spring::new(x); } /// Advances one frame, returning the new value. pub fn step(&mut self, p: Preset) -> f32 { if self.settled() { return self.x; } if LEVEL.with(|l| l.get()) == 0 { self.snap(self.target); return self.x; } let p = adjusted(p); let w = p.stiffness.sqrt(); let c = 2.0 * p.damping * w; let range = (self.target - self.x).abs().max(1.0); let mut left = dt(); while left > 0.0 { let h = left.min(0.002); let a = -p.stiffness * (self.x - self.target) - c * self.v; self.v += a * h; self.x += self.v * h; left -= h; } if (self.x - self.target).abs() < 0.002 * range.min(50.0) && self.v.abs() < 0.05 * range.min(50.0) { self.snap(self.target); } else { keep_alive(); } self.x } } /// The value of the spring called `id`, heading for `target`. pub fn spring(id: impl AsRef, target: f32, p: Preset) -> f32 { let frame = FRAME.with(|f| f.get()); MAP.with(|m| { let mut m = m.borrow_mut(); if let Some(slot) = m.get_mut(id.as_ref()) { slot.s.target = target; if slot.frame != frame { slot.frame = frame; slot.s.step(p); } slot.s.x } else { m.insert(id.as_ref().to_string(), Slot { s: Spring::new(target), frame }); target } }) } /// Like `spring`, but a new id starts at `from` so the value animates in. pub fn spring_from(id: impl AsRef, from: f32, target: f32, p: Preset) -> f32 { let frame = FRAME.with(|f| f.get()); MAP.with(|m| { m.borrow_mut().entry(id.as_ref().to_string()).or_insert_with(|| Slot { s: Spring::new(from), frame: frame.saturating_sub(1) }); }); spring(id, target, p) } /// Gives a spring a shove, for hits like a keypress or save. pub fn kick(id: impl AsRef, velocity: f32) { MAP.with(|m| { if let Some(s) = m.borrow_mut().get_mut(id.as_ref()) { s.s.v += velocity; s.s.x += 0.0001; } }); } /// Forgets a spring, so the next use starts fresh. pub fn forget(id: impl AsRef) { MAP.with(|m| { m.borrow_mut().remove(id.as_ref()); }); } /// Eased 0..1 for staggered lists: `t` seconds since the start, `delay` for this item. pub fn stagger(t: f32, delay: f32, dur: f32) -> f32 { if LEVEL.with(|l| l.get()) == 0 { return 1.0; } let x = ((t - delay) / dur).clamp(0.0, 1.0); let c = 1.70158; 1.0 + (c + 1.0) * (x - 1.0).powi(3) + c * (x - 1.0).powi(2) } #[cfg(test)] mod tests { use super::*; #[test] fn spring_overshoots_then_settles() { begin_frame(1.0 / 60.0, 2); let mut s = Spring::new(0.0); s.target = 100.0; let mut peak: f32 = 0.0; for _ in 0..240 { begin_frame(1.0 / 60.0, 2); peak = peak.max(s.step(DEFAULT)); } assert!(peak > 100.5, "bouncy spring should overshoot, peak {peak}"); assert!(s.settled()); assert_eq!(s.x, 100.0); } #[test] fn calm_never_overshoots_and_off_snaps() { let mut s = Spring::new(0.0); s.target = 100.0; for _ in 0..240 { begin_frame(1.0 / 60.0, 1); assert!(s.step(DEFAULT) <= 100.0); } let mut s = Spring::new(0.0); s.target = 5.0; begin_frame(1.0 / 60.0, 0); assert_eq!(s.step(DEFAULT), 5.0); } }