sgl-3d 0.9.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
use super::*;
use crate::frame_input::{AgxLook, ColorGrading};
use crate::settings::{Bloom, RenderPreset, ToneMapping};
use crate::test_support::{half, read};

/// A 1×1 exposure multiplier of `value`, as the exposure stage writes it.
pub(super) fn exposure_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    value: f32,
) -> wgpu::TextureView {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("fixture exposure"),
        size: wgpu::Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::R32Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        texture.as_image_copy(),
        bytemuck::bytes_of(&value),
        wgpu::TexelCopyBufferLayout::default(),
        texture.size(),
    );
    texture.create_view(&Default::default())
}

/// The default look exposed by `exposure`.
pub(super) fn look(exposure: &wgpu::TextureView) -> Look<'_> {
    static BLOOM: std::sync::LazyLock<crate::BloomParameters> =
        std::sync::LazyLock::new(Default::default);
    static GRADING: std::sync::LazyLock<crate::ColorGrading> =
        std::sync::LazyLock::new(Default::default);
    Look {
        exposure,
        stops: 0.,
        bloom: &BLOOM,
        grading: &GRADING,
        tone_mapping: crate::settings::ToneMapping::default(),
        local_exposure: crate::LocalExposure::default(),
    }
}

/// Sizes for a scene presented at its own size.
fn sizes(size: [u32; 2]) -> Sizes {
    Sizes {
        render: size,
        scene: size,
        output: size,
    }
}

// Defects: AA Off still filters, flips rows, loses channels or skips/doubles the
// display transfer, on an sRGB output or one that stores what is written
// alike. The independent oracle is captured pre-AA scene data plus the sRGB
// transfer equation, within the output's dither of up to a code value.
// Compilation cannot check these pixel semantics.
#[test]
fn antialiasing_off_preserves_captured_pixels() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    pollster::block_on(async {
        let capture = include_bytes!("../../../tests/fixtures/tone-mapped-crop.rgba16");
        for format in [
            HDR,
            wgpu::TextureFormat::Rgba8UnormSrgb,
            wgpu::TextureFormat::Bgra8UnormSrgb,
            wgpu::TextureFormat::Rgba8Unorm,
            wgpu::TextureFormat::Bgra8Unorm,
        ] {
            let mut post = Post::new(
                &device,
                &queue,
                Output::texture(format),
                sizes([80, 64]),
                true,
                SmaaQuality::default(),
            )
            .unwrap();
            for size in [[80, 64], [37, 29]] {
                post.resize(&device, sizes(size), true);
                let bytes = &capture[..(size[0] * size[1] * 8) as usize];
                post.tone_map.hold_capture(&device);
                queue.write_texture(
                    post.tone_map.tone_mapped().texture().as_image_copy(),
                    bytes,
                    wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(size[0] * 8),
                        rows_per_image: Some(size[1]),
                    },
                    post.tone_map.tone_mapped().texture().size(),
                );
                let output = target(&device, "AA switch result", size, format);
                {
                    let mut encoder = device.create_command_encoder(&Default::default());
                    post.tone_map.present_output(
                        &device,
                        &mut encoder,
                        &post.inputs,
                        post.bloom.halo(),
                        &output,
                        None,
                    );
                    queue.submit([encoder.finish()]);
                    let actual = read(
                        &device,
                        &queue,
                        output.texture(),
                        if format == HDR { 8 } else { 4 },
                    );
                    // Linear colour as an 8-bit sRGB code, unrounded.
                    let code = |linear: f64| {
                        let encoded = if linear <= 0.0031308 {
                            12.92 * linear
                        } else {
                            1.055 * linear.powf(1.0 / 2.4) - 0.055
                        };
                        encoded.clamp(0.0, 1.0) * 255.0
                    };
                    if format == HDR {
                        for (index, texel) in actual.chunks_exact(2).enumerate() {
                            let value = f64::from(half(texel));
                            let captured = f64::from(half(&bytes[index * 2..]));
                            let channel = index % 4;
                            if channel == 3 {
                                assert_eq!(value, captured, "AA Off must copy alpha exactly");
                            } else {
                                assert!(
                                    (code(value) - code(captured)).abs() <= 1.,
                                    "{size:?} pixel {} channel {channel}: {value} vs {captured}",
                                    index / 4
                                );
                            }
                        }
                    } else {
                        for (pixel, rgba) in actual.chunks_exact(4).enumerate() {
                            for (channel, &value) in rgba.iter().enumerate() {
                                let source_channel = if format.remove_srgb_suffix()
                                    == wgpu::TextureFormat::Bgra8Unorm
                                    && channel < 3
                                {
                                    2 - channel
                                } else {
                                    channel
                                };
                                let linear =
                                    f64::from(half(&bytes[pixel * 8 + source_channel * 2..]));
                                let expected = if channel == 3 {
                                    linear.clamp(0.0, 1.0) * 255.0
                                } else {
                                    code(linear)
                                }
                                .round() as i32;
                                assert!(
                                    (i32::from(value) - expected).abs() <= 1,
                                    "{format:?} {size:?} pixel {pixel} channel {channel}: {} vs {expected}",
                                    value
                                );
                            }
                        }
                    }
                }
                eprintln!("AA bypass: {format:?} {size:?}; <=1 sRGB code value");
            }
        }
    });
}

