alpha2-render 0.9.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
967
968
969
970
971
972
973
974
975
976
977
978
979
//! The composite node (composite.wesl): layers over a background in order, each result stored
//! as the intermediate holds it before the next layer reads it.
//!
//! Unrotated layers use per-column and per-row tap tables, since their derivatives are
//! constant, edge coverage is an x-y product, and bilinear sampling is separable. Rotated
//! layers run the shader's loop literally.

use std::sync::Arc;

use super::blend::composite as blend;
use super::frames::FramePool;
use super::half;
use super::image::{CpuImage, PixelBox, Texels};
use super::workers::Workers;
use crate::{BlendMode, BlendSpace, Color, LayerTransform, RenderError, RenderSize};

/// Alpha from which a normal-mode source pixel counts as nearly opaque.
///
/// Edge coverage and the filter's average round in `f32` as the shader does, so a minified
/// opaque layer can arrive a few 1e-4 short of opaque. From 2^-8 short the backdrop is mixed in
/// encoded space instead of linear light, which changes results by under 1e-3 (a tenth of an
/// 8-bit code).
const NEARLY_OPAQUE: f32 = 1.0 - 1.0 / 256.0;

pub(crate) struct LayerInput<'a> {
    pub(crate) image: &'a CpuImage,
    pub(crate) visual: LayerTransform,
    pub(crate) blend_mode: BlendMode,
}

#[derive(Copy, Clone)]
pub(crate) struct CompositeSettings {
    pub(crate) size: RenderSize,
    pub(crate) background: Option<Color>,
    pub(crate) blend_space: BlendSpace,
    pub(crate) max_filter_samples: u32,
}

/// Composites `layers` in order over the background.
///
/// # Errors
/// [`RenderError::InvalidVisual`] for an invalid layer transform or opacity.
pub(crate) fn composite(
    workers: &Workers,
    frames: &Arc<FramePool>,
    layers: &[LayerInput<'_>],
    settings: CompositeSettings,
) -> Result<CpuImage, RenderError> {
    let size = settings.size;
    let prepared = prepared_layers(layers, settings)?;
    let background =
        crate::composite::stored_background(settings.background, wgpu::TextureFormat::Rgba16Float);
    let bounds = if settings.background.is_some() {
        PixelBox::whole(size)
    } else {
        prepared
            .iter()
            .fold(PixelBox::EMPTY, |union, layer| union.union(layer.bounds))
    };
    if bounds.is_empty() {
        return Ok(CpuImage::transparent(size));
    }
    let fill = half::store4(background);
    let mut pixels = frames.take(bounds.pixels());
    let width = bounds.width as usize;
    let linear_light = settings.blend_space == BlendSpace::LinearLight;
    let new_caches = || {
        prepared
            .iter()
            .map(|_| RowCache::default())
            .collect::<Vec<_>>()
    };
    let row_work_pixels = width
        + prepared
            .iter()
            .map(PreparedLayer::row_work_pixels)
            .sum::<usize>();
    let draw_band = |caches: &mut Vec<RowCache>, first_row: usize, band: &mut [[u16; 4]]| {
        band.fill(fill);
        for cache in caches.iter_mut() {
            cache.reset();
        }
        for (index, line) in band.chunks_mut(width).enumerate() {
            #[allow(clippy::cast_possible_truncation)]
            let y = bounds.y + (first_row + index) as u32;
            for (layer, cache) in prepared.iter().zip(caches.iter_mut()) {
                layer.draw_row(y, bounds, line, cache, linear_light);
            }
        }
    };
    workers.weighted_bands_with(&mut pixels, width, row_work_pixels, new_caches, draw_band);
    Ok(CpuImage::pooled(size, bounds, pixels, frames))
}

pub(super) fn prepared_layers<'a>(
    layers: &[LayerInput<'a>],
    settings: CompositeSettings,
) -> Result<Vec<PreparedLayer<'a>>, RenderError> {
    for layer in layers {
        crate::composite::validate_visual(layer.visual)?;
    }
    Ok(layers
        .iter()
        .filter(|layer| {
            !crate::composite::is_degenerate(layer.visual)
                && !crate::composite::is_invisible(layer.visual)
        })
        .filter_map(|layer| {
            let bounds = crate::composite::layer_bounds(layer.visual, settings.size)?;
            let bounds = PixelBox {
                x: bounds.x,
                y: bounds.y,
                width: bounds.width,
                height: bounds.height,
            };
            let bounds = bounds.intersect(content_bounds(layer, settings.size)?);
            (!bounds.is_empty()).then(|| PreparedLayer::new(layer, bounds, settings))
        })
        .collect())
}

