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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//! GPU-side state for the document's global selection: ping-pong R8 textures,
//! the shared selection-mask bind group, and the boolean-op render pipelines.
//!
//! The selection itself is a typed [`crate::document::Filter`] attached at
//! the document root, with its pixel-level metadata (`active`, `pixel_bounds`,
//! `cpu_cache`) on [`SelectionFilter`]. What lives here is purely the GPU
//! realisation: textures, bind group, and the shaders that mutate them.
//!
//! Both the brush and paint pipelines sample the mask through a single shared
//! [`selection_mask_bgl`], so one bind group serves every consumer.
//!
//! Ping-pong: combine/invert ops can't read+write the same texture in a single
//! render pass, so we keep two R8 textures and swap which is "current". The
//! bind group always references the current one and is rebuilt after a swap.

use crate::document::SelectionMode;
use crate::gpu::ortho_transform::{OrthoTransformPass, OrthoXform};
use crate::layer::LayerId;

/// Allocate the ping-pong pair of R8 selection textures at `(w, h)`. Shared by
/// every path that (re)allocates the selection mask so the descriptor stays in
/// one place.
fn alloc_sel_textures(device: &wgpu::Device, w: u32, h: u32) -> [wgpu::Texture; 2] {
    std::array::from_fn(|i| {
        device.create_texture(&wgpu::TextureDescriptor {
            label: Some(if i == 0 { "sel-tex-0" } else { "sel-tex-1" }),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        })
    })
}

/// Reusable GPU pipelines for selection boolean operations.
/// Created once in `DarklyEngine::new()`.
pub struct SelectionPipelines {
    combine_pipeline: wgpu::RenderPipeline,
    combine_bgl: wgpu::BindGroupLayout,
    mode_buf: wgpu::Buffer,
    sampler: wgpu::Sampler,
    /// Recyclable R8 texture used as `combine`'s `shape_tex` binding.
    /// Sized to exactly the selection's `(width, height)` because the
    /// combine shader samples with UV in `[0, 1]` over the full texture
    /// extent — a larger scratch would shift the UV mapping and miss the
    /// uploaded shape data. Re-allocated only when the selection's
    /// dimensions change (canvas resize, document load).
    shape_scratch: Option<ShapeScratch>,

    /// Shared layout for the single-input passes (texture + sampler +
    /// uniform): morphology and blur both sample one R8 source, so one layout
    /// and one pipeline-layout serve both pipelines.
    single_bgl: wgpu::BindGroupLayout,
    morph_pipeline: wgpu::RenderPipeline,
    morph_buf: wgpu::Buffer,
    blur_pipeline: wgpu::RenderPipeline,
    blur_buf: wgpu::Buffer,
    /// Reusable R8 scratch textures, sized to the selection, for composite ops
    /// (border) that hold intermediate masks across passes. Realloc'd when the
    /// selection's dimensions change, mirroring `shape_scratch`.
    scratch_pool: Vec<ScratchTex>,
}

struct ShapeScratch {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    width: u32,
    height: u32,
}

struct ScratchTex {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    width: u32,
    height: u32,
}

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct CombineParams {
    mode: u32,
    _pad: [u32; 3],
}

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct MorphParams {
    op: u32,
    neighborhood: u32,
    texel: [f32; 2],
}

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct BlurParams {
    dir: [f32; 2],
    radius: i32,
    sigma: f32,
}

/// Single-pixel morphology step kind. `Dilate` (max) grows the mask, `Erode`
/// (min) shrinks it. Values match `selection_morph.wgsl`'s `op` uniform.
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum MorphOp {
    Dilate = 0,
    Erode = 1,
}

