mirui 0.38.0

A lightweight, no_std ECS-driven UI framework for embedded, desktop, and WebAssembly
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
use alloc::vec::Vec;

use crate::types::{Fixed, Point, Transform};

use super::path::{Path, PathCmd};

/// Cap so a pathological path can't pin tens of KB on a 200 KB MCU heap.
pub const MAX_SEG_CAP: usize = 2048;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineSeg {
    pub p1: Point,
    pub p2: Point,
}

/// Polygon fill rule.
#[allow(dead_code)] // NonZero is used by the ttf-parser path; tests verify both rules.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FillRule {
    /// Pixel is inside if a ray from it crosses an odd number of edges.
    /// Default for SVG / rectangles / shapes that don't self-overlap.
    EvenOdd,
    /// Pixel is inside if the signed winding count (downward-going edges
    /// add 1, upward subtract 1) is non-zero. Required for TrueType /
    /// CFF outlines where the same contour can wrap around itself.
    NonZero,
}

/// One contiguous subpath produced by flatten_subpaths().
/// `closed` is true when the subpath ended with a Close command.
#[derive(Clone, Debug)]
pub struct SubPath {
    pub segs: Vec<LineSeg>,
    pub closed: bool,
}

/// Subdivision step counts. Chosen to keep a single control-point radius
/// visually smooth on 128×128 screens; larger paths may show facets but UI
/// radii are small.
const QUAD_STEPS: i32 = 8;
const CUBIC_STEPS: i32 = 16;

/// `transform` folds in at emit time so backends can compose
/// `viewport × cmd` once and avoid pre-rebuilding the PathCmd stream.
pub fn flatten_into(cmds: &[PathCmd], transform: Option<&Transform>, out: &mut Vec<LineSeg>) {
    out.clear();
    let mut subpath_start = Point::ZERO;
    let mut current = Point::ZERO;

    let apply = |p: Point| -> Point {
        match transform {
            Some(tf) => tf.apply_point(p),
            None => p,
        }
    };

    for cmd in cmds {
        match cmd {
            PathCmd::MoveTo(p) => {
                let p = apply(*p);
                subpath_start = p;
                current = p;
            }
            PathCmd::LineTo(p) => {
                let p = apply(*p);
                out.push(LineSeg { p1: current, p2: p });
                current = p;
            }
            PathCmd::QuadTo { ctrl, end } => {
                let ctrl = apply(*ctrl);
                let end = apply(*end);
                let p0 = current;
                for i in 1..=QUAD_STEPS {
                    let t = Fixed::from_int(i) / Fixed::from_int(QUAD_STEPS);
                    let next = quad_at(p0, ctrl, end, t);
                    out.push(LineSeg {
                        p1: current,
                        p2: next,
                    });
                    current = next;
                }
            }
            PathCmd::CubicTo { ctrl1, ctrl2, end } => {
                let ctrl1 = apply(*ctrl1);
                let ctrl2 = apply(*ctrl2);
                let end = apply(*end);
                let p0 = current;
                for i in 1..=CUBIC_STEPS {
                    let t = Fixed::from_int(i) / Fixed::from_int(CUBIC_STEPS);
                    let next = cubic_at(p0, ctrl1, ctrl2, end, t);
                    out.push(LineSeg {
                        p1: current,
                        p2: next,
                    });
                    current = next;
                }
            }
            PathCmd::Close => {
                if current != subpath_start {
                    out.push(LineSeg {
                        p1: current,
                        p2: subpath_start,
                    });
                }
                current = subpath_start;
            }
        }
    }

    if out.capacity() > MAX_SEG_CAP {
        out.shrink_to(MAX_SEG_CAP);
    }
}

