use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
static OFF: AtomicBool = AtomicBool::new(false);
pub const LIMIT: Duration = Duration::from_millis(150);
pub const STEP: Duration = Duration::from_millis(140);
pub const TOOLTIP_IN: Duration = Duration::from_millis(125);
pub const TOOLTIP_DELAY: Duration = Duration::from_millis(250);
pub const TOOLTIP_WARM: Duration = Duration::from_millis(300);
pub const PULSE: Duration = Duration::from_millis(1_400);
pub const SWEEP: Duration = Duration::from_millis(1_100);
pub const ZOOM_FROM: f32 = 0.35;
const _: () =
assert!(STEP.as_millis() <= LIMIT.as_millis() && TOOLTIP_IN.as_millis() <= LIMIT.as_millis());
pub fn fade_from(from: f32, progress: f32) -> f32 {
from + (1.0 - from) * progress
}
pub fn ease_out(progress: f32) -> f32 {
cubic_bezier(0.23, 1.0, 0.32, 1.0, progress)
}
pub fn ease_in_out(progress: f32) -> f32 {
cubic_bezier(0.65, 0.0, 0.35, 1.0, progress)
}
pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, progress: f32) -> f32 {
let progress = progress.clamp(0.0, 1.0);
if progress == 0.0 || progress == 1.0 {
return progress;
}
let curve = |a: f32, b: f32, t: f32| {
let inverse = 1.0 - t;
3.0 * inverse * inverse * t * a + 3.0 * inverse * t * t * b + t * t * t
};
let slope = |a: f32, b: f32, t: f32| {
let inverse = 1.0 - t;
3.0 * inverse * inverse * a + 6.0 * inverse * t * (b - a) + 3.0 * t * t * (1.0 - b)
};
let mut t = progress;
for _ in 0..8 {
let error = curve(x1, x2, t) - progress;
if error.abs() < 1e-5 {
return curve(y1, y2, t);
}
let derivative = slope(x1, x2, t);
if derivative.abs() < 1e-6 {
break;
}
t = (t - error / derivative).clamp(0.0, 1.0);
}
let (mut low, mut high) = (0.0_f32, 1.0_f32);
t = progress;
for _ in 0..32 {
let x = curve(x1, x2, t);
if (x - progress).abs() < 1e-5 {
break;
}
if x < progress {
low = t;
} else {
high = t;
}
t = (low + high) / 2.0;
}
curve(y1, y2, t)
}
pub fn configure(enabled: bool) {
OFF.store(!enabled, Ordering::Relaxed);
}
pub fn reduced() -> bool {
OFF.load(Ordering::Relaxed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn linear_bezier_is_the_identity() {
for step in 0..=10_u8 {
let progress = f32::from(step) / 10.0;
assert!((cubic_bezier(0.0, 0.0, 1.0, 1.0, progress) - progress).abs() < 1e-3);
}
}
#[test]
fn ease_out_front_loads_the_motion() {
assert!(ease_out(0.0).abs() < f32::EPSILON);
assert!((ease_out(1.0) - 1.0).abs() < f32::EPSILON);
assert!(ease_out(0.2) > 0.6);
let mut previous = 0.0;
for step in 1..=20_u8 {
let value = ease_out(f32::from(step) / 20.0);
assert!(value >= previous);
previous = value;
}
}
}