// Defects: disabling bloom consumes stale halos, or a preset change discards an
// explicit On override. Without bloom, a single bright texel on black leaves
// its neighbours as black as the far corner; with bloom they are brighter,
// independently of the bloom kernel or tone mapper's particular equations.
// The tone-mapped capture is read, before the output's dither.
#[test]
fn bloom_switch_removes_halos_and_preserves_low_override() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    pollster::block_on(async {
        let mut post = Post::new(
            &device,
            &queue,
            Output::texture(HDR),
            sizes([64, 64]),
            true,
            SmaaQuality::default(),
        )
        .unwrap();
        let output = target(&device, "bloom switch result", [64, 64], HDR);
        let exposure = exposure_texture(&device, &queue, 1.);
        let scene = target(&device, "impulse", [64, 64], HDR);
        for preset in [RenderPreset::High, RenderPreset::Low, RenderPreset::High] {
            post.resize(&device, sizes([64, 64]), preset == RenderPreset::High);
            let size = [64, 64];
            let mut input = vec![0u16; (size[0] * size[1] * 4) as usize];
            // 0x4c00 is IEEE binary16 16.0, an HDR impulse.
            let center = ((size[1] / 2 * size[0] + size[0] / 2) * 4) as usize;
            input[center..center + 3].fill(0x4c00);
            queue.write_texture(
                scene.texture().as_image_copy(),
                bytemuck::cast_slice(&input),
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(size[0] * 8),
                    rows_per_image: Some(size[1]),
                },
                scene.texture().size(),
            );
            let mut off_before = None;
            for bloom in [Bloom::Off, Bloom::On, Bloom::Off] {
                let enabled = bloom.enabled(preset == RenderPreset::Low);
                let mut encoder = device.create_command_encoder(&Default::default());
                let presentation = Presentation {
                    bloom: enabled,
                    smaa: None,
                    capture: true,
                    spatial: false,
                    sharpness: None,
                };
                post.present(
                    &device,
                    &queue,
                    &mut encoder,
                    &scene,
                    presentation,
                    look(&exposure),
                    &output,
                    None,
                );
                queue.submit([encoder.finish()]);
                let actual = read(&device, &queue, post.tone_mapped().texture(), 8);
                let neighbor = half(&actual[(32 * 64 + 26) * 8..]);
                // Tone-mapped black, far from the impulse.
                let black = half(&actual[..]);
                if bloom == Bloom::Off {
                    assert_eq!(neighbor, black, "Off must not spread the impulse");
                    if let Some(before) = &off_before {
                        assert_eq!(
                            &actual, before,
                            "disabling bloom must remove all previous halo data"
                        );
                    }
                    off_before = Some(actual);
                } else {
                    assert!(
                        neighbor > black,
                        "explicit On must render a halo in either preset"
                    );
                }
            }
        }
        eprintln!(
            "Bloom: Off/On/Off removes stale halos across High/Low/High; Low honors explicit On"
        );
    });
}

// Defects: DPI scaling is applied twice, a preset stretches a non-16:9 scene,
// small windows upscale, or switching back to Full leaves stale-sized targets.
// Physical texture extents expose these integration failures independently of
// the resolution helper's calculated dimensions.
#[test]
fn scene_resolution_budgets_resize_targets_without_stretching_or_upscaling() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    pollster::block_on(async {
        use crate::settings::SceneResolution;
        let mut settings = crate::settings::Settings::default();
        let mut renderer = crate::renderer::test_frame::TestRenderer::new(
            &device,
            &queue,
            HDR,
            [64, 64],
            2.,
            &settings,
        )
        .unwrap();
        for display in [[2560, 1440], [2560, 1080], [1200, 1600], [800, 600]] {
            for (resolution, bounds) in [
                (SceneResolution::Hd, [1280, 720]),
                (SceneResolution::FullHd, [1920, 1080]),
                (SceneResolution::Full, display),
            ] {
                settings.scene_resolution = resolution;
                renderer.view.resize(&device, display, 2., &settings);
                let extent = renderer.targets().color.texture().size();
                let scene = [extent.width, extent.height];
                for axis in 0..2 {
                    assert!(scene[axis] <= bounds[axis] && scene[axis] <= display[axis]);
                }
                // One dimension must reach its budget (unless the window is smaller).
                assert!(
                    (0..2).any(|axis| scene[axis].abs_diff(bounds[axis].min(display[axis])) <= 1)
                );
                let aspect_error = (scene[0] as i64 * display[1] as i64
                    - scene[1] as i64 * display[0] as i64)
                    .abs();
                assert!(
                    aspect_error <= i64::from(display[0].max(display[1])),
                    "aspect distortion"
                );
                if display[0] <= bounds[0] && display[1] <= bounds[1] {
                    assert_eq!(
                        scene, display,
                        "small windows and Full must retain every pixel"
                    );
                }
                assert!(
                    renderer
                        .view
                        .diagnostic_target(crate::diagnostics::DiagnosticTarget::ToneMapped)
                        .is_none(),
                    "resizing must not allocate a diagnostic-only output target"
                );
                eprintln!("{resolution:?}: {display:?} -> {scene:?}");
            }
        }
    });
}