/// Flatten path into per-subpath groups, tracking whether each ended with
/// Close. stroke_path needs this to decide between offset-ring (closed) and
/// butt-capped strip (open) handling.
pub fn flatten_subpaths_into(
    cmds: &[PathCmd],
    transform: Option<&Transform>,
    out: &mut Vec<SubPath>,
) {
    out.clear();
    let mut subpath_start = Point::ZERO;
    let mut current = Point::ZERO;
    let mut current_segs: Vec<LineSeg> = Vec::new();
    let mut has_moveto = false;

    let apply = |p: Point| -> Point {
        match transform {
            Some(tf) => tf.apply_point(p),
            None => p,
        }
    };

    let flush = |segs: &mut Vec<LineSeg>, out: &mut Vec<SubPath>, closed: bool| {
        if !segs.is_empty() {
            out.push(SubPath {
                segs: core::mem::take(segs),
                closed,
            });
        }
    };

    for cmd in cmds {
        match cmd {
            PathCmd::MoveTo(p) => {
                flush(&mut current_segs, out, false);
                let p = apply(*p);
                subpath_start = p;
                current = p;
                has_moveto = true;
            }
            PathCmd::LineTo(p) => {
                if !has_moveto {
                    continue;
                }
                let p = apply(*p);
                current_segs.push(LineSeg { p1: current, p2: p });
                current = p;
            }
            PathCmd::QuadTo { ctrl, end } => {
                if !has_moveto {
                    continue;
                }
                let ctrl = apply(*ctrl);
                let end = apply(*end);
                let p0 = current;
                for i in 1..=QUAD_STEPS {
                    let t = Fixed::from_int(i) / Fixed::from_int(QUAD_STEPS);
                    let next = quad_at(p0, ctrl, end, t);
                    current_segs.push(LineSeg {
                        p1: current,
                        p2: next,
                    });
                    current = next;
                }
            }
            PathCmd::CubicTo { ctrl1, ctrl2, end } => {
                if !has_moveto {
                    continue;
                }
                let ctrl1 = apply(*ctrl1);
                let ctrl2 = apply(*ctrl2);
                let end = apply(*end);
                let p0 = current;
                for i in 1..=CUBIC_STEPS {
                    let t = Fixed::from_int(i) / Fixed::from_int(CUBIC_STEPS);
                    let next = cubic_at(p0, ctrl1, ctrl2, end, t);
                    current_segs.push(LineSeg {
                        p1: current,
                        p2: next,
                    });
                    current = next;
                }
            }
            PathCmd::Close => {
                if current != subpath_start {
                    current_segs.push(LineSeg {
                        p1: current,
                        p2: subpath_start,
                    });
                }
                current = subpath_start;
                flush(&mut current_segs, out, true);
                has_moveto = false;
            }
        }
    }
    flush(&mut current_segs, out, false);
}

/// Vertical supersampling count per pixel row. 4 sub-scanlines gives 5-level
/// (0/4, 1/4, 2/4, 3/4, 4/4) coverage — enough to hide the worst jaggies
/// without making the rasterizer too heavy on ESP32.
const SUB_SCANLINES: i32 = 4;

