indicatrix 0.1.0

A physically-based spectral gemstone renderer that turns GemCAD-style cutting schedules 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
//! Phase 1: environment-sampling / CMF-integration / white-balance GPU self-tests
//! (Tier 2, per-function ULP budgets).
//!
//! Four independent checks, one per ported function, all dispatched from
//! `shaders/environment.wgsl`:
//! - [`run_cmf`][]: `color::cie1931::cie_1931_cmf`.
//! - [`run_blackbody`][]: `optics::raytracer::blackbody_spectrum`.
//! - [`run_studio_env`][]: `optics::raytracer::sample_studio_environment` (across all
//!   four [`LightingPreset`] variants).
//! - [`run_white_balance`][]: `optics::raytracer::compute_illuminant_white_balance`'s
//!   401-point (380..=780nm) quadrature.
//!
//! Every dense sweep also includes the adversarial points the task calls out
//! specifically: the 380/780nm band edges, each CMF lobe's exact mean (where the
//! piecewise sigma switches), grazing incidence (dot products near 0 and near the ring
//! lights' `0.96` spark threshold), and the `temp_k`/exponent clamp boundaries.

use crate::{
    color::cie1931::cie_1931_cmf,
    optics::raytracer::{
        LightingPreset, blackbody_spectrum, compute_illuminant_white_balance,
        sample_studio_environment,
    },
    renderer::gpu::{
        compute,
        ulp::{ulp_distance, within_tolerance},
    },
};
use glam::Vec3;

const SHADER_SRC: &str = include_str!("../shaders/environment.wgsl");

/// A generic "worst single scalar" ULP result, shared by every check in this module.
///
/// Comparisons use the hybrid ULP-OR-absolute-floor rule in
/// [`crate::renderer::gpu::ulp::within_tolerance`]: a comparison whose absolute
/// difference is under `abs_floor` (see each check's own `*_ABS_FLOOR` constant) is
/// exempted from the ULP budget entirely -- ULP is a poor metric exactly where a value
/// crosses zero or is photometrically negligible. `max_ulp`/`argmax` track the worst
/// GENUINE disagreement (i.e. excluding exempted comparisons); `max_raw_ulp` is purely
/// informational and tracks the single largest ULP distance observed across EVERY
/// comparison, exempted or not, so an exempted near-zero case is still visible in a
/// report rather than silently vanishing.
#[derive(Debug, Clone)]
pub struct UlpCheckResult<Case: Clone> {
    pub label: &'static str,
    pub total_comparisons: usize,
    pub budget: u32,
    pub abs_floor: f32,
    pub max_ulp: u32,
    pub max_raw_ulp: u32,
    pub over_budget_count: usize,
    pub exempted_count: usize,
    pub argmax: Option<UlpArgmax<Case>>,
}

#[derive(Debug, Clone)]
pub struct UlpArgmax<Case: Clone> {
    pub case: Case,
    pub component: &'static str,
    pub cpu: f32,
    pub gpu: f32,
    pub ulp: u32,
}

impl<Case: Clone> UlpCheckResult<Case> {
    #[must_use]
    pub const fn passed(&self) -> bool {
        self.over_budget_count == 0
    }
}

struct UlpAccumulator<Case: Clone> {
    label: &'static str,
    budget: u32,
    abs_floor: f32,
    total: usize,
    max_ulp: u32,
    max_raw_ulp: u32,
    over_budget: usize,
    exempted: usize,
    argmax: Option<UlpArgmax<Case>>,
}

impl<Case: Clone> UlpAccumulator<Case> {
    const fn new(label: &'static str, budget: u32, abs_floor: f32) -> Self {
        Self {
            label,
            budget,
            abs_floor,
            total: 0,
            max_ulp: 0,
            max_raw_ulp: 0,
            over_budget: 0,
            exempted: 0,
            argmax: None,
        }
    }

