grafo 0.16.0

A GPU-accelerated rendering library for Rust
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
/// Visual regression tests for the Grafo renderer.
///
/// These tests use the headless renderer to render scenes into a pixel buffer,
/// then validate specific pixel locations against expected colors.
///
/// Run with:   cargo test --test visual_regression
use futures::executor::block_on;
use grafo_test_scenes::{build_main_scene, check_pixels, CANVAS_HEIGHT, CANVAS_WIDTH};

/// Creates a headless renderer, returning `None` (and printing a skip message)
/// when no suitable GPU adapter is available.
fn create_headless_renderer() -> Option<grafo::Renderer<'static>> {
    create_headless_renderer_with_size_and_scale((CANVAS_WIDTH, CANVAS_HEIGHT), 1.0)
}

fn create_headless_renderer_with_size_and_scale(
    physical_size: (u32, u32),
    scale_factor: f64,
) -> Option<grafo::Renderer<'static>> {
    match block_on(grafo::Renderer::try_new_headless(
        physical_size,
        scale_factor,
    )) {
        Ok(r) => Some(r),
        Err(grafo::RendererCreationError::AdapterNotAvailable(_)) => {
            println!("Skipping test: no suitable GPU adapter available.");
            None
        }
        Err(e) => panic!("Failed to create headless renderer: {e}"),
    }
}

fn assert_pixels_match(pixel_buffer: &[u8], expectations: &[grafo_test_scenes::PixelExpectation]) {
    let failures = check_pixels(pixel_buffer, CANVAS_WIDTH, CANVAS_HEIGHT, expectations);
    if !failures.is_empty() {
        let message = format!(
            "{} pixel expectation(s) failed:\n{}",
            failures.len(),
            failures.join("\n"),
        );
        panic!("{message}");
    }
}

fn read_pixel_rgba(pixel_buffer: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] {
    let stride = (width as usize) * 4;
    let offset = (y as usize) * stride + (x as usize) * 4;

    [
        pixel_buffer[offset + 2],
        pixel_buffer[offset + 1],
        pixel_buffer[offset],
        pixel_buffer[offset + 3],
    ]
}

/// Main regression test — renders all shared visual-regression tiles.
#[test]
fn main_scene_pixel_expectations() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    let expectations = build_main_scene(&mut renderer);

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let failures = check_pixels(&pixel_buffer, CANVAS_WIDTH, CANVAS_HEIGHT, &expectations);
    if !failures.is_empty() {
        let message = format!(
            "{} pixel expectation(s) failed:\n{}",
            failures.len(),
            failures.join("\n"),
        );
        panic!("{message}");
    }
}

/// Regression test — empty draw queue should not crash.
#[test]
fn empty_draw_queue() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    // Render with nothing in the draw queue
    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let bytes_per_pixel = 4;
    let expected_length = (CANVAS_WIDTH as usize) * (CANVAS_HEIGHT as usize) * bytes_per_pixel;
    assert_eq!(
        pixel_buffer.len(),
        expected_length,
        "Pixel buffer length should equal width * height * {bytes_per_pixel}",
    );

    // Every pixel should be fully transparent (all bytes zero)
    assert!(
        pixel_buffer.iter().all(|&byte| byte == 0),
        "Empty scene should produce a fully transparent (all-zero) buffer",
    );
}