impl SelectionPipelines {
    pub fn new(device: &wgpu::Device) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("selection-combine"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!("../../shaders/selection_combine.wgsl").into(),
            ),
        });

        let combine_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("sel-combine-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("sel-combine-layout"),
            bind_group_layouts: &[Some(&combine_bgl)],
            immediate_size: 0,
        });

        let combine_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("sel-combine-pipeline"),
            layout: Some(&pipeline_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::R8Unorm,
                    blend: None,
                    write_mask: wgpu::ColorWrites::RED,
                })],
                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,
        });

        let mode_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("sel-combine-mode"),
            size: std::mem::size_of::<CombineParams>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("sel-combine-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            ..Default::default()
        });

        // Morphology + blur both sample one R8 source through this shared
        // layout (texture + sampler + per-pass uniform).
        let single_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("sel-single-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });
        let single_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("sel-single-layout"),
            bind_group_layouts: &[Some(&single_bgl)],
            immediate_size: 0,
        });

        let morph_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("selection-morph"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!("../../shaders/selection_morph.wgsl").into(),
            ),
        });
        let morph_pipeline =
            Self::build_single_input_pipeline(device, &single_layout, &morph_shader, "sel-morph");

        let blur_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("selection-blur"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!("../../shaders/selection_blur.wgsl").into(),
            ),
        });
        let blur_pipeline =
            Self::build_single_input_pipeline(device, &single_layout, &blur_shader, "sel-blur");

        let morph_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("sel-morph-params"),
            size: std::mem::size_of::<MorphParams>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let blur_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("sel-blur-params"),
            size: std::mem::size_of::<BlurParams>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        SelectionPipelines {
            combine_pipeline,
            combine_bgl,
            mode_buf,
            sampler,
            shape_scratch: None,
            single_bgl,
            morph_pipeline,
            morph_buf,
            blur_pipeline,
            blur_buf,
            scratch_pool: Vec::new(),
        }
    }

    /// Build a fullscreen-triangle pipeline that samples one R8 source and
    /// writes an R8 target — the common shape of the morphology and blur
    /// passes (only the fragment shader differs).
    fn build_single_input_pipeline(
        device: &wgpu::Device,
        layout: &wgpu::PipelineLayout,
        shader: &wgpu::ShaderModule,
        label: &str,
    ) -> wgpu::RenderPipeline {
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            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::R8Unorm,
                    blend: None,
                    write_mask: wgpu::ColorWrites::RED,
                })],
                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,
        })
    }

    /// Ensure `shape_scratch` is exactly `(w, h)` and return its view. The
    /// combine shader's UV must map `(0, 1)` to the uploaded data, so the
    /// scratch dimensions cannot be larger than the selection — when the
    /// selection's dims change we reallocate.
    fn ensure_shape_scratch(&mut self, device: &wgpu::Device, w: u32, h: u32) -> &ShapeScratch {
        let needs_alloc = match &self.shape_scratch {
            Some(s) => s.width != w || s.height != h,
            None => true,
        };
        if needs_alloc {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("sel-shape-scratch"),
                size: wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::R8Unorm,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.shape_scratch = Some(ShapeScratch {
                texture,
                view,
                width: w,
                height: h,
            });
        }
        self.shape_scratch.as_ref().unwrap()
    }

    /// Run the combine shader: reads `state.textures[current]` + shape → writes
    /// to `state.textures[1 - current]`, then swaps and rebuilds bind groups.
    pub fn combine(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        state: &mut SelectionState,
        shape_data: &[u8],
        mode: CombineMode,
    ) {
        let w = state.width;
        let h = state.height;

        self.ensure_shape_scratch(device, w, h);
        let scratch = self.shape_scratch.as_ref().expect("just ensured");
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &scratch.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            shape_data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(w),
                rows_per_image: None,
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
        let shape_view = &scratch.view;
        self.dispatch_combine(encoder, device, queue, state, shape_view, mode);
    }

    /// Run the combine shader with `state`'s current mask as `existing` and an
    /// arbitrary R8 view as `shape`, writing the result to the other ping-pong
    /// texture and swapping. Shared by [`combine`](Self::combine) (shape =
    /// uploaded scratch) and [`border`](Self::border) (shape = an intermediate
    /// scratch). `shape_view` must not alias `state`'s textures.
    fn dispatch_combine(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        state: &mut SelectionState,
        shape_view: &wgpu::TextureView,
        mode: CombineMode,
    ) {
        queue.write_buffer(
            &self.mode_buf,
            0,
            bytemuck::bytes_of(&CombineParams {
                mode: mode as u32,
                _pad: [0; 3],
            }),
        );

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sel-combine-bg"),
            layout: &self.combine_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&state.views[state.current]),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(shape_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: self.mode_buf.as_entire_binding(),
                },
            ],
        });

        let dst = 1 - state.current;
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("sel-combine-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &state.views[dst],
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                ..Default::default()
            });
            pass.set_pipeline(&self.combine_pipeline);
            pass.set_bind_group(0, &bind_group, &[]);
            pass.draw(0..3, 0..1);
        }

        state.current = dst;
        state.rebuild_bind_group(device);
    }

    /// One single-pixel morphology step: reads `state`'s current mask, writes
    /// the dilated/eroded result to the other ping-pong texture, swaps. The
    /// engine loops this N times (alternating `eight` for a rounder element).
    pub fn morph_step(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        state: &mut SelectionState,
        op: MorphOp,
        eight: bool,
    ) {
        queue.write_buffer(
            &self.morph_buf,
            0,
            bytemuck::bytes_of(&MorphParams {
                op: op as u32,
                neighborhood: if eight { 1 } else { 0 },
                texel: [1.0 / state.width as f32, 1.0 / state.height as f32],
            }),
        );
        self.single_input_pass(
            encoder,
            device,
            state,
            &self.morph_pipeline,
            &self.morph_buf,
        );
    }

    /// One separable Gaussian blur pass (horizontal or vertical) over `state`'s
    /// current mask. The engine runs an H pass then a V pass for feather /
    /// antialias. `radius` is the half-kernel extent; `sigma` the gaussian σ.
    pub fn blur_pass(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        state: &mut SelectionState,
        horizontal: bool,
        radius: i32,
        sigma: f32,
    ) {
        let dir = if horizontal {
            [1.0 / state.width as f32, 0.0]
        } else {
            [0.0, 1.0 / state.height as f32]
        };
        queue.write_buffer(
            &self.blur_buf,
            0,
            bytemuck::bytes_of(&BlurParams { dir, radius, sigma }),
        );
        self.single_input_pass(encoder, device, state, &self.blur_pipeline, &self.blur_buf);
    }

    /// Render a single-input pass (`pipeline` sampling `state`'s current mask
    /// with `params`) into the other ping-pong texture, then swap. Shared core
    /// of [`morph_step`](Self::morph_step) and [`blur_pass`](Self::blur_pass).
    fn single_input_pass(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        state: &mut SelectionState,
        pipeline: &wgpu::RenderPipeline,
        params: &wgpu::Buffer,
    ) {
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sel-single-bg"),
            layout: &self.single_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&state.views[state.current]),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: params.as_entire_binding(),
                },
            ],
        });

        let dst = 1 - state.current;
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("sel-single-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &state.views[dst],
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                ..Default::default()
            });
            pass.set_pipeline(pipeline);
            pass.set_bind_group(0, &bind_group, &[]);
            pass.draw(0..3, 0..1);
        }

        state.current = dst;
        state.rebuild_bind_group(device);
    }

    /// Replace the selection with a band of width `radius` straddling its
    /// edge: `dilate(radius) − erode(radius)`. Submits its own command buffers
    /// (one per morphology step plus the snapshot copies), so it takes the
    /// `GpuContext` rather than a borrowed encoder. No-op for `radius == 0`.
    pub fn border(
        &mut self,
        gpu: &crate::gpu::context::GpuContext,
        state: &mut SelectionState,
        radius: u32,
    ) {
        if radius == 0 {
            return;
        }
        let (w, h) = (state.width, state.height);
        // scratch[0] holds the original mask; scratch[1] the eroded interior.
        self.ensure_scratch(&gpu.device, 2, w, h);

        gpu.encode("sel-border-save", |e| {
            Self::copy_tex(
                e,
                &state.textures[state.current],
                &self.scratch_pool[0].texture,
                w,
                h,
            )
        });
        for i in 0..radius {
            gpu.encode("sel-border-erode", |e| {
                self.morph_step(
                    e,
                    &gpu.device,
                    &gpu.queue,
                    state,
                    MorphOp::Erode,
                    i % 2 == 1,
                )
            });
        }
        gpu.encode("sel-border-inner", |e| {
            Self::copy_tex(
                e,
                &state.textures[state.current],
                &self.scratch_pool[1].texture,
                w,
                h,
            )
        });
        gpu.encode("sel-border-restore", |e| {
            Self::copy_tex(
                e,
                &self.scratch_pool[0].texture,
                &state.textures[state.current],
                w,
                h,
            )
        });
        for i in 0..radius {
            gpu.encode("sel-border-dilate", |e| {
                self.morph_step(
                    e,
                    &gpu.device,
                    &gpu.queue,
                    state,
                    MorphOp::Dilate,
                    i % 2 == 1,
                )
            });
        }
        gpu.encode("sel-border-sub", |e| {
            let inner = &self.scratch_pool[1].view;
            self.dispatch_combine(
                e,
                &gpu.device,
                &gpu.queue,
                state,
                inner,
                CombineMode::Subtract,
            )
        });
    }

    /// Ensure `scratch_pool` holds `n` R8 textures of exactly `(w, h)`,
    /// reallocating when the count or selection dimensions change.
    fn ensure_scratch(&mut self, device: &wgpu::Device, n: usize, w: u32, h: u32) {
        let ok = self.scratch_pool.len() == n
            && self
                .scratch_pool
                .iter()
                .all(|s| s.width == w && s.height == h);
        if ok {
            return;
        }
        self.scratch_pool = (0..n)
            .map(|i| {
                let texture = device.create_texture(&wgpu::TextureDescriptor {
                    label: Some(if i == 0 {
                        "sel-scratch-0"
                    } else {
                        "sel-scratch-1"
                    }),
                    size: wgpu::Extent3d {
                        width: w,
                        height: h,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: wgpu::TextureFormat::R8Unorm,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING
                        | wgpu::TextureUsages::COPY_SRC
                        | wgpu::TextureUsages::COPY_DST,
                    view_formats: &[],
                });
                let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
                ScratchTex {
                    texture,
                    view,
                    width: w,
                    height: h,
                }
            })
            .collect();
    }

    fn copy_tex(
        encoder: &mut wgpu::CommandEncoder,
        src: &wgpu::Texture,
        dst: &wgpu::Texture,
        w: u32,
        h: u32,
    ) {
        encoder.copy_texture_to_texture(
            wgpu::TexelCopyTextureInfo {
                texture: src,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyTextureInfo {
                texture: dst,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
    }

    /// Run the combine shader in "invert" mode.
    pub fn invert(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        state: &mut SelectionState,
    ) {
        queue.write_buffer(
            &self.mode_buf,
            0,
            bytemuck::bytes_of(&CombineParams {
                mode: CombineMode::Invert as u32,
                _pad: [0; 3],
            }),
        );

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sel-invert-bg"),
            layout: &self.combine_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&state.views[state.current]),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&state.views[state.current]),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: self.mode_buf.as_entire_binding(),
                },
            ],
        });

        let dst = 1 - state.current;
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("sel-invert-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &state.views[dst],
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                ..Default::default()
            });
            pass.set_pipeline(&self.combine_pipeline);
            pass.set_bind_group(0, &bind_group, &[]);
            pass.draw(0..3, 0..1);
        }

        state.current = dst;
        state.rebuild_bind_group(device);
    }
}

