motion-core 0.1.0

Backend-independent motion engine primitives
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! Bounded path morphing with exact cubic source geometry.

use kurbo::ParamCurveArea;
use std::sync::Arc;

use crate::{Interpolate, MAX_PATH_VERBS, Path2D, PathVerb, Point, Rect, Shape, ValidationError};

const MAX_CONTOURS: usize = 64;

const DEFAULT_SAMPLES: usize = 32;

const MAX_SAMPLES: usize = 256;

const MAX_ALIGNMENT_WORK: usize = 16_777_216;

/// A checked path value for geometry interpolation and fill/stroke.
/// Original path snapshots are retained at exact animation endpoints.
///
/// ```
/// use motion_core::prelude::*;
/// use motion_core::{
///     DisplayList, RasterLimits, ResourcePool, ValidatedDisplayList, MAX_PATH_VERBS,
///     MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
/// };
/// let (from, to) = MorphPath::pair(
///     Circle::new(Point::new(8.0, 8.0), 6.0).path(),
///     Star::new(Point::new(8.0, 8.0), 5, 6.0, 2.5).path(),
/// )?;
/// let animation = Tween::new(from, to, 1.seconds());
/// let middle = animation.sample(500.milliseconds());
/// assert!(middle.bounding_box().is_finite());
/// # Ok::<(), motion_core::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct MorphPath {
    path: Path2D,
    contours: Arc<[Contour]>,
    pair: Option<(Arc<Pair>, bool)>,
}

#[derive(Clone, Debug)]
struct Pair {
    contours: Vec<MatchedContour>,
}

#[derive(Clone, Debug)]
struct MatchedContour {
    source: Vec<[Point; 4]>,
    target: Vec<[Point; 4]>,
    closed: bool,
}

#[derive(Clone, Copy, Debug)]
struct Measure {
    area: f64,
    rank: f64,
    length: f64,
}

#[derive(Clone, Debug)]
struct Contour {
    path: Path2D,
    closed: bool,
}

fn invalid(field: &str, message: &str) -> ValidationError {
    ValidationError::invalid("morph_path", field, message)
}

fn limit(message: &str) -> ValidationError {
    ValidationError::limit("morph_path", "geometry", message)
}

fn finish(
    contours: &mut Vec<Contour>,
    current: &mut Option<Path2D>,
    closed: bool,
) -> Result<(), ValidationError> {
    if let Some(path) = current.take() {
        if contours.len() >= MAX_CONTOURS {
            return Err(limit("Morph paths admit at most 64 contours"));
        }
        contours.push(Contour { path, closed });
    }
    Ok(())
}

impl MorphPath {
    /// Captures a path and promotes line/quadratic segments to cubic controls.
    /// At most 64 contours are accepted; all existing path limits still apply.
    pub fn new(path: Path2D) -> Result<Self, ValidationError> {
        path.validate()?;
        let mut contours = Vec::new();
        let mut current = None;
        let mut position = Point::ORIGIN;
        let mut start = position;
        for verb in path.verbs() {
            if let PathVerb::MoveTo(value) = *verb {
                finish(&mut contours, &mut current, false)?;
                let mut contour = Path2D::new();
                contour.try_move_to(value)?;
                current = Some(contour);
                position = value;
                start = value;
                continue;
            }
            if matches!(verb, PathVerb::Close) && current.is_none() {
                continue;
            }
            if current.is_none() {
                let mut contour = Path2D::new();
                contour.try_move_to(position)?;
                start = position;
                current = Some(contour);
            }
            let contour = current.as_mut().expect("active morph contour");
            match *verb {
                PathVerb::LineTo(end) => {
                    contour.try_cubic_to(
                        position.interpolate(&end, 1.0 / 3.0),
                        position.interpolate(&end, 2.0 / 3.0),
                        end,
                    )?;
                    position = end;
                }
                PathVerb::QuadraticTo(control, end) => {
                    let cubic = kurbo::QuadBez::new(
                        (position.x, position.y),
                        (control.x, control.y),
                        (end.x, end.y),
                    )
                    .raise();
                    contour.try_cubic_to(
                        Point::new(cubic.p1.x, cubic.p1.y),
                        Point::new(cubic.p2.x, cubic.p2.y),
                        end,
                    )?;
                    position = end;
                }
                PathVerb::CubicTo(first, second, end) => {
                    contour.try_cubic_to(first, second, end)?;
                    position = end;
                }
                PathVerb::Close => {
                    if position != start {
                        contour.try_cubic_to(
                            position.interpolate(&start, 1.0 / 3.0),
                            position.interpolate(&start, 2.0 / 3.0),
                            start,
                        )?;
                    }
                    contour.try_close()?;
                    position = start;
                    finish(&mut contours, &mut current, true)?;
                }
                PathVerb::MoveTo(_) => unreachable!("move handled above"),
            }
        }
        finish(&mut contours, &mut current, false)?;
        Ok(Self {
            path,
            contours: contours.into(),
            pair: None,
        })
    }

