1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod autotest_generated {
5
    use super::*;
6

            
7
    /// Documented bounds from the `FxaaConfig::edge_threshold` doc comment.
8
    const EDGE_THRESHOLD_RANGE: (f32, f32) = (0.063, 0.333);
9
    /// Documented bounds from the `FxaaConfig::edge_threshold_min` doc comment.
10
    const EDGE_THRESHOLD_MIN_RANGE: (f32, f32) = (0.0312, 0.0833);
11

            
12
    /// `f32::abs` lives in `std`, and this crate is `no_std`-capable.
13
    fn fabs(x: f32) -> f32 {
14
        if x < 0.0 {
15
            -x
16
        } else {
17
            x
18
        }
19
    }
20

            
21
    /// `FxaaConfig` derives neither `PartialEq` nor `Eq`, so compare field-wise.
22
    fn same(a: FxaaConfig, b: FxaaConfig) -> bool {
23
        a.enabled == b.enabled
24
            && a.edge_threshold.to_bits() == b.edge_threshold.to_bits()
25
            && a.edge_threshold_min.to_bits() == b.edge_threshold_min.to_bits()
26
    }
27

            
28
    fn all_presets() -> [(&'static str, FxaaConfig); 5] {
29
        [
30
            ("default", FxaaConfig::default()),
31
            ("enabled", FxaaConfig::enabled()),
32
            ("high_quality", FxaaConfig::high_quality()),
33
            ("balanced", FxaaConfig::balanced()),
34
            ("performance", FxaaConfig::performance()),
35
        ]
36
    }
37

            
38
    fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
39
        if needle.is_empty() || haystack.len() < needle.len() {
40
            return None;
41
        }
42
        (0..=haystack.len() - needle.len()).find(|&i| &haystack[i..i + needle.len()] == needle)
43
    }
44

            
45
    fn contains(haystack: &[u8], needle: &[u8]) -> bool {
46
        find(haystack, needle).is_some()
47
    }
48

            
49
    // ---------------------------------------------------------------------
50
    // Preset values: exact literals, documented ranges, ordering
51
    // ---------------------------------------------------------------------
52

            
53
    #[test]
54
    fn default_is_disabled_with_documented_defaults() {
55
        let d = FxaaConfig::default();
56
        assert!(!d.enabled, "FXAA must default to off for performance");
57
        assert_eq!(d.edge_threshold, 0.125_f32);
58
        assert_eq!(d.edge_threshold_min, 0.0312_f32);
59
    }
60

            
61
    #[test]
62
    fn enabled_is_default_with_only_the_flag_flipped() {
63
        // `enabled()` is spelled `..Default::default()`; this pins that it never
64
        // silently picks up a different quality preset if Default ever changes.
65
        let e = FxaaConfig::enabled();
66
        let d = FxaaConfig::default();
67
        assert!(e.enabled);
68
        assert_eq!(e.edge_threshold.to_bits(), d.edge_threshold.to_bits());
69
        assert_eq!(
70
            e.edge_threshold_min.to_bits(),
71
            d.edge_threshold_min.to_bits()
72
        );
73
    }
74

            
75
    #[test]
76
    fn balanced_matches_enabled_default() {
77
        // "Balanced preset - default settings" — the doc claims these are the same.
78
        assert!(
79
            same(FxaaConfig::balanced(), FxaaConfig::enabled()),
80
            "balanced() drifted away from the documented default settings"
81
        );
82
    }
83

            
84
    #[test]
85
    fn every_preset_except_default_is_enabled() {
86
        for (name, cfg) in all_presets() {
87
            if name == "default" {
88
                assert!(!cfg.enabled, "{name} should be disabled");
89
            } else {
90
                assert!(cfg.enabled, "{name}() must enable FXAA");
91
            }
92
        }
93
    }
94

            
95
    #[test]
96
    fn preset_thresholds_are_within_documented_ranges() {
97
        let (lo, hi) = EDGE_THRESHOLD_RANGE;
98
        let (min_lo, min_hi) = EDGE_THRESHOLD_MIN_RANGE;
99
        for (name, cfg) in all_presets() {
100
            assert!(
101
                cfg.edge_threshold >= lo && cfg.edge_threshold <= hi,
102
                "{name}: edge_threshold {} outside documented [{lo}, {hi}]",
103
                cfg.edge_threshold
104
            );
105
            assert!(
106
                cfg.edge_threshold_min >= min_lo && cfg.edge_threshold_min <= min_hi,
107
                "{name}: edge_threshold_min {} outside documented [{min_lo}, {min_hi}]",
108
                cfg.edge_threshold_min
109
            );
110
        }
111
    }
112

            
113
    #[test]
114
    fn preset_thresholds_are_finite_and_positive() {
115
        for (name, cfg) in all_presets() {
116
            assert!(
117
                !cfg.edge_threshold.is_nan(),
118
                "{name}: edge_threshold is NaN"
119
            );
120
            assert!(
121
                cfg.edge_threshold.is_finite(),
122
                "{name}: edge_threshold is not finite"
123
            );
124
            assert!(
125
                !cfg.edge_threshold_min.is_nan(),
126
                "{name}: edge_threshold_min is NaN"
127
            );
128
            assert!(
129
                cfg.edge_threshold_min.is_finite(),
130
                "{name}: edge_threshold_min is not finite"
131
            );
132
            // A zero/negative threshold makes the shader's `lumRange < max(...)`
133
            // early-exit unreachable -> AA runs on every single fragment.
134
            assert!(
135
                cfg.edge_threshold > 0.0,
136
                "{name}: edge_threshold must be > 0"
137
            );
138
            assert!(
139
                cfg.edge_threshold_min > 0.0,
140
                "{name}: edge_threshold_min must be > 0"
141
            );
142
        }
143
    }
144

            
145
    #[test]
146
    fn min_threshold_never_exceeds_edge_threshold() {
147
        // The shader computes `max(uEdgeThresholdMin, lumMax * uEdgeThreshold)`;
148
        // with lumMax <= 1.0 the relative term can only ever win if
149
        // edge_threshold >= edge_threshold_min. If min > threshold, the relative
150
        // threshold is dead code for every possible luminance.
151
        for (name, cfg) in all_presets() {
152
            assert!(
153
                cfg.edge_threshold_min <= cfg.edge_threshold,
154
                "{name}: edge_threshold_min ({}) > edge_threshold ({}) makes the relative \
155
                 threshold unreachable",
156
                cfg.edge_threshold_min,
157
                cfg.edge_threshold
158
            );
159
        }
160
    }
161

            
162
    #[test]
163
    fn presets_are_ordered_by_aggressiveness() {
164
        // high_quality = most edges detected (lowest threshold),
165
        // performance = fewest (highest threshold), balanced in between.
166
        let hq = FxaaConfig::high_quality();
167
        let bal = FxaaConfig::balanced();
168
        let perf = FxaaConfig::performance();
169
        assert!(
170
            hq.edge_threshold < bal.edge_threshold,
171
            "high_quality must detect more edges than balanced"
172
        );
173
        assert!(
174
            bal.edge_threshold < perf.edge_threshold,
175
            "balanced must detect more edges than performance"
176
        );
177
        assert!(
178
            hq.edge_threshold_min <= bal.edge_threshold_min,
179
            "high_quality min-threshold must not exceed balanced's"
180
        );
181
        assert!(
182
            bal.edge_threshold_min <= perf.edge_threshold_min,
183
            "balanced min-threshold must not exceed performance's"
184
        );
185
    }
186

            
187
    #[test]
188
    fn const_presets_are_usable_in_const_context() {
189
        // The three `const fn` presets must stay const-evaluable: shader setup
190
        // sites may store them in statics.
191
        const HQ: FxaaConfig = FxaaConfig::high_quality();
192
        const BAL: FxaaConfig = FxaaConfig::balanced();
193
        const PERF: FxaaConfig = FxaaConfig::performance();
194
        assert!(same(HQ, FxaaConfig::high_quality()));
195
        assert!(same(BAL, FxaaConfig::balanced()));
196
        assert!(same(PERF, FxaaConfig::performance()));
197
    }
198

            
199
    #[test]
200
    fn presets_are_deterministic_across_calls() {
201
        for _ in 0..64 {
202
            assert!(same(FxaaConfig::enabled(), FxaaConfig::enabled()));
203
            assert!(same(FxaaConfig::high_quality(), FxaaConfig::high_quality()));
204
            assert!(same(FxaaConfig::balanced(), FxaaConfig::balanced()));
205
            assert!(same(FxaaConfig::performance(), FxaaConfig::performance()));
206
            assert!(same(FxaaConfig::default(), FxaaConfig::default()));
207
        }
208
    }
209

            
210
    #[test]
211
    fn config_is_copy_not_aliased() {
212
        let original = FxaaConfig::high_quality();
213
        let mut copy = original;
214
        copy.enabled = false;
215
        copy.edge_threshold = f32::NAN;
216
        copy.edge_threshold_min = f32::INFINITY;
217
        assert!(!copy.enabled);
218
        assert!(copy.edge_threshold.is_nan());
219
        // `original` must be untouched (Copy, no interior mutability / no heap).
220
        assert!(original.enabled);
221
        assert_eq!(original.edge_threshold, 0.063_f32);
222
        assert_eq!(original.edge_threshold_min, 0.0312_f32);
223
    }
224

            
225
    #[test]
226
    fn threshold_bits_round_trip_through_f32_repr() {
227
        // These values are uploaded verbatim as GL float uniforms; a bit-level
228
        // round-trip guards against any lossy re-encoding in between.
229
        for (name, cfg) in all_presets() {
230
            let t = f32::from_bits(cfg.edge_threshold.to_bits());
231
            let m = f32::from_bits(cfg.edge_threshold_min.to_bits());
232
            assert_eq!(t.to_bits(), cfg.edge_threshold.to_bits(), "{name}");
233
            assert_eq!(m.to_bits(), cfg.edge_threshold_min.to_bits(), "{name}");
234
        }
235
    }
236

            
237
    // ---------------------------------------------------------------------
238
    // The shader's threshold math, replayed in Rust against every preset
239
    // ---------------------------------------------------------------------
240

            
241
    /// Mirrors the shader's early-exit predicate:
242
    /// `lumRange < max(uEdgeThresholdMin, lumMax * uEdgeThreshold)`.
243
    fn shader_skips_aa(cfg: FxaaConfig, lum_min: f32, lum_max: f32) -> bool {
244
        let lum_range = lum_max - lum_min;
245
        let threshold = if cfg.edge_threshold_min > lum_max * cfg.edge_threshold {
246
            cfg.edge_threshold_min
247
        } else {
248
            lum_max * cfg.edge_threshold
249
        };
250
        lum_range < threshold
251
    }
252

            
253
    #[test]
254
    fn flat_regions_never_trigger_aa() {
255
        // Uniform luminance (lumRange == 0) must always take the early-exit path,
256
        // for every preset and across the whole legal luminance domain.
257
        for (name, cfg) in all_presets() {
258
            for step in 0..=32u32 {
259
                let lum = f32::from(step as u16) / 32.0;
260
                assert!(
261
                    shader_skips_aa(cfg, lum, lum),
262
                    "{name}: flat region at lum={lum} would be blurred"
263
                );
264
            }
265
        }
266
    }
267

            
268
    #[test]
269
    fn maximum_contrast_edge_always_triggers_aa() {
270
        // A pure black/white edge (lumRange == 1.0) must never be skipped:
271
        // that requires edge_threshold < 1.0 AND edge_threshold_min < 1.0.
272
        for (name, cfg) in all_presets() {
273
            assert!(
274
                !shader_skips_aa(cfg, 0.0, 1.0),
275
                "{name}: a full-contrast edge would be skipped by the shader"
276
            );
277
        }
278
    }
279

            
280
    #[test]
281
    fn dark_low_contrast_edges_are_gated_by_the_min_threshold() {
282
        // Near-black gradients: `lumMax * edge_threshold` collapses toward 0, so
283
        // only edge_threshold_min prevents AA-ing sensor noise. A tiny ramp well
284
        // below the min threshold must still be skipped.
285
        for (name, cfg) in all_presets() {
286
            let lum_min = 0.0;
287
            let lum_max = cfg.edge_threshold_min * 0.5;
288
            assert!(
289
                shader_skips_aa(cfg, lum_min, lum_max),
290
                "{name}: sub-min-threshold dark gradient (range {lum_max}) would be AA'd"
291
            );
292
        }
293
    }
294

            
295
    #[test]
296
    fn threshold_predicate_is_nan_safe() {
297
        // GL_RGBA16F / GL_RGBA32F render targets can legitimately carry NaN.
298
        // The predicate must not panic and must fall through to "no AA" (all
299
        // float comparisons against NaN are false, so lumRange < t is false).
300
        for (_, cfg) in all_presets() {
301
            let skipped = shader_skips_aa(cfg, f32::NAN, f32::NAN);
302
            assert!(!skipped, "NaN luminance must not take the flat-region path");
303
            let _ = shader_skips_aa(cfg, f32::NEG_INFINITY, f32::INFINITY);
304
            let _ = shader_skips_aa(cfg, f32::MIN, f32::MAX);
305
            let _ = shader_skips_aa(cfg, f32::MAX, f32::MIN);
306
        }
307
    }
308

            
309
    #[test]
310
    fn extreme_luminance_inputs_do_not_produce_nan_thresholds() {
311
        // lumMax * edge_threshold with a huge lumMax must stay finite-or-inf,
312
        // never NaN (NaN would silently disable the early exit).
313
        for (name, cfg) in all_presets() {
314
            for &lum_max in &[0.0_f32, 1.0, 1e30, f32::MAX, f32::MIN_POSITIVE] {
315
                let t = lum_max * cfg.edge_threshold;
316
                assert!(
317
                    !t.is_nan(),
318
                    "{name}: threshold went NaN at lumMax={lum_max}"
319
                );
320
            }
321
        }
322
    }
323

            
324
    // ---------------------------------------------------------------------
325
    // Shader source bytes: what the GL driver actually receives
326
    // ---------------------------------------------------------------------
327

            
328
    #[test]
329
    fn shaders_are_non_empty_ascii_utf8() {
330
        for (name, src) in [
331
            ("vertex", FXAA_VERTEX_SHADER),
332
            ("fragment", FXAA_FRAGMENT_SHADER),
333
        ] {
334
            assert!(!src.is_empty(), "{name} shader is empty");
335
            let text = core::str::from_utf8(src)
336
                .unwrap_or_else(|e| panic!("{name} shader is not valid UTF-8: {e}"));
337
            // GLSL 1.50 source must be ASCII outside of comments; a stray
338
            // non-ASCII byte (e.g. a smart quote from an editor) is a hard
339
            // compile error on some drivers.
340
            assert!(
341
                text.is_ascii(),
342
                "{name} shader contains non-ASCII bytes (unicode smuggled into GLSL)"
343
            );
344
        }
345
    }
346

            
347
    #[test]
348
    fn shaders_contain_no_interior_nul_byte() {
349
        // These are handed to glShaderSource; an embedded NUL truncates the
350
        // source at the driver and yields a baffling "missing main()" error.
351
        for (name, src) in [
352
            ("vertex", FXAA_VERTEX_SHADER),
353
            ("fragment", FXAA_FRAGMENT_SHADER),
354
        ] {
355
            assert!(
356
                !src.contains(&0u8),
357
                "{name} shader contains an interior NUL byte"
358
            );
359
        }
360
    }
361

            
362
    #[test]
363
    fn version_directive_is_the_first_token() {
364
        // GLSL requires #version to precede everything but comments/whitespace.
365
        for (name, src) in [
366
            ("vertex", FXAA_VERTEX_SHADER),
367
            ("fragment", FXAA_FRAGMENT_SHADER),
368
        ] {
369
            let text = core::str::from_utf8(src).expect("utf8");
370
            assert!(
371
                text.starts_with("#version 150"),
372
                "{name} shader must open with `#version 150`, got: {:?}",
373
                &text[..text.len().min(24)]
374
            );
375
        }
376
    }
377

            
378
    #[test]
379
    fn shaders_have_balanced_braces_and_parens() {
380
        for (name, src) in [
381
            ("vertex", FXAA_VERTEX_SHADER),
382
            ("fragment", FXAA_FRAGMENT_SHADER),
383
        ] {
384
            let mut braces: i32 = 0;
385
            let mut parens: i32 = 0;
386
            for &b in src {
387
                match b {
388
                    b'{' => braces += 1,
389
                    b'}' => braces -= 1,
390
                    b'(' => parens += 1,
391
                    b')' => parens -= 1,
392
                    _ => {}
393
                }
394
                assert!(braces >= 0, "{name} shader closes a brace it never opened");
395
                assert!(parens >= 0, "{name} shader closes a paren it never opened");
396
            }
397
            assert_eq!(braces, 0, "{name} shader has unbalanced braces");
398
            assert_eq!(parens, 0, "{name} shader has unbalanced parens");
399
        }
400
    }
401

            
402
    #[test]
403
    fn shaders_define_main() {
404
        assert!(contains(FXAA_VERTEX_SHADER, b"void main()"));
405
        assert!(contains(FXAA_FRAGMENT_SHADER, b"void main()"));
406
    }
407

            
408
    #[test]
409
    fn fragment_shader_declares_every_uniform_the_host_feeds() {
410
        // These names are the contract with the GL pass in layout/src/xml/svg.rs;
411
        // renaming one of them here silently turns the uniform lookup into -1.
412
        for uniform in [
413
            &b"uniform sampler2D uTexture;"[..],
414
            &b"uniform vec2 uTexelSize;"[..],
415
            &b"uniform float uEdgeThreshold;"[..],
416
            &b"uniform float uEdgeThresholdMin;"[..],
417
        ] {
418
            assert!(
419
                contains(FXAA_FRAGMENT_SHADER, uniform),
420
                "fragment shader is missing uniform declaration: {}",
421
                core::str::from_utf8(uniform).unwrap()
422
            );
423
        }
424
    }
425

            
426
    #[test]
427
    fn vertex_and_fragment_varyings_match() {
428
        // vTexCoord is written by the vertex stage and read by the fragment
429
        // stage; a name mismatch is a link error at runtime only.
430
        assert!(contains(FXAA_VERTEX_SHADER, b"varying vec2 vTexCoord;"));
431
        assert!(contains(FXAA_FRAGMENT_SHADER, b"varying vec2 vTexCoord;"));
432
        assert!(contains(FXAA_VERTEX_SHADER, b"attribute vec2 vAttrXY;"));
433
        // The fragment stage must not redeclare the vertex attribute.
434
        assert!(!contains(FXAA_FRAGMENT_SHADER, b"attribute vec2 vAttrXY;"));
435
    }
436

            
437
    #[test]
438
    fn both_shaders_guard_the_es100_compatibility_defines() {
439
        // `#define varying out` (VS) / `#define varying in` (FS) must stay behind
440
        // a `__VERSION__ != 100` guard, or ES2 builds break.
441
        assert!(contains(FXAA_VERTEX_SHADER, b"#if __VERSION__ != 100"));
442
        assert!(contains(FXAA_VERTEX_SHADER, b"#define varying out"));
443
        assert!(contains(FXAA_FRAGMENT_SHADER, b"#if __VERSION__ != 100"));
444
        assert!(contains(FXAA_FRAGMENT_SHADER, b"#define varying in"));
445
        assert!(contains(FXAA_FRAGMENT_SHADER, b"#if __VERSION__ == 100"));
446
        assert!(contains(
447
            FXAA_FRAGMENT_SHADER,
448
            b"#define oFragColor gl_FragColor"
449
        ));
450
    }
451

            
452
    #[test]
453
    fn luminance_weights_are_rec709_and_sum_to_one() {
454
        // Parse the literal `dot(color, vec3(...))` weights straight out of the
455
        // shader text. Weights that don't sum to 1.0 would darken/brighten the
456
        // edge-detection luminance and desync it from the thresholds above.
457
        let text = core::str::from_utf8(FXAA_FRAGMENT_SHADER).expect("utf8");
458
        let start = find(FXAA_FRAGMENT_SHADER, b"dot(color, vec3(")
459
            .expect("fragment shader must compute luminance via dot(color, vec3(..))")
460
            + b"dot(color, vec3(".len();
461
        let rest = &text[start..];
462
        let end = rest.find(')').expect("unterminated vec3(");
463
        let mut weights = [0.0_f32; 3];
464
        let mut count = 0usize;
465
        for part in rest[..end].split(',') {
466
            let v: f32 = part
467
                .trim()
468
                .parse()
469
                .unwrap_or_else(|_| panic!("non-numeric luminance weight: {part:?}"));
470
            assert!(
471
                count < 3,
472
                "luminance vec3 has more than 3 components: {:?}",
473
                &rest[..end]
474
            );
475
            weights[count] = v;
476
            count += 1;
477
        }
478
        assert_eq!(count, 3, "luminance vec3 must have exactly 3 components");
479

            
480
        // Rec. 709 coefficients.
481
        assert_eq!(weights[0], 0.2126_f32, "R weight is not Rec.709");
482
        assert_eq!(weights[1], 0.7152_f32, "G weight is not Rec.709");
483
        assert_eq!(weights[2], 0.0722_f32, "B weight is not Rec.709");
484

            
485
        let sum = weights[0] + weights[1] + weights[2];
486
        assert!(
487
            fabs(sum - 1.0) < 1e-6,
488
            "luminance weights sum to {sum}, not 1.0 — white would not map to lum 1.0"
489
        );
490

            
491
        // Consequence the thresholds rely on: luminance(white) == 1.0, so
492
        // lumMax is bounded by 1.0 for any LDR color, which is what makes
493
        // `lumMax * edge_threshold <= edge_threshold` hold.
494
        for (name, cfg) in all_presets() {
495
            assert!(
496
                sum * cfg.edge_threshold <= cfg.edge_threshold + 1e-6,
497
                "{name}: relative threshold can exceed edge_threshold for white"
498
            );
499
        }
500
    }
501

            
502
    #[test]
503
    fn fragment_shader_writes_the_output_on_every_path() {
504
        // Both the early-exit branch and the two edge branches must assign
505
        // oFragColor; an unwritten output is undefined-value garbage.
506
        let text = core::str::from_utf8(FXAA_FRAGMENT_SHADER).expect("utf8");
507
        let writes = text.matches("oFragColor =").count();
508
        assert!(
509
            writes >= 3,
510
            "expected >= 3 oFragColor writes (early-exit + 2 branches), found {writes}"
511
        );
512
    }
513

            
514
    #[test]
515
    fn shader_direction_clamp_is_symmetric() {
516
        // `min(vec2(8.0), max(vec2(-8.0), dir * rcpDirMin))` — the FXAA span
517
        // clamp must be symmetric, otherwise edges blur asymmetrically.
518
        assert!(contains(
519
            FXAA_FRAGMENT_SHADER,
520
            b"min(vec2(8.0), max(vec2(-8.0)"
521
        ));
522
        // dirReduce must be clamped away from zero, or rcpDirMin divides by 0.
523
        assert!(contains(FXAA_FRAGMENT_SHADER, b"0.0078125"));
524
        assert!(contains(FXAA_FRAGMENT_SHADER, b"max("));
525
    }
526

            
527
    #[test]
528
    fn shader_dir_reduce_never_divides_by_zero() {
529
        // Replay `1.0 / (min(|dir.x|, |dir.y|) + dirReduce)` for the worst case:
530
        // an entirely black neighborhood, where every luminance is 0.
531
        let (lum_n, lum_s, lum_e, lum_w) = (0.0_f32, 0.0, 0.0, 0.0);
532
        let dir_x = (lum_n + lum_s) - (lum_e + lum_w);
533
        let dir_y = lum_n - lum_s;
534
        let dir_reduce = {
535
            let raw = (lum_n + lum_s + lum_e + lum_w) * 0.25 * 0.25;
536
            if raw > 0.007_812_5 {
537
                raw
538
            } else {
539
                0.007_812_5
540
            }
541
        };
542
        let min_abs = if fabs(dir_x) < fabs(dir_y) {
543
            fabs(dir_x)
544
        } else {
545
            fabs(dir_y)
546
        };
547
        let rcp = 1.0_f32 / (min_abs + dir_reduce);
548
        assert!(
549
            rcp.is_finite(),
550
            "rcpDirMin must stay finite even for an all-black neighborhood"
551
        );
552
        assert_eq!(rcp, 128.0_f32, "1.0 / 0.0078125 == 128.0");
553
    }
554
}