oxiui-render-soft 0.2.1

Software CPU framebuffer backend for OxiUI (headless / ffi-audit)
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
//! Active-Edge-Table (AET) scanline rasteriser for polygon and triangle fill.
//!
//! Supports sub-pixel vertical-supersample coverage anti-aliasing, even-odd
//! fill rule, and non-zero winding fill rule. Both are computed by the same
//! AET machinery — the rule only changes how the accumulated winding count is
//! interpreted per scanline span.

use crate::framebuffer::Framebuffer;
use oxiui_core::Color;

/// How self-intersecting or overlapping sub-paths are filled.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum FillRule {
    /// Standard even-odd rule: regions enclosed by an odd number of boundary
    /// crossings are filled; even crossings produce holes.
    EvenOdd,
    /// Non-zero winding rule: a point is inside if the signed crossing count is
    /// non-zero.
    #[default]
    NonZero,
}

// ---------------------------------------------------------------------------
// Internal AET machinery
// ---------------------------------------------------------------------------

/// A single edge for the active-edge-table algorithm, stored in float for
/// sub-pixel accuracy.
#[derive(Clone, Debug)]
pub(crate) struct Edge {
    /// Current X position at the current scanline's top.
    x: f32,
    /// X increment per scanline (dx/dy).
    dx: f32,
    /// Scanline at which this edge ends (exclusive).
    y_max: i32,
    /// Winding contribution: +1 for upward, -1 for downward (used by
    /// non-zero winding rule).
    winding: i32,
}

// ---------------------------------------------------------------------------
// Rasterizer scratch buffers — reused across fills to avoid per-polygon alloc
// ---------------------------------------------------------------------------

/// Scratch buffers owned by a rasterizer, reused across polygon fills.
///
/// Call [`RasterizerScratch::clear`] at the start of each fill instead of
/// creating fresh `Vec`s.
pub struct RasterizerScratch {
    /// Global edge table (y_start, Edge) pairs for the current polygon.
    pub(crate) global_edges: Vec<(i32, Edge)>,
    /// Active edge table for the current scanline.
    pub(crate) active: Vec<Edge>,
}

impl RasterizerScratch {
    /// Allocate empty scratch buffers.
    pub fn new() -> Self {
        Self {
            global_edges: Vec::new(),
            active: Vec::new(),
        }
    }

    /// Clear both buffers for the next polygon fill (no heap deallocation).
    pub fn clear(&mut self) {
        self.global_edges.clear();
        self.active.clear();
    }
}

impl Default for RasterizerScratch {
    fn default() -> Self {
        Self::new()
    }
}

/// A scanline rasterizer that owns reusable scratch buffers so per-polygon
/// heap allocation is avoided.
///
/// Use [`Rasterizer::fill_polygon`] / [`Rasterizer::fill_polygon_clipped`]
/// in performance-critical loops. The free-standing functions in this module
/// delegate here and are kept for API stability.
pub struct Rasterizer {
    scratch: RasterizerScratch,
}

impl Rasterizer {
    /// Create a new rasterizer with empty scratch buffers.
    pub fn new() -> Self {
        Self {
            scratch: RasterizerScratch::new(),
        }
    }

    /// Fill a polygon into `fb`, reusing internal scratch buffers.
    pub fn fill_polygon(
        &mut self,
        fb: &mut Framebuffer,
        points: &[(f32, f32)],
        color: Color,
        fill_rule: FillRule,
        aa: bool,
    ) {
        fill_polygon_with_scratch(fb, points, color, fill_rule, aa, &mut self.scratch);
    }

    /// Fill a polygon into `fb`, clipped to `clip`, reusing internal scratch.
    pub fn fill_polygon_clipped(
        &mut self,
        fb: &mut Framebuffer,
        points: &[(f32, f32)],
        color: Color,
        fill_rule: FillRule,
        aa: bool,
        clip: crate::clip::ClipRect,
    ) {
        fill_polygon_clipped_with_scratch(
            fb,
            points,
            color,
            fill_rule,
            aa,
            clip,
            &mut self.scratch,
        );
    }
}

impl Default for Rasterizer {
    fn default() -> Self {
        Self::new()
    }
}

