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
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
//! Paint terminal — single-pass instanced fragment with a per-brush
//! compiled WGSL shader.
//!
//! ## What this terminal does
//!
//! Per-dab records queue up on [`BrushGpuContext::dab_batch`];
//! one instanced render pass drains them at phase end.
//!
//! - **The fragment shader is generated per-brush at brush load** by
//!   walking the upstream graph and asking each node to emit WGSL.
//!   See [`crate::brush::wgsl`].
//! - **The per-dab record schema is dynamic**, sized by what fields
//!   the brush's nodes contribute. No fixed `PaintDabRecord` struct.
//! - **The uniform buffer carries stroke-constant values** from any
//!   upstream nodes that declared `uniform_fields` (e.g. `paint_color`).
//!
//! Upstream nodes (`shape`, `stamp`, etc.) compile inline into the
//! fragment shader and evaluate per-fragment-per-dab — no intermediate
//! textures.
//!
//! ## Pipeline cache
//!
//! Per-brush pipelines are built lazily on the first `flush_dabs`
//! call and cached on [`PaintPipeline`] keyed by the brush
//! graph's `topology_hash`. Two brushes with identical graph
//! topologies share a pipeline.
//!
//! ## Brush load failure
//!
//! Compilation happens in [`crate::brush::compile_graph`]. If any
//! upstream node returns `Err` from `compile_wgsl`, brush load fails
//! — there is no runtime fallback. See
//! [`crate::brush::wgsl::CompileError`].

use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;

use crate::brush::eval::{BrushNodeEvaluator, EvalContext};
use crate::brush::gpu_context::{BrushGpuContext, MAX_DABS_PER_PHASE};
use crate::brush::node::BrushNodeRegistration;
use crate::brush::paint_target_ext::BrushPaintTargetExt;
use crate::brush::pipeline::{
    BrushPipelineEntry, BrushPipelineRegistration, BuildContext, DynamicUniformRing,
};
use crate::brush::wgsl::{
    pack_intrinsic_uniforms, pack_uniforms, CompileWgslCtx, CompiledBrush, InputBinding, NodeWgsl,
    INTRINSIC_UNIFORMS_SIZE,
};
use crate::brush::wire::{BrushWireType, ScalarValue};
use crate::nodegraph::{NodeRegistration, PortDef, UnitType};

// ── Constants ───────────────────────────────────────────────────────────

/// Canvas-pixel reference for `size_input * size = 1.0`. Same
/// `DAB_REFERENCE_SIZE` used by every other brush node — see
/// [`crate::brush::DAB_REFERENCE_SIZE`].
const SIZE_REFERENCE_PX: f32 = crate::brush::DAB_REFERENCE_SIZE as f32;

/// Maximum uniform buffer size we'll allocate per brush pipeline.
const MAX_UNIFORM_BYTES: usize = 1024;

// ── Per-brush pipeline ──────────────────────────────────────────────────

/// Per-brush resources built on the first `flush_dabs` call for a
/// brush with a given `topology_hash`. Cached on [`PaintPipeline`].
struct PerBrushPipeline {
    /// Per-dab pipeline. Always premultiplied source-over — the scratch
    /// is a coverage accumulator and only paints alpha *up*. Engine-level
    /// paint-vs-erase is a stroke decision applied at commit by
    /// `commit_brush_dab`, not here. (Branching the per-dab pass on
    /// `blend_mode` to a destination-out blend was a regression: the
    /// scratch starts at (0,0,0,0), so `dst*(1-src.a)` stays zero and
    /// the commit's `destination_out` then sees zero alpha and no-ops.)
    paint_pipeline: wgpu::RenderPipeline,
    uniform_ring: DynamicUniformRing,
    uniform_bind_group: wgpu::BindGroup,
    dabs_buffer: wgpu::Buffer,
    dabs_bind_group: wgpu::BindGroup,
    /// Total size of the uniform block (intrinsic + node fields), in bytes.
    uniform_size: usize,
    /// `@group(3)` graph-texture bind group, present when the brush
    /// graph contains `image`-style nodes. Built once at pipeline
    /// build from the engine's
    /// [`crate::gpu::texture_registry::TextureRegistry`]; reused for
    /// every dab. `None` when the brush requests no graph textures
    /// (the pipeline layout also omits group 3 in that case).
    graph_textures_bind_group: Option<wgpu::BindGroup>,
}

