1
//! DOM-morph animation: interpolation core, FLIP geometry, and the keyed
2
//! animation store.
3
//!
4
//! # Model
5
//!
6
//! Animation compiles to keyed timer callbacks writing into the top cascade layer
7
//! (`user_overridden_properties`). This module handles the math and bookkeeping
8
//! across frames:
9
//!
10
//! * [`Spring`] / [`AnimChannel`]: How a single value transitions from `from` to `to`, with
11
//!   interruption as a first-class operation ([`AnimChannel::retarget`]).
12
//! * [`flip`]: The First/Last inversion that turns a layout change into a composited transform,
13
//!   saving relayouts.
14
//! * [`AnimationManager`]: The keyed store - keys are reconciliation identities so that retargeting
15
//!   finds the in-flight state instead of overlapping.
16
//!
17
//! # Curve vs. Spring
18
//!
19
//! Easing curves are functions of normalized time. Interrupting them discards velocity,
20
//! causing snapping. Springs integrate from the current `(value, velocity)`, allowing
21
//! smooth retargeting.
22

            
23
use alloc::{collections::BTreeMap, string::String, vec::Vec};
24

            
25
use azul_css::props::basic::animation::AnimationInterpolationFunction;
26
/// Re-export of [`SpringCurve`].
27
pub use azul_css::props::basic::animation::SpringCurve as Spring;
28

            
29
use crate::{
30
    diff::{calculate_reconciliation_key, NodeMove},
31
    dom::NodeData,
32
    geom::LogicalRect,
33
    id::NodeId,
34
    styled_dom::NodeHierarchyItem,
35
};
36

            
37
/// A single animated value over time (e.g., an x-coordinate or opacity).
38
///
39
/// Complex animations are created by combining multiple channels. For example,
40
/// moving an element in 2D requires four channels: x and y translation, and x and y scale.
41
#[derive(Debug, Clone, Copy, PartialEq)]
42
pub struct AnimChannel {
43
    /// Where the value started. Re-seeded on every retarget.
44
    pub from: f32,
45
    /// Where it is heading.
46
    pub to: f32,
47
    /// The current value to write into the cascade.
48
    pub current: f32,
49
    /// Units per second. Carried across retargets.
50
    pub velocity: f32,
51
    /// Seconds since the animation began (curve mode only).
52
    pub elapsed_secs: f32,
53
    /// How it is driven.
54
    pub mode: InterpolationMode,
55
    /// Latched once the channel arrives.
56
    finished: bool,
57
}
58

            
59
/// Specifies how an animated value transitions over time.
60
///
61
/// It can either be driven by a time-based curve (duration-based) or by a
62
/// physics-based spring (velocity and target-based).
63
#[derive(Debug, Clone, Copy, PartialEq)]
64
pub enum InterpolationMode {
65
    /// Duration-based easing. Not interruptible without a discontinuity.
66
    Curve {
67
        /// The CSS easing curve.
68
        function: AnimationInterpolationFunction,
69
        /// Total duration in seconds. Zero means apply instantly.
70
        duration_secs: f32,
71
    },
72
    /// Physics-based. Interruptible with velocity continuity.
73
    Spring(Spring),
74
}
75

            
76
impl Default for InterpolationMode {
77
    fn default() -> Self {
78
        Self::Spring(Spring::SMOOTH)
79
    }
80
}
81

            
82
impl AnimChannel {
83
    /// A channel that eases `from → to` over `duration_secs`.
84
    #[must_use]
85
128
    pub const fn curve(
86
128
        from: f32,
87
128
        to: f32,
88
128
        function: AnimationInterpolationFunction,
89
128
        duration_secs: f32,
90
128
    ) -> Self {
91
128
        Self {
92
128
            from,
93
128
            to,
94
128
            current: from,
95
128
            velocity: 0.0,
96
128
            elapsed_secs: 0.0,
97
128
            mode: InterpolationMode::Curve {
98
128
                function,
99
128
                duration_secs,
100
128
            },
101
128
            finished: false,
102
128
        }
103
128
    }
104

            
105
    /// A channel that springs `from → to`.
106
    #[must_use]
107
234
    pub const fn spring(from: f32, to: f32, spring: Spring) -> Self {
108
234
        Self {
109
234
            from,
110
234
            to,
111
234
            current: from,
112
234
            velocity: 0.0,
113
234
            elapsed_secs: 0.0,
114
234
            mode: InterpolationMode::Spring(spring),
115
234
            finished: false,
116
234
        }
117
234
    }
118

            
119
    /// Advance by `dt` seconds and return the new current value.
120
15775
    pub fn tick(&mut self, dt: f32) -> f32 {
121
15775
        if self.finished {
122
2667
            return self.current;
123
13108
        }
124
13108
        match self.mode {
125
            InterpolationMode::Curve {
126
12153
                function,
127
12153
                duration_secs,
128
            } => {
129
12153
                if duration_secs <= 0.0 {
130
1
                    self.current = self.to;
131
1
                    self.velocity = 0.0;
132
1
                    self.finished = true;
133
1
                    return self.current;
134
12152
                }
135
12152
                self.elapsed_secs += dt.max(0.0);
136
12152
                let linear_t = (self.elapsed_secs / duration_secs).clamp(0.0, 1.0);
137
12152
                let eased = ease(function, linear_t);
138
12152
                let previous = self.current;
139
                // Suboptimal flops allowed for bit-reproducibility across builds.
140
                #[allow(clippy::suboptimal_flops)]
141
12152
                {
142
12152
                    self.current = self.from + (self.to - self.from) * eased;
143
12152
                }
144
                // Track velocity even on curves to ensure continuous handover to springs.
145
12152
                self.velocity = if dt > 0.0 {
146
12152
                    (self.current - previous) / dt
147
                } else {
148
                    0.0
149
                };
150
12152
                if linear_t >= 1.0 {
151
126
                    self.current = self.to;
152
126
                    self.finished = true;
153
12026
                }
154
            }
155
955
            InterpolationMode::Spring(spring) => {
156
955
                let (value, velocity) = spring.step(self.current, self.to, self.velocity, dt);
157
955
                self.current = value;
158
955
                self.velocity = velocity;
159
955
                if spring.is_settled(value, self.to, velocity) {
160
143
                    self.current = self.to;
161
143
                    self.velocity = 0.0;
162
143
                    self.finished = true;
163
824
                }
164
            }
165
        }
166
13107
        self.current
167
15775
    }
168

            
169
    /// Whether this channel has arrived at the target value and can be dropped (animation finished)
170
    #[must_use]
171
3393
    pub const fn is_finished(&self) -> bool {
172
3393
        self.finished
173
3393
    }
174

            
175
    /// Aim at a new target without losing the current value or velocity.
176
    ///
177
    /// This allows smooth retargeting mid-flight.
178
104
    pub fn retarget(&mut self, new_to: f32) {
179
104
        if (self.to - new_to).abs() < f32::EPSILON && !self.finished {
180
62
            return; // already heading there; do not restart the clock
181
42
        }
182
42
        self.from = self.current;
183
42
        self.to = new_to;
184
42
        self.elapsed_secs = 0.0;
185
42
        self.finished = false;
186
        // Velocity is deliberately not reset to allow smooth retargeting.
187
104
    }
188
}
189

            
190
/// Evaluate a CSS easing curve at `t ∈ [0, 1]`.
191
///
192
/// `Ease` and the cubic-beziers use the same evaluator; the named curves are
193
/// their standard control points.
194
#[must_use]
195
12185
pub fn ease(function: AnimationInterpolationFunction, t: f32) -> f32 {
196
12185
    let t = t.clamp(0.0, 1.0);
197
12185
    match function {
198
12157
        AnimationInterpolationFunction::Linear => t,
199
        // The CSS keyword control points.
200
4
        AnimationInterpolationFunction::Ease => cubic_bezier_y(0.25, 0.1, 0.25, 1.0, t),
201
5
        AnimationInterpolationFunction::EaseIn => cubic_bezier_y(0.42, 0.0, 1.0, 1.0, t),
202
5
        AnimationInterpolationFunction::EaseOut => cubic_bezier_y(0.0, 0.0, 0.58, 1.0, t),
203
9
        AnimationInterpolationFunction::EaseInOut => cubic_bezier_y(0.42, 0.0, 0.58, 1.0, t),
204
        AnimationInterpolationFunction::Spring(_) => {
205
5
            crate::diagnostics::emit(String::from(
206
                "Warning: Spring evaluated as an easing curve. This is a misusage.",
207
            ));
208
            // Degrade gracefully to ease-in-out to prevent crashes.
209
5
            cubic_bezier_y(0.42, 0.0, 0.58, 1.0, t)
210
        }
211
        // The 0,0 and 1,1 points are hardcoded directly into the math equation itself,
212
        // so only ctrl_1 and ctrl_2 are needed.
213
        AnimationInterpolationFunction::CubicBezier(curve) => cubic_bezier_y(
214
            curve.ctrl_1.x,
215
            curve.ctrl_1.y,
216
            curve.ctrl_2.x,
217
            curve.ctrl_2.y,
218
            t,
219
        ),
220
    }
221
12185
}
222

            
223
/// Calculates the y value of a CSS timing bezier given an x (time progress).
224
///
225
/// Unlike a standard bezier evaluation that calculates `(x, y)` from a curve parameter `t`,
226
/// CSS easing requires finding `y` (eased progress) for a specific `x` (linear time).
227
/// To do this, we must first reverse-engineer `t` from `x`.
228
///
229
/// We try a fast math shortcut to find `t`. If the curve is too flat, we fall back
230
/// to a slower, safer method to find the exact `t`, which is then used to calculate `y`.
231
28
fn cubic_bezier_y(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {
232
    const NEWTON_ITERATIONS: usize = 4;
233
    const BISECTION_ITERATIONS: usize = 12;
234
    const EPSILON: f32 = 1e-5;
235

            
236
    // allowed for bit-reproducibility across builds
237
    #[allow(clippy::suboptimal_flops)]
238
29
    let bezier = |a: f32, b: f32, t: f32| {
239
29
        let inv = 1.0 - t;
240
29
        3.0 * inv * inv * t * a + 3.0 * inv * t * t * b + t * t * t
241
29
    };
242
    #[allow(clippy::suboptimal_flops)]
243
28
    let bezier_slope = |a: f32, b: f32, t: f32| {
244
13
        let inv = 1.0 - t;
245
13
        3.0 * inv * inv * a + 6.0 * inv * t * (b - a) + 3.0 * t * t * (1.0 - b)
246
13
    };
247

            
248
28
    if x <= 0.0 {
249
10
        return 0.0;
250
18
    }
251
18
    if x >= 1.0 {
252
10
        return 1.0;
253
8
    }
254

            
255
8
    let mut t = x;
256
21
    for _ in 0..NEWTON_ITERATIONS {
257
21
        let error = bezier(x1, x2, t) - x;
258
21
        if error.abs() < EPSILON {
259
8
            return bezier(y1, y2, t);
260
13
        }
261
13
        let slope = bezier_slope(x1, x2, t);
262
13
        if slope.abs() < EPSILON {
263
            break;
264
13
        }
265
13
        t -= error / slope;
266
    }
267

            
268
    let (mut low, mut high) = (0.0_f32, 1.0_f32);
269
    let mut t = x;
270
    for _ in 0..BISECTION_ITERATIONS {
271
        let value = bezier(x1, x2, t);
272
        if (value - x).abs() < EPSILON {
273
            break;
274
        }
275
        if value < x {
276
            low = t;
277
        } else {
278
            high = t;
279
        }
280
        t = (low + high) * 0.5;
281
    }
282
    bezier(y1, y2, t)
283
28
}
284

            
285
/// The inverted transform of a FLIP move.
286
///
287
/// "First" is the element's original position. "Last" is its new position after layout.
288
/// FLIP animation works by placing the element at Last, then applying a transform to
289
/// make it look like it's at First, and finally animating that transform down to zero.
290
/// This allows elements to move smoothly on the GPU without triggering expensive layout
291
/// recalculations on every frame.
292
#[derive(Debug, Clone, Copy, PartialEq, Default)]
293
#[repr(C)]
294
pub struct FlipTransform {
295
    /// Horizontal offset, logical px.
296
    pub translate_x: f32,
297
    /// Vertical offset, logical px.
298
    pub translate_y: f32,
299
    /// Horizontal scale, 1.0 = unchanged.
300
    pub scale_x: f32,
301
    /// Vertical scale, 1.0 = unchanged.
302
    pub scale_y: f32,
303
}
304

            
305
impl FlipTransform {
306
    /// The no-op transform.
307
    pub const IDENTITY: Self = Self {
308
        translate_x: 0.0,
309
        translate_y: 0.0,
310
        scale_x: 1.0,
311
        scale_y: 1.0,
312
    };
313

            
314
    /// Whether this is close enough to identity.
315
    #[must_use]
316
109
    pub fn is_identity(&self) -> bool {
317
109
        self.translate_x.abs() < 0.01
318
90
            && self.translate_y.abs() < 0.01
319
82
            && (self.scale_x - 1.0).abs() < 0.001
320
82
            && (self.scale_y - 1.0).abs() < 0.001
321
109
    }
322
}
323

            
324
/// Compute the FLIP transform to move from the `first` rect to the `last` rect.
325
///
326
/// If the `last` rect has a zero size, the scale falls back to 1.
327
/// The function only calculates changes in position, avoiding content distortion.
328
#[must_use]
329
114
pub fn flip(first: LogicalRect, last: LogicalRect) -> FlipTransform {
330
114
    let _ = (first.size, last.size); // sizes are layout's job, not the animation's
331
114
    FlipTransform {
332
114
        translate_x: first.origin.x - last.origin.x,
333
114
        translate_y: first.origin.y - last.origin.y,
334
114
        scale_x: 1.0,
335
114
        scale_y: 1.0,
336
114
    }
337
114
}
338

            
339
/// Which presence class an animation belongs to.
340
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341
pub enum AnimClass {
342
    /// Node exists in the new DOM only.
343
    Enter,
344
    /// Node existed in the old DOM only. Needs exit-retention to be visible.
345
    Exit,
346
    /// Node exists in both, at different geometry.
347
    Move,
348
}
349

            
350
/// Identity of an animation across frames.
351
///
352
/// Uses the reconciliation key (`.with_key()` / `#id` / structural hash)
353
/// to remain stable across frames, unlike `NodeId`.
354
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
355
#[repr(C)]
356
pub struct AnimKey(pub u64);
357

            
358
/// One in-flight animation: the FLIP channels plus opacity.
359
#[derive(Debug, Clone, Copy, PartialEq)]
360
pub struct ActiveAnim {
361
    /// What kind of presence change started this.
362
    pub class: AnimClass,
363
    /// Horizontal offset channel.
364
    pub translate_x: AnimChannel,
365
    /// Vertical offset channel.
366
    pub translate_y: AnimChannel,
367
    /// Horizontal scale channel.
368
    pub scale_x: AnimChannel,
369
    /// Vertical scale channel.
370
    pub scale_y: AnimChannel,
371
    /// Opacity channel.
372
    pub opacity: AnimChannel,
373
}
374

            
375
impl ActiveAnim {
376
    /// A move: start at the FLIP inversion, animate to identity.
377
    #[must_use]
378
33
    pub const fn move_from_flip(flip: FlipTransform, mode: InterpolationMode) -> Self {
379
33
        Self {
380
33
            class: AnimClass::Move,
381
33
            translate_x: channel(flip.translate_x, 0.0, mode),
382
33
            translate_y: channel(flip.translate_y, 0.0, mode),
383
33
            scale_x: channel(flip.scale_x, 1.0, mode),
384
33
            scale_y: channel(flip.scale_y, 1.0, mode),
385
33
            opacity: channel(1.0, 1.0, mode),
386
33
        }
387
33
    }
388

            
389
    /// An enter: slide in from `(from_x, from_y)` to identity, full opacity and size.
390
    #[must_use]
391
13
    pub const fn enter_slide(from_x: f32, from_y: f32, mode: InterpolationMode) -> Self {
392
13
        Self {
393
13
            class: AnimClass::Enter,
394
13
            translate_x: channel(from_x, 0.0, mode),
395
13
            translate_y: channel(from_y, 0.0, mode),
396
13
            scale_x: channel(1.0, 1.0, mode),
397
13
            scale_y: channel(1.0, 1.0, mode),
398
13
            opacity: channel(1.0, 1.0, mode),
399
13
        }
400
13
    }
401

            
402
    /// An exit: slide out from identity to `(to_x, to_y)`, full opacity and size.
403
    /// Only visible with exit-retention.
404
    ///
405
    /// Reversing a presence animation in flight will retarget from the current
406
    /// values with velocity preserved.
407
13
    pub fn retarget_presence(&mut self, class: AnimClass, to_x: f32, to_y: f32) {
408
13
        self.class = class;
409
13
        self.translate_x.retarget(to_x);
410
13
        self.translate_y.retarget(to_y);
411
13
        self.scale_x.retarget(1.0);
412
13
        self.scale_y.retarget(1.0);
413
13
        self.opacity.retarget(1.0);
414
13
    }
415

            
416
    #[must_use]
417
25
    pub const fn exit_slide(to_x: f32, to_y: f32, mode: InterpolationMode) -> Self {
418
25
        Self {
419
25
            class: AnimClass::Exit,
420
25
            translate_x: channel(0.0, to_x, mode),
421
25
            translate_y: channel(0.0, to_y, mode),
422
25
            scale_x: channel(1.0, 1.0, mode),
423
25
            scale_y: channel(1.0, 1.0, mode),
424
25
            opacity: channel(1.0, 1.0, mode),
425
25
        }
426
25
    }
427

            
428
    /// Advance every channel by `dt` seconds.
429
3121
    pub fn tick(&mut self, dt: f32) {
430
3121
        self.translate_x.tick(dt);
431
3121
        self.translate_y.tick(dt);
432
3121
        self.scale_x.tick(dt);
433
3121
        self.scale_y.tick(dt);
434
3121
        self.opacity.tick(dt);
435
3121
    }
436

            
437
    /// True once every channel has arrived.
438
    #[must_use]
439
3154
    pub const fn is_finished(&self) -> bool {
440
3154
        self.translate_x.is_finished()
441
39
            && self.translate_y.is_finished()
442
33
            && self.scale_x.is_finished()
443
33
            && self.scale_y.is_finished()
444
33
            && self.opacity.is_finished()
445
3154
    }
446

            
447
    /// The transform to write this frame.
448
    #[must_use]
449
713
    pub const fn current_transform(&self) -> FlipTransform {
450
713
        FlipTransform {
451
713
            translate_x: self.translate_x.current,
452
713
            translate_y: self.translate_y.current,
453
713
            scale_x: self.scale_x.current,
454
713
            scale_y: self.scale_y.current,
455
713
        }
456
713
    }
457

            
458
    /// The opacity to write this frame.
459
    #[must_use]
460
700
    pub const fn current_opacity(&self) -> f32 {
461
700
        self.opacity.current
462
700
    }
463

            
464
    /// Re-aim at a new FLIP target, preserving position and velocity.
465
9
    pub fn retarget_move(&mut self, flip: FlipTransform) {
466
        // Seed toward identity from the current position.
467
9
        self.translate_x.retarget(0.0);
468
9
        self.translate_y.retarget(0.0);
469
9
        self.scale_x.retarget(1.0);
470
9
        self.scale_y.retarget(1.0);
471
        // Fold the freshly measured offset in, rather than snapping to it.
472
9
        self.translate_x.current += flip.translate_x;
473
9
        self.translate_y.current += flip.translate_y;
474
9
    }
475
}
476

            
477
355
const fn channel(from: f32, to: f32, mode: InterpolationMode) -> AnimChannel {
478
355
    match mode {
479
        InterpolationMode::Curve {
480
125
            function,
481
125
            duration_secs,
482
125
        } => AnimChannel::curve(from, to, function, duration_secs),
483
230
        InterpolationMode::Spring(spring) => AnimChannel::spring(from, to, spring),
484
    }
485
355
}
486

            
487
/// The keyed store of in-flight animations.
488
///
489
/// Holds only what must outlive a frame.
490
#[derive(Debug, Clone, Default)]
491
pub struct AnimationManager {
492
    active: BTreeMap<AnimKey, ActiveAnim>,
493
}
494

            
495
impl AnimationManager {
496
    /// An empty manager.
497
    #[must_use]
498
29079
    pub const fn new() -> Self {
499
29079
        Self {
500
29079
            active: BTreeMap::new(),
501
29079
        }
502
29079
    }
503

            
504
    /// How many animations are in flight.
505
    #[must_use]
506
87
    pub fn len(&self) -> usize {
507
87
        self.active.len()
508
87
    }
509

            
510
    /// Whether anything is animating (i.e. whether a frame needs scheduling).
511
    #[must_use]
512
4459
    pub fn is_empty(&self) -> bool {
513
4459
        self.active.is_empty()
514
4459
    }
515

            
516
    /// Start a move, or retarget one already in flight under this key.
517
42
    pub fn start_or_retarget_move(
518
42
        &mut self,
519
42
        key: AnimKey,
520
42
        flip: FlipTransform,
521
42
        mode: InterpolationMode,
522
42
    ) {
523
42
        if let Some(existing) = self.active.get_mut(&key) {
524
9
            existing.retarget_move(flip);
525
33
        } else {
526
33
            self.active
527
33
                .insert(key, ActiveAnim::move_from_flip(flip, mode));
528
33
        }
529
42
    }
530

            
531
    /// Start an enter animation, unless this key is already animating.
532
14
    pub fn start_enter(&mut self, key: AnimKey, from: (f32, f32), mode: InterpolationMode) {
533
14
        self.active
534
14
            .entry(key)
535
14
            .or_insert_with(|| ActiveAnim::enter_slide(from.0, from.1, mode));
536
14
    }
537

            
538
    /// Start an exit animation.
539
    ///
540
    /// If an animation is already in flight, the channels retarget from their
541
    /// current value with velocity preserved.
542
38
    pub fn start_exit(&mut self, key: AnimKey, to: (f32, f32), mode: InterpolationMode) {
543
38
        match self.active.get_mut(&key) {
544
13
            Some(anim) => anim.retarget_presence(AnimClass::Exit, to.0, to.1),
545
25
            None => {
546
25
                self.active
547
25
                    .insert(key, ActiveAnim::exit_slide(to.0, to.1, mode));
548
25
            }
549
        }
550
38
    }
551

            
552
    /// Mutable access to an in-flight animation.
553
24
    pub fn get_mut(&mut self, key: AnimKey) -> Option<&mut ActiveAnim> {
554
24
        self.active.get_mut(&key)
555
24
    }
556

            
557
    /// Read the current state for a key.
558
    #[must_use]
559
534
    pub fn get(&self, key: AnimKey) -> Option<&ActiveAnim> {
560
534
        self.active.get(&key)
561
534
    }
562

            
563
    /// Every in-flight animation with its key.
564
1866
    pub fn iter(&self) -> impl Iterator<Item = (AnimKey, &ActiveAnim)> {
565
1866
        self.active.iter().map(|(k, v)| (*k, v))
566
1866
    }
567

            
568
    /// Advance every animation and drop the ones that arrived.
569
    ///
570
    /// Returns the keys that finished this tick.
571
6791
    pub fn tick(&mut self, dt: f32) -> Vec<AnimKey> {
572
6791
        let mut finished = Vec::new();
573
9912
        for (key, anim) in &mut self.active {
574
3121
            anim.tick(dt);
575
3121
            if anim.is_finished() {
576
33
                finished.push(*key);
577
3088
            }
578
        }
579
6824
        for key in &finished {
580
33
            self.active.remove(key);
581
33
        }
582
6791
        finished
583
6791
    }
584

            
585
    /// Drop an animation without letting it finish.
586
    pub fn cancel(&mut self, key: AnimKey) -> Option<ActiveAnim> {
587
        self.active.remove(&key)
588
    }
589
}
590

            
591
/// Turn the diff's correspondence map into `(key, First, Last)` triples.
592
///
593
/// Pairs missing either rect are dropped.
594
27
pub fn correspondences_from_moves<F, L>(
595
27
    node_moves: &[NodeMove],
596
27
    new_node_data: &[NodeData],
597
27
    new_hierarchy: &[NodeHierarchyItem],
598
27
    first_rect: F,
599
27
    last_rect: L,
600
27
) -> Vec<(AnimKey, LogicalRect, LogicalRect)>
601
27
where
602
27
    F: Fn(NodeId) -> Option<LogicalRect>,
603
27
    L: Fn(NodeId) -> Option<LogicalRect>,
604
{
605
27
    let mut out = Vec::new();
606
247
    for m in node_moves {
607
220
        let (Some(first), Some(last)) = (first_rect(m.old_node_id), last_rect(m.new_node_id))
608
        else {
609
116
            continue;
610
        };
611
104
        if m.new_node_id.index() >= new_node_data.len() {
612
            continue; // stale correspondence; the new tree does not have this node
613
104
        }
614
104
        let key = AnimKey(calculate_reconciliation_key(
615
104
            new_node_data,
616
104
            new_hierarchy,
617
104
            m.new_node_id,
618
104
        ));
619
104
        out.push((key, first, last));
620
    }
621
27
    out
622
27
}
623

            
624
/// The `AnimKey` -> current `NodeId` mapping for this frame's correspondences.
625
///
626
/// Bridges the reconciliation identity and per-frame `NodeId`.
627
#[must_use]
628
92
pub fn anim_keys_for_moves(
629
92
    node_moves: &[NodeMove],
630
92
    new_node_data: &[NodeData],
631
92
    new_hierarchy: &[NodeHierarchyItem],
632
92
) -> Vec<(AnimKey, NodeId)> {
633
92
    node_moves
634
92
        .iter()
635
218
        .filter(|m| m.new_node_id.index() < new_node_data.len())
636
218
        .map(|m| {
637
218
            (
638
218
                AnimKey(calculate_reconciliation_key(
639
218
                    new_node_data,
640
218
                    new_hierarchy,
641
218
                    m.new_node_id,
642
218
                )),
643
218
                m.new_node_id,
644
218
            )
645
218
        })
646
92
        .collect()
647
92
}
648

            
649
/// Seed (or retarget) a FLIP move for every correspondence whose geometry moved.
650
///
651
/// Returns how many animations were started or retargeted.
652
29
pub fn seed_moves<I>(
653
29
    manager: &mut AnimationManager,
654
29
    correspondences: I,
655
29
    mode: InterpolationMode,
656
29
) -> usize
657
29
where
658
29
    I: IntoIterator<Item = (AnimKey, LogicalRect, LogicalRect)>,
659
{
660
29
    let mut seeded = 0;
661
136
    for (key, first, last) in correspondences {
662
107
        let transform = flip(first, last);
663
107
        if transform.is_identity() {
664
80
            continue;
665
27
        }
666
27
        manager.start_or_retarget_move(key, transform, mode);
667
27
        seeded += 1;
668
    }
669
29
    seeded
670
29
}
671

            
672
#[cfg(test)]
673
#[path = "animation_test.rs"]
674
mod animation_test;