/// Build the global edge table from a polygon vertex list, appending into `out`.
///
/// Each consecutive pair of vertices forms an edge; the last vertex connects
/// back to the first to close the polygon. Horizontal edges (dy == 0) are
/// skipped. `out` is *not* cleared by this function — callers must clear it
/// before calling if a fresh table is needed.
fn build_edges_into(points: &[(f32, f32)], out: &mut Vec<(i32, Edge)>) {
    let n = points.len();
    if n < 2 {
        return;
    }
    out.reserve(n);
    for i in 0..n {
        let (x0, y0) = points[i];
        let (x1, y1) = points[(i + 1) % n];
        if (y0 - y1).abs() < f32::EPSILON {
            // Horizontal — skip.
            continue;
        }
        let (top_y, bot_y, top_x, bot_x, winding) = if y0 < y1 {
            (y0, y1, x0, x1, 1i32)
        } else {
            (y1, y0, x1, x0, -1i32)
        };
        let dy = bot_y - top_y;
        let dx = (bot_x - top_x) / dy;
        let y_start = top_y.ceil() as i32;
        // Sub-pixel correction: move x to the y_start scanline centre.
        let x_at_start = top_x + dx * (y_start as f32 - top_y);
        let y_max = bot_y.ceil() as i32;
        out.push((
            y_start,
            Edge {
                x: x_at_start,
                dx,
                y_max,
                winding,
            },
        ));
    }
}

/// Compute the alpha (coverage) for a single pixel column within a span,
/// given supersample coverage fraction.
///
/// This is a simple closed-form computation: sample 8 sub-rows per pixel
/// to get fractional coverage at the span boundary. The interior receives 1.0.
#[inline]
fn span_coverage(left: f32, right: f32, px: f32) -> f32 {
    // Pixel occupies [px, px+1).
    let pl = px;
    let pr = px + 1.0;
    if right <= pl || left >= pr {
        return 0.0;
    }
    let cl = left.max(pl);
    let cr = right.min(pr);
    (cr - cl).clamp(0.0, 1.0)
}

/// Core fill implementation that reuses caller-provided scratch buffers.
fn fill_polygon_with_scratch(
    fb: &mut Framebuffer,
    points: &[(f32, f32)],
    color: Color,
    fill_rule: FillRule,
    aa: bool,
    scratch: &mut RasterizerScratch,
) {
    if points.len() < 3 {
        return;
    }

    // Bounding box.
    let (mut min_y, mut max_y) = (f32::INFINITY, f32::NEG_INFINITY);
    for &(_, y) in points {
        if y < min_y {
            min_y = y;
        }
        if y > max_y {
            max_y = y;
        }
    }
    // `as i32` on floats saturates to i32::MIN/MAX (stable Rust cast
    // semantics), so these stay finite even for +-inf or absurd vertex
    // coordinates — but the *range* itself can still span billions of rows.
    let raw_y_start = min_y.floor() as i32;
    let raw_y_end = max_y.ceil() as i32;

    // Clamp the scanline range to the framebuffer height so a wildly
    // out-of-range vertex Y cannot force the fill loop below to run
    // billions of empty iterations. `height_i32` itself is clamped first so
    // the `clamp` calls can never overflow for a (hypothetical) oversized
    // framebuffer.
    let height_i32 = fb.height().min(i32::MAX as u32) as i32;
    let y_start = raw_y_start.clamp(0, height_i32);
    let y_end = raw_y_end.clamp(y_start, height_i32);

    // Build global edge table into scratch buffer.
    scratch.clear();
    build_edges_into(points, &mut scratch.global_edges);

    // Sort global edge table by y_start ascending, then by x.
    scratch.global_edges.sort_by(|a, b| {
        a.0.cmp(&b.0).then(
            a.1.x
                .partial_cmp(&b.1.x)
                .unwrap_or(core::cmp::Ordering::Equal),
        )
    });

    let mut gi = 0usize;

    // Fast-forward: activate every edge whose (unclamped) `y_start` lies
    // above the clamped `y_start`, advancing its X to the clamped row
    // directly via the edge slope. This is O(edge count), not O(rows), so a
    // polygon whose top is far above the clamped range never costs more
    // than one pass over its edges, while the visible fill is unaffected.
    while gi < scratch.global_edges.len() && scratch.global_edges[gi].0 < y_start {
        let (edge_y_start, edge) = &scratch.global_edges[gi];
        if edge.y_max > y_start {
            let mut e = edge.clone();
            e.x += e.dx * (y_start - edge_y_start) as f32;
            scratch.active.push(e);
        }
        gi += 1;
    }

    for y in y_start..y_end {
        // Add edges whose y_start == y.
        while gi < scratch.global_edges.len() && scratch.global_edges[gi].0 == y {
            scratch.active.push(scratch.global_edges[gi].1.clone());
            gi += 1;
        }

        // Remove expired edges.
        scratch.active.retain(|e| e.y_max > y);

        // Sort active edges by current x.
        scratch
            .active
            .sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap_or(core::cmp::Ordering::Equal));

        // Fill spans using the chosen fill rule.
        fill_spans(
            fb,
            &scratch.active,
            y as u32,
            y as f32,
            color,
            fill_rule,
            aa,
        );

        // Advance active edges.
        for e in &mut scratch.active {
            e.x += e.dx;
        }
    }
}