impl PerBrushPipeline {
    fn build(ctx: &BuildContext, compiled: &CompiledBrush) -> Self {
        let shader = ctx
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("paint-brush"),
                source: wgpu::ShaderSource::Wgsl(compiled.stroke_wgsl.clone().into()),
            });

        // group(1): dabs storage buffer. Same VERTEX_FRAGMENT visibility
        // as `paint` — vertex stage reads `pos`/`bbox_target_px` to build the
        // quad, fragment stage reads the rest.
        let dabs_bgl = ctx
            .device
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("paint-dabs-bgl"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        // Optional `@group(3)` graph-texture bind group. Present only
        // when the brush graph requested at least one `image`-style
        // texture. Paint has no terminal bindings of its own, so the
        // graph-textures layout sits at slot 3 directly — WebGPU's
        // default `max_bind_groups = 4` rules out anything higher.
        // The compile walk rejects graphs that combine an `image`
        // node with a terminal that also claims @group(3) (e.g.
        // watercolor's pickup atlas).
        let graph_layout = if compiled.graph_texture_names.is_empty() {
            None
        } else {
            Some(
                ctx.texture_registry
                    .layout_for_count(ctx.device, compiled.graph_texture_names.len()),
            )
        };
        let layout = match &graph_layout {
            None => ctx
                .device
                .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: Some("paint-layout"),
                    bind_group_layouts: &[
                        Some(ctx.uniform_bgl),
                        Some(&dabs_bgl),
                        Some(ctx.selection_bgl),
                    ],
                    immediate_size: 0,
                }),
            Some(gl) => ctx
                .device
                .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: Some("paint-layout-with-graph-textures"),
                    bind_group_layouts: &[
                        Some(ctx.uniform_bgl),
                        Some(&dabs_bgl),
                        Some(ctx.selection_bgl),
                        Some(gl.as_ref()),
                    ],
                    immediate_size: 0,
                }),
        };

        // Premultiplied source-over: scratch accumulates coverage. See
        // the `paint_pipeline` field doc above for why there's no erase
        // variant at this stage.
        let paint_blend = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
        };

        let paint_pipeline = ctx
            .device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("paint"),
                layout: Some(&layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: Some("vs_main"),
                    buffers: &[],
                    compilation_options: Default::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: wgpu::TextureFormat::Rgba8Unorm,
                        blend: Some(paint_blend),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: Default::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    ..Default::default()
                },
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            });

        // Uniform ring sized for this brush's actual uniform layout.
        let uniform_size =
            (INTRINSIC_UNIFORMS_SIZE + compiled.uniform_size).max(INTRINSIC_UNIFORMS_SIZE);
        let uniform_ring = DynamicUniformRing::new(
            ctx.device,
            "paint-uniforms",
            uniform_size as u64,
            ctx.min_uniform_align,
        );
        let uniform_bind_group = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("paint-uniform-bg"),
            layout: ctx.uniform_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                    buffer: &uniform_ring.buffer,
                    offset: 0,
                    size: Some(uniform_ring.binding_size()),
                }),
            }],
        });

        // Dab record buffer sized for this brush's record stride.
        let dab_record_size = compiled.dab_record_size.max(16);
        let dabs_buffer_size = (MAX_DABS_PER_PHASE as u64) * (dab_record_size as u64);
        let dabs_buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("paint-dabs-buffer"),
            size: dabs_buffer_size,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let dabs_bind_group = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("paint-dabs-bg"),
            layout: &dabs_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: dabs_buffer.as_entire_binding(),
            }],
        });

        // Avoid the unused-let warning while keeping the variable
        // for documentation — `dab_record_size` is what determines
        // `dabs_buffer_size` above.
        let _ = dab_record_size;

        // Resolve the brush's named graph textures against the
        // engine registry and build the `@group(3)` bind group.
        // Missing names fall back to the registry's `_fallback`
        // texture so the pipeline always builds — surfaces a
        // `log::warn` instead of crashing while the user types in
        // the node editor.
        let graph_textures_bind_group = if compiled.graph_texture_names.is_empty() {
            None
        } else {
            let (_layout, bg) = ctx
                .texture_registry
                .make_bind_group(ctx.device, &compiled.graph_texture_names);
            Some(bg)
        };

        Self {
            paint_pipeline,
            uniform_ring,
            uniform_bind_group,
            dabs_buffer,
            dabs_bind_group,
            uniform_size,
            graph_textures_bind_group,
        }
    }
}

