indicatrix 0.9.0

A physically-based spectral gemstone renderer that turns GemCAD-style cutting instructions into rendered output.
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
//! Tests for the edge-avoiding À-Trous wavelet denoiser (`indicatrix::renderer::denoise`).
//!
//! This module is deliberately self-contained and not wired into the render loop (see
//! the module docs on `indicatrix::renderer::denoise`), so these tests exercise it directly
//! against synthetic buffers rather than through any render path.

use glam::Vec3;
use indicatrix::renderer::{
    denoise::{AtrousDenoiser, AtrousParams, GBuffers, taper_strength},
    frame_denoise::{DenoiseScratch, FirstHitSnapshot, denoise_and_tonemap_frame},
    tonemap::tonemap_to_rgba,
};
use std::ops::Range;

/// A tiny deterministic xorshift32 PRNG so tests do not need an external `rand`
/// dependency and are reproducible without any seed-management ceremony.
struct Xorshift32(u32);

impl Xorshift32 {
    const fn new(seed: u32) -> Self {
        Self(if seed == 0 { 0xdead_beef } else { seed })
    }

    const fn next_u32(&mut self) -> u32 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 17;
        x ^= x << 5;
        self.0 = x;
        x
    }

    /// Uniform float in `[0, 1)`.
    #[expect(
        clippy::cast_possible_truncation,
        reason = "the quotient is in [0, 1], well inside f32 range"
    )]
    fn next_f32(&mut self) -> f32 {
        (f64::from(self.next_u32()) / f64::from(u32::MAX)) as f32
    }

    /// Uniform float in `[-1, 1)`.
    fn next_signed(&mut self) -> f32 {
        self.next_f32().mul_add(2.0, -1.0)
    }
}

fn mse(a: &[Vec3], b: &[Vec3]) -> f64 {
    assert_eq!(a.len(), b.len());
    let mut sum = 0.0f64;
    for (x, y) in a.iter().zip(b.iter()) {
        let d = *x - *y;
        sum += f64::from(d.length_squared());
    }
    sum / a.len() as f64
}

fn all_finite(buf: &[Vec3]) -> bool {
    buf.iter()
        .all(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite())
}

/// Mean squared distance to `truth` over the pixels `xs` x `ys` of a row-major image.
fn region_mse(buf: &[Vec3], truth: Vec3, width: usize, xs: &Range<usize>, ys: Range<usize>) -> f64 {
    let mut sum = 0.0f64;
    let mut count = 0usize;
    for y in ys {
        for x in xs.clone() {
            sum += f64::from((buf[y * width + x] - truth).length_squared());
            count += 1;
        }
    }
    sum / count as f64
}

// ---------------------------------------------------------------------------------
// 1. Error reduction (not merely variance reduction).
// ---------------------------------------------------------------------------------

/// Builds a two-region ground-truth image (distinct constant color per half, distinct
/// facet id per half, matching the "sharp facet boundary" structure of an actual
/// gemstone render), adds strong per-pixel chromatic noise simulating single-hero-
/// wavelength speckle, filters it, and asserts the filtered image is measurably closer
/// to ground truth than the noisy input was.
///
/// This is the test the task description calls out by name: an over-aggressive filter
/// can reduce the *variance* of its own output while making the *error against ground
/// truth* worse (e.g. by converging confidently on the wrong local average). Comparing
/// MSE-to-ground-truth (not the filtered output's own variance) is what catches that.
#[test]
fn filtering_reduces_error_against_ground_truth() {
    let width = 48;
    let height = 48;
    let len = width * height;

    let color_a = Vec3::new(0.6, 0.5, 0.2);
    let color_b = Vec3::new(0.1, 0.3, 0.7);

    let mut ground_truth = vec![Vec3::ZERO; len];
    let mut facet_id = vec![0i32; len];
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if x < width / 2 {
                ground_truth[idx] = color_a;
                facet_id[idx] = 0;
            } else {
                ground_truth[idx] = color_b;
                facet_id[idx] = 1;
            }
        }
    }
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];

    // Strong chromatic per-pixel noise: each pixel's color is knocked toward a random
    // saturated hue, at a magnitude comparable to the signal itself -- this is meant to
    // stand in for single-hero-wavelength speckle, not small Gaussian sensor noise.
    let mut rng = Xorshift32::new(12345);
    let mut noisy = ground_truth.clone();
    for c in &mut noisy {
        let n = Vec3::new(rng.next_signed(), rng.next_signed(), rng.next_signed()) * 0.4;
        *c = (*c + n).max(Vec3::ZERO);
    }

    let inputs = GBuffers {
        color: &noisy,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    let mse_before = mse(&noisy, &ground_truth);
    let mse_after = mse(&filtered, &ground_truth);

    assert!(
        mse_after < mse_before * 0.5,
        "filtering should substantially reduce error against ground truth: mse_before={mse_before:.6}, mse_after={mse_after:.6}"
    );
}