// Defect: SMAA detects edges on the unexposed HDR scene, so its absolute
// thresholds scale with the exposure: a scene exposed up by 4 stops loses
// its edges and one exposed down by 4 stops finds edges in every gradient.
// The oracle is the displayed image: a scene 16 times brighter under an
// exposure 16 times lower (and the reverse) is the same image, so its
// antialiased presentation is identical, texel for texel, to the scene's
// own; and SMAA's output differs from its input, so its edges are found at
// all. The scene is presented above its size, through the resample.
#[test]
fn smaa_antialiases_the_displayed_image_whatever_the_exposure() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let scene_size = [48, 40];
    let sizes = Sizes {
        render: scene_size,
        scene: scene_size,
        output: [72, 60],
    };
    let mut post = Post::new(
        &device,
        &queue,
        Output::texture(HDR),
        sizes,
        false,
        SmaaQuality::Medium,
    )
    .unwrap();
    let output = target(&device, "SMAA exposure result", sizes.output, HDR);
    // A dark field and a bright one across a shallow diagonal: 0.05 and 0.8
    // differ by under SMAA's 0.1 threshold once divided by 16.
    let texels = |scale: f32| -> Vec<[f32; 4]> {
        (0..scene_size[1])
            .flat_map(|y| {
                (0..scene_size[0]).map(move |x| {
                    let value = if 3 * x > 5 * y + 10 { 0.8 } else { 0.05 };
                    [value * scale, value * scale, value * scale, 1.]
                })
            })
            .collect()
    };
    // The captured presentation, and whether SMAA changed the tone-mapped
    // scene.
    let mut present = |scale: f32| {
        let scene = crate::test_support::hdr_texture(&device, &queue, scene_size, &texels(scale));
        let exposure = exposure_texture(&device, &queue, 1. / scale);
        let mut encoder = device.create_command_encoder(&Default::default());
        post.present(
            &device,
            &queue,
            &mut encoder,
            &scene,
            Presentation {
                bloom: false,
                smaa: Some(SmaaQuality::Medium),
                capture: true,
                spatial: false,
                sharpness: None,
            },
            look(&exposure),
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
        let targets = post.smaa_targets.as_ref().unwrap();
        let changed = read(&device, &queue, targets.tone_mapped.texture(), 8)
            != read(
                &device,
                &queue,
                targets.antialiased.as_ref().unwrap().texture(),
                8,
            );
        (
            read(&device, &queue, post.tone_mapped().texture(), 8),
            changed,
        )
    };
    let (displayed, changed) = present(1.);
    assert!(changed, "SMAA must change the diagonal");
    for scale in [16., 1. / 16.] {
        assert!(
            present(scale).0 == displayed,
            "the scene times {scale} under an exposure of 1/{scale} must antialias alike"
        );
    }
}

#[test]
fn spatial_upscaling_is_opt_in_and_does_not_replace_temporal_reconstruction() {
    use crate::settings::Upscaling;
    assert_eq!(
        crate::settings::Settings::default().upscaling,
        Upscaling::Off
    );
    let scaled = Sizes {
        render: [8, 6],
        scene: [8, 6],
        output: [17, 13],
    };
    assert!(!spatial_resolves(
        Upscaling::Off,
        scaled,
        Completed::Composite
    ));
    assert!(spatial_resolves(
        Upscaling::On,
        scaled,
        Completed::Composite
    ));
    assert!(spatial_resolves(Upscaling::On, scaled, Completed::Taa));
    assert!(!spatial_resolves(
        Upscaling::On,
        sizes([8, 6]),
        Completed::Composite
    ));
    let temporal = Sizes {
        render: [4, 3],
        ..scaled
    };
    assert!(spatial_resolves(Upscaling::On, temporal, Completed::Fsr));
    assert!(!spatial_resolves(
        Upscaling::On,
        temporal,
        Completed::Composite
    ));
    assert!(!spatial_resolves(
        Upscaling::On,
        Sizes {
            output: [7, 5],
            ..scaled
        },
        Completed::Taa
    ));
}