// ── Pipeline registry entry ─────────────────────────────────────────────

/// The single registry entry for the `paint` terminal. Holds
/// a cache of per-brush pipelines keyed by `topology_hash`. Pipelines
/// are built lazily on first use.
pub struct PaintPipeline {
    cache: RefCell<HashMap<u64, PerBrushPipeline>>,
}

impl PaintPipeline {
    fn build(_ctx: &BuildContext) -> Self {
        Self {
            cache: RefCell::new(HashMap::new()),
        }
    }

    /// Build (or look up) the per-brush pipeline for `compiled`. Called
    /// on every `flush_dabs` — the first call for a hash builds; later
    /// calls reuse. With ~tens of brushes max, the HashMap lookup is
    /// noise compared to the render pass cost.
    fn ensure_pipeline(&self, ctx: &BuildContext, compiled: &CompiledBrush) {
        let mut cache = self.cache.borrow_mut();
        cache
            .entry(compiled.topology_hash)
            .or_insert_with(|| PerBrushPipeline::build(ctx, compiled));
    }

    /// Run a closure with the per-brush pipeline. Panics if the
    /// pipeline hasn't been built yet (caller must `ensure_pipeline`
    /// first within the same `flush_dabs` invocation).
    fn with_pipeline<R>(&self, hash: u64, f: impl FnOnce(&PerBrushPipeline) -> R) -> R {
        let cache = self.cache.borrow();
        let p = cache
            .get(&hash)
            .expect("ensure_pipeline must run before with_pipeline");
        f(p)
    }
}

impl BrushPipelineEntry for PaintPipeline {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn ring(&self) -> Option<&DynamicUniformRing> {
        None
    }
    fn rings(&self) -> Vec<&DynamicUniformRing> {
        // The ring is owned by each per-brush pipeline. We can't
        // safely return references through the RefCell — the frame
        // reset loop expects &DynamicUniformRing with a lifetime tied
        // to self, but the rings live behind a RefCell borrow that
        // doesn't outlive this call. Workaround: keep the rings out
        // of the central reset loop and reset them ourselves on each
        // `flush_dabs` (the ring only holds per-flush state).
        Vec::new()
    }
}

fn paint_pipeline_reg() -> BrushPipelineRegistration {
    BrushPipelineRegistration {
        id: "paint",
        build: |ctx| Box::new(PaintPipeline::build(ctx)),
    }
}

// ── Node ────────────────────────────────────────────────────────────────

pub const TYPE_ID: &str = "paint";

pub fn register() -> BrushNodeRegistration {
    BrushNodeRegistration {
        pipelines: vec![paint_pipeline_reg()],
        evaluator: || Box::new(PaintEvaluator),
        lifecycle: crate::brush::node::Lifecycle::ClearScratchToTransparent,
        node: NodeRegistration {
            type_id: TYPE_ID,
            category: "output",
            display_name: "Paint",
            description: "Output that deposits a brush mark onto the canvas. Plug a Stamp Tip (or any colored mark) into the dab input — this is where paint actually lands.",
            ports: vec![
                PortDef::input("position", BrushWireType::Vec2)
                    .with_description("Canvas-pixel pen tip for this dab"),
                PortDef::input("size_input", BrushWireType::Scalar)
                    .with_range(0.0, 1.0, 1.0)
                    .with_natural_range(0.0, 1.0)
                    .with_label("Size Input")
                    .with_unit(UnitType::Percent)
                    .with_description(
                        "Per-touch size multiplier (wire pressure here for pressure-sensitive size).",
                    ),
                PortDef::input("size", BrushWireType::Scalar)
                    .with_range(0.0, 4.0, 0.1)
                    .with_label("Size")
                    .with_unit(UnitType::Percent)
                    .with_icon("fa6-solid:up-right-and-down-left-from-center")
                    .exposed()
                    .with_preview_value(0.1)
                    .with_description("Overall brush size"),
                PortDef::input("flow", BrushWireType::Scalar)
                    .with_range(0.0, 1.0, 1.0)
                    .with_natural_range(0.0, 1.0)
                    .with_label("Flow")
                    .with_unit(UnitType::Percent)
                    .with_icon("fa6-solid:droplet")
                    .exposed()
                    .with_description("Stroke-level flow cap (folded into rgba alpha)"),
                PortDef::input("opacity", BrushWireType::Scalar)
                    .with_range(0.0, 1.0, 1.0)
                    .with_natural_range(0.0, 1.0)
                    .with_label("Opacity")
                    .with_unit(UnitType::Percent)
                    .with_icon("fa6-solid:fill-drip")
                    .exposed()
                    .with_description("Stroke-level opacity cap (applied at commit)"),
                // Typed as `Texture` to match the upstream `stamp.dab`
                // output's wire type — the wire-type label is shared
                // with the per-dab dispatch model where it'd be a
                // texture handle. In the compiled path it's a
                // `vec4<f32>` expression. Without this match, the
                // graph compiler rejects the connection at brush load.
                PortDef::input("rgba", BrushWireType::Vec4).with_description(
                    "Premultiplied RGBA from the upstream compiled graph (typically `stamp.dab`)",
                ),
                PortDef::output("dab_size", BrushWireType::Vec2)
                    .with_description("Brush mark size in canvas pixels"),
            ],
            params: &[],
            is_gpu: true,
            is_terminal: true,
            supports_erase: true,
        },
    }
}