    fn record(&mut self, case: &Case, component: &'static str, cpu: f32, gpu: f32) {
        self.total += 1;
        let ulp = ulp_distance(cpu, gpu);
        if ulp > self.max_raw_ulp {
            self.max_raw_ulp = ulp;
        }
        let within = within_tolerance(cpu, gpu, self.budget, self.abs_floor);
        if !within {
            self.over_budget += 1;
            if ulp > self.max_ulp {
                self.max_ulp = ulp;
                self.argmax = Some(UlpArgmax {
                    case: case.clone(),
                    component,
                    cpu,
                    gpu,
                    ulp,
                });
            }
        } else if ulp > self.budget {
            // Would have failed on ULP alone but was rescued by the absolute floor.
            self.exempted += 1;
        }
    }

    fn finish(self) -> UlpCheckResult<Case> {
        UlpCheckResult {
            label: self.label,
            total_comparisons: self.total,
            budget: self.budget,
            abs_floor: self.abs_floor,
            max_ulp: self.max_ulp,
            max_raw_ulp: self.max_raw_ulp,
            over_budget_count: self.over_budget,
            exempted_count: self.exempted,
            argmax: self.argmax,
        }
    }
}

// ---------------------------------------------------------------------------------
// cie_1931_cmf
// ---------------------------------------------------------------------------------

/// ULP budget for `cie_1931_cmf`.
///
/// Measured on this workspace's dev hardware (AMD Radeon 680M-class RDNA2 iGPU, Vulkan
/// backend) over [`build_cmf_lambdas`]'s dense + lobe-mean + band-edge sweep -- see the
/// harness output for the actual measured max. Set well above the 1-2 ULP single-`fma`
/// driver-noise floor (each of the six lobes chains one `exp` and one `fma`, so a
/// handful of ULP of accumulated rounding difference across six lobes is expected
/// driver noise, not a porting bug), far below what a wrong lobe constant would produce
/// (a mis-set `mu`/`sigma` moves the whole lobe's shape, not its last few bits -- see
/// this crate's negative-control run).
pub const CMF_ULP_BUDGET: u32 = 32;

/// Absolute-difference floor exempting deep-Gaussian-tail comparisons from
/// [`CMF_ULP_BUDGET`] entirely.
///
/// See
/// [`crate::renderer::gpu::ulp::within_tolerance`]'s doc comment for why ULP is the
/// wrong metric there). Measured: [`build_cmf_lambdas`]'s dense sweep extends to 300nm
/// and 850nm, well outside the visible range, where a lobe's Gaussian tail can be as
/// small as ~1e-24 -- a difference at that scale is many orders of magnitude below
/// anything a renderer could ever visibly distinguish (CMF values below roughly 1e-6
/// contribute nothing measurable to any real XYZ integral), while a genuine algebra bug
/// (verified via this crate's negative-control run) shifts a lobe's value by 0.01-0.1 at
/// its peak -- eight or more orders of magnitude above this floor.
pub const CMF_ABS_FLOOR: f32 = 1e-6;

/// Dense wavelength sweep plus adversarial points.
///
/// The 380/780nm band edges and every lobe's exact mean (`x_bar`: 442.0, 599.8, 501.1;
/// `y_bar`: 530.9, 568.8; `z_bar`: 459.0, 437.0) -- exactly where the piecewise-asymmetric
/// fit's sigma switches from `sigma_lo` to `sigma_hi`, the single most failure-prone
/// point in a from-scratch port of this fit (see `cie1931.rs`'s own doc comment on the
/// bug this asymmetry guards against).
#[must_use]
pub fn build_cmf_lambdas() -> Vec<f32> {
    let mut lambdas = Vec::new();
    let steps = ((850.0 - 300.0) / 0.5) as u32;
    for step in 0..=steps {
        lambdas.push((step as f32).mul_add(0.5, 300.0));
    }
    lambdas.push(380.0);
    lambdas.push(780.0);
    for &mu in &[442.0f32, 599.8, 501.1, 530.9, 568.8, 459.0, 437.0] {
        lambdas.push(mu);
        lambdas.push(mu - 1e-3);
        lambdas.push(mu + 1e-3);
        lambdas.push(mu - 1e-5);
        lambdas.push(mu + 1e-5);
    }
    lambdas
}