// Independent invariants: constant colour and alpha survive EASU and
// presentation, at the borders and inside, sharpened or not: unsharpened,
// the defect is EASU's gamma 2 presented undecoded or decoded twice;
// sharpened, also an undefined zero reciprocal in RCAS's limiters. Spatial
// reconstruction differs from linear sampling on a diagonal; no optional
// feature is requested. Check target lifetime through On/Off and
// output-only resize transitions, not source-code assertions.
#[test]
fn spatial_upscaling_runs_on_baseline_device_and_releases_optional_targets() {
    let Some(adapter) = crate::test_support::adapter() else {
        return;
    };
    let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
        required_features: wgpu::Features::empty(),
        required_limits: wgpu::Limits::default(),
        ..Default::default()
    }))
    .unwrap();
    assert!(device.features().is_empty());
    let scene_size = [8, 6];
    let mut sizes = Sizes {
        render: scene_size,
        scene: scene_size,
        output: [17, 13],
    };
    let mut post = Post::new(
        &device,
        &queue,
        Output::texture(HDR),
        sizes,
        false,
        SmaaQuality::default(),
    )
    .unwrap();
    assert!(!post.tone_map.holds_capture());
    assert!(!post.fsr1.target_is_held());
    let exposure = exposure_texture(&device, &queue, 1.);
    for output_size in [[17, 13], [19, 15], [17, 13]] {
        sizes.output = output_size;
        post.resize(&device, sizes, false);
        assert!(!post.fsr1.target_is_held());
        assert!(!post.tone_map.holds_capture());
        let output = target(&device, "spatial presentation", output_size, HDR);
        // Both flat extremes catch undefined zero reciprocals in AMD's
        // contrast limiters; coloured grey also catches double gamma.
        // Unsharpened, the gamma-2 round trip through EASU's half-float
        // target alone separates the two (under 0.1%, plus roundoff).
        // Sharpened, AMD's medium reciprocal has up to 0.316% relative
        // error, which converting gamma 2 back to linear doubles: allow that
        // 0.632% plus half-float roundoff, without hiding a missing or
        // doubled colour conversion.
        let flats = [[0., 0., 0., 1.], [1., 1., 1., 1.], [0.18, 0.5, 0.75, 1.]];
        let cases = [(None, 0.002), (Some(0.8), 0.008)]
            .into_iter()
            .flat_map(|case| flats.map(|color| (case, color)));
        for ((sharpness, tolerance), color) in cases {
            let scene =
                crate::test_support::hdr_texture(&device, &queue, scene_size, &vec![color; 48]);
            let mut reference = device.create_command_encoder(&Default::default());
            post.present(
                &device,
                &queue,
                &mut reference,
                &scene,
                Presentation {
                    bloom: false,
                    smaa: None,
                    capture: true,
                    spatial: false,
                    sharpness: None,
                },
                look(&exposure),
                &output,
                None,
            );
            queue.submit([reference.finish()]);
            let expected = read(&device, &queue, post.tone_map.tone_mapped().texture(), 8);
            let mut encoder = device.create_command_encoder(&Default::default());
            post.present(
                &device,
                &queue,
                &mut encoder,
                &scene,
                Presentation {
                    bloom: false,
                    smaa: None,
                    capture: true,
                    spatial: true,
                    sharpness,
                },
                look(&exposure),
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            let captured = post.tone_map.tone_mapped();
            assert_eq!(
                [captured.texture().width(), captured.texture().height()],
                output_size
            );
            // Capture is before dither, independent of the output transfer.
            let data = read(&device, &queue, captured.texture(), 8);
            let expected = &expected[..8];
            let flat = &data[..8];
            for pixel in data.chunks_exact(8) {
                for channel in 0..4 {
                    let actual = half(&pixel[channel * 2..]);
                    assert!(actual.is_finite());
                    assert!(
                        (actual - half(&flat[channel * 2..])).abs() < 0.003,
                        "flat colour changed at border"
                    );
                    assert!(
                        (actual - half(&expected[channel * 2..])).abs() < tolerance,
                        "{sharpness:?}: flat colour/gamma {actual} differs from linear presentation"
                    );
                }
                assert_eq!(half(&pixel[6..]), 1.);
            }
        }
        let texels: Vec<_> = (0..6)
            .flat_map(|y| {
                (0..8).map(move |x| {
                    let c = if x + y > 6 { 0.8 } else { 0.1 };
                    [c, c * 0.7, c * 0.3, 1.]
                })
            })
            .collect();
        let scene = crate::test_support::hdr_texture(&device, &queue, scene_size, &texels);
        let mut capture_identity = None;
        for smaa in [None, Some(SmaaQuality::Medium)] {
            for _ in 0..2 {
                let mut encoder = device.create_command_encoder(&Default::default());
                post.present(
                    &device,
                    &queue,
                    &mut encoder,
                    &scene,
                    Presentation {
                        bloom: false,
                        smaa,
                        capture: true,
                        spatial: true,
                        sharpness: None,
                    },
                    look(&exposure),
                    &output,
                    None,
                );
                queue.submit([encoder.finish()]);
                let view = post.captured_tone_mapped().unwrap().clone();
                if let Some(previous) = capture_identity.as_ref() {
                    assert_eq!(
                        &view, previous,
                        "consecutive captures must reuse the output target"
                    );
                }
                capture_identity = Some(view);
            }
        }
        let mut spatial_output = None;
        for spatial in [true, false, true] {
            let mut encoder = device.create_command_encoder(&Default::default());
            post.present(
                &device,
                &queue,
                &mut encoder,
                &scene,
                Presentation {
                    bloom: false,
                    smaa: None,
                    capture: false,
                    spatial,
                    sharpness: None,
                },
                look(&exposure),
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            assert!(post.captured_tone_mapped().is_none());
            assert!(!post.tone_map.holds_capture());
            assert_eq!(post.fsr1.target_is_held(), spatial);
            if spatial {
                let data = read(&device, &queue, output.texture(), 8);
                if let Some(before) = spatial_output.as_ref() {
                    assert_eq!(&data, before);
                }
                spatial_output = Some(data);
                assert!(post.smaa_targets.as_ref().unwrap().antialiased.is_none());
            } else {
                assert!(post.smaa_targets.is_none());
                assert_ne!(
                    spatial_output.as_ref().unwrap(),
                    &read(&device, &queue, output.texture(), 8)
                );
            }
        }
    }
}

// Defect: SMAA's scene-size edge and weight targets live for the renderer's
// life, made by `Post::new` and remade by every resize, on renderers that
// never run SMAA (TAA, FSR). Oracle: the architecture's post item, "Post
// holds full-size intermediate targets only for their active consumer, and
// releases disabled-path resources rather than retaining them in caches".
#[test]
fn smaa_holds_scene_size_targets_only_while_it_runs() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut sizes = sizes([8, 6]);
    let mut post = Post::new(
        &device,
        &queue,
        Output::texture(HDR),
        sizes,
        false,
        SmaaQuality::default(),
    )
    .unwrap();
    let exposure = exposure_texture(&device, &queue, 1.);
    let frame = |post: &mut Post, sizes: Sizes, smaa: Option<SmaaQuality>| {
        let scene = crate::test_support::hdr_texture(
            &device,
            &queue,
            sizes.scene,
            &vec![[0.5, 0.25, 0.1, 1.]; (sizes.scene[0] * sizes.scene[1]) as usize],
        );
        let output = target(&device, "SMAA lifetime output", sizes.output, HDR);
        let mut encoder = device.create_command_encoder(&Default::default());
        post.present(
            &device,
            &queue,
            &mut encoder,
            &scene,
            Presentation {
                bloom: false,
                smaa,
                capture: false,
                spatial: false,
                sharpness: None,
            },
            look(&exposure),
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
    };
    // A TAA frame: SMAA does not run.
    frame(&mut post, sizes, None);
    assert!(!post.smaa.holds_targets(), "held without SMAA running");
    frame(&mut post, sizes, Some(SmaaQuality::Medium));
    assert!(post.smaa.holds_targets(), "SMAA ran without its targets");
    frame(&mut post, sizes, None);
    assert!(!post.smaa.holds_targets(), "kept after SMAA stopped");
    sizes = self::sizes([10, 7]);
    post.resize(&device, sizes, false);
    assert!(!post.smaa.holds_targets(), "resize made unused targets");
    frame(&mut post, sizes, None);
    assert!(!post.smaa.holds_targets(), "held without SMAA running");
    frame(&mut post, sizes, Some(SmaaQuality::Medium));
    assert!(post.smaa.holds_targets(), "SMAA ran without its targets");
}

/// The total variation of an RGBA16F image of `size`: the summed absolute
/// differences of its colour between horizontally and vertically adjacent
/// texels.
fn total_variation(bytes: &[u8], size: [u32; 2]) -> f64 {
    let at = |x: u32, y: u32, channel: u32| {
        f64::from(half(
            &bytes[((y * size[0] + x) * 8 + channel * 2) as usize..],
        ))
    };
    let mut sum = 0.;
    for y in 0..size[1] {
        for x in 0..size[0] {
            for channel in 0..3 {
                if x > 0 {
                    sum += (at(x, y, channel) - at(x - 1, y, channel)).abs();
                }
                if y > 0 {
                    sum += (at(x, y, channel) - at(x, y - 1, channel)).abs();
                }
            }
        }
    }
    sum
}

/// A scene of `size` textured in every channel, within tone mapping's
/// unsaturated range.
fn textured_scene(size: [u32; 2]) -> Vec<[f32; 4]> {
    (0..size[1])
        .flat_map(|y| {
            (0..size[0]).map(move |x| {
                let value = |seed: u32| ((x * 37 + y * 11 + x * y * seed) % 17) as f32 / 17.;
                [
                    0.04 + 0.5 * value(7),
                    0.04 + 0.5 * value(5),
                    0.04 + 0.5 * value(3),
                    1.,
                ]
            })
        })
        .collect()
}

// Defects: a path of the final pass that skips RCAS, or ignores or
// reverses the sharpness. RCAS raises the differences between neighbouring
// pixels, more at a higher sharpness (AMD's FSR1 documentation: 0 the
// least, 1 the most), so on a textured scene the presented image's total
// variation orders off < 0.5 < 1 in every path of Frame item 13's final
// pass: tone mapping at the output size or resampled to it, SMAA at the
// output size or resampled, EASU with and without SMAA; read from the
// tone-mapped capture, and from the output where nothing is captured.
#[test]
fn sharpening_runs_in_every_final_path() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let output_size = [24, 18];
    let smaller = [16, 12];
    let smaa = Some(SmaaQuality::Medium);
    let paths = [
        ("tone map at the output size", output_size, None, false),
        ("tone map resampled", smaller, None, false),
        ("SMAA at the output size", output_size, smaa, false),
        ("SMAA resampled", smaller, smaa, false),
        ("EASU", smaller, None, true),
        ("SMAA then EASU", smaller, smaa, true),
    ];
    let exposure = exposure_texture(&device, &queue, 1.);
    let output = target(&device, "sharpened output", output_size, HDR);
    for (path, scene_size, smaa, spatial) in paths {
        let sizes = Sizes {
            render: scene_size,
            scene: scene_size,
            output: output_size,
        };
        let mut post = Post::new(
            &device,
            &queue,
            Output::texture(HDR),
            sizes,
            false,
            SmaaQuality::Medium,
        )
        .unwrap();
        let scene = crate::test_support::hdr_texture(
            &device,
            &queue,
            scene_size,
            &textured_scene(scene_size),
        );
        for capture in [true, false] {
            let variation = |sharpness| {
                let mut encoder = device.create_command_encoder(&Default::default());
                post.present(
                    &device,
                    &queue,
                    &mut encoder,
                    &scene,
                    Presentation {
                        bloom: false,
                        smaa,
                        capture,
                        spatial,
                        sharpness,
                    },
                    look(&exposure),
                    &output,
                    None,
                );
                queue.submit([encoder.finish()]);
                let image = if capture {
                    post.tone_map.tone_mapped().texture()
                } else {
                    output.texture()
                };
                total_variation(&read(&device, &queue, image, 8), output_size)
            };
            let [off, half, most] = [None, Some(0.5), Some(1.)].map(variation);
            eprintln!("{path}, capture {capture}: off {off}, 0.5 {half}, 1 {most}");
            assert!(
                off < half && half < most,
                "{path}, capture {capture}: off {off}, 0.5 {half}, 1 {most}"
            );
        }
    }
}

