use std::cell::Cell;
use web_time::{Duration, Instant};
thread_local! {
static VIRTUAL: Cell<Option<Instant>> = const { Cell::new(None) };
static ANIM_EPOCH: Cell<Option<Instant>> = const { Cell::new(None) };
}
#[inline]
pub fn now() -> Instant {
VIRTUAL.with(|v| v.get()).unwrap_or_else(Instant::now)
}
pub fn animation_millis() -> u64 {
let t = now();
ANIM_EPOCH.with(|e| {
let epoch = match e.get() {
Some(ep) => ep,
None => {
e.set(Some(t));
t
}
};
t.saturating_duration_since(epoch).as_millis() as u64
})
}
pub fn install_virtual() {
VIRTUAL.with(|v| v.set(Some(Instant::now())));
ANIM_EPOCH.with(|e| e.set(None));
}
pub fn install_virtual_at(t: Instant) {
VIRTUAL.with(|v| v.set(Some(t)));
ANIM_EPOCH.with(|e| e.set(None));
}
pub fn advance(dur: Duration) {
VIRTUAL.with(|v| {
if let Some(t) = v.get() {
v.set(Some(t + dur));
}
});
}
pub fn reset_to_wall() {
VIRTUAL.with(|v| v.set(None));
ANIM_EPOCH.with(|e| e.set(None));
}
pub fn is_virtual() -> bool {
VIRTUAL.with(|v| v.get().is_some())
}
pub struct ClockTimeSource {
start: Instant,
}
impl ClockTimeSource {
pub fn new() -> Self {
Self { start: now() }
}
}
impl Default for ClockTimeSource {
fn default() -> Self {
Self::new()
}
}
impl auralis_task::TimeSource for ClockTimeSource {
fn now_ms(&self) -> u64 {
now().duration_since(self.start).as_millis() as u64
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn animation_millis_follows_virtual_clock() {
reset_to_wall();
install_virtual();
assert_eq!(animation_millis(), 0, "epoch re-anchors on install_virtual");
advance(Duration::from_millis(300));
assert_eq!(animation_millis(), 300);
advance(Duration::from_millis(450));
assert_eq!(animation_millis(), 750);
reset_to_wall();
}
#[test]
fn animation_millis_is_monotonic_in_wall_mode() {
reset_to_wall();
let a = animation_millis();
let b = animation_millis();
assert!(b >= a);
}
#[test]
fn virtual_clock_is_pinned_and_advances() {
reset_to_wall();
assert!(!is_virtual());
install_virtual();
assert!(is_virtual());
let t0 = now();
assert_eq!(now(), t0);
advance(Duration::from_millis(300));
assert_eq!(now(), t0 + Duration::from_millis(300));
reset_to_wall();
assert!(!is_virtual());
}
#[test]
fn advance_is_noop_in_wall_mode() {
reset_to_wall();
advance(Duration::from_secs(10)); assert!(!is_virtual());
}
}