/// Coverage-based fill rasterizer with 4 sub-scanlines per pixel row.
/// Emits `cov ∈ [0, 1]` per pixel under the chosen [`FillRule`].
/// `acc` and `crossings` are caller-owned scratch buffers, reused
/// across calls so a tight fill loop doesn't allocate per draw.
#[allow(clippy::too_many_arguments)]
pub fn scanline_fill(
    segs: &[LineSeg],
    px_x0: i32,
    py_y0: i32,
    px_x1: i32,
    py_y1: i32,
    rule: FillRule,
    acc: &mut Vec<Fixed>,
    crossings: &mut Vec<(Fixed, i8)>,
    mut emit: impl FnMut(i32, i32, Fixed),
) {
    if segs.is_empty() || px_x1 <= px_x0 || py_y1 <= py_y0 {
        return;
    }
    let row_w = (px_x1 - px_x0) as usize;
    acc.clear();
    acc.resize(row_w, Fixed::ZERO);
    let sub_weight = Fixed::ONE / SUB_SCANLINES;

    for py in py_y0..py_y1 {
        for a in acc.iter_mut() {
            *a = Fixed::ZERO;
        }

        for sub in 0..SUB_SCANLINES {
            let y_sample =
                Fixed::from_int(py) + (Fixed::from_int(sub) + Fixed::ONE / 2) / SUB_SCANLINES;

            crossings.clear();
            for s in segs {
                let (y_lo, y_hi, winding) = if s.p1.y <= s.p2.y {
                    (s.p1.y, s.p2.y, 1i8)
                } else {
                    (s.p2.y, s.p1.y, -1i8)
                };
                if y_sample < y_lo || y_sample >= y_hi {
                    continue;
                }
                let dy = s.p2.y - s.p1.y;
                if dy == Fixed::ZERO {
                    continue;
                }
                let t = (y_sample - s.p1.y) / dy;
                let x_cross = s.p1.x + (s.p2.x - s.p1.x) * t;
                crossings.push((x_cross, winding));
            }

            crossings.sort_by_key(|x| x.0);

            match rule {
                FillRule::EvenOdd => {
                    let mut i = 0;
                    while i + 1 < crossings.len() {
                        let xa = crossings[i].0;
                        let xb = crossings[i + 1].0;
                        accumulate_interval(acc, px_x0, px_x1, xa, xb, sub_weight);
                        i += 2;
                    }
                }
                FillRule::NonZero => {
                    let mut count: i32 = 0;
                    let mut span_start: Option<Fixed> = None;
                    for (x, winding) in crossings.iter() {
                        let prev = count;
                        count += *winding as i32;
                        let was_inside = prev != 0;
                        let now_inside = count != 0;
                        match (was_inside, now_inside) {
                            (false, true) => span_start = Some(*x),
                            (true, false) => {
                                if let Some(start) = span_start.take() {
                                    accumulate_interval(acc, px_x0, px_x1, start, *x, sub_weight);
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
        }

        for (i, cov) in acc.iter().enumerate() {
            if *cov > Fixed::ZERO {
                emit(px_x0 + i as i32, py, *cov);
            }
        }
    }
}

/// Add `weight` × (fraction of each pixel covered by [xa, xb]) into `acc`.
fn accumulate_interval(
    acc: &mut [Fixed],
    px_x0: i32,
    px_x1: i32,
    xa: Fixed,
    xb: Fixed,
    weight: Fixed,
) {
    let (xlo, xhi) = if xa <= xb { (xa, xb) } else { (xb, xa) };
    if xhi <= Fixed::from_int(px_x0) || xlo >= Fixed::from_int(px_x1) {
        return;
    }

    let lo_int = xlo.to_int().max(px_x0);
    let hi_int = xhi.ceil().to_int().min(px_x1);

    for px in lo_int..hi_int {
        let pixel_left = Fixed::from_int(px);
        let pixel_right = Fixed::from_int(px + 1);
        let left = xlo.max(pixel_left);
        let right = xhi.min(pixel_right);
        let frac = right - left;
        if frac > Fixed::ZERO {
            acc[(px - px_x0) as usize] += frac * weight;
        }
    }
}

/// Point-in-polygon test via +X ray casting with even-odd rule.
/// Uses the half-open convention [y_min, y_max) to avoid double-counting at
/// shared vertices.
#[allow(dead_code)] // Retained for hit-test use-cases and future rasterizers
pub(crate) fn point_in_segments(pt: Point, segs: &[LineSeg]) -> bool {
    let mut crossings = 0u32;
    for s in segs {
        let (y_lo, y_hi) = if s.p1.y <= s.p2.y {
            (s.p1.y, s.p2.y)
        } else {
            (s.p2.y, s.p1.y)
        };
        if pt.y < y_lo || pt.y >= y_hi {
            continue;
        }
        // x of the edge at this y-row. Skip horizontal edges (can't intersect).
        let dy = s.p2.y - s.p1.y;
        if dy == Fixed::ZERO {
            continue;
        }
        let t = (pt.y - s.p1.y) / dy;
        let x_cross = s.p1.x + (s.p2.x - s.p1.x) * t;
        if x_cross > pt.x {
            crossings += 1;
        }
    }
    crossings & 1 == 1
}

/// Minimum unsigned distance from `pt` to any segment in `segs`, capped at
/// `cap`. Segments whose AABB is farther than `cap` from `pt` are skipped
/// without any sqrt. Returns `cap` when nothing is within range.
///
/// `cap` is compared in **Fixed space** (not squared) to avoid `Fixed * Fixed`
/// overflow when callers pass `Fixed::MAX` or similar large bounds.
#[allow(dead_code)] // Retained for stroke width hit-testing and future use
pub(crate) fn min_dist_to_segments_capped(pt: Point, segs: &[LineSeg], cap: Fixed) -> Fixed {
    let mut best = cap;
    let mut found = false;
    for s in segs {
        let (xlo, xhi) = if s.p1.x <= s.p2.x {
            (s.p1.x, s.p2.x)
        } else {
            (s.p2.x, s.p1.x)
        };
        let (ylo, yhi) = if s.p1.y <= s.p2.y {
            (s.p1.y, s.p2.y)
        } else {
            (s.p2.y, s.p1.y)
        };
        // Quick Chebyshev reject: if the segment's bbox is strictly farther
        // than `best` on either axis, the true distance is ≥ best too.
        let dx_box = if pt.x < xlo {
            xlo - pt.x
        } else if pt.x > xhi {
            pt.x - xhi
        } else {
            Fixed::ZERO
        };
        let dy_box = if pt.y < ylo {
            ylo - pt.y
        } else if pt.y > yhi {
            pt.y - yhi
        } else {
            Fixed::ZERO
        };
        if dx_box >= best || dy_box >= best {
            continue;
        }
        let d = dist_sq_point_to_segment(pt, s.p1, s.p2).sqrt();
        if d < best {
            best = d;
            found = true;
        }
    }
    if found { best } else { cap }
}

/// Squared distance from point `p` to segment `ab`. Caller decides when to sqrt.
fn dist_sq_point_to_segment(p: Point, a: Point, b: Point) -> Fixed {
    let abx = b.x - a.x;
    let aby = b.y - a.y;
    let len_sq = abx * abx + aby * aby;
    if len_sq == Fixed::ZERO {
        let dx = p.x - a.x;
        let dy = p.y - a.y;
        return dx * dx + dy * dy;
    }
    let apx = p.x - a.x;
    let apy = p.y - a.y;
    let t_raw = (apx * abx + apy * aby) / len_sq;
    let t = t_raw.max(Fixed::ZERO).min(Fixed::ONE);
    let cx = a.x + abx * t;
    let cy = a.y + aby * t;
    let dx = p.x - cx;
    let dy = p.y - cy;
    dx * dx + dy * dy
}

/// Miter limit ratio (Fixed). If the miter extension exceeds this multiple of
/// half_width the join degrades to bevel. 4 is the SVG default.
const MITER_LIMIT: Fixed = Fixed::from_int(4);

pub(crate) fn offset_polygon_into(
    cmds: &[PathCmd],
    transform: Option<&Transform>,
    width: Fixed,
    out: &mut Path,
    subpath_scratch: &mut Vec<SubPath>,
    normals_scratch: &mut Vec<Point>,
    rail_scratch: &mut Vec<Point>,
) {
    out.cmds.to_mut().clear();
    if width <= Fixed::ZERO {
        return;
    }
    let half = width / 2;

    flatten_subpaths_into(cmds, transform, subpath_scratch);

    for sub in subpath_scratch.drain(..) {
        if sub.segs.is_empty() {
            continue;
        }

        compute_normals_into(&sub.segs, half, normals_scratch);
        if sub.closed {
            build_ring_into(
                &sub.segs,
                normals_scratch,
                half,
                /*left=*/ true,
                rail_scratch,
            );
            append_closed_polyline(out, rail_scratch);
            build_ring_into(
                &sub.segs,
                normals_scratch,
                half,
                /*left=*/ false,
                rail_scratch,
            );
            rail_scratch.reverse();
            append_closed_polyline(out, rail_scratch);
        } else {
            build_open_rail_into(
                &sub.segs,
                normals_scratch,
                half,
                /*left=*/ true,
                rail_scratch,
            );
            // The ribbon needs both rails alive at once, so the open path
            // pays a one-off temporary clone of the right rail. Closed
            // path stays zero-alloc because it appends each rail before
            // building the next.
            let left = rail_scratch.clone();
            build_open_rail_into(
                &sub.segs,
                normals_scratch,
                half,
                /*left=*/ false,
                rail_scratch,
            );
            append_open_ribbon(out, &left, rail_scratch);
        }
    }
}

fn compute_normals_into(segs: &[LineSeg], half: Fixed, out: &mut Vec<Point>) {
    out.clear();
    out.reserve(segs.len());
    for s in segs {
        let dx = s.p2.x - s.p1.x;
        let dy = s.p2.y - s.p1.y;
        let len_sq = dx * dx + dy * dy;
        if len_sq == Fixed::ZERO {
            out.push(Point::ZERO);
            continue;
        }
        let len = len_sq.sqrt();
        let nx = -dy / len * half;
        let ny = dx / len * half;
        out.push(Point { x: nx, y: ny });
    }
}

fn build_ring_into(segs: &[LineSeg], n: &[Point], half: Fixed, left: bool, out: &mut Vec<Point>) {
    out.clear();
    let sign = if left { Fixed::ONE } else { -Fixed::ONE };
    let count = segs.len();
    out.reserve(count + 1);

    for i in 0..count {
        let prev = if i == 0 { count - 1 } else { i - 1 };
        let p_prev = segs[prev];
        let p_curr = segs[i];
        let n_prev = scaled(n[prev], sign);
        let n_curr = scaled(n[i], sign);

        let joint = compute_join(
            p_prev.p2, p_prev.p1, n_prev, p_curr.p1, p_curr.p2, n_curr, half,
        );
        out.push(joint);
    }
    if let Some(&first) = out.first() {
        out.push(first);
    }
}

fn build_open_rail_into(
    segs: &[LineSeg],
    n: &[Point],
    half: Fixed,
    left: bool,
    out: &mut Vec<Point>,
) {
    out.clear();
    let sign = if left { Fixed::ONE } else { -Fixed::ONE };
    let count = segs.len();
    out.reserve(count + 1);

    let n0 = scaled(n[0], sign);
    out.push(offset(segs[0].p1, n0));

    for i in 1..count {
        let p_prev = segs[i - 1];
        let p_curr = segs[i];
        let n_prev = scaled(n[i - 1], sign);
        let n_curr = scaled(n[i], sign);

        let joint = compute_join(
            p_prev.p2, p_prev.p1, n_prev, p_curr.p1, p_curr.p2, n_curr, half,
        );
        out.push(joint);
    }

    let n_last = scaled(n[count - 1], sign);
    out.push(offset(segs[count - 1].p2, n_last));
}

/// Miter join: intersect the two offset lines. If the intersection is beyond
/// MITER_LIMIT * half from the shared corner, fall back to bevel (average of
/// the two offset corner points).
fn compute_join(
    // a->b is the incoming segment, c->d is the outgoing. b and c are the
    // shared corner in original path space (normally b == c but kept separate
    // for generality).
    _a: Point,
    b: Point,
    n_prev: Point,
    c: Point,
    _d: Point,
    n_curr: Point,
    half: Fixed,
) -> Point {
    let p_in = offset(b, n_prev);
    let p_out = offset(c, n_curr);

    // If adjacent offset points nearly coincide, no real corner — use one.
    if approx_eq(p_in, p_out) {
        return p_in;
    }

    // Miter = intersection of line(p_in, direction of incoming) with
    // line(p_out, direction of outgoing). Build direction from original segs.
    let dir_prev = Point {
        x: b.x - _a.x,
        y: b.y - _a.y,
    };
    let dir_curr = Point {
        x: _d.x - c.x,
        y: _d.y - c.y,
    };

    if let Some(miter) = line_intersect(p_in, dir_prev, p_out, dir_curr) {
        let corner = Point {
            x: (b.x + c.x) / 2,
            y: (b.y + c.y) / 2,
        };
        let dx = miter.x - corner.x;
        let dy = miter.y - corner.y;
        let dist_sq = dx * dx + dy * dy;
        let limit = half * MITER_LIMIT;
        if dist_sq <= limit * limit {
            return miter;
        }
    }
    // Bevel fallback: midpoint of the two offset corner points.
    Point {
        x: (p_in.x + p_out.x) / 2,
        y: (p_in.y + p_out.y) / 2,
    }
}

/// Solve p1 + t*d1 = p2 + s*d2 for t. Returns the intersection point, or None
/// when the directions are parallel.
fn line_intersect(p1: Point, d1: Point, p2: Point, d2: Point) -> Option<Point> {
    let denom = d1.x * d2.y - d1.y * d2.x;
    if denom == Fixed::ZERO {
        return None;
    }
    let dx = p2.x - p1.x;
    let dy = p2.y - p1.y;
    let t = (dx * d2.y - dy * d2.x) / denom;
    Some(Point {
        x: p1.x + d1.x * t,
        y: p1.y + d1.y * t,
    })
}

fn append_closed_polyline(out: &mut Path, pts: &[Point]) {
    if pts.len() < 2 {
        return;
    }
    out.move_to(pts[0]);
    for p in &pts[1..] {
        out.line_to(*p);
    }
    out.close();
}

fn append_open_ribbon(out: &mut Path, left: &[Point], right: &[Point]) {
    if left.is_empty() || right.is_empty() {
        return;
    }
    out.move_to(left[0]);
    for p in &left[1..] {
        out.line_to(*p);
    }
    // Walk right side in reverse so the ribbon stays a simple closed polygon.
    for p in right.iter().rev() {
        out.line_to(*p);
    }
    out.close();
}

fn scaled(p: Point, s: Fixed) -> Point {
    Point {
        x: p.x * s,
        y: p.y * s,
    }
}

fn offset(p: Point, n: Point) -> Point {
    Point {
        x: p.x + n.x,
        y: p.y + n.y,
    }
}

fn approx_eq(a: Point, b: Point) -> bool {
    let dx = a.x - b.x;
    let dy = a.y - b.y;
    // Within ~1/256 pixel in Manhattan distance.
    dx.abs() + dy.abs() < Fixed::ONE / 128
}

fn lerp(a: Point, b: Point, t: Fixed) -> Point {
    Point {
        x: a.x + (b.x - a.x) * t,
        y: a.y + (b.y - a.y) * t,
    }
}

fn quad_at(p0: Point, p1: Point, p2: Point, t: Fixed) -> Point {
    lerp(lerp(p0, p1, t), lerp(p1, p2, t), t)
}

fn cubic_at(p0: Point, p1: Point, p2: Point, p3: Point, t: Fixed) -> Point {
    let q0 = lerp(p0, p1, t);
    let q1 = lerp(p1, p2, t);
    let q2 = lerp(p2, p3, t);
    lerp(lerp(q0, q1, t), lerp(q1, q2, t), t)
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use super::*;

    fn pt(x: i32, y: i32) -> Point {
        Point {
            x: Fixed::from_int(x),
            y: Fixed::from_int(y),
        }
    }

    fn flatten_path(p: &Path) -> Vec<LineSeg> {
        let mut out = Vec::new();
        flatten_into(&p.cmds, None, &mut out);
        out
    }

    fn flatten_subpaths_path(p: &Path) -> Vec<SubPath> {
        let mut out = Vec::new();
        flatten_subpaths_into(&p.cmds, None, &mut out);
        out
    }

    fn offset_polygon_path(p: &Path, width: Fixed) -> Path {
        let mut out = Path::new();
        let mut scratch = Vec::new();
        let mut normals = Vec::new();
        let mut rail = Vec::new();
        offset_polygon_into(
            &p.cmds,
            None,
            width,
            &mut out,
            &mut scratch,
            &mut normals,
            &mut rail,
        );
        out
    }

    #[test]
    fn flatten_empty_path() {
        assert!(flatten_path(&Path::new()).is_empty());
    }

    #[test]
    fn flatten_single_line() {
        let mut p = Path::new();
        p.move_to(pt(0, 0)).line_to(pt(10, 0));
        let segs = flatten_path(&p);
        assert_eq!(segs.len(), 1);
        assert_eq!(segs[0].p1, pt(0, 0));
        assert_eq!(segs[0].p2, pt(10, 0));
    }

    #[test]
    fn flatten_closed_triangle_emits_closing_edge() {
        let mut p = Path::new();
        p.move_to(pt(0, 0))
            .line_to(pt(10, 0))
            .line_to(pt(5, 10))
            .close();
        let segs = flatten_path(&p);
        // 3 explicit lines + 1 implicit close back to (0,0)
        assert_eq!(segs.len(), 3);
        assert_eq!(segs[2].p2, pt(0, 0));
    }

    #[test]
    fn flatten_close_is_noop_when_current_equals_start() {
        let mut p = Path::new();
        p.move_to(pt(0, 0))
            .line_to(pt(10, 0))
            .line_to(pt(0, 0))
            .close();
        let segs = flatten_path(&p);
        // close() sees current == subpath_start, so it must not add a redundant edge
        assert_eq!(segs.len(), 2);
    }

    #[test]
    fn flatten_quad_emits_n_segments_connected() {
        let mut p = Path::new();
        p.move_to(pt(0, 0)).quad_to(pt(10, 10), pt(20, 0));
        let segs = flatten_path(&p);
        assert_eq!(segs.len(), QUAD_STEPS as usize);
        // Chain: seg[i].p2 == seg[i+1].p1
        for i in 0..segs.len() - 1 {
            assert_eq!(segs[i].p2, segs[i + 1].p1);
        }
        assert_eq!(segs.last().unwrap().p2, pt(20, 0));
    }

    #[test]
    fn flatten_cubic_emits_n_segments_connected() {
        let mut p = Path::new();
        p.move_to(pt(0, 0))
            .cubic_to(pt(0, 10), pt(10, 10), pt(10, 0));
        let segs = flatten_path(&p);
        assert_eq!(segs.len(), CUBIC_STEPS as usize);
        for i in 0..segs.len() - 1 {
            assert_eq!(segs[i].p2, segs[i + 1].p1);
        }
        assert_eq!(segs.last().unwrap().p2, pt(10, 0));
    }

    #[test]
    fn flatten_multi_subpath() {
        // Two independent subpaths: a line then a separate triangle.
        let mut p = Path::new();
        p.move_to(pt(0, 0)).line_to(pt(10, 0));
        p.move_to(pt(50, 50)).line_to(pt(60, 50)).close();
        let segs = flatten_path(&p);
        // Subpath 1: 1 line. Subpath 2: 1 explicit + 1 close = 2.
        assert_eq!(segs.len(), 3);
        // Second subpath closes back to (50,50), not (0,0)
        assert_eq!(segs.last().unwrap().p2, pt(50, 50));
    }

    fn square_segs() -> Vec<LineSeg> {
        // Unit square [0, 10] × [0, 10] — 4 edges CCW.
        vec![
            LineSeg {
                p1: pt(0, 0),
                p2: pt(10, 0),
            },
            LineSeg {
                p1: pt(10, 0),
                p2: pt(10, 10),
            },
            LineSeg {
                p1: pt(10, 10),
                p2: pt(0, 10),
            },
            LineSeg {
                p1: pt(0, 10),
                p2: pt(0, 0),
            },
        ]
    }

    #[test]
    fn point_in_square_interior_detected() {
        assert!(point_in_segments(pt(5, 5), &square_segs()));
    }

    #[test]
    fn point_outside_square_rejected() {
        assert!(!point_in_segments(pt(-1, 5), &square_segs()));
        assert!(!point_in_segments(pt(11, 5), &square_segs()));
        assert!(!point_in_segments(pt(5, -1), &square_segs()));
        assert!(!point_in_segments(pt(5, 11), &square_segs()));
    }

    #[test]
    fn point_on_horizontal_edge_half_open() {
        // Half-open [y_lo, y_hi) — bottom edge is inclusive, top edge is exclusive.
        assert!(point_in_segments(pt(5, 0), &square_segs()));
        assert!(!point_in_segments(pt(5, 10), &square_segs()));
    }

    fn big_cap() -> Fixed {
        // Large enough to not affect any test case, small enough that
        // dx_box/dy_box comparisons stay well within i32 Fixed range.
        Fixed::from_int(1000)
    }

    #[test]
    fn dist_on_segment_is_zero() {
        let segs = square_segs();
        let d = min_dist_to_segments_capped(pt(5, 0), &segs, big_cap());
        assert_eq!(d, Fixed::ZERO);
    }

    #[test]
    fn dist_center_to_square_is_half_width() {
        let segs = square_segs();
        let d = min_dist_to_segments_capped(pt(5, 5), &segs, big_cap()).to_f32();
        assert!((d - 5.0).abs() < 0.01, "d = {d}");
    }

    #[test]
    fn dist_beyond_endpoint_uses_endpoint() {
        let segs = vec![LineSeg {
            p1: pt(0, 0),
            p2: pt(10, 0),
        }];
        let d = min_dist_to_segments_capped(pt(15, 0), &segs, big_cap()).to_f32();
        assert!((d - 5.0).abs() < 0.01);
    }

    #[test]
    fn dist_to_degenerate_segment() {
        let segs = vec![LineSeg {
            p1: pt(3, 4),
            p2: pt(3, 4),
        }];
        let d = min_dist_to_segments_capped(pt(0, 0), &segs, big_cap()).to_f32();
        assert!((d - 5.0).abs() < 0.01);
    }

    #[test]
    fn dist_capped_returns_cap_when_far() {
        let segs = vec![LineSeg {
            p1: pt(100, 100),
            p2: pt(110, 100),
        }];
        let cap = Fixed::from_int(5);
        let d = min_dist_to_segments_capped(pt(0, 0), &segs, cap);
        assert_eq!(d, cap);
    }

    #[test]
    fn flatten_subpaths_marks_closed_and_open() {
        // subpath A ends with Close (closed), subpath B is a dangling LineTo (open).
        let mut p = Path::new();
        p.move_to(pt(0, 0))
            .line_to(pt(10, 0))
            .line_to(pt(0, 10))
            .close();
        p.move_to(pt(50, 50)).line_to(pt(60, 50));
        let subs = flatten_subpaths_path(&p);
        assert_eq!(subs.len(), 2);
        assert!(subs[0].closed);
        assert!(!subs[1].closed);
    }

    #[test]
    fn offset_polygon_rectangle_closed_produces_two_rings() {
        // 10×10 rectangle stroked with width=2. The outline path should have
        // exactly 2 subpaths: outer ring + inner ring.
        let path = Path::rect(
            Fixed::from_int(0),
            Fixed::from_int(0),
            Fixed::from_int(10),
            Fixed::from_int(10),
        );
        let outline = offset_polygon_path(&path, Fixed::from_int(2));
        let closes = outline
            .cmds
            .iter()
            .filter(|c| matches!(c, PathCmd::Close))
            .count();
        assert_eq!(closes, 2);
    }

    #[test]
    fn offset_polygon_open_line_makes_one_ribbon() {
        // A single open LineTo should yield a single closed ribbon (butt caps).
        let mut path = Path::new();
        path.move_to(pt(0, 0)).line_to(pt(10, 0));
        let outline = offset_polygon_path(&path, Fixed::from_int(2));
        let closes = outline
            .cmds
            .iter()
            .filter(|c| matches!(c, PathCmd::Close))
            .count();
        assert_eq!(closes, 1);
    }

    #[test]
    fn offset_polygon_zero_width_is_empty() {
        let mut path = Path::new();
        path.move_to(pt(0, 0)).line_to(pt(10, 0));
        let outline = offset_polygon_path(&path, Fixed::ZERO);
        assert!(outline.cmds.is_empty());
    }

    #[test]
    fn flatten_rounded_rect_produces_expected_count() {
        let p = Path::rounded_rect(
            Fixed::from_int(0),
            Fixed::from_int(0),
            Fixed::from_int(20),
            Fixed::from_int(20),
            Fixed::from_int(4),
        );
        let segs = flatten_path(&p);
        // rounded_rect = 4 lines + 4 quad corners (N=8 each) + possibly 1 close.
        // Layout: move, line, quad, line, quad, line, quad, line, quad, close.
        // Close may add 0 or 1 edge depending on whether final point equals start.
        let expected_min = 4 + 4 * QUAD_STEPS as usize;
        assert!(
            segs.len() >= expected_min,
            "got {} segs, expected ≥{}",
            segs.len(),
            expected_min
        );
    }

    fn rect_segs(x0: i32, y0: i32, x1: i32, y1: i32, ccw: bool) -> Vec<LineSeg> {
        // Outer ring CW (default) or CCW. Order matters because winding
        // direction is derived from p1.y vs p2.y in the rasterizer.
        if ccw {
            alloc::vec![
                LineSeg {
                    p1: pt(x0, y0),
                    p2: pt(x0, y1)
                },
                LineSeg {
                    p1: pt(x0, y1),
                    p2: pt(x1, y1)
                },
                LineSeg {
                    p1: pt(x1, y1),
                    p2: pt(x1, y0)
                },
                LineSeg {
                    p1: pt(x1, y0),
                    p2: pt(x0, y0)
                },
            ]
        } else {
            alloc::vec![
                LineSeg {
                    p1: pt(x0, y0),
                    p2: pt(x1, y0)
                },
                LineSeg {
                    p1: pt(x1, y0),
                    p2: pt(x1, y1)
                },
                LineSeg {
                    p1: pt(x1, y1),
                    p2: pt(x0, y1)
                },
                LineSeg {
                    p1: pt(x0, y1),
                    p2: pt(x0, y0)
                },
            ]
        }
    }

    fn count_filled(segs: &[LineSeg], rule: FillRule) -> i32 {
        let mut n = 0;
        let mut acc = Vec::new();
        let mut crossings = Vec::new();
        scanline_fill(
            segs,
            0,
            0,
            10,
            10,
            rule,
            &mut acc,
            &mut crossings,
            |_, _, cov| {
                if cov > Fixed::from_int(0) {
                    n += 1;
                }
            },
        );
        n
    }

    #[test]
    fn fill_rule_even_odd_carves_inner_ring_to_zero() {
        // Outer 0..10 + inner 2..8 (same direction). Even-odd makes the
        // inner ring punch a hole; non-zero would fill solid.
        let mut segs = rect_segs(0, 0, 10, 10, false);
        segs.extend(rect_segs(2, 2, 8, 8, false));
        let lit = count_filled(&segs, FillRule::EvenOdd);
        assert!(lit > 0, "outer ring still fills with hole");
        // Inside hole should be 0; only outer band lit.
        // 10x10 = 100 total, hole 6x6 = 36, ring = 64.
        assert!(lit < 70, "expected hole, got lit={}", lit);
    }

    #[test]
    fn fill_rule_non_zero_fills_overlapping_same_direction_solid() {
        // Outer + inner same winding. Non-zero stays inside (count = 2),
        // entire 10x10 should be lit. Even-odd would punch a hole.
        let mut segs = rect_segs(0, 0, 10, 10, false);
        segs.extend(rect_segs(2, 2, 8, 8, false));
        let lit = count_filled(&segs, FillRule::NonZero);
        assert_eq!(lit, 100, "non-zero with same-winding should fill solid");
    }

    #[test]
    fn fill_rule_non_zero_carves_hole_when_inner_reversed() {
        // Outer CW, inner CCW (opposite winding). Non-zero count cancels
        // inside the inner — TrueType "even-odd-like via path direction".
        let mut segs = rect_segs(0, 0, 10, 10, false);
        segs.extend(rect_segs(2, 2, 8, 8, true));
        let lit = count_filled(&segs, FillRule::NonZero);
        // 10x10 = 100, hole 6x6 = 36, ring = 64.
        assert!(
            (60..70).contains(&lit),
            "non-zero with opposite winding should carve a hole, got lit={}",
            lit
        );
    }
}