// Defect: the final pass's RCAS over linear display colour (every path
// but EASU's) leaves its gamma-2 result undecoded or decodes it twice, or
// reads its taps without their gamma-2 form. Oracle: RCAS leaves a flat
// field flat (its lobe sharpens differences only), so a flat colour
// sharpened presents as the same path unsharpened, at the borders and
// inside, within AMD's medium reciprocal's 0.316% relative error doubled
// by the decode, plus half-float roundoff: the bound the spatial case
// allows. Black and white also catch undefined zero reciprocals in RCAS's
// limiters. Paths: tone mapping at the output size, SMAA at the output
// size, and SMAA on a smaller scene resampled to the output.
#[test]
fn a_flat_colour_sharpened_on_the_display_path_presents_unchanged() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let output_size = [17, 13];
    let smaller = [8, 6];
    let smaa = Some(SmaaQuality::Medium);
    let paths = [
        ("tone map at the output size", output_size, None),
        ("SMAA at the output size", output_size, smaa),
        ("SMAA resampled", smaller, smaa),
    ];
    let exposure = exposure_texture(&device, &queue, 1.);
    let output = target(&device, "flat sharpened output", output_size, HDR);
    for (path, scene_size, smaa) in paths {
        let sizes = Sizes {
            render: scene_size,
            scene: scene_size,
            output: output_size,
        };
        let mut post = Post::new(
            &device,
            &queue,
            Output::texture(HDR),
            sizes,
            false,
            SmaaQuality::Medium,
        )
        .unwrap();
        for color in [[0., 0., 0., 1.], [1., 1., 1., 1.], [0.18, 0.5, 0.75, 1.]] {
            let texels = vec![color; (scene_size[0] * scene_size[1]) as usize];
            let scene = crate::test_support::hdr_texture(&device, &queue, scene_size, &texels);
            let [unsharpened, sharpened] = [None, Some(0.8)].map(|sharpness| {
                let mut encoder = device.create_command_encoder(&Default::default());
                post.present(
                    &device,
                    &queue,
                    &mut encoder,
                    &scene,
                    Presentation {
                        bloom: false,
                        smaa,
                        capture: true,
                        spatial: false,
                        sharpness,
                    },
                    look(&exposure),
                    &output,
                    None,
                );
                queue.submit([encoder.finish()]);
                read(&device, &queue, post.tone_map.tone_mapped().texture(), 8)
            });
            for (pixel, (sharp, plain)) in sharpened
                .chunks_exact(8)
                .zip(unsharpened.chunks_exact(8))
                .enumerate()
            {
                for channel in 0..4 {
                    let (sharp, plain) = (half(&sharp[channel * 2..]), half(&plain[channel * 2..]));
                    assert!(
                        sharp.is_finite() && (sharp - plain).abs() < 0.008,
                        "{path}, {color:?}, pixel {pixel}, channel {channel}: sharpened {sharp}, unsharpened {plain}"
                    );
                }
            }
        }
    }
}