    /// Prepares a pair once for repeated Tween sampling, using 32 uniform
    /// arc-length landmarks plus both paths' existing curve boundaries.
    pub fn pair(source: Path2D, target: Path2D) -> Result<(Self, Self), ValidationError> {
        Self::pair_with_samples(source, target, DEFAULT_SAMPLES)
    }

    /// Prepares 4..=256 arc-length landmarks per contour. Output remains capped
    /// by MAX_PATH_VERBS, with at most 64 matched contours and bounded alignment.
    pub fn pair_with_samples(
        source: Path2D,
        target: Path2D,
        samples: usize,
    ) -> Result<(Self, Self), ValidationError> {
        if !(4..=MAX_SAMPLES).contains(&samples) {
            return Err(invalid("samples", "Morph sample count must be in 4..=256"));
        }
        let mut source = Self::new(source)?;
        let mut target = Self::new(target)?;
        let pair = Arc::new(Pair::new(&source, &target, samples)?);
        source.pair = Some((pair.clone(), false));
        target.pair = Some((pair, true));
        Ok((source, target))
    }

    /// Checked, stateless interpolation. Finite overshoot is allowed; exact
    /// progress 0/1 returns the original verb snapshots. Unprepared values
    /// compute correspondence on demand; prefer pair for repeated sampling.
    pub fn try_interpolate(&self, target: &Self, progress: f64) -> Result<Self, ValidationError> {
        if !progress.is_finite() {
            return Err(invalid("progress", "Morph progress must be finite"));
        }
        if progress == 0.0 {
            return Ok(self.clone());
        }
        if progress == 1.0 {
            return Ok(target.clone());
        }
        if self.path == target.path {
            return Ok(self.clone());
        }
        let prepared;
        let (pair, reversed) = match (&self.pair, &target.pair) {
            (Some((first, side)), Some((second, target_side)))
                if Arc::ptr_eq(first, second) && side != target_side =>
            {
                (first.as_ref(), *side)
            }
            _ => {
                prepared = Pair::new(self, target, DEFAULT_SAMPLES)?;
                (&prepared, false)
            }
        };
        let mut path = Path2D::new();
        for contour in &pair.contours {
            let (source, target) = if reversed {
                (&contour.target, &contour.source)
            } else {
                (&contour.source, &contour.target)
            };
            for (index, (first, second)) in source.iter().zip(target).enumerate() {
                let points: [Point; 4] = std::array::from_fn(|control| {
                    if first[control] == second[control] {
                        first[control]
                    } else {
                        first[control].interpolate(&second[control], progress)
                    }
                });
                if index == 0 {
                    path.try_move_to(points[0])?;
                }
                path.try_cubic_to(points[1], points[2], points[3])?;
            }
            if contour.closed {
                path.try_close()?;
            }
        }
        Self::new(path)
    }
}

impl PartialEq for MorphPath {
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path
    }
}

impl Interpolate for MorphPath {
    fn interpolate(&self, target: &Self, progress: f64) -> Self {
        self.try_interpolate(target, progress)
            .expect("MorphPath interpolation failed")
    }
}

fn cubics(path: &Path2D) -> Vec<[Point; 4]> {
    let mut position = Point::ORIGIN;
    let mut result = Vec::new();
    for verb in path.verbs() {
        match *verb {
            PathVerb::MoveTo(value) => position = value,
            PathVerb::CubicTo(first, second, end) => {
                result.push([position, first, second, end]);
                position = end;
            }
            _ => {}
        }
    }
    result
}

