darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
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
//! Integration tests for the Rough Ink brush — the first 100%-
//! compiled brush. Exercises the full `paint` pipeline
//! end-to-end on a real GPU device:
//!
//! 1. **Single dab renders** — one dab through the compiled pipeline
//!    deposits color where it should. Smoke test that the pipeline
//!    builds and the dab buffer round-trips through the storage
//!    binding.
//! 2. **Two dabs in the same flush produce distinct silhouettes** —
//!    two dabs queued in the same phase get independent per-dab
//!    random seeds (the runner's `dab_index` increments) and the
//!    compiled shader reads them per-instance. Catches accidentally
//!    indexing all instances into slot 0 of the dab buffer.
//! 3. **Zero amplitude collapses to a disc** — with all three random
//!    nodes forced to 0 and the perlin amplitude defaulted via wire
//!    remap, the rendered shape is a disc within blend tolerance.
//!    Validates the compiled `shape_r_theta` parity with the existing
//!    CPU implementation.

use std::sync::{Arc, OnceLock};

use darkly::brush::compile_graph;
use darkly::brush::eval::BrushGraphRunner;
use darkly::brush::gpu_context::{BrushGpuContext, BrushPerfCounters, DabBatch, StrokeResources};
use darkly::brush::paint_info::PaintInformation;
use darkly::brush::pipeline::BrushPipelines;
use darkly::brush::registry;
use darkly::brush::stroke_buffer::StrokeBuffer;
use darkly::brush::wire::BrushWireType;
use darkly::gpu::params::ParamValue;
use darkly::gpu::test_utils::{create_test_texture, readback_texture, test_device};
use darkly::nodegraph::{Graph, PortRef};

const CANVAS: u32 = 128;

fn shared_device() -> (Arc<wgpu::Device>, Arc<wgpu::Queue>) {
    static HANDLES: OnceLock<(Arc<wgpu::Device>, Arc<wgpu::Queue>)> = OnceLock::new();
    HANDLES
        .get_or_init(|| {
            let (d, q) = test_device();
            (Arc::new(d), Arc::new(q))
        })
        .clone()
}

struct Harness {
    device: Arc<wgpu::Device>,
    queue: Arc<wgpu::Queue>,
    layer_texture: wgpu::Texture,
    layer_view: wgpu::TextureView,
    pipelines: BrushPipelines,
    stroke_buffer: StrokeBuffer,
    runner: BrushGraphRunner,
}

/// Build a minimal compiled-brush graph for testing:
///
///   pen_input.position → paint.position
///   pen_input.pressure → curve → paint.size_input
///   paint_color.color  → stamp.color
///   shape.mask    → stamp.tip       (per-dab shape feed)
///   stamp.dab          → paint.rgba
///
/// `algorithm` selects the shape's silhouette function. `amplitude`
/// defaults to 0 (= disc) unless the caller overrides.
fn build_test_graph(algorithm: i32, amplitude: f32, size: f32) -> Graph<BrushWireType> {
    let registry = registry();
    let mut graph = Graph::<BrushWireType>::new();

    let pen = graph.add_node(
        "pen_input",
        registry.get("pen_input").unwrap().ports.clone(),
        vec![],
    );
    let paint_color = graph.add_node(
        "paint_color",
        registry.get("paint_color").unwrap().ports.clone(),
        vec![],
    );
    let curve = graph.add_node(
        "curve",
        registry.get("curve").unwrap().ports.clone(),
        vec![ParamValue::Curve(vec![[0.0, 0.0], [1.0, 1.0]])],
    );
    let shape = graph.add_node(
        "shape",
        registry.get("shape").unwrap().ports.clone(),
        vec![ParamValue::Int(algorithm)],
    );
    let stamp = graph.add_node(
        "stamp",
        registry.get("stamp").unwrap().ports.clone(),
        vec![ParamValue::Int(0)], // Alpha Mask
    );
    let terminal = graph.add_node(
        "paint",
        registry.get("paint").unwrap().ports.clone(),
        vec![],
    );

    graph
        .set_port_default(shape, "amplitude", amplitude)
        .unwrap();
    graph.set_port_default(shape, "softness", 0.0).unwrap();
    graph.set_port_default(terminal, "size", size).unwrap();
    graph.set_port_default(terminal, "opacity", 1.0).unwrap();
    graph.set_port_default(terminal, "flow", 1.0).unwrap();

    // No `pen.pressure → terminal.flow` wire — tests that scale alpha by
    // flow rely on the per-test `set_port_default(terminal, "flow", …)`
    // override, which a wire would shadow.
    let wires = [
        (pen, "pressure", curve, "input"),
        (curve, "output", terminal, "size_input"),
        (shape, "mask", stamp, "tip"),
        (paint_color, "color", stamp, "color"),
        (stamp, "dab", terminal, "rgba"),
        (pen, "position", terminal, "position"),
    ];
    for (fnode, fport, tnode, tport) in wires {
        graph
            .connect(
                PortRef {
                    node: fnode,
                    port: fport.into(),
                },
                PortRef {
                    node: tnode,
                    port: tport.into(),
                },
            )
            .unwrap();
    }

    graph
}