/// Output pixels a layer's samples can reach: its content rect mapped as `layer_bounds` maps the
/// source, grown by the filter reach (two source texels at output scale). Outside, samples read
/// transparency. `None` when it misses the target.
fn content_bounds(layer: &LayerInput<'_>, size: RenderSize) -> Option<PixelBox> {
    let image = layer.image;
    let content = image.bounds();
    if content.is_empty() {
        return None;
    }
    let source = image.size();
    if content == PixelBox::whole(source) {
        return Some(PixelBox::whole(size));
    }
    let visual = layer.visual;
    let (width, height) = (f64::from(size.width), f64::from(size.height));
    let texel = (f64::from(visual.scale[0]).abs() * width / f64::from(source.width))
        .max(f64::from(visual.scale[1]).abs() * height / f64::from(source.height));
    let margin = 4.0 + 2.0 * texel.max(1.0);
    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 (u0, u1) = (
        f64::from(content.x) / f64::from(source.width),
        f64::from(content.right()) / f64::from(source.width),
    );
    let (v0, v1) = (
        f64::from(content.y) / f64::from(source.height),
        f64::from(content.bottom()) / f64::from(source.height),
    );
    let corners = [
        corner(u0, v0),
        corner(u1, v0),
        corner(u0, v1),
        corner(u1, v1),
    ];
    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) - margin)
        .floor()
        .max(0.0);
    let top = (fold(|c| c.1, f64::min, f64::INFINITY) - margin)
        .floor()
        .max(0.0);
    let right = (fold(|c| c.0, f64::max, f64::NEG_INFINITY) + margin)
        .ceil()
        .min(width);
    let bottom = (fold(|c| c.1, f64::max, f64::NEG_INFINITY) + margin)
        .ceil()
        .min(height);
    if !(right > left && bottom > top) {
        return None;
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    Some(PixelBox {
        x: left as u32,
        y: top as u32,
        width: (right - left) as u32,
        height: (bottom - top) as u32,
    })
}

/// One output column's or row's filter taps and weights, and whether coverage reaches it.
#[derive(Default)]
struct AxisTaps {
    /// Per output position, its range of `taps`; empty where coverage is zero.
    spans: Vec<(u32, u32)>,
    taps: Vec<(u32, f32)>,
}

impl AxisTaps {
    fn taps(&self, position: usize) -> &[(u32, f32)] {
        let (start, end) = self.spans[position];
        &self.taps[start as usize..end as usize]
    }

    fn most_taps(&self) -> usize {
        self.spans
            .iter()
            .map(|(start, end)| (end - start) as usize)
            .max()
            .unwrap_or(0)
    }

    fn reach(&self) -> Option<(u32, u32)> {
        let first = self.taps.iter().map(|(index, _)| *index).min()?;
        let last = self.taps.iter().map(|(index, _)| *index).max()?;
        Some((first, last))
    }
}

/// A layer's source rows filtered horizontally per output column, built on first read.
#[derive(Default)]
pub(super) struct RowCache {
    rows: Vec<(u32, Vec<[f32; 4]>)>,
    decoded: Vec<[f32; 4]>,
    /// Buffers of rows forgotten by [`Self::reset`], refilled by [`Self::ensure`].
    spare: Vec<Vec<[f32; 4]>>,
}

impl RowCache {
    /// Forgets every row, keeping the buffers.
    pub(super) fn reset(&mut self) {
        self.spare
            .extend(self.rows.drain(..).map(|(_, filtered)| filtered));
    }

    fn forget_rows_outside(&mut self, taps: &[(u32, f32)]) {
        let mut index = 0;
        while index < self.rows.len() {
            if taps.iter().any(|(row, _)| *row == self.rows[index].0) {
                index += 1;
            } else {
                self.spare.push(self.rows.swap_remove(index).1);
            }
        }
    }