// ---------------------------------------------------------------------------------
// 2. Edges survive: facet boundary stays sharp.
// ---------------------------------------------------------------------------------

/// Two regions of very different color, split by facet id, meeting at a sharp
/// vertical boundary and no noise. After filtering, the cross-edge color jump (the
/// last pixel of region A vs. the first pixel of region B, at the strongest kernel
/// dilation) must remain close to the original jump -- the facet hard-rejection term
/// should have prevented the filter from softening the boundary.
#[test]
fn facet_edges_survive_filtering() {
    let width = 64;
    let height = 32;
    let len = width * height;
    let split = width / 2;

    let color_a = Vec3::new(0.9, 0.05, 0.05);
    let color_b = Vec3::new(0.05, 0.05, 0.9);

    let mut color = vec![Vec3::ZERO; len];
    let mut facet_id = vec![0i32; len];
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if x < split {
                color[idx] = color_a;
                facet_id[idx] = 7;
            } else {
                color[idx] = color_b;
                facet_id[idx] = 42;
            }
        }
    }
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    // Use every pass (widest dilation, stride 16) so this is a meaningful test of the
    // worst case -- the boundary must survive even the largest kernel footprint.
    let params = AtrousParams {
        num_passes: 5,
        ..AtrousParams::default()
    };
    let filtered = denoiser.denoise(&inputs, &params);

    let y = height / 2;
    let left_idx = y * width + (split - 1);
    let right_idx = y * width + split;

    let original_jump = (color[right_idx] - color[left_idx]).length();
    let filtered_jump = (filtered[right_idx] - filtered[left_idx]).length();

    assert!(
        filtered_jump > original_jump * 0.95,
        "facet boundary must stay sharp: original_jump={original_jump:.4}, filtered_jump={filtered_jump:.4}"
    );

    // An identity filter would pass the edge check above, so run the same layout with
    // strong per-pixel noise in both regions and demand that the flat interiors (clear of
    // the boundary columns and the image border) end up at least 4x less noisy.
    let mut rng = Xorshift32::new(0xfeed);
    let noisy: Vec<Vec3> = color
        .iter()
        .map(|c| *c + Vec3::new(rng.next_signed(), rng.next_signed(), rng.next_signed()) * 0.15)
        .collect();
    let noisy_inputs = GBuffers {
        color: &noisy,
        ..inputs
    };
    let cleaned = denoiser.denoise(&noisy_inputs, &params);

    let rows = 4..height - 4;
    for (truth, xs) in [(color_a, 4..split - 4), (color_b, split + 4..width - 4)] {
        let before = region_mse(&noisy, truth, width, &xs, rows.clone());
        let after = region_mse(&cleaned, truth, width, &xs, rows.clone());
        assert!(
            after * 4.0 <= before,
            "a flat noisy region must lose at least 3/4 of its error: before={before:.6}, after={after:.6}"
        );
    }
}