/// Fill a polygon (closed contour) defined by `points` into `fb`.
///
/// `points` is interpreted as an ordered list of (x, y) vertices; the polygon
/// is implicitly closed (last → first). Uses a vertical-supersample AET for
/// sub-pixel AA.
///
/// Does nothing if there are fewer than 3 points.
///
/// For tight loops over many polygons, prefer [`Rasterizer::fill_polygon`]
/// which reuses scratch buffers across calls.
pub fn fill_polygon(
    fb: &mut Framebuffer,
    points: &[(f32, f32)],
    color: Color,
    fill_rule: FillRule,
    aa: bool,
) {
    let mut scratch = RasterizerScratch::new();
    fill_polygon_with_scratch(fb, points, color, fill_rule, aa, &mut scratch);
}

/// Process active edges for one scanline using the chosen fill rule.
fn fill_spans(
    fb: &mut Framebuffer,
    active: &[Edge],
    y: u32,
    _y_float: f32,
    color: Color,
    fill_rule: FillRule,
    aa: bool,
) {
    if y >= fb.height() || active.is_empty() {
        return;
    }

    match fill_rule {
        FillRule::EvenOdd => fill_even_odd(fb, active, y, color, aa),
        FillRule::NonZero => fill_non_zero(fb, active, y, color, aa),
    }
}

/// Even-odd rule: pairs of edges delimit filled spans.
fn fill_even_odd(fb: &mut Framebuffer, active: &[Edge], y: u32, color: Color, aa: bool) {
    let mut i = 0;
    while i + 1 < active.len() {
        let left = active[i].x;
        let right = active[i + 1].x;
        if right > left {
            paint_span(fb, left, right, y, color, aa);
        }
        i += 2;
    }
}

/// Non-zero winding rule: accumulate winding; fill while winding != 0.
fn fill_non_zero(fb: &mut Framebuffer, active: &[Edge], y: u32, color: Color, aa: bool) {
    let mut winding = 0i32;
    let mut fill_start: Option<f32> = None;

    for edge in active {
        let prev_winding = winding;
        winding += edge.winding;

        if prev_winding == 0 && winding != 0 {
            // Entering a filled region.
            fill_start = Some(edge.x);
        } else if prev_winding != 0 && winding == 0 {
            // Leaving a filled region.
            if let Some(start) = fill_start.take() {
                let end = edge.x;
                if end > start {
                    paint_span(fb, start, end, y, color, aa);
                }
            }
        }
    }
}

/// Paint a horizontal span `[left, right)` on row `y`, with optional edge AA.
fn paint_span(fb: &mut Framebuffer, left: f32, right: f32, y: u32, color: Color, aa: bool) {
    if y >= fb.height() {
        return;
    }
    // Clamp the span to the framebuffer width up front. `left`/`right` are
    // raw float edge coordinates that can be arbitrarily large (an extreme
    // edge slope or vertex X), so without this the `x0..x1` loop below could
    // run billions of no-op iterations before a per-pixel bounds check ever
    // discarded anything.
    let width_i32 = fb.width().min(i32::MAX as u32) as i32;
    let x0 = (left.floor() as i32).clamp(0, width_i32);
    let x1 = (right.ceil() as i32).clamp(x0, width_i32);
    let Color(cr, cg, cb, ca) = color;

    for px in x0..x1 {
        // `px` is guaranteed to lie in `[0, fb.width())` by the clamp above.
        let coverage = if aa {
            span_coverage(left, right, px as f32)
        } else {
            // Hard edge: any pixel whose centre is inside the span.
            let centre = px as f32 + 0.5;
            if centre >= left && centre < right {
                1.0
            } else {
                0.0
            }
        };
        if coverage <= 0.0 {
            continue;
        }
        let alpha = (ca as f32 * coverage).round() as u8;
        fb.blend(
            px as u32,
            y,
            crate::framebuffer::pack_rgba(cr, cg, cb, alpha),
        );
    }
}