#[repr(u32)]
pub enum CombineMode {
    Add = 0,
    Subtract = 1,
    Intersect = 2,
    Invert = 3,
}

impl CombineMode {
    pub fn from_selection_mode(mode: &SelectionMode) -> Self {
        match mode {
            SelectionMode::Add => CombineMode::Add,
            SelectionMode::Subtract => CombineMode::Subtract,
            SelectionMode::Intersect => CombineMode::Intersect,
            SelectionMode::Replace => unreachable!("Replace mode uses direct upload"),
        }
    }
}

// ---------------------------------------------------------------------------
// SelectionState — GPU resources for the global selection (compositor-owned)
// ---------------------------------------------------------------------------

/// The single bind group layout for sampling the selection mask, shared by
/// every consumer (brush + paint pipelines, and the cached [`SelectionState`]
/// bind group). One layout means one bind group: a `wgpu::BindGroup` is tied to
/// the exact layout it was built against, so without sharing each pipeline would
/// need its own (structurally identical) copy.
///
/// Visibility is `FRAGMENT | COMPUTE` — the union of where the mask is sampled:
/// paint reads it in a fragment shader, brush nodes also read it from compute
/// shaders. A render pipeline may legally use a layout whose visibility is a
/// superset of the stages it actually uses, so this single layout serves both.
pub fn selection_mask_bgl(device: &wgpu::Device) -> wgpu::BindGroupLayout {
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("selection-mask-bgl"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::FRAGMENT | wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Texture {
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                    view_dimension: wgpu::TextureViewDimension::D2,
                    multisampled: false,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::FRAGMENT | wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                count: None,
            },
        ],
    })
}