pub struct PaintEvaluator;

impl PaintEvaluator {
    fn effective_radius(ctx: &EvalContext) -> f32 {
        let size_input = ctx.input_f32("size_input").max(0.0);
        let size = ctx.input_f32("size").max(0.0);
        let effective_size = size_input * size;
        (effective_size * SIZE_REFERENCE_PX * 0.5).max(0.5)
    }
}

impl BrushNodeEvaluator for PaintEvaluator {
    fn evaluate_cpu(&self, _ctx: &EvalContext) -> Vec<(String, ScalarValue)> {
        vec![]
    }

    fn evaluate_gpu(
        &self,
        ctx: &EvalContext,
        gpu: &mut BrushGpuContext,
    ) -> Vec<(String, ScalarValue)> {
        let Some(compiled) = gpu.dab_batch.compiled_brush.clone() else {
            // Compiled brush wasn't attached — programming error in
            // the engine wiring. Panic in debug, drop dab silently in
            // release so we don't blow up an in-flight stroke.
            debug_assert!(false, "paint requires compiled_brush on gpu_context");
            return vec![];
        };
        let Some(stroke) = gpu.stroke.as_ref() else {
            return vec![];
        };
        let paint_target = &stroke.paint_target;
        let position = ctx.input("position").as_vec2();
        let radius = Self::effective_radius(ctx);
        let diameter = radius * 2.0;
        if diameter <= 0.0 {
            return vec![("dab_size".into(), ScalarValue::Vec2([diameter, diameter]))];
        }

        // Per-brush extent: composed by the framework at compile time
        // from every upstream node's `ExtentContribution`. This is
        // exactly what the WGSL fragment shader discards past
        // (`d.bbox_target_px`); using the same value here means the
        // layer-clip bbox tracks exactly what the shader writes, and
        // mid-stroke rewinds can't truncate previous dabs.
        let bbox_radius = radius * compiled.brush_extent_factor + compiled.brush_extent_extra_px;
        let canvas_ext = paint_target.canvas_extent();
        // Clamp the dab footprint to the layer extent; a dab entirely
        // off-extent has no pixels to draw and is skipped.
        let canvas_bbox = match canvas_ext.clamp_f32(
            position[0] - bbox_radius,
            position[1] - bbox_radius,
            position[0] + bbox_radius,
            position[1] + bbox_radius,
        ) {
            Some(r) => r,
            None => return vec![("dab_size".into(), ScalarValue::Vec2([diameter, diameter]))],
        };
        let local = paint_target
            .canvas_frame()
            .canvas_to_layer_rect(canvas_bbox)
            .expect("canvas_bbox came from canvas_ext.clamp_f32, so it overlaps the extent");
        gpu.dab_batch.push_write_bbox(canvas_bbox);
        gpu.dab_batch.bbox = Some(match gpu.dab_batch.bbox {
            Some([x0, y0, x1, y1]) => [
                x0.min(local.x0()),
                y0.min(local.y0()),
                x1.max(local.x1()),
                y1.max(local.y1()),
            ],
            None => [local.x0(), local.y0(), local.x1(), local.y1()],
        });

        gpu.dab_batch
            .queue_dab(&compiled, position, bbox_radius, radius);

        vec![("dab_size".into(), ScalarValue::Vec2([diameter, diameter]))]
    }

