lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! Continuous fill and stroke support in the actual CSS coordinate frame.
//! Bézier extrema are evaluated on the frozen paths. For potentially
//! cancelling contours, positive winding in every extreme quantum strip
//! is required before an outward-rounded tight bound is accepted.

use super::Precision;
use crate::{
    layout::{InkExtent, Rect},
    Result,
};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Point, Shape, Vec2};

#[derive(Clone, Copy)]
pub(super) enum FillRule {
    NonZero,
    EvenOdd,
}

impl FillRule {
    fn contains(self, path: &BezPath, point: Point) -> bool {
        let winding = path.winding(point);
        match self {
            Self::NonZero => winding != 0,
            Self::EvenOdd => winding % 2 != 0,
        }
    }
}

fn edges(rect: Rect) -> [f64; 4] {
    [
        rect.left(),
        rect.top(),
        rect.left() + rect.width(),
        rect.top() + rect.height(),
    ]
}

pub(super) fn corners(rect: Rect) -> [Point; 4] {
    let [left, top, right, bottom] = edges(rect);
    [
        Point::new(left, top),
        Point::new(right, top),
        Point::new(right, bottom),
        Point::new(left, bottom),
    ]
}

fn point_in(rect: Rect, point: Point, strict: bool) -> bool {
    let [left, top, right, bottom] = edges(rect);
    if strict {
        left < point.x && point.x < right && top < point.y && point.y < bottom
    } else {
        left <= point.x && point.x <= right && top <= point.y && point.y <= bottom
    }
}

#[derive(Default)]
struct Bounds(Option<kurbo::Rect>);
impl Bounds {
    fn point(&mut self, point: Point) {
        self.0 = Some(
            self.0
                .map_or(kurbo::Rect::from_points(point, point), |bounds| {
                    bounds.union_pt(point)
                }),
        );
    }

    fn rect(&mut self, rect: kurbo::Rect) {
        self.0 = Some(self.0.map_or(rect, |bounds| bounds.union(rect)));
    }

    fn extent(self) -> Result<InkExtent> {
        let Some(rect) = self
            .0
            .filter(|rect| rect.width() > 0. && rect.height() > 0.)
        else {
            return Ok(InkExtent::Empty);
        };
        Ok(InkExtent::Bounds(Rect::new(
            rect.x0,
            rect.y0,
            rect.width(),
            rect.height(),
        )?))
    }
}

pub(super) fn close_for_fill(path: &BezPath) -> BezPath {
    let mut closed = BezPath::new();
    for contour in path.subpaths() {
        // Fonts may include degenerate design points outside the visible
        // glyph, and a single-line contour has no fill. Do not let these
        // nonpainting contours participate in the candidate extrema.
        if contour_is_linear(contour) {
            continue;
        }
        for &element in contour {
            closed.push(element);
        }
        if contour.last() != Some(&PathEl::ClosePath) {
            closed.close_path();
        }
    }
    closed
}

fn contour_is_linear(contour: &[PathEl]) -> bool {
    use crate::numeric::binary::units;
    let mut points = contour
        .iter()
        .flat_map(|element| match *element {
            PathEl::MoveTo(point) | PathEl::LineTo(point) => [Some(point), None, None],
            PathEl::QuadTo(control, end) => [Some(control), Some(end), None],
            PathEl::CurveTo(first, second, end) => [Some(first), Some(second), Some(end)],
            PathEl::ClosePath => [None; 3],
        })
        .flatten();
    let Some(first) = points.next() else {
        return true;
    };
    let Some(second) = points.find(|point| *point != first) else {
        return true;
    };
    // Horizontal or vertical collinearity is exact; for other lines use
    // the exact binary64 operands if the floating determinant vanishes.
    points.all(|point| {
        if first.x.to_bits() == second.x.to_bits() {
            return first.x.to_bits() == point.x.to_bits();
        }
        if first.y.to_bits() == second.y.to_bits() {
            return first.y.to_bits() == point.y.to_bits();
        }
        if point == first || point == second {
            return true;
        }
        if (second - first).cross(point - first) != 0. {
            return false;
        }
        let determinant = || -> Result<bool> {
            let x = units(first.x)?;
            let y = units(first.y)?;
            Ok((units(second.x)? - &x) * (units(point.y)? - &y)
                == (units(second.y)? - &y) * (units(point.x)? - &x))
        };
        determinant().unwrap_or(false)
    })
}
pub(super) fn path_bounds(path: &BezPath) -> Result<Option<Rect>> {
    if !path.is_finite() {
        return Ok(None);
    }
    let bounds = path.bounding_box();
    Ok(Some(Rect::new(
        bounds.x0,
        bounds.y0,
        bounds.width(),
        bounds.height(),
    )?))
}