/// Ping-pong R8 textures + the selection mask bind group for the document's
/// global selection. Allocated by the compositor when the selection filter is
/// first needed; lives until the document is dropped.
pub struct SelectionState {
    pub textures: [wgpu::Texture; 2],
    pub views: [wgpu::TextureView; 2],
    /// Index into `textures` for the current (read) selection data.
    pub current: usize,
    /// The selection mask is consumed by both the brush and paint pipelines.
    /// Both share a single [`selection_mask_bgl`] layout, so one bind group
    /// serves every consumer — see that function's note on visibility.
    bind_group: wgpu::BindGroup,
    /// Cloned at construction (cheap, Arc-backed) so reallocating ops can
    /// rebuild `bind_group` against the new texture view without the caller
    /// threading the layout through.
    bgl: wgpu::BindGroupLayout,
    /// Constant across the state's lifetime; built once instead of per-rebuild.
    sampler: wgpu::Sampler,
    /// Filter id this state is paired with (for region-store and undo
    /// keying — the document's selection filter id).
    pub filter_id: LayerId,
    pub width: u32,
    pub height: u32,
}

impl SelectionState {
    pub fn new(
        device: &wgpu::Device,
        filter_id: LayerId,
        width: u32,
        height: u32,
        bgl: &wgpu::BindGroupLayout,
    ) -> Self {
        let textures = alloc_sel_textures(device, width, height);
        let views = [
            textures[0].create_view(&wgpu::TextureViewDescriptor::default()),
            textures[1].create_view(&wgpu::TextureViewDescriptor::default()),
        ];

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("sel-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            ..Default::default()
        });

