use std::time::Duration;
use arc_tokens::{CubicBezierSpec, SpringPhysics, SpringSpec};
use gpui_kit::{App, ElementId, SpringState, Window, base::TransitionId};
use crate::{bezier::CubicBezier, clock::motion_now};
const CRITICAL_EPSILON: f64 = 1e-5;
const GRANULAR_DELTA_THRESHOLD: f64 = 5.0;
const REST_SPEED_GRANULAR: f64 = 0.01;
const REST_SPEED_DEFAULT: f64 = 2.0;
const REST_DELTA_GRANULAR: f64 = 0.005;
const REST_DELTA_DEFAULT: f64 = 0.5;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpringSample {
pub value: f32,
pub velocity: f32,
pub settled: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct SpringSolver {
physics: SpringPhysics,
origin: f64,
target: f64,
initial_velocity: f64,
rest_speed: f64,
rest_delta: f64,
}
impl SpringSolver {
pub fn new(spec: SpringSpec, origin: f64, target: f64, initial_velocity: f64) -> Self {
let physics = spec.resolve();
let delta = target - origin;
let is_granular = delta.abs() < GRANULAR_DELTA_THRESHOLD;
let rest_speed = if is_granular {
REST_SPEED_GRANULAR
} else {
REST_SPEED_DEFAULT
};
let rest_delta = if is_granular {
REST_DELTA_GRANULAR
} else {
REST_DELTA_DEFAULT
};
let vel = if physics.is_time_defined {
0.0
} else {
initial_velocity
};
Self {
physics,
origin,
target,
initial_velocity: vel,
rest_speed,
rest_delta,
}
}
pub fn with_rest_thresholds(mut self, rest_delta: f64, rest_speed: f64) -> Self {
self.rest_delta = rest_delta;
self.rest_speed = rest_speed;
self
}
pub fn sample(&self, t_secs: f64) -> SpringSample {
let t = t_secs.max(0.0);
let stiffness = f64::from(self.physics.stiffness);
let damping = f64::from(self.physics.damping);
let mass = f64::from(self.physics.mass);
let delta = self.target - self.origin;
let x0 = -delta;
let v0 = self.initial_velocity;
let omega0 = (stiffness / mass).sqrt();
let zeta = damping / (2.0 * (stiffness * mass).sqrt());
let decay = zeta * omega0;
let (x, v) = if zeta < 1.0 - CRITICAL_EPSILON {
let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
let env = (-decay * t).exp();
let (sin_wt, cos_wt) = (omega_d * t).sin_cos();
let b = (v0 + decay * x0) / omega_d;
let pos = env * (x0 * cos_wt + b * sin_wt);
let vel =
env * ((omega_d * b - decay * x0) * cos_wt - (omega_d * x0 + decay * b) * sin_wt);
(pos, vel)
} else if (zeta - 1.0).abs() <= CRITICAL_EPSILON {
let env = (-omega0 * t).exp();
let c2 = v0 + omega0 * x0;
let pos = env * (x0 + c2 * t);
let vel = env * (v0 - omega0 * c2 * t);
(pos, vel)
} else {
let omega_d = omega0 * (zeta * zeta - 1.0).sqrt();
let slow = decay - omega_d;
let fast = decay + omega_d;
let limit = if self.physics.is_time_defined {
f64::INFINITY
} else {
300.0 / omega_d
};
let decay_at = |rate: f64| -> f64 {
if t > limit {
(-rate * limit - decay * (t - limit)).exp()
} else {
(-rate * t).exp()
}
};
let p = (v0 + decay * x0) / omega_d;
let s_coeff = 0.5 * (x0 + p);
let f_coeff = 0.5 * (x0 - p);
let e_slow = decay_at(slow);
let e_fast = decay_at(fast);
let pos = s_coeff * e_slow + f_coeff * e_fast;
let vel = -slow * s_coeff * e_slow - fast * f_coeff * e_fast;
(pos, vel)
};
let value = self.target + x;
let settled = v.abs() <= self.rest_speed && (self.target - value).abs() <= self.rest_delta;
SpringSample {
value: (if settled { self.target } else { value }) as f32,
velocity: (if settled { 0.0 } else { v }) as f32,
settled,
}
}
pub fn retarget(&mut self, current_value: f64, current_velocity: f64, new_target: f64) {
self.origin = current_value;
self.target = new_target;
self.initial_velocity = if self.physics.is_time_defined {
0.0
} else {
current_velocity
};
let is_granular = (new_target - current_value).abs() < GRANULAR_DELTA_THRESHOLD;
self.rest_speed = if is_granular {
REST_SPEED_GRANULAR
} else {
REST_SPEED_DEFAULT
};
self.rest_delta = if is_granular {
REST_DELTA_GRANULAR
} else {
REST_DELTA_DEFAULT
};
}
}
#[derive(Clone, Copy, Debug)]
pub struct SpringChannelState {
pub state: SpringState,
pub target: f32,
pub updated_at_secs: f64,
pub initialized: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct SpringOptions {
pub spec: SpringSpec,
pub travel: bool,
pub initial_value: Option<f32>,
pub initial_velocity: Option<f32>,
pub rest_delta: Option<f32>,
pub rest_speed: Option<f32>,
}
impl SpringOptions {
pub const fn new(spec: SpringSpec) -> Self {
Self {
spec,
travel: true,
initial_value: None,
initial_velocity: None,
rest_delta: None,
rest_speed: None,
}
}
pub const fn with_travel(mut self, travel: bool) -> Self {
self.travel = travel;
self
}
pub const fn with_initial_value(mut self, value: f32) -> Self {
self.initial_value = Some(value);
self
}
pub const fn with_initial_velocity(mut self, velocity: f32) -> Self {
self.initial_velocity = Some(velocity);
self
}
pub const fn with_rest_thresholds(mut self, rest_delta: f32, rest_speed: f32) -> Self {
self.rest_delta = Some(rest_delta);
self.rest_speed = Some(rest_speed);
self
}
}
pub fn arc_spring(
id: impl Into<TransitionId>,
target: f32,
spec: SpringSpec,
window: &mut Window,
cx: &mut App,
) -> f32 {
arc_spring_with_options(id, target, SpringOptions::new(spec), window, cx).value
}
pub fn arc_spring_with_options(
id: impl Into<TransitionId>,
target: f32,
options: SpringOptions,
window: &mut Window,
cx: &mut App,
) -> SpringSample {
let target = if target.is_finite() { target } else { 0.0 };
let element_id: ElementId =
ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-spring".into());
let now = motion_now(cx);
let seed_pos = options
.initial_value
.filter(|v| v.is_finite())
.unwrap_or(target);
let state = window.use_keyed_state(element_id, cx, |_, _| SpringChannelState {
state: SpringState {
position: seed_pos,
velocity: 0.0,
},
target,
updated_at_secs: now,
initialized: true,
});
let snapshot = *state.read(cx);
if cx.reduce_motion() || !options.travel {
if snapshot.state.position != target || snapshot.state.velocity != 0.0 {
state.update(cx, |s, _| {
s.state = SpringState {
position: target,
velocity: 0.0,
};
s.target = target;
s.updated_at_secs = now;
});
}
return SpringSample {
value: target,
velocity: 0.0,
settled: true,
};
}
let target_changed = (snapshot.target - target).abs() > 1e-6;
let at_rest = !target_changed
&& (snapshot.state.position - target).abs() <= 1e-6
&& snapshot.state.velocity == 0.0
&& options.initial_velocity.is_none();
if at_rest {
return SpringSample {
value: target,
velocity: 0.0,
settled: true,
};
}
let physics = options.spec.resolve();
let config = physics.to_gpui_config();
let mut current_state = snapshot.state;
let was_resting_on_old_target =
(snapshot.state.position - snapshot.target).abs() <= 1e-6 && snapshot.state.velocity == 0.0;
let elapsed = (now - snapshot.updated_at_secs).max(0.0) as f32;
if elapsed > 0.0 && !was_resting_on_old_target {
current_state = config.step(current_state, snapshot.target, elapsed);
}
if let Some(injected) = options.initial_velocity
&& injected.is_finite()
{
current_state.velocity = injected;
} else if target_changed && physics.is_time_defined {
current_state.velocity = 0.0;
}
if !current_state.position.is_finite() || !current_state.velocity.is_finite() {
current_state = SpringState {
position: target,
velocity: 0.0,
};
}
let is_granular = (target - current_state.position).abs() < GRANULAR_DELTA_THRESHOLD as f32;
let rest_delta = options.rest_delta.unwrap_or(if is_granular {
REST_DELTA_GRANULAR as f32
} else {
REST_DELTA_DEFAULT as f32
});
let rest_speed = options.rest_speed.unwrap_or(if is_granular {
REST_SPEED_GRANULAR as f32
} else {
REST_SPEED_DEFAULT as f32
});
let settled = (current_state.position - target).abs() <= rest_delta
&& current_state.velocity.abs() <= rest_speed;
if settled {
state.update(cx, |s, _| {
s.state = SpringState {
position: target,
velocity: 0.0,
};
s.target = target;
s.updated_at_secs = now;
});
SpringSample {
value: target,
velocity: 0.0,
settled: true,
}
} else {
state.update(cx, |s, _| {
s.state = current_state;
s.target = target;
s.updated_at_secs = now;
});
window.request_animation_frame();
SpringSample {
value: current_state.position,
velocity: current_state.velocity,
settled: false,
}
}
}
#[derive(Clone, Copy, Debug)]
struct ArcTransitionState {
from: f32,
target: f32,
started_at_secs: f64,
duration_secs: f64,
curve: CubicBezier,
}
pub fn arc_transition(
id: impl Into<TransitionId>,
target: f32,
duration: Duration,
ease: CubicBezierSpec,
window: &mut Window,
cx: &mut App,
) -> f32 {
let element_id: ElementId =
ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-transition".into());
let now = motion_now(cx);
let curve = CubicBezier::from_spec(ease);
let duration_secs = duration.as_secs_f64();
let state = window.use_keyed_state(element_id, cx, |_, _| ArcTransitionState {
from: target,
target,
started_at_secs: now,
duration_secs,
curve,
});
let snapshot = *state.read(cx);
if cx.reduce_motion() || duration_secs <= 0.0 {
if snapshot.from != target || snapshot.target != target {
state.update(cx, |s, _| {
s.from = target;
s.target = target;
s.started_at_secs = now;
s.duration_secs = duration_secs;
s.curve = curve;
});
}
return target;
}
let elapsed = (now - snapshot.started_at_secs).max(0.0);
let raw_t = if snapshot.duration_secs <= 0.0 {
1.0
} else {
(elapsed / snapshot.duration_secs).clamp(0.0, 1.0)
};
let eased = snapshot.curve.sample(raw_t as f32);
let current = snapshot.from + (snapshot.target - snapshot.from) * eased;
if (snapshot.target - target).abs() > 1e-6 {
state.update(cx, |s, _| {
s.from = current;
s.target = target;
s.started_at_secs = now;
s.duration_secs = duration_secs;
s.curve = curve;
});
window.request_animation_frame();
current
} else if (snapshot.from - snapshot.target).abs() <= 1e-6 || raw_t >= 1.0 {
target
} else {
window.request_animation_frame();
current
}
}
#[cfg(test)]
mod tests {
use arc_tokens::ArcMotionTokens;
use super::*;
fn motion_spring_at_ms(
stiffness: f64,
damping: f64,
mass: f64,
origin: f64,
target: f64,
velocity_per_sec: f64,
t_ms: f64,
) -> f64 {
let delta = target - origin;
let damping_ratio = damping / (2.0 * (stiffness * mass).sqrt());
let undamped_angular_freq = (stiffness / mass).sqrt() / 1000.0;
let decay = damping_ratio * undamped_angular_freq;
let v = -velocity_per_sec / 1000.0;
if damping_ratio < 1.0 - 1e-5 {
let angular_freq = undamped_angular_freq * (1.0 - damping_ratio * damping_ratio).sqrt();
let a = (v + decay * delta) / angular_freq;
let env = (-decay * t_ms).exp();
target - env * (a * (angular_freq * t_ms).sin() + delta * (angular_freq * t_ms).cos())
} else if (damping_ratio - 1.0).abs() <= 1e-5 {
target
- (-undamped_angular_freq * t_ms).exp()
* (delta + (v + undamped_angular_freq * delta) * t_ms)
} else {
let damped_freq = undamped_angular_freq * (damping_ratio * damping_ratio - 1.0).sqrt();
let slow = decay - damped_freq;
let fast = decay + damped_freq;
let p = (v + decay * delta) / damped_freq;
let s = 0.5 * (delta + p);
let f = 0.5 * (delta - p);
target - s * (-slow * t_ms).exp() - f * (-fast * t_ms).exp()
}
}
#[test]
fn frame_by_frame_matches_motion_within_0_5px_across_all_arc_presets() {
let springs = ArcMotionTokens::DEFAULT.spring;
let cases = [
("responsive", springs.responsive, 0.0, 200.0, 0.0),
("responsive_with_vel", springs.responsive, 0.0, 200.0, 450.0),
("gentle", springs.gentle, 20.0, 180.0, -120.0),
("snappy", springs.snappy, 0.0, 100.0, 0.0),
("smooth", springs.smooth, 0.0, 300.0, 0.0),
("morph", springs.morph, 40.0, 220.0, 0.0),
(
"elastic_snap_back",
SpringSpec::visual(0.5, 0.42).as_physical(),
26.0,
0.0,
-180.0,
),
("overdamped", SpringSpec::visual(0.4, -0.3), 0.0, 100.0, 0.0),
];
for (name, spec, origin, target, velocity) in cases {
let physics = spec.resolve();
let solver = SpringSolver::new(spec, origin, target, velocity);
let effective_vel = if physics.is_time_defined {
0.0
} else {
velocity
};
let gpui_cfg = physics.to_gpui_config();
let mut gpui_state = SpringState {
position: origin as f32,
velocity: effective_vel as f32,
};
let mut max_err_solver = 0.0_f64;
let mut max_err_gpui = 0.0_f64;
let dt_ms = 16.0_f64;
for frame in 1..=60 {
let t_ms = frame as f64 * dt_ms;
let expected = motion_spring_at_ms(
f64::from(physics.stiffness),
f64::from(physics.damping),
f64::from(physics.mass),
origin,
target,
effective_vel,
t_ms,
);
let sample = solver.sample(t_ms / 1000.0);
gpui_state = gpui_cfg.step(gpui_state, target as f32, (dt_ms / 1000.0) as f32);
if !sample.settled {
max_err_solver = max_err_solver.max((f64::from(sample.value) - expected).abs());
}
max_err_gpui = max_err_gpui.max((f64::from(gpui_state.position) - expected).abs());
}
assert!(
max_err_solver < 0.5,
"SpringSolver '{name}' max error {max_err_solver}px >= 0.5px"
);
assert!(
max_err_gpui < 0.5,
"GPUI SpringConfig '{name}' max error {max_err_gpui}px >= 0.5px"
);
}
}
}