fn harness(initial: &[u8], graph: Graph<BrushWireType>) -> Harness {
    let (device, queue) = shared_device();
    let (layer_texture, layer_view) = create_test_texture(&device, &queue, CANVAS, CANVAS, initial);

    let pipelines = BrushPipelines::new(
        &device,
        &queue,
        &darkly::gpu::selection::selection_mask_bgl(&device),
    );
    let stroke_buffer = StrokeBuffer::new(&device, CANVAS, CANVAS, &pipelines);

    let pre_stroke_paint_target = darkly::gpu::paint_target::GpuPaintTarget::from_canvas_texture(
        &layer_texture,
        &layer_view,
        wgpu::TextureFormat::Rgba8Unorm,
        darkly::coord::CanvasRect::from_xywh(0, 0, CANVAS, CANVAS),
    );
    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("rough-ink-test-pre-stroke-init"),
    });
    stroke_buffer.save_pre_stroke(&device, &mut enc, &pipelines, &pre_stroke_paint_target);
    queue.submit([enc.finish()]);

    let runner = compile_graph(&graph).expect("graph compiles");

    Harness {
        device,
        queue,
        layer_texture,
        layer_view,
        pipelines,
        stroke_buffer,
        runner,
    }
}

macro_rules! make_ctx {
    ($h:ident, $label:expr) => {{
        let (_scratch, _pre_stroke_texture, _pre_stroke_bind_group) =
            $h.stroke_buffer.parts_for_brush_ctx();
        BrushGpuContext {
            encoder: $h
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some($label),
                }),
            device: &$h.device,
            queue: &$h.queue,
            pipelines: &$h.pipelines,
            selection_bind_group: $h.pipelines.default_selection_bind_group(),
            canvas_width: CANVAS,
            canvas_height: CANVAS,
            canvas_origin: [0, 0],
            blend_mode: 0,
            view_rotation: 0.0,
            perf: BrushPerfCounters::default(),
            stroke: Some(StrokeResources {
                scratch: _scratch,
                paint_target: darkly::gpu::paint_target::GpuPaintTarget::from_canvas_texture(
                    &$h.layer_texture,
                    &$h.layer_view,
                    wgpu::TextureFormat::Rgba8Unorm,
                    darkly::coord::CanvasRect::from_xywh(0, 0, CANVAS, CANVAS),
                ),
                pre_stroke_texture: _pre_stroke_texture,
                pre_stroke_bind_group: _pre_stroke_bind_group,
            }),
            preview: None,
            dab_batch: DabBatch::default(),
        }
    }};
}

impl Harness {
    fn begin_stroke(&mut self) {
        let mut ctx = make_ctx!(self, "rough-ink-test-begin");
        self.runner.begin_stroke(&mut ctx);
        self.queue.submit([ctx.encoder.finish()]);
    }

    fn dab_and_flush(&mut self, info: &PaintInformation, color: [f32; 4], dab_index: u32) {
        let mut ctx = make_ctx!(self, "rough-ink-test-dab");
        self.runner.seed_sensors(info, color, 0xC0FFEE, dab_index);
        self.runner.execute_cpu();
        self.runner.execute_gpu(&mut ctx);
        self.runner.flush_dabs(&mut ctx);
        self.runner.commit(&mut ctx);
        self.queue.submit([ctx.encoder.finish()]);
    }