/// Core clipped-fill implementation that reuses caller-provided scratch buffers.
fn fill_polygon_clipped_with_scratch(
    fb: &mut Framebuffer,
    points: &[(f32, f32)],
    color: Color,
    fill_rule: FillRule,
    aa: bool,
    clip: crate::clip::ClipRect,
    scratch: &mut RasterizerScratch,
) {
    if points.len() < 3 {
        return;
    }

    // Bounding box.
    let (mut min_y, mut max_y) = (f32::INFINITY, f32::NEG_INFINITY);
    for &(_, y) in points {
        if y < min_y {
            min_y = y;
        }
        if y > max_y {
            max_y = y;
        }
    }
    // `as i32` on floats saturates to i32::MIN/MAX, so these stay finite
    // even for +-inf or absurd vertex coordinates — but the *range* can
    // still span billions of rows before being intersected with the clip.
    let raw_y_start = min_y.floor() as i32;
    let raw_y_end = max_y.ceil() as i32;

    // Clamp the scanline range to both the clip rectangle and the
    // framebuffer height so neither a wildly out-of-range vertex Y nor an
    // oversized clip rectangle can force the fill loop below to run
    // billions of empty iterations. `height_i32` (and the clip bounds
    // derived from it) are clamped first so none of the arithmetic here can
    // overflow.
    let height_i32 = fb.height().min(i32::MAX as u32) as i32;
    let clip_y0 = clip.y0.clamp(0, height_i32 as i64) as i32;
    let clip_y1 = clip.y1.clamp(0, height_i32 as i64) as i32;
    let y_clip_start = raw_y_start.max(clip_y0);
    let y_end = raw_y_end.min(clip_y1);

    scratch.clear();
    build_edges_into(points, &mut scratch.global_edges);
    scratch.global_edges.sort_by(|a, b| {
        a.0.cmp(&b.0).then(
            a.1.x
                .partial_cmp(&b.1.x)
                .unwrap_or(core::cmp::Ordering::Equal),
        )
    });

    let mut gi = 0usize;

    // Fast-forward: activate every edge whose (unclamped) `y_start` lies
    // above the clamped start row, advancing its X to that row directly via
    // the edge slope instead of visiting each intermediate row. O(edge
    // count), not O(rows).
    while gi < scratch.global_edges.len() && scratch.global_edges[gi].0 < y_clip_start {
        let (edge_y_start, edge) = &scratch.global_edges[gi];
        if edge.y_max > y_clip_start {
            let mut e = edge.clone();
            e.x += e.dx * (y_clip_start - edge_y_start) as f32;
            scratch.active.push(e);
        }
        gi += 1;
    }

    for y in y_clip_start..y_end {
        while gi < scratch.global_edges.len() && scratch.global_edges[gi].0 == y {
            scratch.active.push(scratch.global_edges[gi].1.clone());
            gi += 1;
        }
        scratch.active.retain(|e| e.y_max > y);
        scratch
            .active
            .sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap_or(core::cmp::Ordering::Equal));
        fill_spans_clipped(fb, &scratch.active, y as u32, color, fill_rule, aa, &clip);
        for e in &mut scratch.active {
            e.x += e.dx;
        }
    }
}

/// Fill a polygon clipped to a [`crate::clip::ClipRect`].
///
/// This is the same as [`fill_polygon`] but additionally clips to `clip`.
///
/// For tight loops over many polygons, prefer [`Rasterizer::fill_polygon_clipped`]
/// which reuses scratch buffers across calls.
pub fn fill_polygon_clipped(
    fb: &mut Framebuffer,
    points: &[(f32, f32)],
    color: Color,
    fill_rule: FillRule,
    aa: bool,
    clip: crate::clip::ClipRect,
) {
    let mut scratch = RasterizerScratch::new();
    fill_polygon_clipped_with_scratch(fb, points, color, fill_rule, aa, clip, &mut scratch);
}