// Defect: the output-size sharpening input is held on frames that never
// read it (unsharpened frames, or SMAA's or EASU's output at the output
// size, which RCAS reads directly), or kept once its frame stops. Oracle:
// Frame item 13, "Post holds full-size intermediate targets only for their
// active consumer, and releases disabled-path resources", with RCAS its
// consumer exactly where neither SMAA nor EASU writes the output size: a
// sharpened frame without SMAA, or with SMAA on a smaller scene and no
// spatial upscaling.
#[test]
fn the_sharpening_input_is_held_only_while_rcas_reads_it() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let equal = sizes([8, 6]);
    let smaller = Sizes {
        output: [12, 9],
        ..equal
    };
    let smaa = Some(SmaaQuality::Medium);
    let on = Some(0.8);
    // Sizes, SMAA, spatial upscaling, sharpness, and whether it is held.
    let frames = [
        (equal, None, false, None, false),
        (equal, None, false, on, true),
        (equal, smaa, false, on, false),
        (equal, None, false, on, true),
        (equal, None, false, None, false),
        (smaller, None, false, on, true),
        (smaller, smaa, false, on, true),
        (smaller, smaa, true, on, false),
        (smaller, smaa, false, on, true),
        (smaller, None, true, on, false),
        (smaller, None, false, on, true),
        (smaller, smaa, false, None, false),
    ];
    let mut post = Post::new(
        &device,
        &queue,
        Output::texture(HDR),
        equal,
        false,
        SmaaQuality::Medium,
    )
    .unwrap();
    let exposure = exposure_texture(&device, &queue, 1.);
    let mut current = equal;
    for (frame, (sizes, smaa, spatial, sharpness, held)) in frames.into_iter().enumerate() {
        if sizes.output != current.output {
            post.resize(&device, sizes, false);
            assert!(post.sharpening_input.is_none(), "kept across a resize");
            current = sizes;
        }
        let scene = crate::test_support::hdr_texture(
            &device,
            &queue,
            sizes.scene,
            &textured_scene(sizes.scene),
        );
        let output = target(&device, "sharpening lifetime output", sizes.output, HDR);
        let mut encoder = device.create_command_encoder(&Default::default());
        post.present(
            &device,
            &queue,
            &mut encoder,
            &scene,
            Presentation {
                bloom: false,
                smaa,
                capture: false,
                spatial,
                sharpness,
            },
            look(&exposure),
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
        assert_eq!(
            post.sharpening_input.is_some(),
            held,
            "frame {frame}: SMAA {smaa:?}, spatial {spatial}, sharpness {sharpness:?}"
        );
        if let Some(input) = &post.sharpening_input {
            let texture = input.texture();
            assert_eq!([texture.width(), texture.height()], sizes.output);
        }
    }
}