    fn two_dabs_same_phase(&mut self, a: &PaintInformation, b: &PaintInformation, color: [f32; 4]) {
        let mut ctx = make_ctx!(self, "rough-ink-test-two-dabs");
        self.runner.seed_sensors(a, color, 0xC0FFEE, 0);
        self.runner.execute_cpu();
        self.runner.execute_gpu(&mut ctx);
        self.runner.seed_sensors(b, color, 0xC0FFEE, 1);
        self.runner.execute_cpu();
        self.runner.execute_gpu(&mut ctx);
        // Single flush, two instanced dabs.
        self.runner.flush_dabs(&mut ctx);
        self.runner.commit(&mut ctx);
        self.queue.submit([ctx.encoder.finish()]);
    }

    fn readback_canvas(&self) -> Vec<u8> {
        readback_texture(
            &self.device,
            &self.queue,
            &self.layer_texture,
            wgpu::TextureFormat::Rgba8Unorm,
            CANVAS,
            CANVAS,
        )
    }
}

fn center_pixel(rgba: &[u8], x: u32, y: u32) -> [u8; 4] {
    let idx = ((y * CANVAS + x) * 4) as usize;
    [rgba[idx], rgba[idx + 1], rgba[idx + 2], rgba[idx + 3]]
}

/// Initial canvas: opaque black, so a dab depositing red is unmistakable.
fn black_canvas() -> Vec<u8> {
    let mut out = vec![0u8; (CANVAS * CANVAS * 4) as usize];
    for px in out.chunks_exact_mut(4) {
        px[3] = 255;
    }
    out
}

#[test]
fn single_dab_deposits_color_at_center() {
    // size = 0.1 → ~25.6px radius. Place at (64, 64), expect a red
    // dab covering the center.
    let graph = build_test_graph(
        /* sine */ 0, /* amplitude */ 0.0, /* size */ 0.1,
    );
    let mut h = harness(&black_canvas(), graph);
    h.begin_stroke();
    let info = PaintInformation {
        pos: [64.0, 64.0],
        pressure: 1.0,
        ..Default::default()
    };
    h.dab_and_flush(&info, [1.0, 0.0, 0.0, 1.0], 0);

    let rgba = h.readback_canvas();
    let center = center_pixel(&rgba, 64, 64);
    assert!(
        center[0] > 200 && center[1] < 50 && center[2] < 50,
        "center pixel should be ~red after dab, got {center:?}"
    );

    // Outside the disc footprint: still black.
    let outside = center_pixel(&rgba, 10, 10);
    assert_eq!(
        outside,
        [0, 0, 0, 255],
        "outside the dab should be unchanged"
    );
}

#[test]
fn two_dabs_same_flush_both_deposit() {
    // Two dabs at distinct positions in one flush. Both must reach
    // the layer — catches accidentally indexing all instances to dab
    // 0 in the storage buffer.
    let graph = build_test_graph(0, 0.0, 0.1);
    let mut h = harness(&black_canvas(), graph);
    h.begin_stroke();
    let a = PaintInformation {
        pos: [40.0, 40.0],
        pressure: 1.0,
        ..Default::default()
    };
    let b = PaintInformation {
        pos: [88.0, 88.0],
        pressure: 1.0,
        ..Default::default()
    };
    h.two_dabs_same_phase(&a, &b, [0.0, 1.0, 0.0, 1.0]);

    let rgba = h.readback_canvas();
    let center_a = center_pixel(&rgba, 40, 40);
    let center_b = center_pixel(&rgba, 88, 88);
    assert!(
        center_a[1] > 200 && center_a[0] < 50,
        "dab A center should be green, got {center_a:?}"
    );
    assert!(
        center_b[1] > 200 && center_b[0] < 50,
        "dab B center should be green, got {center_b:?}"
    );
    // Halfway between, but outside both: still black.
    let middle = center_pixel(&rgba, 64, 64);
    assert_eq!(
        middle,
        [0, 0, 0, 255],
        "between the two dabs should be untouched, got {middle:?}"
    );
}