// Solve intersections with an axis-parallel line in the actual polynomial
// coordinate, avoiding flattened chords and a device-pixel tolerance.
fn roots(seg: PathSeg, axis: usize, value: f64) -> impl Iterator<Item = f64> {
    let coordinate = |point: Point| if axis == 0 { point.x } else { point.y };
    let polynomial = match seg {
        PathSeg::Line(line) => {
            let a = coordinate(line.p0) - value;
            let b = coordinate(line.p1) - value;
            [a, b - a, 0., 0.]
        }
        PathSeg::Quad(quad) => {
            let a = coordinate(quad.p0) - value;
            let b = coordinate(quad.p1) - value;
            let c = coordinate(quad.p2) - value;
            [a, 2. * (b - a), a - 2. * b + c, 0.]
        }
        PathSeg::Cubic(cubic) => {
            let a = coordinate(cubic.p0) - value;
            let b = coordinate(cubic.p1) - value;
            let c = coordinate(cubic.p2) - value;
            let d = coordinate(cubic.p3) - value;
            [
                a,
                3. * (b - a),
                3. * (a - 2. * b + c),
                -a + 3. * b - 3. * c + d,
            ]
        }
    };
    let [a, b, c, d] = polynomial;
    kurbo::common::solve_cubic(a, b, c, d)
        .into_iter()
        .filter(|t| (0. ..=1.).contains(t))
}

fn segment_pieces(seg: PathSeg, clip: Rect, mut visit: impl FnMut(PathSeg, Point)) {
    let [left, top, right, bottom] = edges(clip);
    let mut split = Vec::with_capacity(14);
    split.extend([0., 1.]);
    for (axis, value) in [(0, left), (0, right), (1, top), (1, bottom)] {
        split.extend(roots(seg, axis, value));
    }
    split.sort_by(f64::total_cmp);
    split.dedup_by(|a, b| a.to_bits() == b.to_bits());
    for interval in split.windows(2) {
        let middle = seg.eval(f64::midpoint(interval[0], interval[1]));
        if point_in(clip, middle, false) {
            visit(seg.subsegment(interval[0]..interval[1]), middle);
        }
    }
}

/// A rectangle with no curve crossing its open interior is in a single
/// winding face. This recognizes holes and wholly clipped shapes too.
pub(super) fn covers_rect(path: &BezPath, rule: FillRule, clip: Rect) -> Result<Option<bool>> {
    for (index, seg) in path.segments().enumerate() {
        if index.is_multiple_of(64) {
            crate::operation::checkpoint()?;
        }
        let mut crosses = false;
        segment_pieces(seg, clip, |_, middle| {
            crosses |= point_in(clip, middle, true);
        });
        if crosses {
            return Ok(None);
        }
    }
    let [left, top, right, bottom] = edges(clip);
    Ok(Some(rule.contains(
        path,
        Point::new(f64::midpoint(left, right), f64::midpoint(top, bottom)),
    )))
}