/// Binary16's +infinity, which an RGBA16F scene texel holds where radiance
/// passed its range on a backend that rounds overflow to infinity (#464).
/// Uploaded as its bits (0x7c00), it is stored as infinity on every backend.
pub(super) const INF: f32 = f32::INFINITY;
/// The scene the infinity tests present.
pub(super) const INFINITE_SCENE: [u32; 2] = [64, 48];
/// 6×6 blocks of the scene, at their top-left texels, infinite in all three
/// channels or in one among ordinary values. Their centres are two texels
/// from any edge SMAA could find.
const INFINITE_BLOCKS: [([u32; 2], [f32; 3]); 4] = [
    ([6, 6], [INF, INF, INF]),
    ([22, 6], [INF, 0.5, 0.25]),
    ([38, 6], [0.25, INF, 0.5]),
    ([6, 26], [0.5, 0.25, INF]),
];
/// Lone infinite texels.
const INFINITE_TEXELS: [([u32; 2], [f32; 3]); 2] =
    [([30, 30], [INF; 3]), ([50, 36], [INF, 0.5, 0.25])];

/// The texels of `INFINITE_SCENE`: an ordinary gradient holding
/// `INFINITE_BLOCKS` and `INFINITE_TEXELS`.
pub(super) fn infinite_scene() -> Vec<[f32; 4]> {
    (0..INFINITE_SCENE[1])
        .flat_map(|y| {
            (0..INFINITE_SCENE[0]).map(move |x| {
                let block = INFINITE_BLOCKS.iter().find(|([left, top], _)| {
                    (*left..left + 6).contains(&x) && (*top..top + 6).contains(&y)
                });
                let lone = INFINITE_TEXELS.iter().find(|(texel, _)| *texel == [x, y]);
                let [r, g, b] = block.or(lone).map_or(
                    [0.05 + x as f32 / 128., 0.1, 0.02 + y as f32 / 96.],
                    |(_, color)| *color,
                );
                [r, g, b, 1.]
            })
        })
        .collect()
}

/// The count of binary16 values in `bytes` that are infinite or NaN.
pub(super) fn non_finite_halves(bytes: &[u8]) -> usize {
    bytes
        .chunks_exact(2)
        .filter(|value| u16::from_le_bytes([value[0], value[1]]) & 0x7c00 == 0x7c00)
        .count()
}

