-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathwgpu.rs
More file actions
2743 lines (2558 loc) · 104 KB
/
Copy pathwgpu.rs
File metadata and controls
2743 lines (2558 loc) · 104 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
// Copyright 2025 the Vello Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! GPU rendering module for the sparse strips CPU/GPU rendering engine.
//!
//! This module provides the GPU-side implementation of the hybrid rendering system.
//! It handles:
//! - GPU resource management (buffers, textures, pipelines)
//! - Surface/window management and presentation
//! - Shader execution and rendering
//!
//! The hybrid approach combines CPU-side path processing with efficient GPU rendering
//! to balance flexibility and performance.
#![expect(
clippy::cast_possible_truncation,
reason = "We temporarily ignore those because the casts\
only break in edge cases, and some of them are also only related to conversions from f64 to f32."
)]
use crate::render::common::IMAGE_PADDING;
use crate::{
GpuStrip, RenderError, RenderSettings, RenderSize,
filter::{FilterContext, FilterInstanceData, FilterPassState, FilterPassTarget},
gradient_cache::GradientRampCache,
render::{
Config,
common::{
GPU_ENCODED_IMAGE_SIZE_TEXELS, GPU_LINEAR_GRADIENT_SIZE_TEXELS,
GPU_RADIAL_GRADIENT_SIZE_TEXELS, GPU_SWEEP_GRADIENT_SIZE_TEXELS, GpuEncodedImage,
GpuEncodedPaint, GpuLinearGradient, GpuRadialGradient, GpuSweepGradient,
pack_image_offset, pack_image_params, pack_image_size, pack_radial_kind_and_swapped,
pack_texture_width_and_extend_mode, pack_tint,
},
},
scene::Scene,
schedule::{
LoadOp, OutputTarget, RendererBackend, Scheduler, SchedulerState, StripPassRenderTarget,
},
};
use alloc::vec::Vec;
use alloc::{sync::Arc, vec};
use bytemuck::{Pod, Zeroable};
use core::{fmt::Debug, num::NonZeroU64};
use vello_common::image_cache::{ImageCache, ImageResource};
use vello_common::multi_atlas::{AtlasConfig, AtlasError, AtlasId};
use vello_common::render_graph::LayerId;
use vello_common::{
coarse::WideTile,
encode::{EncodedGradient, EncodedKind, EncodedPaint, MAX_GRADIENT_LUT_SIZE, RadialKind},
kurbo::Affine,
paint::ImageSource,
peniko,
pixmap::Pixmap,
tile::Tile,
};
use wgpu::{
BindGroup, BindGroupLayout, BlendState, Buffer, ColorTargetState, ColorWrites, CommandEncoder,
Device, Extent3d, PipelineCompilationOptions, Queue, RenderPassColorAttachment,
RenderPassDescriptor, RenderPipeline, Sampler, Texture, TextureView, TextureViewDescriptor,
util::DeviceExt,
};
/// Placeholder value for uninitialized GPU encoded paints.
const GPU_PAINT_PLACEHOLDER: GpuEncodedPaint = GpuEncodedPaint::LinearGradient(GpuLinearGradient {
texture_width_and_extend_mode: 0,
gradient_start: 0,
transform: [0.0; 6],
});
/// Options for the renderer
#[derive(Debug)]
pub struct RenderTargetConfig {
/// Format of the rendering target
pub format: wgpu::TextureFormat,
/// Width of the rendering target
pub width: u32,
/// Height of the rendering target
pub height: u32,
}
/// Vello Hybrid's Renderer.
#[derive(Debug)]
pub struct Renderer {
/// Programs for rendering.
programs: Programs,
/// Scheduler for scheduling draws.
scheduler: Scheduler,
/// The state used by the scheduler.
scheduler_state: SchedulerState,
/// Image cache for storing images atlas allocations.
pub image_cache: ImageCache,
/// Encoded paints for storing encoded paints.
encoded_paints: Vec<GpuEncodedPaint>,
/// Stores the index (offset) of the encoded paints in the encoded paints texture.
paint_idxs: Vec<u32>,
/// Gradient cache for storing gradient ramps.
gradient_cache: GradientRampCache,
/// Context for GPU filter effects.
filter_context: FilterContext,
/// State used for constructing filter passes.
filter_pass_state: FilterPassState,
}
impl Renderer {
/// Creates a new renderer.
pub fn new(device: &Device, render_target_config: &RenderTargetConfig) -> Self {
Self::new_with(device, render_target_config, RenderSettings::default())
}
/// Creates a new renderer with specific settings.
pub fn new_with(
device: &Device,
render_target_config: &RenderTargetConfig,
settings: RenderSettings,
) -> Self {
super::common::maybe_warn_about_webgl_feature_conflict();
let max_texture_dimension_2d = device.limits().max_texture_dimension_2d;
let total_slots = (max_texture_dimension_2d / u32::from(Tile::HEIGHT)) as usize;
let image_cache = ImageCache::new_with_config(settings.atlas_config);
// Estimate the maximum number of gradient cache entries based on the max texture dimension
// and the maximum gradient LUT size - worst case scenario.
let max_gradient_cache_size =
max_texture_dimension_2d * max_texture_dimension_2d / MAX_GRADIENT_LUT_SIZE as u32;
let gradient_cache = GradientRampCache::new(max_gradient_cache_size, settings.level);
let filter_context = FilterContext::new(settings.atlas_config);
Self {
programs: Programs::new(
device,
&image_cache,
&filter_context.image_cache,
render_target_config,
total_slots,
),
scheduler: Scheduler::new(total_slots),
scheduler_state: SchedulerState::default(),
image_cache,
gradient_cache,
encoded_paints: Vec::new(),
paint_idxs: Vec::new(),
filter_context,
filter_pass_state: FilterPassState::default(),
}
}
fn prepare_filter_textures(
&mut self,
scene: &Scene,
device: &Device,
encoder: &mut CommandEncoder,
encoded_paints: &mut Vec<EncodedPaint>,
) -> Result<(), AtlasError> {
// TODO: Maybe we can do the clear implicitly when using the textures for the first time.
if !self.filter_context.filter_textures.is_empty() {
for view in &self.programs.resources.filter_atlas.views {
let _pass = encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("Clear Filter Atlas Texture"),
color_attachments: &[Some(RenderPassColorAttachment {
view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
}
}
self.filter_context
.deallocate_all_and_clear_context(&mut self.image_cache);
self.filter_context
.prepare(&scene.render_graph, &mut self.image_cache, encoded_paints)?;
Programs::maybe_resize_atlas_texture_array(
device,
encoder,
&mut self.programs.resources,
&self.programs.atlas_bind_group_layout,
self.image_cache.atlas_count() as u32,
);
self.programs.resources.filter_atlas.ensure_count(
device,
self.filter_context.image_cache.atlas_count() as u32,
&self.programs.filter_input_bind_group_layouts[0],
&self.programs.filter_input_bind_group_layouts[1],
);
Ok(())
}
/// Render `scene` into the provided command encoder.
///
/// This method creates GPU resources as needed and schedules potentially multiple
/// render passes.
pub fn render(
&mut self,
scene: &Scene,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
render_size: &RenderSize,
view: &TextureView,
) -> Result<(), RenderError> {
let mut encoded_paints = scene.encoded_paints.borrow_mut();
let scene_paint_count = encoded_paints.len();
self.prepare_filter_textures(scene, device, encoder, &mut encoded_paints)?;
// TODO: Passing `false` here because wgpu swapchain textures likely have
// undefined initial content, making an explicit clear redundant in the common
// case. Verify whether there are scenarios where wgpu would need a clear.
let result = self.render_scene(
scene,
device,
queue,
encoder,
render_size,
view,
&encoded_paints,
false,
);
encoded_paints.truncate(scene_paint_count);
result
}
/// Render a `scene` directly into an atlas layer.
///
/// This renders the scene's content into the specified atlas layer, which can then
/// be sampled as an image in subsequent render passes. This is useful for rendering
/// vector content (e.g., glyphs) into the atlas for later use as cached images.
///
/// The scene should be sized to the atlas layer dimensions
/// ([`AtlasConfig::atlas_size`]), with content positioned at the allocated offset
/// coordinates from `ImageCache::allocate`.
///
/// This method creates its own command encoder and submits immediately,
/// ensuring atlas content is committed before any subsequent
/// [`render`](Self::render) call (the two methods share GPU resources that
/// are staged by `queue.write_*` and only applied on the next `queue.submit`).
#[doc(hidden)]
pub fn render_to_atlas(
&mut self,
scene: &Scene,
device: &Device,
queue: &Queue,
atlas_id: AtlasId,
) -> Result<(), RenderError> {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render to Atlas Encoder"),
});
Programs::maybe_resize_atlas_texture_array(
device,
&mut encoder,
&mut self.programs.resources,
&self.programs.atlas_bind_group_layout,
self.image_cache.atlas_count() as u32,
);
let AtlasConfig {
atlas_size: (atlas_width, atlas_height),
..
} = self.image_cache.atlas_manager().config();
let atlas_render_size = RenderSize {
width: *atlas_width,
height: *atlas_height,
};
let layer_view =
self.programs
.resources
.atlas_texture_array
.create_view(&TextureViewDescriptor {
label: Some("Atlas Layer Render View"),
format: Some(wgpu::TextureFormat::Rgba8Unorm),
dimension: Some(wgpu::TextureViewDimension::D2),
aspect: wgpu::TextureAspect::All,
base_mip_level: 0,
mip_level_count: Some(1),
base_array_layer: atlas_id.as_u32(),
array_layer_count: Some(1),
usage: None,
});
// Swap in the stub atlas bind group to avoid the read-write conflict:
// the real atlas texture is used as the render target (COLOR_TARGET), so it
// cannot also be bound as a shader resource (TEXTURE_BINDING) in the same pass.
core::mem::swap(
&mut self.programs.resources.atlas_bind_group,
&mut self.programs.resources.stub_atlas_bind_group,
);
// TODO: The atlas is always RGBA8; when the surface uses a different format (e.g. BGRA on
// macOS), we may need a dedicated RGBA8 render pipeline for atlas rendering. Adopt the
// fix from the filters/native-format pipeline work when available.
let encoded_paints = scene.encoded_paints.borrow();
let result = self.render_scene(
scene,
device,
queue,
&mut encoder,
&atlas_render_size,
&layer_view,
&encoded_paints,
false,
);
// Restore the real atlas bind group.
core::mem::swap(
&mut self.programs.resources.atlas_bind_group,
&mut self.programs.resources.stub_atlas_bind_group,
);
// Submit immediately so the atlas content is committed before subsequent
// render() calls overwrite the shared alpha/config/paint resources.
queue.submit(Some(encoder.finish()));
result
}
/// Shared render pipeline: prepares GPU resources, runs the scheduler against
/// the provided `view` at `render_size`, and maintains caches.
///
/// When `clear` is true the render target is cleared to transparent black
/// before drawing (normal frame rendering).
fn render_scene(
&mut self,
scene: &Scene,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
render_size: &RenderSize,
view: &TextureView,
encoded_paints: &[EncodedPaint],
clear: bool,
) -> Result<(), RenderError> {
self.prepare_gpu_encoded_paints(encoded_paints);
// TODO: For the time being, we upload the entire alpha buffer as one big chunk. As a future
// refinement, we could have a bounded alpha buffer, and break draws when the alpha
// buffer fills.
self.programs.prepare(
device,
queue,
&mut self.gradient_cache,
&self.encoded_paints,
&mut scene.strip_storage.borrow_mut().alphas,
render_size,
&self.paint_idxs,
&self.filter_context,
);
if clear {
Self::clear_view(encoder, view);
}
let mut ctx = RendererContext {
programs: &mut self.programs,
device,
queue,
encoder,
view,
image_cache: &self.image_cache,
filter_context: &self.filter_context,
filter_pass_state: &mut self.filter_pass_state,
};
self.scheduler.do_scene(
&mut self.scheduler_state,
&mut ctx,
scene,
&self.paint_idxs,
&self.filter_context,
encoded_paints,
)?;
self.gradient_cache.maintain();
Ok(())
}
/// Clear the view to transparent black.
// TODO: Investigate adding tests for the clear_view behavior.
fn clear_view(encoder: &mut CommandEncoder, view: &TextureView) {
encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("Clear View"),
color_attachments: &[Some(RenderPassColorAttachment {
view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
}
/// Upload image to cache and atlas in one step. Returns the `ImageId`.
///
/// It's used when an image is not already in the cache.
///
/// This is a convenience method that:
/// 1. Reserves space in the image cache
/// 2. Writes the image data directly to the atlas
/// 3. Returns the `ImageId` for use in rendering
pub fn upload_image<T: AtlasWriter>(
&mut self,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
writer: &T,
) -> vello_common::paint::ImageId {
self.upload_image_with(device, queue, encoder, writer, IMAGE_PADDING)
}
pub(crate) fn upload_image_with<T: AtlasWriter>(
&mut self,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
writer: &T,
padding: u16,
) -> vello_common::paint::ImageId {
let width = writer.width();
let height = writer.height();
let image_id = self.image_cache.allocate(width, height, padding).unwrap();
self.write_to_atlas(device, queue, encoder, image_id, writer, None);
image_id
}
/// Write pixel data to an existing atlas allocation.
///
/// Unlike [`upload_image`](Self::upload_image), this does not allocate space in the image
/// cache. The `image_id` must have been previously allocated (e.g. via
/// `ImageCache::allocate`). This is useful for uploading CPU-side pixel data (such as
/// bitmap font glyphs) to a pre-allocated atlas region.
///
/// If `offset_override` is `Some`, the provided offset is used instead of the
/// allocator-assigned position. Pass `None` to use the default atlas offset.
#[doc(hidden)]
pub fn write_to_atlas<T: AtlasWriter>(
&mut self,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
image_id: vello_common::paint::ImageId,
writer: &T,
offset_override: Option<[u32; 2]>,
) {
let image_resource = self
.image_cache
.get(image_id)
.expect("Image resource not found");
Programs::maybe_resize_atlas_texture_array(
device,
encoder,
&mut self.programs.resources,
&self.programs.atlas_bind_group_layout,
self.image_cache.atlas_count() as u32,
);
let offset = offset_override.unwrap_or([
image_resource.offset[0] as u32,
image_resource.offset[1] as u32,
]);
writer.write_to_atlas_layer(
device,
queue,
encoder,
&self.programs.resources.atlas_texture_array,
image_resource.atlas_id.as_u32(),
offset,
writer.width(),
writer.height(),
);
}
/// Destroy an image from the cache and clear the allocated slot in the atlas.
pub fn destroy_image(
&mut self,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
image_id: vello_common::paint::ImageId,
) {
if let Some(image_resource) = self.image_cache.deallocate(image_id) {
let padding = image_resource.padding as u32;
self.clear_atlas_region(
device,
queue,
encoder,
image_resource.atlas_id,
[
image_resource.offset[0] as u32 - padding,
image_resource.offset[1] as u32 - padding,
],
image_resource.width as u32 + padding * 2,
image_resource.height as u32 + padding * 2,
);
}
}
/// Returns a reference to the underlying atlas texture array.
///
/// This is a 2D array texture (`TextureViewDimension::D2Array`) containing all
/// atlas layers used by the image cache. Each layer holds cached image data
/// (e.g., rasterised glyphs) that the renderer samples during draw calls.
pub fn atlas_texture(&self) -> &Texture {
&self.programs.resources.atlas_texture_array
}
/// Clear a specific region of the atlas texture.
fn clear_atlas_region(
&mut self,
_device: &Device,
_queue: &Queue,
encoder: &mut CommandEncoder,
atlas_id: AtlasId,
offset: [u32; 2],
width: u32,
height: u32,
) {
// Create a texture view for the specific atlas layer
let layer_view =
self.programs
.resources
.atlas_texture_array
.create_view(&TextureViewDescriptor {
label: Some("Atlas Layer Clear View"),
format: Some(wgpu::TextureFormat::Rgba8Unorm),
dimension: Some(wgpu::TextureViewDimension::D2),
aspect: wgpu::TextureAspect::All,
base_mip_level: 0,
mip_level_count: Some(1),
base_array_layer: atlas_id.as_u32(),
array_layer_count: Some(1),
// Inherit usage from the texture
usage: None,
});
let mut render_pass = encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("Clear Atlas Region"),
color_attachments: &[Some(RenderPassColorAttachment {
view: &layer_view,
resolve_target: None,
ops: wgpu::Operations {
// Don't clear entire texture, just the scissor region
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
// Set scissor rectangle to limit clearing to specific region
render_pass.set_scissor_rect(offset[0], offset[1], width, height);
// Use atlas clear pipeline to render transparent pixels
render_pass.set_pipeline(&self.programs.atlas_clear_pipeline);
// Draw fullscreen quad
render_pass.draw(0..4, 0..1);
}
fn prepare_gpu_encoded_paints(&mut self, encoded_paints: &[EncodedPaint]) {
self.encoded_paints
.resize_with(encoded_paints.len(), || GPU_PAINT_PLACEHOLDER);
self.paint_idxs.resize(encoded_paints.len() + 1, 0);
let mut current_idx = 0;
for (encoded_paint_idx, paint) in encoded_paints.iter().enumerate() {
self.paint_idxs[encoded_paint_idx] = current_idx;
match paint {
EncodedPaint::Image(img) => {
if let ImageSource::OpaqueId { id: image_id, .. } = img.source {
let image_resource: Option<&ImageResource> = self.image_cache.get(image_id);
if let Some(image_resource) = image_resource {
let image_paint = self.encode_image_paint(img, image_resource);
self.encoded_paints[encoded_paint_idx] = image_paint;
current_idx += GPU_ENCODED_IMAGE_SIZE_TEXELS;
}
}
}
EncodedPaint::Gradient(gradient) => {
let (gradient_start, gradient_width) =
self.gradient_cache.get_or_create_ramp(gradient);
let gradient_paint: GpuEncodedPaint =
self.encode_gradient_paint(gradient, gradient_width, gradient_start);
let gradient_size_texels = match &gradient_paint {
GpuEncodedPaint::LinearGradient(_) => GPU_LINEAR_GRADIENT_SIZE_TEXELS,
GpuEncodedPaint::RadialGradient(_) => GPU_RADIAL_GRADIENT_SIZE_TEXELS,
GpuEncodedPaint::SweepGradient(_) => GPU_SWEEP_GRADIENT_SIZE_TEXELS,
_ => unreachable!("encode_gradient_for_gpu only returns gradient types"),
};
self.encoded_paints[encoded_paint_idx] = gradient_paint;
current_idx += gradient_size_texels;
}
EncodedPaint::BlurredRoundedRect(_blurred_rect) => {
// TODO: Blurred rounded rectangles are not yet supported
log::warn!(
"Blurred rounded rectangles are not yet supported in sparse strips hybrid renderer"
);
}
}
}
self.paint_idxs[encoded_paints.len()] = current_idx;
}
fn encode_image_paint(
&self,
image: &vello_common::encode::EncodedImage,
image_resource: &ImageResource,
) -> GpuEncodedPaint {
let image_transform = image.transform * Affine::translate((-0.5, -0.5));
let transform = image_transform.as_coeffs().map(|x| x as f32);
let image_size = pack_image_size(image_resource.width, image_resource.height);
let image_offset = pack_image_offset(image_resource.offset[0], image_resource.offset[1]);
let image_params = pack_image_params(
image.sampler.quality as u32,
image.sampler.x_extend as u32,
image.sampler.y_extend as u32,
image_resource.atlas_id.as_u32(),
);
let (tint, tint_mode) = pack_tint(image.tint);
GpuEncodedPaint::Image(GpuEncodedImage {
image_params,
image_size,
image_offset,
transform,
tint,
tint_mode,
image_padding: image_resource.padding as u32,
})
}
fn encode_gradient_paint(
&self,
gradient: &EncodedGradient,
gradient_width: u32,
gradient_start: u32,
) -> GpuEncodedPaint {
let gradient_transform = gradient.transform * Affine::translate((-0.5, -0.5));
let transform = gradient_transform.as_coeffs().map(|x| x as f32);
let extend_mode = match gradient.extend {
peniko::Extend::Pad => 0,
peniko::Extend::Repeat => 1,
peniko::Extend::Reflect => 2,
};
let texture_width_and_extend_mode =
pack_texture_width_and_extend_mode(gradient_width, extend_mode);
match &gradient.kind {
EncodedKind::Linear(_) => GpuEncodedPaint::LinearGradient(GpuLinearGradient {
texture_width_and_extend_mode,
gradient_start,
transform,
}),
EncodedKind::Radial(radial) => {
let (kind, bias, scale, fp0, fp1, fr1, f_focal_x, f_is_swapped, scaled_r0_squared) =
match radial {
RadialKind::Radial { bias, scale } => {
(0, *bias, *scale, 0.0, 0.0, 0.0, 0.0, 0, 0.0)
}
RadialKind::Strip { scaled_r0_squared } => {
(1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, *scaled_r0_squared)
}
RadialKind::Focal {
focal_data,
fp0,
fp1,
} => (
2,
*fp0,
*fp1,
*fp0,
*fp1,
focal_data.fr1,
focal_data.f_focal_x,
focal_data.f_is_swapped as u32,
0.0,
),
};
GpuEncodedPaint::RadialGradient(GpuRadialGradient {
texture_width_and_extend_mode,
gradient_start,
transform,
kind_and_f_is_swapped: pack_radial_kind_and_swapped(kind, f_is_swapped),
bias,
scale,
fp0,
fp1,
fr1,
f_focal_x,
scaled_r0_squared,
})
}
EncodedKind::Sweep(sweep) => GpuEncodedPaint::SweepGradient(GpuSweepGradient {
texture_width_and_extend_mode,
gradient_start,
transform,
start_angle: sweep.start_angle,
inv_angle_delta: sweep.inv_angle_delta,
_padding: [0, 0],
}),
}
}
}
/// Defines the GPU resources and pipelines for rendering.
#[derive(Debug)]
struct Programs {
/// Pipelines for rendering strips.
/// The first pipeline should be used for color attachments in the native pixel format,
/// the second for color attachments in RGBA8.
strip_pipelines: [RenderPipeline; 2],
/// Bind group layout for strip draws
strip_bind_group_layout: BindGroupLayout,
/// Bind group layout for encoded paints
encoded_paints_bind_group_layout: BindGroupLayout,
/// Bind group layout for gradient texture
gradient_bind_group_layout: BindGroupLayout,
/// Bind group layout for atlas textures
atlas_bind_group_layout: BindGroupLayout,
/// Bind group layout for filter data texture.
filter_bind_group_layout: BindGroupLayout,
/// Pipeline for applying filter effects.
filter_pipeline: RenderPipeline,
/// Bind group layouts for filter input.
filter_input_bind_group_layouts: [BindGroupLayout; 2],
/// Pipeline for clearing slots in slot textures.
clear_pipeline: RenderPipeline,
/// Pipeline for clearing atlas regions.
atlas_clear_pipeline: RenderPipeline,
/// GPU resources for rendering (created during prepare)
resources: GpuResources,
/// Dimensions of the rendering target
render_size: RenderSize,
/// Scratch buffer for staging encoded paints texture data.
encoded_paints_data: Vec<u8>,
/// Scratch buffer for staging filter data texture data.
filter_data: Vec<u8>,
}
#[derive(Debug)]
struct FilterAtlasState {
textures: Vec<Texture>,
views: Vec<TextureView>,
input_bind_groups: Vec<BindGroup>,
original_bind_groups: Vec<BindGroup>,
sampler: Sampler,
atlas_size: (u32, u32),
}
impl FilterAtlasState {
fn new(device: &Device, atlas_size: (u32, u32)) -> Self {
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Filter Linear Sampler"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
Self {
textures: Vec::new(),
views: Vec::new(),
input_bind_groups: Vec::new(),
original_bind_groups: Vec::new(),
sampler,
atlas_size,
}
}
fn ensure_count(
&mut self,
device: &Device,
required_count: u32,
input_layout: &BindGroupLayout,
original_layout: &BindGroupLayout,
) {
let current_count = self.textures.len() as u32;
if required_count <= current_count {
return;
}
let (width, height) = self.atlas_size;
for _ in current_count..required_count {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Filter Atlas Texture"),
size: Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = texture.create_view(&TextureViewDescriptor::default());
let input_bg =
create_filter_input_bind_group(device, input_layout, &self.sampler, &view);
let original_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: original_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&view),
}],
});
self.textures.push(texture);
self.views.push(view);
self.input_bind_groups.push(input_bg);
self.original_bind_groups.push(original_bg);
}
}
}
/// Contains all GPU resources needed for rendering
#[derive(Debug)]
struct GpuResources {
/// Buffer for [`GpuStrip`] data
strips_buffer: Buffer,
/// Texture for alpha values (used by both view and slot rendering)
alphas_texture: Texture,
/// Textures for atlas data (multiple atlases supported)
atlas_texture_array: Texture,
/// View for atlas texture array
atlas_texture_array_view: TextureView,
/// Bilinear sampler for GPU-native image sampling
atlas_sampler: Sampler,
/// Bind group for atlas textures (as texture array)
atlas_bind_group: BindGroup,
/// Filter atlas textures and their associated views/bind groups.
/// Lazily allocated: stays empty until the first scene with filters.
filter_atlas: FilterAtlasState,
/// Texture for encoded paints
encoded_paints_texture: Texture,
/// Bind group for encoded paints
encoded_paints_bind_group: BindGroup,
/// Texture for gradient lookup table
gradient_texture: Texture,
/// Bind group for gradient texture
gradient_bind_group: BindGroup,
/// Texture holding serialized `GpuFilterData` for all filter layers.
filter_data_texture: Texture,
/// Bind group for the filter data texture.
filter_base_bind_group: BindGroup,
/// Config buffer for rendering wide tile commands into the view texture.
view_config_buffer: Buffer,
/// Config buffer for rendering wide tile commands into a slot texture.
slot_config_buffer: Buffer,
/// Buffer for slot indices used in `clear_slots`
clear_slot_indices_buffer: Buffer,
/// Buffer holding `FilterInstanceData` for a single filter draw call.
filter_instance_buffer: Buffer,
// Bind groups for rendering with clip buffers
slot_bind_groups: [BindGroup; 3],
/// Slot texture views
slot_texture_views: [TextureView; 2],
/// Bind group for clear slots operation
clear_bind_group: BindGroup,
/// Placeholder atlas bind group with a 1x1 dummy texture, used during
/// `render_to_atlas` to avoid a read-write conflict on the real atlas texture.
stub_atlas_bind_group: BindGroup,
}
const SIZE_OF_CONFIG: NonZeroU64 = NonZeroU64::new(size_of::<Config>() as u64).unwrap();
/// Config for the clear slots pipeline
#[repr(C)]
#[derive(Debug, Copy, Clone, Pod, Zeroable)]
struct ClearSlotsConfig {
/// Width of a slot
pub slot_width: u32,
/// Height of a slot
pub slot_height: u32,
/// Total height of the texture
pub texture_height: u32,
/// Padding for 16-byte alignment
pub _padding: u32,
}
impl GpuStrip {
/// Vertex attributes for the strip
pub fn vertex_attributes() -> [wgpu::VertexAttribute; 5] {
wgpu::vertex_attr_array![
0 => Uint32,
1 => Uint32,
2 => Uint32,
3 => Uint32,
4 => Uint32,
]
}
}
impl Programs {
fn new(
device: &Device,
image_cache: &ImageCache,
filter_texture_cache: &ImageCache,
render_target_config: &RenderTargetConfig,
slot_count: usize,
) -> Self {
let strip_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Strip Bind Group Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Uint,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let atlas_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Atlas Texture Bind Group Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Atlas Bilinear Sampler"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let encoded_paints_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Encoded Paints Bind Group Layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,