agg-gui-wgpu 0.5.0

Hardware-accelerated wgpu renderer for agg-gui — DrawCtx via Vulkan/DX12/Metal/WebGL2, with SSAA, screenshot capture, and a custom render-pass hook
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! `end_frame` implementation — flushes all deferred [`DrawCommand`]s into a
//! single wgpu command submission.
//!
//! Two-phase approach to satisfy wgpu's borrow rules:
//!
//! 1. **Prepare** — walk `commands`, allocate GPU buffers, build bind groups.
//!    All owned resources are collected in a `Vec<Prepared>`.  A *size stack*
//!    is simulated so each command's uniforms get the resolution of whichever
//!    render target is current at that point in the command list.
//! 2. **Execute** — open a `RenderPass` per render target, walk the `Prepared`
//!    list, and issue draw calls.  PushLayer/PopLayer end the current pass and
//!    start a new one on the layer texture or parent target.
//!
//! Multi-pass orchestration: each layer push/pop boundary is a render-pass
//! boundary in wgpu (a `RenderPass<'enc>` exclusively borrows its encoder, so
//! switching attachments requires ending and re-beginning the pass).

use std::sync::Arc;

use crate::end_frame_prepare::prepare_all;
use crate::pipelines::WgpuPipelines;
use crate::{LastEndFrameStats, WgpuGfxCtx};

/// One `(buffer, offset, size)` allocation from the per-frame arena pool.
/// Stored inside [`Prepared`] variants and read by `execute_one` to produce
/// a `wgpu::BufferSlice` for vertex / index binding, or a
/// `wgpu::BufferBinding` for a uniform bind group.
///
/// Holding the `Arc<wgpu::Buffer>` here keeps the underlying chunk alive
/// even if the arena later advances to a different chunk in the same frame
/// (see `buffer_arena` module docs).
#[derive(Clone)]
pub(crate) struct PreparedSlice {
    pub buf: Arc<wgpu::Buffer>,
    pub offset: u64,
    pub size: u64,
}

impl PreparedSlice {
    /// Sub-slice of the underlying buffer covering exactly `size` bytes
    /// starting at `offset`.  Used for `set_vertex_buffer` / `set_index_buffer`.
    #[inline]
    pub fn wgpu_slice(&self) -> wgpu::BufferSlice<'_> {
        self.buf.slice(self.offset..self.offset + self.size)
    }

    /// Binding descriptor for a uniform bind group.  `size = None` would
    /// mean "rest of buffer" — we always want the exact uniform-struct size
    /// because the arena packs multiple uniforms back-to-back into one chunk.
    #[inline]
    pub fn uniform_binding(&self) -> wgpu::BufferBinding<'_> {
        wgpu::BufferBinding {
            buffer: &self.buf,
            offset: self.offset,
            size: std::num::NonZeroU64::new(self.size),
        }
    }
}

// ---------------------------------------------------------------------------
// Per-command prepared GPU resources
// ---------------------------------------------------------------------------

