Skip to main content

repose_render_wgpu/
lib.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3#[cfg(feature = "winit-surface")]
4use std::sync::Arc;
5#[cfg(feature = "winit-surface")]
6use std::panic::{AssertUnwindSafe, catch_unwind};
7use std::ops::{Deref, DerefMut};
8
9use repose_core::color::{ChromaSiting, ColorInfo, PixelFormat};
10use repose_core::request_frame;
11use repose_core::{
12    Brush, FontStyle, GlyphRasterConfig, RenderBackend, Scene, SceneNode, StrokeCap, Transform,
13};
14use wgpu::Instance;
15
16mod slug;
17
18#[derive(Clone)]
19struct UploadRing {
20    buf: wgpu::Buffer,
21    cap: u64,
22    head: u64,
23}
24
25impl UploadRing {
26    fn new(device: &wgpu::Device, label: &str, cap: u64) -> Self {
27        let buf = device.create_buffer(&wgpu::BufferDescriptor {
28            label: Some(label),
29            size: cap,
30            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
31            mapped_at_creation: false,
32        });
33        Self { buf, cap, head: 0 }
34    }
35
36    fn reset(&mut self) {
37        self.head = 0;
38    }
39
40    fn grow_to_fit(&mut self, device: &wgpu::Device, needed: u64) {
41        let start = (self.head + 3) & !3;
42        if start + needed <= self.cap {
43            return;
44        }
45        let new_cap = (start + needed).next_power_of_two();
46        self.buf = device.create_buffer(&wgpu::BufferDescriptor {
47            label: Some("upload ring (grown)"),
48            size: new_cap,
49            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
50            mapped_at_creation: false,
51        });
52        self.cap = new_cap;
53    }
54
55    fn alloc_write(&mut self, queue: &wgpu::Queue, bytes: &[u8]) -> (u64, u64) {
56        let len = bytes.len() as u64;
57        let start = (self.head + 3) & !3; // align to 4
58        let end = start + len;
59        assert!(end <= self.cap, "ring overflow - call grow_to_fit first");
60        queue.write_buffer(&self.buf, start, bytes);
61        self.head = end;
62        (start, len)
63    }
64}
65
66struct InstancedPipe<I: bytemuck::Pod> {
67    ring: UploadRing,
68    _marker: std::marker::PhantomData<I>,
69}
70
71impl<I: bytemuck::Pod> InstancedPipe<I> {
72    fn new(ring: UploadRing) -> Self {
73        Self {
74            ring,
75            _marker: std::marker::PhantomData,
76        }
77    }
78
79    fn upload(
80        &mut self,
81        device: &wgpu::Device,
82        queue: &wgpu::Queue,
83        data: &[I],
84    ) -> Option<(u64, u32)> {
85        if data.is_empty() {
86            return None;
87        }
88        let bytes = bytemuck::cast_slice(data);
89        self.ring.grow_to_fit(device, bytes.len() as u64);
90        let (off, wrote) = self.ring.alloc_write(queue, bytes);
91        debug_assert_eq!(wrote as usize, bytes.len());
92        Some((off, data.len() as u32))
93    }
94
95    fn reset(&mut self) {
96        self.ring.reset();
97    }
98}
99
100#[repr(C)]
101#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
102struct Globals {
103    ndc_to_px: [f32; 2],
104    _pad: [f32; 2],
105}
106
107pub struct WgpuSceneRenderer {
108    pub device: wgpu::Device,
109    pub queue: wgpu::Queue,
110    pub output_format: wgpu::TextureFormat,
111    pub output_width: u32,
112    pub output_height: u32,
113
114    // Render pipelines. Two sets: one for the MSAA surface pass, one for
115    // graphics-layer render-to-texture passes (sample_count = 1).
116    surface_pipes: Pipelines,
117    layer_pipes: Pipelines,
118
119    // Instanced draw rings
120    rects: InstancedPipe<RectInstance>,
121    borders: InstancedPipe<BorderInstance>,
122    ellipses: InstancedPipe<EllipseInstance>,
123    ellipse_borders: InstancedPipe<EllipseBorderInstance>,
124    arcs: InstancedPipe<ArcInstance>,
125    glyph_mask: InstancedPipe<GlyphInstance>,
126    glyph_color: InstancedPipe<GlyphInstance>,
127
128    // Image bind layouts and shared sampler
129    image_bind_layout_rgba: wgpu::BindGroupLayout,
130    image_bind_layout_nv12: wgpu::BindGroupLayout,
131    image_sampler: wgpu::Sampler,
132
133    // Blur composite ring (for graphics-layer drop shadows)
134    blur_ring: UploadRing,
135
136    text_bind_layout: wgpu::BindGroupLayout,
137
138    // Stencil clip ring
139    clip_ring: UploadRing,
140
141    // Tessellated vector glyph pipeline (always enabled)
142    slug_enabled: bool,
143    slug_ring: UploadRing,
144    slug_cache: slug::GlyphSlugCache,
145
146    // Instanced NV12 ring
147    nv12: InstancedPipe<Nv12Instance>,
148
149    msaa_samples: u32,
150
151    // Depth-stencil target
152    depth_stencil_tex: wgpu::Texture,
153    depth_stencil_view: wgpu::TextureView,
154
155    // Optional MSAA color target
156    msaa_tex: Option<wgpu::Texture>,
157    msaa_view: Option<wgpu::TextureView>,
158
159    globals_layout: wgpu::BindGroupLayout,
160    globals_buf: wgpu::Buffer,
161    globals_bind: wgpu::BindGroup,
162
163    // Glyph atlas
164    atlas_mask: AtlasA8,
165    atlas_color: AtlasRGBA,
166
167    // Image management
168    next_image_handle: u64,
169    images: HashMap<u64, ImageTex>,
170
171    // Eviction stats
172    frame_index: u64,
173    image_bytes_total: u64,
174    image_evict_after_frames: u64,
175    image_budget_bytes: u64,
176
177    // Graphics layer pool. Maps `SceneNode::BeginLayer::layer_id` to a
178    // cached offscreen render target.
179    layer_pool: HashMap<u32, LayerTarget>,
180
181    // Linear working-space mode (default off -> fast playback path).
182    // When enabled, the scene is rendered into an Rgba16Float intermediate
183    // texture, then a final full-screen pass applies the display OETF.
184    working_space: bool,
185    ws_tex: Option<wgpu::Texture>,
186    ws_view: Option<wgpu::TextureView>,
187    ws_bind: Option<wgpu::BindGroup>,
188    display_pipeline: Option<wgpu::RenderPipeline>,
189    display_layout: Option<wgpu::BindGroupLayout>,
190}
191
192pub struct WgpuSurfaceBackend {
193    pub surface: Option<wgpu::Surface<'static>>,
194    pub surface_config: Option<wgpu::SurfaceConfiguration>,
195    pub renderer: WgpuSceneRenderer,
196}
197
198impl std::ops::Deref for WgpuSurfaceBackend {
199    type Target = WgpuSceneRenderer;
200    fn deref(&self) -> &Self::Target { &self.renderer }
201}
202impl std::ops::DerefMut for WgpuSurfaceBackend {
203    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.renderer }
204}
205
206#[cfg(feature = "winit-surface")]
207pub type WgpuBackend = WgpuSurfaceBackend;
208
209impl Drop for WgpuSceneRenderer {
210    fn drop(&mut self) {
211        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
212    }
213}
214
215#[derive(Clone)]
216struct LayerTarget {
217    texture: wgpu::Texture,
218    view: wgpu::TextureView,
219    bind: wgpu::BindGroup,
220    depth_stencil_tex: wgpu::Texture,
221    depth_stencil_view: wgpu::TextureView,
222    width: u32,
223    height: u32,
224    rect_px: (f32, f32, f32, f32),
225}
226
227/// Identifies which render target a `Pass` draws into.
228#[derive(Clone, Copy)]
229enum PassTarget {
230    Surface,
231    Layer(u32),
232}
233
234/// A bundle of render pipelines for a single sample-count target. Created
235/// twice: once with `sample_count = msaa_samples` for the surface pass, and
236/// once with `sample_count = 1` for graphics-layer render-to-texture passes
237/// (where MSAA is wasted).
238struct Pipelines {
239    rects: wgpu::RenderPipeline,
240    borders: wgpu::RenderPipeline,
241    ellipses: wgpu::RenderPipeline,
242    ellipse_borders: wgpu::RenderPipeline,
243    arcs: wgpu::RenderPipeline,
244    text_mask: wgpu::RenderPipeline,
245    text_color: wgpu::RenderPipeline,
246    image_rgba: wgpu::RenderPipeline,
247    image_nv12: wgpu::RenderPipeline,
248    blur: wgpu::RenderPipeline,
249    blur_content: wgpu::RenderPipeline,
250    clip_a2c: wgpu::RenderPipeline,
251    clip_bin: wgpu::RenderPipeline,
252    clip_dec: wgpu::RenderPipeline,
253    slug: Option<wgpu::RenderPipeline>,
254}
255
256impl Pipelines {
257    fn create(
258        device: &wgpu::Device,
259        format: wgpu::TextureFormat,
260        sample_count: u32,
261        globals_layout: &wgpu::BindGroupLayout,
262        text_bind_layout: &wgpu::BindGroupLayout,
263        image_bind_layout_nv12: &wgpu::BindGroupLayout,
264        clip_pipeline_layout: &wgpu::PipelineLayout,
265        stencil_for_content: &wgpu::DepthStencilState,
266        stencil_for_clip_inc: &wgpu::DepthStencilState,
267        stencil_for_clip_dec: &wgpu::DepthStencilState,
268        clip_color_target: &wgpu::ColorTargetState,
269        clip_vertex_layout: &wgpu::VertexBufferLayout,
270    ) -> Self {
271        let msaa_state = wgpu::MultisampleState {
272            count: sample_count,
273            mask: !0,
274            alpha_to_coverage_enabled: false,
275        };
276
277        macro_rules! make_content_pipeline {
278            ($name:ident, $shader:literal, $inst_type:ty, $attrs:expr) => {
279                let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
280                    label: Some(concat!($shader, ".wgsl")),
281                    source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(concat!(
282                        "shaders/", $shader, ".wgsl"
283                    )))),
284                });
285                let pipeline_layout =
286                    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
287                        label: Some(concat!($shader, " pipeline layout")),
288                        bind_group_layouts: &[Some(globals_layout)],
289                        immediate_size: 0,
290                    });
291                let $name = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
292                    label: Some(concat!($shader, " pipeline")),
293                    layout: Some(&pipeline_layout),
294                    vertex: wgpu::VertexState {
295                        module: &shader_module,
296                        entry_point: Some("vs_main"),
297                        buffers: &[Some(wgpu::VertexBufferLayout {
298                            array_stride: std::mem::size_of::<$inst_type>() as u64,
299                            step_mode: wgpu::VertexStepMode::Instance,
300                            attributes: $attrs,
301                        })],
302                        compilation_options: wgpu::PipelineCompilationOptions::default(),
303                    },
304                    fragment: Some(wgpu::FragmentState {
305                        module: &shader_module,
306                        entry_point: Some("fs_main"),
307                        targets: &[Some(wgpu::ColorTargetState {
308                            format,
309                            blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
310                            write_mask: wgpu::ColorWrites::ALL,
311                        })],
312                        compilation_options: wgpu::PipelineCompilationOptions::default(),
313                    }),
314                    primitive: wgpu::PrimitiveState::default(),
315                    depth_stencil: Some(stencil_for_content.clone()),
316                    multisample: msaa_state,
317                    multiview_mask: None,
318                    cache: None,
319                });
320            };
321        }
322
323        let rect_attrs: &[wgpu::VertexAttribute] = &[
324            wgpu::VertexAttribute {
325                shader_location: 0,
326                offset: 0,
327                format: wgpu::VertexFormat::Float32x4,
328            },
329            wgpu::VertexAttribute {
330                shader_location: 1,
331                offset: 16,
332                format: wgpu::VertexFormat::Float32x4,
333            },
334            wgpu::VertexAttribute {
335                shader_location: 2,
336                offset: 32,
337                format: wgpu::VertexFormat::Uint32,
338            },
339            wgpu::VertexAttribute {
340                shader_location: 3,
341                offset: 48,
342                format: wgpu::VertexFormat::Float32x4,
343            },
344            wgpu::VertexAttribute {
345                shader_location: 4,
346                offset: 64,
347                format: wgpu::VertexFormat::Float32x4,
348            },
349            wgpu::VertexAttribute {
350                shader_location: 5,
351                offset: 80,
352                format: wgpu::VertexFormat::Float32x2,
353            },
354            wgpu::VertexAttribute {
355                shader_location: 6,
356                offset: 88,
357                format: wgpu::VertexFormat::Float32x2,
358            },
359            wgpu::VertexAttribute {
360                shader_location: 7,
361                offset: 96,
362                format: wgpu::VertexFormat::Float32x2,
363            },
364        ];
365        let border_attrs: &[wgpu::VertexAttribute] = &[
366            wgpu::VertexAttribute {
367                shader_location: 0,
368                offset: 0,
369                format: wgpu::VertexFormat::Float32x4,
370            },
371            wgpu::VertexAttribute {
372                shader_location: 1,
373                offset: 16,
374                format: wgpu::VertexFormat::Float32x4,
375            },
376            wgpu::VertexAttribute {
377                shader_location: 2,
378                offset: 32,
379                format: wgpu::VertexFormat::Float32,
380            },
381            wgpu::VertexAttribute {
382                shader_location: 3,
383                offset: 36,
384                format: wgpu::VertexFormat::Float32x4,
385            },
386            wgpu::VertexAttribute {
387                shader_location: 4,
388                offset: 52,
389                format: wgpu::VertexFormat::Float32x2,
390            },
391        ];
392        let ellipse_attrs: &[wgpu::VertexAttribute] = &[
393            wgpu::VertexAttribute {
394                shader_location: 0,
395                offset: 0,
396                format: wgpu::VertexFormat::Float32x4,
397            },
398            wgpu::VertexAttribute {
399                shader_location: 1,
400                offset: 16,
401                format: wgpu::VertexFormat::Float32x4,
402            },
403            wgpu::VertexAttribute {
404                shader_location: 2,
405                offset: 32,
406                format: wgpu::VertexFormat::Float32x2,
407            },
408        ];
409        let ellipse_border_attrs: &[wgpu::VertexAttribute] = &[
410            wgpu::VertexAttribute {
411                shader_location: 0,
412                offset: 0,
413                format: wgpu::VertexFormat::Float32x4,
414            },
415            wgpu::VertexAttribute {
416                shader_location: 1,
417                offset: 16,
418                format: wgpu::VertexFormat::Float32,
419            },
420            wgpu::VertexAttribute {
421                shader_location: 2,
422                offset: 20,
423                format: wgpu::VertexFormat::Float32,
424            },
425            wgpu::VertexAttribute {
426                shader_location: 3,
427                offset: 24,
428                format: wgpu::VertexFormat::Float32x4,
429            },
430            wgpu::VertexAttribute {
431                shader_location: 4,
432                offset: 40,
433                format: wgpu::VertexFormat::Float32x2,
434            },
435        ];
436
437        make_content_pipeline!(rects, "rect", RectInstance, rect_attrs);
438        make_content_pipeline!(borders, "border", BorderInstance, border_attrs);
439        make_content_pipeline!(ellipses, "ellipse", EllipseInstance, ellipse_attrs);
440        make_content_pipeline!(
441            ellipse_borders,
442            "ellipse_border",
443            EllipseBorderInstance,
444            ellipse_border_attrs
445        );
446
447        let arc_attrs: &[wgpu::VertexAttribute] = &[
448            wgpu::VertexAttribute {
449                shader_location: 0,
450                offset: 0,
451                format: wgpu::VertexFormat::Float32x4,
452            },
453            wgpu::VertexAttribute {
454                shader_location: 1,
455                offset: 16,
456                format: wgpu::VertexFormat::Float32,
457            },
458            wgpu::VertexAttribute {
459                shader_location: 2,
460                offset: 20,
461                format: wgpu::VertexFormat::Float32,
462            },
463            wgpu::VertexAttribute {
464                shader_location: 3,
465                offset: 24,
466                format: wgpu::VertexFormat::Float32,
467            },
468            wgpu::VertexAttribute {
469                shader_location: 4,
470                offset: 28,
471                format: wgpu::VertexFormat::Float32,
472            },
473            wgpu::VertexAttribute {
474                shader_location: 5,
475                offset: 32,
476                format: wgpu::VertexFormat::Float32x4,
477            },
478            wgpu::VertexAttribute {
479                shader_location: 6,
480                offset: 48,
481                format: wgpu::VertexFormat::Float32x2,
482            },
483            wgpu::VertexAttribute {
484                shader_location: 7,
485                offset: 56,
486                format: wgpu::VertexFormat::Float32,
487            },
488        ];
489
490        make_content_pipeline!(arcs, "arc", ArcInstance, arc_attrs);
491
492        // Text (mask)
493        let text_mask_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
494            label: Some("text.wgsl"),
495            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/text.wgsl"))),
496        });
497        // Text (color)
498        let text_color_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
499            label: Some("text_color.wgsl"),
500            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
501                "shaders/text_color.wgsl"
502            ))),
503        });
504        let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
505            label: Some("text pipeline layout"),
506            bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
507            immediate_size: 0,
508        });
509        let glyph_vertex = wgpu::VertexBufferLayout {
510            array_stride: std::mem::size_of::<GlyphInstance>() as u64,
511            step_mode: wgpu::VertexStepMode::Instance,
512            attributes: &[
513                wgpu::VertexAttribute {
514                    shader_location: 0,
515                    offset: 0,
516                    format: wgpu::VertexFormat::Float32x4,
517                },
518                wgpu::VertexAttribute {
519                    shader_location: 1,
520                    offset: 16,
521                    format: wgpu::VertexFormat::Float32x4,
522                },
523                wgpu::VertexAttribute {
524                    shader_location: 2,
525                    offset: 32,
526                    format: wgpu::VertexFormat::Float32x4,
527                },
528                wgpu::VertexAttribute {
529                    shader_location: 3,
530                    offset: 48,
531                    format: wgpu::VertexFormat::Float32x2,
532                },
533            ],
534        };
535        let text_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
536            label: Some("text pipeline (mask)"),
537            layout: Some(&text_pipeline_layout),
538            vertex: wgpu::VertexState {
539                module: &text_mask_shader,
540                entry_point: Some("vs_main"),
541                buffers: &[Some(glyph_vertex.clone())],
542                compilation_options: wgpu::PipelineCompilationOptions::default(),
543            },
544            fragment: Some(wgpu::FragmentState {
545                module: &text_mask_shader,
546                entry_point: Some("fs_main"),
547                targets: &[Some(wgpu::ColorTargetState {
548                    format,
549                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
550                    write_mask: wgpu::ColorWrites::ALL,
551                })],
552                compilation_options: wgpu::PipelineCompilationOptions::default(),
553            }),
554            primitive: wgpu::PrimitiveState::default(),
555            depth_stencil: Some(stencil_for_content.clone()),
556            multisample: msaa_state,
557            multiview_mask: None,
558            cache: None,
559        });
560        let text_color = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
561            label: Some("text pipeline (color)"),
562            layout: Some(&text_pipeline_layout),
563            vertex: wgpu::VertexState {
564                module: &text_color_shader,
565                entry_point: Some("vs_main"),
566                buffers: &[Some(glyph_vertex)],
567                compilation_options: wgpu::PipelineCompilationOptions::default(),
568            },
569            fragment: Some(wgpu::FragmentState {
570                module: &text_color_shader,
571                entry_point: Some("fs_main"),
572                targets: &[Some(wgpu::ColorTargetState {
573                    format,
574                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
575                    write_mask: wgpu::ColorWrites::ALL,
576                })],
577                compilation_options: wgpu::PipelineCompilationOptions::default(),
578            }),
579            primitive: wgpu::PrimitiveState::default(),
580            depth_stencil: Some(stencil_for_content.clone()),
581            multisample: msaa_state,
582            multiview_mask: None,
583            cache: None,
584        });
585        // image_rgba reuses the text color pipeline (same vertex/bindings).
586        let image_rgba = text_color.clone();
587
588        // Blur composite pipeline (graphics-layer drop shadow)
589        let blur_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
590            label: Some("blur_shadow.wgsl"),
591            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
592                "shaders/blur_shadow.wgsl"
593            ))),
594        });
595        let blur_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
596            label: Some("blur pipeline layout"),
597            bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
598            immediate_size: 0,
599        });
600        let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
601            label: Some("blur pipeline"),
602            layout: Some(&blur_pipeline_layout),
603            vertex: wgpu::VertexState {
604                module: &blur_shader,
605                entry_point: Some("vs_main"),
606                buffers: &[Some(wgpu::VertexBufferLayout {
607                    array_stride: std::mem::size_of::<BlurInstance>() as u64,
608                    step_mode: wgpu::VertexStepMode::Instance,
609                    attributes: &[
610                        wgpu::VertexAttribute {
611                            shader_location: 0,
612                            offset: 0,
613                            format: wgpu::VertexFormat::Float32x4,
614                        },
615                        wgpu::VertexAttribute {
616                            shader_location: 1,
617                            offset: 16,
618                            format: wgpu::VertexFormat::Float32x4,
619                        },
620                        wgpu::VertexAttribute {
621                            shader_location: 2,
622                            offset: 32,
623                            format: wgpu::VertexFormat::Float32x4,
624                        },
625                        wgpu::VertexAttribute {
626                            shader_location: 3,
627                            offset: 48,
628                            format: wgpu::VertexFormat::Float32x2,
629                        },
630                        wgpu::VertexAttribute {
631                            shader_location: 4,
632                            offset: 56,
633                            format: wgpu::VertexFormat::Float32x2,
634                        },
635                    ],
636                })],
637                compilation_options: wgpu::PipelineCompilationOptions::default(),
638            },
639            fragment: Some(wgpu::FragmentState {
640                module: &blur_shader,
641                entry_point: Some("fs_main"),
642                targets: &[Some(wgpu::ColorTargetState {
643                    format,
644                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
645                    write_mask: wgpu::ColorWrites::ALL,
646                })],
647                compilation_options: wgpu::PipelineCompilationOptions::default(),
648            }),
649            primitive: wgpu::PrimitiveState::default(),
650            depth_stencil: Some(stencil_for_content.clone()),
651            multisample: msaa_state,
652            multiview_mask: None,
653            cache: None,
654        });
655
656        // Content blur pipeline (full RGBA gaussian blur)
657        let blur_content_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
658            label: Some("blur_content.wgsl"),
659            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
660                "shaders/blur_content.wgsl"
661            ))),
662        });
663        let blur_content = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
664            label: Some("blur content pipeline"),
665            layout: Some(&blur_pipeline_layout),
666            vertex: wgpu::VertexState {
667                module: &blur_content_shader,
668                entry_point: Some("vs_main"),
669                buffers: &[Some(wgpu::VertexBufferLayout {
670                    array_stride: std::mem::size_of::<BlurInstance>() as u64,
671                    step_mode: wgpu::VertexStepMode::Instance,
672                    attributes: &[
673                        wgpu::VertexAttribute {
674                            shader_location: 0,
675                            offset: 0,
676                            format: wgpu::VertexFormat::Float32x4,
677                        },
678                        wgpu::VertexAttribute {
679                            shader_location: 1,
680                            offset: 16,
681                            format: wgpu::VertexFormat::Float32x4,
682                        },
683                        wgpu::VertexAttribute {
684                            shader_location: 2,
685                            offset: 32,
686                            format: wgpu::VertexFormat::Float32x4,
687                        },
688                        wgpu::VertexAttribute {
689                            shader_location: 3,
690                            offset: 48,
691                            format: wgpu::VertexFormat::Float32x2,
692                        },
693                        wgpu::VertexAttribute {
694                            shader_location: 4,
695                            offset: 56,
696                            format: wgpu::VertexFormat::Float32x2,
697                        },
698                    ],
699                })],
700                compilation_options: wgpu::PipelineCompilationOptions::default(),
701            },
702            fragment: Some(wgpu::FragmentState {
703                module: &blur_content_shader,
704                entry_point: Some("fs_main"),
705                targets: &[Some(wgpu::ColorTargetState {
706                    format,
707                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
708                    write_mask: wgpu::ColorWrites::ALL,
709                })],
710                compilation_options: wgpu::PipelineCompilationOptions::default(),
711            }),
712            primitive: wgpu::PrimitiveState::default(),
713            depth_stencil: Some(stencil_for_content.clone()),
714            multisample: msaa_state,
715            multiview_mask: None,
716            cache: None,
717        });
718
719        // NV12 Image Pipeline
720        let image_nv12_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
721            label: Some("image_nv12.wgsl"),
722            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
723                "shaders/image_nv12.wgsl"
724            ))),
725        });
726        let image_nv12_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
727            label: Some("image nv12 pipeline layout"),
728            bind_group_layouts: &[Some(globals_layout), Some(image_bind_layout_nv12)],
729            immediate_size: 0,
730        });
731        let image_nv12 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
732            label: Some("image nv12 pipeline"),
733            layout: Some(&image_nv12_layout),
734            vertex: wgpu::VertexState {
735                module: &image_nv12_shader,
736                entry_point: Some("vs_main"),
737                buffers: &[Some(wgpu::VertexBufferLayout {
738                    array_stride: std::mem::size_of::<Nv12Instance>() as u64,
739                    step_mode: wgpu::VertexStepMode::Instance,
740                    attributes: &[
741                        wgpu::VertexAttribute {
742                            shader_location: 0,
743                            offset: 0,
744                            format: wgpu::VertexFormat::Float32x4,
745                        },
746                        wgpu::VertexAttribute {
747                            shader_location: 1,
748                            offset: 16,
749                            format: wgpu::VertexFormat::Float32x4,
750                        },
751                        wgpu::VertexAttribute {
752                            shader_location: 2,
753                            offset: 32,
754                            format: wgpu::VertexFormat::Float32x4,
755                        },
756                        wgpu::VertexAttribute {
757                            shader_location: 3,
758                            offset: 48,
759                            format: wgpu::VertexFormat::Float32,
760                        },
761                        wgpu::VertexAttribute {
762                            shader_location: 4,
763                            offset: 52,
764                            format: wgpu::VertexFormat::Float32x2,
765                        },
766                    ],
767                })],
768                compilation_options: wgpu::PipelineCompilationOptions::default(),
769            },
770            fragment: Some(wgpu::FragmentState {
771                module: &image_nv12_shader,
772                entry_point: Some("fs_main"),
773                targets: &[Some(wgpu::ColorTargetState {
774                    format,
775                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
776                    write_mask: wgpu::ColorWrites::ALL,
777                })],
778                compilation_options: wgpu::PipelineCompilationOptions::default(),
779            }),
780            primitive: wgpu::PrimitiveState::default(),
781            depth_stencil: Some(stencil_for_content.clone()),
782            multisample: msaa_state,
783            multiview_mask: None,
784            cache: None,
785        });
786
787        // Clipping
788        let clip_shader_a2c = device.create_shader_module(wgpu::ShaderModuleDescriptor {
789            label: Some("clip_round_rect_a2c.wgsl"),
790            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
791                "shaders/clip_round_rect_a2c.wgsl"
792            ))),
793        });
794        let clip_shader_bin = device.create_shader_module(wgpu::ShaderModuleDescriptor {
795            label: Some("clip_round_rect_bin.wgsl"),
796            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
797                "shaders/clip_round_rect_bin.wgsl"
798            ))),
799        });
800        let clip_a2c = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
801            label: Some("clip pipeline (a2c)"),
802            layout: Some(clip_pipeline_layout),
803            vertex: wgpu::VertexState {
804                module: &clip_shader_a2c,
805                entry_point: Some("vs_main"),
806                buffers: &[Some(clip_vertex_layout.clone())],
807                compilation_options: wgpu::PipelineCompilationOptions::default(),
808            },
809            fragment: Some(wgpu::FragmentState {
810                module: &clip_shader_a2c,
811                entry_point: Some("fs_main"),
812                targets: &[Some(clip_color_target.clone())],
813                compilation_options: wgpu::PipelineCompilationOptions::default(),
814            }),
815            primitive: wgpu::PrimitiveState::default(),
816            depth_stencil: Some(stencil_for_clip_inc.clone()),
817            multisample: wgpu::MultisampleState {
818                count: sample_count,
819                mask: !0,
820                alpha_to_coverage_enabled: sample_count > 1,
821            },
822            multiview_mask: None,
823            cache: None,
824        });
825        let clip_bin = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
826            label: Some("clip pipeline (bin)"),
827            layout: Some(clip_pipeline_layout),
828            vertex: wgpu::VertexState {
829                module: &clip_shader_bin,
830                entry_point: Some("vs_main"),
831                buffers: &[Some(clip_vertex_layout.clone())],
832                compilation_options: wgpu::PipelineCompilationOptions::default(),
833            },
834            fragment: Some(wgpu::FragmentState {
835                module: &clip_shader_bin,
836                entry_point: Some("fs_main"),
837                targets: &[Some(clip_color_target.clone())],
838                compilation_options: wgpu::PipelineCompilationOptions::default(),
839            }),
840            primitive: wgpu::PrimitiveState::default(),
841            depth_stencil: Some(stencil_for_clip_inc.clone()),
842            multisample: wgpu::MultisampleState {
843                count: sample_count,
844                mask: !0,
845                alpha_to_coverage_enabled: false,
846            },
847            multiview_mask: None,
848            cache: None,
849        });
850        let clip_dec = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
851            label: Some("clip pipeline (dec)"),
852            layout: Some(clip_pipeline_layout),
853            vertex: wgpu::VertexState {
854                module: &clip_shader_bin,
855                entry_point: Some("vs_main"),
856                buffers: &[Some(clip_vertex_layout.clone())],
857                compilation_options: wgpu::PipelineCompilationOptions::default(),
858            },
859            fragment: Some(wgpu::FragmentState {
860                module: &clip_shader_bin,
861                entry_point: Some("fs_main"),
862                targets: &[Some(clip_color_target.clone())],
863                compilation_options: wgpu::PipelineCompilationOptions::default(),
864            }),
865            primitive: wgpu::PrimitiveState::default(),
866            depth_stencil: Some(stencil_for_clip_dec.clone()),
867            multisample: wgpu::MultisampleState {
868                count: sample_count,
869                mask: !0,
870                alpha_to_coverage_enabled: false,
871            },
872            multiview_mask: None,
873            cache: None,
874        });
875
876        let slug = Some(slug::create_pipeline(
877            device,
878            format,
879            sample_count,
880            stencil_for_content,
881        ));
882
883        Self {
884            rects,
885            borders,
886            ellipses,
887            ellipse_borders,
888            arcs,
889            text_mask,
890            text_color,
891            image_rgba,
892            image_nv12,
893            blur,
894            blur_content,
895            clip_a2c,
896            clip_bin,
897            clip_dec,
898            slug,
899        }
900    }
901}
902
903/// A segment of the frame that draws into a single render target.
904struct Pass {
905    target: PassTarget,
906    /// The initial scissor to apply to the rpass when it is opened.
907    initial_scissor: (u32, u32, u32, u32),
908    /// `None` means `LoadOp::Load` (resume existing content);
909    /// `Some(c)` means `LoadOp::Clear(c)`.
910    clear_color: Option<[f32; 4]>,
911    cmds: Vec<Cmd>,
912}
913
914#[allow(non_snake_case)]
915enum Cmd {
916    ClipPush {
917        off: u64,
918        cnt: u32,
919        scissor: (u32, u32, u32, u32),
920        difference: bool,
921        rounded: bool,
922    },
923    ClipPop {
924        scissor: (u32, u32, u32, u32),
925    },
926    Rect {
927        off: u64,
928        cnt: u32,
929    },
930    Border {
931        off: u64,
932        cnt: u32,
933    },
934    Ellipse {
935        off: u64,
936        cnt: u32,
937    },
938    EllipseBorder {
939        off: u64,
940        cnt: u32,
941    },
942    Arc {
943        off: u64,
944        cnt: u32,
945    },
946    GlyphsMask {
947        off: u64,
948        cnt: u32,
949    },
950    GlyphsColor {
951        off: u64,
952        cnt: u32,
953    },
954    GlyphsVector {
955        off: u64,
956        cnt: u32,
957    },
958    ImageRgba {
959        off: u64,
960        cnt: u32,
961        handle: u64,
962    },
963    ImageNv12 {
964        off: u64,
965        cnt: u32,
966        handle: u64,
967    },
968    PushTransform(Transform),
969    PopTransform,
970    /// Composite a previously-rendered graphics layer back into the
971    /// current target as a textured quad. The quad's vertex buffer
972    /// lives in `self.glyph_color.ring` (a `GlyphInstance`).
973    CompositeLayer {
974        off: u64,
975        cnt: u32,
976        layer_id: u32,
977        alpha: f32,
978    },
979    /// Composite a blurred drop shadow of a previously-rendered graphics
980    /// layer. The quad's vertex buffer lives in `self.blur_ring` (a
981    /// `BlurInstance`).
982    CompositeShadow {
983        off: u64,
984        cnt: u32,
985        layer_id: u32,
986    },
987    /// Apply gaussian blur to a layer and composite the blurred result.
988    /// Uses the `blur_content` pipeline (full RGBA blur).
989    CompositeBlur {
990        off: u64,
991        cnt: u32,
992        layer_id: u32,
993    },
994}
995
996enum ImageTex {
997    Rgba {
998        tex: wgpu::Texture,
999        view: wgpu::TextureView,
1000        bind: wgpu::BindGroup,
1001        w: u32,
1002        h: u32,
1003        format: wgpu::TextureFormat,
1004        last_used_frame: u64,
1005        bytes: u64,
1006    },
1007    Nv12 {
1008        tex_y: wgpu::Texture,
1009        view_y: wgpu::TextureView,
1010        tex_uv: wgpu::Texture,
1011        view_uv: wgpu::TextureView,
1012        bind: wgpu::BindGroup,
1013        yuv_buf: wgpu::Buffer,
1014        w: u32,
1015        h: u32,
1016        color_info: ColorInfo,
1017        last_used_frame: u64,
1018        bytes: u64,
1019    },
1020}
1021
1022struct AtlasA8 {
1023    tex: wgpu::Texture,
1024    view: wgpu::TextureView,
1025    sampler: wgpu::Sampler,
1026    size: u32,
1027    next_x: u32,
1028    next_y: u32,
1029    row_h: u32,
1030    map: HashMap<(repose_text::GlyphKey, u32), GlyphInfo>,
1031}
1032
1033struct AtlasRGBA {
1034    tex: wgpu::Texture,
1035    view: wgpu::TextureView,
1036    sampler: wgpu::Sampler,
1037    size: u32,
1038    next_x: u32,
1039    next_y: u32,
1040    row_h: u32,
1041    map: HashMap<(repose_text::GlyphKey, u32), GlyphInfo>,
1042}
1043
1044#[derive(Clone, Copy)]
1045struct GlyphInfo {
1046    u0: f32,
1047    v0: f32,
1048    u1: f32,
1049    v1: f32,
1050    w: f32,
1051    h: f32,
1052    bearing_x: f32,
1053    bearing_y: f32,
1054    advance: f32,
1055}
1056
1057#[repr(C)]
1058#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1059struct RectInstance {
1060    xywh: [f32; 4],
1061    radii: [f32; 4],
1062    brush_type: u32,
1063    _pad: [f32; 3],
1064    color0: [f32; 4],
1065    color1: [f32; 4],
1066    grad_start: [f32; 2],
1067    grad_end: [f32; 2],
1068    sin_cos: [f32; 2],
1069}
1070
1071#[repr(C)]
1072#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1073struct BorderInstance {
1074    xywh: [f32; 4],
1075    radii: [f32; 4],
1076    stroke: f32,
1077    color: [f32; 4],
1078    sin_cos: [f32; 2],
1079}
1080
1081#[repr(C)]
1082#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1083struct EllipseInstance {
1084    xywh: [f32; 4],
1085    color: [f32; 4],
1086    sin_cos: [f32; 2],
1087}
1088
1089#[repr(C)]
1090#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1091struct EllipseBorderInstance {
1092    xywh: [f32; 4],
1093    stroke: f32,
1094    pad: f32,
1095    color: [f32; 4],
1096    sin_cos: [f32; 2],
1097}
1098
1099#[repr(C)]
1100#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1101struct ArcInstance {
1102    xywh: [f32; 4],
1103    start_angle: f32,
1104    sweep_angle: f32,
1105    stroke: f32,
1106    pad: f32,
1107    color: [f32; 4],
1108    sin_cos: [f32; 2],
1109    cap: f32, // 0=Butt, 1=Round, 2=Square
1110}
1111
1112#[repr(C)]
1113#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1114struct GlyphInstance {
1115    xywh: [f32; 4],
1116    uv: [f32; 4],
1117    color: [f32; 4],
1118    sin_cos: [f32; 2],
1119}
1120
1121#[repr(C)]
1122#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1123struct BlurInstance {
1124    xywh: [f32; 4],
1125    uv: [f32; 4],
1126    color: [f32; 4],
1127    blur_uv: [f32; 2],
1128    sin_cos: [f32; 2],
1129}
1130
1131/// CPU-computed Y′CbCr → R′G′B′ transform uploaded as a uniform buffer.
1132/// Layout matches the WGSL `YuvTransform` struct (4 × vec4<f32>).
1133#[repr(C)]
1134#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1135struct YuvTransformRaw {
1136    row0: [f32; 4],
1137    row1: [f32; 4],
1138    row2: [f32; 4],
1139    b: [f32; 4],
1140}
1141
1142#[repr(C)]
1143#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1144struct Nv12Instance {
1145    xywh: [f32; 4],
1146    uv: [f32; 4],
1147    color: [f32; 4], // tint
1148    uv_x_offset: f32,
1149    sin_cos: [f32; 2],
1150    _pad: [f32; 1],
1151}
1152
1153#[repr(C)]
1154#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1155struct ClipInstance {
1156    xywh: [f32; 4],
1157    radii: [f32; 4],
1158    sin_cos: [f32; 2],
1159}
1160
1161fn swash_to_a8_coverage(content: repose_text::SwashContent, data: &[u8]) -> Option<Vec<u8>> {
1162    match content {
1163        repose_text::SwashContent::Mask => Some(data.to_vec()),
1164        repose_text::SwashContent::SubpixelMask => {
1165            let mut out = Vec::with_capacity(data.len() / 4);
1166            for px in data.chunks_exact(4) {
1167                let r = px[0];
1168                let g = px[1];
1169                let b = px[2];
1170                out.push(r.max(g).max(b));
1171            }
1172            Some(out)
1173        }
1174        repose_text::SwashContent::Color => None,
1175    }
1176}
1177
1178impl WgpuSceneRenderer {
1179    pub fn from_device(
1180        device: wgpu::Device,
1181        queue: wgpu::Queue,
1182        output_format: wgpu::TextureFormat,
1183        msaa_samples: u32,
1184    ) -> Self {
1185        let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1186            label: Some("globals layout"),
1187            entries: &[wgpu::BindGroupLayoutEntry {
1188                binding: 0,
1189                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
1190                ty: wgpu::BindingType::Buffer {
1191                    ty: wgpu::BufferBindingType::Uniform,
1192                    has_dynamic_offset: false,
1193                    min_binding_size: None,
1194                },
1195                count: None,
1196            }],
1197        });
1198
1199        let globals_buf = device.create_buffer(&wgpu::BufferDescriptor {
1200            label: Some("globals buf"),
1201            size: std::mem::size_of::<Globals>() as u64,
1202            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1203            mapped_at_creation: false,
1204        });
1205
1206        let globals_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
1207            label: Some("globals bind"),
1208            layout: &globals_layout,
1209            entries: &[wgpu::BindGroupEntry {
1210                binding: 0,
1211                resource: globals_buf.as_entire_binding(),
1212            }],
1213        });
1214
1215
1216        let ds_format = wgpu::TextureFormat::Depth24PlusStencil8;
1217
1218        let stencil_for_content = wgpu::DepthStencilState {
1219            format: ds_format,
1220            depth_write_enabled: Some(false),
1221            depth_compare: Some(wgpu::CompareFunction::Always),
1222            stencil: wgpu::StencilState {
1223                front: wgpu::StencilFaceState {
1224                    compare: wgpu::CompareFunction::LessEqual,
1225                    fail_op: wgpu::StencilOperation::Keep,
1226                    depth_fail_op: wgpu::StencilOperation::Keep,
1227                    pass_op: wgpu::StencilOperation::Keep,
1228                },
1229                back: wgpu::StencilFaceState {
1230                    compare: wgpu::CompareFunction::LessEqual,
1231                    fail_op: wgpu::StencilOperation::Keep,
1232                    depth_fail_op: wgpu::StencilOperation::Keep,
1233                    pass_op: wgpu::StencilOperation::Keep,
1234                },
1235                read_mask: 0xFF,
1236                write_mask: 0x00,
1237            },
1238            bias: wgpu::DepthBiasState::default(),
1239        };
1240
1241        let stencil_for_clip_inc = wgpu::DepthStencilState {
1242            format: ds_format,
1243            depth_write_enabled: Some(false),
1244            depth_compare: Some(wgpu::CompareFunction::Always),
1245            stencil: wgpu::StencilState {
1246                front: wgpu::StencilFaceState {
1247                    compare: wgpu::CompareFunction::Equal,
1248                    fail_op: wgpu::StencilOperation::Keep,
1249                    depth_fail_op: wgpu::StencilOperation::Keep,
1250                    pass_op: wgpu::StencilOperation::IncrementClamp,
1251                },
1252                back: wgpu::StencilFaceState {
1253                    compare: wgpu::CompareFunction::Equal,
1254                    fail_op: wgpu::StencilOperation::Keep,
1255                    depth_fail_op: wgpu::StencilOperation::Keep,
1256                    pass_op: wgpu::StencilOperation::IncrementClamp,
1257                },
1258                read_mask: 0xFF,
1259                write_mask: 0xFF,
1260            },
1261            bias: wgpu::DepthBiasState::default(),
1262        };
1263
1264        let stencil_for_clip_dec = wgpu::DepthStencilState {
1265            format: ds_format,
1266            depth_write_enabled: Some(false),
1267            depth_compare: Some(wgpu::CompareFunction::Always),
1268            stencil: wgpu::StencilState {
1269                front: wgpu::StencilFaceState {
1270                    compare: wgpu::CompareFunction::Equal,
1271                    fail_op: wgpu::StencilOperation::Keep,
1272                    depth_fail_op: wgpu::StencilOperation::Keep,
1273                    pass_op: wgpu::StencilOperation::DecrementClamp,
1274                },
1275                back: wgpu::StencilFaceState {
1276                    compare: wgpu::CompareFunction::Equal,
1277                    fail_op: wgpu::StencilOperation::Keep,
1278                    depth_fail_op: wgpu::StencilOperation::Keep,
1279                    pass_op: wgpu::StencilOperation::DecrementClamp,
1280                },
1281                read_mask: 0xFF,
1282                write_mask: 0xFF,
1283            },
1284            bias: wgpu::DepthBiasState::default(),
1285        };
1286
1287        let _multisample_state = wgpu::MultisampleState {
1288            count: msaa_samples,
1289            mask: !0,
1290            alpha_to_coverage_enabled: false,
1291        };
1292
1293        // PIPELINES
1294
1295        // Single shared sampler for images/text
1296        let image_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
1297            label: Some("image/text sampler"),
1298            address_mode_u: wgpu::AddressMode::ClampToEdge,
1299            address_mode_v: wgpu::AddressMode::ClampToEdge,
1300            mag_filter: wgpu::FilterMode::Linear,
1301            min_filter: wgpu::FilterMode::Linear,
1302            mipmap_filter: wgpu::MipmapFilterMode::Linear,
1303            ..Default::default()
1304        });
1305
1306        // Layout for Text / RGBA Images (Texture + Sampler)
1307        let text_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1308            label: Some("text/rgba bind layout"),
1309            entries: &[
1310                wgpu::BindGroupLayoutEntry {
1311                    binding: 0,
1312                    visibility: wgpu::ShaderStages::FRAGMENT,
1313                    ty: wgpu::BindingType::Texture {
1314                        multisampled: false,
1315                        view_dimension: wgpu::TextureViewDimension::D2,
1316                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
1317                    },
1318                    count: None,
1319                },
1320                wgpu::BindGroupLayoutEntry {
1321                    binding: 1,
1322                    visibility: wgpu::ShaderStages::FRAGMENT,
1323                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1324                    count: None,
1325                },
1326            ],
1327        });
1328        // We reuse this for RGBA images for simplicity, or create a distinct one
1329        let image_bind_layout_rgba = text_bind_layout.clone();
1330
1331        // Layout for NV12 Images (TextureY + TextureUV + Sampler + YuvTransform uniform)
1332        let image_bind_layout_nv12 =
1333            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1334                label: Some("image bind layout nv12"),
1335                entries: &[
1336                    // Y plane
1337                    wgpu::BindGroupLayoutEntry {
1338                        binding: 0,
1339                        visibility: wgpu::ShaderStages::FRAGMENT,
1340                        ty: wgpu::BindingType::Texture {
1341                            multisampled: false,
1342                            view_dimension: wgpu::TextureViewDimension::D2,
1343                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
1344                        },
1345                        count: None,
1346                    },
1347                    // UV plane
1348                    wgpu::BindGroupLayoutEntry {
1349                        binding: 1,
1350                        visibility: wgpu::ShaderStages::FRAGMENT,
1351                        ty: wgpu::BindingType::Texture {
1352                            multisampled: false,
1353                            view_dimension: wgpu::TextureViewDimension::D2,
1354                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
1355                        },
1356                        count: None,
1357                    },
1358                    // Sampler
1359                    wgpu::BindGroupLayoutEntry {
1360                        binding: 2,
1361                        visibility: wgpu::ShaderStages::FRAGMENT,
1362                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1363                        count: None,
1364                    },
1365                    // YUV transform uniform buffer
1366                    wgpu::BindGroupLayoutEntry {
1367                        binding: 3,
1368                        visibility: wgpu::ShaderStages::FRAGMENT,
1369                        ty: wgpu::BindingType::Buffer {
1370                            ty: wgpu::BufferBindingType::Uniform,
1371                            has_dynamic_offset: false,
1372                            min_binding_size: None,
1373                        },
1374                        count: None,
1375                    },
1376                ],
1377            });
1378
1379        // Clipping layout
1380        let clip_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1381            label: Some("clip pipeline layout"),
1382            bind_group_layouts: &[Some(&globals_layout)],
1383            immediate_size: 0,
1384        });
1385        let clip_vertex_layout = wgpu::VertexBufferLayout {
1386            array_stride: std::mem::size_of::<ClipInstance>() as u64,
1387            step_mode: wgpu::VertexStepMode::Instance,
1388            attributes: &[
1389                wgpu::VertexAttribute {
1390                    shader_location: 0,
1391                    offset: 0,
1392                    format: wgpu::VertexFormat::Float32x4,
1393                },
1394                wgpu::VertexAttribute {
1395                    shader_location: 1,
1396                    offset: 16,
1397                    format: wgpu::VertexFormat::Float32x4,
1398                },
1399                wgpu::VertexAttribute {
1400                    shader_location: 2,
1401                    offset: 32,
1402                    format: wgpu::VertexFormat::Float32x2,
1403                },
1404            ],
1405        };
1406        let clip_color_target = wgpu::ColorTargetState {
1407            format: output_format,
1408            blend: None,
1409            write_mask: wgpu::ColorWrites::empty(),
1410        };
1411
1412        // Two sets of pipelines: one for the MSAA surface pass, one for layer
1413        // render-to-texture passes (sample_count = 1).
1414        let surface_pipes = Pipelines::create(
1415            &device,
1416            output_format,
1417            msaa_samples,
1418            &globals_layout,
1419            &text_bind_layout,
1420            &image_bind_layout_nv12,
1421            &clip_pipeline_layout,
1422            &stencil_for_content,
1423            &stencil_for_clip_inc,
1424            &stencil_for_clip_dec,
1425            &clip_color_target,
1426            &clip_vertex_layout,
1427        );
1428        let layer_pipes = Pipelines::create(
1429            &device,
1430            output_format,
1431            1,
1432            &globals_layout,
1433            &text_bind_layout,
1434            &image_bind_layout_nv12,
1435            &clip_pipeline_layout,
1436            &stencil_for_content,
1437            &stencil_for_clip_inc,
1438            &stencil_for_clip_dec,
1439            &clip_color_target,
1440            &clip_vertex_layout,
1441        );
1442
1443        // Vector glyph rendering always available with tessellation+MSAA approach.
1444        let slug_enabled = true;
1445
1446        // Blur composite ring (for graphics-layer drop shadows)
1447        let blur_ring = UploadRing::new(&device, "blur ring", 1024 * 1024);
1448
1449        // Atlases
1450        let atlas_mask = init_atlas_mask(&device);
1451        let atlas_color = init_atlas_color(&device);
1452
1453        // Upload rings
1454        let ring_rect = UploadRing::new(&device, "ring rect", 1 << 20);
1455        let ring_border = UploadRing::new(&device, "ring border", 1 << 20);
1456        let ring_ellipse = UploadRing::new(&device, "ring ellipse", 1 << 20);
1457        let ring_ellipse_border = UploadRing::new(&device, "ring ellipse border", 1 << 20);
1458        let ring_arc = UploadRing::new(&device, "ring arc", 1 << 20);
1459        let ring_glyph_mask = UploadRing::new(&device, "ring glyph mask", 1 << 20);
1460        let ring_glyph_color = UploadRing::new(&device, "ring glyph color", 1 << 20);
1461        let ring_slug = UploadRing::new(&device, "ring slug", 1 << 22);
1462        let ring_clip = UploadRing::new(&device, "ring clip", 1 << 16);
1463        let ring_nv12 = UploadRing::new(&device, "ring nv12", 1 << 20);
1464
1465        // Placeholder textures
1466        let depth_stencil_tex = device.create_texture(&wgpu::TextureDescriptor {
1467            label: Some("temp ds"),
1468            size: wgpu::Extent3d {
1469                width: 1,
1470                height: 1,
1471                depth_or_array_layers: 1,
1472            },
1473            mip_level_count: 1,
1474            sample_count: 1,
1475            dimension: wgpu::TextureDimension::D2,
1476            format: wgpu::TextureFormat::Depth24PlusStencil8,
1477            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1478            view_formats: &[],
1479        });
1480        let depth_stencil_view =
1481            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
1482
1483        let mut renderer = WgpuSceneRenderer {
1484            device,
1485            queue,
1486            output_format,
1487            output_width: 0,
1488            output_height: 0,
1489
1490            surface_pipes,
1491            layer_pipes,
1492
1493            rects: InstancedPipe::new(ring_rect),
1494            borders: InstancedPipe::new(ring_border),
1495            ellipses: InstancedPipe::new(ring_ellipse),
1496            ellipse_borders: InstancedPipe::new(ring_ellipse_border),
1497            arcs: InstancedPipe::new(ring_arc),
1498            glyph_mask: InstancedPipe::new(ring_glyph_mask),
1499            glyph_color: InstancedPipe::new(ring_glyph_color),
1500
1501            text_bind_layout,
1502
1503            image_bind_layout_rgba,
1504            image_bind_layout_nv12,
1505            image_sampler,
1506
1507            blur_ring,
1508
1509            slug_enabled,
1510            slug_ring: ring_slug,
1511            slug_cache: slug::GlyphSlugCache::new(),
1512
1513            clip_ring: ring_clip,
1514
1515            nv12: InstancedPipe::new(ring_nv12),
1516
1517            msaa_samples,
1518            depth_stencil_tex,
1519            depth_stencil_view,
1520            msaa_tex: None,
1521            msaa_view: None,
1522            globals_bind,
1523            globals_buf,
1524            globals_layout,
1525
1526            atlas_mask,
1527            atlas_color,
1528
1529            next_image_handle: 1,
1530            images: HashMap::new(),
1531
1532            frame_index: 0,
1533            image_bytes_total: 0,
1534            image_evict_after_frames: 600,         // ~10s @ 60fps
1535            image_budget_bytes: 512 * 1024 * 1024, // 512 MB
1536            layer_pool: HashMap::new(),
1537
1538            working_space: false,
1539            ws_tex: None,
1540            ws_view: None,
1541            ws_bind: None,
1542            display_pipeline: None,
1543            display_layout: None,
1544        };
1545
1546        renderer.recreate_msaa_and_depth_stencil();
1547        renderer
1548    }
1549}
1550
1551impl WgpuSurfaceBackend {
1552    #[cfg(feature = "winit-surface")]
1553    pub async fn new_async(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
1554        let instance: Instance;
1555
1556        if cfg!(target_arch = "wasm32") {
1557            let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
1558            desc.backends = wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL;
1559            instance = wgpu::util::new_instance_with_webgpu_detection(desc).await;
1560        } else {
1561            instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
1562        };
1563
1564        let surface = instance.create_surface(window.clone())?;
1565
1566        let adapter = instance
1567            .request_adapter(&wgpu::RequestAdapterOptions {
1568                power_preference: wgpu::PowerPreference::HighPerformance,
1569                compatible_surface: Some(&surface),
1570                force_fallback_adapter: false,
1571                apply_limit_buckets: false,
1572            })
1573            .await
1574            .map_err(|e| anyhow::anyhow!("No suitable adapter: {e:?}"))?;
1575
1576        let limits = adapter.limits();
1577
1578        let (device, queue) = adapter
1579            .request_device(&wgpu::DeviceDescriptor {
1580                label: Some("repose-rs device"),
1581                required_features: wgpu::Features::empty(),
1582                required_limits: limits,
1583                experimental_features: wgpu::ExperimentalFeatures::disabled(),
1584                memory_hints: wgpu::MemoryHints::default(),
1585                trace: wgpu::Trace::Off,
1586            })
1587            .await
1588            .map_err(|e| anyhow::anyhow!("request_device failed: {e:?}"))?;
1589
1590        let size = window.inner_size();
1591
1592        let caps = surface.get_capabilities(&adapter);
1593        let format = caps
1594            .formats
1595            .iter()
1596            .copied()
1597            .find(|f| f.is_srgb())
1598            .unwrap_or(caps.formats[0]);
1599        let present_mode = caps
1600            .present_modes
1601            .iter()
1602            .copied()
1603            .find(|m| *m == wgpu::PresentMode::Fifo)
1604            .or_else(|| caps.present_modes.iter().copied().find(|m| *m == wgpu::PresentMode::Mailbox))
1605            .unwrap_or(wgpu::PresentMode::Immediate);
1606        let alpha_mode = caps.alpha_modes[0];
1607
1608        // Pick MSAA sample count
1609        let fmt_features = adapter.get_texture_format_features(format);
1610        let msaa_samples = if fmt_features.flags.sample_count_supported(4)
1611            && fmt_features
1612                .flags
1613                .contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
1614        {
1615            4
1616        } else {
1617            1
1618        };
1619
1620        let renderer = WgpuSceneRenderer::from_device(device, queue, format, msaa_samples);
1621
1622        let config = wgpu::SurfaceConfiguration {
1623            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1624            format,
1625            width: size.width.max(1),
1626            height: size.height.max(1),
1627            present_mode,
1628            alpha_mode,
1629            color_space: wgpu::SurfaceColorSpace::Auto,
1630            view_formats: vec![],
1631            desired_maximum_frame_latency: 1,
1632        };
1633        surface.configure(&renderer.device, &config);
1634
1635        Ok(WgpuSurfaceBackend { surface: Some(surface), surface_config: Some(config), renderer })
1636    }
1637
1638    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
1639    pub fn new(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
1640        pollster::block_on(Self::new_async(window))
1641    }
1642
1643    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
1644    pub fn new(_window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
1645        anyhow::bail!("Use WgpuSurfaceBackend::new_async(window).await on wasm32")
1646    }
1647}
1648
1649impl WgpuSceneRenderer {
1650    // Image API
1651
1652    pub fn set_image_from_bytes(
1653        &mut self,
1654        handle: u64,
1655        data: &[u8],
1656        srgb: bool,
1657    ) -> anyhow::Result<()> {
1658        let img = image::load_from_memory(data)?;
1659        let rgba = img.to_rgba8();
1660        let (w, h) = rgba.dimensions();
1661        self.set_image_rgba8(handle, w, h, &rgba, srgb)
1662    }
1663
1664    pub fn set_image_rgba8(
1665        &mut self,
1666        handle: u64,
1667        w: u32,
1668        h: u32,
1669        rgba: &[u8],
1670        srgb: bool,
1671    ) -> anyhow::Result<()> {
1672        let expected = (w as usize) * (h as usize) * 4;
1673        if rgba.len() < expected {
1674            return Err(anyhow::anyhow!(
1675                "RGBA buffer too small: {} < {}",
1676                rgba.len(),
1677                expected
1678            ));
1679        }
1680
1681        let format = if srgb {
1682            wgpu::TextureFormat::Rgba8UnormSrgb
1683        } else {
1684            wgpu::TextureFormat::Rgba8Unorm
1685        };
1686
1687        let needs_recreate = match self.images.get(&handle) {
1688            Some(ImageTex::Rgba {
1689                w: cw,
1690                h: ch,
1691                format: cf,
1692                ..
1693            }) => *cw != w || *ch != h || *cf != format,
1694            _ => true,
1695        };
1696
1697        if needs_recreate {
1698            // Remove old to track budget correctly
1699            self.remove_image(handle);
1700
1701            let tex = self.device.create_texture(&wgpu::TextureDescriptor {
1702                label: Some("user image rgba"),
1703                size: wgpu::Extent3d {
1704                    width: w,
1705                    height: h,
1706                    depth_or_array_layers: 1,
1707                },
1708                mip_level_count: 1,
1709                sample_count: 1,
1710                dimension: wgpu::TextureDimension::D2,
1711                format,
1712                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1713                view_formats: &[],
1714            });
1715            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1716
1717            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
1718                label: Some("image bind rgba"),
1719                layout: &self.image_bind_layout_rgba,
1720                entries: &[
1721                    wgpu::BindGroupEntry {
1722                        binding: 0,
1723                        resource: wgpu::BindingResource::TextureView(&view),
1724                    },
1725                    wgpu::BindGroupEntry {
1726                        binding: 1,
1727                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
1728                    },
1729                ],
1730            });
1731
1732            let bytes = (w as u64) * (h as u64) * 4;
1733            self.image_bytes_total += bytes;
1734
1735            self.images.insert(
1736                handle,
1737                ImageTex::Rgba {
1738                    tex,
1739                    view,
1740                    bind,
1741                    w,
1742                    h,
1743                    format,
1744                    last_used_frame: self.frame_index,
1745                    bytes,
1746                },
1747            );
1748        }
1749
1750        let tex = match self.images.get(&handle) {
1751            Some(ImageTex::Rgba { tex, .. }) => tex,
1752            _ => unreachable!(),
1753        };
1754
1755        self.queue.write_texture(
1756            wgpu::TexelCopyTextureInfo {
1757                texture: tex,
1758                mip_level: 0,
1759                origin: wgpu::Origin3d::ZERO,
1760                aspect: wgpu::TextureAspect::All,
1761            },
1762            &rgba[..expected],
1763            wgpu::TexelCopyBufferLayout {
1764                offset: 0,
1765                bytes_per_row: Some(4 * w),
1766                rows_per_image: Some(h),
1767            },
1768            wgpu::Extent3d {
1769                width: w,
1770                height: h,
1771                depth_or_array_layers: 1,
1772            },
1773        );
1774
1775        // Ensure budget limits
1776        self.evict_budget_excess();
1777
1778        Ok(())
1779    }
1780
1781    pub fn set_image_nv12(
1782        &mut self,
1783        handle: u64,
1784        w: u32,
1785        h: u32,
1786        y: &[u8],
1787        uv: &[u8],
1788        color_info: ColorInfo,
1789    ) -> anyhow::Result<()> {
1790        let y_expected = (w as usize) * (h as usize);
1791        let uv_w = (w / 2).max(1);
1792        let uv_h = (h / 2).max(1);
1793        let uv_expected = (uv_w as usize) * (uv_h as usize) * 2;
1794
1795        if y.len() < y_expected {
1796            return Err(anyhow::anyhow!("Y plane too small"));
1797        }
1798        if uv.len() < uv_expected {
1799            return Err(anyhow::anyhow!("UV plane too small"));
1800        }
1801
1802        let needs_recreate = match self.images.get(&handle) {
1803            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
1804            _ => true,
1805        };
1806
1807        // Compute the YUV→RGB transform on the CPU.
1808        let yuv = color_info.to_yuv_transform();
1809        let yuv_raw = YuvTransformRaw {
1810            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
1811            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
1812            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
1813            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
1814        };
1815
1816        if needs_recreate {
1817            self.remove_image(handle);
1818
1819            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
1820                label: Some("nv12 Y"),
1821                size: wgpu::Extent3d {
1822                    width: w,
1823                    height: h,
1824                    depth_or_array_layers: 1,
1825                },
1826                mip_level_count: 1,
1827                sample_count: 1,
1828                dimension: wgpu::TextureDimension::D2,
1829                format: wgpu::TextureFormat::R8Unorm,
1830                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1831                view_formats: &[],
1832            });
1833            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
1834
1835            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
1836                label: Some("nv12 UV"),
1837                size: wgpu::Extent3d {
1838                    width: uv_w,
1839                    height: uv_h,
1840                    depth_or_array_layers: 1,
1841                },
1842                mip_level_count: 1,
1843                sample_count: 1,
1844                dimension: wgpu::TextureDimension::D2,
1845                format: wgpu::TextureFormat::Rg8Unorm,
1846                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1847                view_formats: &[],
1848            });
1849            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
1850
1851            // Create a uniform buffer for the YUV transform (per-image).
1852            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
1853                label: Some("nv12 yuv transform"),
1854                size: std::mem::size_of::<YuvTransformRaw>() as u64,
1855                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1856                mapped_at_creation: false,
1857            });
1858
1859            // Write initial transform.
1860            self.queue
1861                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
1862
1863            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
1864                label: Some("nv12 bind"),
1865                layout: &self.image_bind_layout_nv12,
1866                entries: &[
1867                    wgpu::BindGroupEntry {
1868                        binding: 0,
1869                        resource: wgpu::BindingResource::TextureView(&view_y),
1870                    },
1871                    wgpu::BindGroupEntry {
1872                        binding: 1,
1873                        resource: wgpu::BindingResource::TextureView(&view_uv),
1874                    },
1875                    wgpu::BindGroupEntry {
1876                        binding: 2,
1877                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
1878                    },
1879                    wgpu::BindGroupEntry {
1880                        binding: 3,
1881                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1882                            buffer: &yuv_buf,
1883                            offset: 0,
1884                            size: None,
1885                        }),
1886                    },
1887                ],
1888            });
1889
1890            let bytes = (w as u64) * (h as u64)
1891                + (uv_w as u64) * (uv_h as u64) * 2
1892                + std::mem::size_of::<YuvTransformRaw>() as u64;
1893            self.image_bytes_total += bytes;
1894
1895            self.images.insert(
1896                handle,
1897                ImageTex::Nv12 {
1898                    tex_y,
1899                    view_y,
1900                    tex_uv,
1901                    view_uv,
1902                    bind,
1903                    yuv_buf,
1904                    w,
1905                    h,
1906                    color_info,
1907                    last_used_frame: self.frame_index,
1908                    bytes,
1909                },
1910            );
1911        } else {
1912            // Re-use existing textures; just update the YUV transform if needed.
1913            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
1914                self.queue
1915                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
1916            }
1917        }
1918
1919        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
1920            Some(ImageTex::Nv12 {
1921                tex_y,
1922                tex_uv,
1923                bind,
1924                ..
1925            }) => (tex_y, tex_uv, bind),
1926            _ => return Err(anyhow::anyhow!("Handle is not NV12")),
1927        };
1928
1929        self.queue.write_texture(
1930            wgpu::TexelCopyTextureInfo {
1931                texture: tex_y,
1932                mip_level: 0,
1933                origin: wgpu::Origin3d::ZERO,
1934                aspect: wgpu::TextureAspect::All,
1935            },
1936            &y[..y_expected],
1937            wgpu::TexelCopyBufferLayout {
1938                offset: 0,
1939                bytes_per_row: Some(w),
1940                rows_per_image: Some(h),
1941            },
1942            wgpu::Extent3d {
1943                width: w,
1944                height: h,
1945                depth_or_array_layers: 1,
1946            },
1947        );
1948
1949        self.queue.write_texture(
1950            wgpu::TexelCopyTextureInfo {
1951                texture: tex_uv,
1952                mip_level: 0,
1953                origin: wgpu::Origin3d::ZERO,
1954                aspect: wgpu::TextureAspect::All,
1955            },
1956            &uv[..uv_expected],
1957            wgpu::TexelCopyBufferLayout {
1958                offset: 0,
1959                bytes_per_row: Some(2 * uv_w),
1960                rows_per_image: Some(uv_h),
1961            },
1962            wgpu::Extent3d {
1963                width: uv_w,
1964                height: uv_h,
1965                depth_or_array_layers: 1,
1966            },
1967        );
1968
1969        self.evict_budget_excess();
1970        Ok(())
1971    }
1972
1973    pub fn set_image_planes(
1974        &mut self,
1975        handle: u64,
1976        w: u32,
1977        h: u32,
1978        pixel_format: PixelFormat,
1979        planes: &[&[u8]],
1980        color_info: ColorInfo,
1981    ) -> anyhow::Result<()> {
1982        match pixel_format {
1983            PixelFormat::Nv12 => {
1984                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
1985                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
1986                self.set_image_nv12(handle, w, h, y, uv, color_info)
1987            }
1988            PixelFormat::P010 => {
1989                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
1990                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
1991                self.set_image_p010(handle, w, h, y, uv, color_info)
1992            }
1993            PixelFormat::I420 | PixelFormat::I444 => Err(anyhow::anyhow!(
1994                "I420/I444 not implemented and unlikely -> cheap to convert to NV12 (better for the GPU too)"
1995            )),
1996            PixelFormat::Rgba => {
1997                let rgba = planes
1998                    .first()
1999                    .ok_or(anyhow::anyhow!("missing RGBA plane"))?;
2000                self.set_image_rgba8(handle, w, h, rgba, false)
2001            }
2002        }
2003    }
2004
2005    fn set_image_p010(
2006        &mut self,
2007        handle: u64,
2008        w: u32,
2009        h: u32,
2010        y: &[u8],
2011        uv: &[u8],
2012        color_info: ColorInfo,
2013    ) -> anyhow::Result<()> {
2014        let uv_w = (w / 2).max(1);
2015        let uv_h = (h / 2).max(1);
2016
2017        let y_expected = (w as usize) * 2;
2018        let uv_expected = (uv_w as usize) * (uv_h as usize) * 4;
2019
2020        if y.len() < y_expected {
2021            return Err(anyhow::anyhow!("P010 Y plane too small"));
2022        }
2023        if uv.len() < uv_expected {
2024            return Err(anyhow::anyhow!("P010 UV plane too small"));
2025        }
2026
2027        // P010 reuses the NV12 pipeline (same bind group layout -> wgpu
2028        // abstracts the storage format so R16Unorm/Rg16Unorm are
2029        // filterable float textures just like R8Unorm/Rg8Unorm).
2030        let needs_recreate = match self.images.get(&handle) {
2031            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
2032            _ => true,
2033        };
2034
2035        let yuv = color_info.to_yuv_transform();
2036        let yuv_raw = YuvTransformRaw {
2037            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2038            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2039            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2040            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2041        };
2042
2043        if needs_recreate {
2044            self.remove_image(handle);
2045
2046            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
2047                label: Some("p010 Y"),
2048                size: wgpu::Extent3d {
2049                    width: w,
2050                    height: h,
2051                    depth_or_array_layers: 1,
2052                },
2053                mip_level_count: 1,
2054                sample_count: 1,
2055                dimension: wgpu::TextureDimension::D2,
2056                format: wgpu::TextureFormat::R16Unorm,
2057                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2058                view_formats: &[],
2059            });
2060            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2061
2062            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
2063                label: Some("p010 UV"),
2064                size: wgpu::Extent3d {
2065                    width: uv_w,
2066                    height: uv_h,
2067                    depth_or_array_layers: 1,
2068                },
2069                mip_level_count: 1,
2070                sample_count: 1,
2071                dimension: wgpu::TextureDimension::D2,
2072                format: wgpu::TextureFormat::Rg16Unorm,
2073                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2074                view_formats: &[],
2075            });
2076            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2077
2078            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2079                label: Some("p010 yuv transform"),
2080                size: std::mem::size_of::<YuvTransformRaw>() as u64,
2081                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2082                mapped_at_creation: false,
2083            });
2084            self.queue
2085                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2086
2087            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2088                label: Some("p010 bind"),
2089                layout: &self.image_bind_layout_nv12,
2090                entries: &[
2091                    wgpu::BindGroupEntry {
2092                        binding: 0,
2093                        resource: wgpu::BindingResource::TextureView(&view_y),
2094                    },
2095                    wgpu::BindGroupEntry {
2096                        binding: 1,
2097                        resource: wgpu::BindingResource::TextureView(&view_uv),
2098                    },
2099                    wgpu::BindGroupEntry {
2100                        binding: 2,
2101                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2102                    },
2103                    wgpu::BindGroupEntry {
2104                        binding: 3,
2105                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2106                            buffer: &yuv_buf,
2107                            offset: 0,
2108                            size: None,
2109                        }),
2110                    },
2111                ],
2112            });
2113
2114            let bytes = (w as u64) * 2
2115                + (uv_w as u64) * (uv_h as u64) * 4
2116                + std::mem::size_of::<YuvTransformRaw>() as u64;
2117            self.image_bytes_total += bytes;
2118
2119            self.images.insert(
2120                handle,
2121                ImageTex::Nv12 {
2122                    tex_y,
2123                    view_y,
2124                    tex_uv,
2125                    view_uv,
2126                    bind,
2127                    yuv_buf,
2128                    w,
2129                    h,
2130                    color_info,
2131                    last_used_frame: self.frame_index,
2132                    bytes,
2133                },
2134            );
2135        } else {
2136            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
2137                self.queue
2138                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2139            }
2140        }
2141
2142        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
2143            Some(ImageTex::Nv12 {
2144                tex_y,
2145                tex_uv,
2146                bind,
2147                ..
2148            }) => (tex_y, tex_uv, bind),
2149            _ => return Err(anyhow::anyhow!("Handle is not P010/NV12")),
2150        };
2151
2152        self.queue.write_texture(
2153            wgpu::TexelCopyTextureInfo {
2154                texture: tex_y,
2155                mip_level: 0,
2156                origin: wgpu::Origin3d::ZERO,
2157                aspect: wgpu::TextureAspect::All,
2158            },
2159            &y[..y_expected],
2160            wgpu::TexelCopyBufferLayout {
2161                offset: 0,
2162                bytes_per_row: Some(w * 2),
2163                rows_per_image: Some(h),
2164            },
2165            wgpu::Extent3d {
2166                width: w,
2167                height: h,
2168                depth_or_array_layers: 1,
2169            },
2170        );
2171        self.queue.write_texture(
2172            wgpu::TexelCopyTextureInfo {
2173                texture: tex_uv,
2174                mip_level: 0,
2175                origin: wgpu::Origin3d::ZERO,
2176                aspect: wgpu::TextureAspect::All,
2177            },
2178            &uv[..uv_expected],
2179            wgpu::TexelCopyBufferLayout {
2180                offset: 0,
2181                bytes_per_row: Some(uv_w * 4),
2182                rows_per_image: Some(uv_h),
2183            },
2184            wgpu::Extent3d {
2185                width: uv_w,
2186                height: uv_h,
2187                depth_or_array_layers: 1,
2188            },
2189        );
2190
2191        self.evict_budget_excess();
2192        Ok(())
2193    }
2194
2195    pub fn remove_image(&mut self, handle: u64) {
2196        if let Some(img) = self.images.remove(&handle) {
2197            let b = match &img {
2198                ImageTex::Rgba { bytes, .. } => *bytes,
2199                ImageTex::Nv12 { bytes, .. } => *bytes,
2200            };
2201            self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
2202        }
2203    }
2204
2205    // Legacy support from Step 1 instructions (temporary until platform render logic is fully swapped)
2206    pub fn register_image_from_bytes(&mut self, data: &[u8], srgb: bool) -> u64 {
2207        let handle = self.next_image_handle;
2208        self.next_image_handle += 1;
2209        if let Err(e) = self.set_image_from_bytes(handle, data, srgb) {
2210            log::error!("Failed to register image: {e}");
2211        }
2212        handle
2213    }
2214
2215    fn evict_unused_images(&mut self) {
2216        let now = self.frame_index;
2217        let evict_after = self.image_evict_after_frames;
2218
2219        // Time based eviction
2220        let mut to_remove = Vec::new();
2221        for (h, t) in self.images.iter() {
2222            let last = match t {
2223                ImageTex::Rgba {
2224                    last_used_frame, ..
2225                } => *last_used_frame,
2226                ImageTex::Nv12 {
2227                    last_used_frame, ..
2228                } => *last_used_frame,
2229            };
2230            if now.saturating_sub(last) > evict_after {
2231                to_remove.push(*h);
2232            }
2233        }
2234        for h in to_remove {
2235            self.remove_image(h);
2236        }
2237
2238        self.evict_budget_excess();
2239    }
2240
2241    fn evict_budget_excess(&mut self) {
2242        if self.image_bytes_total <= self.image_budget_bytes {
2243            return;
2244        }
2245        // Collect (handle, last_used, bytes)
2246        let mut candidates: Vec<(u64, u64, u64)> = self
2247            .images
2248            .iter()
2249            .map(|(h, t)| {
2250                let (last, bytes) = match t {
2251                    ImageTex::Rgba {
2252                        last_used_frame,
2253                        bytes,
2254                        ..
2255                    } => (*last_used_frame, *bytes),
2256                    ImageTex::Nv12 {
2257                        last_used_frame,
2258                        bytes,
2259                        ..
2260                    } => (*last_used_frame, *bytes),
2261                };
2262                (*h, last, bytes)
2263            })
2264            .collect();
2265
2266        // Sort by last_used ascending (LRU first)
2267        candidates.sort_by_key(|k| k.1);
2268
2269        let now = self.frame_index;
2270        for (h, last, _bytes) in candidates {
2271            if self.image_bytes_total <= self.image_budget_bytes {
2272                break;
2273            }
2274            // Don't evict something used this frame
2275            if last == now {
2276                continue;
2277            }
2278            self.remove_image(h);
2279        }
2280    }
2281
2282    /// Enable or disable linear working-space rendering.
2283    /// When enabled, the scene is rendered into an Rgba16Float intermediate
2284    /// and a final full-screen pass applies the display OETF.
2285    pub fn set_working_space(&mut self, enabled: bool) {
2286        if enabled == self.working_space {
2287            return;
2288        }
2289        self.working_space = enabled;
2290        if enabled {
2291            self.ensure_display_pipeline();
2292            self.recreate_working_space_texture();
2293        } else {
2294            self.ws_tex = None;
2295            self.ws_view = None;
2296            self.ws_bind = None;
2297        }
2298    }
2299
2300    fn ensure_display_pipeline(&mut self) {
2301        if self.display_pipeline.is_some() {
2302            return;
2303        }
2304
2305        let layout = self
2306            .device
2307            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2308                label: Some("display transform layout"),
2309                entries: &[
2310                    wgpu::BindGroupLayoutEntry {
2311                        binding: 0,
2312                        visibility: wgpu::ShaderStages::FRAGMENT,
2313                        ty: wgpu::BindingType::Texture {
2314                            multisampled: false,
2315                            view_dimension: wgpu::TextureViewDimension::D2,
2316                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
2317                        },
2318                        count: None,
2319                    },
2320                    wgpu::BindGroupLayoutEntry {
2321                        binding: 1,
2322                        visibility: wgpu::ShaderStages::FRAGMENT,
2323                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
2324                        count: None,
2325                    },
2326                ],
2327            });
2328        self.display_layout = Some(layout);
2329
2330        let shader = self
2331            .device
2332            .create_shader_module(wgpu::ShaderModuleDescriptor {
2333                label: Some("display_transform.wgsl"),
2334                source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
2335                    "shaders/display_transform.wgsl"
2336                ))),
2337            });
2338
2339        let pipeline_layout = self
2340            .device
2341            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
2342                label: Some("display transform pipeline layout"),
2343                bind_group_layouts: &[None, self.display_layout.as_ref()],
2344                immediate_size: 0,
2345            });
2346
2347        let pipeline = self
2348            .device
2349            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
2350                label: Some("display transform pipeline"),
2351                layout: Some(&pipeline_layout),
2352                vertex: wgpu::VertexState {
2353                    module: &shader,
2354                    entry_point: Some("vs_main"),
2355                    buffers: &[],
2356                    compilation_options: wgpu::PipelineCompilationOptions::default(),
2357                },
2358                fragment: Some(wgpu::FragmentState {
2359                    module: &shader,
2360                    entry_point: Some("fs_main"),
2361                    targets: &[Some(wgpu::ColorTargetState {
2362                        format: self.output_format,
2363                        blend: None,
2364                        write_mask: wgpu::ColorWrites::ALL,
2365                    })],
2366                    compilation_options: wgpu::PipelineCompilationOptions::default(),
2367                }),
2368                primitive: wgpu::PrimitiveState::default(),
2369                depth_stencil: None,
2370                multisample: wgpu::MultisampleState::default(),
2371                multiview_mask: None,
2372                cache: None,
2373            });
2374        self.display_pipeline = Some(pipeline);
2375    }
2376
2377    /// Resize the render target dimensions.
2378    ///
2379    /// Recreates MSAA, depth-stencil, and working-space textures to match the
2380    /// new size..
2381    pub fn resize(&mut self, width: u32, height: u32) {
2382        self.output_width = width;
2383        self.output_height = height;
2384        self.recreate_msaa_and_depth_stencil();
2385        self.recreate_working_space_texture();
2386    }
2387
2388    fn recreate_working_space_texture(&mut self) {
2389        if !self.working_space {
2390            return;
2391        }
2392        let w = self.output_width.max(1);
2393        let h = self.output_height.max(1);
2394
2395        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2396            label: Some("working space"),
2397            size: wgpu::Extent3d {
2398                width: w,
2399                height: h,
2400                depth_or_array_layers: 1,
2401            },
2402            mip_level_count: 1,
2403            sample_count: 1,
2404            dimension: wgpu::TextureDimension::D2,
2405            format: wgpu::TextureFormat::Rgba16Float,
2406            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
2407            view_formats: &[],
2408        });
2409        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2410
2411        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2412            label: Some("working space bind"),
2413            layout: self.display_layout.as_ref().unwrap(),
2414            entries: &[
2415                wgpu::BindGroupEntry {
2416                    binding: 0,
2417                    resource: wgpu::BindingResource::TextureView(&view),
2418                },
2419                wgpu::BindGroupEntry {
2420                    binding: 1,
2421                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2422                },
2423            ],
2424        });
2425
2426        self.ws_tex = Some(tex);
2427        self.ws_view = Some(view);
2428        self.ws_bind = Some(bind);
2429    }
2430
2431    fn recreate_msaa_and_depth_stencil(&mut self) {
2432        if self.msaa_samples > 1 {
2433            let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2434                label: Some("msaa color"),
2435                size: wgpu::Extent3d {
2436                    width: self.output_width.max(1),
2437                    height: self.output_height.max(1),
2438                    depth_or_array_layers: 1,
2439                },
2440                mip_level_count: 1,
2441                sample_count: self.msaa_samples,
2442                dimension: wgpu::TextureDimension::D2,
2443                format: self.output_format,
2444                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2445                view_formats: &[],
2446            });
2447            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2448            self.msaa_tex = Some(tex);
2449            self.msaa_view = Some(view);
2450        } else {
2451            self.msaa_tex = None;
2452            self.msaa_view = None;
2453        }
2454
2455        self.depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
2456            label: Some("depth-stencil (stencil clips)"),
2457            size: wgpu::Extent3d {
2458                width: self.output_width.max(1),
2459                height: self.output_height.max(1),
2460                depth_or_array_layers: 1,
2461            },
2462            mip_level_count: 1,
2463            sample_count: self.msaa_samples,
2464            dimension: wgpu::TextureDimension::D2,
2465            format: wgpu::TextureFormat::Depth24PlusStencil8,
2466            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2467            view_formats: &[],
2468        });
2469        self.depth_stencil_view = self
2470            .depth_stencil_tex
2471            .create_view(&wgpu::TextureViewDescriptor::default());
2472    }
2473
2474
2475
2476    fn get_or_create_layer(
2477        &mut self,
2478        layer_id: u32,
2479        width: u32,
2480        height: u32,
2481        rect: repose_core::Rect,
2482    ) {
2483        let needs_alloc = match self.layer_pool.get(&layer_id) {
2484            Some(lt) => lt.width != width || lt.height != height,
2485            None => true,
2486        };
2487        if !needs_alloc {
2488            return;
2489        }
2490        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2491            label: Some("graphics layer"),
2492            size: wgpu::Extent3d {
2493                width: width.max(1),
2494                height: height.max(1),
2495                depth_or_array_layers: 1,
2496            },
2497            mip_level_count: 1,
2498            sample_count: 1,
2499            dimension: wgpu::TextureDimension::D2,
2500            format: self.output_format,
2501            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
2502            view_formats: &[],
2503        });
2504        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2505        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2506            label: Some("layer bind"),
2507            layout: &self.image_bind_layout_rgba,
2508            entries: &[
2509                wgpu::BindGroupEntry {
2510                    binding: 0,
2511                    resource: wgpu::BindingResource::TextureView(&view),
2512                },
2513                wgpu::BindGroupEntry {
2514                    binding: 1,
2515                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2516                },
2517            ],
2518        });
2519        let depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
2520            label: Some("graphics layer depth-stencil"),
2521            size: wgpu::Extent3d {
2522                width: width.max(1),
2523                height: height.max(1),
2524                depth_or_array_layers: 1,
2525            },
2526            mip_level_count: 1,
2527            sample_count: 1,
2528            dimension: wgpu::TextureDimension::D2,
2529            format: wgpu::TextureFormat::Depth24PlusStencil8,
2530            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2531            view_formats: &[],
2532        });
2533        let depth_stencil_view =
2534            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
2535        self.layer_pool.insert(
2536            layer_id,
2537            LayerTarget {
2538                texture: tex,
2539                view,
2540                bind,
2541                depth_stencil_tex,
2542                depth_stencil_view,
2543                width,
2544                height,
2545                rect_px: (rect.x, rect.y, rect.w, rect.h),
2546            },
2547        );
2548    }
2549
2550    fn atlas_bind_group_mask(&self) -> wgpu::BindGroup {
2551        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2552            label: Some("atlas bind"),
2553            layout: &self.text_bind_layout,
2554            entries: &[
2555                wgpu::BindGroupEntry {
2556                    binding: 0,
2557                    resource: wgpu::BindingResource::TextureView(&self.atlas_mask.view),
2558                },
2559                wgpu::BindGroupEntry {
2560                    binding: 1,
2561                    resource: wgpu::BindingResource::Sampler(&self.atlas_mask.sampler),
2562                },
2563            ],
2564        })
2565    }
2566
2567    fn atlas_bind_group_color(&self) -> wgpu::BindGroup {
2568        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2569            label: Some("atlas bind color"),
2570            layout: &self.text_bind_layout,
2571            entries: &[
2572                wgpu::BindGroupEntry {
2573                    binding: 0,
2574                    resource: wgpu::BindingResource::TextureView(&self.atlas_color.view),
2575                },
2576                wgpu::BindGroupEntry {
2577                    binding: 1,
2578                    resource: wgpu::BindingResource::Sampler(&self.atlas_color.sampler),
2579                },
2580            ],
2581        })
2582    }
2583
2584    fn upload_glyph_mask(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
2585        let keyp = (key, px.to_bits());
2586        if let Some(info) = self.atlas_mask.map.get(&keyp) {
2587            return Some(*info);
2588        }
2589
2590        let gb = repose_text::rasterize(key, px)?;
2591        if gb.w == 0 || gb.h == 0 || gb.data.is_empty() {
2592            return None;
2593        }
2594
2595        let coverage = swash_to_a8_coverage(gb.content, &gb.data)?;
2596
2597        let w = gb.w.max(1);
2598        let h = gb.h.max(1);
2599
2600        if !self.alloc_space_mask(w, h) {
2601            self.grow_mask_and_rebuild();
2602        }
2603        if !self.alloc_space_mask(w, h) {
2604            return None;
2605        }
2606        let x = self.atlas_mask.next_x;
2607        let y = self.atlas_mask.next_y;
2608        self.atlas_mask.next_x += w + 1;
2609        self.atlas_mask.row_h = self.atlas_mask.row_h.max(h + 1);
2610
2611        let layout = wgpu::TexelCopyBufferLayout {
2612            offset: 0,
2613            bytes_per_row: Some(w),
2614            rows_per_image: Some(h),
2615        };
2616        let size = wgpu::Extent3d {
2617            width: w,
2618            height: h,
2619            depth_or_array_layers: 1,
2620        };
2621        self.queue.write_texture(
2622            wgpu::TexelCopyTextureInfoBase {
2623                texture: &self.atlas_mask.tex,
2624                mip_level: 0,
2625                origin: wgpu::Origin3d { x, y, z: 0 },
2626                aspect: wgpu::TextureAspect::All,
2627            },
2628            &coverage,
2629            layout,
2630            size,
2631        );
2632
2633        let info = GlyphInfo {
2634            u0: x as f32 / self.atlas_mask.size as f32,
2635            v0: y as f32 / self.atlas_mask.size as f32,
2636            u1: (x + w) as f32 / self.atlas_mask.size as f32,
2637            v1: (y + h) as f32 / self.atlas_mask.size as f32,
2638            w: w as f32,
2639            h: h as f32,
2640            bearing_x: 0.0,
2641            bearing_y: 0.0,
2642            advance: 0.0,
2643        };
2644        self.atlas_mask.map.insert(keyp, info);
2645        Some(info)
2646    }
2647
2648    fn upload_glyph_color(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
2649        let keyp = (key, px.to_bits());
2650        if let Some(info) = self.atlas_color.map.get(&keyp) {
2651            return Some(*info);
2652        }
2653        let gb = repose_text::rasterize(key, px)?;
2654        if !matches!(gb.content, repose_text::SwashContent::Color) {
2655            return None;
2656        }
2657        let w = gb.w.max(1);
2658        let h = gb.h.max(1);
2659        if !self.alloc_space_color(w, h) {
2660            self.grow_color_and_rebuild();
2661        }
2662        if !self.alloc_space_color(w, h) {
2663            return None;
2664        }
2665        let x = self.atlas_color.next_x;
2666        let y = self.atlas_color.next_y;
2667        self.atlas_color.next_x += w + 1;
2668        self.atlas_color.row_h = self.atlas_color.row_h.max(h + 1);
2669
2670        let layout = wgpu::TexelCopyBufferLayout {
2671            offset: 0,
2672            bytes_per_row: Some(w * 4),
2673            rows_per_image: Some(h),
2674        };
2675        let size = wgpu::Extent3d {
2676            width: w,
2677            height: h,
2678            depth_or_array_layers: 1,
2679        };
2680        self.queue.write_texture(
2681            wgpu::TexelCopyTextureInfoBase {
2682                texture: &self.atlas_color.tex,
2683                mip_level: 0,
2684                origin: wgpu::Origin3d { x, y, z: 0 },
2685                aspect: wgpu::TextureAspect::All,
2686            },
2687            &gb.data,
2688            layout,
2689            size,
2690        );
2691        let info = GlyphInfo {
2692            u0: x as f32 / self.atlas_color.size as f32,
2693            v0: y as f32 / self.atlas_color.size as f32,
2694            u1: (x + w) as f32 / self.atlas_color.size as f32,
2695            v1: (y + h) as f32 / self.atlas_color.size as f32,
2696            w: w as f32,
2697            h: h as f32,
2698            bearing_x: 0.0,
2699            bearing_y: 0.0,
2700            advance: 0.0,
2701        };
2702        self.atlas_color.map.insert(keyp, info);
2703        Some(info)
2704    }
2705
2706    fn alloc_space_mask(&mut self, w: u32, h: u32) -> bool {
2707        if self.atlas_mask.next_x + w + 1 >= self.atlas_mask.size {
2708            self.atlas_mask.next_x = 1;
2709            self.atlas_mask.next_y += self.atlas_mask.row_h + 1;
2710            self.atlas_mask.row_h = 0;
2711        }
2712        if self.atlas_mask.next_y + h + 1 >= self.atlas_mask.size {
2713            return false;
2714        }
2715        true
2716    }
2717
2718    fn grow_mask_and_rebuild(&mut self) {
2719        let new_size = (self.atlas_mask.size * 2).min(4096);
2720        if new_size == self.atlas_mask.size {
2721            return;
2722        }
2723        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2724            label: Some("glyph atlas A8 (grown)"),
2725            size: wgpu::Extent3d {
2726                width: new_size,
2727                height: new_size,
2728                depth_or_array_layers: 1,
2729            },
2730            mip_level_count: 1,
2731            sample_count: 1,
2732            dimension: wgpu::TextureDimension::D2,
2733            format: wgpu::TextureFormat::R8Unorm,
2734            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2735            view_formats: &[],
2736        });
2737        self.atlas_mask.tex = tex;
2738        self.atlas_mask.view = self
2739            .atlas_mask
2740            .tex
2741            .create_view(&wgpu::TextureViewDescriptor::default());
2742        self.atlas_mask.size = new_size;
2743        self.atlas_mask.next_x = 1;
2744        self.atlas_mask.next_y = 1;
2745        self.atlas_mask.row_h = 0;
2746        let keys: Vec<(repose_text::GlyphKey, u32)> = self.atlas_mask.map.keys().copied().collect();
2747        self.atlas_mask.map.clear();
2748        for (k, px_bits) in keys {
2749            let _ = self.upload_glyph_mask(k, f32::from_bits(px_bits));
2750        }
2751    }
2752
2753    fn alloc_space_color(&mut self, w: u32, h: u32) -> bool {
2754        if self.atlas_color.next_x + w + 1 >= self.atlas_color.size {
2755            self.atlas_color.next_x = 1;
2756            self.atlas_color.next_y += self.atlas_color.row_h + 1;
2757            self.atlas_color.row_h = 0;
2758        }
2759        if self.atlas_color.next_y + h + 1 >= self.atlas_color.size {
2760            return false;
2761        }
2762        true
2763    }
2764
2765    fn grow_color_and_rebuild(&mut self) {
2766        let new_size = (self.atlas_color.size * 2).min(4096);
2767        if new_size == self.atlas_color.size {
2768            return;
2769        }
2770        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2771            label: Some("glyph atlas RGBA (grown)"),
2772            size: wgpu::Extent3d {
2773                width: new_size,
2774                height: new_size,
2775                depth_or_array_layers: 1,
2776            },
2777            mip_level_count: 1,
2778            sample_count: 1,
2779            dimension: wgpu::TextureDimension::D2,
2780            format: wgpu::TextureFormat::Rgba8UnormSrgb,
2781            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2782            view_formats: &[],
2783        });
2784        self.atlas_color.tex = tex;
2785        self.atlas_color.view = self
2786            .atlas_color
2787            .tex
2788            .create_view(&wgpu::TextureViewDescriptor::default());
2789        self.atlas_color.size = new_size;
2790        self.atlas_color.next_x = 1;
2791        self.atlas_color.next_y = 1;
2792        self.atlas_color.row_h = 0;
2793        let keys: Vec<(repose_text::GlyphKey, u32)> =
2794            self.atlas_color.map.keys().copied().collect();
2795        self.atlas_color.map.clear();
2796        for (k, px_bits) in keys {
2797            let _ = self.upload_glyph_color(k, f32::from_bits(px_bits));
2798        }
2799    }
2800}
2801
2802fn brush_to_instance_fields(brush: &Brush) -> (u32, [f32; 4], [f32; 4], [f32; 2], [f32; 2]) {
2803    match brush {
2804        Brush::Solid(c) => (
2805            0u32,
2806            c.to_linear(),
2807            [0.0, 0.0, 0.0, 0.0],
2808            [0.0, 0.0],
2809            [0.0, 1.0],
2810        ),
2811        Brush::Linear {
2812            start,
2813            end,
2814            start_color,
2815            end_color,
2816        } => (
2817            1u32,
2818            start_color.to_linear(),
2819            end_color.to_linear(),
2820            [start.x, start.y],
2821            [end.x, end.y],
2822        ),
2823        _ => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
2824    }
2825}
2826
2827fn brush_to_solid_color(brush: &Brush) -> [f32; 4] {
2828    match brush {
2829        Brush::Solid(c) => c.to_linear(),
2830        Brush::Linear { start_color, .. } => start_color.to_linear(),
2831        _ => [0.0; 4],
2832    }
2833}
2834
2835fn init_atlas_mask(device: &wgpu::Device) -> AtlasA8 {
2836    let size = 1024u32;
2837    let tex = device.create_texture(&wgpu::TextureDescriptor {
2838        label: Some("glyph atlas A8"),
2839        size: wgpu::Extent3d {
2840            width: size,
2841            height: size,
2842            depth_or_array_layers: 1,
2843        },
2844        mip_level_count: 1,
2845        sample_count: 1,
2846        dimension: wgpu::TextureDimension::D2,
2847        format: wgpu::TextureFormat::R8Unorm,
2848        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2849        view_formats: &[],
2850    });
2851    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2852    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2853        label: Some("glyph atlas sampler A8"),
2854        address_mode_u: wgpu::AddressMode::ClampToEdge,
2855        address_mode_v: wgpu::AddressMode::ClampToEdge,
2856        address_mode_w: wgpu::AddressMode::ClampToEdge,
2857        mag_filter: wgpu::FilterMode::Linear,
2858        min_filter: wgpu::FilterMode::Linear,
2859        mipmap_filter: wgpu::MipmapFilterMode::Linear,
2860        ..Default::default()
2861    });
2862
2863    AtlasA8 {
2864        tex,
2865        view,
2866        sampler,
2867        size,
2868        next_x: 1,
2869        next_y: 1,
2870        row_h: 0,
2871        map: HashMap::new(),
2872    }
2873}
2874
2875fn init_atlas_color(device: &wgpu::Device) -> AtlasRGBA {
2876    let size = 1024u32;
2877    let tex = device.create_texture(&wgpu::TextureDescriptor {
2878        label: Some("glyph atlas RGBA"),
2879        size: wgpu::Extent3d {
2880            width: size,
2881            height: size,
2882            depth_or_array_layers: 1,
2883        },
2884        mip_level_count: 1,
2885        sample_count: 1,
2886        dimension: wgpu::TextureDimension::D2,
2887        format: wgpu::TextureFormat::Rgba8UnormSrgb,
2888        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2889        view_formats: &[],
2890    });
2891    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2892    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2893        label: Some("glyph atlas sampler RGBA"),
2894        address_mode_u: wgpu::AddressMode::ClampToEdge,
2895        address_mode_v: wgpu::AddressMode::ClampToEdge,
2896        address_mode_w: wgpu::AddressMode::ClampToEdge,
2897        mag_filter: wgpu::FilterMode::Linear,
2898        min_filter: wgpu::FilterMode::Linear,
2899        mipmap_filter: wgpu::MipmapFilterMode::Linear,
2900        ..Default::default()
2901    });
2902    AtlasRGBA {
2903        tex,
2904        view,
2905        sampler,
2906        size,
2907        next_x: 1,
2908        next_y: 1,
2909        row_h: 0,
2910        map: HashMap::new(),
2911    }
2912}
2913
2914#[cfg(feature = "winit-surface")]
2915impl RenderBackend for WgpuSurfaceBackend {
2916    fn configure_surface(&mut self, width: u32, height: u32) {
2917        if width == 0 || height == 0 {
2918            return;
2919        }
2920        self.renderer.output_width = width;
2921        self.renderer.output_height = height;
2922        if let Some(ref mut config) = self.surface_config {
2923            config.width = width;
2924            config.height = height;
2925        }
2926        if let (Some(surface), Some(config)) = (self.surface.as_ref(), self.surface_config.as_ref()) {
2927            surface.configure(&self.renderer.device, config);
2928        }
2929        self.renderer.recreate_msaa_and_depth_stencil();
2930        self.renderer.recreate_working_space_texture();
2931    }
2932
2933    fn frame(&mut self, scene: &Scene, _glyph_cfg: GlyphRasterConfig) {
2934        let surface = self.surface.as_ref().expect("WgpuSurfaceBackend::frame() requires a surface (use from_device + render_to_view instead)");
2935        let surface_config = self.surface_config.as_ref().expect("surface_config required for frame()");
2936
2937        self.renderer.frame_index = self.renderer.frame_index.wrapping_add(1);
2938        self.renderer.slug_cache.next_frame();
2939
2940        if self.renderer.output_width == 0 || self.renderer.output_height == 0 {
2941            return;
2942        }
2943
2944        let mut retries = 0u32;
2945        const MAX_RETRIES: u32 = 4;
2946        let frame = loop {
2947            match surface.get_current_texture() {
2948                wgpu::CurrentSurfaceTexture::Success(f) => break f,
2949                wgpu::CurrentSurfaceTexture::Suboptimal(f) => {
2950                    log::warn!("suboptimal surface; reconfiguring");
2951                    surface.configure(&self.renderer.device, surface_config);
2952                    break f;
2953                }
2954                wgpu::CurrentSurfaceTexture::Outdated => {
2955                    retries += 1;
2956                    if retries >= MAX_RETRIES {
2957                        log::warn!("surface outdated persisted after {MAX_RETRIES} retries; skipping frame");
2958                        return;
2959                    }
2960                    log::warn!("surface outdated; reconfiguring");
2961                    surface.configure(&self.renderer.device, surface_config);
2962                }
2963                wgpu::CurrentSurfaceTexture::Lost => {
2964                    retries += 1;
2965                    if retries >= MAX_RETRIES {
2966                        log::warn!("surface lost persisted after {MAX_RETRIES} retries; skipping frame");
2967                        return;
2968                    }
2969                    log::warn!("surface lost; reconfiguring");
2970                    surface.configure(&self.renderer.device, surface_config);
2971                }
2972                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
2973                    request_frame();
2974                    return;
2975                }
2976                wgpu::CurrentSurfaceTexture::Validation => {
2977                    retries += 1;
2978                    if retries >= MAX_RETRIES {
2979                        log::warn!("surface validation persisted after {MAX_RETRIES} retries; skipping frame");
2980                        return;
2981                    }
2982                    surface.configure(&self.renderer.device, surface_config);
2983                }
2984            }
2985        };
2986
2987        let swap_view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
2988        let mut encoder = self.renderer.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2989            label: Some("frame encoder"),
2990        });
2991
2992        let clear_color = Some([
2993            scene.clear_color.0 as f64 / 255.0,
2994            scene.clear_color.1 as f64 / 255.0,
2995            scene.clear_color.2 as f64 / 255.0,
2996            scene.clear_color.3 as f64 / 255.0,
2997        ]);
2998
2999        self.renderer.render_scene_to_encoder(scene, &mut encoder, &swap_view, clear_color);
3000
3001        self.renderer.queue.submit(std::iter::once(encoder.finish()));
3002        if let Err(e) = catch_unwind(AssertUnwindSafe(|| self.renderer.queue.present(frame))) {
3003            log::warn!("queue.present panicked: {:?}", e);
3004        }
3005    }
3006}
3007
3008impl WgpuSceneRenderer {
3009    pub fn render_scene_to_encoder(
3010        &mut self,
3011        scene: &Scene,
3012        encoder: &mut wgpu::CommandEncoder,
3013        target_view: &wgpu::TextureView,
3014        clear_color_override: Option<[f64; 4]>,
3015    ) {
3016        fn to_ndc(x: f32, y: f32, w: f32, h: f32, fb_w: f32, fb_h: f32) -> [f32; 4] {
3017            let x0 = (x / fb_w) * 2.0 - 1.0;
3018            let y0 = 1.0 - (y / fb_h) * 2.0;
3019            let x1 = ((x + w) / fb_w) * 2.0 - 1.0;
3020            let y1 = 1.0 - ((y + h) / fb_h) * 2.0;
3021            let min_x = x0.min(x1);
3022            let min_y = y0.min(y1);
3023            let w_ndc = (x1 - x0).abs();
3024            let h_ndc = (y1 - y0).abs();
3025            [min_x, min_y, w_ndc, h_ndc]
3026        }
3027
3028        /// Convert a local-space rect + transform to NDC center-based position+size and rotation.
3029        fn rect_to_instance_ndc(
3030            rect: repose_core::Rect,
3031            transform: &Transform,
3032            fb_w: f32,
3033            fb_h: f32,
3034        ) -> ([f32; 4], [f32; 2]) {
3035            let cx = rect.x + rect.w * 0.5;
3036            let cy = rect.y + rect.h * 0.5;
3037
3038            // Apply full transform to center
3039            let sx = cx * transform.scale_x;
3040            let sy = cy * transform.scale_y;
3041            let cos_a = transform.rotate.cos();
3042            let sin_a = transform.rotate.sin();
3043            let tx = sx * cos_a - sy * sin_a + transform.translate_x;
3044            let ty = sx * sin_a + sy * cos_a + transform.translate_y;
3045
3046            // NDC center
3047            let ndc_cx = (tx / fb_w) * 2.0 - 1.0;
3048            let ndc_cy = 1.0 - (ty / fb_h) * 2.0;
3049            // NDC size (after scale only, no rotation - rotation is done in shader)
3050            let ndc_w = (rect.w * transform.scale_x / fb_w) * 2.0;
3051            let ndc_h = (rect.h * transform.scale_y / fb_h) * 2.0;
3052
3053            ([ndc_cx, ndc_cy, ndc_w, ndc_h], [cos_a, sin_a])
3054        }
3055
3056        fn to_scissor(r: &repose_core::Rect, fb_w: u32, fb_h: u32) -> (u32, u32, u32, u32) {
3057            let mut x = r.x.floor() as i64;
3058            let mut y = r.y.floor() as i64;
3059            let fb_wi = fb_w as i64;
3060            let fb_hi = fb_h as i64;
3061            x = x.clamp(0, fb_wi.saturating_sub(1));
3062            y = y.clamp(0, fb_hi.saturating_sub(1));
3063            let w_req = r.w.ceil().max(1.0) as i64;
3064            let h_req = r.h.ceil().max(1.0) as i64;
3065            let w = (w_req).min(fb_wi - x).max(1);
3066            let h = (h_req).min(fb_hi - y).max(1);
3067            (x as u32, y as u32, w as u32, h as u32)
3068        }
3069
3070        let fb_w = self.output_width as f32;
3071        let fb_h = self.output_height as f32;
3072
3073        let globals = Globals {
3074            ndc_to_px: [fb_w * 0.5, fb_h * 0.5],
3075            _pad: [0.0, 0.0],
3076        };
3077        self.queue
3078            .write_buffer(&self.globals_buf, 0, bytemuck::bytes_of(&globals));
3079
3080        let mut passes: Vec<Pass> = Vec::with_capacity(1);
3081        let clear_color = clear_color_override.unwrap_or_else(|| {
3082            [
3083                scene.clear_color.0 as f64 / 255.0,
3084                scene.clear_color.1 as f64 / 255.0,
3085                scene.clear_color.2 as f64 / 255.0,
3086                scene.clear_color.3 as f64 / 255.0,
3087            ]
3088        });
3089        let mut current_pass: Pass = Pass {
3090            target: PassTarget::Surface,
3091            initial_scissor: (0, 0, self.output_width, self.output_height),
3092            clear_color: Some([
3093                clear_color[0] as f32,
3094                clear_color[1] as f32,
3095                clear_color[2] as f32,
3096                clear_color[3] as f32,
3097            ]),
3098            cmds: Vec::with_capacity(scene.nodes.len()),
3099        };
3100        let mut target_stack: Vec<PassTarget> = Vec::new();
3101        let mut layer_alphas: Vec<(u32, f32, (u32, u32, u32, u32))> = Vec::new();
3102        let mut layer_blurs: Vec<(u32, f32, f32)> = Vec::new();
3103        let mut current_target_size: (f32, f32) = (fb_w, fb_h);
3104
3105        struct Batch {
3106            rects: Vec<RectInstance>,
3107            borders: Vec<BorderInstance>,
3108            ellipses: Vec<EllipseInstance>,
3109            e_borders: Vec<EllipseBorderInstance>,
3110            arcs: Vec<ArcInstance>,
3111            masks: Vec<GlyphInstance>,
3112            colors: Vec<GlyphInstance>,
3113            nv12s: Vec<Nv12Instance>,
3114        }
3115
3116        impl Batch {
3117            fn new() -> Self {
3118                Self {
3119                    rects: vec![],
3120                    borders: vec![],
3121                    ellipses: vec![],
3122                    e_borders: vec![],
3123                    arcs: vec![],
3124                    masks: vec![],
3125                    colors: vec![],
3126                    nv12s: vec![],
3127                }
3128            }
3129
3130            fn is_empty(&self) -> bool {
3131                self.rects.is_empty()
3132                    && self.borders.is_empty()
3133                    && self.ellipses.is_empty()
3134                    && self.e_borders.is_empty()
3135                    && self.arcs.is_empty()
3136                    && self.masks.is_empty()
3137                    && self.colors.is_empty()
3138                    && self.nv12s.is_empty()
3139            }
3140
3141            fn flush(
3142                &mut self,
3143                pipes: (
3144                    &mut InstancedPipe<RectInstance>,
3145                    &mut InstancedPipe<BorderInstance>,
3146                    &mut InstancedPipe<EllipseInstance>,
3147                    &mut InstancedPipe<EllipseBorderInstance>,
3148                    &mut InstancedPipe<ArcInstance>,
3149                ),
3150                glyph_pipes: (
3151                    &mut InstancedPipe<GlyphInstance>,
3152                    &mut InstancedPipe<GlyphInstance>,
3153                ),
3154                nv12_pipe: &mut InstancedPipe<Nv12Instance>,
3155                device: &wgpu::Device,
3156                queue: &wgpu::Queue,
3157                cmds: &mut Vec<Cmd>,
3158            ) {
3159                let (rects, borders, ellipses, e_borders, arcs) = pipes;
3160                let (masks, colors) = glyph_pipes;
3161
3162                macro_rules! flush_one {
3163                    ($buf:ident, $pipe:expr, $variant:ident) => {
3164                        if !self.$buf.is_empty() {
3165                            if let Some((off, cnt)) = $pipe.upload(device, queue, &self.$buf) {
3166                                cmds.push(Cmd::$variant { off, cnt });
3167                            }
3168                            self.$buf.clear();
3169                        }
3170                    };
3171                }
3172
3173                flush_one!(rects, rects, Rect);
3174                flush_one!(borders, borders, Border);
3175                flush_one!(ellipses, ellipses, Ellipse);
3176                flush_one!(e_borders, e_borders, EllipseBorder);
3177                flush_one!(arcs, arcs, Arc);
3178                flush_one!(masks, masks, GlyphsMask);
3179                flush_one!(colors, colors, GlyphsColor);
3180
3181                if !self.nv12s.is_empty() {
3182                    if let Some((off, cnt)) = nv12_pipe.upload(device, queue, &self.nv12s) {
3183                        let _ = (off, cnt);
3184                    }
3185                    self.nv12s.clear();
3186                }
3187            }
3188        }
3189
3190        self.rects.reset();
3191        self.borders.reset();
3192        self.ellipses.reset();
3193        self.ellipse_borders.reset();
3194        self.arcs.reset();
3195        self.glyph_mask.reset();
3196        self.glyph_color.reset();
3197        self.clip_ring.reset();
3198        self.blur_ring.reset();
3199        self.nv12.reset();
3200
3201        self.slug_ring.reset();
3202        let mut batch = Batch::new();
3203        let mut slug_verts_local: Vec<slug::TessVertex> = Vec::new();
3204        let mut transform_stack: Vec<Transform> = vec![Transform::identity()];
3205        let mut scissor_stack: Vec<repose_core::Rect> = Vec::with_capacity(8);
3206        let root_clip_rect = repose_core::Rect {
3207            x: 0.0,
3208            y: 0.0,
3209            w: fb_w,
3210            h: fb_h,
3211        };
3212
3213        let mut current_prim: Option<&'static str> = None;
3214
3215        macro_rules! flush_if_prim_changed {
3216            ($prim:literal, $pipe:expr) => {
3217                if current_prim != Some($prim) {
3218                    flush_batch!();
3219                    current_prim = Some($prim);
3220                }
3221            };
3222        }
3223
3224        macro_rules! flush_batch {
3225            () => {
3226                if !batch.is_empty() {
3227                    batch.flush(
3228                        (
3229                            &mut self.rects,
3230                            &mut self.borders,
3231                            &mut self.ellipses,
3232                            &mut self.ellipse_borders,
3233                            &mut self.arcs,
3234                        ),
3235                        (&mut self.glyph_mask, &mut self.glyph_color),
3236                        &mut self.nv12,
3237                        &self.device,
3238                        &self.queue,
3239                        &mut current_pass.cmds,
3240                    )
3241                }
3242            };
3243        }
3244        for node in &scene.nodes {
3245            let t_identity = Transform::identity();
3246            let current_transform = transform_stack.last().unwrap_or(&t_identity);
3247
3248            match node {
3249                SceneNode::Rect {
3250                    rect,
3251                    brush,
3252                    radius,
3253                } => {
3254                    flush_if_prim_changed!("rect", &self.rects);
3255                    let (ndc, sin_cos) = rect_to_instance_ndc(
3256                        *rect,
3257                        current_transform,
3258                        current_target_size.0,
3259                        current_target_size.1,
3260                    );
3261                    let (brush_type, color0, color1, grad_start, grad_end) =
3262                        brush_to_instance_fields(brush);
3263                    batch.rects.push(RectInstance {
3264                        xywh: ndc,
3265                        radii: *radius,
3266                        brush_type,
3267                        _pad: [0.0; 3],
3268                        color0,
3269                        color1,
3270                        grad_start,
3271                        grad_end,
3272                        sin_cos,
3273                    });
3274                }
3275                SceneNode::Border {
3276                    rect,
3277                    color,
3278                    width,
3279                    radius,
3280                } => {
3281                    flush_if_prim_changed!("border", &self.borders);
3282                    let (ndc, sin_cos) = rect_to_instance_ndc(
3283                        *rect,
3284                        current_transform,
3285                        current_target_size.0,
3286                        current_target_size.1,
3287                    );
3288                    batch.borders.push(BorderInstance {
3289                        xywh: ndc,
3290                        radii: *radius,
3291                        stroke: *width,
3292                        color: color.to_linear(),
3293                        sin_cos,
3294                    });
3295                }
3296                SceneNode::Ellipse { rect, brush } => {
3297                    flush_if_prim_changed!("ellipse", &self.ellipses);
3298                    let (ndc, sin_cos) = rect_to_instance_ndc(
3299                        *rect,
3300                        current_transform,
3301                        current_target_size.0,
3302                        current_target_size.1,
3303                    );
3304                    let color = brush_to_solid_color(brush);
3305                    batch.ellipses.push(EllipseInstance {
3306                        xywh: ndc,
3307                        color,
3308                        sin_cos,
3309                    });
3310                }
3311                SceneNode::EllipseBorder { rect, color, width } => {
3312                    flush_if_prim_changed!("ellipse_border", &self.ellipse_borders);
3313                    let (ndc, sin_cos) = rect_to_instance_ndc(
3314                        *rect,
3315                        current_transform,
3316                        current_target_size.0,
3317                        current_target_size.1,
3318                    );
3319                    let pad_px = *width * 0.5 + 2.0;
3320                    let pad = (pad_px / current_target_size.0) * 2.0;
3321                    batch.e_borders.push(EllipseBorderInstance {
3322                        xywh: ndc,
3323                        stroke: *width,
3324                        pad,
3325                        color: color.to_linear(),
3326                        sin_cos,
3327                    });
3328                }
3329                SceneNode::Arc {
3330                    rect,
3331                    start_angle,
3332                    sweep_angle,
3333                    stroke_width,
3334                    color,
3335                    cap,
3336                } => {
3337                    flush_if_prim_changed!("arc", &self.arcs);
3338                    let (ndc, sin_cos) = rect_to_instance_ndc(
3339                        *rect,
3340                        current_transform,
3341                        current_target_size.0,
3342                        current_target_size.1,
3343                    );
3344                    let pad_px = *stroke_width * 0.5 + 2.0;
3345                    let pad = (pad_px / current_target_size.0) * 2.0;
3346                    let cap_val = match cap {
3347                        StrokeCap::Butt => 0.0,
3348                        StrokeCap::Round => 1.0,
3349                        StrokeCap::Square => 2.0,
3350                    };
3351                    batch.arcs.push(ArcInstance {
3352                        xywh: ndc,
3353                        start_angle: *start_angle,
3354                        sweep_angle: *sweep_angle,
3355                        stroke: *stroke_width,
3356                        pad,
3357                        color: color.to_linear(),
3358                        sin_cos,
3359                        cap: cap_val,
3360                    });
3361                }
3362                SceneNode::Text {
3363                    rect,
3364                    text,
3365                    color,
3366                    size,
3367                    font_family,
3368                    text_align: _,
3369                    font_weight,
3370                    font_style,
3371                    text_decoration,
3372                    letter_spacing,
3373                    line_height: _,
3374                    extra_style,
3375                    url: _,
3376                    font_variation_settings,
3377                } => {
3378                    flush_batch!(); // flush any prior primitives
3379
3380                    let px = *size;
3381                    let lh_ratio = rect.h / px;
3382                    let fw = font_weight.0;
3383                    let fs = if *font_style == FontStyle::Italic {
3384                        1
3385                    } else {
3386                        0
3387                    };
3388                    let shaped = repose_text::shape_line(
3389                        text.as_ref(),
3390                        px,
3391                        lh_ratio,
3392                        *font_family,
3393                        fw,
3394                        fs,
3395                        *letter_spacing,
3396                        font_variation_settings.as_deref(),
3397                    );
3398                    let baseline_y = shaped.first().map(|g| rect.y + g.y);
3399
3400                    let cos_a = current_transform.rotate.cos();
3401                    let sin_a = current_transform.rotate.sin();
3402                    let has_rotation = current_transform.rotate != 0.0;
3403
3404                    // For rotated text, the pivot is the center of the text rect.
3405                    let pivot_x = rect.x + rect.w * 0.5;
3406                    let pivot_y = rect.y + rect.h * 0.5;
3407
3408                    // Helper: compute NDC for a glyph rect, handling rotation correctly.
3409                    let make_glyph_instance =
3410                        |gx: f32, gy: f32, gw: f32, gh: f32| -> ([f32; 4], [f32; 2]) {
3411                            if has_rotation {
3412                                let corners =
3413                                    [(gx, gy), (gx + gw, gy), (gx + gw, gy + gh), (gx, gy + gh)];
3414                                let mut min_x = f32::MAX;
3415                                let mut max_x = f32::MIN;
3416                                let mut min_y = f32::MAX;
3417                                let mut max_y = f32::MIN;
3418                                for &(x, y) in &corners {
3419                                    let dx = x - pivot_x;
3420                                    let dy = y - pivot_y;
3421                                    let rx = pivot_x + dx * cos_a - dy * sin_a;
3422                                    let ry = pivot_y + dx * sin_a + dy * cos_a;
3423                                    min_x = min_x.min(rx);
3424                                    max_x = max_x.max(rx);
3425                                    min_y = min_y.min(ry);
3426                                    max_y = max_y.max(ry);
3427                                }
3428                                let bb_w = max_x - min_x;
3429                                let bb_h = max_y - min_y;
3430                                let ndc_tl = to_ndc(
3431                                    min_x,
3432                                    min_y,
3433                                    bb_w,
3434                                    bb_h,
3435                                    current_target_size.0,
3436                                    current_target_size.1,
3437                                );
3438                                let ndc = [
3439                                    ndc_tl[0] + ndc_tl[2] * 0.5,
3440                                    ndc_tl[1] + ndc_tl[3] * 0.5,
3441                                    ndc_tl[2],
3442                                    ndc_tl[3],
3443                                ];
3444                                (ndc, [cos_a, sin_a])
3445                            } else {
3446                                rect_to_instance_ndc(
3447                                    repose_core::Rect {
3448                                        x: gx,
3449                                        y: gy,
3450                                        w: gw,
3451                                        h: gh,
3452                                    },
3453                                    current_transform,
3454                                    current_target_size.0,
3455                                    current_target_size.1,
3456                                )
3457                            }
3458                        };
3459
3460                    let baseline_shift_y: f32 = px * extra_style.baseline_shift.0;
3461
3462                    let (
3463                        is_stroke,
3464                        stroke_width,
3465                        stroke_cap,
3466                        stroke_join,
3467                        stroke_miter,
3468                        stroke_path_effect,
3469                    ) = match &extra_style.draw_style {
3470                        repose_core::DrawStyle::Stroke {
3471                            width,
3472                            cap,
3473                            join,
3474                            miter,
3475                            path_effect,
3476                        } => (true, *width, *cap, *join, *miter, path_effect.clone()),
3477                        _ => (
3478                            false,
3479                            0.0,
3480                            repose_core::StrokeCap::Butt,
3481                            repose_core::StrokeJoin::Miter,
3482                            4.0,
3483                            None,
3484                        ),
3485                    };
3486                    let stroke_tess_key = if is_stroke {
3487                        Some(slug::StrokeTessKey::new(
3488                            stroke_width,
3489                            stroke_cap,
3490                            stroke_join,
3491                            stroke_miter,
3492                            &stroke_path_effect,
3493                        ))
3494                    } else {
3495                        None
3496                    };
3497
3498                    for sg in shaped {
3499                        let gx = rect.x + sg.x + sg.bearing_x;
3500                        let gy = rect.y + sg.y - sg.bearing_y + baseline_shift_y;
3501
3502                        // Vector glyph path: tessellated geometry with MSAA.
3503                        if self.slug_enabled {
3504                            let ck = repose_text::lookup_cache_key(sg.key, sg.px);
3505                            if let Some(ref ck) = ck {
3506                                // Check if cached.
3507                                let need_tessellate = self.slug_cache.get(ck).map_or(true, |g| {
3508                                    if is_stroke {
3509                                        let key = stroke_tess_key.as_ref().unwrap();
3510                                        !g.stroke_variants.contains_key(key)
3511                                    } else {
3512                                        g.fill_vertices.is_none()
3513                                    }
3514                                });
3515                                if need_tessellate {
3516                                    if let Some((ck2, commands)) =
3517                                        repose_text::lookup_and_extract_outline(sg.key, sg.px)
3518                                    {
3519                                        let font_size_px = f32::from_bits(ck2.font_size_bits);
3520                                        if is_stroke {
3521                                            self.slug_cache.get_or_insert_stroke(
3522                                                ck2,
3523                                                font_size_px,
3524                                                &commands,
3525                                                stroke_width,
3526                                                stroke_cap,
3527                                                stroke_join,
3528                                                stroke_miter,
3529                                                &stroke_path_effect,
3530                                            );
3531                                        } else {
3532                                            self.slug_cache.get_or_insert(
3533                                                ck2,
3534                                                font_size_px,
3535                                                &commands,
3536                                            );
3537                                        }
3538                                    }
3539                                } else {
3540                                    self.slug_cache.touch(ck);
3541                                }
3542                            }
3543                            if let Some(entry) = ck.as_ref().and_then(|ck| self.slug_cache.get(ck))
3544                            {
3545                                let ox = rect.x + sg.x;
3546                                let oy = rect.y + sg.y + baseline_shift_y;
3547                                let scx = current_transform.scale_x;
3548                                let scy = current_transform.scale_y;
3549                                let ttx = current_transform.translate_x;
3550                                let tty = current_transform.translate_y;
3551
3552                                let tf = |x: f32, y: f32| -> (f32, f32) {
3553                                    if has_rotation {
3554                                        let dx = x - pivot_x;
3555                                        let dy = y - pivot_y;
3556                                        let rx = pivot_x + dx * cos_a - dy * sin_a;
3557                                        let ry = pivot_y + dx * sin_a + dy * cos_a;
3558                                        (rx, ry)
3559                                    } else {
3560                                        (x * scx + ttx, y * scy + tty)
3561                                    }
3562                                };
3563
3564                                let tw = current_target_size.0;
3565                                let th = current_target_size.1;
3566
3567                                let verts = if is_stroke {
3568                                    let key = stroke_tess_key.as_ref().unwrap();
3569                                    entry
3570                                        .stroke_variants
3571                                        .get(key)
3572                                        .map(|v| v.as_slice())
3573                                        .unwrap_or(&[])
3574                                } else {
3575                                    entry.fill_vertices.as_deref().unwrap_or(&[])
3576                                };
3577
3578                                for &v in verts {
3579                                    let (sx, sy) = tf(ox + v[0] * px, oy - v[1] * px);
3580                                    let ndc_x = sx / tw * 2.0 - 1.0;
3581                                    let ndc_y = -(sy / th) * 2.0 + 1.0;
3582                                    slug_verts_local.push(slug::TessVertex {
3583                                        ndc_pos: [ndc_x, ndc_y],
3584                                        color: color.to_linear(),
3585                                    });
3586                                }
3587
3588                                if is_stroke {
3589                                    // Stroke glyphs cannot use atlas fallback...
3590                                    continue;
3591                                }
3592                                continue;
3593                            }
3594                        }
3595
3596                        // Don't use atlas fallback for strokes too
3597                        if is_stroke {
3598                            continue;
3599                        }
3600
3601                        // Atlas fallback: color emoji + failed slug extraction
3602                        if let Some(info) = self.upload_glyph_color(sg.key, sg.px) {
3603                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
3604                            batch.colors.push(GlyphInstance {
3605                                xywh: ndc,
3606                                uv: [info.u0, info.v1, info.u1, info.v0],
3607                                color: color.to_linear(),
3608                                sin_cos,
3609                            });
3610                        } else if let Some(info) = self.upload_glyph_mask(sg.key, sg.px) {
3611                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
3612                            batch.masks.push(GlyphInstance {
3613                                xywh: ndc,
3614                                uv: [info.u0, info.v1, info.u1, info.v0],
3615                                color: color.to_linear(),
3616                                sin_cos,
3617                            });
3618                        }
3619                    }
3620
3621                    // Upload slug vertices if any
3622                    if !slug_verts_local.is_empty() {
3623                        let bytes = bytemuck::cast_slice(&slug_verts_local);
3624                        self.slug_ring.grow_to_fit(&self.device, bytes.len() as u64);
3625                        let (off, _) = self.slug_ring.alloc_write(&self.queue, bytes);
3626                        current_pass.cmds.push(Cmd::GlyphsVector {
3627                            off,
3628                            cnt: slug_verts_local.len() as u32,
3629                        });
3630                        slug_verts_local.clear();
3631                    }
3632
3633                    // Text decoration: underline / strikethrough
3634                    if (text_decoration.underline || text_decoration.strikethrough)
3635                        && let Some(baseline_y) = baseline_y
3636                    {
3637                        flush_batch!();
3638                        current_prim = Some("rect");
3639                        let deco_color = text_decoration.color.unwrap_or(*color);
3640                        let thickness = (px * 0.07).max(1.0);
3641
3642                        if text_decoration.underline {
3643                            let dy = baseline_y + px * 0.1;
3644                            let (ndc, sin_cos) = rect_to_instance_ndc(
3645                                repose_core::Rect {
3646                                    x: rect.x,
3647                                    y: dy,
3648                                    w: rect.w,
3649                                    h: thickness,
3650                                },
3651                                current_transform,
3652                                current_target_size.0,
3653                                current_target_size.1,
3654                            );
3655                            batch.rects.push(RectInstance {
3656                                xywh: ndc,
3657                                radii: [0.0; 4],
3658                                brush_type: 0,
3659                                _pad: [0.0; 3],
3660                                color0: deco_color.to_linear(),
3661                                color1: [0.0; 4],
3662                                grad_start: [0.0; 2],
3663                                grad_end: [0.0; 2],
3664                                sin_cos,
3665                            });
3666                        }
3667                        if text_decoration.strikethrough {
3668                            let sy = baseline_y - px * 0.3;
3669                            let (ndc, sin_cos) = rect_to_instance_ndc(
3670                                repose_core::Rect {
3671                                    x: rect.x,
3672                                    y: sy,
3673                                    w: rect.w,
3674                                    h: thickness,
3675                                },
3676                                current_transform,
3677                                current_target_size.0,
3678                                current_target_size.1,
3679                            );
3680                            batch.rects.push(RectInstance {
3681                                xywh: ndc,
3682                                radii: [0.0; 4],
3683                                brush_type: 0,
3684                                _pad: [0.0; 3],
3685                                color0: deco_color.to_linear(),
3686                                color1: [0.0; 4],
3687                                grad_start: [0.0; 2],
3688                                grad_end: [0.0; 2],
3689                                sin_cos,
3690                            });
3691                        }
3692                    }
3693                }
3694                SceneNode::Image {
3695                    rect,
3696                    handle,
3697                    tint,
3698                    fit,
3699                } => {
3700                    flush_batch!();
3701
3702                    // Update usage timestamp for eviction
3703                    let (img_w, img_h, is_nv12) = if let Some(t) = self.images.get_mut(handle) {
3704                        match t {
3705                            ImageTex::Rgba {
3706                                w,
3707                                h,
3708                                last_used_frame,
3709                                ..
3710                            } => {
3711                                *last_used_frame = self.frame_index;
3712                                (*w, *h, false)
3713                            }
3714                            ImageTex::Nv12 {
3715                                w,
3716                                h,
3717                                last_used_frame,
3718                                ..
3719                            } => {
3720                                *last_used_frame = self.frame_index;
3721                                (*w, *h, true)
3722                            }
3723                        }
3724                    } else {
3725                        log::warn!("Image handle {} not found", handle);
3726                        continue;
3727                    };
3728
3729                    let src_w = img_w as f32;
3730                    let src_h = img_h as f32;
3731                    let transformed = current_transform.apply_to_rect(*rect);
3732                    let dst_w = transformed.w.max(0.0);
3733                    let dst_h = transformed.h.max(0.0);
3734                    if dst_w <= 0.0 || dst_h <= 0.0 {
3735                        continue;
3736                    }
3737
3738                    let (xywh_ndc, uv_rect) = match fit {
3739                        repose_core::view::ImageFit::Contain => {
3740                            let scale = (dst_w / src_w).min(dst_h / src_h);
3741                            let w = src_w * scale;
3742                            let h = src_h * scale;
3743                            let x = transformed.x + (dst_w - w) * 0.5;
3744                            let y = transformed.y + (dst_h - h) * 0.5;
3745                            (
3746                                to_ndc(x, y, w, h, current_target_size.0, current_target_size.1),
3747                                [0.0, 1.0, 1.0, 0.0],
3748                            )
3749                        }
3750                        repose_core::view::ImageFit::Cover => {
3751                            let scale = (dst_w / src_w).max(dst_h / src_h);
3752                            let content_w = src_w * scale;
3753                            let content_h = src_h * scale;
3754                            let overflow_x = (content_w - dst_w) * 0.5;
3755                            let overflow_y = (content_h - dst_h) * 0.5;
3756                            let u0 = (overflow_x / content_w).clamp(0.0, 1.0);
3757                            let v0 = (overflow_y / content_h).clamp(0.0, 1.0);
3758                            let u1 = ((overflow_x + dst_w) / content_w).clamp(0.0, 1.0);
3759                            let v1 = ((overflow_y + dst_h) / content_h).clamp(0.0, 1.0);
3760                            (
3761                                to_ndc(
3762                                    transformed.x,
3763                                    transformed.y,
3764                                    dst_w,
3765                                    dst_h,
3766                                    current_target_size.0,
3767                                    current_target_size.1,
3768                                ),
3769                                [u0, 1.0 - v1, u1, 1.0 - v0],
3770                            )
3771                        }
3772                        repose_core::view::ImageFit::FitWidth => {
3773                            let scale = dst_w / src_w;
3774                            let w = dst_w;
3775                            let h = src_h * scale;
3776                            let y = transformed.y + (dst_h - h) * 0.5;
3777                            (
3778                                to_ndc(
3779                                    transformed.x,
3780                                    y,
3781                                    w,
3782                                    h,
3783                                    current_target_size.0,
3784                                    current_target_size.1,
3785                                ),
3786                                [0.0, 1.0, 1.0, 0.0],
3787                            )
3788                        }
3789                        repose_core::view::ImageFit::FitHeight => {
3790                            let scale = dst_h / src_h;
3791                            let w = src_w * scale;
3792                            let h = dst_h;
3793                            let x = transformed.x + (dst_w - w) * 0.5;
3794                            (
3795                                to_ndc(
3796                                    x,
3797                                    transformed.y,
3798                                    w,
3799                                    h,
3800                                    current_target_size.0,
3801                                    current_target_size.1,
3802                                ),
3803                                [0.0, 1.0, 1.0, 0.0],
3804                            )
3805                        }
3806                        _ => ([0.0; 4], [0.0; 4]),
3807                    };
3808
3809                    // Convert top-left based NDC to center-based for shader
3810                    let ndc_center = [
3811                        xywh_ndc[0] + xywh_ndc[2] * 0.5,
3812                        xywh_ndc[1] + xywh_ndc[3] * 0.5,
3813                        xywh_ndc[2],
3814                        xywh_ndc[3],
3815                    ];
3816
3817                    if is_nv12 {
3818                        let uv_x_offset = if let Some(ImageTex::Nv12 { w, color_info, .. }) =
3819                            self.images.get(handle)
3820                        {
3821                            match color_info.chroma_siting {
3822                                ChromaSiting::Center | ChromaSiting::TopLeft => 0.0,
3823                                ChromaSiting::Left => -1.0 / *w as f32,
3824                            }
3825                        } else {
3826                            0.0
3827                        };
3828
3829                        let inst = Nv12Instance {
3830                            xywh: ndc_center,
3831                            uv: uv_rect,
3832                            color: tint.to_linear(),
3833                            uv_x_offset,
3834                            sin_cos: [1.0, 0.0],
3835                            _pad: [0.0],
3836                        };
3837                        if let Some((off, _)) = self.nv12.upload(&self.device, &self.queue, &[inst])
3838                        {
3839                            current_pass.cmds.push(Cmd::ImageNv12 {
3840                                off,
3841                                cnt: 1,
3842                                handle: *handle,
3843                            });
3844                        }
3845                    } else {
3846                        // RGBA uses GlyphInstance struct (reused pipeline)
3847                        let inst = GlyphInstance {
3848                            xywh: ndc_center,
3849                            uv: uv_rect,
3850                            color: tint.to_linear(),
3851                            sin_cos: [1.0, 0.0],
3852                        };
3853                        if let Some((off, _)) =
3854                            self.glyph_color.upload(&self.device, &self.queue, &[inst])
3855                        {
3856                            current_pass.cmds.push(Cmd::ImageRgba {
3857                                off,
3858                                cnt: 1,
3859                                handle: *handle,
3860                            });
3861                        }
3862                    }
3863                }
3864                SceneNode::PushClip { rect, radius, op } => {
3865                    flush_batch!(); // flush content before entering clip
3866
3867                    let is_diff = matches!(op, repose_core::ClipOp::Difference);
3868
3869                    let t_identity = Transform::identity();
3870                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
3871                    let transformed = current_transform.apply_to_rect(*rect);
3872
3873                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
3874                    let next_scissor = if is_diff {
3875                        top
3876                    } else {
3877                        intersect(top, transformed)
3878                    };
3879                    scissor_stack.push(next_scissor);
3880                    let scissor = to_scissor(
3881                        &next_scissor,
3882                        current_target_size.0 as u32,
3883                        current_target_size.1 as u32,
3884                    );
3885
3886                    let clip_ndc_tl = to_ndc(
3887                        transformed.x,
3888                        transformed.y,
3889                        transformed.w,
3890                        transformed.h,
3891                        current_target_size.0,
3892                        current_target_size.1,
3893                    );
3894                    let inst = ClipInstance {
3895                        xywh: [
3896                            clip_ndc_tl[0] + clip_ndc_tl[2] * 0.5,
3897                            clip_ndc_tl[1] + clip_ndc_tl[3] * 0.5,
3898                            clip_ndc_tl[2],
3899                            clip_ndc_tl[3],
3900                        ],
3901                        radii: *radius,
3902                        sin_cos: [1.0, 0.0],
3903                    };
3904                    let bytes = bytemuck::bytes_of(&inst);
3905                    self.clip_ring.grow_to_fit(&self.device, bytes.len() as u64);
3906                    let (off, _) = self.clip_ring.alloc_write(&self.queue, bytes);
3907
3908                    let rounded = radius.iter().any(|&r| r > 0.5);
3909
3910                    current_pass.cmds.push(Cmd::ClipPush {
3911                        off,
3912                        cnt: 1,
3913                        scissor,
3914                        difference: is_diff,
3915                        rounded,
3916                    });
3917                }
3918                SceneNode::PopClip => {
3919                    flush_batch!();
3920
3921                    if !scissor_stack.is_empty() {
3922                        scissor_stack.pop();
3923                    } else {
3924                        log::warn!("PopClip with empty stack");
3925                    }
3926
3927                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
3928                    let scissor = to_scissor(
3929                        &top,
3930                        current_target_size.0 as u32,
3931                        current_target_size.1 as u32,
3932                    );
3933                    current_pass.cmds.push(Cmd::ClipPop { scissor });
3934                }
3935                SceneNode::Shadow {
3936                    rect,
3937                    radius,
3938                    elevation: _,
3939                    color,
3940                } => {
3941                    flush_if_prim_changed!("rect", &self.rects);
3942                    let (ndc, sin_cos) = rect_to_instance_ndc(
3943                        *rect,
3944                        current_transform,
3945                        current_target_size.0,
3946                        current_target_size.1,
3947                    );
3948                    let (brush_type, color0, _color1, _grad_start, _grad_end) =
3949                        brush_to_instance_fields(&Brush::Solid(*color));
3950                    batch.rects.push(RectInstance {
3951                        xywh: ndc,
3952                        radii: *radius,
3953                        brush_type,
3954                        _pad: [0.0; 3],
3955                        color0,
3956                        color1: [0.0; 4],
3957                        grad_start: [0.0; 2],
3958                        grad_end: [0.0; 2],
3959                        sin_cos,
3960                    });
3961                }
3962                SceneNode::PushTransform { transform } => {
3963                    flush_batch!(); // flush before transform change
3964                    let combined = current_transform.combine(transform);
3965                    transform_stack.push(combined);
3966                }
3967                SceneNode::PopTransform => {
3968                    flush_batch!(); // flush before transform change
3969                    transform_stack.pop();
3970                }
3971                SceneNode::BeginLayer {
3972                    rect,
3973                    layer_id,
3974                    alpha,
3975                    blur_radius_x,
3976                    blur_radius_y,
3977                    rectangle_edge: _,
3978                } => {
3979                    flush_batch!();
3980                    let w = (rect.w.max(1.0)).ceil() as u32;
3981                    let h = (rect.h.max(1.0)).ceil() as u32;
3982                    // Close out the current pass, start a new one for the layer.
3983                    let prev_target = current_pass.target;
3984                    let prev_scissor = current_pass.initial_scissor;
3985                    let saved = std::mem::replace(
3986                        &mut current_pass,
3987                        Pass {
3988                            target: PassTarget::Layer(*layer_id),
3989                            initial_scissor: (0, 0, w, h),
3990                            clear_color: Some([0.0, 0.0, 0.0, 0.0]),
3991                            cmds: Vec::new(),
3992                        },
3993                    );
3994                    passes.push(saved);
3995                    target_stack.push(prev_target);
3996                    let _ = prev_scissor; // initial_scissor of resumed pass is restored at EndLayer
3997                    // Get or create the layer's offscreen texture now so that
3998                    // subsequent scissor ops / draws have a valid target.
3999                    self.get_or_create_layer(*layer_id, w, h, *rect);
4000                    current_target_size = (w as f32, h as f32);
4001                    layer_alphas.push((*layer_id, *alpha, current_pass.initial_scissor));
4002                    // Store blur info for post-processing after EndLayer
4003                    if *blur_radius_x > 0.0 || *blur_radius_y > 0.0 {
4004                        layer_blurs.push((*layer_id, *blur_radius_x, *blur_radius_y));
4005                    }
4006                }
4007                SceneNode::EndLayer { layer_id } => {
4008                    flush_batch!();
4009                    // Finish the layer's pass, start a new one on the previous target.
4010                    let saved = std::mem::replace(
4011                        &mut current_pass,
4012                        Pass {
4013                            target: target_stack.pop().unwrap_or(PassTarget::Surface),
4014                            initial_scissor: (0, 0, self.output_width, self.output_height),
4015                            clear_color: None, // LoadOp::Load - don't wipe earlier surface content
4016                            cmds: Vec::new(),
4017                        },
4018                    );
4019                    passes.push(saved);
4020                    current_target_size = (fb_w, fb_h);
4021                    // Issue a composite quad for the just-finished layer in the new pass.
4022                    if let Some((_, layer_alpha, _)) = layer_alphas
4023                        .iter()
4024                        .find(|(id, _, _)| id == layer_id)
4025                        .copied()
4026                    {
4027                        let layer = self.layer_pool.get(layer_id).expect("layer target");
4028                        let ndc_tl = to_ndc(
4029                            layer.rect_px.0,
4030                            layer.rect_px.1,
4031                            layer.rect_px.2,
4032                            layer.rect_px.3,
4033                            fb_w,
4034                            fb_h,
4035                        );
4036                        // Check if this layer needs content blur
4037                        let blur_px_val = layer_blurs
4038                            .iter()
4039                            .find(|(id, _, _)| id == layer_id)
4040                            .map(|(_, bx, by)| (*bx, *by));
4041                        if let Some((blur_x, blur_y)) =
4042                            blur_px_val.filter(|(bx, by)| *bx > 0.0 || *by > 0.0)
4043                        {
4044                            // Content blur: draw blurred version using the blur_content pipeline
4045                            let bw_uv = (blur_x * 1.5) / layer.width.max(1) as f32;
4046                            let bh_uv = (blur_y * 1.5) / layer.height.max(1) as f32;
4047                            let inst = BlurInstance {
4048                                xywh: [
4049                                    ndc_tl[0] + ndc_tl[2] * 0.5,
4050                                    ndc_tl[1] + ndc_tl[3] * 0.5,
4051                                    ndc_tl[2],
4052                                    ndc_tl[3],
4053                                ],
4054                                uv: [0.0, 0.0, 1.0, 1.0],
4055                                color: [1.0, 1.0, 1.0, layer_alpha],
4056                                blur_uv: [bw_uv, bh_uv],
4057                                sin_cos: [1.0, 0.0],
4058                            };
4059                            self.blur_ring.grow_to_fit(
4060                                &self.device,
4061                                std::mem::size_of::<BlurInstance>() as u64,
4062                            );
4063                            let bytes = bytemuck::bytes_of(&inst);
4064                            let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
4065                            current_pass.cmds.push(Cmd::CompositeBlur {
4066                                off,
4067                                cnt: 1,
4068                                layer_id: *layer_id,
4069                            });
4070                        } else {
4071                            // Normal sharp composite
4072                            let inst = GlyphInstance {
4073                                xywh: [
4074                                    ndc_tl[0] + ndc_tl[2] * 0.5,
4075                                    ndc_tl[1] + ndc_tl[3] * 0.5,
4076                                    ndc_tl[2],
4077                                    ndc_tl[3],
4078                                ],
4079                                uv: [0.0, 1.0, 1.0, 0.0],
4080                                color: [1.0, 1.0, 1.0, layer_alpha],
4081                                sin_cos: [1.0, 0.0],
4082                            };
4083                            if let Some((off, cnt)) =
4084                                self.glyph_color.upload(&self.device, &self.queue, &[inst])
4085                            {
4086                                current_pass.cmds.push(Cmd::CompositeLayer {
4087                                    off,
4088                                    cnt,
4089                                    layer_id: *layer_id,
4090                                    alpha: layer_alpha,
4091                                });
4092                            }
4093                        }
4094                    }
4095                }
4096                SceneNode::CompositeShadow {
4097                    layer_id,
4098                    blur_px,
4099                    offset_px,
4100                    color,
4101                } => {
4102                    flush_batch!();
4103                    if let Some(layer) = self.layer_pool.get(layer_id).cloned() {
4104                        // Shadow rect = layer rect + offset.
4105                        let sx = layer.rect_px.0 + offset_px.0;
4106                        let sy = layer.rect_px.1 + offset_px.1;
4107                        let sw = layer.rect_px.2;
4108                        let sh = layer.rect_px.3;
4109                        // The blur in UV space is 1.5 * blur_px / texture_size
4110                        // (the 1.5 matches the 3x3 Gaussian span).
4111                        let bw_uv = (blur_px * 1.5) / layer.width.max(1) as f32;
4112                        let bh_uv = (blur_px * 1.5) / layer.height.max(1) as f32;
4113                        let ndc_tl = to_ndc(sx, sy, sw, sh, fb_w, fb_h);
4114                        let inst = BlurInstance {
4115                            xywh: [
4116                                ndc_tl[0] + ndc_tl[2] * 0.5,
4117                                ndc_tl[1] + ndc_tl[3] * 0.5,
4118                                ndc_tl[2],
4119                                ndc_tl[3],
4120                            ],
4121                            uv: [0.0, 0.0, 1.0, 1.0],
4122                            color: [
4123                                color.0 as f32 / 255.0,
4124                                color.1 as f32 / 255.0,
4125                                color.2 as f32 / 255.0,
4126                                color.3 as f32 / 255.0,
4127                            ],
4128                            blur_uv: [bw_uv, bh_uv],
4129                            sin_cos: [1.0, 0.0],
4130                        };
4131                        self.blur_ring
4132                            .grow_to_fit(&self.device, std::mem::size_of::<BlurInstance>() as u64);
4133                        let bytes = bytemuck::bytes_of(&inst);
4134                        let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
4135                        current_pass.cmds.push(Cmd::CompositeShadow {
4136                            off,
4137                            cnt: 1,
4138                            layer_id: *layer_id,
4139                        });
4140                    }
4141                }
4142                _ => {}
4143            }
4144        }
4145
4146        flush_batch!();
4147
4148        // Push the final pass.
4149        passes.push(current_pass);
4150
4151        let bind_mask = self.atlas_bind_group_mask();
4152        let bind_color = self.atlas_bind_group_color();
4153        let mut clip_depth: u32 = 0;
4154
4155        for pass in std::mem::take(&mut passes) {
4156            let (color_view, resolve_target, depth_stencil_view, is_layer) = match pass.target {
4157                PassTarget::Surface => {
4158                    let swap_view = target_view.clone();
4159                    let use_ws = self.working_space && self.ws_view.is_some();
4160                    let (color, resolve) = if use_ws {
4161                        let ws_view = self.ws_view.as_ref().unwrap();
4162                        if let Some(msaa_view) = &self.msaa_view {
4163                            // MSAA resolves to working-space texture
4164                            (msaa_view.clone(), Some(ws_view.clone()))
4165                        } else {
4166                            // Direct render to working-space texture
4167                            (ws_view.clone(), None)
4168                        }
4169                    } else if let Some(msaa_view) = &self.msaa_view {
4170                        (msaa_view.clone(), Some(swap_view))
4171                    } else {
4172                        (swap_view, None)
4173                    };
4174                    (color, resolve, self.depth_stencil_view.clone(), false)
4175                }
4176                PassTarget::Layer(layer_id) => {
4177                    if let Some(lt) = self.layer_pool.get(&layer_id) {
4178                        (lt.view.clone(), None, lt.depth_stencil_view.clone(), true)
4179                    } else {
4180                        log::warn!("missing layer target {layer_id}");
4181                        continue;
4182                    }
4183                }
4184            };
4185
4186            if is_layer {
4187                clip_depth = 0;
4188            }
4189
4190            let pipes: &Pipelines = if is_layer {
4191                &self.layer_pipes
4192            } else {
4193                &self.surface_pipes
4194            };
4195
4196            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4197                label: Some("pass"),
4198                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4199                    view: &color_view,
4200                    resolve_target: resolve_target.as_ref(),
4201                    ops: wgpu::Operations {
4202                        load: match pass.clear_color {
4203                            Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
4204                                r: c[0] as f64,
4205                                g: c[1] as f64,
4206                                b: c[2] as f64,
4207                                a: c[3] as f64,
4208                            }),
4209                            None => wgpu::LoadOp::Load,
4210                        },
4211                        store: wgpu::StoreOp::Store,
4212                    },
4213                    depth_slice: None,
4214                })],
4215                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
4216                    view: &depth_stencil_view,
4217                    depth_ops: None,
4218                    stencil_ops: Some(wgpu::Operations {
4219                        load: if is_layer || pass.clear_color.is_some() {
4220                            wgpu::LoadOp::Clear(0)
4221                        } else {
4222                            wgpu::LoadOp::Load
4223                        },
4224                        store: wgpu::StoreOp::Store,
4225                    }),
4226                }),
4227                timestamp_writes: None,
4228                occlusion_query_set: None,
4229                multiview_mask: None,
4230            });
4231
4232            rpass.set_bind_group(0, &self.globals_bind, &[]);
4233            rpass.set_stencil_reference(clip_depth);
4234            rpass.set_scissor_rect(
4235                pass.initial_scissor.0,
4236                pass.initial_scissor.1,
4237                pass.initial_scissor.2,
4238                pass.initial_scissor.3,
4239            );
4240
4241            macro_rules! draw_simple {
4242                ($pipeline:expr, $ring:expr, $inst:ty, $off:ident, $n:ident) => {{
4243                    rpass.set_pipeline($pipeline);
4244                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
4245                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
4246                    rpass.draw(0..6, 0..$n);
4247                }};
4248            }
4249
4250            macro_rules! draw_with_bind {
4251                ($pipeline:expr, $ring:expr, $inst:ty, $bind:expr, $off:ident, $n:ident) => {{
4252                    rpass.set_pipeline($pipeline);
4253                    rpass.set_bind_group(1, $bind, &[]);
4254                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
4255                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
4256                    rpass.draw(0..6, 0..$n);
4257                }};
4258            }
4259
4260            for cmd in pass.cmds {
4261                match cmd {
4262                    Cmd::ClipPush {
4263                        off,
4264                        cnt: n,
4265                        scissor,
4266                        difference,
4267                        rounded,
4268                    } => {
4269                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
4270                        rpass.set_stencil_reference(clip_depth);
4271
4272                        if difference {
4273                            rpass.set_pipeline(&pipes.clip_dec);
4274                        } else if self.msaa_samples > 1 && !is_layer && rounded {
4275                            rpass.set_pipeline(&pipes.clip_a2c);
4276                        } else {
4277                            rpass.set_pipeline(&pipes.clip_bin);
4278                        }
4279
4280                        let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
4281                        rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
4282                        rpass.draw(0..6, 0..n);
4283
4284                        if !difference {
4285                            clip_depth = (clip_depth + 1).min(255);
4286                            rpass.set_stencil_reference(clip_depth);
4287                        }
4288                    }
4289
4290                    Cmd::ClipPop { scissor } => {
4291                        clip_depth = clip_depth.saturating_sub(1);
4292                        rpass.set_stencil_reference(clip_depth);
4293                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
4294                    }
4295
4296                    Cmd::Rect { off, cnt: n } => {
4297                        draw_simple!(&pipes.rects, self.rects.ring, RectInstance, off, n);
4298                    }
4299
4300                    Cmd::Border { off, cnt: n } => {
4301                        draw_simple!(&pipes.borders, self.borders.ring, BorderInstance, off, n);
4302                    }
4303
4304                    Cmd::GlyphsMask { off, cnt: n } => {
4305                        draw_with_bind!(
4306                            &pipes.text_mask,
4307                            self.glyph_mask.ring,
4308                            GlyphInstance,
4309                            &bind_mask,
4310                            off,
4311                            n
4312                        );
4313                    }
4314
4315                    Cmd::GlyphsColor { off, cnt: n } => {
4316                        draw_with_bind!(
4317                            &pipes.text_color,
4318                            self.glyph_color.ring,
4319                            GlyphInstance,
4320                            &bind_color,
4321                            off,
4322                            n
4323                        );
4324                    }
4325
4326                    Cmd::GlyphsVector { off, cnt: n } => {
4327                        if let Some(ref slug_pipe) = pipes.slug.as_ref() {
4328                            rpass.set_pipeline(slug_pipe);
4329                            let bytes = (n as u64) * std::mem::size_of::<slug::TessVertex>() as u64;
4330                            rpass.set_vertex_buffer(0, self.slug_ring.buf.slice(off..off + bytes));
4331                            rpass.draw(0..n, 0..1);
4332                        }
4333                    }
4334
4335                    Cmd::ImageRgba {
4336                        off,
4337                        cnt: n,
4338                        handle,
4339                    } => {
4340                        if let Some(ImageTex::Rgba { bind, .. }) = self.images.get(&handle) {
4341                            draw_with_bind!(
4342                                &pipes.image_rgba,
4343                                self.glyph_color.ring,
4344                                GlyphInstance,
4345                                bind,
4346                                off,
4347                                n
4348                            );
4349                        }
4350                    }
4351
4352                    Cmd::ImageNv12 {
4353                        off,
4354                        cnt: n,
4355                        handle,
4356                    } => {
4357                        if let Some(ImageTex::Nv12 { bind, .. }) = self.images.get(&handle) {
4358                            draw_with_bind!(
4359                                &pipes.image_nv12,
4360                                self.nv12.ring,
4361                                Nv12Instance,
4362                                bind,
4363                                off,
4364                                n
4365                            );
4366                        }
4367                    }
4368
4369                    Cmd::Ellipse { off, cnt: n } => {
4370                        draw_simple!(&pipes.ellipses, self.ellipses.ring, EllipseInstance, off, n);
4371                    }
4372
4373                    Cmd::EllipseBorder { off, cnt: n } => {
4374                        draw_simple!(
4375                            &pipes.ellipse_borders,
4376                            self.ellipse_borders.ring,
4377                            EllipseBorderInstance,
4378                            off,
4379                            n
4380                        );
4381                    }
4382
4383                    Cmd::Arc { off, cnt: n } => {
4384                        draw_simple!(&pipes.arcs, self.arcs.ring, ArcInstance, off, n);
4385                    }
4386
4387                    Cmd::PushTransform(_) => {}
4388                    Cmd::PopTransform => {}
4389                    Cmd::CompositeLayer {
4390                        off,
4391                        cnt: n,
4392                        layer_id,
4393                        alpha: _,
4394                    } => {
4395                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
4396                            draw_with_bind!(
4397                                &pipes.image_rgba,
4398                                self.glyph_color.ring,
4399                                GlyphInstance,
4400                                &lt.bind,
4401                                off,
4402                                n
4403                            );
4404                        }
4405                    }
4406                    Cmd::CompositeShadow {
4407                        off,
4408                        cnt: n,
4409                        layer_id,
4410                    } => {
4411                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
4412                            draw_with_bind!(
4413                                &pipes.blur,
4414                                self.blur_ring,
4415                                BlurInstance,
4416                                &lt.bind,
4417                                off,
4418                                n
4419                            );
4420                        }
4421                    }
4422                    Cmd::CompositeBlur {
4423                        off,
4424                        cnt: n,
4425                        layer_id,
4426                    } => {
4427                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
4428                            draw_with_bind!(
4429                                &pipes.blur_content,
4430                                self.blur_ring,
4431                                BlurInstance,
4432                                &lt.bind,
4433                                off,
4434                                n
4435                            );
4436                        }
4437                    }
4438                }
4439            }
4440        }
4441
4442        // Display pass: linear working space → sRGB OETF → swapchain
4443        if self.working_space {
4444            if let (Some(_ws_view), Some(ws_bind), Some(display_pipeline)) =
4445                (&self.ws_view, &self.ws_bind, &self.display_pipeline)
4446            {
4447                let swap_view = target_view.clone();
4448                let mut display_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4449                    label: Some("display transform"),
4450                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4451                        view: &swap_view,
4452                        resolve_target: None,
4453                        ops: wgpu::Operations {
4454                            load: wgpu::LoadOp::Load,
4455                            store: wgpu::StoreOp::Store,
4456                        },
4457                        depth_slice: None,
4458                    })],
4459                    depth_stencil_attachment: None,
4460                    timestamp_writes: None,
4461                    occlusion_query_set: None,
4462                    multiview_mask: None,
4463                });
4464                display_pass.set_pipeline(display_pipeline);
4465                display_pass.set_bind_group(1, ws_bind, &[]);
4466                display_pass.draw(0..3, 0..1);
4467            }
4468        }
4469
4470
4471        // Frame end maintenance: Evict unused images
4472        self.evict_unused_images();
4473    }
4474
4475    /// Render a scene into an externally-provided texture view.
4476    /// Use this when embedding Repose in a host that owns the GPU.
4477    /// The host is responsible for submitting the encoder and handling present.
4478    pub fn render_to_view(
4479        &mut self,
4480        scene: &Scene,
4481        encoder: &mut wgpu::CommandEncoder,
4482        target_view: &wgpu::TextureView,
4483        width: u32,
4484        height: u32,
4485        clear_color: Option<[f64; 4]>,
4486    ) {
4487        self.resize(width, height);
4488
4489        self.frame_index = self.frame_index.wrapping_add(1);
4490        self.slug_cache.next_frame();
4491
4492        if width == 0 || height == 0 {
4493            return;
4494        }
4495
4496        self.render_scene_to_encoder(scene, encoder, target_view, clear_color);
4497    }
4498}
4499
4500
4501fn intersect(a: repose_core::Rect, b: repose_core::Rect) -> repose_core::Rect {
4502    let x0 = a.x.max(b.x);
4503    let y0 = a.y.max(b.y);
4504    let x1 = (a.x + a.w).min(b.x + b.w);
4505    let y1 = (a.y + a.h).min(b.y + b.h);
4506    repose_core::Rect {
4507        x: x0,
4508        y: y0,
4509        w: (x1 - x0).max(0.0),
4510        h: (y1 - y0).max(0.0),
4511    }
4512}