/// One facet, two interior path-signature regions of nearly equal colour (the dark-stone
/// case: a reflection boundary the colour term cannot see). Without the signature the
/// boundary is smeared away; with it the boundary survives the widest kernel, and noise
/// inside each region is still averaged out.
#[test]
fn path_signature_boundary_survives_inside_one_facet() {
    let width = 64;
    let height = 32;
    let len = width * height;
    let split = width / 2;

    let color_a = Vec3::new(0.30, 0.20, 0.10);
    let color_b = Vec3::new(0.34, 0.22, 0.12);

    let mut color = vec![Vec3::ZERO; len];
    let mut sig = vec![0u32; len];
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if x < split {
                color[idx] = color_a;
                sig[idx] = 0x1111;
            } else {
                color[idx] = color_b;
                sig[idx] = 0x2222;
            }
        }
    }
    let facet_id = vec![3i32; len];
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];

    let without = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };
    let with_sig = GBuffers {
        path_sig: Some(&sig),
        ..without
    };
    let params = AtrousParams {
        num_passes: 5,
        ..AtrousParams::default()
    };
    let mut denoiser = AtrousDenoiser::new();

    let y = height / 2;
    let left_idx = y * width + (split - 1);
    let right_idx = y * width + split;
    let original_jump = (color[right_idx] - color[left_idx]).length();

    let smeared = denoiser.denoise(&without, &params);
    let smeared_jump = (smeared[right_idx] - smeared[left_idx]).length();
    assert!(
        smeared_jump < original_jump * 0.5,
        "premise: colour alone must smear this boundary: original={original_jump:.4}, smeared={smeared_jump:.4}"
    );

    let kept = denoiser.denoise(&with_sig, &params);
    let kept_jump = (kept[right_idx] - kept[left_idx]).length();
    assert!(
        kept_jump > original_jump * 0.95,
        "the signature boundary must stay sharp: original={original_jump:.4}, kept={kept_jump:.4}"
    );

    // Noise inside each region is still filtered.
    let mut rng = Xorshift32::new(0xbeef);
    let noisy: Vec<Vec3> = color
        .iter()
        .map(|c| *c + Vec3::new(rng.next_signed(), rng.next_signed(), rng.next_signed()) * 0.1)
        .collect();
    let cleaned = denoiser.denoise(
        &GBuffers {
            color: &noisy,
            ..with_sig
        },
        &params,
    );
    let rows = 4..height - 4;
    for (truth, xs) in [(color_a, 4..split - 4), (color_b, split + 4..width - 4)] {
        let before = region_mse(&noisy, truth, width, &xs, rows.clone());
        let after = region_mse(&cleaned, truth, width, &xs, rows.clone());
        assert!(
            after * 4.0 <= before,
            "a noisy region must lose at least 3/4 of its error: before={before:.6}, after={after:.6}"
        );
    }
}

// ---------------------------------------------------------------------------------
// 3. Convergence taper: near-identity at high sample counts.
// ---------------------------------------------------------------------------------

#[test]
fn high_sample_count_approaches_identity() {
    let width = 16;
    let height = 16;
    let len = width * height;

    let mut rng = Xorshift32::new(999);
    let mut color = vec![Vec3::ZERO; len];
    let mut facet_id = vec![0i32; len];
    for (i, c) in color.iter_mut().enumerate() {
        *c = Vec3::new(rng.next_f32(), rng.next_f32(), rng.next_f32());
        facet_id[i] = i32::try_from(i % 3).expect("a remainder below 3");
    }
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 100_000,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    for (f, c) in filtered.iter().zip(color.iter()) {
        let d = (*f - *c).length();
        assert!(
            d < 1.0e-5,
            "expected near-identity at high spp, got diff {d}"
        );
    }
}

#[test]
fn taper_strength_decreases_monotonically_with_spp() {
    let n0 = 4.0;
    let mut prev = taper_strength(0, n0);
    assert!(
        (prev - 1.0).abs() < 1.0e-6,
        "taper at spp=0 should be exactly 1.0"
    );
    for spp in [1u32, 4, 16, 64, 256, 1024, 100_000] {
        let t = taper_strength(spp, n0);
        assert!(
            t < prev,
            "taper must strictly decrease as spp grows (spp={spp})"
        );
        assert!(t > 0.0, "taper must stay positive (spp={spp})");
        prev = t;
    }
}

// ---------------------------------------------------------------------------------
// 4. A uniform image is unchanged (kernel-normalisation sanity check).
// ---------------------------------------------------------------------------------