#[test]
fn builtin_rough_ink_brush_renders_within_declared_bbox() {
    // Render the actual Rough Ink builtin — exercises `random →
    // shape` wires that pack per-dab values into the dab record
    // and reference them from the shape evaluator. Regression test
    // for the case where the shape evaluator's body was emitted as a
    // top-level WGSL function that captured `d.<field>` from outside
    // its scope (Dawn rejects, naga silently accepted on native).
    //
    // Also acts as a regression test for the extent protocol: the
    // rendered footprint must fall inside the brush's declared
    // bbox (effective_radius × `brush_extent_factor`). If the shader
    // writes outside the bbox, the save-point system on rewind
    // truncates previous dabs to the un-inflated square — the bug
    // the protocol was introduced to fix.
    let rough_ink = darkly::brush::builtin_brushes::all()
        .into_iter()
        .find(|b| b.metadata.name == "Rough Ink")
        .expect("Rough Ink registered");
    let (device, queue) = shared_device();
    let (layer_texture, layer_view) =
        create_test_texture(&device, &queue, CANVAS, CANVAS, &black_canvas());
    let pipelines = BrushPipelines::new(
        &device,
        &queue,
        &darkly::gpu::selection::selection_mask_bgl(&device),
    );
    let stroke_buffer = StrokeBuffer::new(&device, CANVAS, CANVAS, &pipelines);
    let pre_stroke_paint_target = darkly::gpu::paint_target::GpuPaintTarget::from_canvas_texture(
        &layer_texture,
        &layer_view,
        wgpu::TextureFormat::Rgba8Unorm,
        darkly::coord::CanvasRect::from_xywh(0, 0, CANVAS, CANVAS),
    );
    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("rough-ink-builtin-pre-stroke"),
    });
    stroke_buffer.save_pre_stroke(&device, &mut enc, &pipelines, &pre_stroke_paint_target);
    queue.submit([enc.finish()]);

    // Override the brush's size port so the dab fits in the test
    // canvas — the builtin's exposed size is small by default.
    let mut graph = rough_ink.metadata.graph.clone();
    let term_id = darkly::brush::find_terminal(&graph).unwrap();
    graph.set_port_default(term_id, "size", 0.15).unwrap();

    let runner = compile_graph(&graph).expect("Rough Ink compiles");
    let compiled = runner.compiled_brush().expect("compiled brush attached");
    // Rough Ink wires `random → shape.amplitude` (natural_range max
    // = 0.5) so the brush extent factor composes to 1.5.
    assert!(
        (compiled.brush_extent_factor - 1.5).abs() < 1e-4,
        "expected rough-ink extent factor ≈ 1.5, got {}",
        compiled.brush_extent_factor,
    );

    let mut h = Harness {
        device,
        queue,
        layer_texture,
        layer_view,
        pipelines,
        stroke_buffer,
        runner,
    };
    h.begin_stroke();
    let info = PaintInformation {
        pos: [64.0, 64.0],
        pressure: 1.0,
        ..Default::default()
    };
    h.dab_and_flush(&info, [1.0, 0.5, 0.0, 1.0], 0);

    let rgba = h.readback_canvas();
    // Perlin shape varies per random seed — the centre may be inside
    // or outside, but *some* deposition has to land within the dab
    // footprint (radius ~38px around (64, 64)) if the shader
    // compiled.
    let mut deposited = 0;
    let mut max_dist_sq: f32 = 0.0;
    for y in 0..CANVAS {
        for x in 0..CANVAS {
            let p = center_pixel(&rgba, x, y);
            if p[0] > 0 || p[1] > 0 || p[2] > 0 {
                deposited += 1;
                let dx = x as f32 - 64.0;
                let dy = y as f32 - 64.0;
                max_dist_sq = max_dist_sq.max(dx * dx + dy * dy);
            }
        }
    }
    assert!(
        deposited > 50,
        "expected ≥50 non-black pixels inside dab footprint, found {deposited} \
         (shader compile silently failed or dab missed the layer)"
    );

    // size = 0.15 → effective_radius = 0.15 * DAB_REFERENCE_SIZE * 0.5
    // = ~38.4 (DAB_REFERENCE_SIZE = 512 px). bbox_radius =
    // effective_radius * 1.5 = ~57.6. Allow 1px slack for the
    // rasterizer's edge.
    let effective_radius = 0.15 * darkly::brush::DAB_REFERENCE_SIZE as f32 * 0.5;
    let bbox_radius =
        effective_radius * compiled.brush_extent_factor + compiled.brush_extent_extra_px;
    let max_dist = max_dist_sq.sqrt();
    assert!(
        max_dist <= bbox_radius + 1.0,
        "rendered pixel at distance {max_dist} exceeds declared bbox \
         {bbox_radius} (effective_radius {effective_radius}, factor \
         {})",
        compiled.brush_extent_factor,
    );
    // Sanity: shape must extend at least to the unmodulated disc
    // boundary somewhere — confirms perlin is actually drawing past
    // the un-inflated radius, which is the half of the bug we're
    // defending against (bbox too small → clipping inside the bbox
    // is the "bug not present" check).
    assert!(
        max_dist >= effective_radius * 0.5,
        "rendered footprint suspiciously small (max_dist {max_dist}, \
         effective_radius {effective_radius}) — shader may be \
         clipping inside the declared bbox",
    );
}

