comfy_core/
tween.rs

1use crate::*;
2
3pub struct Tween {
4    initial_val: f32,
5    final_val: f32,
6    duration: f32,
7    elapsed: f32,
8    delay: f32,
9    easing_fn: fn(f32) -> f32,
10    value: f32,
11}
12
13impl Default for Tween {
14    fn default() -> Self {
15        Self::new(0.0, 0.0, 0.0, 0.0, linear)
16    }
17}
18
19impl Tween {
20    pub fn new(
21        initial_val: f32,
22        final_val: f32,
23        duration: f32,
24        delay: f32,
25        easing_fn: fn(f32) -> f32,
26    ) -> Self {
27        Tween {
28            initial_val,
29            final_val,
30            duration,
31            elapsed: 0.0,
32            delay,
33            easing_fn,
34            value: initial_val,
35        }
36    }
37
38    pub fn is_finished(&self) -> bool {
39        self.elapsed >= self.duration + self.delay
40    }
41
42    pub fn update(&mut self, delta_time: f32) {
43        if self.delay > 0.0 {
44            self.delay -= delta_time;
45            return;
46        }
47
48        self.elapsed += delta_time;
49        let progress = (self.elapsed / self.duration).min(1.0);
50
51        let t = (self.easing_fn)(progress);
52        self.value = self.initial_val + t * (self.final_val - self.initial_val);
53    }
54
55    pub fn value(&self) -> f32 {
56        self.value
57    }
58}
59
60#[derive(Copy, Clone, Debug)]
61pub struct FlashingColor {
62    color: Color,
63    flash_color: Color,
64    duration: f32,
65    total_remaining: f32,
66    interval: f32,
67    interval_remaining: f32,
68    easing_fn: fn(f32) -> f32,
69}
70
71impl FlashingColor {
72    pub fn new(
73        color: Color,
74        flash_color: Color,
75        duration: f32,
76        interval: f32,
77        easing_fn: fn(f32) -> f32,
78    ) -> Self {
79        Self {
80            color,
81            flash_color,
82            duration,
83            total_remaining: 0.0,
84            interval,
85            interval_remaining: 0.0,
86            easing_fn,
87        }
88    }
89
90    pub fn trigger(&mut self) {
91        self.total_remaining = self.duration;
92    }
93
94    pub fn update(&mut self, delta: f32) {
95        if self.total_remaining > 0.0 {
96            self.total_remaining -= delta;
97            self.interval_remaining -= delta;
98
99            if self.interval_remaining <= 0.0 {
100                self.interval_remaining = self.interval;
101            }
102        }
103    }
104
105    pub fn current_color(&self) -> Color {
106        if self.total_remaining <= 0.0 {
107            self.color
108        } else {
109            let progress = (self.interval_remaining / self.interval).min(1.0);
110            let t = (self.easing_fn)(progress);
111            Color::lerp(self.color, self.flash_color, t)
112        }
113    }
114}