alpha2-render 0.5.0

Render graph and effect registry for alpha2.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
use crate::{
    BlendMode, Color, GraphError, GraphLayer, RenderError, RenderGraph, RenderSize,
    RenderedTexture, Renderer, SourceView,
    pipeline::CachedCompositePipeline,
    uniform::{BATCH_UNIFORM_FLOATS, UniformArenaLease, f32_bytes, float_uniform_bytes},
};
use alpha2_shaders::COMPOSITE_WGSL;

/// Most layers per composite pass (`BATCH_LAYERS` in composite.wesl). With the backdrop this
/// stays within the 16 sampled textures per stage of a WebGL2-class device.
pub(crate) const COMPOSITE_BATCH_LAYERS: usize = 8;

/// Placement and opacity of one composited layer.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct LayerTransform {
    /// Normalized output translation, as `[x, y]`.
    pub position: [f32; 2],
    /// Normalized source anchor, as `[x, y]`.
    pub anchor: [f32; 2],
    /// Per-axis scale, as `[x, y]`.
    pub scale: [f32; 2],
    /// Clockwise rotation in degrees.
    pub rotation_degrees: f32,
    /// Opacity from zero to one.
    pub opacity: f32,
}

/// One decoded, premultiplied sRGB layer and its presentation controls.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
pub struct CompositeLayer<'a> {
    /// Source texture sampled by this layer.
    pub texture: &'a wgpu::TextureView,
    /// Layer transform and opacity.
    pub visual: LayerTransform,
    /// Artistic blend operation evaluated before source-over coverage.
    pub blend_mode: BlendMode,
}

#[derive(Clone, Copy)]
pub(crate) struct CompositeTarget<'a> {
    /// Composited over by the first layer; transparent when `None`.
    pub(crate) background: Option<Color>,
    pub(crate) blend_space: crate::BlendSpace,
    pub(crate) output: &'a wgpu::Texture,
    pub(crate) output_view: &'a wgpu::TextureView,
}