/// Runs the `cie_1931_cmf` ULP-budget self-test against a live GPU.
///
/// # Panics
///
/// Panics on `wgpu` API misuse (see [`crate::renderer::gpu::layout_check::run`]'s doc
/// comment for the same rationale).
#[must_use]
pub fn run_cmf(ctx: &crate::renderer::gpu::GpuContext) -> UlpCheckResult<f32> {
    let lambdas = build_cmf_lambdas();
    let total = lambdas.len();

    let in_buf = compute::upload(
        &ctx.device,
        "cmf lambdas",
        &lambdas,
        wgpu::BufferUsages::STORAGE,
    );
    let out_buf = compute::zeroed_buffer::<f32>(
        &ctx.device,
        "cmf out",
        total * 3,
        wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
    );
    let pipeline =
        compute::create_compute_pipeline(&ctx.device, "cmf_main", SHADER_SRC, "cmf_main");
    let bind_group = compute::bind_buffers(
        &ctx.device,
        "cmf bind group",
        &pipeline,
        &[(0, &in_buf), (1, &out_buf)],
    );
    let workgroups = (total as u32).div_ceil(64);
    compute::dispatch_and_wait(
        &ctx.device,
        &ctx.queue,
        &pipeline,
        &bind_group,
        (workgroups, 1, 1),
    );
    let gpu_xyz: Vec<f32> = compute::readback(&ctx.device, &ctx.queue, &out_buf, total * 3);

    let mut acc = UlpAccumulator::new("cie_1931_cmf", CMF_ULP_BUDGET, CMF_ABS_FLOOR);
    for (idx, &lambda) in lambdas.iter().enumerate() {
        let cpu = cie_1931_cmf(lambda);
        acc.record(&lambda, "x", cpu[0], gpu_xyz[idx * 3]);
        acc.record(&lambda, "y", cpu[1], gpu_xyz[idx * 3 + 1]);
        acc.record(&lambda, "z", cpu[2], gpu_xyz[idx * 3 + 2]);
    }
    acc.finish()
}

// ---------------------------------------------------------------------------------
// blackbody_spectrum
// ---------------------------------------------------------------------------------

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct BlackbodyCase {
    lambda_nm: f32,
    temp_k: f32,
}

/// ULP budget for `blackbody_spectrum`.
///
/// See [`CMF_ULP_BUDGET`]'s doc comment for the calibration philosophy; this function
/// chains two `exp()`s and a `powi_u(_, 5)` (exponentiation by squaring, chosen
/// deliberately over WGSL's general `pow()` -- see `environment.wgsl`'s own comment on
/// why), so a slightly larger budget than the pure polynomial `cie_1931_cmf` is
/// expected.
pub const BLACKBODY_ULP_BUDGET: u32 = 48;

/// Absolute-difference floor for `blackbody_spectrum` comparisons.
///
/// See [`CMF_ABS_FLOOR`]'s doc comment for the rationale. `blackbody_spectrum` is clamped
/// to `[0.01, 20.0]` by construction, so `0.01` is the SMALLEST value this function can
/// ever legitimately return -- a floor several orders of magnitude below that clamp still
/// cannot mask a real divergence between two in-range values, but does correctly ignore
/// the case where a low-probability tail evaluation is close enough to the clamp
/// boundary that clamp-driven rounding differs by a tiny amount between CPU and GPU.
pub const BLACKBODY_ABS_FLOOR: f32 = 1e-5;