pub(crate) enum Prepared {
    /// Pass-level clear — handled via `LoadOp::Clear` on the next pass open.
    Clear(wgpu::Color),
    /// Solid colour (no AA).
    Solid {
        vb: PreparedSlice,
        ib: PreparedSlice,
        index_count: u32,
        bg0: wgpu::BindGroup,
        clip: Option<[i32; 4]>,
    },
    /// AA solid (per-vertex alpha from tess2 halo strips).
    AaSolid {
        vb: PreparedSlice,
        ib: PreparedSlice,
        index_count: u32,
        bg0: wgpu::BindGroup,
        clip: Option<[i32; 4]>,
    },
    /// AA via texture lookup — agg-sharp `Graphics2DGpu` port.
    /// `bg1` is the cached alpha-step texture binding owned by
    /// `WgpuGfxCtx::aa_step_bg1`.
    AaTexture {
        vb: PreparedSlice,
        ib: PreparedSlice,
        index_count: u32,
        bg0: wgpu::BindGroup,
        bg1: Arc<wgpu::BindGroup>,
        clip: Option<[i32; 4]>,
    },
    /// Linear or radial gradient.
    Gradient {
        _ramp_tex: wgpu::Texture,
        _ramp_view: wgpu::TextureView,
        vb: PreparedSlice,
        ib: PreparedSlice,
        index_count: u32,
        bg0: wgpu::BindGroup,
        bg1: wgpu::BindGroup,
        clip: Option<[i32; 4]>,
    },
    /// Textured quad (image blit).
    Textured {
        _texture: Arc<wgpu::Texture>,
        _view: wgpu::TextureView,
        vb: PreparedSlice,
        bg0: wgpu::BindGroup,
        bg1: wgpu::BindGroup,
        clip: Option<[i32; 4]>,
    },
    /// LCD subpixel mask (3-pass, or single grayscale pass when `flatten`).
    LcdMask {
        _texture: Arc<wgpu::Texture>,
        _view: wgpu::TextureView,
        vb: PreparedSlice,
        ib: PreparedSlice,
        bg0s: [wgpu::BindGroup; 3],
        bg1: wgpu::BindGroup,
        clip: Option<[i32; 4]>,
        flatten: bool,
    },
    /// LCD backbuffer (3-pass two-plane, or single flatten pass when `flatten`).
    LcbMask {
        _color_tex: Arc<wgpu::Texture>,
        _color_view: wgpu::TextureView,
        _alpha_tex: Arc<wgpu::Texture>,
        _alpha_view: wgpu::TextureView,
        vb: PreparedSlice,
        ib: PreparedSlice,
        bg0s: [wgpu::BindGroup; 3],
        bg1: wgpu::BindGroup,
        clip: Option<[i32; 4]>,
        flatten: bool,
    },
    /// Begin rendering into a new layer texture.
    PushLayer {
        _texture: Arc<wgpu::Texture>,
        view: wgpu::TextureView,
        size: (u32, u32),
    },
    /// End layer rendering and composite onto the parent target.
    PopLayer {
        _texture: Arc<wgpu::Texture>,
        _view: wgpu::TextureView,
        vb: PreparedSlice,
        bg0: wgpu::BindGroup,
        bg1: wgpu::BindGroup,
        parent_clip: Option<[i32; 4]>,
    },
    /// Composite a retained layer onto the current target — no layer-stack
    /// change.
    CompositeLayer {
        _texture: Arc<wgpu::Texture>,
        _view: wgpu::TextureView,
        vb: PreparedSlice,
        bg0: wgpu::BindGroup,
        bg1: wgpu::BindGroup,
        parent_clip: Option<[i32; 4]>,
    },
    /// Generic custom render hook (see `crate::custom_render`).  Treated as a
    /// pass break (current pass ends, the renderer records its own pass on the
    /// same encoder, parent pass reopens with `LoadOp::Load`) so a custom
    /// renderer targets the active layer when its widget is hosted in a window.
    Custom {
        renderer: crate::custom_render::SharedCustomRenderer,
        screen_rect: agg_gui::Rect,
        parent_clip: Option<[i32; 4]>,
    },
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

impl WgpuGfxCtx {
    pub(crate) fn flush_to_surface(&mut self, surface_view: &wgpu::TextureView) {
        let commands = std::mem::take(&mut self.commands);
        let command_count = commands.len() as u32;

        // Rewind the per-frame buffer pool to chunk 0 / offset 0. Last
        // frame's `Prepared` Vec was dropped at the end of the previous
        // `flush_to_surface`, so nothing external still references the
        // chunks; the wgpu::Buffers themselves are kept and overwritten via
        // `queue.write_buffer` instead of being reallocated.
        self.frame_arenas.begin_frame();

        // Wall-clock split of the three phases. We deliberately keep this
        // measurement in-renderer (vs. having the shell measure end_frame as
        // a whole) so consumers see prepare-vs-execute-vs-submit separately —
        // those three have very different optimisation strategies (CPU-side
        // buffer allocation, render-pass batching, driver/GPU sync).
        let t_prepare = web_time::Instant::now();
        let prepared = prepare_all(
            &self.device,
            &self.queue,
            &self.pipelines,
            &mut self.frame_arenas,
            &commands,
            self.viewport,
            &self.aa_step_bg1,
        );
        let prepare_us = t_prepare.elapsed().as_micros().min(u32::MAX as u128) as u32;

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("frame"),
            });

        let t_execute = web_time::Instant::now();
        execute_prepared(
            &self.device,
            &self.queue,
            self.surface_format,
            &mut encoder,
            surface_view,
            &self.pipelines,
            &prepared,
            self.viewport,
        );
        let execute_us = t_execute.elapsed().as_micros().min(u32::MAX as u128) as u32;

        let t_submit = web_time::Instant::now();
        self.queue.submit(std::iter::once(encoder.finish()));
        let submit_us = t_submit.elapsed().as_micros().min(u32::MAX as u128) as u32;

        self.last_end_frame_stats = LastEndFrameStats {
            prepare_us,
            execute_us,
            submit_us,
            command_count,
        };
    }
}
// ---------------------------------------------------------------------------
// Phase 2 — execute in render passes
// ---------------------------------------------------------------------------