impl Renderer {
    /// Composites layers in slice order onto a transparent RGBA target.
    ///
    /// Inputs and output are premultiplied sRGB; blending uses the renderer's
    /// [`crate::BlendSpace`].
    ///
    /// # Errors
    /// Returns [`RenderError::InvalidVisual`] for non-finite or out-of-range layer values. A
    /// zero-scale layer is valid and draws nothing.
    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
    pub fn render_layers(
        &self,
        size: RenderSize,
        layers: &[CompositeLayer<'_>],
    ) -> Result<RenderedTexture, RenderError> {
        let mut graph = RenderGraph::new(size);
        let mut graph_layers = Vec::with_capacity(layers.len());
        for layer in layers {
            graph_layers.push(GraphLayer {
                source: graph.add_source(SourceView::from_wgpu(layer.texture)),
                visual: layer.visual,
                blend_mode: layer.blend_mode,
            });
        }
        let output = graph
            .add_composite(graph_layers)
            .map_err(GraphError::into_render_error)?;
        graph
            .set_output(output)
            .map_err(GraphError::into_render_error)?;
        self.execute_graph(&graph)
            .map_err(GraphError::into_render_error)
    }

    /// Composites `layers` over `background` into `output`, returning the passes encoded.
    ///
    /// Layers that miss the target or have zero opacity are skipped. Small layers batch up to
    /// [`Self::composite_batch_layers`] per pass and always draw with the loop pipeline, so a lone
    /// small layer and a batch run identical code. Large layers get their own one-layer pass.
    /// The first pass clears to the background; a later batch covering half the target or more
    /// ping-pongs full-frame between two textures, while a smaller one draws in place, scissored,
    /// over a copy of its region.
    #[allow(clippy::too_many_lines)]
    pub(crate) fn encode_layers_pass(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        size: RenderSize,
        layers: &[CompositeLayer<'_>],
        target: CompositeTarget<'_>,
        uniforms: &mut UniformArenaLease,
    ) -> Result<u64, RenderError> {
        let CompositeTarget {
            background,
            blend_space,
            output,
            output_view,
        } = target;
        for layer in layers {
            validate_visual(layer.visual)?;
        }
        let format = self.intermediate_format();
        let drawn = self.drawn_layers(layers.iter().map(|layer| layer.visual), size);
        let drawn = drawn
            .iter()
            .map(|(index, bounds, tier)| (&layers[*index], *bounds, *tier))
            .collect::<Vec<_>>();
        let background = stored_background(background, format);
        if drawn.is_empty() {
            // What a first layer writes where it does not reach, so an empty canvas matches.
            clear_target(encoder, output_view, background);
            return Ok(1);
        }

        let cached = self.composite_pipeline();
        let preparation = BatchPreparationContext {
            device: self.gpu.device(),
            layout: &cached.bind_group_layout,
            sampler: &cached.sampler,
            no_backdrop: &self.empty_input,
            blend_space,
            max_filter_samples: self.quality_controls().max_filter_samples,
            output_size: size,
            background,
        };
        let batches = composite_batches(&drawn, self.composite_batch_layers())
            .into_iter()
            .map(|(range, bounds)| (&drawn[range], bounds))
            .collect::<Vec<_>>();
        let bounded = |bounds: &PixelRect| under_half(*bounds, size);
        let ((first, first_bounds), rest) = batches.split_first().expect("a layer is drawn");
        let first_program = self.batch_program(first);
        let first = prepare_batch(&preparation, None, first, uniforms);
        // The clear writes the stored background, so a small first batch can draw only inside its
        // bounds.
        let first_pass = PassTarget {
            load: wgpu::LoadOp::Clear(stored_color(background)),
            scissor: bounded(first_bounds).then_some(*first_bounds),
        };
        if rest.is_empty() {
            self.draw_batch(
                encoder,
                cached,
                first_program,
                &first,
                output_view,
                first_pass,
            );
            return Ok(1);
        }

        let scratch = self.textures.acquire(
            self.gpu.device(),
            size,
            format,
            "alpha2 layer composition scratch",
        );
        let textures = [output, scratch.texture()];
        let views = [output_view, scratch.view()];
        // Each full-frame batch flips the target; start so the last one lands in `output`.
        let mut current = rest.iter().filter(|(_, bounds)| !bounded(bounds)).count() % 2;
        self.draw_batch(
            encoder,
            cached,
            first_program,
            &first,
            views[current],
            first_pass,
        );
        for (batch, bounds) in rest {
            let other = 1 - current;
            let program = self.batch_program(batch);
            if bounded(bounds) {
                // A pass cannot read the texture it writes, so copy the backdrop region aside
                // first.
                copy_region(encoder, textures[current], textures[other], *bounds);
                let prepared = prepare_batch(&preparation, Some(views[other]), batch, uniforms);
                self.draw_batch(
                    encoder,
                    cached,
                    program,
                    &prepared,
                    views[current],
                    PassTarget {
                        load: wgpu::LoadOp::Load,
                        scissor: Some(*bounds),
                    },
                );
            } else {
                let prepared = prepare_batch(&preparation, Some(views[current]), batch, uniforms);
                self.draw_batch(
                    encoder,
                    cached,
                    program,
                    &prepared,
                    views[other],
                    PassTarget::WHOLE,
                );
                current = other;
            }
        }
        debug_assert_eq!(current, 0);
        Ok(u64::try_from(batches.len()).unwrap_or(u64::MAX))
    }

    /// The program a batch draws with; a multi-layer batch always uses the loop.
    fn batch_program(
        &self,
        batch: &[(&CompositeLayer<'_>, PixelRect, LayerTier)],
    ) -> (CompositeProgram, LayerTier, usize) {
        let tier = batch[0].2;
        debug_assert!(batch.iter().all(|(_, _, other)| *other == tier));
        let program = self.composite_program(tier);
        debug_assert!(batch.len() == 1 || program == CompositeProgram::Loop);
        (program, tier, batch.len())
    }

    fn draw_batch(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        cached: &CachedCompositePipeline,
        (program, tier, layers): (CompositeProgram, LayerTier, usize),
        bind_group: &wgpu::BindGroup,
        target: &wgpu::TextureView,
        pass: PassTarget,
    ) {
        let pipeline = self.composite_program_pipeline(cached, program);
        #[cfg(test)]
        {
            let mut log = self
                .composite_pipelines
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            log.passes += 1;
            log.drawn
                .insert((program, pipeline.clone(), tier, layers > 1));
        }
        #[cfg(not(test))]
        let _ = (tier, layers);
        encode_batch(encoder, pipeline, bind_group, target, pass);
    }

    /// Whether small layers are batched and drawn with the loop pipeline: on a GPU, and in tests
    /// that set `composite_batch_limit`.
    pub(crate) fn batches_small_layers(&self) -> bool {
        #[cfg(test)]
        {
            if self
                .composite_batch_limit
                .load(std::sync::atomic::Ordering::Relaxed)
                > 0
            {
                return true;
            }
        }
        !self.gpu.capabilities().software_rasterizer
    }

    /// The program for a layer of `tier`: the loop for small layers when batching, otherwise the
    /// one-layer program.
    ///
    /// Small layers always use the loop, alone or batched, because Metal, D3D12 and GL compilers
    /// contract two separate programs differently and the stored bytes differ in the last bit.
    /// Software rasterizers execute every branch, so they never batch.
    pub(crate) fn composite_program(&self, tier: LayerTier) -> CompositeProgram {
        if tier == LayerTier::Small && self.batches_small_layers() {
            CompositeProgram::Loop
        } else {
            CompositeProgram::OneLayer
        }
    }

    /// Most layers per composite pass: [`COMPOSITE_BATCH_LAYERS`] on a GPU, one on a software
    /// rasterizer, or `composite_batch_limit` in tests.
    ///
    /// A GPU runs a layer's step only on quads overlapping it, so batching saves passes, barriers
    /// and backdrop copies. A software rasterizer pays for the whole batch area per layer.
    pub(crate) fn composite_batch_layers(&self) -> usize {
        #[cfg(test)]
        {
            let limit = self
                .composite_batch_limit
                .load(std::sync::atomic::Ordering::Relaxed);
            if limit > 0 {
                return limit.min(COMPOSITE_BATCH_LAYERS);
            }
        }
        if self.batches_small_layers() {
            COMPOSITE_BATCH_LAYERS
        } else {
            1
        }
    }

    /// Shader, layout and sampler shared by both composite pipelines, created on first use.
    pub(crate) fn composite_pipeline(&self) -> &CachedCompositePipeline {
        self.pipelines.composite.get_or_init(|| {
            let device = self.gpu.device();
            let bind_group_layout = batch_layout(device);
            let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("alpha2 layer composite shader"),
                source: wgpu::ShaderSource::Wgsl(COMPOSITE_WGSL.into()),
            });
            let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("alpha2 layer sampler"),
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                mag_filter: wgpu::FilterMode::Linear,
                min_filter: wgpu::FilterMode::Linear,
                ..Default::default()
            });
            CachedCompositePipeline {
                bind_group_layout,
                sampler,
                shader,
                programs: Default::default(),
            }
        })
    }

