1use crate::gpu_pipeline::{
10 GpuClipVertex, GpuQuadInstance, GpuUniforms, GpuVertex, Hardware2DFrame, HardwareDrawOpKind,
11 HardwareRenderItem, QUAD_VERTICES, SIGNED_QUAD_VERTICES, WGSL_ANALYTICAL_QUAD_SHADER,
12 WGSL_STENCIL_CLIP_SHADER,
13};
14use std::ops::Range;
15use std::sync::Arc;
16use strata_layout::Rect;
17
18const MAX_STENCIL_LAYERS: usize = 8;
19
20#[repr(C)]
23#[derive(Debug, Clone, Copy)]
24struct Gpu2DUniformData {
25 viewport_size: [f32; 2],
26 dpr: f32,
27 _pad: f32,
28}
29
30impl Gpu2DUniformData {
31 #[inline]
32 fn as_bytes(&self) -> &[u8] {
33 unsafe {
34 std::slice::from_raw_parts(
35 (self as *const Self) as *const u8,
36 std::mem::size_of::<Self>(),
37 )
38 }
39 }
40}
41
42pub struct GpuStencilClipPipeline {
48 uniform_bgl: wgpu::BindGroupLayout,
49 pipeline_layout: wgpu::PipelineLayout,
50 shader: wgpu::ShaderModule,
51 color_format: wgpu::TextureFormat,
52 invert_bit_pipelines: [wgpu::RenderPipeline; MAX_STENCIL_LAYERS],
53}
54
55impl GpuStencilClipPipeline {
56 pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
58 let uniform_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
59 label: Some("strata_2d_uniform_bgl"),
60 entries: &[wgpu::BindGroupLayoutEntry {
61 binding: 0,
62 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
63 ty: wgpu::BindingType::Buffer {
64 ty: wgpu::BufferBindingType::Uniform,
65 has_dynamic_offset: false,
66 min_binding_size: None,
67 },
68 count: None,
69 }],
70 });
71
72 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
73 label: Some("strata_2d_stencil_clip_pl"),
74 bind_group_layouts: &[&uniform_bgl],
75 push_constant_ranges: &[],
76 });
77
78 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
79 label: Some("strata_2d_stencil_clip_wgsl"),
80 source: wgpu::ShaderSource::Wgsl(WGSL_STENCIL_CLIP_SHADER.into()),
81 });
82
83 let vertex_layout = wgpu::VertexBufferLayout {
84 array_stride: GpuClipVertex::BYTE_SIZE as u64,
85 step_mode: wgpu::VertexStepMode::Vertex,
86 attributes: &[wgpu::VertexAttribute {
87 format: wgpu::VertexFormat::Float32x2,
88 offset: 0,
89 shader_location: 0,
90 }],
91 };
92
93 let invert_bit_pipelines = std::array::from_fn(|bit_idx| {
94 let bit_mask = 1u32 << bit_idx;
95 let invert_face = wgpu::StencilFaceState {
96 compare: wgpu::CompareFunction::Always,
97 fail_op: wgpu::StencilOperation::Keep,
98 depth_fail_op: wgpu::StencilOperation::Keep,
99 pass_op: wgpu::StencilOperation::Invert,
100 };
101 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
102 label: Some("strata_2d_stencil_clip_bit_pipeline"),
103 layout: Some(&pipeline_layout),
104 vertex: wgpu::VertexState {
105 module: &shader,
106 entry_point: Some("vs_main"),
107 buffers: std::slice::from_ref(&vertex_layout),
108 compilation_options: Default::default(),
109 },
110 fragment: Some(wgpu::FragmentState {
111 module: &shader,
112 entry_point: Some("fs_main"),
113 targets: &[Some(wgpu::ColorTargetState {
114 format: color_format,
115 blend: None,
116 write_mask: wgpu::ColorWrites::empty(),
117 })],
118 compilation_options: Default::default(),
119 }),
120 primitive: wgpu::PrimitiveState {
121 topology: wgpu::PrimitiveTopology::TriangleList,
122 cull_mode: None,
123 ..Default::default()
124 },
125 depth_stencil: Some(wgpu::DepthStencilState {
126 format: wgpu::TextureFormat::Depth24PlusStencil8,
127 depth_write_enabled: false,
128 depth_compare: wgpu::CompareFunction::Always,
129 stencil: wgpu::StencilState {
130 front: invert_face,
131 back: invert_face,
132 read_mask: bit_mask,
133 write_mask: bit_mask,
134 },
135 bias: wgpu::DepthBiasState::default(),
136 }),
137 multisample: wgpu::MultisampleState::default(),
138 multiview: None,
139 cache: None,
140 })
141 });
142
143 Self {
144 uniform_bgl,
145 pipeline_layout,
146 shader,
147 color_format,
148 invert_bit_pipelines,
149 }
150 }
151
152 #[inline]
153 pub fn uniform_bind_group_layout(&self) -> &wgpu::BindGroupLayout {
154 &self.uniform_bgl
155 }
156
157 #[inline]
158 pub fn uniform_pipeline_layout(&self) -> &wgpu::PipelineLayout {
159 &self.pipeline_layout
160 }
161
162 #[inline]
163 pub fn color_format(&self) -> wgpu::TextureFormat {
164 self.color_format
165 }
166
167 #[inline]
168 pub fn shader(&self) -> &wgpu::ShaderModule {
169 &self.shader
170 }
171
172 #[inline]
173 pub fn layer_pipeline(&self, layer_bit: usize) -> &wgpu::RenderPipeline {
174 &self.invert_bit_pipelines[layer_bit.min(MAX_STENCIL_LAYERS - 1)]
175 }
176
177 fn record_mask<'pass>(
180 &'pass self,
181 pass: &mut wgpu::RenderPass<'pass>,
182 uniform_bg: &'pass wgpu::BindGroup,
183 stencil_vbuf: &'pass wgpu::Buffer,
184 layers: &[(Range<u64>, u32)],
185 ) -> usize {
186 let mut active_layers = 0usize;
187 for (byte_range, vert_count) in layers.iter().take(MAX_STENCIL_LAYERS) {
188 if *vert_count == 0 {
189 continue;
190 }
191 pass.set_pipeline(&self.invert_bit_pipelines[active_layers]);
192 pass.set_bind_group(0, uniform_bg, &[]);
193 pass.set_vertex_buffer(0, stencil_vbuf.slice(byte_range.clone()));
194 pass.set_stencil_reference(0);
195 pass.draw(0..*vert_count, 0..1);
196 active_layers += 1;
197 }
198 active_layers
199 }
200}
201
202struct StencilDepthTarget {
203 width: u32,
204 height: u32,
205 _texture: wgpu::Texture,
206 view: wgpu::TextureView,
207}
208
209struct Offscreen2DTarget {
210 width: u32,
211 height: u32,
212 format: wgpu::TextureFormat,
213 color: wgpu::Texture,
214 view: wgpu::TextureView,
215 readback: wgpu::Buffer,
216 padded_bytes_per_row: u32,
217}
218
219pub struct Wgpu2DRenderer {
225 device: Arc<wgpu::Device>,
226 queue: Arc<wgpu::Queue>,
227 color_format: wgpu::TextureFormat,
228
229 stencil_clip_pipeline: GpuStencilClipPipeline,
230
231 quad_shader: wgpu::ShaderModule,
232 quad_pipeline: wgpu::RenderPipeline,
233 quad_stenciled: [Option<wgpu::RenderPipeline>; MAX_STENCIL_LAYERS],
234
235 path_shader: wgpu::ShaderModule,
236 path_pipeline: wgpu::RenderPipeline,
237 path_stenciled: [Option<wgpu::RenderPipeline>; MAX_STENCIL_LAYERS],
238
239 slug_shader: wgpu::ShaderModule,
240 slug_bgl: wgpu::BindGroupLayout,
241 slug_pl: wgpu::PipelineLayout,
242 slug_pipeline: wgpu::RenderPipeline,
243 slug_stenciled: [Option<wgpu::RenderPipeline>; MAX_STENCIL_LAYERS],
244 slug_bind_group: wgpu::BindGroup,
245
246 uniform_buffer: wgpu::Buffer,
247 uniform_bind_group: wgpu::BindGroup,
248
249 unit_quad_vbuf: wgpu::Buffer,
250 signed_quad_vbuf: wgpu::Buffer,
251 quad_ibuf: wgpu::Buffer,
252 quad_ibuf_cap_bytes: u64,
253 path_seg_ibuf: wgpu::Buffer,
254 path_seg_ibuf_cap_bytes: u64,
255 slug_inst_ibuf: wgpu::Buffer,
256 slug_inst_ibuf_cap_bytes: u64,
257 slug_curve_sbuf: wgpu::Buffer,
258 slug_curve_sbuf_cap_bytes: u64,
259 stencil_vbuf: wgpu::Buffer,
260 stencil_vbuf_cap_bytes: u64,
261
262 stencil_target: Option<StencilDepthTarget>,
263 offscreen: Option<Offscreen2DTarget>,
264 last_stencil_ranges: Vec<Vec<(Range<u64>, u32)>>,
265}
266
267#[inline]
268fn create_growable_buffer(
269 device: &wgpu::Device,
270 label: &str,
271 byte_size: u64,
272 usage: wgpu::BufferUsages,
273) -> (wgpu::Buffer, u64) {
274 let cap = byte_size.max(64).next_power_of_two();
275 let buf = device.create_buffer(&wgpu::BufferDescriptor {
276 label: Some(label),
277 size: cap,
278 usage,
279 mapped_at_creation: false,
280 });
281 (buf, cap)
282}
283
284#[inline]
285fn upload_growable(
286 device: &wgpu::Device,
287 queue: &wgpu::Queue,
288 label: &str,
289 usage: wgpu::BufferUsages,
290 buf: &mut wgpu::Buffer,
291 cap_bytes: &mut u64,
292 bytes: &[u8],
293) -> bool {
294 if bytes.is_empty() {
295 return false;
296 }
297 let needed = bytes.len() as u64;
298 let mut reallocated = false;
299 if needed > *cap_bytes {
300 let (next_buf, next_cap) = create_growable_buffer(device, label, needed, usage);
301 *buf = next_buf;
302 *cap_bytes = next_cap;
303 reallocated = true;
304 }
305 queue.write_buffer(buf, 0, bytes);
306 reallocated
307}
308
309#[inline]
310fn quad_vertex_bytes(verts: &[GpuVertex; 6]) -> &[u8] {
311 unsafe {
312 std::slice::from_raw_parts(verts.as_ptr() as *const u8, std::mem::size_of_val(verts))
313 }
314}
315
316#[inline]
317fn make_unit_vertex_layout() -> wgpu::VertexBufferLayout<'static> {
318 wgpu::VertexBufferLayout {
319 array_stride: std::mem::size_of::<GpuVertex>() as u64,
320 step_mode: wgpu::VertexStepMode::Vertex,
321 attributes: &[wgpu::VertexAttribute {
322 format: wgpu::VertexFormat::Float32x2,
323 offset: 0,
324 shader_location: 0,
325 }],
326 }
327}
328
329#[inline]
330fn make_quad_instance_layout() -> wgpu::VertexBufferLayout<'static> {
331 const ATTRS: [wgpu::VertexAttribute; 6] = [
332 wgpu::VertexAttribute {
333 format: wgpu::VertexFormat::Float32x4,
334 offset: 0,
335 shader_location: 1,
336 },
337 wgpu::VertexAttribute {
338 format: wgpu::VertexFormat::Float32x4,
339 offset: 16,
340 shader_location: 2,
341 },
342 wgpu::VertexAttribute {
343 format: wgpu::VertexFormat::Float32x4,
344 offset: 32,
345 shader_location: 3,
346 },
347 wgpu::VertexAttribute {
348 format: wgpu::VertexFormat::Float32x4,
349 offset: 48,
350 shader_location: 4,
351 },
352 wgpu::VertexAttribute {
353 format: wgpu::VertexFormat::Float32x4,
354 offset: 64,
355 shader_location: 5,
356 },
357 wgpu::VertexAttribute {
358 format: wgpu::VertexFormat::Float32x4,
359 offset: 80,
360 shader_location: 6,
361 },
362 ];
363 wgpu::VertexBufferLayout {
364 array_stride: GpuQuadInstance::BYTE_SIZE as u64,
365 step_mode: wgpu::VertexStepMode::Instance,
366 attributes: &ATTRS,
367 }
368}
369
370#[inline]
371fn make_path_instance_layout() -> wgpu::VertexBufferLayout<'static> {
372 const ATTRS: [wgpu::VertexAttribute; 7] = [
373 wgpu::VertexAttribute {
374 format: wgpu::VertexFormat::Float32x2,
375 offset: 0,
376 shader_location: 1,
377 },
378 wgpu::VertexAttribute {
379 format: wgpu::VertexFormat::Float32x2,
380 offset: 8,
381 shader_location: 2,
382 },
383 wgpu::VertexAttribute {
384 format: wgpu::VertexFormat::Float32x2,
385 offset: 16,
386 shader_location: 3,
387 },
388 wgpu::VertexAttribute {
389 format: wgpu::VertexFormat::Float32,
390 offset: 24,
391 shader_location: 4,
392 },
393 wgpu::VertexAttribute {
394 format: wgpu::VertexFormat::Uint32,
395 offset: 28,
396 shader_location: 5,
397 },
398 wgpu::VertexAttribute {
399 format: wgpu::VertexFormat::Float32x4,
400 offset: 32,
401 shader_location: 6,
402 },
403 wgpu::VertexAttribute {
404 format: wgpu::VertexFormat::Float32,
405 offset: 48,
406 shader_location: 7,
407 },
408 ];
409 wgpu::VertexBufferLayout {
410 array_stride: strata_gpu_path::GpuPathSegment::BYTE_SIZE as u64,
411 step_mode: wgpu::VertexStepMode::Instance,
412 attributes: &ATTRS,
413 }
414}
415
416#[inline]
417fn make_slug_instance_layout() -> wgpu::VertexBufferLayout<'static> {
418 const ATTRS: [wgpu::VertexAttribute; 5] = [
419 wgpu::VertexAttribute {
420 format: wgpu::VertexFormat::Float32x4,
421 offset: 0,
422 shader_location: 1,
423 },
424 wgpu::VertexAttribute {
425 format: wgpu::VertexFormat::Float32x4,
426 offset: 16,
427 shader_location: 2,
428 },
429 wgpu::VertexAttribute {
430 format: wgpu::VertexFormat::Uint32x2,
431 offset: 32,
432 shader_location: 3,
433 },
434 wgpu::VertexAttribute {
435 format: wgpu::VertexFormat::Float32x4,
436 offset: 40,
437 shader_location: 4,
438 },
439 wgpu::VertexAttribute {
440 format: wgpu::VertexFormat::Float32x4,
441 offset: 56,
442 shader_location: 5,
443 },
444 ];
445 wgpu::VertexBufferLayout {
446 array_stride: std::mem::size_of::<strata_gpu_path::GpuGlyphInstance>() as u64,
447 step_mode: wgpu::VertexStepMode::Instance,
448 attributes: &ATTRS,
449 }
450}
451
452#[inline]
453fn build_2d_pipeline(
454 device: &wgpu::Device,
455 label: &str,
456 layout: &wgpu::PipelineLayout,
457 shader: &wgpu::ShaderModule,
458 buffers: &[wgpu::VertexBufferLayout<'_>],
459 color_format: wgpu::TextureFormat,
460 blend: wgpu::BlendState,
461 stencil_layer_count: Option<usize>,
462) -> wgpu::RenderPipeline {
463 let stencil = match stencil_layer_count {
464 None => wgpu::StencilState {
465 front: wgpu::StencilFaceState::IGNORE,
466 back: wgpu::StencilFaceState::IGNORE,
467 read_mask: 0,
468 write_mask: 0,
469 },
470 Some(n) => {
471 let layers = n.clamp(1, MAX_STENCIL_LAYERS);
472 let mask_bits = ((1u32 << layers) - 1) & 0xFF;
473 let eq_face = wgpu::StencilFaceState {
474 compare: wgpu::CompareFunction::Equal,
475 fail_op: wgpu::StencilOperation::Keep,
476 depth_fail_op: wgpu::StencilOperation::Keep,
477 pass_op: wgpu::StencilOperation::Keep,
478 };
479 wgpu::StencilState {
480 front: eq_face,
481 back: eq_face,
482 read_mask: mask_bits,
483 write_mask: 0,
484 }
485 }
486 };
487
488 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
489 label: Some(label),
490 layout: Some(layout),
491 vertex: wgpu::VertexState {
492 module: shader,
493 entry_point: Some("vs_main"),
494 buffers,
495 compilation_options: Default::default(),
496 },
497 fragment: Some(wgpu::FragmentState {
498 module: shader,
499 entry_point: Some("fs_main"),
500 targets: &[Some(wgpu::ColorTargetState {
501 format: color_format,
502 blend: Some(blend),
503 write_mask: wgpu::ColorWrites::ALL,
504 })],
505 compilation_options: Default::default(),
506 }),
507 primitive: wgpu::PrimitiveState {
508 topology: wgpu::PrimitiveTopology::TriangleList,
509 cull_mode: None,
510 ..Default::default()
511 },
512 depth_stencil: Some(wgpu::DepthStencilState {
513 format: wgpu::TextureFormat::Depth24PlusStencil8,
514 depth_write_enabled: false,
515 depth_compare: wgpu::CompareFunction::Always,
516 stencil,
517 bias: wgpu::DepthBiasState::default(),
518 }),
519 multisample: wgpu::MultisampleState::default(),
520 multiview: None,
521 cache: None,
522 })
523}
524
525fn create_static_vertex_buffer(
526 device: &wgpu::Device,
527 queue: &wgpu::Queue,
528 label: &str,
529 bytes: &[u8],
530) -> wgpu::Buffer {
531 let buf = device.create_buffer(&wgpu::BufferDescriptor {
532 label: Some(label),
533 size: bytes.len() as u64,
534 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
535 mapped_at_creation: false,
536 });
537 queue.write_buffer(&buf, 0, bytes);
538 buf
539}
540
541fn compute_scissor_pixels(
542 op_scissor: Option<Rect>,
543 damage: Option<Rect>,
544 target_width: u32,
545 target_height: u32,
546 logical_w: f32,
547 logical_h: f32,
548) -> Option<[u32; 4]> {
549 let mut r = Rect::new(0.0, 0.0, logical_w.max(1.0), logical_h.max(1.0));
550 if let Some(s) = op_scissor {
551 r = r.intersect(s)?;
552 }
553 if let Some(d) = damage {
554 r = r.intersect(d)?;
555 }
556 let sx = target_width as f32 / logical_w.max(1.0);
557 let sy = target_height as f32 / logical_h.max(1.0);
558 let x0 = (r.x * sx).floor().max(0.0) as u32;
559 let y0 = (r.y * sy).floor().max(0.0) as u32;
560 let x1 = ((r.x + r.width) * sx).ceil().min(target_width as f32) as u32;
561 let y1 = ((r.y + r.height) * sy).ceil().min(target_height as f32) as u32;
562 if x1 <= x0 || y1 <= y0 {
563 return None;
564 }
565 Some([x0, y0, x1 - x0, y1 - y0])
566}
567
568impl Wgpu2DRenderer {
569 pub fn from_device(
571 device: Arc<wgpu::Device>,
572 queue: Arc<wgpu::Queue>,
573 color_format: wgpu::TextureFormat,
574 ) -> Self {
575 let stencil_clip_pipeline = GpuStencilClipPipeline::new(&device, color_format);
576
577 let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
578 label: Some("strata_2d_uniforms"),
579 size: GpuUniforms::BYTE_SIZE as u64,
580 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
581 mapped_at_creation: false,
582 });
583 let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
584 label: Some("strata_2d_uniform_bg"),
585 layout: stencil_clip_pipeline.uniform_bind_group_layout(),
586 entries: &[wgpu::BindGroupEntry {
587 binding: 0,
588 resource: uniform_buffer.as_entire_binding(),
589 }],
590 });
591
592 let unit_quad_vbuf = create_static_vertex_buffer(
593 &device,
594 &queue,
595 "strata_2d_unit_quad_vbuf",
596 quad_vertex_bytes(&QUAD_VERTICES),
597 );
598 let signed_quad_vbuf = create_static_vertex_buffer(
599 &device,
600 &queue,
601 "strata_2d_signed_quad_vbuf",
602 quad_vertex_bytes(&SIGNED_QUAD_VERTICES),
603 );
604
605 let unit_layout = make_unit_vertex_layout();
606 let quad_inst_layout = make_quad_instance_layout();
607 let path_inst_layout = make_path_instance_layout();
608 let slug_inst_layout = make_slug_instance_layout();
609
610 let quad_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
611 label: Some("strata_2d_analytical_quad_wgsl"),
612 source: wgpu::ShaderSource::Wgsl(WGSL_ANALYTICAL_QUAD_SHADER.into()),
613 });
614 let quad_pipeline = build_2d_pipeline(
615 &device,
616 "strata_2d_quad_pipeline",
617 stencil_clip_pipeline.uniform_pipeline_layout(),
618 &quad_shader,
619 &[unit_layout.clone(), quad_inst_layout.clone()],
620 color_format,
621 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
622 None,
623 );
624 let quad_l1 = build_2d_pipeline(
625 &device,
626 "strata_2d_quad_stenciled_pipeline",
627 stencil_clip_pipeline.uniform_pipeline_layout(),
628 &quad_shader,
629 &[unit_layout.clone(), quad_inst_layout],
630 color_format,
631 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
632 Some(1),
633 );
634 let quad_stenciled = [Some(quad_l1), None, None, None, None, None, None, None];
635
636 let path_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
637 label: Some("strata_2d_analytical_path_wgsl"),
638 source: wgpu::ShaderSource::Wgsl(
639 strata_gpu_path::WGSL_ANALYTICAL_PATH_RASTER_SHADER.into(),
640 ),
641 });
642 let path_pipeline = build_2d_pipeline(
643 &device,
644 "strata_2d_path_pipeline",
645 stencil_clip_pipeline.uniform_pipeline_layout(),
646 &path_shader,
647 &[unit_layout.clone(), path_inst_layout.clone()],
648 color_format,
649 wgpu::BlendState::ALPHA_BLENDING,
650 None,
651 );
652 let path_l1 = build_2d_pipeline(
653 &device,
654 "strata_2d_path_stenciled_pipeline",
655 stencil_clip_pipeline.uniform_pipeline_layout(),
656 &path_shader,
657 &[unit_layout.clone(), path_inst_layout],
658 color_format,
659 wgpu::BlendState::ALPHA_BLENDING,
660 Some(1),
661 );
662 let path_stenciled = [Some(path_l1), None, None, None, None, None, None, None];
663
664 let slug_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
665 label: Some("strata_2d_slug_bgl"),
666 entries: &[
667 wgpu::BindGroupLayoutEntry {
668 binding: 0,
669 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
670 ty: wgpu::BindingType::Buffer {
671 ty: wgpu::BufferBindingType::Uniform,
672 has_dynamic_offset: false,
673 min_binding_size: None,
674 },
675 count: None,
676 },
677 wgpu::BindGroupLayoutEntry {
678 binding: 1,
679 visibility: wgpu::ShaderStages::FRAGMENT,
680 ty: wgpu::BindingType::Buffer {
681 ty: wgpu::BufferBindingType::Storage { read_only: true },
682 has_dynamic_offset: false,
683 min_binding_size: None,
684 },
685 count: None,
686 },
687 ],
688 });
689 let slug_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
690 label: Some("strata_2d_slug_pl"),
691 bind_group_layouts: &[&slug_bgl],
692 push_constant_ranges: &[],
693 });
694 let slug_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
695 label: Some("strata_2d_slug_wgsl"),
696 source: wgpu::ShaderSource::Wgsl(strata_gpu_path::WGSL_SLUG_FONT_SHADER.into()),
697 });
698 let slug_pipeline = build_2d_pipeline(
699 &device,
700 "strata_2d_slug_pipeline",
701 &slug_pl,
702 &slug_shader,
703 &[unit_layout.clone(), slug_inst_layout.clone()],
704 color_format,
705 wgpu::BlendState::ALPHA_BLENDING,
706 None,
707 );
708 let slug_l1 = build_2d_pipeline(
709 &device,
710 "strata_2d_slug_stenciled_pipeline",
711 &slug_pl,
712 &slug_shader,
713 &[unit_layout, slug_inst_layout],
714 color_format,
715 wgpu::BlendState::ALPHA_BLENDING,
716 Some(1),
717 );
718 let slug_stenciled = [Some(slug_l1), None, None, None, None, None, None, None];
719
720 let (quad_ibuf, quad_ibuf_cap_bytes) = create_growable_buffer(
721 &device,
722 "strata_2d_quad_instances",
723 4096,
724 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
725 );
726 let (path_seg_ibuf, path_seg_ibuf_cap_bytes) = create_growable_buffer(
727 &device,
728 "strata_2d_path_segments",
729 4096,
730 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
731 );
732 let (slug_inst_ibuf, slug_inst_ibuf_cap_bytes) = create_growable_buffer(
733 &device,
734 "strata_2d_slug_instances",
735 4096,
736 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
737 );
738 let (slug_curve_sbuf, slug_curve_sbuf_cap_bytes) = create_growable_buffer(
739 &device,
740 "strata_2d_slug_curves",
741 4096,
742 wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
743 );
744 let (stencil_vbuf, stencil_vbuf_cap_bytes) = create_growable_buffer(
745 &device,
746 "strata_2d_stencil_vertices",
747 4096,
748 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
749 );
750
751 let slug_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
752 label: Some("strata_2d_slug_bg"),
753 layout: &slug_bgl,
754 entries: &[
755 wgpu::BindGroupEntry {
756 binding: 0,
757 resource: uniform_buffer.as_entire_binding(),
758 },
759 wgpu::BindGroupEntry {
760 binding: 1,
761 resource: slug_curve_sbuf.as_entire_binding(),
762 },
763 ],
764 });
765
766 Self {
767 device,
768 queue,
769 color_format,
770 stencil_clip_pipeline,
771 quad_shader,
772 quad_pipeline,
773 quad_stenciled,
774 path_shader,
775 path_pipeline,
776 path_stenciled,
777 slug_shader,
778 slug_bgl,
779 slug_pl,
780 slug_pipeline,
781 slug_stenciled,
782 slug_bind_group,
783 uniform_buffer,
784 uniform_bind_group,
785 unit_quad_vbuf,
786 signed_quad_vbuf,
787 quad_ibuf,
788 quad_ibuf_cap_bytes,
789 path_seg_ibuf,
790 path_seg_ibuf_cap_bytes,
791 slug_inst_ibuf,
792 slug_inst_ibuf_cap_bytes,
793 slug_curve_sbuf,
794 slug_curve_sbuf_cap_bytes,
795 stencil_vbuf,
796 stencil_vbuf_cap_bytes,
797 stencil_target: None,
798 offscreen: None,
799 last_stencil_ranges: Vec::new(),
800 }
801 }
802
803 #[inline]
804 pub fn device(&self) -> &Arc<wgpu::Device> {
805 &self.device
806 }
807
808 #[inline]
809 pub fn queue(&self) -> &Arc<wgpu::Queue> {
810 &self.queue
811 }
812
813 #[inline]
814 pub fn color_format(&self) -> wgpu::TextureFormat {
815 self.color_format
816 }
817
818 #[inline]
820 pub fn stencil_clip_pipeline(&self) -> &GpuStencilClipPipeline {
821 &self.stencil_clip_pipeline
822 }
823
824 pub fn gpu_memory_bytes(&self) -> u64 {
826 let mut bytes = self.uniform_buffer.size()
827 + self.unit_quad_vbuf.size()
828 + self.signed_quad_vbuf.size()
829 + self.quad_ibuf_cap_bytes
830 + self.path_seg_ibuf_cap_bytes
831 + self.slug_inst_ibuf_cap_bytes
832 + self.slug_curve_sbuf_cap_bytes
833 + self.stencil_vbuf_cap_bytes;
834 if let Some(ref st) = self.stencil_target {
835 bytes += (st.width as u64) * (st.height as u64) * 4;
836 }
837 if let Some(ref off) = self.offscreen {
838 bytes += (off.width as u64) * (off.height as u64) * 4
839 + (off.padded_bytes_per_row as u64) * (off.height as u64);
840 }
841 bytes
842 }
843
844 fn ensure_stencil_target(&mut self, width: u32, height: u32) {
845 let w = width.max(1);
846 let h = height.max(1);
847 let valid = self
848 .stencil_target
849 .as_ref()
850 .is_some_and(|t| t.width == w && t.height == h);
851 if valid {
852 return;
853 }
854 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
855 label: Some("strata_2d_depth24_stencil8"),
856 size: wgpu::Extent3d {
857 width: w,
858 height: h,
859 depth_or_array_layers: 1,
860 },
861 mip_level_count: 1,
862 sample_count: 1,
863 dimension: wgpu::TextureDimension::D2,
864 format: wgpu::TextureFormat::Depth24PlusStencil8,
865 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
866 view_formats: &[],
867 });
868 let view = tex.create_view(&Default::default());
869 self.stencil_target = Some(StencilDepthTarget {
870 width: w,
871 height: h,
872 _texture: tex,
873 view,
874 });
875 }
876
877 fn ensure_stenciled_pipelines(&mut self, layer_count: usize) {
878 let slot = layer_count.clamp(1, MAX_STENCIL_LAYERS) - 1;
879 if self.quad_stenciled[slot].is_none() {
880 self.quad_stenciled[slot] = Some(build_2d_pipeline(
881 &self.device,
882 "strata_2d_quad_stenciled_pipeline",
883 self.stencil_clip_pipeline.uniform_pipeline_layout(),
884 &self.quad_shader,
885 &[make_unit_vertex_layout(), make_quad_instance_layout()],
886 self.color_format,
887 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
888 Some(slot + 1),
889 ));
890 }
891 if self.path_stenciled[slot].is_none() {
892 self.path_stenciled[slot] = Some(build_2d_pipeline(
893 &self.device,
894 "strata_2d_path_stenciled_pipeline",
895 self.stencil_clip_pipeline.uniform_pipeline_layout(),
896 &self.path_shader,
897 &[make_unit_vertex_layout(), make_path_instance_layout()],
898 self.color_format,
899 wgpu::BlendState::ALPHA_BLENDING,
900 Some(slot + 1),
901 ));
902 }
903 if self.slug_stenciled[slot].is_none() {
904 self.slug_stenciled[slot] = Some(build_2d_pipeline(
905 &self.device,
906 "strata_2d_slug_stenciled_pipeline",
907 &self.slug_pl,
908 &self.slug_shader,
909 &[make_unit_vertex_layout(), make_slug_instance_layout()],
910 self.color_format,
911 wgpu::BlendState::ALPHA_BLENDING,
912 Some(slot + 1),
913 ));
914 }
915 }
916
917 pub fn prepare_frame(&mut self, frame: &Hardware2DFrame, logical_w: f32, logical_h: f32, dpr: f32) {
919 let uni = Gpu2DUniformData {
920 viewport_size: [logical_w.max(1.0), logical_h.max(1.0)],
921 dpr: dpr.max(0.1),
922 _pad: 0.0,
923 };
924 self.queue.write_buffer(&self.uniform_buffer, 0, uni.as_bytes());
925
926 upload_growable(
927 &self.device,
928 &self.queue,
929 "strata_2d_quad_instances",
930 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
931 &mut self.quad_ibuf,
932 &mut self.quad_ibuf_cap_bytes,
933 frame.quads.as_bytes(),
934 );
935 upload_growable(
936 &self.device,
937 &self.queue,
938 "strata_2d_path_segments",
939 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
940 &mut self.path_seg_ibuf,
941 &mut self.path_seg_ibuf_cap_bytes,
942 frame.paths.as_bytes(),
943 );
944 upload_growable(
945 &self.device,
946 &self.queue,
947 "strata_2d_slug_instances",
948 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
949 &mut self.slug_inst_ibuf,
950 &mut self.slug_inst_ibuf_cap_bytes,
951 frame.text.instance_bytes(),
952 );
953 if upload_growable(
954 &self.device,
955 &self.queue,
956 "strata_2d_slug_curves",
957 wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
958 &mut self.slug_curve_sbuf,
959 &mut self.slug_curve_sbuf_cap_bytes,
960 frame.text.curve_bytes(),
961 ) {
962 self.slug_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
963 label: Some("strata_2d_slug_bg"),
964 layout: &self.slug_bgl,
965 entries: &[
966 wgpu::BindGroupEntry {
967 binding: 0,
968 resource: self.uniform_buffer.as_entire_binding(),
969 },
970 wgpu::BindGroupEntry {
971 binding: 1,
972 resource: self.slug_curve_sbuf.as_entire_binding(),
973 },
974 ],
975 });
976 }
977
978 self.last_stencil_ranges.clear();
980 let total_verts: usize = frame
981 .clip_masks
982 .iter()
983 .map(|m| m.total_stencil_vertices())
984 .sum();
985 let mut max_layer_count = 1usize;
986 if total_verts > 0 {
987 let mut packed = Vec::<GpuClipVertex>::with_capacity(total_verts);
988 for mask in &frame.clip_masks {
989 let mut layer_ranges = Vec::with_capacity(mask.stencil_layers.len());
990 let mut non_empty = 0usize;
991 for layer in &mask.stencil_layers {
992 if layer.is_empty() {
993 continue;
994 }
995 let start_byte = (packed.len() * GpuClipVertex::BYTE_SIZE) as u64;
996 packed.extend_from_slice(layer);
997 let end_byte = (packed.len() * GpuClipVertex::BYTE_SIZE) as u64;
998 layer_ranges.push((start_byte..end_byte, layer.len() as u32));
999 non_empty += 1;
1000 }
1001 max_layer_count = max_layer_count.max(non_empty.min(MAX_STENCIL_LAYERS));
1002 self.last_stencil_ranges.push(layer_ranges);
1003 }
1004 upload_growable(
1005 &self.device,
1006 &self.queue,
1007 "strata_2d_stencil_vertices",
1008 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1009 &mut self.stencil_vbuf,
1010 &mut self.stencil_vbuf_cap_bytes,
1011 GpuClipVertex::slice_to_bytes(&packed),
1012 );
1013 }
1014 for n in 1..=max_layer_count {
1015 self.ensure_stenciled_pipelines(n);
1016 }
1017 }
1018
1019 #[allow(clippy::too_many_arguments)]
1022 pub fn render_batch_slice_to_view(
1023 &mut self,
1024 frame: &Hardware2DFrame,
1025 item_range: Range<usize>,
1026 target_view: &wgpu::TextureView,
1027 target_width: u32,
1028 target_height: u32,
1029 logical_w: f32,
1030 logical_h: f32,
1031 clear_color: Option<[f32; 4]>,
1032 damage: Option<Rect>,
1033 ) {
1034 let w = target_width.max(1);
1035 let h = target_height.max(1);
1036 self.ensure_stencil_target(w, h);
1037 let stencil_view = self.stencil_target.as_ref().unwrap().view.clone();
1038
1039 let has_batches = frame.items[item_range.clone()]
1040 .iter()
1041 .any(|it| matches!(it, HardwareRenderItem::Batch(_)));
1042 if !has_batches && clear_color.is_none() {
1043 return;
1044 }
1045
1046 let mut encoder = self
1047 .device
1048 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1049 label: Some("strata_2d_encoder"),
1050 });
1051
1052 if !has_batches {
1053 if let Some(c) = clear_color {
1054 {
1055 let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1056 label: Some("strata_2d_clear_pass"),
1057 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1058 view: target_view,
1059 resolve_target: None,
1060 ops: wgpu::Operations {
1061 load: wgpu::LoadOp::Clear(wgpu::Color {
1062 r: c[0] as f64,
1063 g: c[1] as f64,
1064 b: c[2] as f64,
1065 a: c[3] as f64,
1066 }),
1067 store: wgpu::StoreOp::Store,
1068 },
1069 })],
1070 depth_stencil_attachment: None,
1071 timestamp_writes: None,
1072 occlusion_query_set: None,
1073 });
1074 }
1075 self.queue.submit(Some(encoder.finish()));
1076 }
1077 return;
1078 }
1079
1080 let mut pass_slices: Vec<(usize, usize)> = Vec::new();
1083 let mut run_start = item_range.start;
1084 let mut active_stencil_mask: Option<usize> = None;
1085 for idx in item_range.clone() {
1086 if let HardwareRenderItem::Batch(op) = frame.items[idx] {
1087 if let Some(mask_id) = op.clip_mask {
1088 if let Some(prev) = active_stencil_mask {
1089 if prev != mask_id {
1090 pass_slices.push((run_start, idx));
1091 run_start = idx;
1092 active_stencil_mask = Some(mask_id);
1093 }
1094 } else {
1095 active_stencil_mask = Some(mask_id);
1096 }
1097 }
1098 }
1099 }
1100 pass_slices.push((run_start, item_range.end));
1101
1102 let quad_bytes = frame.quads.as_bytes();
1103 let path_bytes = frame.paths.as_bytes();
1104 let slug_inst_bytes = frame.text.instance_bytes();
1105
1106 for (pass_idx, (s, e)) in pass_slices.into_iter().enumerate() {
1107 let color_load = if pass_idx == 0 {
1108 match clear_color {
1109 Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
1110 r: c[0] as f64,
1111 g: c[1] as f64,
1112 b: c[2] as f64,
1113 a: c[3] as f64,
1114 }),
1115 None => wgpu::LoadOp::Load,
1116 }
1117 } else {
1118 wgpu::LoadOp::Load
1119 };
1120
1121 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1122 label: Some("strata_2d_batch_pass"),
1123 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1124 view: target_view,
1125 resolve_target: None,
1126 ops: wgpu::Operations {
1127 load: color_load,
1128 store: wgpu::StoreOp::Store,
1129 },
1130 })],
1131 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
1132 view: &stencil_view,
1133 depth_ops: Some(wgpu::Operations {
1134 load: wgpu::LoadOp::Clear(1.0),
1135 store: wgpu::StoreOp::Discard,
1136 }),
1137 stencil_ops: Some(wgpu::Operations {
1138 load: wgpu::LoadOp::Clear(0),
1139 store: wgpu::StoreOp::Discard,
1140 }),
1141 }),
1142 timestamp_writes: None,
1143 occlusion_query_set: None,
1144 });
1145
1146 let mut loaded_mask: Option<(usize, usize)> = None;
1147 for item in &frame.items[s..e] {
1148 let HardwareRenderItem::Batch(op) = item else {
1149 continue;
1150 };
1151 if op.end <= op.start {
1152 continue;
1153 }
1154
1155 let mut active_layers = 0usize;
1156 if let Some(mask_id) = op.clip_mask {
1157 if let Some((prev_id, prev_layers)) = loaded_mask {
1158 if prev_id == mask_id {
1159 active_layers = prev_layers;
1160 }
1161 } else if let Some(layers) = self.last_stencil_ranges.get(mask_id) {
1162 if let Some([sx, sy, sw, sh]) = compute_scissor_pixels(
1163 None, damage, w, h, logical_w, logical_h,
1164 ) {
1165 pass.set_scissor_rect(sx, sy, sw, sh);
1166 active_layers = self.stencil_clip_pipeline.record_mask(
1167 &mut pass,
1168 &self.uniform_bind_group,
1169 &self.stencil_vbuf,
1170 layers,
1171 );
1172 loaded_mask = Some((mask_id, active_layers));
1173 }
1174 }
1175 }
1176
1177 let Some([sx, sy, sw, sh]) = compute_scissor_pixels(
1178 op.scissor_rect,
1179 damage,
1180 w,
1181 h,
1182 logical_w,
1183 logical_h,
1184 ) else {
1185 continue;
1186 };
1187 pass.set_scissor_rect(sx, sy, sw, sh);
1188
1189 let inst_count = (op.end - op.start) as u32;
1190 let stencil_ref = if active_layers > 0 {
1191 ((1u32 << active_layers.min(MAX_STENCIL_LAYERS)) - 1) & 0xFF
1192 } else {
1193 0
1194 };
1195
1196 match op.kind {
1197 HardwareDrawOpKind::Quads => {
1198 let start_byte = (op.start * GpuQuadInstance::BYTE_SIZE) as u64;
1199 let end_byte = (op.end * GpuQuadInstance::BYTE_SIZE) as u64;
1200 if end_byte as usize > quad_bytes.len() {
1201 continue;
1202 }
1203 let pipe = if active_layers > 0 {
1204 self.quad_stenciled[active_layers - 1]
1205 .as_ref()
1206 .unwrap_or(&self.quad_pipeline)
1207 } else {
1208 &self.quad_pipeline
1209 };
1210 pass.set_pipeline(pipe);
1211 pass.set_bind_group(0, &self.uniform_bind_group, &[]);
1212 pass.set_vertex_buffer(0, self.unit_quad_vbuf.slice(..));
1213 pass.set_vertex_buffer(1, self.quad_ibuf.slice(start_byte..end_byte));
1214 pass.set_stencil_reference(stencil_ref);
1215 pass.draw(0..6, 0..inst_count);
1216 }
1217 HardwareDrawOpKind::Paths => {
1218 let stride = strata_gpu_path::GpuPathSegment::BYTE_SIZE;
1219 let start_byte = (op.start * stride) as u64;
1220 let end_byte = (op.end * stride) as u64;
1221 if end_byte as usize > path_bytes.len() {
1222 continue;
1223 }
1224 let pipe = if active_layers > 0 {
1225 self.path_stenciled[active_layers - 1]
1226 .as_ref()
1227 .unwrap_or(&self.path_pipeline)
1228 } else {
1229 &self.path_pipeline
1230 };
1231 pass.set_pipeline(pipe);
1232 pass.set_bind_group(0, &self.uniform_bind_group, &[]);
1233 pass.set_vertex_buffer(0, self.signed_quad_vbuf.slice(..));
1234 pass.set_vertex_buffer(1, self.path_seg_ibuf.slice(start_byte..end_byte));
1235 pass.set_stencil_reference(stencil_ref);
1236 pass.draw(0..6, 0..inst_count);
1237 }
1238 HardwareDrawOpKind::Text => {
1239 let stride = std::mem::size_of::<strata_gpu_path::GpuGlyphInstance>();
1240 let start_byte = (op.start * stride) as u64;
1241 let end_byte = (op.end * stride) as u64;
1242 if end_byte as usize > slug_inst_bytes.len() {
1243 continue;
1244 }
1245 let pipe = if active_layers > 0 {
1246 self.slug_stenciled[active_layers - 1]
1247 .as_ref()
1248 .unwrap_or(&self.slug_pipeline)
1249 } else {
1250 &self.slug_pipeline
1251 };
1252 pass.set_pipeline(pipe);
1253 pass.set_bind_group(0, &self.slug_bind_group, &[]);
1254 pass.set_vertex_buffer(0, self.unit_quad_vbuf.slice(..));
1255 pass.set_vertex_buffer(1, self.slug_inst_ibuf.slice(start_byte..end_byte));
1256 pass.set_stencil_reference(stencil_ref);
1257 pass.draw(0..6, 0..inst_count);
1258 }
1259 }
1260 }
1261 }
1262
1263 self.queue.submit(Some(encoder.finish()));
1264 }
1265
1266 #[allow(clippy::too_many_arguments)]
1269 pub fn render_display_list_to_view(
1270 &mut self,
1271 collector: &mut crate::gpu_pipeline::UnifiedGpuCollector,
1272 list: &crate::compositor::DisplayList,
1273 target_view: &wgpu::TextureView,
1274 target_width: u32,
1275 target_height: u32,
1276 dpr: f32,
1277 clear_color: Option<[f32; 4]>,
1278 damage: Option<Rect>,
1279 ) -> crate::gpu_pipeline::GpuBatchSummary {
1280 let frame = collector.collect_hardware_frame(list, damage);
1281 self.prepare_frame(&frame, collector.viewport_width, collector.viewport_height, dpr);
1282 self.render_batch_slice_to_view(
1283 &frame,
1284 0..frame.items.len(),
1285 target_view,
1286 target_width,
1287 target_height,
1288 collector.viewport_width,
1289 collector.viewport_height,
1290 clear_color,
1291 damage,
1292 );
1293 frame.summary
1294 }
1295
1296 #[allow(clippy::too_many_arguments)]
1299 pub fn render_display_list_offscreen(
1300 &mut self,
1301 collector: &mut crate::gpu_pipeline::UnifiedGpuCollector,
1302 list: &crate::compositor::DisplayList,
1303 width: u32,
1304 height: u32,
1305 dpr: f32,
1306 clear_color: [f32; 4],
1307 damage: Option<Rect>,
1308 readback: bool,
1309 ) -> Result<(crate::gpu_pipeline::GpuBatchSummary, Vec<u8>), String> {
1310 let w = width.max(1);
1311 let h = height.max(1);
1312 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1313 let unpadded = w * 4;
1314 let padded = unpadded.div_ceil(align) * align;
1315
1316 let recreate = self
1317 .offscreen
1318 .as_ref()
1319 .is_none_or(|o| o.width != w || o.height != h || o.format != self.color_format);
1320 if recreate {
1321 let color = self.device.create_texture(&wgpu::TextureDescriptor {
1322 label: Some("strata_2d_offscreen_color"),
1323 size: wgpu::Extent3d {
1324 width: w,
1325 height: h,
1326 depth_or_array_layers: 1,
1327 },
1328 mip_level_count: 1,
1329 sample_count: 1,
1330 dimension: wgpu::TextureDimension::D2,
1331 format: self.color_format,
1332 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
1333 view_formats: &[],
1334 });
1335 let view = color.create_view(&Default::default());
1336 let rb = self.device.create_buffer(&wgpu::BufferDescriptor {
1337 label: Some("strata_2d_offscreen_readback"),
1338 size: (padded * h) as u64,
1339 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1340 mapped_at_creation: false,
1341 });
1342 self.offscreen = Some(Offscreen2DTarget {
1343 width: w,
1344 height: h,
1345 format: self.color_format,
1346 color,
1347 view,
1348 readback: rb,
1349 padded_bytes_per_row: padded,
1350 });
1351 }
1352
1353 let target_view = self.offscreen.as_ref().unwrap().view.clone();
1354 let summary = self.render_display_list_to_view(
1355 collector,
1356 list,
1357 &target_view,
1358 w,
1359 h,
1360 dpr,
1361 Some(clear_color),
1362 damage,
1363 );
1364
1365 if !readback {
1366 self.device.poll(wgpu::Maintain::Wait);
1367 return Ok((summary, Vec::new()));
1368 }
1369
1370 let off = self.offscreen.as_ref().unwrap();
1371 let mut enc = self
1372 .device
1373 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1374 label: Some("strata_2d_readback_encoder"),
1375 });
1376 enc.copy_texture_to_buffer(
1377 wgpu::TexelCopyTextureInfo {
1378 texture: &off.color,
1379 mip_level: 0,
1380 origin: wgpu::Origin3d::ZERO,
1381 aspect: wgpu::TextureAspect::All,
1382 },
1383 wgpu::TexelCopyBufferInfo {
1384 buffer: &off.readback,
1385 layout: wgpu::TexelCopyBufferLayout {
1386 offset: 0,
1387 bytes_per_row: Some(off.padded_bytes_per_row),
1388 rows_per_image: Some(h),
1389 },
1390 },
1391 wgpu::Extent3d {
1392 width: w,
1393 height: h,
1394 depth_or_array_layers: 1,
1395 },
1396 );
1397 self.queue.submit(Some(enc.finish()));
1398
1399 let slice = off.readback.slice(..);
1400 let (tx, rx) = std::sync::mpsc::channel();
1401 slice.map_async(wgpu::MapMode::Read, move |res| {
1402 let _ = tx.send(res);
1403 });
1404 self.device.poll(wgpu::Maintain::Wait);
1405 rx.recv()
1406 .map_err(|e| format!("2d readback recv error: {e}"))?
1407 .map_err(|e| format!("2d readback map error: {e:?}"))?;
1408
1409 let data = slice.get_mapped_range();
1410 let mut out = vec![0u8; (w * h * 4) as usize];
1411 let row_len = w as usize * 4;
1412 for row in 0..h as usize {
1413 let src_start = row * off.padded_bytes_per_row as usize;
1414 let dst_start = row * row_len;
1415 out[dst_start..dst_start + row_len]
1416 .copy_from_slice(&data[src_start..src_start + row_len]);
1417 }
1418 drop(data);
1419 off.readback.unmap();
1420 Ok((summary, out))
1421 }
1422}