fn execute_prepared<'a>(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    surface_format: wgpu::TextureFormat,
    encoder: &mut wgpu::CommandEncoder,
    surface_view: &'a wgpu::TextureView,
    pipelines: &WgpuPipelines,
    prepared: &'a [Prepared],
    surface_viewport: (f32, f32),
) {
    // Initial clear: only honoured if the very first command is Clear.  Mid-frame
    // clears (after a draw) are skipped — the layer system makes them rare.
    let init_clear = match prepared.first() {
        Some(Prepared::Clear(c)) => Some(*c),
        _ => None,
    };

    // Stack of `(target_view, viewport_size)`.  Borrowed from `surface_view` (root)
    // or `Prepared::PushLayer.view` for active layers.
    let mut target_stack: Vec<(&'a wgpu::TextureView, (f32, f32))> =
        vec![(surface_view, surface_viewport)];

    let mut load_op: wgpu::LoadOp<wgpu::Color> = match init_clear {
        Some(c) => wgpu::LoadOp::Clear(c),
        None => wgpu::LoadOp::Load,
    };

    // After a PopLayer we must emit a composite quad at the start of the parent's
    // resumed pass — captured here between the closed layer pass and the reopened
    // parent pass.  The references point into `prepared`.
    let mut pending_composite: Option<(
        &'a PreparedSlice,
        &'a wgpu::BindGroup,
        &'a wgpu::BindGroup,
        Option<[i32; 4]>,
    )> = None;

    let mut i = 0usize;

    // Each iteration of the outer loop runs exactly one render pass.  The inner
    // block scopes the pass so the encoder borrow ends when we exit it.
    while i < prepared.len() || pending_composite.is_some() {
        let &(target_view, target_vp) = target_stack.last().unwrap();

        {
            let mut pass = begin_pass(encoder, target_view, load_op);
            pass.set_viewport(0.0, 0.0, target_vp.0, target_vp.1, 0.0, 1.0);

            // First, if a PopLayer is pending, emit its composite quad at the
            // start of this resumed parent pass — clipped to the scissor that
            // was active in the parent when the layer was pushed, so the blit
            // can't spill outside the parent's clip (e.g. over a title bar).
            if let Some((vb, bg0, bg1, parent_clip)) = pending_composite.take() {
                if apply_clip(&mut pass, parent_clip, target_vp) {
                    pass.set_pipeline(&pipelines.layer_pipeline);
                    pass.set_bind_group(0, bg0, &[]);
                    pass.set_bind_group(1, bg1, &[]);
                    pass.set_vertex_buffer(0, vb.wgpu_slice());
                    pass.draw(0..6, 0..1);
                }
            }

            // Drive the pass forward until end-of-list or a pass break.  Layer
            // push/pop and Custom all force the active 2-D pass to end so the
            // boundary handler below can do its work on the bare encoder.
            while i < prepared.len() {
                match &prepared[i] {
                    Prepared::PushLayer { .. }
                    | Prepared::PopLayer { .. }
                    | Prepared::Custom { .. } => break,
                    other => {
                        execute_one(&mut pass, pipelines, other, target_vp);
                        i += 1;
                    }
                }
            }
            // pass is dropped here, releasing the encoder borrow.
        }

        // Subsequent passes use Load by default.
        load_op = wgpu::LoadOp::Load;

        // Process the boundary command (if any) to set up the next pass's state.
        if i < prepared.len() {
            match &prepared[i] {
                Prepared::PushLayer { view, size, .. } => {
                    target_stack.push((view, (size.0 as f32, size.1 as f32)));
                    load_op = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);
                    i += 1;
                }
                Prepared::PopLayer {
                    vb,
                    bg0,
                    bg1,
                    parent_clip,
                    ..
                } => {
                    target_stack.pop();
                    pending_composite = Some((vb, bg0, bg1, *parent_clip));
                    i += 1;
                }
                Prepared::Custom {
                    renderer,
                    screen_rect,
                    parent_clip,
                } => {
                    // Generic external render hook — see `custom_render` mod.
                    // Renders onto whatever target is current: the surface when
                    // the widget is at top level, the active window's layer view
                    // when hosted in a window.  No stack change; the next
                    // iteration reopens the same target with Load.
                    let target_size = (target_vp.0 as u32, target_vp.1 as u32);
                    let ctx = crate::custom_render::WgpuCustomRenderCtx {
                        device,
                        queue,
                        encoder,
                        target_view,
                        target_size,
                        surface_format,
                        screen_rect: *screen_rect,
                        parent_clip: *parent_clip,
                        pipelines,
                    };
                    renderer.borrow_mut().render(ctx);
                    i += 1;
                }
                _ => unreachable!("loop only breaks on pass-boundary commands"),
            }
        }
    }
}