    pub(crate) fn composite_program_pipeline<'a>(
        &self,
        cached: &'a CachedCompositePipeline,
        program: CompositeProgram,
    ) -> &'a wgpu::RenderPipeline {
        let (slot, entry, label) = match program {
            CompositeProgram::Loop => (0, "fs", "alpha2 small layer composite pipeline"),
            CompositeProgram::OneLayer => (1, "fs_layer", "alpha2 large layer composite pipeline"),
        };
        cached.programs[slot].get_or_init(|| {
            #[cfg(test)]
            {
                self.composite_pipelines
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .created
                    .push(program);
            }
            crate::diagnostics::timed_pipeline_creation(
                &self.diagnostics,
                || label.to_owned(),
                || {
                    composite_pipeline(
                        self.gpu.device(),
                        &cached.bind_group_layout,
                        &cached.shader,
                        self.intermediate_format(),
                        entry,
                        label,
                    )
                },
            )
        })
    }

    /// Drawn layers by index with their reachable target pixels and tier; skips layers that miss
    /// or have zero opacity.
    #[cfg_attr(not(test), allow(clippy::unused_self))]
    pub(crate) fn drawn_layers(
        &self,
        visuals: impl Iterator<Item = LayerTransform>,
        size: RenderSize,
    ) -> Vec<(usize, PixelRect, LayerTier)> {
        #[cfg(test)]
        let full_frame = self
            .full_frame_layers
            .load(std::sync::atomic::Ordering::Relaxed);
        #[cfg(not(test))]
        let full_frame = false;
        visuals
            .enumerate()
            .filter_map(|(index, visual)| {
                if is_degenerate(visual) || is_invisible(visual) {
                    return None;
                }
                let bounds = layer_bounds(visual, size);
                // Drawn full-frame in tests, a layer keeps its bounded tier so the pipeline
                // matches.
                let tier = LayerTier::of(bounds.unwrap_or(PixelRect::EMPTY), size);
                if full_frame {
                    Some((index, PixelRect::whole(size), tier))
                } else {
                    bounds.map(|bounds| (index, bounds, tier))
                }
            })
            .collect()
    }

    /// Passes (and batch uniforms) a composite of these layers encodes, not counting a clear.
    pub(crate) fn composite_batch_count(
        &self,
        visuals: impl Iterator<Item = LayerTransform>,
        size: RenderSize,
    ) -> usize {
        let drawn = self.drawn_layers(visuals, size);
        composite_batches(&drawn, self.composite_batch_layers()).len()
    }

    pub(crate) fn warm_composite(&self, layers: usize) {
        if layers == 0 {
            return;
        }
        let cached = self.composite_pipeline();
        self.composite_program_pipeline(cached, CompositeProgram::OneLayer);
        if self.batches_small_layers() {
            self.composite_program_pipeline(cached, CompositeProgram::Loop);
        }
    }
}