#[test]
fn uniform_image_is_unchanged() {
    let width = 20;
    let height = 20;
    let len = width * height;
    let constant = Vec3::new(0.37, 0.61, 0.14);

    // Vary the guide buffers so the weight pattern per pixel is non-trivial (some
    // neighbours hard-rejected by facet id, some down-weighted by normal/depth) --
    // a normalisation bug would show up as drift away from `constant` even though
    // every contributing sample has exactly value `constant`.
    let mut rng = Xorshift32::new(42);
    let mut facet_id = vec![0i32; len];
    let mut depth = vec![0.0f32; len];
    let mut normal = vec![Vec3::Z; len];
    for i in 0..len {
        facet_id[i] = (rng.next_u32() % 4).cast_signed();
        depth[i] = rng.next_f32();
        let jitter = Vec3::new(rng.next_signed(), rng.next_signed(), 1.0).normalize();
        normal[i] = jitter;
    }
    let color = vec![constant; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    for v in &filtered {
        let d = (*v - constant).length();
        assert!(
            d < 1.0e-4,
            "uniform image must be unchanged by filtering (drift {d})"
        );
    }
}

// ---------------------------------------------------------------------------------
// 5. Determinism.
// ---------------------------------------------------------------------------------

#[test]
fn filtering_is_deterministic() {
    let width = 24;
    let height = 24;
    let len = width * height;

    let mut rng = Xorshift32::new(7);
    let mut color = vec![Vec3::ZERO; len];
    let mut facet_id = vec![0i32; len];
    let mut normal = vec![Vec3::Z; len];
    let mut depth = vec![0.0f32; len];
    for i in 0..len {
        color[i] = Vec3::new(rng.next_f32(), rng.next_f32(), rng.next_f32());
        facet_id[i] = (rng.next_u32() % 5).cast_signed();
        depth[i] = rng.next_f32();
        normal[i] = Vec3::new(rng.next_signed() * 0.1, rng.next_signed() * 0.1, 1.0).normalize();
    }

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 3,
        path_sig: None,
    };
    let params = AtrousParams::default();

    let mut denoiser_a = AtrousDenoiser::new();
    let out_a = denoiser_a.denoise(&inputs, &params);

    let mut denoiser_b = AtrousDenoiser::new();
    let out_b = denoiser_b.denoise(&inputs, &params);

    assert_eq!(out_a.len(), out_b.len());
    for (a, b) in out_a.iter().zip(out_b.iter()) {
        assert_eq!(
            a.x.to_bits(),
            b.x.to_bits(),
            "filtering must be bit-exact deterministic"
        );
        assert_eq!(a.y.to_bits(), b.y.to_bits());
        assert_eq!(a.z.to_bits(), b.z.to_bits());
    }

    // Also check that reusing the same denoiser instance across repeated calls
    // (the intended steady-state usage pattern) gives the same result as a fresh one.
    let out_c = denoiser_a.denoise(&inputs, &params);
    for (a, c) in out_a.iter().zip(out_c.iter()) {
        assert_eq!(a.x.to_bits(), c.x.to_bits());
        assert_eq!(a.y.to_bits(), c.y.to_bits());
        assert_eq!(a.z.to_bits(), c.z.to_bits());
    }
}

// ---------------------------------------------------------------------------------
// 6. Degenerate inputs: must not panic or produce NaN.
// ---------------------------------------------------------------------------------

#[test]
fn one_by_one_image_does_not_panic() {
    let color = [Vec3::new(0.3, 0.6, 0.9)];
    let depth = [1.0f32];
    let normal = [Vec3::Z];
    let facet_id = [0i32];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width: 1,
        height: 1,
        spp: 2,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    assert_eq!(filtered.len(), 1);
    assert!(all_finite(&filtered));
    let d = (filtered[0] - color[0]).length();
    assert!(
        d < 1.0e-4,
        "single-pixel image should trivially reproduce its own color"
    );
}

#[test]
fn zero_by_zero_image_does_not_panic() {
    let color: [Vec3; 0] = [];
    let depth: [f32; 0] = [];
    let normal: [Vec3; 0] = [];
    let facet_id: [i32; 0] = [];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width: 0,
        height: 0,
        spp: 0,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());
    assert_eq!(filtered, [] as [Vec3; 0]);
}