/// Issue draw calls for a single non-layer-boundary prepared command into an
/// open render pass.
fn execute_one(
    pass: &mut wgpu::RenderPass,
    pipelines: &WgpuPipelines,
    item: &Prepared,
    vp: (f32, f32),
) {
    match item {
        Prepared::Clear(_) => {
            // LoadOp::Clear was used at pass open; mid-frame Clears ignored.
        }
        Prepared::Solid {
            vb,
            ib,
            index_count,
            bg0,
            clip,
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_pipeline(&pipelines.solid_pipeline);
            pass.set_bind_group(0, bg0, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.set_index_buffer(ib.wgpu_slice(), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..*index_count, 0, 0..1);
        }
        Prepared::AaSolid {
            vb,
            ib,
            index_count,
            bg0,
            clip,
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_pipeline(&pipelines.aa_solid_pipeline);
            pass.set_bind_group(0, bg0, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.set_index_buffer(ib.wgpu_slice(), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..*index_count, 0, 0..1);
        }
        Prepared::AaTexture {
            vb,
            ib,
            index_count,
            bg0,
            bg1,
            clip,
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_pipeline(&pipelines.aa_texture_pipeline);
            pass.set_bind_group(0, bg0, &[]);
            pass.set_bind_group(1, &**bg1, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.set_index_buffer(ib.wgpu_slice(), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..*index_count, 0, 0..1);
        }
        Prepared::Gradient {
            vb,
            ib,
            index_count,
            bg0,
            bg1,
            clip,
            ..
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_pipeline(&pipelines.gradient_pipeline);
            pass.set_bind_group(0, bg0, &[]);
            pass.set_bind_group(1, bg1, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.set_index_buffer(ib.wgpu_slice(), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..*index_count, 0, 0..1);
        }
        Prepared::Textured {
            vb, bg0, bg1, clip, ..
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_pipeline(&pipelines.tex_pipeline);
            pass.set_bind_group(0, bg0, &[]);
            pass.set_bind_group(1, bg1, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.draw(0..6, 0..1);
        }
        Prepared::LcdMask {
            vb,
            ib,
            bg0s,
            bg1,
            clip,
            flatten,
            ..
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_bind_group(1, bg1, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.set_index_buffer(ib.wgpu_slice(), wgpu::IndexFormat::Uint32);
            if *flatten {
                // Single alpha-writing grayscale pass (inside a layer). Uniforms
                // in bg0s[0] carry the colour; the channel field is ignored.
                pass.set_pipeline(&pipelines.text_gray);
                pass.set_bind_group(0, &bg0s[0], &[]);
                pass.draw_indexed(0..6, 0, 0..1);
            } else {
                let lcd_pipelines = [&pipelines.lcd_r, &pipelines.lcd_g, &pipelines.lcd_b];
                for ch in 0..3 {
                    pass.set_pipeline(lcd_pipelines[ch]);
                    pass.set_bind_group(0, &bg0s[ch], &[]);
                    pass.draw_indexed(0..6, 0, 0..1);
                }
            }
        }
        Prepared::LcbMask {
            vb,
            ib,
            bg0s,
            bg1,
            clip,
            flatten,
            ..
        } => {
            if !apply_clip(pass, *clip, vp) {
                return;
            }
            pass.set_bind_group(1, bg1, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.set_index_buffer(ib.wgpu_slice(), wgpu::IndexFormat::Uint32);
            if *flatten {
                // Single flatten pass (inside a layer). Any of the three bind
                // groups works — they share resolution + global_alpha and only
                // differ in the (here-ignored) channel selector.
                pass.set_pipeline(&pipelines.lcb_flatten);
                pass.set_bind_group(0, &bg0s[0], &[]);
                pass.draw_indexed(0..6, 0, 0..1);
            } else {
                let lcb_pipelines = [&pipelines.lcb_r, &pipelines.lcb_g, &pipelines.lcb_b];
                for ch in 0..3 {
                    pass.set_pipeline(lcb_pipelines[ch]);
                    pass.set_bind_group(0, &bg0s[ch], &[]);
                    pass.draw_indexed(0..6, 0, 0..1);
                }
            }
        }
        Prepared::CompositeLayer {
            vb,
            bg0,
            bg1,
            parent_clip,
            ..
        } => {
            // Composite a retained layer onto the current target — no stack
            // change.  Clip to the scissor active when the composite was
            // requested so the blit can't paint outside the parent's clip.
            if !apply_clip(pass, *parent_clip, vp) {
                return;
            }
            pass.set_pipeline(&pipelines.layer_pipeline);
            pass.set_bind_group(0, bg0, &[]);
            pass.set_bind_group(1, bg1, &[]);
            pass.set_vertex_buffer(0, vb.wgpu_slice());
            pass.draw(0..6, 0..1);
        }
        // Pass-boundary commands are handled in the outer driver, not here.
        Prepared::PushLayer { .. } | Prepared::PopLayer { .. } | Prepared::Custom { .. } => {}
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn begin_pass<'a>(
    encoder: &'a mut wgpu::CommandEncoder,
    view: &'a wgpu::TextureView,
    load: wgpu::LoadOp<wgpu::Color>,
) -> wgpu::RenderPass<'a> {
    encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("pass"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view,
            resolve_target: None,
            depth_slice: None,
            ops: wgpu::Operations {
                load,
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    })
}

/// Apply `clip` (Y-up scissor stored in the draw-state stack) to the open
/// render pass and return whether the draw can proceed.
///
/// Returns `false` when the clip would reject every fragment (zero width or
/// zero height after intersection with the viewport).  Callers MUST skip
/// the subsequent `draw` / `draw_indexed` when this returns `false`,
/// because wgpu's render-pass scissor state is sticky — if we silently
/// don't update the scissor on a zero-area clip, the previous draw's
/// scissor leaks into this one and the draw paints unclipped.  The
/// canonical reproducer is a collapsed [`Window`]: its `clip_children_rect`
/// returns `(0, 0, w, 0)` (zero content height), and without this signal
/// the body widgets render on top of the title bar.
fn apply_clip(pass: &mut wgpu::RenderPass, clip: Option<[i32; 4]>, vp: (f32, f32)) -> bool {
    let vp_w = vp.0 as u32;
    let vp_h = vp.1 as u32;
    if let Some(scissor) = clip {
        let (x, y, w, h) = WgpuGfxCtx::yup_to_ydown_scissor(scissor, vp_h);
        let w = w.min(vp_w.saturating_sub(x));
        let h = h.min(vp_h.saturating_sub(y));
        if w > 0 && h > 0 {
            pass.set_scissor_rect(x, y, w, h);
            true
        } else {
            false
        }
    } else {
        pass.set_scissor_rect(0, 0, vp_w, vp_h);
        true
    }
}

/// Pure-function shadow of the [`apply_clip`] decision used by tests —
/// returns whether a clip rect would let any fragments through.  Mirrors
/// the same intersection math (Y-up → Y-down + viewport clamp + zero-area
/// reject) without needing a live `wgpu::RenderPass`.
#[cfg(test)]
pub(crate) fn clip_yields_visible_pixels(clip: Option<[i32; 4]>, vp: (f32, f32)) -> bool {
    let vp_w = vp.0 as u32;
    let vp_h = vp.1 as u32;
    match clip {
        None => vp_w > 0 && vp_h > 0,
        Some(scissor) => {
            let (x, y, w, h) = WgpuGfxCtx::yup_to_ydown_scissor(scissor, vp_h);
            let w = w.min(vp_w.saturating_sub(x));
            let h = h.min(vp_h.saturating_sub(y));
            w > 0 && h > 0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::clip_yields_visible_pixels;

    #[test]
    fn zero_height_clip_skips_draw() {
        // The collapsed-Window path passes `(x, y, w, 0)` as the children
        // clip rect — a zero-height area.  Without skipping the draw,
        // wgpu's sticky scissor state lets children paint over the title
        // bar.  Regression test for that bug: ensure the clip is rejected.
        assert!(!clip_yields_visible_pixels(
            Some([0, 0, 200, 0]),
            (400.0, 300.0)
        ));
    }

    #[test]
    fn zero_width_clip_skips_draw() {
        // Mirror case — a vertical zero-width clip should also be rejected.
        assert!(!clip_yields_visible_pixels(
            Some([0, 0, 0, 100]),
            (400.0, 300.0)
        ));
    }

    #[test]
    fn ordinary_clip_passes() {
        assert!(clip_yields_visible_pixels(
            Some([10, 10, 100, 50]),
            (400.0, 300.0)
        ));
    }

    #[test]
    fn no_clip_passes_when_viewport_is_non_empty() {
        assert!(clip_yields_visible_pixels(None, (400.0, 300.0)));
    }

    #[test]
    fn clip_entirely_outside_viewport_is_rejected() {
        // A scissor placed past the viewport's right edge has zero
        // intersection — should be rejected so the draw is skipped.
        assert!(!clip_yields_visible_pixels(
            Some([400, 0, 50, 50]),
            (400.0, 300.0)
        ));
    }
}