fn measure(contour: &Contour) -> Result<Measure, ValidationError> {
    let length = contour.path.try_length()?;
    let bounds = contour.path.bounding_box();
    let scale = bounds.width().max(bounds.height());
    if !contour.closed || scale == 0.0 {
        return Ok(Measure {
            area: 0.0,
            rank: f64::NEG_INFINITY,
            length,
        });
    }
    let center = bounds.center();
    let mut area = 0.0;
    for curve in cubics(&contour.path) {
        let controls = curve.map(|point| (point - center) / scale);
        let controls = controls.map(|point| kurbo::Point::new(point.x, point.y));
        area +=
            kurbo::CubicBez::new(controls[0], controls[1], controls[2], controls[3]).signed_area();
    }
    if !area.is_finite() {
        return Err(invalid("area", "Morph contour area must remain finite"));
    }
    let rank = if area == 0.0 {
        f64::NEG_INFINITY
    } else {
        libm::log(area.abs()) + 2.0 * libm::log(scale)
    };
    Ok(Measure { area, rank, length })
}

fn reverse(contour: &Contour) -> Result<Path2D, ValidationError> {
    let curves = cubics(&contour.path);
    let mut path = Path2D::new();
    let first = curves
        .last()
        .map(|curve| curve[3])
        .unwrap_or(contour.path.try_point_at(0.0)?.0);
    path.try_move_to(first)?;
    for curve in curves.iter().rev() {
        path.try_cubic_to(curve[2], curve[1], curve[0])?;
    }
    if contour.closed {
        path.try_close()?;
    }
    Ok(path)
}

fn rotate(path: &Path2D, phase: f64) -> Result<Path2D, ValidationError> {
    if phase == 0.0 {
        return Ok(path.clone());
    }
    let mut output = Path2D::new();
    for (index, piece) in [path.try_trim(phase, 1.0)?, path.try_trim(0.0, phase)?]
        .iter()
        .enumerate()
    {
        for verb in piece.verbs() {
            match *verb {
                PathVerb::MoveTo(value) if index == 0 => output.try_move_to(value)?,
                PathVerb::CubicTo(first, second, end) => output.try_cubic_to(first, second, end)?,
                PathVerb::MoveTo(_) | PathVerb::Close => {}
                _ => {
                    return Err(invalid(
                        "curve",
                        "Morph normalization requires cubic contours",
                    ));
                }
            }
        }
    }
    output.try_close()?;
    Ok(output)
}

fn phase(
    source: &Path2D,
    target: &Path2D,
    samples: usize,
    work: &mut usize,
) -> Result<f64, ValidationError> {
    *work += samples * samples;
    if *work > MAX_ALIGNMENT_WORK {
        return Err(limit("Morph alignment work allowance exhausted"));
    }
    let first = (0..samples)
        .map(|index| {
            source
                .try_point_at(index as f64 / samples as f64)
                .map(|value| value.0)
        })
        .collect::<Result<Vec<_>, _>>()?;
    let second = (0..samples)
        .map(|index| {
            target
                .try_point_at(index as f64 / samples as f64)
                .map(|value| value.0)
        })
        .collect::<Result<Vec<_>, _>>()?;
    let bounds = source.bounding_box().union(target.bounding_box());
    let scale = bounds.width().max(bounds.height());
    if !scale.is_finite() {
        return Err(invalid(
            "bounds",
            "Combined morph extent must remain finite",
        ));
    }
    if scale == 0.0 {
        return Ok(0.0);
    }
    let mut best = (f64::INFINITY, 0);
    for shift in 0..samples {
        let mut cost = 0.0;
        for index in 0..samples {
            let delta = (first[index] - second[(index + shift) % samples]) / scale;
            cost += delta.dot(delta);
        }
        if cost < best.0 {
            best = (cost, shift);
        }
    }
    Ok(best.1 as f64 / samples as f64)
}