    fn flush_dabs(&self, _ctx: &EvalContext, gpu: &mut BrushGpuContext) {
        if gpu.dab_batch.count == 0 {
            return;
        }
        let Some(compiled) = gpu.dab_batch.compiled_brush.clone() else {
            debug_assert!(false, "paint::flush_dabs requires compiled_brush");
            return;
        };

        let bbox = gpu.dab_batch.bbox.unwrap_or([0, 0, 0, 0]);
        let union_w = bbox[2].saturating_sub(bbox[0]);
        let union_h = bbox[3].saturating_sub(bbox[1]);
        let (dab_bytes, total_dabs) = gpu.dab_batch.take();
        if total_dabs == 0 {
            return;
        }
        gpu.perf
            .record_dab_flush_workload(total_dabs, union_w, union_h);

        let pipeline_ref = gpu.pipelines.get::<PaintPipeline>("paint");

        // Build the per-brush pipeline if this is the first dab for
        // this hash. The BuildContext borrows pieces from
        // BrushPipelines via private accessors — we use a minimal
        // local BuildContext built from the gpu_context's wgpu refs.
        // Note: this is a one-shot build per brush, so the cost is
        // amortised across thousands of dabs.
        ensure_per_brush_pipeline(gpu, pipeline_ref, &compiled);

        let stroke = gpu
            .stroke
            .as_ref()
            .expect("paint::flush_dabs requires stroke resources");
        let scratch = &*stroke.scratch;
        let paint_target = &stroke.paint_target;
        let canvas_ext = paint_target.canvas_extent();
        let layer_offset = [canvas_ext.x0(), canvas_ext.y0()];
        let layer_size = [canvas_ext.width, canvas_ext.height];

        // Build the uniform buffer: intrinsic header + node fields.
        // Per-stroke not per-dab, but still no need to clone.
        let mut uniform_bytes: Vec<u8> = Vec::with_capacity(MAX_UNIFORM_BYTES);
        pack_intrinsic_uniforms(
            &mut uniform_bytes,
            gpu.intrinsic_header(layer_offset, layer_size),
        );
        let outputs = gpu
            .dab_batch
            .slot_outputs
            .as_ref()
            .expect("paint::flush_dabs requires dab_batch.slot_outputs");
        pack_uniforms(&compiled, outputs, &mut uniform_bytes);

        pipeline_ref.with_pipeline(compiled.topology_hash, |per_brush| {
            // Pad uniform bytes up to the per-brush uniform size so the
            // ring entry's binding_size matches.
            if uniform_bytes.len() < per_brush.uniform_size {
                uniform_bytes.resize(per_brush.uniform_size, 0);
            }
            // Reset the ring before each flush — the ring is per-
            // brush and isn't shared with other terminals, so this is
            // safe (we own all live writes in this `flush_dabs`).
            per_brush.uniform_ring.reset();
            let uniform_offset = per_brush.uniform_ring.write(gpu.queue, &uniform_bytes);

            // Upload the dab records.
            gpu.queue
                .write_buffer(&per_brush.dabs_buffer, 0, &dab_bytes);

            // Always source-over at per-dab. Paint-vs-erase routes through
            // `gpu.blend_mode` in `commit_brush_dab`; see `paint_pipeline`'s
            // doc on `PerBrushPipeline`.
            let pipeline = &per_brush.paint_pipeline;
            let mut pass = gpu.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("paint-flush"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: scratch.write_view(),
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                })],
                ..Default::default()
            });
            pass.set_viewport(
                0.0,
                0.0,
                layer_size[0] as f32,
                layer_size[1] as f32,
                0.0,
                1.0,
            );
            pass.set_pipeline(pipeline);
            pass.set_bind_group(0, &per_brush.uniform_bind_group, &[uniform_offset]);
            pass.set_bind_group(1, &per_brush.dabs_bind_group, &[]);
            pass.set_bind_group(2, gpu.selection_bind_group, &[]);
            // `@group(3)` holds the brush's graph textures (paper
            // grain etc.) when any are requested. Paint never uses
            // group 3 for anything else.
            if let Some(graph_bg) = per_brush.graph_textures_bind_group.as_ref() {
                pass.set_bind_group(3, graph_bg, &[]);
            }
            pass.draw(0..6, 0..total_dabs);
        });

        gpu.perf.record_dab_flush(total_dabs);
    }

    fn commit(&self, ctx: &EvalContext, gpu: &mut BrushGpuContext) {
        let Some(stroke) = gpu.stroke.as_ref() else {
            return;
        };
        let opacity = ctx.input_f32("opacity").clamp(0.0, 1.0);
        stroke.paint_target.commit_brush_dab(
            &mut gpu.encoder,
            gpu.pipelines,
            gpu.queue,
            stroke.scratch.write_bind_group(),
            gpu.selection_bind_group,
            stroke.pre_stroke_bind_group,
            opacity,
            gpu.blend_mode,
            /* fg_premultiplied */ true,
        );
    }

    /// Hover-cursor preview — reuses the shared
    /// [`crate::brush::wgsl::render_compiled_cursor_preview`] helper.
    /// `paint`'s stroke body and preview body are the same
    /// source (no `compile_cursor_preview_body` override), so the cursor
    /// shows the brush color × shape × flow as the stroke would
    /// deposit.
    fn render_cursor_preview(
        &self,
        ctx: &EvalContext,
        gpu: &mut BrushGpuContext,
    ) -> Vec<(String, ScalarValue)> {
        let radius = Self::effective_radius(ctx);
        let _ = crate::brush::wgsl::render_compiled_cursor_preview(gpu, radius);
        vec![]
    }

    /// Emit the fragment-shader body's terminal — multiplies the
    /// upstream graph's premultiplied RGBA expression by the
    /// selection mask and returns. The framework's
    /// [`crate::brush::wgsl::assemble_shader`] places the
    /// node bodies inside `fs_main` already bound with `d`, `u`,
    /// `local_uv`, `local_dist`, `theta`, `target_pos`, and `sel`.
    fn compile_wgsl(&self, cctx: &CompileWgslCtx) -> Result<NodeWgsl, String> {
        let mut wgsl = NodeWgsl::default();
        let rgba_expr = match cctx.inputs.get("rgba") {
            Some(InputBinding::Wired(expr)) => expr.clone(),
            _ => {
                // Unwired rgba — fall back to opaque white modulated
                // by the soft-disc that the wrapper's `local_dist`
                // gives us. This makes a graph with just
                // pen → paint still produce something
                // visible, mirroring `paint`'s procedural-disc
                // fallback.
                "vec4<f32>(1.0, 1.0, 1.0, 1.0) * max(1.0 - local_dist, 0.0)".into()
            }
        };
        // Stroke-/dab-level flow cap. Matches the `paint` terminal's
        // `color[3] *= flow` step — folded directly into the
        // premultiplied rgba (multiply all four components). Wired
        // values flow through their dab-record field; unwired uses
        // the port default literal (1.0 by default).
        let flow_expr = cctx.input("flow").as_f32();
        wgsl.body = format!(
            "    let rgba = {rgba_expr};\n\
             \x20   let flow = clamp({flow_expr}, 0.0, 1.0);\n\
             \x20   return rgba * flow * sel;\n"
        );
        Ok(wgsl)
    }
}