#[test]
fn rough_ink_overlapping_dabs_render_without_truncation() {
    // Regression test for the QUAD_R_MAX-vs-radius divergence bug.
    // Render two overlapping perlin dabs in the same flush. Each dab
    // packs its own `bbox_radius` into the per-instance dab record;
    // the WGSL vertex stage sizes the quad to that per-dab value,
    // and the fragment stage discards past it. If the per-instance
    // bbox were globally clamped (the pre-protocol bug), the larger
    // dab would be clipped by the smaller's quad.
    let rough_ink = darkly::brush::builtin_brushes::all()
        .into_iter()
        .find(|b| b.metadata.name == "Rough Ink")
        .expect("Rough Ink registered");
    let mut graph = rough_ink.metadata.graph.clone();
    let term_id = darkly::brush::find_terminal(&graph).unwrap();
    graph.set_port_default(term_id, "size", 0.15).unwrap();
    // Replace the builtin's pressure-shaping curve (a monotone Hermite
    // spline through `(0,0), (0.4,0.7), (1,1)`) with the identity curve
    // so this test's `r_a` / `r_b` math (radius ∝ pressure) lines up
    // with what the CPU side packs into the dab record. The QUAD_R_MAX-
    // vs-radius divergence we're guarding against is independent of the
    // curve shape.
    let curve_id = graph
        .nodes()
        .iter()
        .find(|(_, n)| n.type_id == darkly::brush::nodes::curve::TYPE_ID)
        .map(|(id, _)| *id)
        .unwrap();
    graph
        .set_param(curve_id, 0, ParamValue::Curve(vec![[0.0, 0.0], [1.0, 1.0]]))
        .unwrap();

    let mut h = harness(&black_canvas(), graph);
    let compiled = h.runner.compiled_brush().expect("compiled brush attached");
    h.begin_stroke();
    // Two overlapping dabs at different pressures → different
    // effective_radius → different bbox_radius per dab record.
    let a = PaintInformation {
        pos: [44.0, 64.0],
        pressure: 0.5,
        ..Default::default()
    };
    let b = PaintInformation {
        pos: [84.0, 64.0],
        pressure: 1.0,
        ..Default::default()
    };
    h.two_dabs_same_phase(&a, &b, [1.0, 0.0, 0.0, 1.0]);

    let rgba = h.readback_canvas();
    let bbox_factor = compiled.brush_extent_factor;

    // Sum deposited pixels per dab, gated by each dab's declared bbox.
    let mut dab_a_pixels = 0;
    let mut dab_b_pixels = 0;
    let dab_size = 0.15 * darkly::brush::DAB_REFERENCE_SIZE as f32 * 0.5;
    // Per-dab effective_radius differs only through the curve(pressure)
    // wire; the brush's curve is identity-shape so radius ∝ pressure.
    let r_a = (dab_size * 0.5 * bbox_factor) + 1.0;
    let r_b = (dab_size * 1.0 * bbox_factor) + 1.0;
    for y in 0..CANVAS {
        for x in 0..CANVAS {
            let p = center_pixel(&rgba, x, y);
            if p[0] == 0 && p[1] == 0 && p[2] == 0 {
                continue;
            }
            let dxa = x as f32 - a.pos[0];
            let dya = y as f32 - a.pos[1];
            let dxb = x as f32 - b.pos[0];
            let dyb = y as f32 - b.pos[1];
            let da = (dxa * dxa + dya * dya).sqrt();
            let db = (dxb * dxb + dyb * dyb).sqrt();
            // Pixel must lie within at least one dab's declared bbox.
            assert!(
                da <= r_a || db <= r_b,
                "pixel at ({x}, {y}) deposited outside both declared \
                 bboxes (da={da}, r_a={r_a}; db={db}, r_b={r_b})",
            );
            if da <= r_a {
                dab_a_pixels += 1;
            }
            if db <= r_b {
                dab_b_pixels += 1;
            }
        }
    }
    // Both dabs must have actually deposited something — catches the
    // case where a per-instance buffer index bug aliases all draws
    // to dab 0 (or one dab gets entirely clipped).
    assert!(
        dab_a_pixels > 20 && dab_b_pixels > 20,
        "both dabs must render — got A={dab_a_pixels}, B={dab_b_pixels}",
    );
}