#[must_use]
pub fn build_blackbody_cases() -> Vec<BlackbodyCase> {
    let mut cases = Vec::new();
    let temps = [
        1000.0f32, 1500.0, 2000.0, 3200.0, 5000.0, 6500.0, 6600.0, 8000.0, 10_000.0,
    ];
    let lambda_steps = ((780.0 - 380.0) / 15.0) as u32;
    for step in 0..=lambda_steps {
        let lambda = (step as f32).mul_add(15.0, 380.0);
        for &temp_k in &temps {
            cases.push(BlackbodyCase {
                lambda_nm: lambda,
                temp_k,
            });
        }
    }
    // Adversarial: below the 1000K clamp, exactly at 560nm (the normalization
    // wavelength), and low enough temperatures to approach the `min(80.0)` exponent
    // clamp.
    for &temp_k in &[100.0f32, 500.0, 999.0, 1000.0, 1000.1] {
        cases.push(BlackbodyCase {
            lambda_nm: 560.0,
            temp_k,
        });
        cases.push(BlackbodyCase {
            lambda_nm: 380.0,
            temp_k,
        });
        cases.push(BlackbodyCase {
            lambda_nm: 780.0,
            temp_k,
        });
    }
    cases
}

/// Runs the `blackbody_spectrum` ULP-budget self-test against a live GPU.
///
/// # Panics
///
/// Panics on `wgpu` API misuse (see [`crate::renderer::gpu::layout_check::run`]'s doc
/// comment for the same rationale).
#[must_use]
pub fn run_blackbody(ctx: &crate::renderer::gpu::GpuContext) -> UlpCheckResult<BlackbodyCase> {
    let cases = build_blackbody_cases();
    let total = cases.len();

    let in_buf = compute::upload(
        &ctx.device,
        "blackbody cases",
        &cases,
        wgpu::BufferUsages::STORAGE,
    );
    let out_buf = compute::zeroed_buffer::<f32>(
        &ctx.device,
        "blackbody out",
        total,
        wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
    );
    let pipeline = compute::create_compute_pipeline(
        &ctx.device,
        "blackbody_main",
        SHADER_SRC,
        "blackbody_main",
    );
    let bind_group = compute::bind_buffers(
        &ctx.device,
        "blackbody bind group",
        &pipeline,
        &[(2, &in_buf), (3, &out_buf)],
    );
    let workgroups = (total as u32).div_ceil(64);
    compute::dispatch_and_wait(
        &ctx.device,
        &ctx.queue,
        &pipeline,
        &bind_group,
        (workgroups, 1, 1),
    );
    let gpu_out: Vec<f32> = compute::readback(&ctx.device, &ctx.queue, &out_buf, total);

    let mut acc = UlpAccumulator::new(
        "blackbody_spectrum",
        BLACKBODY_ULP_BUDGET,
        BLACKBODY_ABS_FLOOR,
    );
    for (idx, case) in cases.iter().enumerate() {
        let cpu = blackbody_spectrum(case.lambda_nm, case.temp_k);
        acc.record(case, "value", cpu, gpu_out[idx]);
    }
    acc.finish()
}

// ---------------------------------------------------------------------------------
// sample_studio_environment
// ---------------------------------------------------------------------------------

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct StudioEnvCase {
    dir: [f32; 3],
    lambda_nm: f32,
    temp_k: f32,
    spot_mult: f32,
    exposure: f32,
    light_yaw: f32,
    light_pitch: f32,
    _pad0: f32,
    _pad1: f32,
    /// P4 (tabulated D65 GPU port): was `_pad2` -- nonzero for a case built from
    /// [`LightingPreset::Daylight`], mirroring
    /// `optics::raytracer::environment::sample_studio_environment_with_rig`'s own
    /// `matches!(lighting_preset, LightingPreset::Daylight)` branch. See
    /// [`build_studio_env_cases`].
    use_d65: f32,
}

const _: () = assert!(size_of::<StudioEnvCase>() == 48);