/// Regression test — single root shape with no children should render correctly.
#[test]
fn single_root_no_children() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    let shape = grafo::Shape::rect([(10.0, 10.0), (100.0, 100.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            shape,
            None,
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(200, 50, 50)),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let expectations = vec![
        grafo_test_scenes::PixelExpectation::opaque(55, 55, 200, 50, 50, "center_red"),
        grafo_test_scenes::PixelExpectation::transparent(5, 5, "outside_rect"),
    ];

    assert_pixels_match(&pixel_buffer, &expectations);
}

/// Regression test — OriginalSize texture fit uses physical pixels, not logical units.
#[test]
fn original_size_texture_fit_uses_physical_pixels_on_hidpi() {
    let physical_size = (200, 200);
    let scale_factor = 2.0;
    let Some(mut renderer) =
        create_headless_renderer_with_size_and_scale(physical_size, scale_factor)
    else {
        return;
    };

    let green_texture_id = 9_001u64;
    let green_texture_with_transparent_border_20x20 = (0..20u32)
        .flat_map(|y| {
            (0..20u32).flat_map(move |x| {
                if x == 0 || x == 19 || y == 0 || y == 19 {
                    [0u8, 0u8, 0u8, 0u8]
                } else {
                    [0u8, 255u8, 0u8, 255u8]
                }
            })
        })
        .collect::<Vec<_>>();
    renderer.texture_manager().allocate_texture_with_data(
        green_texture_id,
        (20, 20),
        &green_texture_with_transparent_border_20x20,
    );

    let shape = grafo::Shape::rect([(10.0, 10.0), (70.0, 70.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            shape,
            None,
            None,
            grafo::ShapeDrawCommandOptions::new()
                .background_texture(
                    grafo::ShapeTextureOptions::new(green_texture_id)
                        .fit_mode(grafo::ShapeTextureFitMode::OriginalSize),
                )
                .color(grafo::Color::WHITE),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let expectations = vec![
        grafo_test_scenes::PixelExpectation::opaque(
            30,
            30,
            0,
            255,
            0,
            "inside_20px_physical_texture_region",
        ),
        grafo_test_scenes::PixelExpectation::opaque(
            60,
            30,
            255,
            255,
            255,
            "outside_texture_region_inside_shape",
        ),
        grafo_test_scenes::PixelExpectation::transparent(5, 5, "outside_shape"),
    ];

    let failures = check_pixels(
        &pixel_buffer,
        physical_size.0,
        physical_size.1,
        &expectations,
    );
    if !failures.is_empty() {
        let message = format!(
            "{} pixel expectation(s) failed:\n{}",
            failures.len(),
            failures.join("\n"),
        );
        panic!("{message}");
    }
}

/// Regression test — scissor-only clipping rect clips children without drawing itself.
#[test]
fn clipping_rect_clips_child_without_visible_surface() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    let clip_rect_id = renderer
        .add_clipping_rect(
            [(20.0, 20.0), (80.0, 80.0)],
            None,
            None::<grafo::TransformInstance>,
            true,
        )
        .unwrap();
    let child = grafo::Shape::rect([(0.0, 0.0), (100.0, 100.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            child,
            Some(clip_rect_id),
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(200, 50, 50)),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let expectations = vec![
        grafo_test_scenes::PixelExpectation::opaque(50, 50, 200, 50, 50, "inside_clip_rect"),
        grafo_test_scenes::PixelExpectation::transparent(10, 50, "left_of_clip_rect"),
        grafo_test_scenes::PixelExpectation::transparent(50, 10, "above_clip_rect"),
        grafo_test_scenes::PixelExpectation::transparent(90, 50, "right_of_clip_rect"),
        grafo_test_scenes::PixelExpectation::transparent(50, 90, "below_clip_rect"),
    ];

    assert_pixels_match(&pixel_buffer, &expectations);
}

/// Regression test — partially offscreen backdrop captures clear untouched pooled pixels.
#[test]
fn partially_offscreen_backdrop_capture_clears_reused_texture_space() {
    let physical_size = (100, 80);
    let Some(mut renderer) = create_headless_renderer_with_size_and_scale(physical_size, 1.0)
    else {
        return;
    };

    const AVERAGE_WITH_RIGHT_NEIGHBOR_EFFECT_ID: u64 = 9_101;
    const AVERAGE_WITH_RIGHT_NEIGHBOR_WGSL: &str = r#"
const LOOKAHEAD_UV: vec2<f32> = vec2<f32>(0.4, 0.0);

@fragment
fn effect_main(@location(0) uv: vec2<f32>) -> @location(0) vec4<f32> {
    let base = textureSample(t_input, s_input, uv);
    let lookahead = textureSample(t_input, s_input, uv + LOOKAHEAD_UV);
    return 0.5 * (base + lookahead);
}
"#;

    renderer
        .load_effect(
            AVERAGE_WITH_RIGHT_NEIGHBOR_EFFECT_ID,
            &[AVERAGE_WITH_RIGHT_NEIGHBOR_WGSL],
        )
        .expect("Failed to compile deterministic backdrop test effect");

    let seeded_blue_panel =
        grafo::Shape::rect([(20.0, 20.0), (60.0, 60.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            seeded_blue_panel.clone(),
            None,
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(40, 40, 220)),
        )
        .unwrap();
    let seeded_blue_panel_id = renderer
        .add_shape(
            seeded_blue_panel,
            None,
            None,
            grafo::ShapeDrawCommandOptions::new(),
        )
        .unwrap();
    renderer
        .set_shape_backdrop_effect(
            seeded_blue_panel_id,
            AVERAGE_WITH_RIGHT_NEIGHBOR_EFFECT_ID,
            &[],
            grafo::BackdropEffectConfig::new().capture_area(
                grafo::BackdropCaptureArea::ScreenRect([(20.0, 20.0), (60.0, 60.0)]),
            ),
        )
        .unwrap();

    let mut seeded_frame: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut seeded_frame);

    renderer.clear_draw_queue();

    let visible_red_source =
        grafo::Shape::rect([(70.0, 20.0), (100.0, 60.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            visible_red_source,
            None,
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(220, 40, 40)),
        )
        .unwrap();

    let partially_offscreen_panel =
        grafo::Shape::rect([(70.0, 20.0), (100.0, 60.0)], grafo::Stroke::default());
    let partially_offscreen_panel_id = renderer
        .add_shape(
            partially_offscreen_panel,
            None,
            None,
            grafo::ShapeDrawCommandOptions::new(),
        )
        .unwrap();
    renderer
        .set_shape_backdrop_effect(
            partially_offscreen_panel_id,
            AVERAGE_WITH_RIGHT_NEIGHBOR_EFFECT_ID,
            &[],
            grafo::BackdropEffectConfig::new().capture_area(
                grafo::BackdropCaptureArea::ScreenRect([(70.0, 20.0), (110.0, 60.0)]),
            ),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let sampled_pixel = read_pixel_rgba(&pixel_buffer, physical_size.0, 86, 40);
    assert!(
        sampled_pixel[0] > 80,
        "expected visible red contribution after clearing untouched capture space, got {:?}",
        sampled_pixel
    );
    assert!(
        sampled_pixel[2] <= 50,
        "expected offscreen capture space to stay transparent instead of leaking recycled blue, got {:?}",
        sampled_pixel
    );
    assert!(
        sampled_pixel[3] > 240,
        "expected the cleared backdrop sample to composite back over the visible red source, got {:?}",
        sampled_pixel
    );
}

/// Regression test — standalone clipping rect is a no-op and does not enter shape drawing.
#[test]
fn standalone_clipping_rect_does_not_panic() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    renderer
        .add_clipping_rect(
            [(20.0, 20.0), (80.0, 80.0)],
            None,
            None::<grafo::TransformInstance>,
            true,
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    assert!(
        pixel_buffer.iter().all(|&byte| byte == 0),
        "Standalone clipping rect should not draw any pixels",
    );
}

/// Regression test — unsupported clip-rect transforms are rejected instead of disabling clipping.
#[test]
fn clipping_rect_rejects_non_axis_aligned_transform() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    let clip_rect_id = renderer
        .add_clipping_rect(
            [(20.0, 20.0), (80.0, 80.0)],
            None,
            None::<grafo::TransformInstance>,
            true,
        )
        .unwrap();
    assert!(matches!(
        renderer.add_clipping_rect(
            [(20.0, 20.0), (80.0, 80.0)],
            None,
            Some(grafo::TransformInstance::rotation_z_deg(45.0)),
            true,
        ),
        Err(grafo::DrawCommandError::UnsupportedClipRectTransform)
    ));

    let child = grafo::Shape::rect([(0.0, 0.0), (100.0, 100.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            child,
            Some(clip_rect_id),
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(200, 50, 50)),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let expectations = vec![
        grafo_test_scenes::PixelExpectation::opaque(
            50,
            50,
            200,
            50,
            50,
            "inside_unrotated_clip_rect",
        ),
        grafo_test_scenes::PixelExpectation::transparent(10, 50, "outside_unrotated_clip_rect"),
    ];

    assert_pixels_match(&pixel_buffer, &expectations);
}

/// Smoke test — gradient fill should produce non-transparent pixels.
#[test]
fn gradient_fill_basic() {
    use grafo::*;

    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    // Root shape
    let root = Shape::rect([(0.0, 0.0), (100.0, 100.0)], Stroke::default());
    let root_id = renderer
        .add_shape(
            root,
            None,
            None,
            ShapeDrawCommandOptions::new().color(Color::WHITE),
        )
        .unwrap();

    let gradient = Gradient::linear(
        LinearGradientDesc::new(
            LinearGradientLine {
                start: [10.0, 50.0],
                end: [90.0, 50.0],
            },
            [
                GradientStop::at_position(
                    GradientStopOffset::linear_radial(0.0),
                    Color::rgb(255, 0, 0),
                ),
                GradientStop::at_position(
                    GradientStopOffset::linear_radial(1.0),
                    Color::rgb(0, 0, 255),
                ),
            ],
        )
        .with_interpolation(ColorInterpolation::Srgb),
    )
    .expect("valid gradient");

    renderer
        .add_shape(
            Shape::rect([(10.0, 10.0), (90.0, 90.0)], Stroke::default()),
            Some(root_id),
            None,
            ShapeDrawCommandOptions::new().fill(Fill::from(gradient)),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    // Canvas is CANVAS_WIDTH × CANVAS_HEIGHT
    let w = CANVAS_WIDTH;
    let center_x = 50u32;
    let center_y = 50u32;
    let offset = ((center_y * w + center_x) * 4) as usize;
    let b = pixel_buffer[offset];
    let g = pixel_buffer[offset + 1];
    let r = pixel_buffer[offset + 2];
    let a = pixel_buffer[offset + 3];
    // The center of a red-to-blue gradient should not be pure white
    assert!(
        !(r == 255 && g == 255 && b == 255),
        "Center pixel should not be white (got rgba({r},{g},{b},{a})). Gradient is not rendering."
    );
    // Should be opaque
    assert_eq!(a, 255, "Gradient pixel should be opaque");
}

/// Regression test — gradient bind groups must survive pipeline recreation
/// (e.g. MSAA sample count change) without producing validation errors or
/// rendering as white/transparent.
#[test]
fn gradient_survives_pipeline_recreation() {
    use grafo::*;

    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    let gradient = Gradient::linear(
        LinearGradientDesc::new(
            LinearGradientLine {
                start: [10.0, 50.0],
                end: [90.0, 50.0],
            },
            [
                GradientStop::at_position(
                    GradientStopOffset::linear_radial(0.0),
                    Color::rgb(255, 0, 0),
                ),
                GradientStop::at_position(
                    GradientStopOffset::linear_radial(1.0),
                    Color::rgb(0, 0, 255),
                ),
            ],
        )
        .with_interpolation(ColorInterpolation::Srgb),
    )
    .expect("valid gradient");

    renderer
        .add_shape(
            Shape::rect([(10.0, 10.0), (90.0, 90.0)], Stroke::default()),
            None,
            None,
            ShapeDrawCommandOptions::new().fill(Fill::from(gradient)),
        )
        .unwrap();

    // First render — populates and caches the gradient bind group.
    let mut buf = Vec::new();
    renderer.render_to_buffer(&mut buf);

    // Trigger pipeline recreation (swaps bind group layouts).
    renderer.set_msaa_samples(4);

    // Second render — stale bind groups must have been invalidated;
    // the gradient should render correctly against the new layout.
    buf.clear();
    renderer.render_to_buffer(&mut buf);

    let w = CANVAS_WIDTH;
    let cx = 50u32;
    let cy = 50u32;
    let off = ((cy * w + cx) * 4) as usize;
    let (b, g, r, a) = (buf[off], buf[off + 1], buf[off + 2], buf[off + 3]);

    assert_eq!(
        a, 255,
        "Gradient pixel should be opaque after pipeline recreation"
    );
    assert!(
        !(r == 255 && g == 255 && b == 255),
        "Gradient should not be white after pipeline recreation (got rgba({r},{g},{b},{a}))"
    );
    assert!(
        r < 200 && b < 200,
        "Center of red-to-blue gradient should be a purple-ish mix, got rgba({r},{g},{b},{a})"
    );
}

/// Regression test — a solid-colored non-leaf parent drawn immediately after a
/// gradient non-leaf parent on the same StencilIncrement pipeline must NOT
/// inherit the previous parent's gradient bind group.
///
/// We use rounded-rect parents so the renderer takes the stencil-increment path
/// instead of the scissor-optimization path (which only applies to axis-aligned
/// `Shape::Rect`).
///
/// Scene layout:
///
///   gradient_parent  (rounded rect, gradient fill, non-leaf)
///     └─ gradient_child
///   solid_parent     (rounded rect, green solid fill, non-leaf)
///     └─ solid_child
///
/// We check that the center of solid_child is green, not gradient-contaminated.
#[test]
fn stencil_increment_gradient_does_not_leak_to_solid_parent() {
    use grafo::*;

    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    // Full-canvas rect root so all children are visible.
    let root = renderer
        .add_shape(
            Shape::rect(
                [(0.0, 0.0), (CANVAS_WIDTH as f32, CANVAS_HEIGHT as f32)],
                Stroke::default(),
            ),
            None,
            None,
            ShapeDrawCommandOptions::new().color(Color::rgba(0, 0, 0, 0)),
        )
        .unwrap();

    let radii = BorderRadii::new(8.0);

    let gradient = Gradient::linear(
        LinearGradientDesc::new(
            LinearGradientLine {
                start: [10.0, 50.0],
                end: [140.0, 50.0],
            },
            [
                GradientStop::at_position(
                    GradientStopOffset::linear_radial(0.0),
                    Color::rgb(255, 0, 0),
                ),
                GradientStop::at_position(
                    GradientStopOffset::linear_radial(1.0),
                    Color::rgb(0, 0, 255),
                ),
            ],
        )
        .with_interpolation(ColorInterpolation::Srgb),
    )
    .expect("valid gradient");

    // ── Gradient non-leaf parent (rounded rect → stencil path) ───────────
    let gradient_parent = renderer
        .add_shape(
            Shape::rounded_rect([(10.0, 10.0), (140.0, 90.0)], radii, Stroke::default()),
            Some(root),
            None,
            ShapeDrawCommandOptions::new().fill(Fill::from(gradient)),
        )
        .unwrap();

    // Child of gradient parent (makes it non-leaf → StencilIncrement).
    renderer
        .add_shape(
            Shape::rect([(20.0, 20.0), (130.0, 80.0)], Stroke::default()),
            Some(gradient_parent),
            None,
            ShapeDrawCommandOptions::new().color(Color::WHITE),
        )
        .unwrap();

    // ── Solid non-leaf parent (rounded rect → stencil path) ──────────────
    let solid_parent = renderer
        .add_shape(
            Shape::rounded_rect([(160.0, 10.0), (290.0, 90.0)], radii, Stroke::default()),
            Some(root),
            None,
            ShapeDrawCommandOptions::new().color(Color::rgb(0, 200, 0)),
        )
        .unwrap();

    // Child of solid parent (makes it non-leaf → StencilIncrement too).
    renderer
        .add_shape(
            Shape::rect([(170.0, 20.0), (280.0, 80.0)], Stroke::default()),
            Some(solid_parent),
            None,
            ShapeDrawCommandOptions::new().color(Color::rgb(0, 200, 0)),
        )
        .unwrap();

    // ── Render and verify ─────────────────────────────────────────────────
    let mut buf = Vec::new();
    renderer.render_to_buffer(&mut buf);

    // Sample the center of the solid_child rect.
    let w = CANVAS_WIDTH;
    let cx = 225u32; // midpoint of [170, 280]
    let cy = 50u32; // midpoint of [20, 80]
    let off = ((cy * w + cx) * 4) as usize;
    let (b, g, r, a) = (buf[off], buf[off + 1], buf[off + 2], buf[off + 3]);

    // Should be a solid green, not gradient-contaminated.
    assert_eq!(a, 255, "Solid child should be opaque, got alpha={a}");
    assert!(
        g >= 180 && r < 40 && b < 40,
        "Solid child should be green, got rgba({r},{g},{b},{a}). \
         If this is reddish/bluish the gradient leaked from the previous StencilIncrement parent."
    );
}

/// Regression test — touching triangle subpaths in one filled shape should not
/// show an internal AA seam along their shared diagonal.
#[test]
fn multi_subpath_fill_has_no_internal_seam() {
    let Some(mut renderer) = create_headless_renderer() else {
        return;
    };

    let canvas_root = grafo::Shape::rect(
        [(0.0, 0.0), (CANVAS_WIDTH as f32, CANVAS_HEIGHT as f32)],
        grafo::Stroke::default(),
    );
    let canvas_root_id = renderer
        .add_shape(
            canvas_root,
            None,
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::WHITE),
        )
        .unwrap();

    let shape = grafo::Shape::builder()
        .begin((10.0, 10.0))
        .line_to((100.0, 10.0))
        .line_to((100.0, 100.0))
        .close()
        .begin((10.0, 10.0))
        .line_to((100.0, 100.0))
        .line_to((10.0, 100.0))
        .close()
        .build();
    renderer
        .add_shape(
            shape,
            Some(canvas_root_id),
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(200, 50, 50)),
        )
        .unwrap();

    let rect = grafo::Shape::rect([(140.0, 10.0), (230.0, 100.0)], grafo::Stroke::default());
    renderer
        .add_shape(
            rect,
            Some(canvas_root_id),
            None,
            grafo::ShapeDrawCommandOptions::new().color(grafo::Color::rgb(200, 50, 50)),
        )
        .unwrap();

    let mut pixel_buffer: Vec<u8> = Vec::new();
    renderer.render_to_buffer(&mut pixel_buffer);

    let expectations = vec![
        grafo_test_scenes::PixelExpectation::opaque(30, 30, 200, 50, 50, "diag_top_left"),
        grafo_test_scenes::PixelExpectation::opaque(55, 55, 200, 50, 50, "diag_center"),
        grafo_test_scenes::PixelExpectation::opaque(80, 80, 200, 50, 50, "diag_bottom_right"),
        grafo_test_scenes::PixelExpectation::opaque(5, 5, 255, 255, 255, "outside_shape"),
        grafo_test_scenes::PixelExpectation::opaque(185, 55, 200, 50, 50, "rect_center"),
        grafo_test_scenes::PixelExpectation::opaque(145, 15, 200, 50, 50, "rect_near_corner"),
        grafo_test_scenes::PixelExpectation::opaque(235, 55, 255, 255, 255, "outside_rect"),
    ];

    assert_pixels_match(&pixel_buffer, &expectations);
}