/// A drawn layer's size class. It alone decides both batching ([`composite_batches`]) and the
/// program ([`Renderer::composite_program`]), so the two cannot disagree.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) enum LayerTier {
    /// Bounds under half the target: may share a pass.
    Small,
    /// Bounds of half the target or more: always a pass of its own.
    Large,
}

impl LayerTier {
    pub(crate) fn of(bounds: PixelRect, size: RenderSize) -> Self {
        if under_half(bounds, size) {
            Self::Small
        } else {
            Self::Large
        }
    }
}

fn under_half(bounds: PixelRect, size: RenderSize) -> bool {
    bounds.area() * 2 < PixelRect::whole(size).area()
}

/// Entry points of composite.wesl sharing `composite_layer`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) enum CompositeProgram {
    /// `fs`: the pass's layers in a loop, count in a uniform.
    Loop,
    /// `fs_layer`: one layer, no loop.
    OneLayer,
}

/// Test-only record of composite pipelines created and drawn with.
#[cfg(test)]
#[derive(Debug, Default)]
pub(crate) struct CompositePipelineLog {
    pub(crate) created: Vec<CompositeProgram>,
    pub(crate) passes: usize,
    /// Distinct (program, pipeline, tier, multi-layer) combinations drawn.
    pub(crate) drawn:
        std::collections::HashSet<(CompositeProgram, wgpu::RenderPipeline, LayerTier, bool)>,
}