    fn ensure(
        &mut self,
        row: u32,
        image: &CpuImage,
        columns: &AxisTaps,
        shared: Option<&mut DecodedRows>,
    ) {
        if self.rows.iter().any(|(held, _)| *held == row) {
            return;
        }
        let Some((first, last)) = columns.reach() else {
            return;
        };
        let (decoded, decoded_from) = if let Some(shared) = shared {
            let decoded_from = shared.first;
            (shared.row(image, row), decoded_from)
        } else {
            self.decoded.resize((last - first + 1) as usize, [0.0; 4]);
            image.decode_row(row, first, &mut self.decoded);
            (self.decoded.as_slice(), first)
        };
        let mut filtered = self.spare.pop().unwrap_or_default();
        filtered.clear();
        filtered.extend((0..columns.spans.len()).map(|column| {
            let mut sum = [0.0_f32; 4];
            for &(texel, weight) in columns.taps(column) {
                let value = decoded[(texel - decoded_from) as usize];
                for channel in 0..4 {
                    sum[channel] += value[channel] * weight;
                }
            }
            sum
        }));
        self.rows.push((row, filtered));
    }

    fn row(&self, row: u32) -> &[[f32; 4]] {
        self.rows
            .iter()
            .find(|(held, _)| *held == row)
            .map_or(&[], |(_, filtered)| filtered.as_slice())
    }
}

const SHARED_DECODED_BYTES: usize = 4 * 1024 * 1024;

pub(super) struct DecodedRows {
    first: u32,
    width: usize,
    most_rows: usize,
    rows: Vec<(u32, Vec<[f32; 4]>)>,
    oldest: usize,
}

impl DecodedRows {
    pub(super) fn read_by(layers: &[PreparedLayer<'_>]) -> Option<Self> {
        let (first, last) = layers
            .iter()
            .filter_map(|layer| match &layer.sampler {
                Sampler::Separable { columns, .. } => columns.reach(),
                Sampler::General(_) => None,
            })
            .reduce(|(first, last), (other_first, other_last)| {
                (first.min(other_first), last.max(other_last))
            })?;
        let width = (last - first + 1) as usize;
        Some(Self {
            first,
            width,
            most_rows: (SHARED_DECODED_BYTES / (width * size_of::<[f32; 4]>())).clamp(8, 256),
            rows: Vec::new(),
            oldest: 0,
        })
    }

    pub(super) fn reset(&mut self) {
        for (row, _) in &mut self.rows {
            *row = u32::MAX;
        }
    }

    fn row(&mut self, image: &CpuImage, row: u32) -> &[[f32; 4]] {
        let held = self.rows.iter().position(|(held, _)| *held == row);
        let index = held.unwrap_or_else(|| {
            let index = if self.rows.len() < self.most_rows {
                self.rows.push((row, vec![[0.0; 4]; self.width]));
                self.rows.len() - 1
            } else {
                let index = self.oldest;
                self.oldest = (self.oldest + 1) % self.most_rows;
                index
            };
            let (held, decoded) = &mut self.rows[index];
            *held = row;
            image.decode_row(row, self.first, decoded);
            index
        });
        &self.rows[index].1
    }
}

enum Sampler {
    /// An unrotated layer: tap tables for its columns and rows.
    Separable { columns: AxisTaps, rows: AxisTaps },
    /// A rotated layer, sampled as the shader samples it.
    General(General),
}

/// The shader's per-pixel mapping for a rotated layer.
struct General {
    position_y: f32,
    anchor: [f32; 2],
    scale: [f32; 2],
    cosine: f32,
    sine: f32,
    output: [f32; 2],
    gate_footprint: [f32; 2],
    footprint: [f32; 2],
    turned_columns: Vec<TurnedColumn>,
    sample_steps: Vec<SampleStep>,
    samples: f32,
}

#[derive(Copy, Clone)]
struct TurnedColumn {
    along_x: f32,
    along_y: f32,
}

#[derive(Copy, Clone)]
struct SampleStep {
    across_columns: [f32; 2],
    across_rows: [f32; 2],
}

pub(super) struct PreparedLayer<'a> {
    image: &'a CpuImage,
    texels: Texels<'a>,
    /// Every half float's value, for reading the backdrop.
    halves: &'static [f32; 65_536],
    blend_mode: BlendMode,
    opacity: f32,
    pub(super) bounds: PixelBox,
    sampler: Sampler,
}