/// Like `fill_spans` but clips each span to `clip`.
fn fill_spans_clipped(
    fb: &mut Framebuffer,
    active: &[Edge],
    y: u32,
    color: Color,
    fill_rule: FillRule,
    aa: bool,
    clip: &crate::clip::ClipRect,
) {
    if y >= fb.height() || (y as i64) < clip.y0 || (y as i64) >= clip.y1 || active.is_empty() {
        return;
    }
    match fill_rule {
        FillRule::EvenOdd => {
            let mut i = 0;
            while i + 1 < active.len() {
                let left = active[i].x.max(clip.x0 as f32);
                let right = active[i + 1].x.min(clip.x1 as f32);
                if right > left {
                    paint_span(fb, left, right, y, color, aa);
                }
                i += 2;
            }
        }
        FillRule::NonZero => {
            let mut winding = 0i32;
            let mut fill_start: Option<f32> = None;
            for edge in active {
                let prev_winding = winding;
                winding += edge.winding;
                if prev_winding == 0 && winding != 0 {
                    fill_start = Some(edge.x.max(clip.x0 as f32));
                } else if prev_winding != 0 && winding == 0 {
                    if let Some(start) = fill_start.take() {
                        let end = edge.x.min(clip.x1 as f32);
                        if end > start {
                            paint_span(fb, start, end, y, color, aa);
                        }
                    }
                }
            }
        }
    }
}