/// Groups drawn layers, in order, into passes, each with the union of its layers' bounds.
///
/// Only [`LayerTier::Small`] layers share a pass, up to `limit`. Batching saves a small layer's
/// pass, barrier and backdrop copy; a large layer would make every batched step run over its
/// area, so it gets its own pass.
pub(crate) fn composite_batches<T>(
    drawn: &[(T, PixelRect, LayerTier)],
    limit: usize,
) -> Vec<(std::ops::Range<usize>, PixelRect)> {
    let mut batches: Vec<(std::ops::Range<usize>, PixelRect)> = Vec::new();
    for (index, (_, bounds, tier)) in drawn.iter().enumerate() {
        match batches.last_mut() {
            Some((range, union))
                if range.len() < limit
                    && *tier == LayerTier::Small
                    && drawn[range.start].2 == LayerTier::Small =>
            {
                range.end = index + 1;
                *union = union.union(*bounds);
            }
            _ => batches.push((index..index + 1, *bounds)),
        }
    }
    batches
}

/// How the intermediate stores a value; the shader rounds to match (`STORED_FORMAT`).
#[derive(Copy, Clone, Debug)]
enum StoredValue {
    /// Kept as computed.
    AsIs,
    /// Rounded to a half float.
    Half,
    /// Rounded to an 8-bit unorm code.
    Unorm8,
}

impl StoredValue {
    fn of(format: wgpu::TextureFormat) -> Self {
        match format {
            wgpu::TextureFormat::Rgba16Float => Self::Half,
            wgpu::TextureFormat::Rgba8Unorm => Self::Unorm8,
            _ => Self::AsIs,
        }
    }

    const fn shader_value(self) -> f64 {
        match self {
            Self::AsIs => 0.0,
            Self::Half => 1.0,
            Self::Unorm8 => 2.0,
        }
    }
}

struct BatchPreparationContext<'a> {
    device: &'a wgpu::Device,
    layout: &'a wgpu::BindGroupLayout,
    sampler: &'a wgpu::Sampler,
    /// Bound as the first pass's backdrop, which composites over `background` and reads nothing.
    no_backdrop: &'a wgpu::TextureView,
    blend_space: crate::BlendSpace,
    max_filter_samples: u32,
    output_size: RenderSize,
    background: [f32; 4],
}

/// Writes a batch's `BatchParams` and binds its textures, filling unused slots with the first
/// layer's. Without `backdrop` the batch composites over the background.
fn prepare_batch(
    context: &BatchPreparationContext<'_>,
    backdrop: Option<&wgpu::TextureView>,
    batch: &[(&CompositeLayer<'_>, PixelRect, LayerTier)],
    uniforms: &mut UniformArenaLease,
) -> wgpu::BindGroup {
    debug_assert!(!batch.is_empty() && batch.len() <= COMPOSITE_BATCH_LAYERS);
    let mut values = [0.0_f32; BATCH_UNIFORM_FLOATS];
    #[allow(clippy::cast_precision_loss)]
    let controls = [
        context.blend_space.shader_value(),
        context.max_filter_samples as f32,
        batch.len() as f32,
        if backdrop.is_some() { 0.0 } else { 1.0 },
        context.output_size.width as f32,
        context.output_size.height as f32,
        0.0,
        0.0,
        context.background[0],
        context.background[1],
        context.background[2],
        context.background[3],
    ];
    values[..controls.len()].copy_from_slice(&controls);
    for ((layer, bounds, _), slot) in batch
        .iter()
        .zip(values[controls.len()..].as_chunks_mut::<16>().0)
    {
        let visual = layer.visual;
        #[allow(clippy::cast_precision_loss)]
        slot.copy_from_slice(&[
            visual.position[0],
            visual.position[1],
            visual.anchor[0],
            visual.anchor[1],
            visual.scale[0],
            visual.scale[1],
            visual.rotation_degrees.to_radians(),
            visual.opacity,
            layer.blend_mode.shader_value(),
            0.0,
            0.0,
            0.0,
            bounds.x as f32,
            bounds.y as f32,
            (bounds.x + bounds.width) as f32,
            (bounds.y + bounds.height) as f32,
        ]);
    }
    let uniform = uniforms.write(&f32_bytes(values));
    let texture = |slot: usize| {
        let (layer, _, _) = batch.get(slot).unwrap_or(&batch[0]);
        layer.texture
    };
    let mut entries = (0..COMPOSITE_BATCH_LAYERS)
        .map(|slot| wgpu::BindGroupEntry {
            binding: u32::try_from(slot).expect("few layer slots"),
            resource: wgpu::BindingResource::TextureView(texture(slot)),
        })
        .collect::<Vec<_>>();
    entries.push(wgpu::BindGroupEntry {
        binding: SAMPLER_BINDING,
        resource: wgpu::BindingResource::Sampler(context.sampler),
    });
    entries.push(wgpu::BindGroupEntry {
        binding: BACKDROP_BINDING,
        resource: wgpu::BindingResource::TextureView(backdrop.unwrap_or(context.no_backdrop)),
    });
    entries.push(wgpu::BindGroupEntry {
        binding: UNIFORM_BINDING,
        resource: uniforms.binding(uniform),
    });
    context
        .device
        .create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("alpha2 layer batch bind group"),
            layout: context.layout,
            entries: &entries,
        })
}