/// composite.wesl's `rectangle_coverage` on one axis.
#[inline]
fn coverage(position: f32, footprint: f32) -> f32 {
    let width = footprint.max(0.000_000_1);
    let half_width = width * 0.5;
    let past_the_end = position + half_width - 1.0;
    let before_the_start = half_width - position;
    if past_the_end <= 0.0 && before_the_start <= 0.0 {
        return 1.0;
    }
    let cut = past_the_end.max(0.0) + before_the_start.max(0.0);
    (1.0 - cut / width).clamp(0.0, 1.0)
}

const MOST_AXIS_SAMPLES: usize = 8;
const MOST_AXIS_TAPS: usize = 2 * MOST_AXIS_SAMPLES;

#[allow(clippy::cast_precision_loss)]
fn filter_grid(dx: [f32; 2], dy: [f32; 2], dimensions: [f32; 2], budget: u32) -> [f32; 2] {
    let length = |v: [f32; 2]| (v[0] * v[0] + v[1] * v[1]).sqrt();
    let wanted_x = (length([dx[0] * dimensions[0], dx[1] * dimensions[1]]) - 0.0001)
        .ceil()
        .clamp(1.0, MOST_AXIS_SAMPLES as f32);
    let wanted_y = (length([dy[0] * dimensions[0], dy[1] * dimensions[1]]) - 0.0001)
        .ceil()
        .clamp(1.0, MOST_AXIS_SAMPLES as f32);
    let budget = (budget as f32).clamp(1.0, 64.0);
    let nx = wanted_x.min(budget);
    let ny = wanted_y.min((budget / nx).floor().max(1.0));
    [nx, ny]
}

impl<'a> PreparedLayer<'a> {
    #[allow(clippy::cast_precision_loss)]
    fn new(layer: &LayerInput<'a>, bounds: PixelBox, settings: CompositeSettings) -> Self {
        let visual = layer.visual;
        let output = [settings.size.width as f32, settings.size.height as f32];
        let dimensions = [
            layer.image.size().width as f32,
            layer.image.size().height as f32,
        ];
        let angle = visual.rotation_degrees.to_radians();
        let (sine, cosine) = (libm::sinf(angle), libm::cosf(angle));
        let scale = visual.scale;
        // The shader's affine mapping derivatives per output pixel.
        let dx = [cosine / output[0] / scale[0], -sine / output[1] / scale[1]];
        let dy = [sine / output[0] / scale[0], cosine / output[1] / scale[1]];
        let grid = filter_grid(dx, dy, dimensions, settings.max_filter_samples);
        let footprint = [
            dx[0].abs() / grid[0] + dy[0].abs() / grid[1],
            dx[1].abs() / grid[0] + dy[1].abs() / grid[1],
        ];
        let sampler = if sine == 0.0 {
            Sampler::Separable {
                columns: axis_taps(
                    bounds.x..bounds.right(),
                    output[0],
                    visual.position[0],
                    scale[0],
                    visual.anchor[0],
                    dx[0],
                    grid[0],
                    footprint[0],
                    dimensions[0],
                ),
                rows: axis_taps(
                    bounds.y..bounds.bottom(),
                    output[1],
                    visual.position[1],
                    scale[1],
                    visual.anchor[1],
                    dy[1],
                    grid[1],
                    footprint[1],
                    dimensions[1],
                ),
            }
        } else {
            Sampler::General(General::new(
                visual,
                (cosine, sine),
                output,
                [dx, dy],
                grid,
                footprint,
                bounds.x..bounds.right(),
            ))
        };
        Self {
            image: layer.image,
            texels: layer.image.texels(),
            halves: half::table(),
            blend_mode: layer.blend_mode,
            opacity: visual.opacity,
            bounds,
            sampler,
        }
    }

    /// Composites this layer into output row `y`, `line` holding the `bounds` columns.
    fn draw_row(
        &self,
        y: u32,
        bounds: PixelBox,
        line: &mut [[u16; 4]],
        cache: &mut RowCache,
        linear_light: bool,
    ) {
        self.sample_row(y, cache, None, |x, color| {
            let out = &mut line[(x - bounds.x) as usize];
            *out = self.composite_source(*out, self.at_opacity(color), linear_light);
        });
    }

