tm25ray 0.2.5

Reader, writer and far-field converter for IES TM-25 ray files (.TM25RAY): near-field LED and light-source ray sets — zero-copy, streaming, WASM-clean, no dependencies
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
//! IES TM-25 ray files (`.TM25RAY`): zero-copy and streaming readers, a
//! writer, flux-preserving subsampling, a far-field C/γ converter, a
//! luminance map ([`luminance`]), a quality report ([`quality`]), a channel
//! mixer ([`mod@mix`]) with V(λ) photometry ([`photometry`]), and LightTools
//! import/export ([`lighttools`]).
//!
//! TM-25 describes a light source as individual rays (start point in mm,
//! unit direction, flux) rather than an angular intensity table, so it is
//! the near-field counterpart of EULUMDAT/IES LM-63.
//!
//! # Layout (TM-25-13, little-endian)
//!
//! Verified against real vendor files, the reference implementation and
//! Table 4-2 of the standard; see `docs/format.md` in the repository for the
//! full table and the remaining `VERIFY` items.
//!
//! | Offset | Content |
//! |---|---|
//! | 0 | `TM25` magic, i32 version 2013, i32 creation method |
//! | 12 | f32 luminous flux lm, f32 radiant flux W, u64 ray count |
//! | 28 | 28-byte ASCII date/time, i32 start-position flag |
//! | 60 | i32 spectral id (0 none, 1 single λ, 2 per-ray λ, 3 shared table, 4 per-ray table index) |
//! | 64 | f32 single λ (NaN if unused), f32 λ min, f32 λ max |
//! | 76 | i32 spectral table count, i32 additional item count, i32 additional text size, reserved to 256 |
//! | 256 | 8 × i32 known-data flags: position, direction, radiant flux, wavelength, luminous flux, Stokes, tristimulus, spectrum index |
//! | 288 | 9 × 1000 UTF-32LE description strings |
//! | 36 288 | spectral tables (i32 N, N × (f32 λ, f32 value)), zero padded to a multiple of 32 bytes |
//! | then | one 512-byte UTF-32LE name per additional column, then the additional text block (size at offset 84, in bytes) |
//! | then | ray records: `x y z kx ky kz` + flagged columns, f32 except the i32 spectrum index |
//!
//! # Coordinates
//!
//! TM-25 positions are mm with +z the emission axis. [`direction_to_c_gamma`]
//! gives EULUMDAT angles (γ = 0 on +z, C from +x towards +y) and [`to_bevy`]
//! maps to the y-up convention used by the eulumdat-rs Bevy viewer
//! (`x, −z, y`) so a ray-derived solid overlays an LDT solid.
//!
//! # WASM
//!
//! The core is `std`-only and never touches the clock. `mmap` is an opt-in
//! feature for native builds. Browser callers feed `Blob.slice` chunks to
//! [`Tm25Reader`] through any `Read` adapter.

pub mod error;
pub mod farfield;
pub mod header;
pub mod lighttools;
pub mod luminance;
pub mod mix;
#[cfg(feature = "mmap")]
pub mod mmap;
pub mod photometry;
pub mod quality;
pub mod ray;
pub mod reader;
pub mod sample;
pub mod writer;