impl Pair {
    fn new(
        source: &MorphPath,
        target: &MorphPath,
        samples: usize,
    ) -> Result<Self, ValidationError> {
        let mut minimum_verbs = 0;
        let mut count = 0;
        for closed in [true, false] {
            let matched = source
                .contours
                .iter()
                .filter(|contour| contour.closed == closed)
                .count()
                .max(
                    target
                        .contours
                        .iter()
                        .filter(|contour| contour.closed == closed)
                        .count(),
                );
            minimum_verbs += matched * (samples + 1 + usize::from(closed));
            count += matched;
        }
        if count > MAX_CONTOURS || minimum_verbs > MAX_PATH_VERBS {
            return Err(limit(
                "Requested morph topology exceeds the contour or verb allowance",
            ));
        }
        let source_measures = source
            .contours
            .iter()
            .map(measure)
            .collect::<Result<Vec<_>, _>>()?;
        let target_measures = target
            .contours
            .iter()
            .map(measure)
            .collect::<Result<Vec<_>, _>>()?;
        let largest = |measures: &[Measure]| {
            measures
                .iter()
                .max_by(|first, second| first.rank.total_cmp(&second.rank))
                .map_or(0.0, |value| value.area)
        };
        let source_area = largest(&source_measures);
        let target_area = largest(&target_measures);
        let reverse_target = source_area != 0.0
            && target_area != 0.0
            && source_area.is_sign_positive() != target_area.is_sign_positive();
        let mut contours = Vec::new();
        let mut work = 0;
        let mut verbs = 0;
        for closed in [true, false] {
            let sorted = |path: &MorphPath, measures: &[Measure]| {
                let mut indices = path
                    .contours
                    .iter()
                    .enumerate()
                    .filter(|(_, contour)| contour.closed == closed)
                    .map(|(index, _)| index)
                    .collect::<Vec<_>>();
                indices.sort_by(|first, second| {
                    measures[*second]
                        .rank
                        .total_cmp(&measures[*first].rank)
                        .then_with(|| measures[*second].length.total_cmp(&measures[*first].length))
                        .then_with(|| first.cmp(second))
                });
                indices
            };
            let source_indices = sorted(source, &source_measures);
            let target_indices = sorted(target, &target_measures);
            for index in 0..source_indices.len().max(target_indices.len()) {
                if contours.len() >= MAX_CONTOURS {
                    return Err(limit("Matched topology exceeds 64 contours"));
                }
                let first = source_indices
                    .get(index)
                    .map(|index| &source.contours[*index]);
                let second = target_indices
                    .get(index)
                    .map(|index| &target.contours[*index]);
                let collapse =
                    |owner: &MorphPath, fallback: &MorphPath| -> Result<Path2D, ValidationError> {
                        let mut path = Path2D::new();
                        let bounds = if owner.path.verbs().is_empty() {
                            fallback.path.bounding_box()
                        } else {
                            owner.path.bounding_box()
                        };
                        path.try_move_to(bounds.center())?;
                        Ok(path)
                    };
                let first_path = match first {
                    Some(contour) => contour.path.clone(),
                    None => collapse(source, target)?,
                };
                let mut second_path = match second {
                    Some(contour) if reverse_target => reverse(contour)?,
                    Some(contour) => contour.path.clone(),
                    None => collapse(target, source)?,
                };
                if closed {
                    second_path = rotate(
                        &second_path,
                        phase(&first_path, &second_path, samples, &mut work)?,
                    )?;
                }
                let mut knots = first_path.cubic_breakpoints()?;
                knots.extend(second_path.cubic_breakpoints()?);
                knots.extend((0..=samples).map(|index| index as f64 / samples as f64));
                knots.sort_by(f64::total_cmp);
                knots.dedup_by(|first, second| (*first - *second).abs() <= 1e-12);
                if let Some(last) = knots.last_mut() {
                    *last = 1.0;
                }
                verbs += knots.len() + usize::from(closed);
                if verbs > MAX_PATH_VERBS {
                    return Err(limit("Resampled morph exceeds the verb allowance"));
                }
                let mut first_segments = first_path.cubic_intervals(&knots)?;
                let mut second_segments = second_path.cubic_intervals(&knots)?;
                for segments in [&mut first_segments, &mut second_segments] {
                    for segment in 1..segments.len() {
                        segments[segment][0] = segments[segment - 1][3];
                    }
                    if closed {
                        let first = segments[0][0];
                        segments.last_mut().unwrap()[3] = first;
                    }
                }
                contours.push(MatchedContour {
                    source: first_segments,
                    target: second_segments,
                    closed,
                });
            }
        }
        Ok(Self { contours })
    }
}

impl Shape for MorphPath {
    fn path(&self) -> Path2D {
        self.path.clone()
    }