fn witness(path: &BezPath, rule: FillRule, axis: usize, value: f64, clip: Rect) -> Result<bool> {
    let [left, top, right, bottom] = edges(clip);
    let (low, high) = if axis == 0 {
        (top, bottom)
    } else {
        (left, right)
    };
    let mut events = vec![low, high];
    for (index, seg) in path.segments().enumerate() {
        if index.is_multiple_of(256) {
            crate::operation::check()?;
        }
        for t in roots(seg, axis, value) {
            let point = seg.eval(t);
            let other = if axis == 0 { point.y } else { point.x };
            if low < other && other < high {
                crate::data::source::reserve_source(&mut events, 1)?;
                events.push(other);
            }
        }
    }
    events.sort_by(f64::total_cmp);
    for pair in events.windows(2) {
        let middle = f64::midpoint(pair[0], pair[1]);
        if middle > pair[0] && middle < pair[1] {
            let point = if axis == 0 {
                Point::new(value, middle)
            } else {
                Point::new(middle, value)
            };
            if rule.contains(path, point) {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

fn proves_extreme(
    path: &BezPath,
    rule: FillRule,
    axis: usize,
    edge: f64,
    opposite: f64,
    clip: Rect,
    precision: Precision,
) -> Result<bool> {
    let low = edge < opposite;
    if precision == Precision::Continuous {
        let probe = if low {
            edge.next_up()
        } else {
            edge.next_down()
        };
        if !(edge.min(opposite) < probe && probe < edge.max(opposite)) {
            return Ok(false);
        }
        return witness(path, rule, axis, probe, clip);
    }
    let quantum = if low {
        ((edge * 1024.).floor() + 1.) / 1024.
    } else {
        ((edge * 1024.).ceil() - 1.) / 1024.
    };
    let boundary = if low {
        quantum.min(opposite)
    } else {
        quantum.max(opposite)
    };
    // Every successful witness is within the same outward quantum. Try
    // progressively closer interior lines for thin curved extrema.
    let mut probe = f64::midpoint(edge, boundary);
    while probe > edge.min(boundary) && probe < edge.max(boundary) {
        crate::operation::check()?;
        if witness(path, rule, axis, probe, clip)? {
            return Ok(true);
        }
        let next = f64::midpoint(edge, probe);
        if next.to_bits() == probe.to_bits() {
            break;
        }
        probe = next;
    }
    Ok(false)
}

// A non-retraced polynomial boundary has filled support on at least one
// side, arbitrarily close to any of its portions in the open clip. Prove
// non-coincidence using the exact binary64 operands, rather than assuming
// that every contour segment is a visible boundary. Lines and nondegenerate
// quadratics admit particularly simple implicit loci.
type ExactPoint = [num_bigint::BigInt; 2];

fn exact(point: Point) -> Result<ExactPoint> {
    use crate::numeric::binary::units;
    Ok([units(point.x)?, units(point.y)?])
}

fn difference(left: &ExactPoint, right: &ExactPoint) -> ExactPoint {
    [&left[0] - &right[0], &left[1] - &right[1]]
}

fn cross(left: &ExactPoint, right: &ExactPoint) -> num_bigint::BigInt {
    &left[0] * &right[1] - &left[1] * &right[0]
}

enum Locus {
    Line {
        origin: ExactPoint,
        direction: ExactPoint,
    },
    Parabola {
        origin: ExactPoint,
        quadratic: ExactPoint,
        linear: ExactPoint,
        determinant: num_bigint::BigInt,
    },
}

impl Locus {
    fn new(segment: PathSeg) -> Result<Option<Self>> {
        Ok(match segment {
            PathSeg::Line(line) if line.p0 != line.p1 => {
                let origin = exact(line.p0)?;
                let direction = difference(&exact(line.p1)?, &origin);
                Some(Self::Line { origin, direction })
            }
            PathSeg::Quad(quad) => {
                let origin = exact(quad.p0)?;
                let middle = exact(quad.p1)?;
                let end = exact(quad.p2)?;
                let linear = difference(&middle, &origin).map(|value| value * 2);
                let quadratic =
                    difference(&difference(&end, &middle), &difference(&middle, &origin));
                let determinant = cross(&quadratic, &linear);
                (determinant.sign() != num_bigint::Sign::NoSign).then_some(Self::Parabola {
                    origin,
                    quadratic,
                    linear,
                    determinant,
                })
            }
            _ => None,
        })
    }

    fn contains(&self, point: &ExactPoint, denominator: u32) -> bool {
        match self {
            Self::Line { origin, direction } => {
                let delta = difference(point, &origin.clone().map(|value| value * denominator));
                cross(&delta, direction).sign() == num_bigint::Sign::NoSign
            }
            Self::Parabola {
                origin,
                quadratic,
                linear,
                determinant,
            } => {
                let delta = difference(point, &origin.clone().map(|value| value * denominator));
                let parameter = cross(quadratic, &delta);
                determinant * cross(&delta, linear) * denominator == &parameter * &parameter
            }
        }
    }

    fn distinct(&self, other: PathSeg) -> Result<bool> {
        for point in [other.start(), other.end()] {
            if !self.contains(&exact(point)?, 1) {
                return Ok(true);
            }
        }
        // Evaluate the actual polynomial at t=1/2 using integer
        // Bernstein weights. One off-locus point proves that no open
        // portion of this polynomial can coincide with the selected locus.
        let (points, weights, denominator) = match other {
            PathSeg::Line(line) => ([line.p0, line.p1, line.p1, line.p1], [1, 1, 0, 0], 2),
            PathSeg::Quad(quad) => ([quad.p0, quad.p1, quad.p2, quad.p2], [1, 2, 1, 0], 4),
            PathSeg::Cubic(cubic) => ([cubic.p0, cubic.p1, cubic.p2, cubic.p3], [1, 3, 3, 1], 8),
        };
        let mut sum = ExactPoint::default();
        for (point, weight) in points.into_iter().zip(weights) {
            let [x, y] = exact(point)?;
            sum[0] += x * weight;
            sum[1] += y * weight;
        }
        Ok(!self.contains(&sum, denominator))
    }
}

fn control_bounds(segment: PathSeg) -> kurbo::Rect {
    let mut bounds = kurbo::Rect::from_points(segment.start(), segment.end());
    match segment {
        PathSeg::Line(_) => {}
        PathSeg::Quad(quad) => bounds = bounds.union_pt(quad.p1),
        PathSeg::Cubic(cubic) => bounds = bounds.union_pt(cubic.p1).union_pt(cubic.p2),
    }
    bounds
}

fn may_coincide(first: kurbo::Rect, second: kurbo::Rect) -> bool {
    // A shared open arc must have a nonzero overlap in every coordinate
    // that varies along the original polynomial.
    (first.width() == 0. || (first.x0.max(second.x0) < first.x1.min(second.x1)))
        && (first.height() == 0. || (first.y0.max(second.y0) < first.y1.min(second.y1)))
}

fn unique_boundary(path: &BezPath, index: usize, segment: PathSeg) -> Result<bool> {
    let Some(locus) = Locus::new(segment)? else {
        return Ok(false);
    };
    let bounds = control_bounds(segment);
    for (other_index, other) in path.segments().enumerate() {
        if index == other_index || !may_coincide(bounds, control_bounds(other)) {
            continue;
        }
        crate::operation::check()?;
        if !locus.distinct(other)? {
            return Ok(false);
        }
    }
    Ok(true)
}

fn supported_extreme(
    path: &BezPath,
    axis: usize,
    edge: f64,
    low: bool,
    clip: Rect,
) -> Result<bool> {
    for (index, segment) in path.segments().enumerate() {
        let mut reaches = false;
        segment_pieces(segment, clip, |part, middle| {
            if !point_in(clip, middle, true) {
                return;
            }
            let bounds = ParamCurveExtrema::bounding_box(&part);
            let extreme = match (axis, low) {
                (0, true) => bounds.x0,
                (0, false) => bounds.x1,
                (_, true) => bounds.y0,
                (_, false) => bounds.y1,
            };
            reaches |= extreme.to_bits() == edge.to_bits();
        });
        if reaches && unique_boundary(path, index, segment)? {
            return Ok(true);
        }
    }
    Ok(false)
}
pub(super) fn filled_path(
    path: &BezPath,
    rule: FillRule,
    clip: Rect,
    precision: Precision,
) -> Result<InkExtent> {
    let Some(bounds) = path_bounds(path)? else {
        return Ok(InkExtent::Unknown);
    };
    let Some(possible) = bounds.intersection(clip) else {
        return Ok(InkExtent::Empty);
    };
    if let Some(full) = covers_rect(path, rule, clip)? {
        return Ok(if full {
            InkExtent::Bounds(clip)
        } else {
            InkExtent::Empty
        });
    }
    let mut candidates = Bounds::default();
    for (index, seg) in path.segments().enumerate() {
        if index.is_multiple_of(64) {
            crate::operation::checkpoint()?;
        }
        segment_pieces(seg, clip, |part, _| {
            candidates.rect(ParamCurveExtrema::bounding_box(&part));
        });
    }
    for corner in corners(clip) {
        if rule.contains(path, corner) {
            candidates.point(corner);
        }
    }
    let InkExtent::Bounds(candidate) = candidates.extent()? else {
        return Ok(InkExtent::Unknown);
    };
    let Some(candidate) = candidate.intersection(possible) else {
        return Ok(InkExtent::Empty);
    };
    let [left, top, right, bottom] = edges(candidate);
    for (axis, edge, opposite) in [
        (0, left, right),
        (0, right, left),
        (1, top, bottom),
        (1, bottom, top),
    ] {
        if !proves_extreme(path, rule, axis, edge, opposite, clip, precision)?
            && !supported_extreme(path, axis, edge, edge < opposite, clip)?
        {
            return Ok(InkExtent::Unknown);
        }
    }
    Ok(InkExtent::Bounds(candidate))
}

/// Clip one convex, filled polygon; unlike intersecting enclosing boxes this
/// preserves the actual segment crossings and rejects tangential contact.
pub(super) fn convex_polygon(points: &[Point], transform: Affine, clip: Rect) -> Result<InkExtent> {
    let mut polygon: Vec<_> = points.iter().map(|point| transform * *point).collect();
    let [left, top, right, bottom] = edges(clip);
    for (axis, value, lower) in [
        (0, left, true),
        (0, right, false),
        (1, top, true),
        (1, bottom, false),
    ] {
        let coord = |point: Point| if axis == 0 { point.x } else { point.y };
        let inside = |point: Point| {
            if lower {
                coord(point) >= value
            } else {
                coord(point) <= value
            }
        };
        let mut clipped = Vec::new();
        crate::data::source::reserve_source(&mut clipped, polygon.len() + 2)?;
        if polygon.is_empty() {
            return Ok(InkExtent::Empty);
        }
        let mut previous = *polygon.last().expect("nonempty polygon");
        for &current in &polygon {
            if inside(previous) != inside(current) {
                let t = (value - coord(previous)) / (coord(current) - coord(previous));
                clipped.push(previous + (current - previous) * t);
            }
            if inside(current) {
                clipped.push(current);
            }
            previous = current;
        }
        polygon = clipped;
    }
    if polygon.len() < 3 {
        return Ok(InkExtent::Empty);
    }
    let origin = polygon[0];
    let area: f64 = polygon[1..]
        .windows(2)
        .map(|pair| (pair[0] - origin).cross(pair[1] - origin))
        .sum();
    if area == 0. {
        return Ok(InkExtent::Empty);
    }
    let mut bounds = Bounds::default();
    for point in polygon {
        bounds.point(point);
    }
    bounds.extent()
}

pub(super) fn rectangle(rect: Rect, transform: Affine, clip: Rect) -> Result<InkExtent> {
    convex_polygon(&corners(rect), transform, clip)
}

#[derive(Clone, Copy)]
struct Ellipse {
    center: Point,
    u: Vec2,
    v: Vec2,
}

impl Ellipse {
    fn new(center: Point, rx: f64, ry: f64, transform: Affine) -> Self {
        let [a, b, c, d, _, _] = transform.as_coeffs();
        Self {
            center: transform * center,
            u: Vec2::new(a * rx, b * rx),
            v: Vec2::new(c * ry, d * ry),
        }
    }

    fn point(self, angle: f64) -> Point {
        let (sin, cos) = angle.sin_cos();
        self.center + self.u * cos + self.v * sin
    }

    fn contains(self, point: Point) -> bool {
        let det = self.u.cross(self.v);
        if det == 0. {
            return false;
        }
        let delta = point - self.center;
        let a = delta.cross(self.v) / det;
        let b = self.u.cross(delta) / det;
        a.hypot(b) <= 1.
    }

    fn boundary(self, clip: Rect, bounds: &mut Bounds) {
        use std::f64::consts::{PI, TAU};
        let [left, top, right, bottom] = edges(clip);
        let mut events = vec![0., TAU];
        for (center, u, v, low, high) in [
            (self.center.x, self.u.x, self.v.x, left, right),
            (self.center.y, self.u.y, self.v.y, top, bottom),
        ] {
            let radius = u.hypot(v);
            if radius == 0. {
                continue;
            }
            let phase = v.atan2(u);
            events.extend([phase.rem_euclid(TAU), (phase + PI).rem_euclid(TAU)]);
            for side in [low, high] {
                let ratio = (side - center) / radius;
                if (-1. ..=1.).contains(&ratio) {
                    let angle = ratio.acos();
                    events.extend([
                        (phase - angle).rem_euclid(TAU),
                        (phase + angle).rem_euclid(TAU),
                    ]);
                }
            }
        }
        events.sort_by(f64::total_cmp);
        events.dedup_by(|a, b| a.to_bits() == b.to_bits());
        for angles in events.windows(2) {
            if point_in(clip, self.point(f64::midpoint(angles[0], angles[1])), true) {
                bounds.point(self.point(angles[0]));
                bounds.point(self.point(angles[1]));
            }
        }
    }
}

pub(super) fn ellipse_band(
    center: Point,
    radii: (f64, f64),
    inner: Option<(f64, f64)>,
    transform: Affine,
    clip: Rect,
) -> Result<InkExtent> {
    if radii.0 <= 0. || radii.1 <= 0. {
        return Ok(InkExtent::Empty);
    }
    let outer = Ellipse::new(center, radii.0, radii.1, transform);
    let inner = inner
        .filter(|(rx, ry)| *rx > 0. && *ry > 0.)
        .map(|(rx, ry)| Ellipse::new(center, rx, ry, transform));
    let mut bounds = Bounds::default();
    outer.boundary(clip, &mut bounds);
    if let Some(inner) = inner {
        inner.boundary(clip, &mut bounds);
    }
    for corner in corners(clip) {
        if outer.contains(corner) && inner.is_none_or(|inner| !inner.contains(corner)) {
            bounds.point(corner);
        }
    }
    Ok(bounds.extent()?.clipped(clip))
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Cap {
    Butt,
    Round,
    Square,
}
#[derive(Clone, Copy, PartialEq)]
pub(super) enum Join {
    Miter(f64),
    Round,
    Bevel,
}

pub(super) struct Pen {
    pub(super) radius: f64,
    pub(super) cap: Cap,
    pub(super) join: Join,
    pub(super) dash: Vec<f64>,
}

fn disk(center: Point, radius: f64, transform: Affine, clip: Rect) -> Result<InkExtent> {
    ellipse_band(center, (radius, radius), None, transform, clip)
}

fn segment_body(
    start: Point,
    end: Point,
    radius: f64,
    cap: Cap,
    transform: Affine,
    clip: Rect,
) -> Result<InkExtent> {
    let delta = end - start;
    let length = delta.hypot();
    if length == 0. {
        return if cap == Cap::Round {
            disk(start, radius, transform, clip)
        } else {
            Ok(InkExtent::Empty)
        };
    }
    let direction = delta / length;
    let normal = Vec2::new(-direction.y, direction.x) * radius;
    let extension = if cap == Cap::Square {
        direction * radius
    } else {
        Vec2::ZERO
    };
    let mut ink = convex_polygon(
        &[
            start - extension + normal,
            end + extension + normal,
            end + extension - normal,
            start - extension - normal,
        ],
        transform,
        clip,
    )?;
    if cap == Cap::Round {
        ink = ink
            .union(disk(start, radius, transform, clip)?)
            .union(disk(end, radius, transform, clip)?);
    }
    Ok(ink)
}

fn join(
    before: Point,
    vertex: Point,
    after: Point,
    pen: &Pen,
    transform: Affine,
    clip: Rect,
) -> Result<InkExtent> {
    if pen.join == Join::Round {
        return disk(vertex, pen.radius, transform, clip);
    }
    let first = vertex - before;
    let second = after - vertex;
    let (l1, l2) = (first.hypot(), second.hypot());
    if l1 == 0. || l2 == 0. {
        return Ok(InkExtent::Empty);
    }
    let (first, second) = (first / l1, second / l2);
    let cross = first.cross(second);
    if cross == 0. {
        return Ok(InkExtent::Empty);
    }
    let sign = -cross.signum() * pen.radius;
    let outer_first = vertex + Vec2::new(-first.y, first.x) * sign;
    let outer_second = vertex + Vec2::new(-second.y, second.x) * sign;
    if let Join::Miter(limit) = pen.join {
        let apex = outer_first + first * ((outer_second - outer_first).cross(second) / cross);
        if (apex - vertex).hypot() <= limit * pen.radius {
            return convex_polygon(&[vertex, outer_first, apex, outer_second], transform, clip);
        }
    }
    convex_polygon(&[vertex, outer_first, outer_second], transform, clip)
}

fn dashed_stroke(
    points: &[Point],
    closed: bool,
    pen: &Pen,
    transform: Affine,
    clip: Rect,
) -> Result<InkExtent> {
    let mut ink = InkExtent::Empty;
    // Closing a dashed path joins the last and first dash according to
    // their actual phase. Native dashed lines are open polylines.
    if closed {
        return Ok(InkExtent::Unknown);
    }
    if pen.cap != Cap::Round || pen.join != Join::Round {
        return Ok(InkExtent::Unknown);
    }
    let mut dash_index = 0;
    let mut left = pen.dash[0];
    for pair in points.windows(2) {
        let delta = pair[1] - pair[0];
        let length = delta.hypot();
        let mut distance = 0.;
        while distance < length {
            crate::operation::check()?;
            let step = left.min(length - distance);
            let end = distance + step;
            if end <= distance {
                return Ok(InkExtent::Unknown);
            }
            if dash_index % 2 == 0 {
                ink = ink.union(segment_body(
                    pair[0] + delta * (distance / length),
                    pair[0] + delta * (end / length),
                    pen.radius,
                    Cap::Round,
                    transform,
                    clip,
                )?);
            }
            distance = end;
            left -= step;
            if left <= 0. {
                dash_index = (dash_index + 1) % pen.dash.len();
                left = pen.dash[dash_index];
            }
        }
    }
    Ok(ink)
}

pub(super) fn linear_stroke(
    points: &[Point],
    closed: bool,
    pen: &Pen,
    transform: Affine,
    clip: Rect,
) -> Result<InkExtent> {
    let mut ink = InkExtent::Empty;
    if points.len() < 2 || pen.radius <= 0. {
        return Ok(ink);
    }
    let mut distinct = std::borrow::Cow::Borrowed(points);
    if points.windows(2).any(|pair| pair[0] == pair[1]) {
        distinct.to_mut().dedup();
    }
    let points = distinct.as_ref();
    if points.len() == 1 {
        if closed {
            return Ok(InkExtent::Unknown);
        }
        return match pen.cap {
            Cap::Butt => Ok(InkExtent::Empty),
            Cap::Round => disk(points[0], pen.radius, transform, clip),
            Cap::Square => {
                let point = points[0];
                rectangle(
                    Rect::new(
                        point.x - pen.radius,
                        point.y - pen.radius,
                        2. * pen.radius,
                        2. * pen.radius,
                    )?,
                    transform,
                    clip,
                )
            }
        };
    }
    if !pen.dash.is_empty() {
        return dashed_stroke(points, closed, pen, transform, clip);
    }
    if pen.join == Join::Round && pen.cap != Cap::Round && !closed && points.len() > 2 {
        return Ok(InkExtent::Unknown);
    }
    let pairs = points.windows(2);
    for pair in pairs {
        crate::operation::check()?;
        ink = ink.union(segment_body(
            pair[0],
            pair[1],
            pen.radius,
            Cap::Butt,
            transform,
            clip,
        )?);
    }
    for triple in points.windows(3) {
        ink = ink.union(join(triple[0], triple[1], triple[2], pen, transform, clip)?);
    }
    let first = points[0];
    let last = *points.last().expect("nonempty path");
    if closed {
        if last != first {
            ink = ink.union(segment_body(
                last,
                first,
                pen.radius,
                Cap::Butt,
                transform,
                clip,
            )?);
            ink = ink.union(join(
                points[points.len() - 2],
                last,
                first,
                pen,
                transform,
                clip,
            )?);
        }
        let previous = if last == first {
            points[points.len() - 2]
        } else {
            last
        };
        ink = ink.union(join(previous, first, points[1], pen, transform, clip)?);
    } else if pen.cap == Cap::Round {
        ink = ink
            .union(disk(first, pen.radius, transform, clip)?)
            .union(disk(last, pen.radius, transform, clip)?);
    } else if pen.cap == Cap::Square {
        for (point, other) in [(first, points[1]), (last, points[points.len() - 2])] {
            let direction = point - other;
            if direction.hypot() > 0. {
                ink = ink.union(segment_body(
                    point,
                    point + direction / direction.hypot() * pen.radius,
                    pen.radius,
                    Cap::Butt,
                    transform,
                    clip,
                )?);
            }
        }
    }
    Ok(ink)
}
/// Exact circular rounded corners under an axis-aligned placement. A
/// rounded rectangle is the union of its two middle bands and four sector
/// disks; its stroke consists of four straight strips and annular sectors.
pub(super) fn rounded_rectangle(
    rect: Rect,
    radius: f64,
    fill: bool,
    pen: Option<&Pen>,
    transform: Affine,
    clip: Rect,
) -> Result<InkExtent> {
    let [scale_x, skew_y, skew_x, scale_y, _, _] = transform.as_coeffs();
    if skew_y != 0. || skew_x != 0. || scale_x == 0. || scale_y == 0. {
        return Ok(InkExtent::Unknown);
    }
    if pen.is_some_and(|pen| !pen.dash.is_empty()) {
        return Ok(InkExtent::Unknown);
    }
    let [left, top, right, bottom] = edges(rect);
    let x0 = left + radius;
    let x1 = right - radius;
    let y0 = top + radius;
    let y1 = bottom - radius;
    let mut ink = InkExtent::Empty;
    let half_width = pen.map_or(0., |pen| pen.radius);
    let mut band = |l: f64, t: f64, r: f64, b: f64| -> Result<()> {
        if r > l && b > t {
            ink = ink.union(rectangle(Rect::new(l, t, r - l, b - t)?, transform, clip)?);
        }
        Ok(())
    };
    if fill {
        band(x0, top - half_width, x1, bottom + half_width)?;
        band(left - half_width, y0, right + half_width, y1)?;
    } else {
        band(x0, top - half_width, x1, top + half_width)?;
        band(x0, bottom - half_width, x1, bottom + half_width)?;
        band(left - half_width, y0, left + half_width, y1)?;
        band(right - half_width, y0, right + half_width, y1)?;
    }
    let outer = radius + half_width;
    let inner = (!fill).then_some((radius - half_width, radius - half_width));
    for (x, y, sx, sy) in [
        (x0, y0, -1., -1.),
        (x1, y0, 1., -1.),
        (x0, y1, -1., 1.),
        (x1, y1, 1., 1.),
    ] {
        let center = Point::new(x, y);
        let opposite = center + Vec2::new(sx * outer, sy * outer);
        let a = transform * center;
        let b = transform * opposite;
        let quadrant = Rect::new(
            a.x.min(b.x),
            a.y.min(b.y),
            (a.x - b.x).abs(),
            (a.y - b.y).abs(),
        )?;
        if let Some(clip) = clip.intersection(quadrant) {
            ink = ink.union(ellipse_band(
                center,
                (outer, outer),
                inner,
                transform,
                clip,
            )?);
        }
    }
    Ok(ink)
}