1use crate::{Brush, Color, GradientStop, Length, Node, Percent, Value};
2use std::{borrow::Cow, collections::BTreeMap, sync::Arc, time::Duration};
3
4#[derive(Clone, Copy, Debug, Default, PartialEq)]
5pub struct Easing(Option<[f64; 4]>);
6
7impl Easing {
8 pub const LINEAR: Self = Self(None);
9
10 pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> Option<Self> {
11 ((0.0..=1.0).contains(&x1) && (0.0..=1.0).contains(&x2) && y1.is_finite() && y2.is_finite())
12 .then_some(Self(Some([x1, y1, x2, y2])))
13 }
14
15 fn sample(self, progress: f64) -> f64 {
16 let Some([x1, y1, x2, y2]) = self.0 else {
17 return progress;
18 };
19 if progress == 0.0 || progress == 1.0 {
20 return progress;
21 }
22 let coordinate = |p1: f64, p2: f64, t: f64| {
23 let inverse = 1.0 - t;
24 (3.0 * inverse * inverse * t) * p1 + (3.0 * inverse * t * t) * p2 + t * t * t
25 };
26 let (mut low, mut high) = (0.0, 1.0);
29 for _ in 0..24 {
30 let mid = (low + high) * 0.5;
31 if coordinate(x1, x2, mid) < progress {
32 low = mid;
33 } else {
34 high = mid;
35 }
36 }
37 coordinate(y1, y2, (low + high) * 0.5)
38 }
39}
40
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
42pub struct Animation {
43 duration: Duration,
44 delay: Duration,
45 easing: Easing,
46}
47
48impl Animation {
49 pub fn new(duration_ms: u64, delay_ms: u64, easing: Easing) -> Self {
50 Self {
51 duration: Duration::from_millis(duration_ms),
52 delay: Duration::from_millis(delay_ms),
53 easing,
54 }
55 }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct StateTiming {
60 pub case: i64,
61 pub enter: Option<Animation>,
62 pub exit: Option<Animation>,
63}
64
65struct Track {
66 from: Value,
67 begin: Duration,
68 end: Duration,
69 easing: Easing,
70}
71
72impl Track {
73 fn sample(&self, to: &Value, now: Duration) -> Option<Value> {
74 if now >= self.end {
75 return None;
76 }
77 if now <= self.begin {
78 return Some(self.from.clone());
79 }
80 let progress = (now - self.begin).as_secs_f64() / (self.end - self.begin).as_secs_f64();
81 interpolate(&self.from, to, self.easing.sample(progress))
82 }
83}
84
85type Tracks = BTreeMap<Vec<usize>, BTreeMap<&'static str, Track>>;
86
87#[derive(Default)]
88pub struct SceneTransition {
89 tracks: Tracks,
90}
91
92impl SceneTransition {
93 pub fn between(previous: &Node, next: &Node) -> Self {
94 let mut result = Self::default();
95 result.retarget(previous, next, Duration::ZERO);
96 result
97 }
98
99 pub fn retarget(&mut self, previous: &Node, next: &Node, now: Duration) {
102 fn collect(
103 previous: &Node,
104 next: &Node,
105 path: &mut Vec<usize>,
106 old: &mut Tracks,
107 new: &mut Tracks,
108 now: Duration,
109 ) {
110 if previous.kind != next.kind
111 || previous.id != next.id
112 || previous.row_key != next.row_key
113 {
114 return;
115 }
116 let mut old_at_path = old.remove(path.as_slice()).unwrap_or_default();
117 let mut tracks = BTreeMap::new();
118 let mut track = |property, timing: Option<Animation>| {
119 if timing.is_some_and(|timing| timing.duration.is_zero() && timing.delay.is_zero())
120 {
121 return;
122 }
123 let (Some(previous_target), Some(next_target)) = (
124 previous.properties.get(property),
125 next.properties.get(property),
126 ) else {
127 return;
128 };
129 let old = old_at_path.remove(property).filter(|track| now < track.end);
130 if previous_target == next_target {
131 if let Some(old) = old {
132 tracks.insert(property, old);
133 }
134 return;
135 }
136 let Some(timing) = timing else {
137 return;
138 };
139 let from = old
140 .and_then(|track| track.sample(previous_target, now))
141 .unwrap_or_else(|| previous_target.clone());
142 if from != *next_target && interpolate(&from, next_target, 0.0).is_some() {
143 let begin = now.saturating_add(timing.delay);
144 tracks.insert(
145 property,
146 Track {
147 from,
148 begin,
149 end: begin.saturating_add(timing.duration),
150 easing: timing.easing,
151 },
152 );
153 }
154 };
155 for (&property, &timing) in &next.animations {
156 track(property, Some(timing));
157 }
158 if let Some(timings) = &next.state_timings {
159 for (&property, next_state) in timings.iter() {
160 let previous_state = previous
161 .state_timings
162 .as_ref()
163 .and_then(|timings| timings.get(property));
164 let timing = previous_state
165 .filter(|state| state.case != next_state.case)
166 .and_then(|state| next_state.enter.or(state.exit));
167 track(property, timing);
168 }
169 }
170 if !tracks.is_empty() {
171 new.insert(path.clone(), tracks);
172 }
173 for (index, child) in next.materialized_children() {
174 let Some(previous) = previous.child_at(index) else {
175 continue;
176 };
177 path.push(index);
178 collect(previous, child, path, old, new, now);
179 path.pop();
180 }
181 }
182 let mut old = std::mem::take(&mut self.tracks);
183 collect(
184 previous,
185 next,
186 &mut Vec::new(),
187 &mut old,
188 &mut self.tracks,
189 now,
190 );
191 }
192
193 pub fn next_frame(&self, elapsed: Duration) -> Option<Duration> {
196 self.tracks
197 .values()
198 .flat_map(|tracks| tracks.values())
199 .filter(|track| elapsed < track.end)
200 .map(|track| track.begin.max(elapsed))
201 .min()
202 }
203
204 pub fn running(&self, elapsed: Duration) -> bool {
205 self.next_frame(elapsed).is_some()
206 }
207
208 pub fn frame<'a>(&self, target: &'a Node, elapsed: Duration) -> Cow<'a, Node> {
209 if !self.running(elapsed) {
210 return Cow::Borrowed(target);
211 }
212 let mut frame = target.clone();
213 for (path, tracks) in &self.tracks {
214 if tracks.values().all(|track| elapsed >= track.end) {
215 continue;
216 }
217 let mut node = Some(&mut frame);
218 for &index in path {
219 node = node.and_then(|node| node.child_at_mut(index));
220 }
221 let Some(node) = node else {
222 continue;
223 };
224 for (&property, track) in tracks {
225 if let Some(value) = node.properties.get_mut(property)
226 && let Some(interpolated) = track.sample(value, elapsed)
227 {
228 *value = interpolated;
229 }
230 }
231 }
232 Cow::Owned(frame)
233 }
234}
235
236fn mix(a: f64, b: f64, amount: f64) -> f64 {
237 a * (1.0 - amount) + b * amount
238}
239
240fn mix_color(a: Color, b: Color, amount: f64) -> Color {
241 let channels = [24, 16, 8, 0].map(|shift| {
242 mix(
243 f64::from((a.0 >> shift) & 255),
244 f64::from((b.0 >> shift) & 255),
245 amount,
246 )
247 .round()
248 .clamp(0.0, 255.0) as u32
249 });
250 let [r, g, b, a] = channels;
251 Color((r << 24) | (g << 16) | (b << 8) | a)
252}
253
254fn mix_stops(a: &[GradientStop], b: &[GradientStop], amount: f64) -> Option<Arc<[GradientStop]>> {
255 if a.len() != b.len() {
256 return None;
257 }
258 let position_progress = amount.clamp(0.0, 1.0);
259 Some(
260 a.iter()
261 .zip(b)
262 .map(|(a, b)| GradientStop {
263 offset: mix(a.offset, b.offset, position_progress),
264 color: mix_color(a.color, b.color, amount),
265 })
266 .collect(),
267 )
268}
269
270fn interpolate(from: &Value, to: &Value, amount: f64) -> Option<Value> {
271 if !amount.is_finite() {
272 return None;
273 }
274 let number = |a: f64, b: f64| {
275 let result = mix(a, b, amount);
276 result.is_finite().then_some(result)
277 };
278 Some(match (from, to) {
279 (Value::Int(a), Value::Int(b)) => {
280 Value::Int(mix(*a as f64, *b as f64, amount).round() as i64)
281 }
282 (Value::Float(a), Value::Float(b)) => Value::Float(number(*a, *b)?),
283 (Value::Length(Length(a)), Value::Length(Length(b))) => {
284 Value::Length(Length(number(*a, *b)?))
285 }
286 (Value::Percent(Percent(a)), Value::Percent(Percent(b))) => {
287 Value::Percent(Percent(number(*a, *b)?))
288 }
289 (Value::Color(a) | Value::Brush(Brush::Solid(a)), Value::Color(b)) => {
290 Value::Color(mix_color(*a, *b, amount))
291 }
292 (Value::Color(a) | Value::Brush(Brush::Solid(a)), Value::Brush(Brush::Solid(b))) => {
293 Value::Brush(Brush::Solid(mix_color(*a, *b, amount)))
294 }
295 (
296 Value::Brush(Brush::Linear {
297 angle_degrees: a,
298 stops: from,
299 }),
300 Value::Brush(Brush::Linear {
301 angle_degrees: b,
302 stops: to,
303 }),
304 ) => Value::Brush(Brush::Linear {
305 angle_degrees: number(*a, *b)?,
306 stops: mix_stops(from, to, amount)?,
307 }),
308 (
309 Value::Brush(Brush::Radial { stops: from }),
310 Value::Brush(Brush::Radial { stops: to }),
311 ) => Value::Brush(Brush::Radial {
312 stops: mix_stops(from, to, amount)?,
313 }),
314 _ => return None,
315 })
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 fn time(ms: u64) -> Duration {
323 Duration::from_millis(ms)
324 }
325
326 fn rectangle(width: f64, timing: Animation) -> Node {
327 let mut node = Node::new("Rectangle", Some("bar"));
328 node.properties.insert("width", Length(width).into());
329 node.animations.insert("width", timing);
330 node
331 }
332
333 #[test]
334 fn unrelated_updates_keep_deadlines_and_retargeting_starts_at_the_visible_value() {
335 let timing = Animation::new(200, 100, Easing::LINEAR);
336 let initial = rectangle(10.0, timing);
337 let target = rectangle(110.0, timing);
338 let mut transition = SceneTransition::between(&initial, &target);
339 assert_eq!(transition.next_frame(time(20)), Some(time(100)));
340 assert_eq!(
341 transition.frame(&target, time(20)).length("width"),
342 Some(10.0)
343 );
344
345 let mut updated = target.clone();
346 updated.properties.insert("height", Length(40.0).into());
347 transition.retarget(&target, &updated, time(50));
348 assert_eq!(transition.next_frame(time(50)), Some(time(100)));
349 assert_eq!(
350 transition.frame(&updated, time(200)).length("width"),
351 Some(60.0)
352 );
353
354 let reversed = rectangle(0.0, timing);
355 transition.retarget(&updated, &reversed, time(200));
356 assert_eq!(transition.next_frame(time(200)), Some(time(300)));
357 assert_eq!(
358 transition.frame(&reversed, time(200)).length("width"),
359 Some(60.0)
360 );
361 assert_eq!(
362 transition.frame(&reversed, time(400)).length("width"),
363 Some(30.0)
364 );
365 assert!(matches!(
366 transition.frame(&reversed, time(500)),
367 Cow::Borrowed(_)
368 ));
369
370 let mut immediate = reversed.clone();
371 immediate.animations.clear();
372 transition.retarget(&reversed, &immediate, time(400));
373 assert_eq!(transition.next_frame(time(400)), None);
374 assert_eq!(
375 transition.frame(&immediate, time(400)).length("width"),
376 Some(0.0)
377 );
378 }
379
380 #[test]
381 fn a_delayed_zero_duration_track_jumps_only_at_its_deadline() {
382 let timing = Animation::new(0, 90, Easing::LINEAR);
383 let initial = rectangle(20.0, timing);
384 let target = rectangle(100.0, timing);
385 let transition = SceneTransition::between(&initial, &target);
386 assert_eq!(transition.next_frame(time(0)), Some(time(90)));
387 assert_eq!(
388 transition.frame(&target, time(89)).length("width"),
389 Some(20.0)
390 );
391 assert_eq!(
392 transition.frame(&target, time(90)).length("width"),
393 Some(100.0)
394 );
395 assert_eq!(transition.next_frame(time(90)), None);
396 }
397
398 #[test]
399 fn easing_clamps_overshooting_channels_and_interpolates_matching_gradients() {
400 let fast = Easing::cubic_bezier(0.0, 0.8, 1.0, 0.8).unwrap();
401 assert!((fast.sample(0.5) - 0.725).abs() < 1e-6);
402 let overshoot = Easing::cubic_bezier(0.0, 2.0, 1.0, 2.0)
403 .unwrap()
404 .sample(0.5);
405 assert!(overshoot > 1.0);
406 assert_eq!(
407 mix_color(Color(0x001020ff), Color(0xeeeeeeff), overshoot),
408 Color(0xffffffff)
409 );
410
411 let brush = |angle_degrees, start, end, color| {
412 Value::Brush(Brush::Linear {
413 angle_degrees,
414 stops: [
415 GradientStop {
416 color,
417 offset: start,
418 },
419 GradientStop { color, offset: end },
420 ]
421 .into(),
422 })
423 };
424 let from = brush(0.0, 0.0, 0.8, Color(0xff0000ff));
425 let to = brush(90.0, 0.2, 1.0, Color(0x0000ffff));
426 assert_eq!(
427 interpolate(&from, &to, 0.5),
428 Some(brush(45.0, 0.1, 0.9, Color(0x800080ff)))
429 );
430 }
431}