    #[inline]
    pub(super) fn sample_row(
        &self,
        y: u32,
        cache: &mut RowCache,
        shared: Option<&mut DecodedRows>,
        put: impl FnMut(u32, [f32; 4]),
    ) {
        if y < self.bounds.y || y >= self.bounds.bottom() {
            return;
        }
        match &self.sampler {
            Sampler::Separable { columns, rows } => {
                self.sample_separable_row(columns, rows, y, cache, shared, put);
            }
            Sampler::General(general) => general.sample_row(&self.texels, self.bounds.x, y, put),
        }
    }

    #[inline]
    fn sample_separable_row(
        &self,
        columns: &AxisTaps,
        rows: &AxisTaps,
        y: u32,
        cache: &mut RowCache,
        mut shared: Option<&mut DecodedRows>,
        mut put: impl FnMut(u32, [f32; 4]),
    ) {
        let first = self.bounds.x;
        let row_taps = rows.taps((y - self.bounds.y) as usize);
        if row_taps.is_empty() {
            return;
        }
        cache.forget_rows_outside(row_taps);
        for &(row, _) in row_taps {
            cache.ensure(row, self.image, columns, shared.as_deref_mut());
        }
        let mut lines: [(&[[f32; 4]], f32); MOST_AXIS_TAPS] = [(&[], 0.0); MOST_AXIS_TAPS];
        for (slot, &(row, weight)) in lines.iter_mut().zip(row_taps) {
            *slot = (cache.row(row), weight);
        }
        let lines = &lines[..row_taps.len().min(MOST_AXIS_TAPS)];
        for x in first..self.bounds.right() {
            let column = (x - first) as usize;
            if columns.spans[column].0 == columns.spans[column].1 {
                continue;
            }
            let mut color = [0.0_f32; 4];
            for &(filtered, row_weight) in lines {
                let value = filtered[column];
                for channel in 0..4 {
                    color[channel] += value[channel] * row_weight;
                }
            }
            put(x, color);
        }
    }

    pub(super) fn row_work_pixels(&self) -> usize {
        let taps = match &self.sampler {
            Sampler::Separable { columns, rows } => {
                columns.most_taps().max(1) * rows.most_taps().max(1)
            }
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "a filter grid of at most 8 by 8"
            )]
            Sampler::General(general) => general.samples as usize * 4,
        };
        self.bounds.width as usize * taps
    }

    #[inline]
    pub(super) fn at_opacity(&self, color: [f32; 4]) -> [f32; 4] {
        color.map(|value| value * self.opacity)
    }

    #[inline(always)]
    #[allow(clippy::inline_always)]
    pub(super) fn composite_source(
        &self,
        backdrop: [u16; 4],
        source: [f32; 4],
        linear_light: bool,
    ) -> [u16; 4] {
        // A transparent source leaves the backdrop (the curve round trip is identity up to `pow`).
        if source[3] <= 0.0 {
            return backdrop;
        }
        // Nearly opaque normal-mode source: the round trip is identity up to `pow`, so mix the
        // visible backdrop directly.
        if self.blend_mode == BlendMode::Normal && source[3] >= NEARLY_OPAQUE {
            let below = backdrop.map(|bits| self.halves[usize::from(bits)]);
            let rest = 1.0 - source[3].min(1.0);
            return [
                half::store_nearest((source[0] + below[0] * rest).clamp(0.0, 1.0)),
                half::store_nearest((source[1] + below[1] * rest).clamp(0.0, 1.0)),
                half::store_nearest((source[2] + below[2] * rest).clamp(0.0, 1.0)),
                half::store_nearest((source[3] + below[3] * rest).min(1.0)),
            ];
        }
        self.blend_pixel(backdrop, source, linear_light)
    }

    /// The full blend, out of line since most pixels take a shortcut.
    #[inline(never)]
    fn blend_pixel(&self, backdrop: [u16; 4], source: [f32; 4], linear_light: bool) -> [u16; 4] {
        half::store4_nearest(blend(
            backdrop.map(|bits| self.halves[usize::from(bits)]),
            source,
            self.blend_mode,
            linear_light,
        ))
    }
}