// ── Per-brush pipeline build helper ─────────────────────────────────────

/// Build the per-brush pipeline for `compiled` if it isn't already
/// cached. Reconstructs a [`BuildContext`] from the `BrushGpuContext`'s
/// shared state — same BGLs and shared limits used at the original
/// `BrushPipelines::new` time, so the layouts match.
fn ensure_per_brush_pipeline(
    gpu: &BrushGpuContext,
    pipe: &PaintPipeline,
    compiled: &CompiledBrush,
) {
    // Skip the work entirely if the pipeline is already cached.
    if pipe.cache.borrow().contains_key(&compiled.topology_hash) {
        return;
    }
    let ctx = BuildContext {
        device: gpu.device,
        queue: gpu.queue,
        uniform_bgl: gpu.pipelines.uniform_bind_group_layout(),
        selection_bgl: gpu.pipelines.selection_bind_group_layout(),
        canvas_copy_bgl: gpu.pipelines.canvas_copy_bind_group_layout(),
        canvas_copy_sampler: gpu.pipelines.canvas_copy_sampler(),
        min_uniform_align: gpu.device.limits().min_uniform_buffer_offset_alignment,
        texture_registry: gpu.pipelines.texture_registry(),
    };
    pipe.ensure_pipeline(&ctx, compiled);
}