/// Clears `target` to `stored`, a value its format holds exactly, so the clear matches what a
/// layer pass writes for the same background.
fn clear_target(encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, stored: [f32; 4]) {
    let color = stored_color(stored);
    let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("alpha2 layer clear pass"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: target,
            depth_slice: None,
            resolve_target: None,
            ops: wgpu::Operations {
                load: wgpu::LoadOp::Clear(color),
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    });
}

#[derive(Copy, Clone)]
struct PassTarget {
    load: wgpu::LoadOp<wgpu::Color>,
    /// Only these pixels are drawn; the whole target when `None`.
    scissor: Option<PixelRect>,
}

impl PassTarget {
    /// Writes every pixel, so previous contents do not matter.
    const WHOLE: Self = Self {
        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
        scissor: None,
    };
}

/// A stored value as a clear color, exact in the target format so no device rounds it.
fn stored_color(stored: [f32; 4]) -> wgpu::Color {
    let [r, g, b, a] = stored.map(f64::from);
    wgpu::Color { r, g, b, a }
}

/// Draws one batch into `target`, full-frame or scissored, after loading or clearing it.
fn encode_batch(
    encoder: &mut wgpu::CommandEncoder,
    pipeline: &wgpu::RenderPipeline,
    bind_group: &wgpu::BindGroup,
    target: &wgpu::TextureView,
    PassTarget { load, scissor }: PassTarget,
) {
    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("alpha2 layer composition pass"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: target,
            depth_slice: None,
            resolve_target: None,
            ops: wgpu::Operations {
                load,
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    });
    pass.set_pipeline(pipeline);
    pass.set_bind_group(0, bind_group, &[]);
    if let Some(scissor) = scissor {
        pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
    }
    pass.draw(0..3, 0..1);
}

fn copy_region(
    encoder: &mut wgpu::CommandEncoder,
    source: &wgpu::Texture,
    destination: &wgpu::Texture,
    region: PixelRect,
) {
    let at = |texture| wgpu::TexelCopyTextureInfo {
        texture,
        mip_level: 0,
        origin: wgpu::Origin3d {
            x: region.x,
            y: region.y,
            z: 0,
        },
        aspect: wgpu::TextureAspect::All,
    };
    encoder.copy_texture_to_texture(
        at(source),
        at(destination),
        wgpu::Extent3d {
            width: region.width,
            height: region.height,
            depth_or_array_layers: 1,
        },
    );
}

/// A rectangle of target pixels.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) struct PixelRect {
    pub(crate) x: u32,
    pub(crate) y: u32,
    pub(crate) width: u32,
    pub(crate) height: u32,
}