/// Taps of every output position in `range` along one axis of an unrotated layer.
#[allow(clippy::too_many_arguments, clippy::cast_precision_loss)]
fn axis_taps(
    range: std::ops::Range<u32>,
    output: f32,
    position: f32,
    scale: f32,
    anchor: f32,
    derivative: f32,
    grid: f32,
    footprint: f32,
    dimension: f32,
) -> AxisTaps {
    let mut taps = AxisTaps::default();
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let (samples, last) = (grid as u32, dimension as i64 - 1);
    for pixel in range {
        #[allow(clippy::cast_possible_truncation)]
        let start = taps.taps.len() as u32;
        let uv = (pixel as f32 + 0.5) / output;
        let source = (uv - position) * output / output / scale + anchor;
        // The shader's coverage gate.
        if coverage(source, derivative.abs()) <= 0.0 {
            taps.spans.push((start, start));
            continue;
        }
        for sample in 0..samples {
            let offset = (sample as f32 + 0.5) / grid - 0.5;
            let point = source + derivative * offset;
            let weight = coverage(point, footprint) / grid;
            if weight <= 0.0 {
                continue;
            }
            let texel = point * dimension - 0.5;
            let origin = texel.floor();
            let fraction = texel - origin;
            #[allow(clippy::cast_possible_truncation)]
            let origin = origin as i64;
            for (index, tap_weight) in [(origin, 1.0 - fraction), (origin + 1, fraction)] {
                if tap_weight <= 0.0 {
                    continue;
                }
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let index = index.clamp(0, last) as u32;
                let weight = weight * tap_weight;
                match taps.taps[start as usize..]
                    .iter_mut()
                    .find(|(existing, _)| *existing == index)
                {
                    Some((_, existing)) => *existing += weight,
                    None => taps.taps.push((index, weight)),
                }
            }
        }
        #[allow(clippy::cast_possible_truncation)]
        taps.spans.push((start, taps.taps.len() as u32));
    }
    taps
}

