Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
1873 lines (1780 loc) · 80.7 KB
/
Copy pathlib.rs
File metadata and controls
1873 lines (1780 loc) · 80.7 KB
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
//! GPU compositor (architecture §7.2, milestone M5).
//!
//! Renders a [`Document`] with wgpu, producing the same straight-alpha composite as the CPU
//! reference (`photocraft-compose`) within ~1/255:
//!
//! - **Residency.** Layer and mask surfaces live on the GPU in square *pages* (up to [`PAGE`]²,
//! never above the device's texture limit) covering their allocated tiles. A page is uploaded
//! only when a chunk inside it is drawn, and surfaces are copy-on-write `Arc` tiles, so a tile
//! is re-uploaded only when its `Arc` changed (a brush stroke uploads just the touched 256²
//! tiles; undo swaps pointers back and uploads only what differs). RGBA8 tiles upload with
//! zero conversion. Pages over a byte budget are evicted least recently used first.
//! - **Planner** ([`plan`]). The layer tree becomes a linear list of passes over abstract
//! chunk-sized buffers (blend with every Photoshop mode, opacity × fill, masks, clipping groups,
//! pass-through vs isolated groups, adjustments, solid / gradient fills, layer effects).
//! - **Layer effects** (`fx.rs`). Each effect layer's maps (shadow, glow, satin, bevel, stroke
//! bands) are built by fragment passes over its effect region and cached on the GPU per layer
//! state; a brush stroke rebuilds only the damaged tiles grown by the effect reach. A region
//! larger than the texture limit is built per page cell, over the cell grown by the effects'
//! reach, so every map is exact inside its cell.
//! - **Execution.** The canvas is processed page cell by page cell, each in chunks (1024²
//! RGBA32F accumulators, reused) that bind only that cell's pages, and each finished chunk is
//! handed to a caller-supplied sink, e.g. to encode it straight into a display texture — no
//! readback. Documents of any size composite on the GPU; a huge refresh submits as it goes, so
//! staged uploads and evicted pages stay bounded.
//!
//! Vector masks (rasterised once per mask state into a combined mask texture), layers clipped to
//! pass-through groups, stroked shapes with clipped layers (fill and stroke split once per shape
//! state), pattern fills and artboards are planned like everything else. What remains
//! (Multichannel documents, patterns larger than the texture limit) returns [`Unsupported`];
//! callers fall back to the CPU compositor.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bounds;
mod fx;
pub mod plan;
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::Arc;
use photocraft_color::{PixelFormat, SampleType};
use photocraft_compose::effects::FieldKind;
use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, Pattern};
use photocraft_geom::{Rect, TILE_SIZE, TileCoord};
use photocraft_raster::{Surface, Tile};
pub use plan::{Kernel, Plan, Role, Unsupported, plan};
/// Accumulator format for intermediate buffers. Full float: discontinuous operations
/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as
/// the CPU reference, and Color Burn/Dodge amplify input error.
pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; // default accumulation format; `preferred_acc_format` downgrades to Rgba16Float where 32-bit float isn't renderable
/// Effect intermediates (distances, blurs) and layer shapes.
const MAP32: wgpu::TextureFormat = wgpu::TextureFormat::R32Float;
/// Final effect coverage maps (0..1; half precision is ~1/4000).
const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float;
/// Side of the square chunks the canvas is processed in.
pub const CHUNK: u32 = 1024;
const STRIDE: u64 = 256;
const CHUNK_UNIFORM: u64 = 16;
const OP_UNIFORM: u64 = 176;
/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame.
pub const FX_BUDGET: usize = 1536 << 20;
/// Largest side of the square pages layer surfaces are stored in on the GPU (smaller when the
/// device's texture limit is). A chunk only binds the pages of the cell it lies in, so layers of
/// any size composite on the GPU.
pub const PAGE: u32 = 2048;
/// GPU memory resident layer pages may hold before the least recently used are evicted.
pub const RESIDENT_BUDGET: u64 = 4 << 30;
/// Uploads (bytes) [`Compositor::render`] stages before submitting the work recorded so far, so
/// a refresh of a huge document never holds all its uploads in staging memory at once.
const FLUSH_BYTES: u64 = 512 << 20;
/// Pass pixels (chunk pixels × passes) [`Compositor::render`] records before submitting: one
/// command buffer holding a whole huge refresh can run for seconds, long enough for the OS to
/// reset the GPU.
const FLUSH_WORK: u64 = 1 << 30;
/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the
/// texture's origin.
pub struct ChunkOut<'a> {
pub rect: Rect,
pub texture: &'a wgpu::Texture,
pub view: &'a wgpu::TextureView,
}
/// What a render did (for profiling and tests).
#[derive(Clone, Copy, Debug, Default)]
pub struct Stats {
pub passes: usize,
pub chunks: usize,
pub slots: u32,
pub tiles_uploaded: usize,
pub bytes_uploaded: usize,
/// Effect layers whose shape was (re)rendered, fully or partially.
pub fx_shapes: usize,
/// Effect map programs run (one per effect whose maps were rebuilt).
pub fx_programs: usize,
/// Effect-map pixels written (all stages).
pub fx_pixels: u64,
/// Page cells the region spans (each binds only the layer pages it overlaps).
pub cells: usize,
/// Layer pages and paged effect maps evicted to stay within the memory budgets.
pub evicted: usize,
/// Intermediate submits of a huge refresh (to bound staging and evicted memory).
pub flushes: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TexKind {
/// RGBA8 tiles copied verbatim.
Rgba8Direct,
/// Other 8-bit formats converted to RGBA8.
Rgba8,
/// 16/32-bit formats converted to RGBA16F.
Rgba16F,
/// GRAY8 masks copied verbatim.
R8Direct,
/// Other masks as R32F.
R32F,
}
impl TexKind {
fn for_surface(role: Role, f: PixelFormat) -> Self {
match role {
Role::Content | Role::Stroke if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct,
Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8,
Role::Content | Role::Stroke => TexKind::Rgba16F,
Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct,
Role::Mask => TexKind::R32F,
}
}
fn format(self) -> wgpu::TextureFormat {
match self {
TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm,
TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float,
TexKind::R8Direct => wgpu::TextureFormat::R8Unorm,
TexKind::R32F => wgpu::TextureFormat::R32Float,
}
}
fn bytes_per_pixel(self) -> usize {
match self {
TexKind::Rgba8Direct | TexKind::Rgba8 => 4,
TexKind::Rgba16F => 8,
TexKind::R8Direct => 1,
TexKind::R32F => 4,
}
}
}
/// Index into the render's resident key list, and the texture's region (x, y, w, h).
type ResidentRef = (usize, [i32; 4]);
/// A page cell: the square `[x·page, (x+1)·page) × [y·page, (y+1)·page)` of document pixels.
type Cell = (i32, i32);
/// A resident layer page.
type ResKey = (LayerId, Role, Cell);
/// Effect maps of a layer: over its whole effect region (`None`), or one page cell of a region
/// larger than the texture limit.
type FxKey = (LayerId, Option<Cell>);
struct Resident {
texture: wgpu::Texture,
view: wgpu::TextureView,
/// Document-pixel rect covered (tile aligned, inside one page cell).
region: Rect,
kind: TexKind,
format: PixelFormat,
tiles: HashMap<TileCoord, Arc<Tile>>,
default_nonzero: bool,
doc: DocId,
last_used: u64,
/// Cell visit that last used it (least recently used pages are evicted first).
stamp: u64,
/// CMYK profile the texels were converted with (`CmykSpace::id`, 0 = built-in / not CMYK).
cmyk: u64,
}
impl Resident {
fn bytes(&self) -> u64 {
self.region.width() as u64 * self.region.height() as u64 * self.kind.bytes_per_pixel() as u64
}
}
/// A texture and its default view.
#[derive(Clone)]
struct Tex {
texture: wgpu::Texture,
view: wgpu::TextureView,
}
impl Tex {
fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
});
let view = texture.create_view(&Default::default());
Tex { texture, view }
}
fn map(device: &wgpu::Device, label: &str, r: Rect, format: wgpu::TextureFormat) -> Self {
Tex::new(
device,
label,
r.width(),
r.height(),
format,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
)
}
/// Upload R32F values (row-major over `r`) into this region-space texture at `r`.
fn write_r32(&self, queue: &wgpu::Queue, region: Rect, r: Rect, v: &[f32]) {
if r.is_empty() {
return;
}
let bytes: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.texture,
mip_level: 0,
origin: wgpu::Origin3d { x: (r.x0 - region.x0) as u32, y: (r.y0 - region.y0) as u32, z: 0 },
aspect: wgpu::TextureAspect::All,
},
&bytes,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(r.width() * 4), rows_per_image: Some(r.height()) },
wgpu::Extent3d { width: r.width(), height: r.height(), depth_or_array_layers: 1 },
);
}
fn bytes(&self) -> usize {
let s = self.texture.size();
let bpp = match self.texture.format() {
wgpu::TextureFormat::R16Float => 2,
wgpu::TextureFormat::Rgba32Float => 16,
wgpu::TextureFormat::Rgba16Float => 8,
_ => 4,
};
s.width as usize * s.height as usize * bpp
}
}
/// Cached maps of one effect (one enabled item of a layer).
struct ProgState {
key: u64,
maps: Vec<Option<Tex>>,
}
/// Cached effect state of one layer.
struct FxEntry {
doc: DocId,
region: Rect,
shape_key: u64,
/// Tiles the shape was rendered from (content, mask): damage is their difference.
tiles: [Option<fx::Tiles>; 2],
/// Groups: a clone pinning the tile pointers `shape_key` hashes.
_pin: Option<Layer>,
/// The shape on the CPU (distance fields are computed from it) and on the GPU.
shape_cpu: Vec<f32>,
shape: Tex,
/// Distance fields: the reach each is exact to, and its texture.
fields: HashMap<FieldKind, (i32, Tex)>,
progs: Vec<ProgState>,
last_used: u64,
stamp: u64,
}
impl FxEntry {
fn bytes(&self) -> usize {
self.shape.bytes()
+ self.shape_cpu.len() * 4
+ self.fields.values().map(|(_, t)| t.bytes()).sum::<usize>()
+ self.progs.iter().flat_map(|p| p.maps.iter().flatten()).map(Tex::bytes).sum::<usize>()
}
}
/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted).
#[derive(Clone)]
struct Kit {
pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>,
bgl0: wgpu::BindGroupLayout,
bgl1: wgpu::BindGroupLayout,
dummy: wgpu::TextureView,
}
/// One draw of an effect-map kernel (outside the chunk loop).
struct MapDraw {
kernel: Kernel,
format: wgpu::TextureFormat,
target: wgpu::TextureView,
/// Target-local scissor (x, y, w, h).
scissor: [u32; 4],
/// Chunk record: origin and size of the target's space.
space: [i32; 4],
op: Vec<u8>,
views: [Option<wgpu::TextureView>; 8],
lut: Option<Arc<Vec<f32>>>,
}
impl Kit {
/// Record `draws` (each its own render pass) into `encoder`.
fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) {
if draws.is_empty() {
return;
}
let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize];
for (i, d) in draws.iter().enumerate() {
let w = words(&[I(d.space[0]), I(d.space[1]), I(d.space[2]), I(d.space[3])]);
data[2 * i * STRIDE as usize..][..w.len()].copy_from_slice(&w);
data[(2 * i + 1) * STRIDE as usize..][..d.op.len()].copy_from_slice(&d.op);
}
let ubuf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("pc_fx_uniforms"),
size: data.len() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
queue.write_buffer(&ubuf, 0, &data);
let bg0 = uniform_group(device, &self.bgl0, &ubuf);
for (i, d) in draws.iter().enumerate() {
let lut = d.lut.as_ref().map(|l| {
let mut row = [0.0f32; 4096];
row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]);
lut_texture(device, queue, &[row])
});
let mut views: Vec<&wgpu::TextureView> = d.views.iter().map(|v| v.as_ref().unwrap_or(&self.dummy)).collect();
if let Some((_, lv)) = &lut {
views[4] = lv;
}
let bg1 = texture_group(device, &self.bgl1, &views);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("pc_fx_map"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &d.target,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]);
pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]);
pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]);
pass.set_bind_group(1, &bg1, &[]);
pass.draw(0..3, 0..1);
}
}
}
fn uniform_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, ubuf: &wgpu::Buffer) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("pc_compose_uniforms"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }),
},
],
})
}
fn texture_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, views: &[&wgpu::TextureView]) -> wgpu::BindGroup {
let e: Vec<wgpu::BindGroupEntry> =
views.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect();
device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout, entries: &e })
}
/// GPU compositor. Create once per device; call [`Compositor::render`] per refresh.
pub struct Compositor {
kit: Kit,
pool: Vec<(wgpu::Texture, wgpu::TextureView)>,
residents: HashMap<ResKey, Resident>,
fx: HashMap<FxKey, FxEntry>,
/// Effect temporaries (R32F, region sized) and the frame they were last used.
temps: Vec<(Tex, u64)>,
patterns: HashMap<String, (u64, Tex)>,
/// Texture side limit the paging is planned for (the device's, or smaller in tests).
max_dim: u32,
/// The device's real texture side limit.
device_max: u32,
/// Page side (a power of two, multiple of the tile size, at most `max_dim`).
page: u32,
/// Chunk side (divides `page`).
chunk: u32,
resident_budget: u64,
/// GPU memory the effect-map cache may hold ([`FX_BUDGET`] or less).
fx_budget: u64,
/// What the view shows: a full refresh draws these cells last, so their pages are the
/// ones still resident for the edits that follow.
focus: Option<Rect>,
frame: u64,
/// Cell visits so far (LRU clock of pages).
stamp: u64,
/// Bytes staged by uploads since the last submit.
staged: u64,
acc_format: wgpu::TextureFormat,
/// Whether the effect-map pipelines could be built (else documents with layer effects are
/// [`Unsupported`] and use the CPU compositor).
effect_maps: bool,
/// `CmykSpace::id` of the document being encoded (0: built-in coated CMYK).
cmyk: u64,
}
fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
}
}
fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: NonZeroU64::new(size) },
count: None,
}
}
/// The compositor's WGSL source (exposed for validation in tests).
pub const SHADER: &str = include_str!("compose.wgsl");
/// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect
/// maps (view and region) per pass.
struct Bound {
views: Vec<(Option<ResidentRef>, Option<ResidentRef>)>,
keys: Vec<ResKey>,
maps: Vec<Option<(wgpu::TextureView, Rect)>>,
}
/// Pass-level resources shared by every cell of a frame.
struct FrameRes {
/// Tile area of each pass's (texture, mask) surface within the canvas tile grid.
areas: Vec<(Rect, Rect)>,
luts: Vec<Option<(wgpu::Texture, wgpu::TextureView)>>,
patterns: Vec<Option<wgpu::TextureView>>,
}
/// Document pixels of page cell `c`.
fn cell_rect(c: Cell, page: u32) -> Rect {
let p = page as i32;
Rect::new(c.0.saturating_mul(p), c.1.saturating_mul(p), c.0.saturating_add(1).saturating_mul(p), c.1.saturating_add(1).saturating_mul(p))
}
/// `r` cut along the grid of `step`-sized squares (row-major).
fn grid_rects(r: Rect, step: u32) -> Vec<Rect> {
let s = step.max(1) as i32;
let mut out = Vec::new();
let mut y = r.y0.div_euclid(s) * s;
while y < r.y1 {
let mut x = r.x0.div_euclid(s) * s;
while x < r.x1 {
out.push(Rect::new(x, y, x.saturating_add(s), y.saturating_add(s)).intersect(&r));
x = x.saturating_add(s);
}
y = y.saturating_add(s);
}
out
}
/// The reach up to which each distance field must be exact (the largest any program asks for).
fn field_reaches(progs: &[fx::MapProgram]) -> HashMap<FieldKind, i32> {
let mut want: HashMap<FieldKind, i32> = HashMap::new();
for (k, r) in progs.iter().flat_map(|p| p.fields.iter()) {
let w = want.entry(*k).or_insert(0);
*w = (*w).max(*r);
}
want
}
/// Runs `f` inside validation and internal-error scopes and returns the first error raised.
/// Native wgpu reports errors synchronously; where they only arrive asynchronously (WebGPU) none
/// is reported.
fn first_error<T>(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option<wgpu::Error>) {
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
let out = f();
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
let mut error = None;
// Scopes pop in reverse order.
for pop in [internal.pop(), validation.pop()] {
if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) {
error.get_or_insert(e);
}
}
(out, error)
}
impl Compositor {
/// Create a compositor with the default accumulation format ([`ACC_FORMAT`]).
pub fn new(device: &wgpu::Device) -> Self {
Self::new_with_format(device, ACC_FORMAT)
}
/// The accumulation format to use on `adapter`: `Rgba32Float` when it can be a render target,
/// else `Rgba16Float`. Some drivers (e.g. Intel Vulkan) don't support rendering to `Rgba32Float`
/// and would otherwise panic at render-pipeline creation.
pub fn preferred_acc_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat {
let feats = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba32Float);
if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float }
}
/// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a
/// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back
/// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed
/// to have worked.
pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result<Self, Unsupported> {
match first_error(device, || Self::new_with_format(device, acc_format)) {
(comp, None) => Ok(comp),
(_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))),
}
}
/// Create a compositor whose accumulation/render-target format is `acc_format`. Pass
/// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers),
/// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`.
pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("pc_compose_uniforms"),
entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)],
});
let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("pc_compose_textures"),
entries: &(0..8).map(tex_entry).collect::<Vec<_>>(),
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pc_compose"),
bind_group_layouts: &[Some(&bgl0), Some(&bgl1)],
immediate_size: 0,
});
// `None` only for kernels without a fragment entry point, which are never drawn.
let pipeline = |k: Kernel, format: wgpu::TextureFormat| {
let entry = k.entry()?;
Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(entry),
layout: Some(&layout),
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some(entry),
targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })],
compilation_options: Default::default(),
}),
multiview_mask: None,
cache: None,
}))
};
let mut pipelines: HashMap<_, _> =
Kernel::DRAWN.iter().filter(|k| !k.is_map()).filter_map(|&k| Some(((k, acc_format), pipeline(k, acc_format)?))).collect();
// Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float
// render targets) can't: then layer effects use the CPU compositor and the rest stays here.
let maps = Kernel::DRAWN.iter().filter(|k| k.is_map()).flat_map(|&k| [(k, MAP32), (k, MAP16)]);
let (maps, map_error) = first_error(device, || maps.filter_map(|key| Some((key, pipeline(key.0, key.1)?))).collect::<Vec<_>>());
if let Some(e) = &map_error {
log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU");
} else {
pipelines.extend(maps);
}
let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view;
Self {
kit: Kit { pipelines, bgl0, bgl1, dummy },
pool: Vec::new(),
residents: HashMap::new(),
fx: HashMap::new(),
temps: Vec::new(),
patterns: HashMap::new(),
max_dim: 0,
device_max: device.limits().max_texture_dimension_2d,
page: PAGE,
chunk: CHUNK,
resident_budget: RESIDENT_BUDGET,
fx_budget: FX_BUDGET as u64,
focus: None,
frame: 0,
stamp: 0,
staged: 0,
acc_format,
effect_maps: map_error.is_none(),
cmyk: 0,
}
.with_texture_limit(device.limits().max_texture_dimension_2d)
}
fn with_texture_limit(mut self, max: u32) -> Self {
self.set_texture_limit(max);
self
}
/// Plan paging for a texture side limit of `max` (clamped to the device's own limit and at
/// least one tile). Tests use a small limit to exercise documents larger than it on any
/// adapter. Drops every cached texture.
pub fn set_texture_limit(&mut self, max: u32) {
let tile = TILE_SIZE as u32;
self.max_dim = max.min(self.device_max).max(tile);
let mut page = tile;
while page * 2 <= self.max_dim.min(PAGE) {
page *= 2;
}
self.page = page;
self.chunk = CHUNK.min(page);
self.pool.clear();
self.residents.clear();
self.fx.clear();
self.temps.clear();
}
/// The page side layer surfaces are stored in.
pub fn page_size(&self) -> u32 {
self.page
}
/// Set the GPU memory resident layer pages may hold (default [`RESIDENT_BUDGET`]).
pub fn set_resident_budget(&mut self, bytes: u64) {
self.resident_budget = bytes;
}
/// Set the GPU memory the compositor may hold for layer pages and effect maps together
/// (a quarter of it, at most [`FX_BUDGET`], for effect maps). Uploads and evicted pages in
/// flight during a refresh stay within about a quarter more.
pub fn set_memory_budget(&mut self, bytes: u64) {
self.fx_budget = (FX_BUDGET as u64).min(bytes / 4);
self.resident_budget = bytes.saturating_sub(self.fx_budget);
}
/// The budget of layer pages plus effect maps (bytes).
pub fn memory_budget(&self) -> u64 {
self.resident_budget.saturating_add(self.fx_budget)
}
/// Bytes of the layer pages a render of `region` needs resident (each layer and mask
/// surface's tiles within the region's page cells, in their texture format).
pub fn working_set(&self, doc: &Document, region: Rect) -> u64 {
let Ok(plan) = plan(doc) else { return 0 };
let grid = tile_grid(doc.bounds());
let cells = grid_rects(region.intersect(&doc.bounds()), self.page)
.into_iter()
.map(|r| cell_rect((r.x0.div_euclid(self.page as i32), r.y0.div_euclid(self.page as i32)), self.page))
.fold(Rect::EMPTY, |a, c| if a.is_empty() { c } else { a.union(&c) });
let mut seen = std::collections::HashSet::new();
let mut total = 0u64;
for p in &plan.passes {
let sources = [p.tex.as_ref().map(|t| (t.layer, t.role, t.surface.get())), p.mask.as_ref().map(|m| (m.layer, Role::Mask, m.surface.get()))];
for (layer, role, s) in sources.into_iter().flatten() {
if seen.insert((layer, role)) {
let a = s.tile_bounds().intersect(&grid).intersect(&cells);
total += a.width() as u64 * a.height() as u64 * TexKind::for_surface(role, s.format()).bytes_per_pixel() as u64;
}
}
}
total
}
/// Whether a render of `region` keeps every layer page it needs within the budget; when it
/// doesn't, each render re-uploads what was evicted.
pub fn fits_budget(&self, doc: &Document, region: Rect) -> bool {
self.working_set(doc, region) <= self.resident_budget
}
/// The document area the view shows (`None`: unknown). Full refreshes draw its cells last.
pub fn set_focus(&mut self, focus: Option<Rect>) {
self.focus = focus;
}
/// GPU memory held by resident layer pages (bytes).
pub fn resident_bytes(&self) -> u64 {
self.residents.values().map(Resident::bytes).sum()
}
/// Whether `doc` can be composited on the GPU. Documents and layers larger than the texture
/// limit are fine: surfaces are stored in page-sized textures and effect maps of regions
/// larger than the limit are built per page cell.
pub fn supports(&self, doc: &Document) -> Result<(), Unsupported> {
let p = plan(doc)?;
self.check_fx(doc, &p)
}
/// Whether the maps of an effect region are built per page cell (it exceeds the limit).
fn fx_paged(&self, region: Rect) -> bool {
region.width() > self.max_dim || region.height() > self.max_dim
}
/// How far beyond a page cell the effect maps of `f` must be computed to be exact in it.
fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 {
let vector_shape = matches!(f.layer.content, LayerContent::Shape(_));
let progs: Vec<fx::MapProgram> = f
.layer
.effects
.items
.iter()
.filter(|e| e.enabled())
.map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0)))
.collect();
let want = field_reaches(&progs);
// Distance fields are exact one pixel inside the window they are computed from.
progs.iter().map(|p| p.reach(&|k| want.get(&k).copied().unwrap_or(0))).max().unwrap_or(0).saturating_add(2)
}
/// Effect maps must fit in textures (per page cell when the region exceeds the limit), and
/// patterns in one texture.
fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> {
if !self.effect_maps && !p.fx.is_empty() {
return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into()));
}
for f in &p.fx {
if self.fx_paged(f.region) {
let side = i64::from(self.page) + 2 * i64::from(Self::fx_apron(doc, f));
if side > i64::from(self.device_max) {
return Err(Unsupported(format!("effects of `{}` reach too far to build per page", f.layer.name)));
}
}
for e in f.layer.effects.items.iter().filter(|e| e.enabled()) {
for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages {
if s.lut.as_ref().is_some_and(|l| l.len() > 4096) {
return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name)));
}
}
}
}
for pass in &p.passes {
if let Some(pat) = pass.pattern
&& (pat.width > self.device_max || pat.height > self.device_max)
{
return Err(Unsupported(format!("pattern `{}` larger than the GPU texture limit", pat.name)));
}
}
Ok(())
}
/// Drop GPU textures of a closed document.
pub fn forget_doc(&mut self, doc: DocId) {
self.residents.retain(|_, r| r.doc != doc);
self.fx.retain(|_, e| e.doc != doc);
}
/// GPU memory held by cached effect maps (bytes).
pub fn fx_cache_bytes(&self) -> usize {
self.fx.values().map(FxEntry::bytes).sum()
}
/// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is
/// still open; the chunk texture is reused afterwards, so the sink must record any copies
/// or passes that read it into the given encoder. Submits the work before returning; a
/// refresh of a huge document also submits in between (the sink may be handed a new
/// encoder), so its uploads and evicted pages never pile up in memory.
pub fn render(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
doc: &Document,
region: Rect,
mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>),
) -> Result<Stats, Unsupported> {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") });
let stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true)?;
queue.submit([encoder.finish()]);
Ok(stats)
}
/// Like [`Self::render`] but records into `encoder` without submitting.
pub fn encode(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
doc: &Document,
region: Rect,
sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>),
) -> Result<Stats, Unsupported> {
self.encode_inner(device, queue, encoder, doc, region, sink, false)
}
#[allow(clippy::too_many_arguments)]
fn encode_inner(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
doc: &Document,
region: Rect,
sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>),
flush: bool,
) -> Result<Stats, Unsupported> {
// CMYK layers convert through the document's own CMYK profile (uploads and plan colours).
let space = photocraft_compose::cmyk_space(doc);
self.cmyk = space.as_ref().map_or(0, |s| s.id);
photocraft_color::convert::with_cmyk_space(space.as_ref(), || self.encode_scoped(device, queue, encoder, doc, region, sink, flush))
}
#[allow(clippy::too_many_arguments)]
fn encode_scoped(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
doc: &Document,
region: Rect,
sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>),
flush: bool,
) -> Result<Stats, Unsupported> {
let canvas = doc.bounds();
let region = region.intersect(&canvas);
let plan = plan(doc)?;
self.check_fx(doc, &plan)?;
let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() };
if region.is_empty() {
return Ok(stats);
}
self.frame += 1;
self.stamp += 1;
self.staged = 0;
// Effect maps of whole regions first (they may render group shapes through sub-plans);
// regions larger than the limit are built per cell below.
let paged: Vec<bool> = plan.fx.iter().map(|f| self.fx_paged(f.region)).collect();
let aprons: Vec<i32> = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect();
for (f, &pg) in plan.fx.iter().zip(&paged) {
if !pg {
self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats);
}
}
let fr = self.frame_res(device, queue, canvas, &plan);
// Page cells; every other frame in reverse, so a repeated full refresh of a document
// larger than the budget starts with the pages still resident.
let page = self.page;
let mut cells = grid_rects(region, page);
if self.frame.is_multiple_of(2) {
cells.reverse();
}
if let Some(f) = self.focus {
let p = page as i32;
let focused = |r: &Rect| !cell_rect((r.x0.div_euclid(p), r.y0.div_euclid(p)), page).intersect(&f).is_empty();
cells.sort_by_key(focused);
}
let flush_bytes = FLUSH_BYTES.min(self.memory_budget() / 8).max(16 << 20);
stats.cells = cells.len();
// The previous intermediate submit (waited for before the next is queued; the web has
// no blocking wait and relies on the browser's own scheduling).
#[cfg(not(target_arch = "wasm32"))]
let mut last_submit: Option<wgpu::SubmissionIndex> = None;
// Work recorded and bytes evicted since the last submit.
let (mut work, mut freed) = (0u64, 0u64);
for part in cells {
self.stamp += 1;
let cell = (part.x0.div_euclid(page as i32), part.y0.div_euclid(page as i32));
let cr = cell_rect(cell, page);
for (i, f) in plan.fx.iter().enumerate() {
let pf = cr.intersect(&f.region);
if !paged.get(i).copied().unwrap_or(false) || pf.is_empty() {
continue;
}
let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region);
self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats);
}
let chunks = grid_rects(part, self.chunk);
stats.chunks += chunks.len();
work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64;
self.run_cell(device, queue, encoder, doc.id, &plan, &paged, cell, &fr, &chunks, &mut stats, sink);
let (evicted, bytes) = self.evict();
stats.evicted += evicted;
freed += bytes;
if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes) {
// Submit what's recorded, and wait for the previous submit, so at most two
// batches of uploads and evicted pages are in flight.
let done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }));
let index = queue.submit([done.finish()]);
#[cfg(not(target_arch = "wasm32"))]
if let Some(prev) = last_submit.replace(index) {
let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(prev), timeout: None });
}
#[cfg(target_arch = "wasm32")]
let _ = index;
self.staged = 0;
work = 0;
freed = 0;
stats.flushes += 1;
}
}
// Evict this document's textures whose layers are gone (hidden layers stay resident so
// toggling visibility costs no upload).
let frame = self.frame;
let live: std::collections::HashSet<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
self.residents.retain(|(id, _, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id));
self.fx.retain(|(id, _), e| e.doc != doc.id || e.last_used == frame || live.contains(id));
stats.evicted += self.evict().0;
self.temps.retain(|(_, used)| frame.saturating_sub(*used) < 240);
Ok(stats)
}
/// Keep resident pages within the resident budget and the effect cache within
/// its budget, least recently used first. Never drops what the current cell uses, nor
/// whole-region effect maps drawn this frame. Returns how many textures were dropped and
/// their bytes.
fn evict(&mut self) -> (usize, u64) {
let (mut n, mut freed) = (0, 0u64);
let mut total = self.resident_bytes();
if total > self.resident_budget {
let mut lru: Vec<(u64, ResKey, u64)> =
self.residents.iter().filter(|(_, r)| r.stamp != self.stamp).map(|(k, r)| (r.stamp, *k, r.bytes())).collect();
lru.sort_unstable_by_key(|c| c.0);
for (_, k, bytes) in lru {
if total <= self.resident_budget {
break;
}
self.residents.remove(&k);
total = total.saturating_sub(bytes);
n += 1;
freed += bytes;
}
}
let mut total = self.fx_cache_bytes();
let fx_budget = usize::try_from(self.fx_budget).unwrap_or(usize::MAX);
if total > fx_budget {
let (frame, stamp) = (self.frame, self.stamp);
let mut lru: Vec<((u64, u64), FxKey)> = self
.fx
.iter()
.filter(|(k, e)| e.last_used != frame || (k.1.is_some() && e.stamp != stamp))
.map(|(k, e)| ((e.last_used, e.stamp), *k))
.collect();
lru.sort_unstable_by_key(|c| c.0);
for (_, k) in lru {
if total <= fx_budget {
break;
}
if let Some(e) = self.fx.remove(&k) {
total = total.saturating_sub(e.bytes());
n += 1;
freed += e.bytes() as u64;
}
}
}
(n, freed)
}
/// Per-frame resources of `plan`: the tile area of each pass's surfaces, its LUT and pattern.
fn frame_res(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, canvas: Rect, plan: &Plan<'_>) -> FrameRes {
let grid = tile_grid(canvas);
let area = |s: &Surface| s.tile_bounds().intersect(&grid);
let areas = plan
.passes
.iter()
.map(|p| (p.tex.as_ref().map_or(Rect::EMPTY, |t| area(t.surface.get())), p.mask.as_ref().map_or(Rect::EMPTY, |m| area(m.surface.get()))))
.collect();
let luts = plan.passes.iter().map(|p| p.lut.as_ref().map(|rows| lut_texture(device, queue, rows))).collect();
let patterns = plan.passes.iter().map(|p| p.pattern.map(|pat| self.pattern_view(device, queue, pat))).collect();
FrameRes { areas, luts, patterns }
}
/// Bring the pages of `cell` that `plan` samples up to date and resolve its effect maps.
#[allow(clippy::too_many_arguments)]
fn bind_cell(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
doc: DocId,
plan: &Plan<'_>,
paged: &[bool],
cell: Cell,
fr: &FrameRes,
stats: &mut Stats,
) -> Bound {
let cr = cell_rect(cell, self.page);
let mut views: Vec<(Option<ResidentRef>, Option<ResidentRef>)> = Vec::with_capacity(plan.passes.len());
let mut keys: Vec<ResKey> = Vec::new();
let mut maps = Vec::with_capacity(plan.passes.len());
for (i, p) in plan.passes.iter().enumerate() {
let (ta, ma) = fr.areas.get(i).copied().unwrap_or((Rect::EMPTY, Rect::EMPTY));
let tex =
p.tex.as_ref().and_then(|t| self.sync(device, queue, encoder, doc, (t.layer, t.role, cell), t.surface.get(), ta.intersect(&cr), stats)).map(
|(k, r)| {
keys.push(k);
(keys.len() - 1, r)
},
);
let mask = p
.mask