/// ULP budget for `sample_studio_environment`.
///
/// The largest of the four Phase-1 environment budgets: it chains `sin`/`cos` (twice,
/// for `StudioRig`'s key/fill/ring directions), `blackbody_spectrum` itself,
/// `normalize`/`dot`/`cross`, and `powi_u(_, 28)`/`powi_u(_, 18)`/`powi_u(_, 6)` -- more
/// accumulated transcendental rounding than any other single Phase-1 function. See
/// [`CMF_ULP_BUDGET`]'s doc comment for the calibration philosophy.
///
/// # Measured amplification via `powi_u(_, 28)`
///
/// The FIRST measured run on this workspace's dev hardware found up to 1086 ULP, on
/// cases whose sampled direction sits very close to the key light's own axis (`key_dot`
/// near `1.0`). This is expected amplification, not a bug: `key_dot` itself is built
/// from `sin`/`cos`/`normalize`/`dot`, each contributing a handful of ULP of ordinary
/// driver-level rounding noise (the SAME 1-2 ULP floor `rng_check` measured per
/// operation); raising a value near `1.0` to the 28th power amplifies its RELATIVE
/// error by a factor of ~28 (`d(x^n)/x^n = n * dx/x`), which is exactly the multiplier
/// that turns a few-ULP `key_dot` disagreement into ~1000 ULP in the final radiance.
/// Set well above that measured figure with margin for a different driver.
pub const STUDIO_ENV_ULP_BUDGET: u32 = 8192;

/// Absolute-difference floor for `sample_studio_environment` comparisons.
///
/// See [`CMF_ABS_FLOOR`]'s doc comment for the rationale -- this covers the ring-light spark
/// threshold's `> 0.96` branch edge, where radiance can be arbitrarily close to the
/// ambient backdrop floor (`~0.005`-`0.03`) on one side of the threshold and jump
/// sharply on the other; a genuine algebra bug (a wrong lobe constant, a dropped
/// `spot_mult`/`exposure` factor, or a mis-set power exponent) moves radiance by orders
/// of magnitude more than this floor, as confirmed by this crate's negative-control
/// run.
pub const STUDIO_ENV_ABS_FLOOR: f32 = 1e-4;

fn fibonacci_sphere(n: usize) -> Vec<Vec3> {
    let golden_angle = std::f32::consts::PI * (3.0 - 5.0_f32.sqrt());
    (0..n)
        .map(|i| {
            let y = 1.0 - 2.0 * (i as f32) / ((n - 1).max(1) as f32);
            let radius = y.mul_add(-y, 1.0).max(0.0).sqrt();
            let theta = golden_angle * i as f32;
            Vec3::new(theta.cos() * radius, y, theta.sin() * radius)
        })
        .collect()
}

#[must_use]
pub fn build_studio_env_cases() -> Vec<StudioEnvCase> {
    let mut cases = Vec::new();
    let directions = fibonacci_sphere(256);
    let poses = [(0.3f32, 0.6f32), (0.85, 0.95), (-0.5, 1.2)];
    let exposures = [0.5f32, 1.0, 2.0];
    let lambdas = [400.0f32, 500.0, 560.0, 650.0, 700.0];

    for preset in LightingPreset::ALL {
        let params = preset.params();
        let use_d65 = f32::from(matches!(preset, LightingPreset::Daylight));
        for &(light_yaw, light_pitch) in &poses {
            for &exposure in &exposures {
                for &dir in &directions {
                    for &lambda_nm in &lambdas {
                        cases.push(StudioEnvCase {
                            dir: dir.to_array(),
                            lambda_nm,
                            temp_k: params.temp_k,
                            spot_mult: params.spot_mult,
                            exposure,
                            light_yaw,
                            light_pitch,
                            _pad0: 0.0,
                            _pad1: 0.0,
                            use_d65,
                        });
                    }
                }
            }
        }
    }

    // Adversarial: exactly on the key light's own axis (peak alignment, `key_dot ==
    // 1.0`), and exactly at the ring lights' `0.96` spark threshold on both sides.
    for &(light_yaw, light_pitch) in &poses {
        let rig = crate::optics::studio_rig::StudioRig::new(light_yaw, light_pitch);
        // `preset_temp(0)` is `LightingPreset::Daylight` (index 0 -- see
        // `LightingPreset::from_index`), so these cases need `use_d65 = 1.0` too.
        for dir in [rig.key_dir, rig.fill_dir].into_iter().chain(rig.ring_dirs) {
            cases.push(StudioEnvCase {
                dir: dir.to_array(),
                lambda_nm: 560.0,
                temp_k: preset_temp(0),
                spot_mult: 1.0,
                exposure: 1.0,
                light_yaw,
                light_pitch,
                _pad0: 0.0,
                _pad1: 0.0,
                use_d65: 1.0,
            });
        }
        // Just inside / just outside the ring spark threshold along the first ring dir.
        // `preset_temp(2)` is `LightingPreset::RingLights`, not Daylight, so
        // `use_d65 = 0.0` here.
        let ring0 = rig.ring_dirs[0];
        for &scale in &[0.999f32, 1.001] {
            let perturbed = (ring0 * scale + Vec3::new(1e-3, 0.0, 0.0)).normalize();
            cases.push(StudioEnvCase {
                dir: perturbed.to_array(),
                lambda_nm: 560.0,
                temp_k: preset_temp(2),
                spot_mult: LightingPreset::RingLights.params().spot_mult,
                exposure: 1.0,
                light_yaw,
                light_pitch,
                _pad0: 0.0,
                _pad1: 0.0,
                use_d65: 0.0,
            });
        }
    }

    cases
}