impl General {
    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "pixel columns and a filter grid of at most 8 by 8"
    )]
    fn new(
        visual: LayerTransform,
        (cosine, sine): (f32, f32),
        output: [f32; 2],
        [dx, dy]: [[f32; 2]; 2],
        grid: [f32; 2],
        footprint: [f32; 2],
        columns: std::ops::Range<u32>,
    ) -> Self {
        let turned_columns = columns
            .map(|x| {
                let u = (x as f32 + 0.5) / output[0];
                let pixel_offset = (u - visual.position[0]) * output[0];
                TurnedColumn {
                    along_x: cosine * pixel_offset,
                    along_y: -sine * pixel_offset,
                }
            })
            .collect();
        let (nx, ny) = (grid[0] as u32, grid[1] as u32);
        let sample_steps = (0..ny)
            .flat_map(|row| (0..nx).map(move |column| (column, row)))
            .map(|(column, row)| {
                let offset = [
                    (column as f32 + 0.5) / grid[0] - 0.5,
                    (row as f32 + 0.5) / grid[1] - 0.5,
                ];
                SampleStep {
                    across_columns: [dx[0] * offset[0], dx[1] * offset[0]],
                    across_rows: [dy[0] * offset[1], dy[1] * offset[1]],
                }
            })
            .collect();
        Self {
            position_y: visual.position[1],
            anchor: visual.anchor,
            scale: visual.scale,
            cosine,
            sine,
            output,
            gate_footprint: [dx[0].abs() + dy[0].abs(), dx[1].abs() + dy[1].abs()],
            footprint,
            turned_columns,
            sample_steps,
            samples: grid[0] * grid[1],
        }
    }

    #[inline]
    #[expect(clippy::cast_precision_loss, reason = "a pixel row")]
    fn sample_row(
        &self,
        image: &Texels<'_>,
        first_column: u32,
        y: u32,
        mut put: impl FnMut(u32, [f32; 4]),
    ) {
        let v = (y as f32 + 0.5) / self.output[1];
        let pixel_offset = (v - self.position_y) * self.output[1];
        let (across_x, across_y) = (self.sine * pixel_offset, self.cosine * pixel_offset);
        let one_sample = self.sample_steps.len() == 1;
        for (x, turned) in (first_column..).zip(&self.turned_columns) {
            let rotated = [turned.along_x + across_x, turned.along_y + across_y];
            let source = [
                rotated[0] / self.output[0] / self.scale[0] + self.anchor[0],
                rotated[1] / self.output[1] / self.scale[1] + self.anchor[1],
            ];
            let gate = coverage(source[0], self.gate_footprint[0])
                * coverage(source[1], self.gate_footprint[1]);
            if gate <= 0.0 {
                continue;
            }
            let mut color = [0.0_f32; 4];
            for step in &self.sample_steps {
                let point = [
                    source[0] + step.across_columns[0] + step.across_rows[0],
                    source[1] + step.across_columns[1] + step.across_rows[1],
                ];
                let weight =
                    coverage(point[0], self.footprint[0]) * coverage(point[1], self.footprint[1]);
                if weight <= 0.0 {
                    continue;
                }
                let sample = image.sample(point[0], point[1]);
                for channel in 0..4 {
                    color[channel] += sample[channel] * weight;
                }
            }
            put(
                x,
                if one_sample {
                    color
                } else {
                    color.map(|value| value / self.samples)
                },
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CompositeSettings, LayerInput, PreparedLayer, RowCache, coverage, filter_grid};
    use crate::cpu::image::{CpuImage, PixelBox, Texels};
    use crate::cpu::kernels::builtin_interval_coverage;
    use crate::{BlendMode, BlendSpace, LayerTransform, RenderSize};

    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "pixel coordinates and a filter grid of at most 8 by 8"
    )]
    fn shader_loop_sample(
        image: &Texels<'_>,
        visual: LayerTransform,
        output: [f32; 2],
        dimensions: [f32; 2],
        budget: u32,
        (x, y): (u32, u32),
    ) -> Option<[f32; 4]> {
        let angle = visual.rotation_degrees.to_radians();
        let (sine, cosine) = (libm::sinf(angle), libm::cosf(angle));
        let scale = visual.scale;
        let dx = [cosine / output[0] / scale[0], -sine / output[1] / scale[1]];
        let dy = [sine / output[0] / scale[0], cosine / output[1] / scale[1]];
        let grid = filter_grid(dx, dy, dimensions, budget);
        let footprint = [
            dx[0].abs() / grid[0] + dy[0].abs() / grid[1],
            dx[1].abs() / grid[0] + dy[1].abs() / grid[1],
        ];
        let uv = [(x as f32 + 0.5) / output[0], (y as f32 + 0.5) / output[1]];
        let pixel_offset = [
            (uv[0] - visual.position[0]) * output[0],
            (uv[1] - visual.position[1]) * output[1],
        ];
        let rotated = [
            cosine * pixel_offset[0] + sine * pixel_offset[1],
            -sine * pixel_offset[0] + cosine * pixel_offset[1],
        ];
        let source = [
            rotated[0] / output[0] / scale[0] + visual.anchor[0],
            rotated[1] / output[1] / scale[1] + visual.anchor[1],
        ];
        let gate = coverage(source[0], dx[0].abs() + dy[0].abs())
            * coverage(source[1], dx[1].abs() + dy[1].abs());
        if gate <= 0.0 {
            return None;
        }
        let (nx, ny) = (grid[0] as u32, grid[1] as u32);
        let mut color = [0.0_f32; 4];
        for row in 0..ny {
            for column in 0..nx {
                let offset = [
                    (column as f32 + 0.5) / grid[0] - 0.5,
                    (row as f32 + 0.5) / grid[1] - 0.5,
                ];
                let point = [
                    source[0] + dx[0] * offset[0] + dy[0] * offset[1],
                    source[1] + dx[1] * offset[0] + dy[1] * offset[1],
                ];
                let weight = coverage(point[0], footprint[0]) * coverage(point[1], footprint[1]);
                if weight <= 0.0 {
                    continue;
                }
                let sample = image.sample(point[0], point[1]);
                for channel in 0..4 {
                    color[channel] += sample[channel] * weight;
                }
            }
        }
        let samples = grid[0] * grid[1];
        Some(color.map(|value| value / samples))
    }

    #[test]
    #[expect(clippy::cast_precision_loss, reason = "small picture sizes")]
    fn a_rotated_layers_rows_hold_the_shaders_per_pixel_loop_bit_for_bit() {
        let size = RenderSize::new(77, 51).expect("size");
        let picture = RenderSize::new(40, 28).expect("size");
        let pixels = (0..picture.width * picture.height)
            .flat_map(|index| {
                let (x, y) = (index % picture.width, index / picture.width);
                let alpha = u8::try_from(55 + (x * 5) % 200).expect("u8");
                let level = u8::try_from((x * 7 + y * 13) % 256).expect("u8");
                [level, 255 - level, u8::try_from(y * 9).expect("u8"), 255]
                    .map(|value| {
                        u8::try_from(u16::from(value) * u16::from(alpha) / 255).expect("u8")
                    })
                    .into_iter()
                    .take(3)
                    .chain([alpha])
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();
        let image = CpuImage::from_premultiplied_rgba8(picture, &pixels).expect("picture");
        let texels = image.texels();
        let output = [size.width as f32, size.height as f32];
        let dimensions = [picture.width as f32, picture.height as f32];
        let turned = |position, scale, rotation_degrees| LayerTransform {
            position,
            anchor: [0.4, 0.55],
            scale,
            rotation_degrees,
            opacity: 1.0,
        };
        let visuals = [
            turned([0.5, 0.5], [1.0, 1.0], 17.0),
            turned([0.3, 0.6], [0.31, 0.27], -40.0),
            turned([0.7, 0.2], [0.07, 0.11], 123.0),
            turned([0.02, 0.95], [-0.6, 0.4], 200.0),
            turned([0.5, 0.5], [2.3, 1.7], 5.0),
            turned([0.5, 0.5], [0.5, 0.5], 90.0),
            turned([0.45, 0.5], [0.12, 0.9], 0.25),
        ];
        for visual in visuals {
            for budget in [1, 6, 16, 64] {
                let settings = CompositeSettings {
                    size,
                    background: None,
                    blend_space: BlendSpace::LinearLight,
                    max_filter_samples: budget,
                };
                let layer = LayerInput {
                    image: &image,
                    visual,
                    blend_mode: BlendMode::Normal,
                };
                let prepared = PreparedLayer::new(&layer, PixelBox::whole(size), settings);
                let mut sampled = 0;
                for y in 0..size.height {
                    let mut row = vec![None; size.width as usize];
                    prepared.sample_row(y, &mut RowCache::default(), None, |x, color| {
                        row[x as usize] = Some(color.map(f32::to_bits));
                    });
                    for x in 0..size.width {
                        let expected =
                            shader_loop_sample(&texels, visual, output, dimensions, budget, (x, y))
                                .map(|color| color.map(f32::to_bits));
                        assert_eq!(
                            row[x as usize], expected,
                            "{visual:?} x{budget} at {x}, {y}"
                        );
                        sampled += usize::from(expected.is_some());
                    }
                }
                assert!(sampled > 0, "{visual:?} reaches nothing");
            }
        }
    }

    fn clipped_interval(position: f32, footprint: f32) -> f32 {
        let width = footprint.max(0.000_000_1);
        let lower = (position - width * 0.5).max(0.0);
        let upper = (position + width * 0.5).min(1.0);
        ((upper - lower) / width).clamp(0.0, 1.0)
    }

    #[test]
    fn coverage_is_one_inside_and_the_clipped_interval_at_power_of_two_sizes() {
        for side in [1_u16, 2, 4, 64, 256, 1024, 4096] {
            for scale in [0.125_f32, 0.25, 0.5, 1.0, 2.0, 8.0] {
                let footprint = 1.0 / f32::from(side) / scale;
                for step in 0..=side * 8 + 128 {
                    let position = (f32::from(step) - 64.0) / (8.0 * f32::from(side));
                    let expected = clipped_interval(position, footprint);
                    for actual in [
                        coverage(position, footprint),
                        builtin_interval_coverage(position, footprint),
                    ] {
                        assert_eq!(
                            actual.to_bits(),
                            expected.to_bits(),
                            "side {side}, scale {scale}, position {position}"
                        );
                    }
                }
            }
        }
        for side in [5_u16, 90, 160, 1080, 1920] {
            let footprint = 1.0 / f32::from(side);
            for pixel in 1..side - 1 {
                let position = (f32::from(pixel) + 0.5) / f32::from(side);
                assert_eq!(coverage(position, footprint), 1.0, "{pixel} of {side}");
                assert_eq!(builtin_interval_coverage(position, footprint), 1.0);
            }
        }
    }
}