1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#[derive(Debug, Clone, Copy)]
/// Options for ease.
pub enum Ease {
/// Linear option.
Linear,
/// Ease in option.
EaseIn,
/// Ease out option.
EaseOut,
/// Ease in out option.
EaseInOut,
/// CSS-like cubic-bezier; maps input progress t in \[0,1\] to output y by solving x(t)=progress.
CubicBezier {
/// Item value.
x1: f32,
/// Item value.
y1: f32,
/// Item value.
x2: f32,
/// Item value.
y2: f32,
},
}
/// Documents ease value.
pub fn ease_value(e: Ease, t: f32) -> f32 {
let x = t.clamp(0.0, 1.0);
match e {
Ease::Linear => x,
Ease::EaseIn => x * x,
Ease::EaseOut => 1.0 - (1.0 - x) * (1.0 - x),
Ease::EaseInOut => {
if x < 0.5 {
2.0 * x * x
} else {
1.0 - (-2.0 * x + 2.0).powi(2) / 2.0
}
}
Ease::CubicBezier { x1, y1, x2, y2 } => cubic_bezier_solve(x1, y1, x2, y2, x),
}
}
// Solve y given progress p in [0,1] for a cubic-bezier defined by (0,0),(x1,y1),(x2,y2),(1,1)
// using Newton-Raphson on x(t)=p then evaluate y(t).
fn cubic_bezier_solve(x1: f32, y1: f32, x2: f32, y2: f32, p: f32) -> f32 {
// Clamp control points to sane ranges
let x1 = x1.clamp(0.0, 1.0);
let x2 = x2.clamp(0.0, 1.0);
// Initial guess: p
let mut t = p;
for _ in 0..6 {
let (x_t, dx_dt) = bezier_x_and_derivative(t, x1, x2);
let err = x_t - p;
if err.abs() < 1e-4 {
break;
}
if dx_dt.abs() > 1e-6 {
t -= err / dx_dt;
}
t = t.clamp(0.0, 1.0);
}
bezier_y(t, y1, y2)
}
#[inline]
fn bezier_x_and_derivative(t: f32, x1: f32, x2: f32) -> (f32, f32) {
// x(t) = 3(1-t)^2 t x1 + 3(1-t) t^2 x2 + t^3
let u = 1.0 - t;
let tt = t * t;
let uu = u * u;
let x = 3.0 * uu * t * x1 + 3.0 * u * tt * x2 + tt * t;
// dx/dt = 3( (1-t)^2 x1 + 2(1-t)t(x2 - x1) + t^2(1 - x2) )
let dx = 3.0 * (uu * x1 + 2.0 * u * t * (x2 - x1) + tt * (1.0 - x2));
(x, dx)
}
#[inline]
fn bezier_y(t: f32, y1: f32, y2: f32) -> f32 {
let u = 1.0 - t;
let _b0 = u * u * u;
let b1 = 3.0 * u * u * t;
let b2 = 3.0 * u * t * t;
let b3 = t * t * t;
b1 * y1 + b2 * y2 + b3 // P0.y=0,P3.y=1
}
#[derive(Debug, Clone)]
/// Tween data.
pub struct Tween<T> {
/// Start value.
pub start: T,
/// End value.
pub end: T,
/// Duration value.
pub duration: f32,
/// Elapsed value.
pub elapsed: f32,
/// Ease value.
pub ease: Ease,
}
impl<
T: Copy
+ core::ops::Add<Output = T>
+ core::ops::Sub<Output = T>
+ core::ops::Mul<f32, Output = T>,
> Tween<T>
{
/// Creates a new value.
pub fn new(start: T, end: T, duration: f32, ease: Ease) -> Self {
Self {
start,
end,
duration,
elapsed: 0.0,
ease,
}
}
/// Reset.
pub fn reset(&mut self) {
self.elapsed = 0.0;
}
/// Is finished.
pub fn is_finished(&self) -> bool {
self.elapsed >= self.duration
}
/// Sample.
pub fn sample(&self) -> T {
if self.duration <= 0.0 {
return self.end;
}
let t = (self.elapsed / self.duration).clamp(0.0, 1.0);
let w = ease_value(self.ease, t);
self.start + (self.end - self.start) * w
}
/// Step.
pub fn step(&mut self, dt: f32) -> T {
self.elapsed += dt;
self.sample()
}
}
#[derive(Debug, Clone)]
/// Options for track.
pub enum Track<T> {
/// Sequence option.
Sequence(Vec<Tween<T>>),
/// Parallel option.
Parallel(Vec<Tween<T>>),
}
impl<T> Track<T>
where
T: Copy
+ core::ops::Add<Output = T>
+ core::ops::Sub<Output = T>
+ core::ops::Mul<f32, Output = T>,
{
/// Step.
pub fn step(&mut self, dt: f32) -> Vec<T> {
match self {
Track::Sequence(ref mut tweens) => {
let mut out = Vec::new();
if tweens.is_empty() {
return out;
}
let mut i = 0usize;
let mut remaining_dt = dt;
while i < tweens.len() {
let before = tweens[i].elapsed;
let v = tweens[i].step(remaining_dt);
out.push(v);
if tweens[i].is_finished() {
// deduct used dt if any remained after finishing
let used = tweens[i].duration - before;
remaining_dt = (remaining_dt - used).max(0.0);
i += 1;
if i >= tweens.len() || remaining_dt <= 0.0 {
break;
}
} else {
break;
}
}
out
}
Track::Parallel(ref mut tweens) => tweens.iter_mut().map(|tw| tw.step(dt)).collect(),
}
}
}
/// Timeline data.
pub struct Timeline<T>
where
T: Copy
+ core::ops::Add<Output = T>
+ core::ops::Sub<Output = T>
+ core::ops::Mul<f32, Output = T>,
{
tracks: Vec<Track<T>>,
time: f32,
rate: f32,
playing: bool,
labels: std::collections::HashMap<String, f32>,
callbacks: Vec<TimelineCallback>,
}
impl<T> Default for Timeline<T>
where
T: Copy
+ core::ops::Add<Output = T>
+ core::ops::Sub<Output = T>
+ core::ops::Mul<f32, Output = T>,
{
fn default() -> Self {
Self::new()
}
}
impl<T> Timeline<T>
where
T: Copy
+ core::ops::Add<Output = T>
+ core::ops::Sub<Output = T>
+ core::ops::Mul<f32, Output = T>,
{
/// Creates a new value.
pub fn new() -> Self {
Self {
tracks: Vec::new(),
time: 0.0,
rate: 1.0,
playing: true,
labels: std::collections::HashMap::new(),
callbacks: Vec::new(),
}
}
/// Push track.
pub fn push_track(&mut self, track: Track<T>) {
self.tracks.push(track);
}
/// Sets the rate.
pub fn set_rate(&mut self, rate: f32) {
self.rate = rate;
}
/// Play.
pub fn play(&mut self) {
self.playing = true;
}
/// Pause.
pub fn pause(&mut self) {
self.playing = false;
}
/// Seek.
pub fn seek(&mut self, _t: f32) {
// Re-simulate all tracks from t=0 to requested time using a fixed small step for determinism.
// This is a simple implementation intended for tests/snapshots, not a high-perf runtime.
let t = _t.max(0.0);
// Reset internal time and callbacks fired state
self.time = 0.0;
for cb in &mut self.callbacks {
cb.fired = false;
}
// Reset all tweens by reconstructing them from their current values; we need owned data.
// We approximate rewinding by creating new tracks with same tweens and calling reset.
// Sequence/Parallel reset
for tr in &mut self.tracks {
match tr {
Track::Sequence(tweens) | Track::Parallel(tweens) => {
for tw in tweens.iter_mut() {
tw.reset();
}
}
}
}
// Fixed small delta to step forward deterministically
let dt = 1.0 / 240.0; // 240 Hz stepping for accuracy
let mut rem = t;
while rem > 0.0 {
let step = if rem < dt { rem } else { dt };
let prev_time = self.time;
self.time += step;
// Fire callbacks crossed in this step
for cb in &mut self.callbacks {
if !cb.fired && cb.time > prev_time && cb.time <= self.time {
(cb.func)();
cb.fired = true;
}
}
// Advance tracks
for tr in &mut self.tracks {
let _ = tr.step(step);
}
rem -= step;
}
}
/// Step.
pub fn step(&mut self, dt: f32) -> Vec<Vec<T>> {
if !self.playing {
return vec![];
}
let scaled = dt * self.rate;
let prev_time = self.time;
self.time += scaled;
// Fire any callbacks whose time is now reached
for cb in &mut self.callbacks {
if !cb.fired && cb.time > prev_time && cb.time <= self.time {
(cb.func)();
cb.fired = true;
}
}
self.tracks.iter_mut().map(|tr| tr.step(scaled)).collect()
}
// Labels
/// Add label.
pub fn add_label(&mut self, name: impl Into<String>, at_time: f32) {
self.labels.insert(name.into(), at_time);
}
/// Label time.
pub fn label_time(&self, name: &str) -> Option<f32> {
self.labels.get(name).copied()
}
// Callbacks
/// On at.
pub fn on_at(&mut self, at_time: f32, f: impl FnMut() + 'static) {
self.callbacks.push(TimelineCallback {
time: at_time,
fired: false,
func: Box::new(f),
});
}
/// On label.
pub fn on_label(&mut self, name: &str, f: impl FnMut() + 'static) {
if let Some(t) = self.labels.get(name).copied() {
self.on_at(t, f);
}
}
}
struct TimelineCallback {
time: f32,
fired: bool,
func: Box<dyn FnMut()>,
}