261 lines
7.8 KiB
Rust
261 lines
7.8 KiB
Rust
//! 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. Presets are in `tokens::spring`.
|
|
|
|
use eframe::egui::Id;
|
|
use medlar_core::settings::Motion;
|
|
use std::cell::{Cell, RefCell};
|
|
use std::collections::HashMap;
|
|
use std::hash::Hash;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct Preset {
|
|
pub stiffness: f32,
|
|
pub damping: f32,
|
|
}
|
|
|
|
/// A spring nobody asked for in this many frames is forgotten.
|
|
const KEEP_FRAMES: u64 = 600;
|
|
|
|
thread_local! {
|
|
static BUSY: Cell<bool> = const { Cell::new(false) };
|
|
static LEVEL: Cell<Motion> = const { Cell::new(Motion::Normal) };
|
|
static DT: Cell<f32> = const { Cell::new(1.0 / 60.0) };
|
|
static FRAME: Cell<u64> = const { Cell::new(0) };
|
|
static MAP: RefCell<HashMap<Id, Slot>> = RefCell::new(HashMap::new());
|
|
}
|
|
|
|
struct Slot {
|
|
s: Spring,
|
|
frame: u64,
|
|
}
|
|
|
|
/// Starts a frame; `level` is the motion choice in settings.
|
|
pub fn begin_frame(dt: f32, level: Motion) {
|
|
DT.set(dt.clamp(0.001, 0.05));
|
|
LEVEL.set(level);
|
|
BUSY.set(false);
|
|
let frame = FRAME.get() + 1;
|
|
FRAME.set(frame);
|
|
if frame.is_multiple_of(KEEP_FRAMES) {
|
|
MAP.with_borrow_mut(|m| m.retain(|_, slot| slot.frame + KEEP_FRAMES > frame));
|
|
}
|
|
}
|
|
|
|
/// Did anything move this frame? If so the next frame must be drawn.
|
|
pub fn busy() -> bool {
|
|
BUSY.get()
|
|
}
|
|
|
|
/// For motion that isn't a spring, such as a wave that travels while bytes arrive.
|
|
pub fn keep_alive() {
|
|
BUSY.set(true);
|
|
}
|
|
|
|
pub fn dt() -> f32 {
|
|
DT.get()
|
|
}
|
|
|
|
pub fn level() -> Motion {
|
|
LEVEL.get()
|
|
}
|
|
|
|
fn adjusted(p: Preset) -> Preset {
|
|
match level() {
|
|
Motion::Reduced => Preset { damping: p.damping.max(1.0), ..p },
|
|
// What must not overshoot stays that way.
|
|
Motion::Expressive if p.damping < 1.0 => Preset { stiffness: p.stiffness * 0.8, damping: p.damping * 0.62 },
|
|
_ => 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 && self.v == 0.0
|
|
}
|
|
|
|
pub fn snap(&mut self, x: f32) {
|
|
*self = Spring::new(x);
|
|
}
|
|
|
|
/// Advances one frame and returns the new value. Changing `target` in flight keeps position and velocity.
|
|
pub fn step(&mut self, p: Preset) -> f32 {
|
|
if self.settled() {
|
|
return self.x;
|
|
}
|
|
if level() == Motion::Off {
|
|
self.snap(self.target);
|
|
return self.x;
|
|
}
|
|
let p = adjusted(p);
|
|
let c = 2.0 * p.damping * p.stiffness.sqrt();
|
|
let range = (self.target - self.x).abs().clamp(1.0, 50.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 && self.v.abs() < 0.05 * range {
|
|
self.snap(self.target);
|
|
} else {
|
|
keep_alive();
|
|
}
|
|
self.x
|
|
}
|
|
}
|
|
|
|
/// The value of the spring called `id`, heading for `target`. A new one starts there.
|
|
pub fn spring(id: impl Hash + std::fmt::Debug, target: f32, p: Preset) -> f32 {
|
|
spring_from(id, target, target, p)
|
|
}
|
|
|
|
/// Like `spring`, but a new one starts at `from`, so the value animates in.
|
|
pub fn spring_from(id: impl Hash + std::fmt::Debug, from: f32, target: f32, p: Preset) -> f32 {
|
|
let frame = FRAME.get();
|
|
MAP.with_borrow_mut(|m| {
|
|
let slot = m.entry(Id::unique(id)).or_insert(Slot { s: Spring::new(from), frame: 0 });
|
|
slot.s.target = target;
|
|
// Asking twice in a frame must not move it twice.
|
|
if slot.frame != frame {
|
|
slot.frame = frame;
|
|
slot.s.step(p);
|
|
}
|
|
slot.s.x
|
|
})
|
|
}
|
|
|
|
/// Gives a spring a shove, such as on a key press.
|
|
pub fn kick(id: impl Hash + std::fmt::Debug, velocity: f32) {
|
|
MAP.with_borrow_mut(|m| {
|
|
if let Some(slot) = m.get_mut(&Id::unique(id)) {
|
|
slot.s.v += velocity;
|
|
keep_alive();
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Forgets a spring, so the next use starts fresh.
|
|
pub fn forget(id: impl Hash + std::fmt::Debug) {
|
|
MAP.with_borrow_mut(|m| m.remove(&Id::unique(id)));
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::tokens::spring::{DEFAULT, EFFECT, FAST, SLOW};
|
|
|
|
const DT60: f32 = 1.0 / 60.0;
|
|
|
|
fn run(s: &mut Spring, p: Preset, level: Motion, frames: usize) -> f32 {
|
|
let mut peak = f32::MIN;
|
|
for _ in 0..frames {
|
|
begin_frame(DT60, level);
|
|
peak = peak.max(s.step(p));
|
|
}
|
|
peak
|
|
}
|
|
|
|
fn towards_100() -> Spring {
|
|
Spring { target: 100.0, ..Spring::new(0.0) }
|
|
}
|
|
|
|
#[test]
|
|
fn overshoots_then_settles() {
|
|
let mut s = towards_100();
|
|
let peak = run(&mut s, DEFAULT, Motion::Normal, 240);
|
|
assert!(peak > 100.5, "peak {peak}");
|
|
assert!(s.settled() && s.x == 100.0);
|
|
let peak_expressive = run(&mut towards_100(), DEFAULT, Motion::Expressive, 240);
|
|
assert!(peak_expressive > peak);
|
|
}
|
|
|
|
#[test]
|
|
fn reduced_never_overshoots_and_off_snaps() {
|
|
for p in [FAST, DEFAULT, SLOW] {
|
|
assert!(run(&mut towards_100(), p, Motion::Reduced, 240) <= 100.0);
|
|
}
|
|
let mut s = towards_100();
|
|
assert_eq!(run(&mut s, DEFAULT, Motion::Off, 1), 100.0);
|
|
assert!(!busy());
|
|
}
|
|
|
|
#[test]
|
|
fn colours_never_overshoot() {
|
|
for level in [Motion::Reduced, Motion::Normal, Motion::Expressive] {
|
|
assert!(run(&mut towards_100(), EFFECT, level, 240) <= 100.0, "{level:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn retarget_keeps_position_and_velocity() {
|
|
let mut s = towards_100();
|
|
run(&mut s, DEFAULT, Motion::Normal, 3);
|
|
let (x, v) = (s.x, s.v);
|
|
assert!(x > 1.0 && v > 100.0);
|
|
s.target = 0.0;
|
|
assert_eq!((s.x, s.v), (x, v), "a new target changes nothing by itself");
|
|
begin_frame(0.001, Motion::Normal);
|
|
s.step(DEFAULT);
|
|
assert!(s.x > x, "still carried on by its speed: {} after {x}", s.x);
|
|
assert!(s.v < v, "but already slowing");
|
|
run(&mut s, DEFAULT, Motion::Normal, 240);
|
|
assert!(s.settled() && s.x == 0.0);
|
|
}
|
|
|
|
#[test]
|
|
fn retarget_onto_the_current_place_does_not_freeze_it() {
|
|
let mut s = towards_100();
|
|
run(&mut s, DEFAULT, Motion::Normal, 3);
|
|
s.target = s.x;
|
|
assert!(!s.settled());
|
|
begin_frame(DT60, Motion::Normal);
|
|
assert!(s.step(DEFAULT) > s.target);
|
|
assert!(busy());
|
|
}
|
|
|
|
#[test]
|
|
fn named_springs_move_once_a_frame_and_stop_asking_for_frames() {
|
|
begin_frame(DT60, Motion::Normal);
|
|
assert_eq!(spring("named", 0.0, DEFAULT), 0.0);
|
|
assert!(!busy());
|
|
begin_frame(DT60, Motion::Normal);
|
|
let x = spring("named", 1.0, DEFAULT);
|
|
assert!(x > 0.0 && busy());
|
|
assert_eq!(spring("named", 1.0, DEFAULT), x);
|
|
for _ in 0..240 {
|
|
begin_frame(DT60, Motion::Normal);
|
|
spring("named", 1.0, DEFAULT);
|
|
}
|
|
assert!(!busy());
|
|
assert_eq!(spring_from("fresh", 5.0, 5.0, DEFAULT), 5.0);
|
|
kick("named", 10.0);
|
|
begin_frame(DT60, Motion::Normal);
|
|
assert!(spring("named", 1.0, DEFAULT) > 1.0);
|
|
forget("named");
|
|
begin_frame(DT60, Motion::Normal);
|
|
assert_eq!(spring("named", 3.0, DEFAULT), 3.0);
|
|
}
|
|
|
|
#[test]
|
|
fn unused_springs_are_dropped() {
|
|
begin_frame(DT60, Motion::Normal);
|
|
spring("gone", 0.0, DEFAULT);
|
|
for _ in 0..KEEP_FRAMES * 2 {
|
|
begin_frame(DT60, Motion::Normal);
|
|
}
|
|
MAP.with_borrow(|m| assert!(!m.contains_key(&Id::unique("gone"))));
|
|
}
|
|
}
|