use std::cell::RefCell;
use std::collections::HashMap;
use std::mem::ManuallyDrop;
use std::rc::Weak;
use std::time::Instant;
pub(crate) trait Tickable {
fn tick(&self, now: Instant, scale: f32);
fn is_settled(&self) -> bool;
}
struct Registry {
entries: HashMap<u64, Weak<dyn Tickable>>,
next_id: u64,
scale: f32,
}
impl Registry {
fn new() -> Self {
Registry {
entries: HashMap::new(),
next_id: 0,
scale: 1.0,
}
}
}
thread_local! {
static REGISTRY: ManuallyDrop<RefCell<Registry>> = ManuallyDrop::new(RefCell::new(Registry::new()));
}
pub(crate) fn next_id() -> u64 {
REGISTRY.with(|r| {
let mut reg = r.borrow_mut();
let id = reg.next_id;
reg.next_id += 1;
id
})
}
pub(crate) fn register(id: u64, weak: Weak<dyn Tickable>) {
REGISTRY.with(|r| {
r.borrow_mut().entries.insert(id, weak);
});
}
fn is_live(weak: &Weak<dyn Tickable>) -> bool {
matches!(weak.upgrade(), Some(anim) if !anim.is_settled())
}
pub fn tick(now: Instant) {
let (scale, live): (f32, Vec<std::rc::Rc<dyn Tickable>>) = REGISTRY.with(|r| {
let reg = r.borrow();
let live = reg.entries.values().filter_map(Weak::upgrade).collect();
(reg.scale, live)
});
for anim in &live {
anim.tick(now, scale);
}
REGISTRY.with(|r| {
r.borrow_mut().entries.retain(|_, weak| is_live(weak));
});
}
pub fn has_active() -> bool {
REGISTRY.with(|r| r.borrow().entries.values().any(is_live))
}
pub fn reset() {
REGISTRY.with(|r| r.borrow_mut().entries.clear());
}
pub fn set_scale(scale: f32) {
REGISTRY.with(|r| r.borrow_mut().scale = scale.max(0.0));
}