/// Fill a triangle defined by three points into `fb` with coverage AA.
///
/// Delegates to [`fill_polygon`] with three vertices.
pub fn fill_triangle(
    fb: &mut Framebuffer,
    p0: (f32, f32),
    p1: (f32, f32),
    p2: (f32, f32),
    color: Color,
) {
    fill_polygon(fb, &[p0, p1, p2], color, FillRule::NonZero, true);
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn fresh(w: u32, h: u32) -> Framebuffer {
        Framebuffer::with_fill(w, h, Color(0, 0, 0, 255))
    }

    #[test]
    fn triangle_fill_coverage() {
        let mut fb = fresh(20, 20);
        // Fill a large triangle covering roughly half the buffer.
        fill_triangle(
            &mut fb,
            (0.0, 0.0),
            (20.0, 0.0),
            (10.0, 20.0),
            Color(255, 255, 255, 255),
        );
        // Count non-background pixels.
        let mut count = 0u32;
        for y in 0..20 {
            for x in 0..20 {
                let (r, _, _, _) = fb.get_rgba(x, y).unwrap_or((0, 0, 0, 0));
                if r > 0 {
                    count += 1;
                }
            }
        }
        // The triangle should fill at least 50 pixels in a 20x20 buffer.
        assert!(count >= 50, "expected >= 50 filled pixels, got {count}");
    }

    #[test]
    fn polygon_fill_even_odd() {
        // 5-pointed star: a self-intersecting polygon where even-odd leaves the
        // center pentagon empty, while non-zero fills it.
        //
        // Use a large star (radius=30, centre=35,35) so individual arms are wide.
        let cx = 35.0f32;
        let cy = 35.0f32;
        let r = 30.0f32;
        let star: Vec<(f32, f32)> = (0..5)
            .map(|i| {
                // "Skip-one" order produces a 5-pointed star.
                let angle = std::f32::consts::PI * (2.0 * (2 * i) as f32 / 5.0 - 0.5);
                (cx + r * angle.cos(), cy + r * angle.sin())
            })
            .collect();

        let mut fb_eo = fresh(70, 70);
        let mut fb_nz = fresh(70, 70);
        fill_polygon(
            &mut fb_eo,
            &star,
            Color(255, 0, 0, 255),
            FillRule::EvenOdd,
            false,
        );
        fill_polygon(
            &mut fb_nz,
            &star,
            Color(255, 0, 0, 255),
            FillRule::NonZero,
            false,
        );

        // The top arm of the star spans roughly x=[32,38] at y=8 (well inside the arm).
        let (r_eo_tip, _, _, _) = fb_eo.get_rgba(35, 8).unwrap_or((0, 0, 0, 0));
        let (r_nz_tip, _, _, _) = fb_nz.get_rgba(35, 8).unwrap_or((0, 0, 0, 0));
        assert!(r_eo_tip > 0, "EvenOdd: star arm should be painted");
        assert!(r_nz_tip > 0, "NonZero: star arm should be painted");

        // Center pentagon: NonZero should fill it; EvenOdd should leave it empty.
        let (r_nz_ctr, _, _, _) = fb_nz.get_rgba(35, 35).unwrap_or((0, 0, 0, 0));
        assert!(r_nz_ctr > 0, "NonZero: star center must be filled");
        let (r_eo_ctr, _, _, _) = fb_eo.get_rgba(35, 35).unwrap_or((0, 0, 0, 0));
        assert_eq!(
            r_eo_ctr, 0,
            "EvenOdd: star center should be a hole (r={r_eo_ctr})"
        );
    }

    #[test]
    fn fill_rect_via_polygon() {
        let mut fb = fresh(10, 10);
        let pts = [(2.0f32, 2.0), (8.0, 2.0), (8.0, 8.0), (2.0, 8.0)];
        fill_polygon(
            &mut fb,
            &pts,
            Color(0, 255, 0, 255),
            FillRule::NonZero,
            false,
        );
        // Centre should be green.
        assert_eq!(fb.get_rgba(5, 5), Some((0, 255, 0, 255)));
        // Corner outside should be black.
        assert_eq!(fb.get_rgba(0, 0), Some((0, 0, 0, 255)));
    }

    #[test]
    fn fill_rule_noop_on_empty_polygon() {
        let mut fb = fresh(5, 5);
        fill_polygon(
            &mut fb,
            &[],
            Color(255, 0, 0, 255),
            FillRule::NonZero,
            false,
        );
        // Nothing should change.
        assert_eq!(fb.get_rgba(2, 2), Some((0, 0, 0, 255)));
    }

    // -----------------------------------------------------------------------
    // S2: scanline buffer reuse regression test
    // -----------------------------------------------------------------------

    #[test]
    fn test_scanline_reuse_output_identical() {
        // Regression test: filling a triangle into a 100×100 framebuffer twice
        // using the `Rasterizer` (scratch-reuse path) must produce byte-identical
        // results across both calls.  This verifies that `scratch.clear()` fully
        // resets state between fills so stale edges never contaminate the next fill.
        let triangle: &[(f32, f32)] = &[(10.0, 90.0), (50.0, 10.0), (90.0, 90.0)];
        let color = Color(200, 100, 50, 255);

        // First fill — using the reuse-scratch Rasterizer.
        let mut fb1 = fresh(100, 100);
        let mut ras = Rasterizer::new();
        ras.fill_polygon(&mut fb1, triangle, color, FillRule::NonZero, true);

        // Second fill into a fresh buffer — same Rasterizer, scratch is reused.
        let mut fb2 = fresh(100, 100);
        ras.fill_polygon(&mut fb2, triangle, color, FillRule::NonZero, true);

        // Results must be byte-identical.
        for y in 0..100 {
            for x in 0..100 {
                let p1 = fb1.get_rgba(x, y);
                let p2 = fb2.get_rgba(x, y);
                assert_eq!(
                    p1, p2,
                    "pixel ({x},{y}) differs: first={p1:?} second={p2:?}"
                );
            }
        }

        // Also verify the public free-fn path gives the same pixels (API stability).
        let mut fb3 = fresh(100, 100);
        fill_polygon(&mut fb3, triangle, color, FillRule::NonZero, true);
        for y in 0..100 {
            for x in 0..100 {
                let p1 = fb1.get_rgba(x, y);
                let p3 = fb3.get_rgba(x, y);
                assert_eq!(
                    p1, p3,
                    "pixel ({x},{y}): Rasterizer={p1:?} vs free fn={p3:?}"
                );
            }
        }
    }

    // -----------------------------------------------------------------------
    // Security regression: unclamped raster spans (billions-of-iterations DoS)
    // -----------------------------------------------------------------------

    #[test]
    fn fill_polygon_far_out_of_bounds_is_clamped_and_fast() {
        // A quad whose vertices sit ~1e9 units outside a tiny framebuffer.
        // Before the vertical/horizontal span clamps were added, the scanline
        // loop iterated the *raw* vertex extent (billions of rows/columns)
        // instead of the framebuffer's actual size, so this call would take
        // an unreasonable amount of time (effectively a DoS from one
        // attacker-controlled coordinate). With the fix, the fill must be
        // bounded by the framebuffer's own dimensions and complete quickly.
        let mut fb = fresh(10, 10);
        let huge = 1.0e9_f32;
        let pts = [(-huge, -huge), (huge, -huge), (huge, huge), (-huge, huge)];
        let start = std::time::Instant::now();
        fill_polygon(
            &mut fb,
            &pts,
            Color(255, 0, 0, 255),
            FillRule::NonZero,
            false,
        );
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_secs(2),
            "fill_polygon took {elapsed:?} for far-out-of-bounds coordinates; \
             the vertical/horizontal span is not being clamped to the framebuffer"
        );
        // The quad fully covers the framebuffer, so every in-bounds pixel
        // must be painted — clamping must not silently drop the fill.
        for y in 0..10 {
            for x in 0..10 {
                assert_eq!(
                    fb.get_rgba(x, y),
                    Some((255, 0, 0, 255)),
                    "pixel ({x},{y}) should be filled"
                );
            }
        }
    }

    #[test]
    fn fill_polygon_clipped_far_out_of_bounds_is_clamped_and_fast() {
        // Same DoS scenario as above but through the clip-aware fill path,
        // which has its own (previously unclamped) vertical loop.
        let mut fb = fresh(10, 10);
        let huge = 1.0e9_f32;
        let pts = [(-huge, -huge), (huge, -huge), (huge, huge), (-huge, huge)];
        let clip = crate::clip::ClipRect::full(10, 10);
        let start = std::time::Instant::now();
        fill_polygon_clipped(
            &mut fb,
            &pts,
            Color(0, 0, 255, 255),
            FillRule::NonZero,
            false,
            clip,
        );
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_secs(2),
            "fill_polygon_clipped took {elapsed:?} for far-out-of-bounds coordinates"
        );
        for y in 0..10 {
            for x in 0..10 {
                assert_eq!(fb.get_rgba(x, y), Some((0, 0, 255, 255)));
            }
        }
    }

    #[test]
    fn paint_span_far_out_of_bounds_x_is_clamped() {
        // Directly exercises `paint_span`'s horizontal clamp: a span whose
        // edges are far outside the framebuffer width must not attempt to
        // iterate that raw (billions-wide) pixel range.
        let mut fb = fresh(8, 8);
        let start = std::time::Instant::now();
        paint_span(&mut fb, -1.0e9, 1.0e9, 3, Color(10, 20, 30, 255), false);
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_secs(2),
            "paint_span took {elapsed:?} for a far-out-of-bounds span"
        );
        // Row 3 should be fully painted (span covers the whole width) and
        // every other row must remain untouched.
        for x in 0..8 {
            assert_eq!(fb.get_rgba(x, 3), Some((10, 20, 30, 255)));
        }
        assert_eq!(fb.get_rgba(0, 0), Some((0, 0, 0, 255)));
    }

    #[test]
    fn fill_polygon_partial_offscreen_top_still_paints_visible_rows() {
        // Regression for the fast-forward logic added alongside the vertical
        // clamp: a shape that starts well above the framebuffer but extends
        // into the visible area must still be filled correctly for the
        // visible rows (clamping the loop start must not skip edges that
        // were already active when the visible range begins).
        let mut fb = fresh(10, 10);
        let pts = [(2.0f32, -1000.0), (8.0, -1000.0), (8.0, 5.0), (2.0, 5.0)];
        fill_polygon(
            &mut fb,
            &pts,
            Color(0, 255, 0, 255),
            FillRule::NonZero,
            false,
        );
        for y in 0..5 {
            assert_eq!(
                fb.get_rgba(5, y),
                Some((0, 255, 0, 255)),
                "row {y} should be filled by the far-off-screen rectangle"
            );
        }
        // Below the rectangle's bottom edge (y=5) should be untouched.
        assert_eq!(fb.get_rgba(5, 9), Some((0, 0, 0, 255)));
    }
}