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 fn ensure_stencil_target(&mut self, width: u32, height: u32) {
825 let w = width.max(1);
826 let h = height.max(1);
827 let valid = self
828 .stencil_target
829 .as_ref()
830 .is_some_and(|t| t.width == w && t.height == h);
831 if valid {
832 return;
833 }
834 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
835 label: Some("strata_2d_depth24_stencil8"),
836 size: wgpu::Extent3d {
837 width: w,
838 height: h,
839 depth_or_array_layers: 1,
840 },
841 mip_level_count: 1,
842 sample_count: 1,
843 dimension: wgpu::TextureDimension::D2,
844 format: wgpu::TextureFormat::Depth24PlusStencil8,
845 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
846 view_formats: &[],
847 });
848 let view = tex.create_view(&Default::default());
849 self.stencil_target = Some(StencilDepthTarget {
850 width: w,
851 height: h,
852 _texture: tex,
853 view,
854 });
855 }
856
857 fn ensure_stenciled_pipelines(&mut self, layer_count: usize) {
858 let slot = layer_count.clamp(1, MAX_STENCIL_LAYERS) - 1;
859 if self.quad_stenciled[slot].is_none() {
860 self.quad_stenciled[slot] = Some(build_2d_pipeline(
861 &self.device,
862 "strata_2d_quad_stenciled_pipeline",
863 self.stencil_clip_pipeline.uniform_pipeline_layout(),
864 &self.quad_shader,
865 &[make_unit_vertex_layout(), make_quad_instance_layout()],
866 self.color_format,
867 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
868 Some(slot + 1),
869 ));
870 }
871 if self.path_stenciled[slot].is_none() {
872 self.path_stenciled[slot] = Some(build_2d_pipeline(
873 &self.device,
874 "strata_2d_path_stenciled_pipeline",
875 self.stencil_clip_pipeline.uniform_pipeline_layout(),
876 &self.path_shader,
877 &[make_unit_vertex_layout(), make_path_instance_layout()],
878 self.color_format,
879 wgpu::BlendState::ALPHA_BLENDING,
880 Some(slot + 1),
881 ));
882 }
883 if self.slug_stenciled[slot].is_none() {
884 self.slug_stenciled[slot] = Some(build_2d_pipeline(
885 &self.device,
886 "strata_2d_slug_stenciled_pipeline",
887 &self.slug_pl,
888 &self.slug_shader,
889 &[make_unit_vertex_layout(), make_slug_instance_layout()],
890 self.color_format,
891 wgpu::BlendState::ALPHA_BLENDING,
892 Some(slot + 1),
893 ));
894 }
895 }
896
897 pub fn prepare_frame(&mut self, frame: &Hardware2DFrame, logical_w: f32, logical_h: f32, dpr: f32) {
899 let uni = Gpu2DUniformData {
900 viewport_size: [logical_w.max(1.0), logical_h.max(1.0)],
901 dpr: dpr.max(0.1),
902 _pad: 0.0,
903 };
904 self.queue.write_buffer(&self.uniform_buffer, 0, uni.as_bytes());
905
906 upload_growable(
907 &self.device,
908 &self.queue,
909 "strata_2d_quad_instances",
910 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
911 &mut self.quad_ibuf,
912 &mut self.quad_ibuf_cap_bytes,
913 frame.quads.as_bytes(),
914 );
915 upload_growable(
916 &self.device,
917 &self.queue,
918 "strata_2d_path_segments",
919 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
920 &mut self.path_seg_ibuf,
921 &mut self.path_seg_ibuf_cap_bytes,
922 frame.paths.as_bytes(),
923 );
924 upload_growable(
925 &self.device,
926 &self.queue,
927 "strata_2d_slug_instances",
928 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
929 &mut self.slug_inst_ibuf,
930 &mut self.slug_inst_ibuf_cap_bytes,
931 frame.text.instance_bytes(),
932 );
933 if upload_growable(
934 &self.device,
935 &self.queue,
936 "strata_2d_slug_curves",
937 wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
938 &mut self.slug_curve_sbuf,
939 &mut self.slug_curve_sbuf_cap_bytes,
940 frame.text.curve_bytes(),
941 ) {
942 self.slug_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
943 label: Some("strata_2d_slug_bg"),
944 layout: &self.slug_bgl,
945 entries: &[
946 wgpu::BindGroupEntry {
947 binding: 0,
948 resource: self.uniform_buffer.as_entire_binding(),
949 },
950 wgpu::BindGroupEntry {
951 binding: 1,
952 resource: self.slug_curve_sbuf.as_entire_binding(),
953 },
954 ],
955 });
956 }
957
958 self.last_stencil_ranges.clear();
960 let total_verts: usize = frame
961 .clip_masks
962 .iter()
963 .map(|m| m.total_stencil_vertices())
964 .sum();
965 let mut max_layer_count = 1usize;
966 if total_verts > 0 {
967 let mut packed = Vec::<GpuClipVertex>::with_capacity(total_verts);
968 for mask in &frame.clip_masks {
969 let mut layer_ranges = Vec::with_capacity(mask.stencil_layers.len());
970 let mut non_empty = 0usize;
971 for layer in &mask.stencil_layers {
972 if layer.is_empty() {
973 continue;
974 }
975 let start_byte = (packed.len() * GpuClipVertex::BYTE_SIZE) as u64;
976 packed.extend_from_slice(layer);
977 let end_byte = (packed.len() * GpuClipVertex::BYTE_SIZE) as u64;
978 layer_ranges.push((start_byte..end_byte, layer.len() as u32));
979 non_empty += 1;
980 }
981 max_layer_count = max_layer_count.max(non_empty.min(MAX_STENCIL_LAYERS));
982 self.last_stencil_ranges.push(layer_ranges);
983 }
984 upload_growable(
985 &self.device,
986 &self.queue,
987 "strata_2d_stencil_vertices",
988 wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
989 &mut self.stencil_vbuf,
990 &mut self.stencil_vbuf_cap_bytes,
991 GpuClipVertex::slice_to_bytes(&packed),
992 );
993 }
994 for n in 1..=max_layer_count {
995 self.ensure_stenciled_pipelines(n);
996 }
997 }
998
999 #[allow(clippy::too_many_arguments)]
1002 pub fn render_batch_slice_to_view(
1003 &mut self,
1004 frame: &Hardware2DFrame,
1005 item_range: Range<usize>,
1006 target_view: &wgpu::TextureView,
1007 target_width: u32,
1008 target_height: u32,
1009 logical_w: f32,
1010 logical_h: f32,
1011 clear_color: Option<[f32; 4]>,
1012 damage: Option<Rect>,
1013 ) {
1014 let w = target_width.max(1);
1015 let h = target_height.max(1);
1016 self.ensure_stencil_target(w, h);
1017 let stencil_view = self.stencil_target.as_ref().unwrap().view.clone();
1018
1019 let has_batches = frame.items[item_range.clone()]
1020 .iter()
1021 .any(|it| matches!(it, HardwareRenderItem::Batch(_)));
1022 if !has_batches && clear_color.is_none() {
1023 return;
1024 }
1025
1026 let mut encoder = self
1027 .device
1028 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1029 label: Some("strata_2d_encoder"),
1030 });
1031
1032 if !has_batches {
1033 if let Some(c) = clear_color {
1034 {
1035 let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1036 label: Some("strata_2d_clear_pass"),
1037 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1038 view: target_view,
1039 resolve_target: None,
1040 ops: wgpu::Operations {
1041 load: wgpu::LoadOp::Clear(wgpu::Color {
1042 r: c[0] as f64,
1043 g: c[1] as f64,
1044 b: c[2] as f64,
1045 a: c[3] as f64,
1046 }),
1047 store: wgpu::StoreOp::Store,
1048 },
1049 })],
1050 depth_stencil_attachment: None,
1051 timestamp_writes: None,
1052 occlusion_query_set: None,
1053 });
1054 }
1055 self.queue.submit(Some(encoder.finish()));
1056 }
1057 return;
1058 }
1059
1060 let mut pass_slices: Vec<(usize, usize)> = Vec::new();
1063 let mut run_start = item_range.start;
1064 let mut active_stencil_mask: Option<usize> = None;
1065 for idx in item_range.clone() {
1066 if let HardwareRenderItem::Batch(op) = frame.items[idx] {
1067 if let Some(mask_id) = op.clip_mask {
1068 if let Some(prev) = active_stencil_mask {
1069 if prev != mask_id {
1070 pass_slices.push((run_start, idx));
1071 run_start = idx;
1072 active_stencil_mask = Some(mask_id);
1073 }
1074 } else {
1075 active_stencil_mask = Some(mask_id);
1076 }
1077 }
1078 }
1079 }
1080 pass_slices.push((run_start, item_range.end));
1081
1082 let quad_bytes = frame.quads.as_bytes();
1083 let path_bytes = frame.paths.as_bytes();
1084 let slug_inst_bytes = frame.text.instance_bytes();
1085
1086 for (pass_idx, (s, e)) in pass_slices.into_iter().enumerate() {
1087 let color_load = if pass_idx == 0 {
1088 match clear_color {
1089 Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
1090 r: c[0] as f64,
1091 g: c[1] as f64,
1092 b: c[2] as f64,
1093 a: c[3] as f64,
1094 }),
1095 None => wgpu::LoadOp::Load,
1096 }
1097 } else {
1098 wgpu::LoadOp::Load
1099 };
1100
1101 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1102 label: Some("strata_2d_batch_pass"),
1103 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1104 view: target_view,
1105 resolve_target: None,
1106 ops: wgpu::Operations {
1107 load: color_load,
1108 store: wgpu::StoreOp::Store,
1109 },
1110 })],
1111 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
1112 view: &stencil_view,
1113 depth_ops: Some(wgpu::Operations {
1114 load: wgpu::LoadOp::Clear(1.0),
1115 store: wgpu::StoreOp::Discard,
1116 }),
1117 stencil_ops: Some(wgpu::Operations {
1118 load: wgpu::LoadOp::Clear(0),
1119 store: wgpu::StoreOp::Discard,
1120 }),
1121 }),
1122 timestamp_writes: None,
1123 occlusion_query_set: None,
1124 });
1125
1126 let mut loaded_mask: Option<(usize, usize)> = None;
1127 for item in &frame.items[s..e] {
1128 let HardwareRenderItem::Batch(op) = item else {
1129 continue;
1130 };
1131 if op.end <= op.start {
1132 continue;
1133 }
1134
1135 let mut active_layers = 0usize;
1136 if let Some(mask_id) = op.clip_mask {
1137 if let Some((prev_id, prev_layers)) = loaded_mask {
1138 if prev_id == mask_id {
1139 active_layers = prev_layers;
1140 }
1141 } else if let Some(layers) = self.last_stencil_ranges.get(mask_id) {
1142 if let Some([sx, sy, sw, sh]) = compute_scissor_pixels(
1143 None, damage, w, h, logical_w, logical_h,
1144 ) {
1145 pass.set_scissor_rect(sx, sy, sw, sh);
1146 active_layers = self.stencil_clip_pipeline.record_mask(
1147 &mut pass,
1148 &self.uniform_bind_group,
1149 &self.stencil_vbuf,
1150 layers,
1151 );
1152 loaded_mask = Some((mask_id, active_layers));
1153 }
1154 }
1155 }
1156
1157 let Some([sx, sy, sw, sh]) = compute_scissor_pixels(
1158 op.scissor_rect,
1159 damage,
1160 w,
1161 h,
1162 logical_w,
1163 logical_h,
1164 ) else {
1165 continue;
1166 };
1167 pass.set_scissor_rect(sx, sy, sw, sh);
1168
1169 let inst_count = (op.end - op.start) as u32;
1170 let stencil_ref = if active_layers > 0 {
1171 ((1u32 << active_layers.min(MAX_STENCIL_LAYERS)) - 1) & 0xFF
1172 } else {
1173 0
1174 };
1175
1176 match op.kind {
1177 HardwareDrawOpKind::Quads => {
1178 let start_byte = (op.start * GpuQuadInstance::BYTE_SIZE) as u64;
1179 let end_byte = (op.end * GpuQuadInstance::BYTE_SIZE) as u64;
1180 if end_byte as usize > quad_bytes.len() {
1181 continue;
1182 }
1183 let pipe = if active_layers > 0 {
1184 self.quad_stenciled[active_layers - 1]
1185 .as_ref()
1186 .unwrap_or(&self.quad_pipeline)
1187 } else {
1188 &self.quad_pipeline
1189 };
1190 pass.set_pipeline(pipe);
1191 pass.set_bind_group(0, &self.uniform_bind_group, &[]);
1192 pass.set_vertex_buffer(0, self.unit_quad_vbuf.slice(..));
1193 pass.set_vertex_buffer(1, self.quad_ibuf.slice(start_byte..end_byte));
1194 pass.set_stencil_reference(stencil_ref);
1195 pass.draw(0..6, 0..inst_count);
1196 }
1197 HardwareDrawOpKind::Paths => {
1198 let stride = strata_gpu_path::GpuPathSegment::BYTE_SIZE;
1199 let start_byte = (op.start * stride) as u64;
1200 let end_byte = (op.end * stride) as u64;
1201 if end_byte as usize > path_bytes.len() {
1202 continue;
1203 }
1204 let pipe = if active_layers > 0 {
1205 self.path_stenciled[active_layers - 1]
1206 .as_ref()
1207 .unwrap_or(&self.path_pipeline)
1208 } else {
1209 &self.path_pipeline
1210 };
1211 pass.set_pipeline(pipe);
1212 pass.set_bind_group(0, &self.uniform_bind_group, &[]);
1213 pass.set_vertex_buffer(0, self.signed_quad_vbuf.slice(..));
1214 pass.set_vertex_buffer(1, self.path_seg_ibuf.slice(start_byte..end_byte));
1215 pass.set_stencil_reference(stencil_ref);
1216 pass.draw(0..6, 0..inst_count);
1217 }
1218 HardwareDrawOpKind::Text => {
1219 let stride = std::mem::size_of::<strata_gpu_path::GpuGlyphInstance>();
1220 let start_byte = (op.start * stride) as u64;
1221 let end_byte = (op.end * stride) as u64;
1222 if end_byte as usize > slug_inst_bytes.len() {
1223 continue;
1224 }
1225 let pipe = if active_layers > 0 {
1226 self.slug_stenciled[active_layers - 1]
1227 .as_ref()
1228 .unwrap_or(&self.slug_pipeline)
1229 } else {
1230 &self.slug_pipeline
1231 };
1232 pass.set_pipeline(pipe);
1233 pass.set_bind_group(0, &self.slug_bind_group, &[]);
1234 pass.set_vertex_buffer(0, self.unit_quad_vbuf.slice(..));
1235 pass.set_vertex_buffer(1, self.slug_inst_ibuf.slice(start_byte..end_byte));
1236 pass.set_stencil_reference(stencil_ref);
1237 pass.draw(0..6, 0..inst_count);
1238 }
1239 }
1240 }
1241 }
1242
1243 self.queue.submit(Some(encoder.finish()));
1244 }
1245
1246 #[allow(clippy::too_many_arguments)]
1249 pub fn render_display_list_to_view(
1250 &mut self,
1251 collector: &mut crate::gpu_pipeline::UnifiedGpuCollector,
1252 list: &crate::compositor::DisplayList,
1253 target_view: &wgpu::TextureView,
1254 target_width: u32,
1255 target_height: u32,
1256 dpr: f32,
1257 clear_color: Option<[f32; 4]>,
1258 damage: Option<Rect>,
1259 ) -> crate::gpu_pipeline::GpuBatchSummary {
1260 let frame = collector.collect_hardware_frame(list, damage);
1261 self.prepare_frame(&frame, collector.viewport_width, collector.viewport_height, dpr);
1262 self.render_batch_slice_to_view(
1263 &frame,
1264 0..frame.items.len(),
1265 target_view,
1266 target_width,
1267 target_height,
1268 collector.viewport_width,
1269 collector.viewport_height,
1270 clear_color,
1271 damage,
1272 );
1273 frame.summary
1274 }
1275
1276 #[allow(clippy::too_many_arguments)]
1279 pub fn render_display_list_offscreen(
1280 &mut self,
1281 collector: &mut crate::gpu_pipeline::UnifiedGpuCollector,
1282 list: &crate::compositor::DisplayList,
1283 width: u32,
1284 height: u32,
1285 dpr: f32,
1286 clear_color: [f32; 4],
1287 damage: Option<Rect>,
1288 readback: bool,
1289 ) -> Result<(crate::gpu_pipeline::GpuBatchSummary, Vec<u8>), String> {
1290 let w = width.max(1);
1291 let h = height.max(1);
1292 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1293 let unpadded = w * 4;
1294 let padded = unpadded.div_ceil(align) * align;
1295
1296 let recreate = self
1297 .offscreen
1298 .as_ref()
1299 .is_none_or(|o| o.width != w || o.height != h || o.format != self.color_format);
1300 if recreate {
1301 let color = self.device.create_texture(&wgpu::TextureDescriptor {
1302 label: Some("strata_2d_offscreen_color"),
1303 size: wgpu::Extent3d {
1304 width: w,
1305 height: h,
1306 depth_or_array_layers: 1,
1307 },
1308 mip_level_count: 1,
1309 sample_count: 1,
1310 dimension: wgpu::TextureDimension::D2,
1311 format: self.color_format,
1312 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
1313 view_formats: &[],
1314 });
1315 let view = color.create_view(&Default::default());
1316 let rb = self.device.create_buffer(&wgpu::BufferDescriptor {
1317 label: Some("strata_2d_offscreen_readback"),
1318 size: (padded * h) as u64,
1319 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1320 mapped_at_creation: false,
1321 });
1322 self.offscreen = Some(Offscreen2DTarget {
1323 width: w,
1324 height: h,
1325 format: self.color_format,
1326 color,
1327 view,
1328 readback: rb,
1329 padded_bytes_per_row: padded,
1330 });
1331 }
1332
1333 let target_view = self.offscreen.as_ref().unwrap().view.clone();
1334 let summary = self.render_display_list_to_view(
1335 collector,
1336 list,
1337 &target_view,
1338 w,
1339 h,
1340 dpr,
1341 Some(clear_color),
1342 damage,
1343 );
1344
1345 if !readback {
1346 self.device.poll(wgpu::Maintain::Wait);
1347 return Ok((summary, Vec::new()));
1348 }
1349
1350 let off = self.offscreen.as_ref().unwrap();
1351 let mut enc = self
1352 .device
1353 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1354 label: Some("strata_2d_readback_encoder"),
1355 });
1356 enc.copy_texture_to_buffer(
1357 wgpu::TexelCopyTextureInfo {
1358 texture: &off.color,
1359 mip_level: 0,
1360 origin: wgpu::Origin3d::ZERO,
1361 aspect: wgpu::TextureAspect::All,
1362 },
1363 wgpu::TexelCopyBufferInfo {
1364 buffer: &off.readback,
1365 layout: wgpu::TexelCopyBufferLayout {
1366 offset: 0,
1367 bytes_per_row: Some(off.padded_bytes_per_row),
1368 rows_per_image: Some(h),
1369 },
1370 },
1371 wgpu::Extent3d {
1372 width: w,
1373 height: h,
1374 depth_or_array_layers: 1,
1375 },
1376 );
1377 self.queue.submit(Some(enc.finish()));
1378
1379 let slice = off.readback.slice(..);
1380 let (tx, rx) = std::sync::mpsc::channel();
1381 slice.map_async(wgpu::MapMode::Read, move |res| {
1382 let _ = tx.send(res);
1383 });
1384 self.device.poll(wgpu::Maintain::Wait);
1385 rx.recv()
1386 .map_err(|e| format!("2d readback recv error: {e}"))?
1387 .map_err(|e| format!("2d readback map error: {e:?}"))?;
1388
1389 let data = slice.get_mapped_range();
1390 let mut out = vec![0u8; (w * h * 4) as usize];
1391 let row_len = w as usize * 4;
1392 for row in 0..h as usize {
1393 let src_start = row * off.padded_bytes_per_row as usize;
1394 let dst_start = row * row_len;
1395 out[dst_start..dst_start + row_len]
1396 .copy_from_slice(&data[src_start..src_start + row_len]);
1397 }
1398 drop(data);
1399 off.readback.unmap();
1400 Ok((summary, out))
1401 }
1402}