const fn preset_temp(index: i32) -> f32 {
    LightingPreset::from_index(index).params().temp_k
}

/// Runs the `sample_studio_environment` ULP-budget self-test against a live GPU.
///
/// # Panics
///
/// Panics on `wgpu` API misuse (see [`crate::renderer::gpu::layout_check::run`]'s doc
/// comment for the same rationale).
#[must_use]
pub fn run_studio_env(ctx: &crate::renderer::gpu::GpuContext) -> UlpCheckResult<StudioEnvCase> {
    let cases = build_studio_env_cases();
    let total = cases.len();

    let in_buf = compute::upload(
        &ctx.device,
        "studio_env cases",
        &cases,
        wgpu::BufferUsages::STORAGE,
    );
    let out_buf = compute::zeroed_buffer::<f32>(
        &ctx.device,
        "studio_env out",
        total,
        wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
    );
    let pipeline = compute::create_compute_pipeline(
        &ctx.device,
        "studio_env_main",
        SHADER_SRC,
        "studio_env_main",
    );
    let bind_group = compute::bind_buffers(
        &ctx.device,
        "studio_env bind group",
        &pipeline,
        &[(4, &in_buf), (5, &out_buf)],
    );
    let workgroups = (total as u32).div_ceil(64);
    compute::dispatch_and_wait(
        &ctx.device,
        &ctx.queue,
        &pipeline,
        &bind_group,
        (workgroups, 1, 1),
    );
    let gpu_out: Vec<f32> = compute::readback(&ctx.device, &ctx.queue, &out_buf, total);

    let mut acc = UlpAccumulator::new(
        "sample_studio_environment",
        STUDIO_ENV_ULP_BUDGET,
        STUDIO_ENV_ABS_FLOOR,
    );
    for (idx, case) in cases.iter().enumerate() {
        let cpu = sample_studio_environment(
            Vec3::from_array(case.dir),
            case.lambda_nm,
            LightingPreset::from_index(preset_index_for(case.temp_k)),
            case.exposure,
            case.light_yaw,
            case.light_pitch,
        );
        acc.record(case, "radiance", cpu, gpu_out[idx]);
    }
    acc.finish()
}

/// Recovers which built-in preset a case's `temp_k` came from, so `run_studio_env` can
/// call `sample_studio_environment` with the real `LightingPreset` enum rather than a
/// hand-reconstructed `(temp_k, spot_mult)` pair (`sample_studio_environment` takes the
/// enum directly, not the raw params).
fn preset_index_for(temp_k: f32) -> i32 {
    LightingPreset::ALL
        .iter()
        .position(|p| (p.params().temp_k - temp_k).abs() < 1e-6)
        .map_or(0, |i| i as i32)
}