pub use error::{Result, Tm25Error};
pub use farfield::{FarField, FarFieldBuilder, IntensityUnit};
pub use header::{
    columns_from_flags, Column, FluxKind, Header, KnownDataFlags, ParseOptions, SpectralId,
    SpectralTable, TextFields, FIXED_HEADER_SIZE, MAGIC, VERSION_2013,
};
pub use lighttools::{
    is_lighttools, spectrum_from_rays, to_lighttools_bytes, to_lighttools_bytes_sampled,
    write_lighttools, write_lighttools_sampled, write_sre, LightToolsFile, LightToolsHeader,
    SpectrumSampler, LIGHTTOOLS_VERSION_TAG,
};
pub use luminance::{image_axes, lambertian_luminance, luminance_map, LuminanceMap};
pub use mix::{
    combine_spectra, fit_weights, mix, mixed_spectrum, mixed_totals, table_integral,
    table_value_at, weights_for_flux_fractions, Channel, MixMode,
};
#[cfg(feature = "mmap")]
pub use mmap::Tm25Mmap;
pub use photometry::{luminous_efficacy_lm_per_w, v_lambda, KM};
pub use quality::{
    quality_report, Finding, QualityAccumulator, QualityReport, QualityStats, Severity,
};
pub use ray::{direction_to_c_gamma, from_bevy, to_bevy, Ray, RayIter, RayLayout, RayView};
pub use reader::{RayStream, Tm25File, Tm25Reader};
pub use sample::{subsample, Reservoir, Rng64};
pub use writer::{encode_header, to_bytes, write_tm25};

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;

    /// Synthetic Lambertian emitter on a 2 mm square, `n` rays of `flux_each`.
    fn lambertian_rays(n: usize, flux_each: f32, seed: u64) -> Vec<Ray> {
        let mut rng = Rng64::new(seed);
        (0..n)
            .map(|_| {
                let u = rng.next_f64();
                let v = rng.next_f64();
                // Cosine-weighted hemisphere: γ = asin(√u), uniform azimuth.
                let sin_g = u.sqrt();
                let cos_g = (1.0 - u).sqrt();
                let phi = 2.0 * std::f64::consts::PI * v;
                let x = (rng.next_f64() * 2.0 - 1.0) as f32;
                let y = (rng.next_f64() * 2.0 - 1.0) as f32;
                Ray::new(
                    [x, y, -0.5],
                    [
                        (sin_g * phi.cos()) as f32,
                        (sin_g * phi.sin()) as f32,
                        cos_g as f32,
                    ],
                )
                .with_radiant_flux(flux_each)
            })
            .collect()
    }

    fn header_uv() -> Header {
        let mut h = Header::new(KnownDataFlags::radiometric());
        h.creation_method = -1;
        h.radiant_flux_w = 0.051;
        h.date_time = "2026-05-12 13:57:44".into();
        h.spectral_id = SpectralId::SharedTable;
        h.min_wavelength_nm = Some(220.0);
        h.max_wavelength_nm = Some(320.0);
        h.spectra = vec![SpectralTable {
            wavelengths_nm: (0..51).map(|i| 220.0 + 2.0 * i as f32).collect(),
            values: (0..51).map(|i| if i == 23 { 100.0 } else { 1.0 }).collect(),
        }];
        h.text.raw[0] = "SYNTH LED".into();
        h.text.raw[1] = "eulumdat-rs".into();
        h.text.raw[6] = "150mA".into();
        h
    }

    /// A Lumileds-style header: luminous flux, tristimulus columns, unknown
    /// wavelengths written as the signalling NaN, and no spectral table — so
    /// no padding, and the ray block starts right after the fixed 36 288-byte
    /// header.
    fn header_luxeon() -> Header {
        let mut flags = KnownDataFlags::photometric();
        flags.tristimulus = true;
        let mut h = Header::new(flags);
        h.creation_method = 1;
        h.luminous_flux_lm = 23.994_17;
        h.date_time = "2021-03-15T15:50:05-07:00".into();
        h.spectral_id = SpectralId::None;
        h.nan_pattern = 0x7F80_0001;
        h.text.raw[0] = "LUXEON_2835N_2780".into();
        h.text.raw[1] = "Lumileds".into();
        h
    }

    /// With no spectral table there is nothing to pad, so the ray block
    /// starts at 36 288 exactly. A real Lumileds file is laid out like this;
    /// 0.1.0 read its first ray as a column-name count of −1 089 800 634.
    #[test]
    fn header_without_spectral_table_round_trips() {
        let h = header_luxeon();
        let rays: Vec<Ray> = lambertian_rays(2_000, 1.0, 7)
            .into_iter()
            .map(|r| Ray::new(r.position(), r.direction()).with_luminous_flux(0.012))
            .collect();
        let bytes = to_bytes(&h, &rays).unwrap();
        assert_eq!(
            bytes.len(),
            FIXED_HEADER_SIZE + rays.len() * h.record_size()
        );

        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.ray_start, FIXED_HEADER_SIZE);
        assert_eq!(f.header.n_rays, 2_000);
        assert_eq!(f.header.flux_kind(), FluxKind::Photometric);
        assert_eq!(f.header.text.manufacturer(), "Lumileds");
        assert_eq!(f.rays.iter().count(), 2_000);

        // Byte-exact header round trip, including the vendor's NaN sentinel.
        let again = to_bytes(&f.header, &rays).unwrap();
        assert_eq!(&again[..FIXED_HEADER_SIZE], &bytes[..FIXED_HEADER_SIZE]);
        assert_eq!(f.header.nan_pattern, 0x7F80_0001);
    }

    /// Column names and the additional text survive a round trip, and a
    /// header with no rays is a complete file.
    #[test]
    fn column_names_and_text_round_trip() {
        let mut h = header_uv();
        h.n_additional_items = 1;
        h.column_names = vec!["user column".into()];
        h.additional_text = "notes".into();
        let bytes = to_bytes(&h, &[]).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.column_names, vec!["user column".to_string()]);
        assert_eq!(f.header.additional_text, "notes");
        // 5 chars = 20 bytes of text, padded to 32.
        assert_eq!(f.header.additional_text_size, 32);
        assert_eq!(f.header.ray_start, 36_704 + 512 + 32);
        assert_eq!(to_bytes(&f.header, &[]).unwrap(), bytes);
    }

    /// The spectral block is padded to a multiple of 32 bytes: a 51-point
    /// table (412 bytes) gets 4, a 81-point table (652 bytes) gets 20.
    #[test]
    fn spectral_block_is_padded_to_32_bytes() {
        let mut h = header_uv();
        h.spectra[0].wavelengths_nm = (0..81).map(|i| 380.0 + 5.0 * i as f32).collect();
        h.spectra[0].values = vec![1.0; 81];
        h.min_wavelength_nm = Some(380.0);
        h.max_wavelength_nm = Some(780.0);
        let rays = lambertian_rays(3, 1.0, 1);
        let bytes = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.ray_start, FIXED_HEADER_SIZE + 652 + 20);
        assert!(bytes[FIXED_HEADER_SIZE + 652..f.header.ray_start]
            .iter()
            .all(|b| *b == 0));
        assert_eq!(f.rays.get(2).unwrap().position(), rays[2].position());
    }

    /// LightTools export: radiometric with a wavelength per ray keeps the
    /// 32-byte record, and the file reads back with the same rays.
    #[test]
    fn lighttools_round_trip_spectral() {
        let mut flags = KnownDataFlags::radiometric();
        flags.wavelength = true;
        let mut h = Header::new(flags);
        h.spectral_id = SpectralId::PerRayWavelength;
        h.min_wavelength_nm = Some(400.0);
        h.max_wavelength_nm = Some(700.0);
        h.radiant_flux_w = 1.0;
        let rays: Vec<Ray> = lambertian_rays(500, 0.002, 9)
            .into_iter()
            .enumerate()
            .map(|(i, r)| r.with_wavelength(400.0 + (i % 300) as f32))
            .collect();
        let bytes = to_lighttools_bytes(&h, &rays).unwrap();
        assert_eq!(&bytes[..4], b"LTRF");
        assert_eq!(bytes.len(), 44 + 500 * 32 + 7);
        assert_eq!(&bytes[bytes.len() - 7..], b"LTRFEND");
        // Header words: major 2, minor 0, radiometric 0, near field 0, colour 2, mm 1.
        let w = |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]);
        assert_eq!([w(4), w(8), w(12), w(16), w(20), w(24)], [2, 0, 0, 0, 2, 1]);
        assert_eq!(f32::from_bits(w(40)), 1.0);
        let back = LightToolsFile::parse(&bytes).unwrap();
        assert_eq!(back.header.flux_kind, FluxKind::Radiometric);
        assert!(back.header.per_ray_wavelength);
        assert_eq!(back.rays.len(), 500);
        for (a, b) in back.rays.iter().zip(&rays) {
            assert_eq!(a.position(), b.position());
            assert_eq!(a.direction(), b.direction());
            assert_eq!(a.radiant_flux_w, b.radiant_flux_w);
            assert_eq!(a.wavelength_nm, b.wavelength_nm);
        }
    }

    /// A photometric file exports luminous flux in 28-byte records, and a
    /// flux-rescaled subsample keeps the header total meaningful.
    #[test]
    fn lighttools_photometric_and_subsample() {
        let h = header_luxeon();
        let rays: Vec<Ray> = lambertian_rays(2_000, 1.0, 7)
            .into_iter()
            .map(|r| Ray::new(r.position(), r.direction()).with_luminous_flux(0.012))
            .collect();
        let tm25 = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&tm25).unwrap();
        let mut lt = LightToolsHeader::from_tm25(&f.header).unwrap();
        assert_eq!(lt.flux_kind, FluxKind::Photometric);
        assert!(!lt.per_ray_wavelength);
        lt.total_flux = 2_000.0 * 0.012;
        let mut out = Vec::new();
        let n = write_lighttools(&mut out, &lt, subsample(&f.rays, 200, 3)).unwrap();
        assert_eq!(n, 200);
        assert_eq!(out.len(), 44 + 200 * 28 + 7);
        let back = LightToolsFile::parse(&out).unwrap();
        let sum: f32 = back.rays.iter().map(|r| r.luminous_flux_lm.unwrap()).sum();
        assert!((sum - 24.0).abs() < 1e-3, "{sum}");
        assert!(back.rays.iter().all(|r| r.radiant_flux_w.is_none()));
    }

    /// A LightTools file read back as a TM-25 header streams through the
    /// TM-25 record decoder unchanged: same columns, record size, start
    /// offset and ray count, and written out as TM-25 it parses again with
    /// the same rays.
    #[test]
    fn lighttools_reads_back_as_tm25() {
        let mut flags = KnownDataFlags::radiometric();
        flags.wavelength = true;
        let mut h = Header::new(flags);
        h.spectral_id = SpectralId::PerRayWavelength;
        h.min_wavelength_nm = Some(400.0);
        h.max_wavelength_nm = Some(700.0);
        h.radiant_flux_w = 0.5;
        let rays: Vec<Ray> = lambertian_rays(300, 0.5 / 300.0, 11)
            .into_iter()
            .enumerate()
            .map(|(i, r)| r.with_wavelength(450.0 + i as f32))
            .collect();
        let lt_bytes = to_lighttools_bytes(&h, &rays).unwrap();
        assert!(is_lighttools(&lt_bytes));
        let lt = LightToolsHeader::parse(&lt_bytes).unwrap();
        let th = lt.to_tm25_header("lamp.ray", Some(lt_bytes.len() as u64));
        assert!(th.is_lighttools());
        assert_eq!(th.n_rays, 300);
        assert_eq!(th.ray_start, 44);
        assert_eq!(th.record_size(), 32);
        assert_eq!(th.spectral_id, SpectralId::PerRayWavelength);
        assert_eq!(th.flux_kind(), FluxKind::Radiometric);
        assert_eq!(th.radiant_flux_w, 0.5);
        assert_eq!(th.text.name(), "lamp.ray");
        // Stream the records with the TM-25 layout.
        let layout = RayLayout::from_header(&th);
        let block = &lt_bytes[th.ray_start..th.ray_start + th.ray_block_size() as usize];
        let streamed: Vec<Ray> = block
            .chunks_exact(th.record_size())
            .map(|r| layout.decode(r))
            .collect();
        assert_eq!(streamed, rays);
        // And as a TM-25 file.
        let (th2, rays2) = LightToolsFile::parse(&lt_bytes)
            .unwrap()
            .to_tm25("lamp.ray");
        assert_eq!(th2, th);
        let tm25 = to_bytes(&th2, &rays2).unwrap();
        let f = Tm25File::parse(&tm25).unwrap();
        assert_eq!(f.header.version, 2013);
        assert_eq!(f.rays.iter().collect::<Vec<_>>(), rays);
        // Photometric, no wavelength: 28-byte records, luminous column.
        let lt_p = LightToolsHeader {
            flux_kind: FluxKind::Photometric,
            per_ray_wavelength: false,
            total_flux: 12.0,
            ..lt.clone()
        };
        let th_p = lt_p.to_tm25_header("p.ray", Some(lt_p.file_size_for(10)));
        assert_eq!((th_p.n_rays, th_p.record_size()), (10, 28));
        assert_eq!(th_p.flux_kind(), FluxKind::Photometric);
        assert_eq!(th_p.luminous_flux_lm, 12.0);
        assert_eq!(th_p.spectral_id, SpectralId::None);
    }

    /// `.sre` has the vendor layout; the sampler reproduces the table; the
    /// sampled export carries a wavelength per ray inside the table's range;
    /// the ray histogram recovers the spectrum from such rays.
    #[test]
    fn lighttools_spectrum_companions() {
        let h = header_uv(); // 51 points 220..320 nm, peak 100 at 266 nm
        let sre = write_sre(h.shared_spectrum().unwrap(), "UV-C sample");
        let lines: Vec<&str> = sre.split("\r\n").collect();
        assert_eq!(lines[0], "#\tUV-C sample");
        assert_eq!(lines[1], "dfat 1.0\t");
        assert_eq!(lines[2], "dataname:\tUV-C sample");
        assert_eq!(lines[3], "continuous\t");
        assert_eq!(lines[4], "radiometric\t");
        assert_eq!(lines[5], "220.0000\t0.0100");
        assert!(lines.contains(&"266.0000\t1.0000"));
        assert_eq!(lines.len(), 5 + 51 + 1);

        // Sampler: a table with two equal triangles must split 50/50 and
        // stay inside the range; a flat table is uniform.
        let flat = SpectralTable {
            wavelengths_nm: vec![400.0, 700.0],
            values: vec![1.0, 1.0],
        };
        let s = SpectrumSampler::new(&flat).unwrap();
        assert!((s.sample(0.0) - 400.0).abs() < 1e-3);
        assert!((s.sample(0.5) - 550.0).abs() < 1e-3);
        let peaked = SpectralTable {
            wavelengths_nm: vec![400.0, 450.0, 500.0],
            values: vec![0.0, 1.0, 0.0],
        };
        let s = SpectrumSampler::new(&peaked).unwrap();
        let mut rng = Rng64::new(5);
        let n = 100_000;
        let below = (0..n).filter(|_| s.sample(rng.next_f64()) < 450.0).count();
        assert!((below as f64 / n as f64 - 0.5).abs() < 0.01, "{below}");
        // Linear density 0→1 on [400, 450]: median at 400 + 50/√2.
        let mut xs: Vec<f32> = (0..n).map(|_| s.sample(rng.next_f64() * 0.5)).collect();
        xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
        assert!(
            (xs[n / 2] - (400.0 + 50.0 / 2f32.sqrt())).abs() < 0.5,
            "{}",
            xs[n / 2]
        );

        // Sampled export of the UV header: 32-byte records, λ within range.
        let rays = lambertian_rays(2_000, 0.051 / 2_000.0, 3);
        let bytes = to_lighttools_bytes_sampled(&h, &rays, 1).unwrap();
        let f = LightToolsFile::parse(&bytes).unwrap();
        assert!(f.header.per_ray_wavelength);
        assert_eq!(f.rays.len(), 2_000);
        assert!(f
            .rays
            .iter()
            .all(|r| (220.0..=320.0).contains(&r.wavelength_nm.unwrap())));
        assert_eq!(to_lighttools_bytes_sampled(&h, &rays, 1).unwrap(), bytes);
        // Histogram of those rays peaks where the table does.
        let hist = spectrum_from_rays(&f.rays, FluxKind::Radiometric, 4.0).unwrap();
        assert_eq!(hist.peak().map(|p| p.0.round()), Some(266.0));
        // No table, or photometric only: refused.
        assert!(to_lighttools_bytes_sampled(&header_luxeon(), &rays, 1).is_err());
    }

    /// The Lambertian ground truth: the map returns `Φ / (π A)` at every
    /// interior pixel from any direction, within Monte-Carlo noise, with the
    /// projected footprint shrinking by cos γ. No extra cosine anywhere.
    #[test]
    fn luminance_map_matches_lambertian_ground_truth() {
        // lambertian_rays: 2 mm square at z = 0, cosine-weighted directions.
        let n = 400_000;
        let rays = lambertian_rays(n, 1.0 / n as f32, 21);
        let expected = lambertian_luminance(1.0, 4.0); // 79 577 W/(sr·m²)
        for gamma_deg in [0.0f32, 45.0, 70.0] {
            let cos_g = gamma_deg.to_radians().cos();
            let g = gamma_deg.to_radians();
            let dir = [g.sin(), 0.0, g.cos()];
            let m = luminance_map(&rays, FluxKind::Radiometric, dir, 5.0, 0.25, 64).unwrap();
            assert_eq!(m.pixel_mm, 0.25);
            // Footprint: 2 mm × 2 mm. The view tilts in the xz-plane, so the
            // horizontal image axis (e1) is y, 8 pixels, and the vertical one
            // is the foreshortened x, 2 cos γ wide.
            assert!((m.width as f32 - 8.0).abs() <= 1.0, "width {}", m.width);
            let exp_h = (2.0 * cos_g / 0.25).round();
            assert!(
                (m.height as f32 - exp_h).abs() <= 1.0,
                "height {} vs {exp_h} at γ={gamma_deg}",
                m.height
            );
            // Interior pixels (skip the partially covered edge) average to the truth.
            let mut sum = 0.0;
            let mut cnt = 0;
            for y in 1..m.height - 1 {
                for x in 1..m.width - 1 {
                    sum += m.get(x, y);
                    cnt += 1;
                }
            }
            let mean = sum / cnt as f64;
            let noise = 1.0 / m.rays_per_lit_pixel.sqrt();
            assert!(
                (mean / expected - 1.0).abs() < 3.0 * noise / (cnt as f64).sqrt() + 0.02,
                "γ={gamma_deg}: mean {mean:.0} vs {expected:.0}, noise {noise:.3}, pixels {cnt}"
            );
            assert_eq!(m.unit(), "W/(sr·m²)");
            assert!(m.rays > 0 && m.peak > expected * 0.8);
        }
        // Caps: a 0.01 mm request on a 2 mm emitter grows to fit 32 pixels.
        let m =
            luminance_map(&rays, FluxKind::Radiometric, [0.0, 0.0, 1.0], 5.0, 0.01, 32).unwrap();
        assert!(m.width <= 32 && m.height <= 32 && m.pixel_mm > 0.06);
        // No ray towards −z: no map.
        assert!(luminance_map(
            &rays,
            FluxKind::Radiometric,
            [0.0, 0.0, -1.0],
            5.0,
            0.25,
            64
        )
        .is_none());
        // Image axes: a view along +z keeps x right and y up.
        let (e1, e2) = image_axes([0.0, 0.0, 1.0]);
        assert!(
            (e1[0] - 1.0).abs() < 1e-6 && (e2[1] - 1.0).abs() < 1e-6,
            "{e1:?} {e2:?}"
        );
    }

    /// V(λ) peaks at 555 nm; a monochromatic line there has 683 lm/W, a
    /// UV table essentially none; a photometric vendor header whose lm/W
    /// disagrees with its own spectrum is flagged by the quality report.
    #[test]
    fn photometry_and_lm_per_w_check() {
        assert_eq!(v_lambda(555.0), 1.0);
        assert!((v_lambda(507.0) - 0.4456).abs() < 0.001); // between 0.4073 at 505 and 0.503 at 510
        assert_eq!(v_lambda(300.0), 0.0);
        let line = SpectralTable {
            wavelengths_nm: vec![554.0, 555.0, 556.0],
            values: vec![0.0, 1.0, 0.0],
        };
        let ler = luminous_efficacy_lm_per_w(&line).unwrap();
        assert!((ler - 683.0).abs() < 1.0, "{ler}");
        assert!(luminous_efficacy_lm_per_w(header_uv().shared_spectrum().unwrap()).unwrap() < 0.1);
        // A yellow-ish table: header claims 311 lm/W, consistent → no finding;
        // header claims 200 lm/W → warning.
        let t = SpectralTable {
            wavelengths_nm: (0..31).map(|i| 500.0 + 10.0 * i as f32).collect(),
            values: (0..31)
                .map(|i| {
                    let d = (i as f32 - 12.0) / 7.0;
                    100.0 * (-d * d).exp()
                })
                .collect(),
        };
        let ler = luminous_efficacy_lm_per_w(&t).unwrap();
        let mut h = Header::new(KnownDataFlags::photometric());
        h.spectral_id = SpectralId::SharedTable;
        h.spectra = vec![t];
        h.luminous_flux_lm = 100.0;
        h.radiant_flux_w = (100.0 / ler) as f32;
        let rays: Vec<Ray> = lambertian_rays(1_000, 1.0, 1)
            .into_iter()
            .map(|r| Ray::new(r.position(), r.direction()).with_luminous_flux(0.1))
            .collect();
        let ok = quality_report(&h, &rays);
        assert!(
            !ok.findings.iter().any(|f| f.code == "lm-per-w"),
            "{:?}",
            ok.findings
        );
        h.radiant_flux_w = 0.5;
        let bad = quality_report(&h, &rays);
        assert!(
            bad.findings
                .iter()
                .any(|f| f.code == "lm-per-w" && f.severity == Severity::Warning),
            "{:?}",
            bad.findings
        );
    }

    /// Two channels (narrow blue, broad yellow) mix into one file whose
    /// flux and spectrum follow the weights, in both modes, through the
    /// writer and the strict parser; the fit recovers known weights.
    #[test]
    fn mix_channels_shared_and_indexed() {
        let blue_t = SpectralTable {
            wavelengths_nm: (0..21).map(|i| 430.0 + 2.0 * i as f32).collect(),
            values: (0..21)
                .map(|i| {
                    let d = (i as f32 - 10.0) / 4.0;
                    100.0 * (-d * d).exp()
                })
                .collect(),
        };
        let yellow_t = SpectralTable {
            wavelengths_nm: (0..31).map(|i| 500.0 + 10.0 * i as f32).collect(),
            values: (0..31)
                .map(|i| {
                    let d = (i as f32 - 12.0) / 7.0;
                    100.0 * (-d * d).exp()
                })
                .collect(),
        };
        // Photometric channel files with radiant totals, as ams OSRAM ships them.
        let channel = |t: &SpectralTable, lm: f32, w: f32, seed: u64| {
            let mut h = Header::new(KnownDataFlags::photometric());
            h.spectral_id = SpectralId::SharedTable;
            h.luminous_flux_lm = lm;
            h.radiant_flux_w = w;
            h.min_wavelength_nm = Some(t.wavelengths_nm[0]);
            h.max_wavelength_nm = Some(*t.wavelengths_nm.last().unwrap());
            h.spectra = vec![t.clone()];
            h.text.raw[0] = "GW TEST".into();
            let n = 4_000;
            let rays: Vec<Ray> = lambertian_rays(n, 1.0, seed)
                .into_iter()
                .map(|r| Ray::new(r.position(), r.direction()).with_luminous_flux(lm / n as f32))
                .collect();
            (h, rays)
        };
        let (hb, rb) = channel(&blue_t, 12.0, 0.1, 1);
        let (hy, ry) = channel(&yellow_t, 226.0, 0.725, 2);
        let channels = [
            Channel {
                header: &hb,
                rays: &rb,
                weight: 1.0,
                label: "blue".into(),
                spectrum: None,
            },
            Channel {
                header: &hy,
                rays: &ry,
                weight: 0.5,
                label: "yellow".into(),
                spectrum: None,
            },
        ];
        // Shared: lumens and watts both present, scaled by the weights.
        let (h, rays) = mix(&channels, MixMode::Shared).unwrap();
        assert_eq!(h.flux_kind(), FluxKind::Both);
        assert_eq!(rays.len(), 8_000);
        let lm: f64 = rays
            .iter()
            .map(|r| r.luminous_flux_lm.unwrap() as f64)
            .sum();
        let w: f64 = rays.iter().map(|r| r.radiant_flux_w.unwrap() as f64).sum();
        assert!((lm - (12.0 + 113.0)).abs() < 1e-2, "{lm}");
        assert!((w - (0.1 + 0.3625)).abs() < 1e-3, "{w}");
        assert!((h.luminous_flux_lm - 125.0).abs() < 1e-3);
        assert_eq!(h.spectral_id, SpectralId::SharedTable);
        let t = h.shared_spectrum().unwrap();
        assert_eq!(
            (t.wavelengths_nm[0], *t.wavelengths_nm.last().unwrap()),
            (430.0, 800.0)
        );
        // Blue carries 0.1 of 0.4625 W = 21.6 % of the radiant power: the
        // energy below 500 nm must be that fraction (the narrow blue line
        // still has the higher spectral peak, as in a real white LED).
        let below: f64 = (1..t.len())
            .filter(|i| t.wavelengths_nm[*i] <= 500.0)
            .map(|i| (t.values[i - 1] + t.values[i]) as f64 * 0.5)
            .sum();
        let frac = below / table_integral(t);
        assert!((frac - 0.216).abs() < 0.02, "blue fraction {frac}");
        assert_eq!(t.peak().map(|p| p.0), Some(450.0));
        let bytes = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.spectra[0].len(), t.len());
        // Indexed: radiometric only, two tables, index per ray, strict parse.
        let (hi, ri) = mix(&channels, MixMode::Indexed).unwrap();
        assert_eq!(hi.flux_kind(), FluxKind::Radiometric);
        assert_eq!(hi.spectral_id, SpectralId::PerRayTableIndex);
        assert_eq!(hi.spectra.len(), 2);
        assert!(hi.flags.spectrum_index && !hi.flags.luminous_flux);
        assert_eq!(ri[0].spectrum_index, Some(1));
        assert_eq!(ri[7_999].spectrum_index, Some(2));
        let bytes = to_bytes(&hi, &ri).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.record_size(), 32);
        assert_eq!(f.rays.get(7_999).unwrap().spectrum_index, Some(2));
        let wi: f64 = f
            .rays
            .iter()
            .map(|r| r.radiant_flux_w.unwrap() as f64)
            .sum();
        assert!((wi - 0.4625).abs() < 1e-3, "{wi}");
        // Fit: a target made of 0.3 blue + 0.7 yellow (by radiant power) is recovered.
        let target = combine_spectra(&[(&blue_t, 0.3), (&yellow_t, 0.7)]).unwrap();
        let w = fit_weights(&target, &[&blue_t, &yellow_t]);
        let sum: f64 = w.iter().sum();
        assert!(
            (w[0] / sum - 0.3).abs() < 0.01 && (w[1] / sum - 0.7).abs() < 0.01,
            "{w:?}"
        );
        // A channel without radiometric information cannot be mixed spectrally.
        let mut hb2 = hb.clone();
        hb2.radiant_flux_w = 0.0;
        let bad = [
            Channel {
                header: &hb2,
                rays: &rb,
                weight: 1.0,
                label: "b".into(),
                spectrum: None,
            },
            channels[1].clone(),
        ];
        assert!(mix(&bad, MixMode::Indexed).is_err());
        let (hs, _) = mix(&bad, MixMode::Shared).unwrap();
        assert_eq!(hs.flux_kind(), FluxKind::Photometric);
        assert_eq!(hs.spectral_id, SpectralId::None);
    }

    /// A clean synthetic file passes; every injected defect is reported
    /// with the right code and severity, and the text report lists them.
    #[test]
    fn quality_report_finds_injected_defects() {
        let h = header_uv();
        let rays = lambertian_rays(20_000, 0.051 / 20_000.0, 4);
        let clean = quality_report(&h, &rays);
        assert_eq!(clean.errors(), 0, "{:?}", clean.findings);
        assert_eq!(clean.warnings(), 0, "{:?}", clean.findings);
        assert!(clean.stats.duplicates == 0 && clean.stats.position_outliers == 0);
        assert!((clean.stats.flux_sum - 0.051).abs() < 1e-5);
        // 20k rays: about 44 per bin at γ = 30°, 15 % noise, reported as info.
        assert!(
            (0.1..0.2).contains(&clean.far_field_noise),
            "{}",
            clean.far_field_noise
        );
        let codes = |r: &QualityReport| r.findings.iter().map(|f| f.code).collect::<Vec<_>>();
        assert_eq!(codes(&clean), vec!["creation-method", "few-rays"]);

        let mut bad = rays.clone();
        bad[0].kx = 2.0; // not unit
        bad[1].radiant_flux_w = Some(f32::NAN);
        bad[2].radiant_flux_w = Some(-1e-6);
        bad[3].radiant_flux_w = Some(0.0);
        bad[4] = bad[5]; // duplicate
        bad[5000].x = 500.0; // far outside the 2 mm square (outliers are judged after a 1000-ray warm-up)
        bad[7].radiant_flux_w = Some(0.02); // one ray with 40 % of the flux
        bad[8].kz = -bad[8].kz; // backwards
        let mut h2 = h.clone();
        h2.radiant_flux_w = 0.1; // header disagrees with the sum
        let r = quality_report(&h2, &bad);
        let c = codes(&r);
        for code in [
            "flux-mismatch",
            "nan-records",
            "negative-flux",
            "zero-flux",
            "flux-outlier",
            "non-unit-direction",
            "backward-rays",
            "position-outliers",
            "duplicates",
        ] {
            assert!(c.contains(&code), "missing {code} in {c:?}");
        }
        assert!(r.errors() >= 3);
        assert!(r.verdict().contains("error"));
        let text = r.to_text("bad.TM25RAY");
        assert!(text.contains("[ERROR] flux-mismatch") && text.contains("Duplicates 1"));
        // Findings are sorted by severity, errors first.
        assert!(r
            .findings
            .windows(2)
            .all(|w| w[0].severity >= w[1].severity));

        // Wavelength bounds and spectrum index.
        let mut flags = KnownDataFlags::radiometric();
        flags.wavelength = true;
        let mut h3 = Header::new(flags);
        h3.spectral_id = SpectralId::PerRayWavelength;
        h3.min_wavelength_nm = Some(400.0);
        h3.max_wavelength_nm = Some(700.0);
        h3.radiant_flux_w = 1.0;
        let rays3: Vec<Ray> = lambertian_rays(1_000, 1e-3, 2)
            .into_iter()
            .enumerate()
            .map(|(i, r)| r.with_wavelength(if i < 10 { 900.0 } else { 550.0 }))
            .collect();
        let r3 = quality_report(&h3, &rays3);
        assert!(codes(&r3).contains(&"wavelength"));
        assert_eq!(r3.stats.wavelength_out_of_bounds, 10);
        // Few rays → noise info; µm-sized extent → warning.
        let mut h4 = header_uv();
        h4.radiant_flux_w = 1.0;
        let rays4: Vec<Ray> = lambertian_rays(500, 1.0 / 500.0, 8)
            .into_iter()
            .map(|mut r| {
                r.x *= 1000.0;
                r.y *= 1000.0;
                r
            })
            .collect();
        let r4 = quality_report(&h4, &rays4);
        assert!(
            codes(&r4).contains(&"few-rays") && codes(&r4).contains(&"extent"),
            "{:?}",
            codes(&r4)
        );
    }

    /// LightTools has no photometric + spectral combination, and a shared
    /// spectral table is not a per-ray column, so it maps to "no colour".
    #[test]
    fn lighttools_mapping_rules() {
        let h = header_uv();
        let lt = LightToolsHeader::from_tm25(&h).unwrap();
        assert_eq!(lt.flux_kind, FluxKind::Radiometric);
        assert!(!lt.per_ray_wavelength);
        let mut flags = KnownDataFlags::photometric();
        flags.wavelength = true;
        let mut bad = Header::new(flags);
        bad.spectral_id = SpectralId::PerRayWavelength;
        assert!(LightToolsHeader::from_tm25(&bad).is_err());
        let mut none = Header::new(KnownDataFlags::radiometric());
        none.flags.radiant_flux = false;
        assert!(LightToolsHeader::from_tm25(&none).is_err());
        assert!(matches!(
            LightToolsFile::parse(b"LTRX"),
            Err(Tm25Error::Truncated { .. })
        ));
        let mut v3 = to_lighttools_bytes(&h, &[]).unwrap();
        v3[4] = 3;
        assert!(matches!(
            LightToolsFile::parse(&v3),
            Err(Tm25Error::UnsupportedVersion(3))
        ));
    }

    /// The spectrum index is an i32 on disk; the f32 bit pattern the C++
    /// reference writes is accepted too.
    #[test]
    fn spectrum_index_is_an_integer_on_disk() {
        let mut flags = KnownDataFlags::radiometric();
        flags.spectrum_index = true;
        let mut h = Header::new(flags);
        h.spectral_id = SpectralId::PerRayTableIndex;
        h.min_wavelength_nm = Some(400.0);
        h.max_wavelength_nm = Some(700.0);
        let table = |peak: f32| SpectralTable {
            wavelengths_nm: vec![400.0, peak, 700.0],
            values: vec![0.0, 1.0, 0.0],
        };
        h.spectra = vec![table(450.0), table(600.0)];
        h.radiant_flux_w = 2.0;
        let rays = vec![
            Ray::new([0.0; 3], [0.0, 0.0, 1.0])
                .with_radiant_flux(1.0)
                .with_spectrum_index(1),
            Ray::new([0.0; 3], [0.0, 0.0, 1.0])
                .with_radiant_flux(1.0)
                .with_spectrum_index(2),
        ];
        let mut bytes = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        let start = f.header.ray_start;
        assert_eq!(f.header.record_size(), 32);
        assert_eq!(&bytes[start + 28..start + 32], &1i32.to_le_bytes());
        assert_eq!(f.rays.get(1).unwrap().spectrum_index, Some(2));
        // The reference's float encoding of the same index.
        bytes[start + 60..start + 64].copy_from_slice(&2.0f32.to_le_bytes());
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.rays.get(1).unwrap().spectrum_index, Some(2));
    }

    /// Unknown flux totals are NaN in the file; callers get 0.0 so arithmetic
    /// does not poison every derived value. Lumileds writes that sentinel
    /// byte-swapped, so little-endian it decodes to the denormal 2.36e-38
    /// rather than a NaN — which would look like a real, tiny measurement.
    #[test]
    fn unknown_flux_totals_are_normalised() {
        // Both spellings of "unknown": a plain NaN and the swapped sentinel.
        for bits in [0x7FC0_0001u32, 0x0100_807F] {
            let mut h = header_luxeon();
            h.luminous_flux_lm = f32::from_bits(bits);
            h.radiant_flux_w = f32::from_bits(bits);
            let bytes = to_bytes(&h, &[]).unwrap();
            let f = Tm25File::parse(&bytes).unwrap();
            assert_eq!(f.header.luminous_flux_lm, 0.0, "bits {bits:#010x}");
            assert_eq!(f.header.radiant_flux_w, 0.0, "bits {bits:#010x}");
            assert!(!f.header.total_flux(FluxKind::Photometric).is_nan());
        }
    }

    /// A normalised sentinel is written back unchanged, but an edit wins.
    #[test]
    fn unknown_sentinel_survives_a_round_trip_unless_edited() {
        let mut h = header_luxeon();
        h.radiant_flux_w = f32::from_bits(0x0100_807F);
        let bytes = to_bytes(&h, &[]).unwrap();
        let parsed = Tm25File::parse(&bytes).unwrap().header;
        assert_eq!(parsed.radiant_flux_w, 0.0);
        // Untouched: the original sentinel bits come back.
        let again = to_bytes(&parsed, &[]).unwrap();
        assert_eq!(&again[16..20], &0x0100_807Fu32.to_le_bytes());
        // Edited: the new value is written instead.
        let mut edited = parsed.clone();
        edited.radiant_flux_w = 0.051;
        let out = to_bytes(&edited, &[]).unwrap();
        assert_eq!(&out[16..20], &0.051f32.to_bits().to_le_bytes());
    }

    /// The sentinel is matched exactly. Ordinary measurements must survive,
    /// including ones whose byte-swapped image happens to look like a NaN.
    #[test]
    fn real_values_are_not_mistaken_for_unknown() {
        let mut h = header_luxeon();
        h.luminous_flux_lm = 23.994_17;
        h.radiant_flux_w = 0.051;
        h.min_wavelength_nm = Some(220.0);
        h.max_wavelength_nm = Some(320.0);
        let bytes = to_bytes(&h, &[]).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_relative_eq!(f.header.luminous_flux_lm, 23.994_17);
        assert_relative_eq!(f.header.radiant_flux_w, 0.051);
        assert_eq!(f.header.min_wavelength_nm, Some(220.0));

        // A value whose swapped bytes are a NaN pattern is still a real value.
        let tricky = f32::from_bits(0x0100_C07F);
        assert!(!tricky.is_nan());
        let mut h2 = header_luxeon();
        h2.luminous_flux_lm = tricky;
        let b2 = to_bytes(&h2, &[]).unwrap();
        let f2 = Tm25File::parse(&b2).unwrap();
        assert_eq!(f2.header.luminous_flux_lm.to_bits(), 0x0100_C07F);
    }

    /// Builder methods for the optional per-ray columns write and read back.
    #[test]
    fn wavelength_and_spectrum_index_round_trip() {
        let mut flags = KnownDataFlags::radiometric();
        flags.wavelength = true;
        let mut h = Header::new(flags);
        h.radiant_flux_w = 1.0;
        let rays: Vec<Ray> = (0..64)
            .map(|i| {
                Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
                    .with_radiant_flux(1.0 / 64.0)
                    .with_wavelength(400.0 + i as f32)
            })
            .collect();
        let bytes = to_bytes(&h, &rays).unwrap();
        let back = Tm25File::parse(&bytes).unwrap();
        let decoded: Vec<Ray> = back.rays.iter().collect();
        assert_eq!(decoded.len(), 64);
        assert_eq!(decoded[0].wavelength_nm, Some(400.0));
        assert_eq!(decoded[63].wavelength_nm, Some(463.0));
    }

    #[test]
    fn axis_mapping_matches_photometric_solid() {
        // Emission axis (+z) lands on Bevy −Y, C = 0 (+x) on +X, C = 90 (+y) on +Z.
        assert_eq!(to_bevy([0.0, 0.0, 1.0]), [0.0, -1.0, 0.0]);
        assert_eq!(to_bevy([1.0, 0.0, 0.0]), [1.0, 0.0, 0.0]);
        assert_eq!(to_bevy([0.0, 1.0, 0.0]), [0.0, 0.0, 1.0]);
        assert_eq!(from_bevy(to_bevy([0.3, -0.7, 2.0])), [0.3, -0.7, 2.0]);
        // Proper rotation: (x × y) · z stays +1.
        let (a, b, c) = (
            to_bevy([1.0, 0.0, 0.0]),
            to_bevy([0.0, 1.0, 0.0]),
            to_bevy([0.0, 0.0, 1.0]),
        );
        let cross = [
            a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0],
        ];
        let det = cross[0] * c[0] + cross[1] * c[1] + cross[2] * c[2];
        assert_eq!(det, 1.0);
    }

    #[test]
    fn c_gamma_convention() {
        let (c, g) = direction_to_c_gamma(0.0, 0.0, 1.0);
        assert_relative_eq!(g, 0.0);
        assert_relative_eq!(c, 0.0);
        let (c, g) = direction_to_c_gamma(1.0, 0.0, 0.0);
        assert_relative_eq!(g, 90.0);
        assert_relative_eq!(c, 0.0);
        let (c, g) = direction_to_c_gamma(0.0, 1.0, 0.0);
        assert_relative_eq!(g, 90.0);
        assert_relative_eq!(c, 90.0);
        let (c, _) = direction_to_c_gamma(0.0, -1.0, 1.0);
        assert_relative_eq!(c, 270.0);
        let (_, g) = direction_to_c_gamma(0.0, 0.0, -1.0);
        assert_relative_eq!(g, 180.0);
    }

    #[test]
    fn round_trip_header_and_rays() {
        let rays = lambertian_rays(1000, 5.1e-5, 1);
        let bytes = to_bytes(&header_uv(), &rays).unwrap();
        // 51-point table = 412 bytes, padded to 416: the ray block starts at
        // 36 704, as in the ams OSRAM files.
        assert_eq!(bytes.len(), 36_704 + 1000 * 28);
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.version, 2013);
        assert_eq!(f.header.creation_method, -1);
        assert_eq!(f.header.n_rays, 1000);
        assert_eq!(f.header.ray_start, 36_704);
        assert_eq!(f.header.record_size(), 28);
        assert_eq!(f.header.date_time, "2026-05-12 13:57:44");
        assert_eq!(f.header.spectral_id, SpectralId::SharedTable);
        assert_eq!(f.header.single_wavelength_nm, None);
        assert_eq!(f.header.min_wavelength_nm, Some(220.0));
        assert_eq!(f.header.flux_kind(), FluxKind::Radiometric);
        assert_eq!(f.header.text.name(), "SYNTH LED");
        assert_eq!(f.header.text.operating_condition(), "150mA");
        let t = f.header.shared_spectrum().unwrap();
        assert_eq!(t.len(), 51);
        assert_eq!(t.peak(), Some((266.0, 100.0)));
        assert!(t.is_ultraviolet());
        assert_eq!(f.rays.len(), 1000);
        for (i, r) in f.rays.iter().enumerate() {
            assert_eq!(r, rays[i]);
        }
        assert_eq!(f.rays.get(1000), None);
        // Header re-encodes identically.
        let again = encode_header(&f.header, 1000).unwrap();
        assert_eq!(again, &bytes[..36_704]);
    }

    #[test]
    fn errors_are_descriptive() {
        let rays = lambertian_rays(10, 1.0, 2);
        let bytes = to_bytes(&header_uv(), &rays).unwrap();

        let mut bad = bytes.clone();
        bad[0] = b'X';
        assert!(matches!(Tm25File::parse(&bad), Err(Tm25Error::BadMagic(_))));

        let mut bad = bytes.clone();
        bad[4..8].copy_from_slice(&2020i32.to_le_bytes());
        assert!(matches!(
            Tm25File::parse(&bad),
            Err(Tm25Error::UnsupportedVersion(2020))
        ));

        assert!(matches!(
            Tm25File::parse(&bytes[..100]),
            Err(Tm25Error::Truncated { .. })
        ));
        assert!(matches!(
            Tm25File::parse(&bytes[..36_500]),
            Err(Tm25Error::Truncated { .. })
        ));

        assert!(matches!(
            Tm25File::parse(&bytes[..bytes.len() - 5]),
            Err(Tm25Error::SizeMismatch {
                ray_start: 36_704,
                ..
            })
        ));

        // No flux column at all is rejected strictly, accepted leniently.
        let mut h = header_uv();
        h.flags.radiant_flux = false;
        h.spectral_id = SpectralId::None;
        h.spectra.clear();
        let plain: Vec<Ray> = rays
            .iter()
            .map(|r| Ray::new(r.position(), r.direction()))
            .collect();
        let b = to_bytes(&h, &plain).unwrap();
        assert!(matches!(
            Tm25File::parse(&b),
            Err(Tm25Error::InvalidHeader(_))
        ));
        let lenient = Tm25File::parse_with(
            &b,
            &ParseOptions {
                strict_flags: false,
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(lenient.header.record_size(), 24);
        assert_eq!(lenient.rays.get(0).unwrap().radiant_flux_w, None);

        // Bad UTF-32 in a text field.
        let mut bad = bytes.clone();
        bad[288..292].copy_from_slice(&0x0011_0000u32.to_le_bytes());
        assert!(matches!(
            Tm25File::parse(&bad),
            Err(Tm25Error::InvalidText { field: "name", .. })
        ));
    }

    #[test]
    fn additional_items_shift_the_ray_block() {
        let mut h = header_uv();
        h.n_additional_items = 1;
        h.column_names = vec!["phase".to_string()];
        h.additional_text = "hi".to_string();
        let rays = lambertian_rays(5, 1.0, 3);
        let bytes = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        // 4 bytes of padding after the table, a 512-byte name, 2 text chars
        // (8 bytes) padded to 32.
        assert_eq!(f.header.ray_start, 36_700 + 4 + 512 + 32);
        assert_eq!(f.header.record_size(), 32);
        assert_eq!(f.header.columns.last(), Some(&Column::Additional(0)));
        assert_eq!(f.header.column_names, vec!["phase".to_string()]);
        assert_eq!(f.header.additional_text, "hi");
        assert_eq!(f.header.additional_text_size, 32);
        assert_eq!(f.rays.get(4).unwrap().position(), rays[4].position());
        assert_eq!(
            f.rays
                .layout()
                .field(f.rays.raw(0).unwrap(), Column::Additional(0)),
            Some(0.0)
        );
    }

    #[test]
    fn photometric_and_both_layouts() {
        let mut h = Header::new(KnownDataFlags::photometric());
        h.luminous_flux_lm = 100.0;
        let rays: Vec<Ray> = lambertian_rays(3, 1.0, 4)
            .into_iter()
            .map(|r| Ray::new(r.position(), r.direction()).with_luminous_flux(2.5))
            .collect();
        let bytes = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.flux_kind(), FluxKind::Photometric);
        assert_eq!(f.rays.get(0).unwrap().luminous_flux_lm, Some(2.5));
        assert_eq!(f.rays.get(0).unwrap().flux(FluxKind::Photometric), 2.5);

        let mut h = Header::new(KnownDataFlags {
            luminous_flux: true,
            ..KnownDataFlags::radiometric()
        });
        h.radiant_flux_w = 1.0;
        h.luminous_flux_lm = 683.0;
        let rays: Vec<Ray> = rays.iter().map(|r| r.with_radiant_flux(0.01)).collect();
        let bytes = to_bytes(&h, &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        assert_eq!(f.header.flux_kind(), FluxKind::Both);
        assert_eq!(f.header.record_size(), 32);
        assert_eq!(f.header.column_index(Column::LuminousFlux), Some(7));
    }

    #[test]
    fn streaming_reader_matches_slice_reader() {
        let rays = lambertian_rays(10_007, 1e-6, 5);
        let bytes = to_bytes(&header_uv(), &rays).unwrap();
        let slice = Tm25File::parse(&bytes).unwrap();

        // Feed through a Read that returns tiny pieces to exercise buffering.
        struct Trickle<'a>(&'a [u8], usize);
        impl std::io::Read for Trickle<'_> {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                let n = buf.len().min(self.1).min(self.0.len());
                buf[..n].copy_from_slice(&self.0[..n]);
                self.0 = &self.0[n..];
                Ok(n)
            }
        }
        let mut reader = Tm25Reader::new(Trickle(&bytes, 1000)).unwrap();
        assert_eq!(reader.header(), &slice.header);
        let mut all = Vec::new();
        loop {
            let chunk = reader.read_chunk(999).unwrap();
            if chunk.is_empty() {
                break;
            }
            all.extend(chunk);
        }
        assert_eq!(all.len(), 10_007);
        assert!(all.iter().zip(slice.rays.iter()).all(|(a, b)| *a == b));

        let streamed: Vec<Ray> = Tm25Reader::new(Trickle(&bytes, 4096))
            .unwrap()
            .rays()
            .map(|r| r.unwrap())
            .collect();
        assert_eq!(streamed, all);

        // Early EOF is a ray-count error, not a panic.
        let mut short = Tm25Reader::new(Trickle(&bytes[..bytes.len() - 28 * 10], 4096)).unwrap();
        let mut got = 0u64;
        let err = loop {
            match short.read_chunk(4096) {
                Ok(v) if v.is_empty() => panic!("expected an error"),
                Ok(v) => got += v.len() as u64,
                Err(e) => break e,
            }
        };
        assert!(
            matches!(err, Tm25Error::RayCountMismatch { expected: 10_007, actual } if actual >= got)
        );
    }

    #[test]
    fn subsampling_preserves_flux_and_is_deterministic() {
        let rays = lambertian_rays(5000, 1e-5, 6);
        let bytes = to_bytes(&header_uv(), &rays).unwrap();
        let f = Tm25File::parse(&bytes).unwrap();
        let total: f64 = f
            .rays
            .iter()
            .map(|r| r.radiant_flux_w.unwrap() as f64)
            .sum();

        let a = subsample(&f.rays, 500, 42);
        let b = subsample(&f.rays, 500, 42);
        let c = subsample(&f.rays, 500, 43);
        assert_eq!(a.len(), 500);
        assert_eq!(a, b);
        assert_ne!(a, c);
        let kept: f64 = a.iter().map(|r| r.radiant_flux_w.unwrap() as f64).sum();
        assert_relative_eq!(kept, total, max_relative = 1e-4);
        assert_eq!(subsample(&f.rays, 10_000, 1).len(), 5000);

        let mut res = Reservoir::new(300, 7);
        res.extend(f.rays.iter());
        assert_eq!(res.seen(), 5000);
        let kept = res.finish();
        assert_eq!(kept.len(), 300);
        let sum: f64 = kept.iter().map(|r| r.radiant_flux_w.unwrap() as f64).sum();
        assert_relative_eq!(sum, total, max_relative = 1e-4);
        let mut res2 = Reservoir::new(300, 7);
        res2.extend(f.rays.iter());
        assert_eq!(res2.finish(), kept);
    }

    #[test]
    fn far_field_of_lambertian_is_cosine() {
        let rays = lambertian_rays(400_000, 1e-6, 8);
        let ff = FarField::from_rays(&rays, 10.0, 5.0, FluxKind::Radiometric);
        assert_eq!(ff.unit, IntensityUnit::WattPerSteradian);
        assert_eq!(ff.ray_count, 400_000);
        assert_relative_eq!(ff.total_flux, 0.4, max_relative = 1e-6);
        // Lambertian: I(γ) = Φ/π · cos γ.
        let prof = ff.azimuthal_average();
        let g = ff.g_angles();
        let i0 = 0.4 / std::f64::consts::PI;
        for (gi, &gamma) in g.iter().enumerate() {
            if gamma < 80.0 {
                assert_relative_eq!(prof[gi], i0 * gamma.to_radians().cos(), max_relative = 0.05);
            }
            if gamma > 90.0 {
                assert_eq!(prof[gi], 0.0);
            }
        }
        let half = ff.half_intensity_gamma().unwrap();
        assert!((half - 60.0).abs() < 2.0, "half intensity at {half}");
        assert_relative_eq!(ff.forward_fraction(), 1.0, max_relative = 1e-6);
        // Nearest-bin and bilinear agree at bin centres; bilinear is continuous.
        assert_relative_eq!(ff.sample_nearest(0.0, 0.0), ff.intensity(0, 0));
        assert_relative_eq!(ff.sample_nearest(359.9, 179.9), ff.intensity(35, 35));
        assert_relative_eq!(ff.sample(5.0, 2.5), ff.intensity(0, 0));
        assert_relative_eq!(ff.sample(355.0, 177.5), ff.intensity(35, 35));
        let mid = ff.sample(10.0, 2.5);
        assert!((mid - 0.5 * (ff.intensity(0, 0) + ff.intensity(1, 0))).abs() < 1e-9);
        // Smoothing keeps a rotationally symmetric profile and removes pole noise.
        let sm = ff.smoothed(1, 0, 10.0);
        let p0: Vec<f64> = (0..36).map(|ci| sm.intensity(ci, 0)).collect();
        assert!(p0.iter().all(|v| (v - p0[0]).abs() < 1e-9));
        assert_relative_eq!(sm.azimuthal_average()[10], prof[10], max_relative = 0.02);
        // Single bins near the axis hold only ~85 rays, so the per-bin maximum
        // is noisy; the azimuthal average of the first bin is the robust check.
        assert_relative_eq!(prof[0], i0, max_relative = 0.05);
        assert!(ff.max_intensity() >= prof[0]);
    }
}