impl PixelRect {
    /// No pixels; the bounds of a layer that misses the target.
    const EMPTY: Self = Self {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
    };

    const fn whole(size: RenderSize) -> Self {
        Self {
            x: 0,
            y: 0,
            width: size.width,
            height: size.height,
        }
    }

    pub(crate) fn area(self) -> u64 {
        u64::from(self.width) * u64::from(self.height)
    }

    fn union(self, other: Self) -> Self {
        let x = self.x.min(other.x);
        let y = self.y.min(other.y);
        let right = (self.x + self.width).max(other.x + other.width);
        let bottom = (self.y + self.height).max(other.y + other.height);
        Self {
            x,
            y,
            width: right - x,
            height: bottom - y,
        }
    }
}

/// Pixels beyond a layer's edges its coverage can still reach. Antialiasing reaches about
/// 1.5 pixels, so this is generous.
const COVERAGE_MARGIN: f64 = 4.0;

/// Target pixels a layer can change: its transformed rectangle widened by [`COVERAGE_MARGIN`]
/// and clamped, or `None` if it misses. Elsewhere coverage is zero.
///
/// Mirrors the shader: source corner `(u, v)` lands at
/// `position * size + R^T ((u, v) - anchor) * scale * size`, with `R` the shader's rotation.
pub(crate) fn layer_bounds(visual: LayerTransform, size: RenderSize) -> Option<PixelRect> {
    let (width, height) = (f64::from(size.width), f64::from(size.height));
    let (turn_sin, turn_cos) = libm::sincos(f64::from(visual.rotation_degrees).to_radians());
    let corner = |u: f64, v: f64| {
        let x = (u - f64::from(visual.anchor[0])) * f64::from(visual.scale[0]) * width;
        let y = (v - f64::from(visual.anchor[1])) * f64::from(visual.scale[1]) * height;
        (
            f64::from(visual.position[0]) * width + turn_cos * x - turn_sin * y,
            f64::from(visual.position[1]) * height + turn_sin * x + turn_cos * y,
        )
    };
    let corners = [
        corner(0.0, 0.0),
        corner(1.0, 0.0),
        corner(0.0, 1.0),
        corner(1.0, 1.0),
    ];
    let fold = |pick: fn(&(f64, f64)) -> f64, extreme: fn(f64, f64) -> f64, start: f64| {
        corners.iter().map(pick).fold(start, extreme)
    };
    let left = (fold(|c| c.0, f64::min, f64::INFINITY) - COVERAGE_MARGIN)
        .floor()
        .max(0.0);
    let top = (fold(|c| c.1, f64::min, f64::INFINITY) - COVERAGE_MARGIN)
        .floor()
        .max(0.0);
    let right = (fold(|c| c.0, f64::max, f64::NEG_INFINITY) + COVERAGE_MARGIN)
        .ceil()
        .min(width);
    let bottom = (fold(|c| c.1, f64::max, f64::NEG_INFINITY) + COVERAGE_MARGIN)
        .ceil()
        .min(height);
    if !(right > left && bottom > top) {
        return None;
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    Some(PixelRect {
        x: left as u32,
        y: top as u32,
        width: (right - left) as u32,
        height: (bottom - top) as u32,
    })
}

/// The canvas background as the intermediate stores it (8-bit or half, round to nearest),
/// transparent when absent.
///
/// Both the empty-canvas clear and the first layer pass use this value. Letting the device
/// convert the original can round a tie differently (0.7 is 178.49999 in `f32`), so an empty
/// frame would differ from its neighbour by one code.
pub(crate) fn stored_background(
    background: Option<Color>,
    format: wgpu::TextureFormat,
) -> [f32; 4] {
    let Some(color) = background else {
        return [0.0; 4];
    };
    // Clear values reach the device as `f32`.
    #[allow(clippy::cast_possible_truncation)]
    let channel = |value: f64| {
        let value = value as f32;
        match format {
            wgpu::TextureFormat::Rgba8Unorm => (value.clamp(0.0, 1.0) * 255.0).round() / 255.0,
            wgpu::TextureFormat::Rgba16Float => half::f16::from_f32(value).to_f32(),
            _ => value,
        }
    };
    [
        channel(color.red),
        channel(color.green),
        channel(color.blue),
        channel(color.alpha),
    ]
}

const SAMPLER_BINDING: u32 = 8;
const BACKDROP_BINDING: u32 = 9;
const UNIFORM_BINDING: u32 = 10;

/// Composite pass layout: a texture per layer slot, sampler, backdrop and batch uniform.
fn batch_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
    let mut entries = (0..COMPOSITE_BATCH_LAYERS)
        .map(|slot| texture_entry(u32::try_from(slot).expect("few layer slots"), true))
        .collect::<Vec<_>>();
    entries.push(wgpu::BindGroupLayoutEntry {
        binding: SAMPLER_BINDING,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
        count: None,
    });
    entries.push(texture_entry(BACKDROP_BINDING, false));
    entries.push(wgpu::BindGroupLayoutEntry {
        binding: UNIFORM_BINDING,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: batch_uniform_binding(),
        count: None,
    });
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("alpha2 layer batch bind group layout"),
        entries: &entries,
    })
}