#[test]
fn zero_samples_does_not_panic_or_produce_nan() {
    let width = 8;
    let height = 8;
    let len = width * height;
    let mut rng = Xorshift32::new(2024);
    let color: Vec<Vec3> = (0..len)
        .map(|_| Vec3::new(rng.next_f32(), rng.next_f32(), rng.next_f32()))
        .collect();
    let depth = vec![0.5f32; len];
    let normal = vec![Vec3::Z; len];
    let facet_id = vec![0i32; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 0,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    assert_eq!(filtered.len(), len);
    assert!(all_finite(&filtered));
}

#[test]
fn all_black_buffer_does_not_panic_or_produce_nan() {
    let width = 10;
    let height = 10;
    let len = width * height;

    let color = vec![Vec3::ZERO; len];
    let depth = vec![0.0f32; len];
    let normal = vec![Vec3::ZERO; len]; // degenerate zero-length normals on purpose
    let facet_id = vec![0i32; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 5,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    assert_eq!(filtered.len(), len);
    assert!(all_finite(&filtered));
    for v in &filtered {
        assert_eq!(*v, Vec3::ZERO);
    }
}

#[test]
fn mismatched_buffer_lengths_degrade_gracefully() {
    let width = 6;
    let height = 6;
    let len = width * height;

    let color = vec![Vec3::new(1.0, 1.0, 1.0); len];
    // Deliberately short auxiliary buffers.
    let depth = vec![0.0f32; len / 2];
    let normal = vec![Vec3::Z; len / 2];
    let facet_id = vec![0i32; len / 2];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &AtrousParams::default());

    assert_eq!(filtered.len(), len);
    assert!(all_finite(&filtered));
}

// ---------------------------------------------------------------------------------
// 7. Parallelisation: bit-exact and thread-count invariant.
// ---------------------------------------------------------------------------------

/// Pins the property `atrous_pass`'s row-chunked parallelisation depends on: within a
/// single À-Trous pass, each output pixel is a pure function of the previous pass's
/// full input buffer, with no accumulation across pixels and no ordering dependency.
/// That means splitting the image into row chunks and running them on different
/// threads must produce output that is bit-identical (not merely close) to running the
/// whole image on one thread -- and identical again for any other thread count.
///
/// Exercised through `AtrousDenoiser::denoise_into_with_threads` (the full 5-pass
/// default pipeline, ping-ponging scratch buffers exactly as the real render loop
/// does), on a deliberately non-trivial, non-square, non-power-of-two-sized image with
/// several facet regions, jittered normals, varying depth and noisy color, so every
/// edge-stopping term actually does work and row-chunk boundaries fall unevenly across
/// most of the tested thread counts.
#[test]
fn parallel_denoise_is_bit_identical_across_thread_counts() {
    let width = 173;
    let height = 101;
    let len = width * height;

    let mut rng = Xorshift32::new(0x5eed_c0de);
    let mut color = vec![Vec3::ZERO; len];
    let mut depth = vec![0.0f32; len];
    let mut normal = vec![Vec3::Z; len];
    let mut facet_id = vec![0i32; len];
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            facet_id[idx] = i32::try_from((x / 6 + y / 4) % 7).expect("a remainder below 7");
            depth[idx] = rng.next_f32() * 3.0;
            normal[idx] =
                Vec3::new(rng.next_signed() * 0.4, rng.next_signed() * 0.4, 1.0).normalize();
            color[idx] = Vec3::new(rng.next_f32(), rng.next_f32(), rng.next_f32());
        }
    }

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };
    let params = AtrousParams::default();

    let mut reference_denoiser = AtrousDenoiser::new();
    let mut reference = Vec::new();
    reference_denoiser.denoise_into_with_threads(&inputs, &params, &mut reference, 1);

    for threads in [2usize, 8, 16] {
        let mut denoiser = AtrousDenoiser::new();
        let mut out = Vec::new();
        denoiser.denoise_into_with_threads(&inputs, &params, &mut out, threads);

        assert_eq!(out.len(), reference.len());
        for (i, (a, b)) in reference.iter().zip(out.iter()).enumerate() {
            assert_eq!(
                a.x.to_bits(),
                b.x.to_bits(),
                "threads={threads}: pixel {i} x component differs"
            );
            assert_eq!(
                a.y.to_bits(),
                b.y.to_bits(),
                "threads={threads}: pixel {i} y component differs"
            );
            assert_eq!(
                a.z.to_bits(),
                b.z.to_bits(),
                "threads={threads}: pixel {i} z component differs"
            );
        }
    }

    // The public, auto-thread-count entry point (what the real render loop calls) must
    // agree with the pinned single-threaded reference too.
    let mut auto_denoiser = AtrousDenoiser::new();
    let mut auto_out = Vec::new();
    auto_denoiser.denoise_into(&inputs, &params, &mut auto_out);
    for (a, b) in reference.iter().zip(auto_out.iter()) {
        assert_eq!(a.x.to_bits(), b.x.to_bits());
        assert_eq!(a.y.to_bits(), b.y.to_bits());
        assert_eq!(a.z.to_bits(), b.z.to_bits());
    }
}

#[test]
fn zero_passes_param_does_not_panic() {
    let width = 4;
    let height = 4;
    let len = width * height;
    let color = vec![Vec3::new(0.2, 0.4, 0.6); len];
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];
    let facet_id = vec![0i32; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };
    let params = AtrousParams {
        num_passes: 0,
        ..AtrousParams::default()
    };

    let mut denoiser = AtrousDenoiser::new();
    let filtered = denoiser.denoise(&inputs, &params);

    assert_eq!(filtered.len(), len);
    assert!(all_finite(&filtered));
}