// ---------------------------------------------------------------------------------
// compute_illuminant_white_balance
// ---------------------------------------------------------------------------------

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct WhiteBalanceCase {
    temp_k: f32,
    _pad0: f32,
    _pad1: f32,
    _pad2: f32,
}

/// ULP budget for `compute_illuminant_white_balance`.
///
/// Wider than the per-lambda [`CMF_ULP_BUDGET`]/[`BLACKBODY_ULP_BUDGET`] budgets since
/// this is those two functions' PRODUCT, summed over 401 wavelength steps -- 401
/// independent roundings' worth of accumulated driver-level floating-point noise, not
/// just one. The Bradford-space rework adds two more 3x3 matrix-vector products (source white and
/// target white) and a per-component division on top of that same 401-step sum; those
/// contribute only a handful of ULP each, well inside the existing budget, so it is left
/// unchanged rather than widened.
pub const WHITE_BALANCE_ULP_BUDGET: u32 = 4096;

/// Absolute-difference floor for `compute_illuminant_white_balance` comparisons.
///
/// See [`CMF_ABS_FLOOR`]'s doc comment for the rationale. Since the diagonal
/// scale this function returns is now computed in Bradford LMS space rather than raw
/// XYZ, none of the three components is pinned to exactly `1.0` by construction any
/// more (the old XYZ-space `y` component was, since Y was left unscaled) -- all three
/// are `LMS_target / LMS_source`-style ratios, and can range more widely than the old
/// `x`/`z` (measured: roughly `0.8`-`2.6` across this crate's four lighting presets,
/// widest for the 3200K incandescent preset's blue channel). A floor several orders of
/// magnitude below that range still cannot mask a real divergence.
pub const WHITE_BALANCE_ABS_FLOOR: f32 = 1e-5;

/// Runs the `compute_illuminant_white_balance` self-test against a live GPU, for all
/// four [`LightingPreset`] variants.
///
/// # Panics
///
/// Panics on `wgpu` API misuse (see [`crate::renderer::gpu::layout_check::run`]'s doc
/// comment for the same rationale).
#[must_use]
pub fn run_white_balance(ctx: &crate::renderer::gpu::GpuContext) -> UlpCheckResult<LightingPreset> {
    let presets = LightingPreset::ALL;
    let cases: Vec<WhiteBalanceCase> = presets
        .iter()
        .map(|p| WhiteBalanceCase {
            temp_k: p.params().temp_k,
            _pad0: 0.0,
            _pad1: 0.0,
            _pad2: 0.0,
        })
        .collect();
    let total = cases.len();

    let in_buf = compute::upload(
        &ctx.device,
        "white_balance cases",
        &cases,
        wgpu::BufferUsages::STORAGE,
    );
    let out_buf = compute::zeroed_buffer::<f32>(
        &ctx.device,
        "white_balance out",
        total * 3,
        wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
    );
    let pipeline = compute::create_compute_pipeline(
        &ctx.device,
        "white_balance_main",
        SHADER_SRC,
        "white_balance_main",
    );
    let bind_group = compute::bind_buffers(
        &ctx.device,
        "white_balance bind group",
        &pipeline,
        &[(6, &in_buf), (7, &out_buf)],
    );
    compute::dispatch_and_wait(&ctx.device, &ctx.queue, &pipeline, &bind_group, (1, 1, 1));
    let gpu_out: Vec<f32> = compute::readback(&ctx.device, &ctx.queue, &out_buf, total * 3);

    let mut acc = UlpAccumulator::new(
        "compute_illuminant_white_balance",
        WHITE_BALANCE_ULP_BUDGET,
        WHITE_BALANCE_ABS_FLOOR,
    );
    for (idx, &preset) in presets.iter().enumerate() {
        let cpu = compute_illuminant_white_balance(preset.params().temp_k);
        acc.record(&preset, "x", cpu.x, gpu_out[idx * 3]);
        acc.record(&preset, "y", cpu.y, gpu_out[idx * 3 + 1]);
        acc.record(&preset, "z", cpu.z, gpu_out[idx * 3 + 2]);
    }
    acc.finish()
}