/// Sized to the graph's reservation so an oversized `BatchParams` fails pipeline creation
/// instead of overrunning the uniform arena.
fn batch_uniform_binding() -> wgpu::BindingType {
    wgpu::BindingType::Buffer {
        ty: wgpu::BufferBindingType::Uniform,
        has_dynamic_offset: false,
        min_binding_size: std::num::NonZeroU64::new(float_uniform_bytes(BATCH_UNIFORM_FLOATS)),
    }
}

fn texture_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
        },
        count: None,
    }
}

fn composite_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    shader: &wgpu::ShaderModule,
    format: wgpu::TextureFormat,
    fragment_entry: &str,
    label: &str,
) -> wgpu::RenderPipeline {
    let label = Some(label);
    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label,
        bind_group_layouts: &[Some(layout)],
        immediate_size: 0,
    });
    let constants = [("STORED_FORMAT", StoredValue::of(format).shader_value())];
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label,
        layout: Some(&pipeline_layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: Some("vs"),
            buffers: &[],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: shader,
            entry_point: Some(fragment_entry),
            targets: &[Some(format.into())],
            compilation_options: wgpu::PipelineCompilationOptions {
                constants: &constants,
                ..wgpu::PipelineCompilationOptions::default()
            },
        }),
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: None,
        multisample: wgpu::MultisampleState::default(),
        multiview_mask: None,
        cache: None,
    })
}

pub(crate) fn validate_visual(visual: LayerTransform) -> Result<(), RenderError> {
    let values = [
        visual.position[0],
        visual.position[1],
        visual.anchor[0],
        visual.anchor[1],
        visual.scale[0],
        visual.scale[1],
        visual.rotation_degrees,
        visual.opacity,
    ];
    if values.into_iter().any(|value| !value.is_finite()) || !(0.0..=1.0).contains(&visual.opacity)
    {
        return Err(RenderError::InvalidVisual);
    }
    Ok(())
}

/// Whether a layer collapses to a line or point and covers no pixel.
///
/// A scale passing through zero is a valid instant, not an error; the transform just has no
/// inverse.
pub(crate) fn is_degenerate(visual: LayerTransform) -> bool {
    visual.scale[0].abs() <= f32::EPSILON || visual.scale[1].abs() <= f32::EPSILON
}

/// Whether a layer has zero opacity and so leaves every pixel unchanged.
///
/// Drawing it would only round the backdrop through the blend space.
pub(crate) fn is_invisible(visual: LayerTransform) -> bool {
    visual.opacity <= 0.0
}