    fn bounding_box(&self) -> Rect {
        self.path.bounding_box()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ValidationErrorKind;

    #[test]
    fn exact_endpoints_and_nonuniform_curve_segmentation_preserve_geometry() {
        let source = Path2D::parse_svg("M0 0Q4 8 8 0").unwrap();
        let target = Path2D::parse_svg("M0 0Q2 4 4 4Q6 4 8 0").unwrap();
        let (first, second) = MorphPath::pair(source.clone(), target.clone()).unwrap();
        assert_eq!(first.interpolate(&second, 0.0).path(), source);
        assert_eq!(first.interpolate(&second, 1.0).path(), target);
        for progress in [0.01, 0.25, 0.5, 0.99] {
            let result = first.try_interpolate(&second, progress).unwrap();
            assert!((result.path().length() - source.length()).abs() < 1e-8);
            for sample in [0.0, 0.25, 0.5, 0.75, 1.0] {
                assert!(
                    result
                        .path()
                        .point_at(sample)
                        .0
                        .distance(source.point_at(sample).0)
                        < 1e-8
                );
            }
        }
        let line = Path2D::parse_svg("M0 0H8").unwrap();
        let curve = Path2D::parse_svg("M0 4Q4 12 8 4").unwrap();
        let (first, second) = MorphPath::pair(line, curve).unwrap();
        let middle = first.interpolate(&second, 0.5).path();
        assert!(middle.point_at(0.5).0.distance(Point::new(4.0, 4.0)) < 1e-8);
        assert_eq!(middle.point_at(0.0).0, Point::new(0.0, 2.0));
        assert_eq!(middle.point_at(1.0).0, Point::new(8.0, 2.0));
    }

    #[test]
    fn closed_phase_alignment_and_area_pairing_are_not_input_order_zip() {
        let source = Path2D::parse_svg("M2 2H10V10H2Z").unwrap();
        let target = Path2D::parse_svg("M10 10H2V2H10Z").unwrap();
        let (first, second) = MorphPath::pair(source, target).unwrap();
        let middle = first.interpolate(&second, 0.5);
        assert_eq!(middle.bounding_box(), Rect::new(2.0, 2.0, 10.0, 10.0));
        let source = Path2D::parse_svg("M99 -1h2v2h-2Z M-3 -3h6v6h-6Z").unwrap();
        let target = Path2D::parse_svg("M16 -4h8v8h-8Z M199 -1h2v2h-2Z").unwrap();
        let (first, second) = MorphPath::pair(source, target).unwrap();
        let middle = first.interpolate(&second, 0.5);
        assert!((middle.contours[0].path.bounding_box().center().x - 10.0).abs() < 1e-8);
        assert!((middle.contours[1].path.bounding_box().center().x - 150.0).abs() < 1e-8);
    }

    #[test]
    fn missing_contours_and_holes_grow_from_points_with_winding_preserved() {
        let source = Path2D::from_rect(Rect::new(0.0, 0.0, 16.0, 16.0)).unwrap();
        let target = Path2D::parse_svg("M0 0H16V16H0Z M6 6V10H10V6Z").unwrap();
        let (first, second) = MorphPath::pair(source, target).unwrap();
        let middle = first.interpolate(&second, 0.5);
        assert_eq!(middle.contours.len(), 2);
        assert_eq!(
            middle.contours[1].path.bounding_box(),
            Rect::new(7.0, 7.0, 9.0, 9.0)
        );
        let (empty, filled) = MorphPath::pair(
            Path2D::new(),
            crate::Circle::new(Point::new(8.0, 8.0), 4.0).path(),
        )
        .unwrap();
        assert!(empty.path().verbs().is_empty());
        assert!((empty.interpolate(&filled, 0.5).bounding_box().width() - 4.0).abs() < 1e-8);
        assert!(filled.interpolate(&empty, 1.0).path().verbs().is_empty());
    }

    #[test]
    fn disappearing_and_offset_holes_follow_the_path_coordinate_frame() {
        let source = Path2D::parse_svg("M0 0H16V16H0Z M6 6V10H10V6Z").unwrap();
        let target = Path2D::parse_svg("M16 0H32V16H16Z").unwrap();
        let (first, second) = MorphPath::pair(source, target).unwrap();
        let middle = first.interpolate(&second, 0.5);
        let outer = middle.contours[0].path.bounding_box();
        let hole = middle.contours[1].path.bounding_box();
        assert_eq!(hole.center(), Point::new(16.0, 8.0));
        assert!(
            hole.left >= outer.left
                && hole.right <= outer.right
                && hole.top >= outer.top
                && hole.bottom <= outer.bottom
        );
        let target = Path2D::parse_svg("M0 0H16V16H0Z M2 2V4H4V2Z").unwrap();
        let (first, second) = MorphPath::pair(Path2D::new(), target).unwrap();
        let middle = first.interpolate(&second, 0.5);
        let outer = middle.contours[0].path.bounding_box();
        let hole = middle.contours[1].path.bounding_box();
        assert!(
            hole.left >= outer.left
                && hole.right <= outer.right
                && hole.top >= outer.top
                && hole.bottom <= outer.bottom
        );
    }

    #[test]
    fn prepared_morphs_support_tweens_reverse_queries_and_checked_failures() {
        use crate::{Animation, Time, Tween};
        let source = Path2D::parse_svg("M1 1H5V5H1Z").unwrap();
        let target = Path2D::parse_svg("M3 3H9V9H3Z").unwrap();
        let (first, second) = MorphPath::pair(source.clone(), target.clone()).unwrap();
        let animation = Tween::new(first.clone(), second.clone(), Time::from_ticks(100));
        let expected = animation.sample(Time::from_ticks(50));
        assert_eq!(
            MorphPath::new(source.clone())
                .unwrap()
                .try_interpolate(&MorphPath::new(target.clone()).unwrap(), 0.5)
                .unwrap(),
            expected
        );
        std::thread::scope(|scope| {
            let handles = (0..3)
                .map(|_| scope.spawn(|| first.interpolate(&second, 0.5)))
                .collect::<Vec<_>>();
            for handle in handles {
                assert_eq!(handle.join().unwrap(), expected);
            }
        });
        for ticks in [100, 25, 0, 75, 50] {
            let _result = animation.sample(Time::from_ticks(ticks));
        }
        assert_eq!(animation.sample(Time::from_ticks(50)), expected);
        assert_eq!(
            first.interpolate(&second, 0.25),
            second.interpolate(&first, 0.75)
        );
        assert!(first.try_interpolate(&second, f64::NAN).is_err());
        assert!(first.try_interpolate(&second, f64::MAX).is_err());
        let (stationary, growing) = MorphPath::pair(
            Path2D::parse_svg("M1 0H2").unwrap(),
            Path2D::parse_svg("M1 0H3").unwrap(),
        )
        .unwrap();
        assert_eq!(
            stationary
                .try_interpolate(&growing, 1e16)
                .unwrap()
                .path()
                .verbs()[0],
            PathVerb::MoveTo(Point::new(1.0, 0.0))
        );
        assert_eq!(first.path(), source);
        assert_eq!(second.path(), target);
        assert!(MorphPath::pair_with_samples(source, target, 257).is_err());
        let mut many = Path2D::new();
        for index in 0..65 {
            many.try_move_to(Point::new(index as f64, 0.0)).unwrap();
        }
        assert_eq!(
            MorphPath::new(many).unwrap_err().kind,
            ValidationErrorKind::StructuralLimit
        );
        let mut bounded = Path2D::new();
        for index in 0..64 {
            bounded.try_move_to(Point::new(index as f64, 0.0)).unwrap();
            bounded.try_close().unwrap();
        }
        assert_eq!(
            MorphPath::pair_with_samples(bounded.clone(), bounded, 256)
                .unwrap_err()
                .kind,
            ValidationErrorKind::StructuralLimit
        );
    }

    #[test]
    fn cubic_promotion_preserves_source_geometry_and_contour_boundaries() {
        let source = Path2D::parse_svg("M0 0L2 0Q3 2 4 0Z L1 1 M10 10").unwrap();
        let retained = source.clone();
        let morph = MorphPath::new(source).unwrap();
        assert_eq!(morph.path(), retained);
        assert_eq!(morph.contours.len(), 3);
        assert!(morph.contours[0].closed);
        assert!(!morph.contours[1].closed);
        assert!(
            morph
                .contours
                .iter()
                .all(|contour| contour.path.verbs().iter().all(|verb| matches!(
                    verb,
                    PathVerb::MoveTo(_) | PathVerb::CubicTo(..) | PathVerb::Close
                )))
        );
        let quadratic = Path2D::parse_svg("M0 0Q1 1 2 0").unwrap();
        let promoted = MorphPath::new(quadratic.clone()).unwrap();
        assert!((promoted.contours[0].path.length() - quadratic.length()).abs() < 1e-10);
        for progress in [0.0, 0.25, 0.5, 0.75, 1.0] {
            assert!(
                promoted.contours[0]
                    .path
                    .point_at(progress)
                    .0
                    .distance(quadratic.point_at(progress).0)
                    < 1e-9
            );
        }
        assert!(MorphPath::new(Path2D::new()).unwrap().contours.is_empty());
    }
}