#[test]
fn terminal_flow_scales_dab_alpha() {
    // Regression test: `paint.flow` must fold into the
    // returned rgba's alpha, matching the `paint` terminal's
    // `color[3] *= flow` step. Before the fix, the terminal declared
    // the `flow` port but never read it in `compile_wgsl`, so the
    // brush properties' Flow slider was a no-op.
    fn deposit_red_at_center(flow: f32) -> [u8; 4] {
        let mut graph = build_test_graph(
            /* sine */ 0, /* amplitude */ 0.0, /* size */ 0.2,
        );
        // Replace the terminal.flow default. build_test_graph hard-
        // sets it to 1.0 already; override here per-test.
        let term_id = darkly::brush::find_terminal(&graph).unwrap();
        graph.set_port_default(term_id, "flow", flow).unwrap();
        let mut h = harness(&black_canvas(), graph);
        h.begin_stroke();
        let info = PaintInformation {
            pos: [64.0, 64.0],
            pressure: 1.0,
            ..Default::default()
        };
        h.dab_and_flush(&info, [1.0, 0.0, 0.0, 1.0], 0);
        let rgba = h.readback_canvas();
        center_pixel(&rgba, 64, 64)
    }

    let full = deposit_red_at_center(1.0);
    let third = deposit_red_at_center(0.3);
    // Both render red (no green/blue), opaque (canvas is opaque
    // black underneath). Difference is the per-pixel red intensity
    // — at flow=0.3 the source RGB only deposits ~30% over the
    // underlying black.
    assert!(
        full[0] > 200,
        "flow=1.0 should deposit ~full red, got {full:?}",
    );
    assert!(
        third[0] > 40 && third[0] < 120,
        "flow=0.3 should deposit ~30% red over black, got {third:?}",
    );
    assert!(
        full[0] > third[0] + 80,
        "flow=1.0 ({}) must deposit more red than flow=0.3 ({})",
        full[0],
        third[0],
    );
}

#[test]
fn perlin_amplitude_zero_collapses_to_disc() {
    // Perlin algorithm but amplitude = 0 → r(θ) = 1 for all θ, i.e.
    // a clean disc. The center should be solid, the corner of the
    // bounding box should be transparent (outside the disc but
    // inside the rasterized quad).
    let graph = build_test_graph(
        /* perlin */ 1, /* amplitude */ 0.0, /* size */ 0.2,
    );
    let mut h = harness(&black_canvas(), graph);
    h.begin_stroke();
    let info = PaintInformation {
        pos: [64.0, 64.0],
        pressure: 1.0,
        ..Default::default()
    };
    h.dab_and_flush(&info, [0.0, 0.0, 1.0, 1.0], 0);

    let rgba = h.readback_canvas();
    let center = center_pixel(&rgba, 64, 64);
    assert!(
        center[2] > 200,
        "center should be ~blue with amplitude=0, got {center:?}"
    );

    // The dab radius at size = 0.2 is ~51 px. So a pixel ~70px away
    // should be outside the disc and unchanged.
    let outside = center_pixel(&rgba, 64, 0);
    assert_eq!(
        outside,
        [0, 0, 0, 255],
        "outside the disc should be unchanged, got {outside:?}"
    );
}