        let bind_group = Self::make_bg(device, &views[0], &sampler, bgl);

        SelectionState {
            textures,
            views,
            current: 0,
            bind_group,
            bgl: bgl.clone(),
            sampler,
            filter_id,
            width,
            height,
        }
    }

    pub fn texture(&self) -> &wgpu::Texture {
        &self.textures[self.current]
    }

    /// The selection mask bind group, usable by both the brush and paint
    /// pipelines (they share [`selection_mask_bgl`]).
    pub fn selection_bind_group(&self) -> &wgpu::BindGroup {
        &self.bind_group
    }

    /// Borrow the current selection texture as a `CanvasFrame`. The selection
    /// texture is window-sized; its `canvas_extent` is window-local `(0, 0,
    /// w, h)` (the plane anchoring is realized by [`Self::resize`], not by a
    /// non-zero extent origin — see CLAUDE.md selection notes).
    pub fn canvas_frame(&self) -> crate::gpu::atlas::CanvasFrame<'_> {
        crate::gpu::atlas::CanvasFrame {
            texture: self.texture(),
            canvas_extent: crate::coord::CanvasRect::from_xywh(0, 0, self.width, self.height),
        }
    }

    /// Re-realize the window-sized selection mask for a moved/resized canvas
    /// window (crop / canvas resize).
    ///
    /// The mask is a window-sized R8 texture whose pixel `(0, 0)` represents
    /// the plane position `old_origin`. When the window moves to `new_rect`,
    /// allocate fresh ping-pong textures at the new dimensions, clear them to
    /// "unselected", and copy the **plane-overlap** of the old and new windows
    /// — preserving which *plane* pixels stay selected. Selection outside the
    /// new window is clipped away. Same overlap-anchored copy as
    /// [`Compositor::resize_node_texture`], generalized to a window that may
    /// move in any direction (so the overlap is clipped, not assumed to grow).
    pub fn resize(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        old_origin: crate::coord::CanvasPoint,
        new_rect: crate::coord::CanvasRect,
    ) {
        use crate::coord::CanvasRect;
        let new_w = new_rect.width;
        let new_h = new_rect.height;

        let new_textures = alloc_sel_textures(device, new_w, new_h);
        let new_views = [
            new_textures[0].create_view(&wgpu::TextureViewDescriptor::default()),
            new_textures[1].create_view(&wgpu::TextureViewDescriptor::default()),
        ];

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("sel-resize"),
        });
        // Clear the new "current" texture (index 0) to unselected (0). The
        // other ping-pong side is overwritten by the next combine pass.
        {
            let _clear = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("sel-resize-clear"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &new_views[0],
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                ..Default::default()
            });
        }

        let old_rect = CanvasRect::new(old_origin, self.width, self.height);
        if let Some(ov) = old_rect.intersect(new_rect) {
            let src_x = (ov.origin.x - old_origin.x) as u32;
            let src_y = (ov.origin.y - old_origin.y) as u32;
            let dst_x = (ov.origin.x - new_rect.origin.x) as u32;
            let dst_y = (ov.origin.y - new_rect.origin.y) as u32;
            encoder.copy_texture_to_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.textures[self.current],
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: src_x,
                        y: src_y,
                        z: 0,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyTextureInfo {
                    texture: &new_textures[0],
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: dst_x,
                        y: dst_y,
                        z: 0,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::Extent3d {
                    width: ov.width,
                    height: ov.height,
                    depth_or_array_layers: 1,
                },
            );
        }
        queue.submit([encoder.finish()]);

        self.textures = new_textures;
        self.views = new_views;
        self.current = 0;
        self.width = new_w;
        self.height = new_h;

        self.rebuild_bind_group(device);
    }

    /// Orthogonally transform the selection mask about its own centre (which
    /// coincides with the canvas centre — the mask is window-sized). Flips and
    /// 180° rotate ping-pong in place; 90° rotations swap the mask dimensions
    /// to match the rotated canvas. Exact, like every ortho transform.
    pub fn apply_ortho(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        pass: &OrthoTransformPass,
        xform: OrthoXform,
    ) {
        let (old_w, old_h) = (self.width, self.height);
        let r8 = wgpu::TextureFormat::R8Unorm;
        if xform.swaps_dims() {
            let (new_w, new_h) = (old_h, old_w);
            let new_textures = alloc_sel_textures(device, new_w, new_h);
            let new_views = [
                new_textures[0].create_view(&wgpu::TextureViewDescriptor::default()),
                new_textures[1].create_view(&wgpu::TextureViewDescriptor::default()),
            ];
            pass.render_remap(
                device,
                queue,
                encoder,
                &self.views[self.current],
                &new_views[0],
                old_w,
                old_h,
                xform,
                r8,
            );
            self.textures = new_textures;
            self.views = new_views;
            self.current = 0;
            self.width = new_w;
            self.height = new_h;
        } else {
            let dst = 1 - self.current;
            pass.render_remap(
                device,
                queue,
                encoder,
                &self.views[self.current],
                &self.views[dst],
                old_w,
                old_h,
                xform,
                r8,
            );
            self.current = dst;
        }
        self.rebuild_bind_group(device);
    }

    /// Replace the selection with a tight-bounds rasterized R8 region. Clears
    /// the previous active region first, then writes the new one.
    pub fn upload_replace(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        old_bounds: Option<crate::coord::WindowRect>,
        mask: &crate::mask::RasterizedMask,
    ) {
        if let Some(bounds) = old_bounds {
            let ow = bounds.width;
            let oh = bounds.height;
            let zeros = vec![0u8; (ow * oh) as usize];
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.textures[self.current],
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: bounds.x0() as u32,
                        y: bounds.y0() as u32,
                        z: 0,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                &zeros,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(ow),
                    rows_per_image: None,
                },
                wgpu::Extent3d {
                    width: ow,
                    height: oh,
                    depth_or_array_layers: 1,
                },
            );
        }

        if mask.width > 0 && mask.height > 0 {
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.textures[self.current],
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: mask.x,
                        y: mask.y,
                        z: 0,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                &mask.data,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(mask.width),
                    rows_per_image: None,
                },
                wgpu::Extent3d {
                    width: mask.width,
                    height: mask.height,
                    depth_or_array_layers: 1,
                },
            );
        }

        self.rebuild_bind_group(device);
    }

    /// Replace the selection with a full-canvas R8 buffer (magic wand, mask-
    /// to-selection).
    pub fn upload_replace_full(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, data: &[u8]) {
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &self.textures[self.current],
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(self.width),
                rows_per_image: None,
            },
            wgpu::Extent3d {
                width: self.width,
                height: self.height,
                depth_or_array_layers: 1,
            },
        );

        self.rebuild_bind_group(device);
    }

    /// Zero out the previously-active region (clear). `bounds` are window-local
    /// (the selection texture is window-sized; see `crate::coord`).
    pub fn clear_region(&mut self, queue: &wgpu::Queue, bounds: Option<crate::coord::WindowRect>) {
        if let Some(bounds) = bounds {
            let ow = bounds.width;
            let oh = bounds.height;
            let zeros = vec![0u8; (ow * oh) as usize];
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.textures[self.current],
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: bounds.x0() as u32,
                        y: bounds.y0() as u32,
                        z: 0,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                &zeros,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(ow),
                    rows_per_image: None,
                },
                wgpu::Extent3d {
                    width: ow,
                    height: oh,
                    depth_or_array_layers: 1,
                },
            );
        }
    }

    /// Rebuild the bind group after a ping-pong swap or texture reallocation,
    /// re-pointing it at the now-current view. Uses the layout + sampler the
    /// state owns, so callers never thread them through.
    fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
        self.bind_group =
            Self::make_bg(device, &self.views[self.current], &self.sampler, &self.bgl);
    }

    fn make_bg(
        device: &wgpu::Device,
        view: &wgpu::TextureView,
        sampler: &wgpu::Sampler,
        layout: &wgpu::BindGroupLayout,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sel-bg"),
            layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
            ],
        })
    }
}