// Plausible defect: a scene texel of +infinity becoming NaN in post, where
// neither TAA nor FSR clamped it first (SMAA or antialiasing Off): the tone
// map's exposure, hue rotation, white-balance matrix and tone curves, and
// bloom's Karis average and composite, do arithmetic that turns infinity
// into NaN, which presents black or garbage and spreads through the bloom
// chain. Oracles: RD-4's finite-output invariant, and each tone curve's
// limit as its input grows without bound, its white: Khronos PBR Neutral's
// new peak and desaturation both tend to 1 (white); the ACES fit's rational
// tends to 1/0.983729 in every channel, which its output matrix (rows
// summing to 1) and clamp make 1; AgX saturates its log range in every
// channel of any input whose inset Rec. 2020 channels pass 2^6.5 × 0.18,
// which Filament's own output for [96, 64, 16] (FILAMENT_AGX's last row)
// gives for each look. A white balance and hue rotation that leave every
// channel unbounded keep that limit.
#[test]
fn infinite_scene_texels_present_finite_as_each_curves_white() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let (_, agx_white) = super::tone_map::tests::FILAMENT_AGX[13];
    let curves = [
        (ToneMapping::KhronosPbrNeutral, AgxLook::None, [1.; 3]),
        (ToneMapping::AcesFilmic, AgxLook::None, [1.; 3]),
        (ToneMapping::Agx, AgxLook::None, agx_white[0]),
        (ToneMapping::Agx, AgxLook::Punchy, agx_white[1]),
        (ToneMapping::Agx, AgxLook::Golden, agx_white[2]),
    ];
    let mut graded = ColorGrading::default();
    graded.global.temperature = 0.05;
    graded.global.tint = -0.02;
    graded.global.hue = 1.;
    let scene =
        crate::test_support::hdr_texture(&device, &queue, INFINITE_SCENE, &infinite_scene());
    let exposure = exposure_texture(&device, &queue, 1.);
    let mut post = Post::new(
        &device,
        &queue,
        Output::texture(HDR),
        sizes(INFINITE_SCENE),
        true,
        SmaaQuality::Medium,
    )
    .unwrap();
    let output = target(&device, "infinite scene output", INFINITE_SCENE, HDR);
    let bloom = crate::BloomParameters::default();
    let mut failures = Vec::new();
    for smaa in [None, Some(SmaaQuality::Medium)] {
        for with_bloom in [false, true] {
            for (tone_mapping, agx_look, white) in curves {
                for grading in [ColorGrading::default(), graded] {
                    let grading = ColorGrading {
                        agx_look,
                        ..grading
                    };
                    let mut encoder = device.create_command_encoder(&Default::default());
                    post.present(
                        &device,
                        &queue,
                        &mut encoder,
                        &scene,
                        Presentation {
                            bloom: with_bloom,
                            smaa,
                            capture: true,
                            spatial: false,
                            sharpness: None,
                        },
                        Look {
                            exposure: &exposure,
                            stops: 0.,
                            bloom: &bloom,
                            grading: &grading,
                            tone_mapping,
                            local_exposure: crate::LocalExposure::default(),
                        },
                        &output,
                        None,
                    );
                    queue.submit([encoder.finish()]);
                    let case = format!(
                        "SMAA {smaa:?}, bloom {with_bloom}, {tone_mapping:?} {agx_look:?}, hue {}",
                        grading.global.hue
                    );
                    let presented = read(&device, &queue, post.tone_mapped().texture(), 8);
                    let output_bytes = read(&device, &queue, output.texture(), 8);
                    for (name, bytes) in
                        [("tone-mapped scene", &presented), ("output", &output_bytes)]
                    {
                        let count = non_finite_halves(bytes);
                        if count > 0 {
                            failures
                                .push(format!("{case}: {count} non-finite values in the {name}"));
                        }
                    }
                    for ([left, top], color) in INFINITE_BLOCKS {
                        for y in top + 2..top + 4 {
                            for x in left + 2..left + 4 {
                                let texel = ((y * INFINITE_SCENE[0] + x) * 8) as usize;
                                for (channel, white) in white.into_iter().enumerate() {
                                    let value = half(&presented[texel + channel * 2..]);
                                    // Binary16 output rounding, and 65504
                                    // standing in for infinity, within
                                    // 1e-4 of each curve's limit.
                                    if (value - white).abs() > 2e-3 {
                                        failures.push(format!(
                                            "{case}: {color:?} at ({x}, {y}) channel {channel} is {value}, white {white}"
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    assert!(failures.is_empty(), "{}", failures.join("\n"));
}

// Plausible defect: `bounded_filter` (inputs.wgsl), which filters a
// footprint again from bounded texels where the hardware filter of a texel
// of +infinity gave infinity or NaN, weighing, offsetting or edge-clamping
// its taps unlike the linear sampler, or leaving a texel unbounded. Metal's
// filter gives infinity rather than NaN for the frame tests' footprints, so
// their results would be bounded without it; here it runs directly. Oracle:
// the hardware linear sampler over the same scene with each infinite texel
// at binary16's largest finite value, at output pixels twice the scene's
// density, whose bilinear weights (1/4 and 3/4) are exact at any sub-texel
// precision, unoffset and offset, edges included; within binary16
// filtering precision.
#[test]
fn bounded_filter_filters_as_the_sampler_filters_the_bounded_scene() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let size = [9u32, 7];
    let output_size = size.map(|v| v * 2);
    let texels = |infinity: f32| -> Vec<[f32; 4]> {
        (0..size[1])
            .flat_map(|y| (0..size[0]).map(move |x| [x, y]))
            .map(|[x, y]| match [x, y] {
                [0, 0] | [4, 3] => [infinity, infinity, infinity, 1.],
                [8, 6] => [infinity, 0.5, 0.25, 1.],
                [3, 6] => [0.25, infinity, 0.5, 1.],
                [8, 0] => [0.5, 0.25, infinity, 1.],
                _ => [0.125 + x as f32 / 16., 0.25 + y as f32 / 16., 0.5, 1.],
            })
            .collect()
    };
    let infinite = crate::test_support::hdr_texture(&device, &queue, size, &texels(INF));
    let bounded = crate::test_support::hdr_texture(&device, &queue, size, &texels(65504.));
    let inputs = inputs::Inputs::new(&device);
    let unread_bloom = target(&device, "unread bloom", [1, 1], HDR);
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("bounded_filter against the sampler"),
        source: wgpu::ShaderSource::Wgsl(
            (crate::shading::compose(&[&inputs::INPUTS])
                + "
@fragment fn bounded(i:Output)->@location(0) vec4<f32> {return bounded_filter(scene,i.uv,vec2(0));}
@fragment fn bounded_offset(i:Output)->@location(0) vec4<f32> {return bounded_filter(scene,i.uv,vec2(2,-1));}
@fragment fn sampled(i:Output)->@location(0) vec4<f32> {return textureSampleLevel(scene,linear_sampler,i.uv,0.);}
@fragment fn sampled_offset(i:Output)->@location(0) vec4<f32> {return textureSampleLevel(scene,linear_sampler,i.uv,0.,vec2(2,-1));}
")
            .into(),
        ),
    });
    let format = wgpu::TextureFormat::Rgba32Float;
    let render = |entry: &str, scene: &wgpu::TextureView| {
        let pipeline = inputs::pipeline(
            &device,
            &[Some(inputs.layout())],
            &shader,
            entry,
            &[format],
            (None, &[]),
        );
        let output = target(&device, entry, output_size, format);
        let group = inputs.group(&device, scene, &unread_bloom);
        let mut encoder = device.create_command_encoder(&Default::default());
        inputs::draw(&mut encoder, &pipeline, &group, &output, entry, None);
        queue.submit([encoder.finish()]);
        let bytes = read(&device, &queue, output.texture(), 16);
        bytemuck::cast_slice::<u8, f32>(&bytes).to_vec()
    };
    for (entry, sampled) in [("bounded", "sampled"), ("bounded_offset", "sampled_offset")] {
        let actual = render(entry, &infinite);
        let expected = render(sampled, &bounded);
        assert_eq!(actual.len(), expected.len());
        for (index, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
            assert!(
                (actual - expected).abs() <= expected.abs() / 1024.,
                "{entry}: pixel {} channel {}: {actual}, sampler {expected}",
                index / 4,
                index % 4
            );
        }
    }
}