// ---------------------------------------------------------------------------------
// 8. Non-finite texels, background pixels, and frames with no samples.
// ---------------------------------------------------------------------------------

/// One NaN or infinite color texel must stay a local problem: every other pixel of a
/// uniform image has to come out as the uniform color, and the damaged texels themselves
/// must be repaired from their neighbours rather than staying non-finite. (Previously a single NaN poisoned the whole 5x5 window of every pass.)
#[test]
fn a_non_finite_texel_does_not_contaminate_its_neighbours() {
    let width = 40;
    let height = 40;
    let len = width * height;
    let constant = Vec3::new(0.4, 0.5, 0.6);

    let mut color = vec![constant; len];
    color[20 * width + 20] = Vec3::new(f32::NAN, 0.5, 0.6);
    color[5 * width + 30] = Vec3::new(f32::INFINITY, f32::NEG_INFINITY, 0.1);
    color[35 * width + 2] = Vec3::splat(f32::NAN);
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];
    let facet_id = vec![0i32; len];

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };
    let filtered = AtrousDenoiser::new().denoise(&inputs, &AtrousParams::default());

    // A NaN distance also fails the comparison, so this covers finiteness too.
    for (i, v) in filtered.iter().enumerate() {
        let d = (*v - constant).length();
        assert!(d < 1.0e-4, "pixel {i} is {v:?}, not the uniform color");
    }
}

/// A pixel with a negative facet id is background: its value passes through every pass
/// bit for bit, while the foreground beside it is still filtered.
#[test]
fn background_pixels_are_copied_through_unfiltered() {
    let width = 24;
    let height = 24;
    let len = width * height;
    let split = 12;

    let mut rng = Xorshift32::new(77);
    let color: Vec<Vec3> = (0..len)
        .map(|_| Vec3::new(rng.next_f32(), rng.next_f32(), rng.next_f32()))
        .collect();
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];
    let facet_id: Vec<i32> = (0..len)
        .map(|i| if i % width < split { -1 } else { 3 })
        .collect();

    let inputs = GBuffers {
        color: &color,
        depth: &depth,
        normal: &normal,
        facet_id: &facet_id,
        width,
        height,
        spp: 1,
        path_sig: None,
    };
    let filtered = AtrousDenoiser::new().denoise(&inputs, &AtrousParams::default());

    let mut foreground_changed = false;
    for i in 0..len {
        if facet_id[i] < 0 {
            assert_eq!(filtered[i], color[i], "background pixel {i} was altered");
        } else {
            foreground_changed |= filtered[i] != color[i];
        }
    }
    assert!(foreground_changed, "the foreground must still be filtered");
}

/// A frame with no samples accumulated yet (the first poll) is a finite black picture,
/// not `0 * inf = NaN` pushed through the denoiser and tone-mapper.
#[test]
fn a_frame_with_no_samples_is_a_finite_black_frame() {
    let (width, height) = (6u32, 5u32);
    let len = (width * height) as usize;
    let mut rng = Xorshift32::new(31);
    let accum: Vec<Vec3> = (0..len)
        .map(|_| Vec3::new(rng.next_f32(), rng.next_f32(), rng.next_f32()))
        .collect();
    let depth = vec![1.0f32; len];
    let normal = vec![Vec3::Z; len];
    let facet_id = vec![0i32; len];

    let mut denoiser = AtrousDenoiser::new();
    let (mut avg_color_buf, mut filtered_buf) = (Vec::new(), Vec::new());
    let rgba = denoise_and_tonemap_frame(
        FirstHitSnapshot {
            width,
            height,
            current_sample_count: 0,
            accum_buffer: &accum,
            first_hit_depth: &depth,
            first_hit_normal: &normal,
            first_hit_facet_id: &facet_id,
            first_hit_path_sig: &[],
        },
        &mut DenoiseScratch {
            denoiser: &mut denoiser,
            avg_color_buf: &mut avg_color_buf,
            filtered_buf: &mut filtered_buf,
        },
    );

    assert!(all_finite(&filtered_buf));
    let black = vec![Vec3::ZERO; len];
    assert_eq!(rgba, tonemap_to_rgba(&black, 1.0));
    assert!(
        rgba.as_chunks::<4>()
            .0
            .iter()
            .all(|px| px[..3] == [0, 0, 0]),
        "a frame with no samples must be black"
    );
}