dcmnorm 0.22.4

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
//! Builds a 3D voxel volume from a set of DICOM slice files sharing a `FrameOfReference` and
//! resamples arbitrary oblique planes through it (server-side MPR - Multiplanar Reformation).
//!
//! Reuses `super::render`'s existing per-frame pixel-decode pipeline
//! (`decode_frame_grayscale_values`, which already handles decompression across transfer syntaxes
//! and modality LUT application) for every source slice, and its VOI-windowing/encode pipeline
//! (`apply_voi_window`, `encode_rendered_frame`) for the reformatted output - so a volume's voxels
//! and a reformatted plane's rendering are never a second, drifting implementation of what 2D
//! rendering already does.

use std::error::Error;
use std::fmt;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;

use dcmnorm_core::Tag;
use dcmnorm_dictionary::tags;
use dcmnorm_object::DefaultDicomObject;
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

use super::io::read_dicom_bytes;
#[cfg(not(target_arch = "wasm32"))]
use super::io::{read_dicom_file, read_dicom_file_deferring_bulk_data};
#[cfg(not(target_arch = "wasm32"))]
use super::render::RenderMetadata;
use super::render::{
    apply_voi_window, decode_frame_grayscale_values, encode_rendered_frame,
    ensure_native_render_object, RenderedFramePixels,
};
pub use super::render::{RenderFrameOutput, RenderOutputFormat};
use super::types::{ReadError, RenderError};

/// Tolerance, in direction-cosine units, for treating two slices' `ImageOrientationPatient` as
/// "the same plane orientation" - i.e. a parallel stack. DICOM direction cosines are typically
/// exact to several decimal places within one series; this is generous enough to absorb float
/// round-trip noise while still catching a genuinely gantry-tilted-inconsistent or multi-orientation
/// series.
const ORIENTATION_EPSILON: f64 = 1e-3;

/// In-plane slice-origin drift, in pixels, above which a stack counts as sheared (gantry tilt, or
/// any other acquisition whose `ImagePositionPatient` step is not parallel to the row x column
/// normal) and is desheared while building. Well below anything visible (a twentieth of a pixel)
/// but far above the rounding noise of DS-encoded positions.
const SHEAR_TOLERANCE_PX: f64 = 0.05;

/// Largest growth of the slice plane a deshear may cause (the desheared grid covers the union of
/// every slice's footprint): beyond this the "stack" is not one tilted acquisition but positions
/// that make no sense together, and building is refused instead of allocating a huge grid.
const MAX_DESHEAR_PLANE_GROWTH: f64 = 4.0;

/// Relative deviation of one slice gap from the stack's nominal spacing above which the stack
/// counts as irregularly spaced (`Volume::has_irregular_spacing`).
const IRREGULAR_SPACING_TOLERANCE: f64 = 0.01;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Interpolation {
    Nearest,
    Trilinear,
}

/// How a slab's samples (see `PlaneParams::slab_thickness_mm`) combine into one output pixel.
/// `MaximumIntensity` (MIP) is the conventional radiology default for a thick MPR - it's what
/// makes vessels/bright structures visible across a slab instead of only whichever thin plane
/// happens to intersect them.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SlabProjection {
    MaximumIntensity,
    MinimumIntensity,
    Average,
}

/// Parameters for one reformatted plane through a `Volume`. `origin`/`row_dir`/`col_dir` are in
/// patient (LPS) millimeters, matching `Volume::origin`/`row_vector`/`col_vector`.
#[derive(Clone, Debug)]
pub struct PlaneParams {
    /// World-space (mm) point at the CENTER of the output image.
    pub origin: [f64; 3],
    /// Unit vector: direction of travel across the output image as the column index increases.
    pub row_dir: [f64; 3],
    /// Unit vector: direction of travel down the output image as the row index increases.
    pub col_dir: [f64; 3],
    pub output_width: u32,
    pub output_height: u32,
    /// Physical size of one output pixel, in mm - the SAME value in both output axes
    /// (isotropic), which is what makes a coronal/sagittal/oblique reformat physically
    /// undistorted even when the volume's own row/column/slice spacings differ.
    pub spacing_mm: f64,
    pub window_center: Option<f64>,
    pub window_width: Option<f64>,
    pub interpolation: Interpolation,
    /// Total slab thickness, in mm, centered on `origin` along the plane's own normal
    /// (`cross(row_dir, col_dir)`) - `0.0` (the default) reformats an infinitely-thin single
    /// plane, matching every other field's "just a flat 2D slice" behavior. A positive value
    /// samples multiple depths spanning this thickness and combines them per `slab_projection` -
    /// e.g. a 20mm MIP slab makes a thin vessel visible even when it only crosses the exact
    /// center plane at one point.
    pub slab_thickness_mm: f64,
    /// Combination method for `slab_thickness_mm > 0.0` - ignored (but still validated as
    /// present) when thickness is `0.0`.
    pub slab_projection: SlabProjection,
}

#[derive(Debug)]
pub enum VolumeError {
    Empty,
    TooFewSlices {
        found: usize,
        required: usize,
    },
    Read(ReadError),
    Render(RenderError),
    MissingGeometry(&'static str),
    InconsistentGeometry(String),
    InconsistentDimensions,
    UnsupportedPhotometricInterpretation(String),
    InvalidOutputDimensions,
    InvalidSlabThickness,
    /// Internal: a classic one-slice-per-file read met a multi-frame file, so `build_volume`
    /// switches to its per-frame path. Never returned to callers.
    MultiFrameSource,
}

impl fmt::Display for VolumeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(formatter, "no files given to build a volume from"),
            Self::TooFewSlices { found, required } => write!(
                formatter,
                "not enough slices to build a volume: found {found}, need at least {required}"
            ),
            Self::Read(error) => write!(formatter, "failed to read a DICOM file for volume building: {error}"),
            Self::Render(error) => write!(formatter, "failed to decode a slice for volume building: {error}"),
            Self::MissingGeometry(attribute) => write!(
                formatter,
                "missing or unparseable {attribute} - MPR requires full slice geometry"
            ),
            Self::InconsistentGeometry(message) => write!(formatter, "inconsistent slice geometry: {message}"),
            Self::InconsistentDimensions => write!(
                formatter,
                "slices in this series do not all share the same Rows/Columns"
            ),
            Self::UnsupportedPhotometricInterpretation(value) => write!(
                formatter,
                "unsupported PhotometricInterpretation for volume building: {value} (only MONOCHROME1/MONOCHROME2 are supported)"
            ),
            Self::InvalidOutputDimensions => write!(formatter, "requested output width/height is invalid"),
            Self::InvalidSlabThickness => write!(formatter, "slab thickness must be zero (a thin plane) or a positive number of millimeters"),
            Self::MultiFrameSource => write!(formatter, "a multi-frame file needs the per-frame volume path"),
        }
    }
}

impl Error for VolumeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Read(error) => Some(error),
            Self::Render(error) => Some(error),
            _ => None,
        }
    }
}

impl From<ReadError> for VolumeError {
    fn from(value: ReadError) -> Self {
        Self::Read(value)
    }
}

impl From<RenderError> for VolumeError {
    fn from(value: RenderError) -> Self {
        Self::Render(value)
    }
}

/// A 3D voxel volume assembled from a parallel stack of DICOM slices, with modality LUT
/// (RescaleSlope/RescaleIntercept) already applied per-slice - `samples` holds physically
/// meaningful values (e.g. Hounsfield units for CT), not raw stored integers.
pub struct Volume {
    // `Debug` is implemented manually below (omitting `samples`, which can be hundreds of MB) so
    // this type stays usable in `assert!`/`{:?}` failure messages without flooding test output.
    /// Flat `[slice][row][col]` array (slice-major, then row-major within a slice - matching how
    /// `decode_frame_grayscale_values` already returns each slice), length
    /// `rows * cols * num_slices`.
    pub samples: Vec<f32>,
    pub rows: u32,
    pub cols: u32,
    pub num_slices: u32,
    /// `ImagePositionPatient` of the spatially-first (sorted) slice, mm, patient/LPS space.
    pub origin: [f64; 3],
    /// Unit vector: direction of travel as COLUMN index increases (`ImageOrientationPatient[0..3]`).
    pub row_vector: [f64; 3],
    /// Unit vector: direction of travel as ROW index increases (`ImageOrientationPatient[3..6]`).
    pub col_vector: [f64; 3],
    /// Unit vector: direction of travel as SLICE index increases (`cross(row_vector, col_vector)`,
    /// re-derived from the actual sort order so it always points from slice 0 toward the last).
    pub slice_normal: [f64; 3],
    /// `PixelSpacing[1]` (column spacing) - physical distance between adjacent columns, i.e. the
    /// step size along `row_vector`.
    pub col_spacing_mm: f64,
    /// `PixelSpacing[0]` (row spacing) - physical distance between adjacent rows, i.e. the step
    /// size along `col_vector`.
    pub row_spacing_mm: f64,
    /// Each (sorted) slice's projected position along `slice_normal`, mm - `slice_zs[0]`
    /// corresponds to `origin`. Monotonically non-decreasing. Kept as real per-slice positions
    /// (not an assumed-uniform spacing) so any irregular gap in the acquisition is still handled
    /// correctly during resampling.
    pub slice_zs: Vec<f64>,
    /// `Modality` of the first source slice, when present (`CT`, `MR`, `PT`, ...). Registration
    /// uses it to pick its metric, intensity normalization and body mask.
    pub modality: Option<String>,
    /// `FrameOfReferenceUID` of the first source slice, when present.
    pub frame_of_reference_uid: Option<String>,
    /// `SeriesInstanceUID` of the first source slice, when present.
    pub series_instance_uid: Option<String>,
    /// `StudyInstanceUID` of the first source slice, when present.
    pub study_instance_uid: Option<String>,
    /// Angle, in degrees, between the acquisition's slice-to-slice `ImagePositionPatient` step and
    /// the slice normal - the gantry tilt of a tilted CT. `0.0` for an ordinary stack.
    pub gantry_tilt_deg: f64,
    /// Whether `build_volume` resampled the slices in-plane onto an orthogonal grid because the
    /// stack was sheared (`gantry_tilt_deg` > 0). The volume's geometry fields then describe that
    /// orthogonal grid, which may be larger than the source images (`rows`/`cols` cover the union
    /// of every slice's footprint).
    pub desheared: bool,
}

impl fmt::Debug for Volume {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Volume")
            .field("rows", &self.rows)
            .field("cols", &self.cols)
            .field("num_slices", &self.num_slices)
            .field("origin", &self.origin)
            .field("row_vector", &self.row_vector)
            .field("col_vector", &self.col_vector)
            .field("slice_normal", &self.slice_normal)
            .field("col_spacing_mm", &self.col_spacing_mm)
            .field("row_spacing_mm", &self.row_spacing_mm)
            .field("slice_zs", &self.slice_zs)
            .field("modality", &self.modality)
            .field("gantry_tilt_deg", &self.gantry_tilt_deg)
            .field("desheared", &self.desheared)
            .field("samples_len", &self.samples.len())
            .finish()
    }
}

impl Volume {
    /// A reasonable default reformat origin: the volume's own physical center.
    pub fn center(&self) -> [f64; 3] {
        let half_col = (self.cols.saturating_sub(1)) as f64 / 2.0;
        let half_row = (self.rows.saturating_sub(1)) as f64 / 2.0;
        let mid_z = (self.slice_zs[0] + self.slice_zs[self.slice_zs.len() - 1]) / 2.0;
        let along_slices = mid_z - self.slice_zs[0];
        add3(
            add3(
                add3(
                    self.origin,
                    scale3(self.row_vector, half_col * self.col_spacing_mm),
                ),
                scale3(self.col_vector, half_row * self.row_spacing_mm),
            ),
            scale3(self.slice_normal, along_slices),
        )
    }

    /// A reasonable default output pixel spacing: the volume's own smallest voxel dimension, so
    /// a reformat defaults to (at least) native resolution in every direction.
    pub fn min_spacing_mm(&self) -> f64 {
        let slice_spacing = if self.slice_zs.len() > 1 {
            let span = self.slice_zs[self.slice_zs.len() - 1] - self.slice_zs[0];
            (span / (self.slice_zs.len() - 1) as f64).abs()
        } else {
            f64::INFINITY
        };
        self.row_spacing_mm
            .min(self.col_spacing_mm)
            .min(slice_spacing)
            .max(1e-6)
    }

    /// Nominal slice spacing, mm: the stack's span divided by its gap count (`0.0` for one slice).
    pub fn nominal_slice_spacing_mm(&self) -> f64 {
        let n = self.slice_zs.len();
        if n > 1 {
            ((self.slice_zs[n - 1] - self.slice_zs[0]) / (n - 1) as f64).abs()
        } else {
            0.0
        }
    }

    /// Whether any slice gap differs from the nominal spacing by more than 1% (missing slices,
    /// a variable-pitch acquisition, or a stack assembled from two ranges). The CPU reformat path
    /// always interpolates by real position; consumers that assume a uniform lattice (the GPU
    /// texture export) resample by position when this is true.
    pub fn has_irregular_spacing(&self) -> bool {
        let nominal = self.nominal_slice_spacing_mm();
        if self.slice_zs.len() < 3 || nominal <= 0.0 {
            return false;
        }
        self.slice_zs.windows(2).any(|pair| {
            ((pair[1] - pair[0]) - nominal).abs() > IRREGULAR_SPACING_TOLERANCE * nominal + 1e-4
        })
    }

    /// Row-major 4x4 matrix mapping a voxel index `(col, row, slice, 1)` to patient (LPS) mm,
    /// using the nominal uniform slice spacing (exact unless `has_irregular_spacing`).
    pub fn voxel_to_patient(&self) -> [f64; 16] {
        let dz = self.nominal_slice_spacing_mm();
        let c = scale3(self.row_vector, self.col_spacing_mm);
        let r = scale3(self.col_vector, self.row_spacing_mm);
        let k = scale3(self.slice_normal, dz);
        let o = self.origin;
        [
            c[0], r[0], k[0], o[0], //
            c[1], r[1], k[1], o[1], //
            c[2], r[2], k[2], o[2], //
            0.0, 0.0, 0.0, 1.0,
        ]
    }

    /// Samples the volume at a world (patient/LPS mm) point with trilinear interpolation, by real
    /// slice position. `None` outside the volume (beyond a one-voxel margin).
    pub fn sample_world(&self, world: [f64; 3]) -> Option<f64> {
        sample_volume_at_world_point(self, world, Interpolation::Trilinear)
    }

    fn voxel(&self, row: i64, col: i64, slice: i64) -> f32 {
        let row = row.clamp(0, self.rows as i64 - 1) as usize;
        let col = col.clamp(0, self.cols as i64 - 1) as usize;
        let slice = slice.clamp(0, self.num_slices as i64 - 1) as usize;
        let plane = self.rows as usize * self.cols as usize;
        self.samples[slice * plane + row * self.cols as usize + col]
    }
}

type Vec3 = [f64; 3];

fn dot3(a: Vec3, b: Vec3) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

fn cross3(a: Vec3, b: Vec3) -> Vec3 {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}

fn sub3(a: Vec3, b: Vec3) -> Vec3 {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}

fn add3(a: Vec3, b: Vec3) -> Vec3 {
    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}

fn scale3(a: Vec3, s: f64) -> Vec3 {
    [a[0] * s, a[1] * s, a[2] * s]
}

fn norm3(a: Vec3) -> f64 {
    dot3(a, a).sqrt()
}

fn normalize3(a: Vec3) -> Vec3 {
    let n = norm3(a);
    if n < 1e-9 {
        a
    } else {
        [a[0] / n, a[1] / n, a[2] / n]
    }
}

fn vectors_close(a: Vec3, b: Vec3, tolerance: f64) -> bool {
    norm3(sub3(a, b)) <= tolerance
}

fn read_multi_f64(
    object: &DefaultDicomObject,
    tag: Tag,
    attribute: &'static str,
) -> Result<Vec<f64>, VolumeError> {
    let element = object
        .get(tag)
        .ok_or(VolumeError::MissingGeometry(attribute))?;
    let text = element
        .to_str()
        .map_err(|_| VolumeError::MissingGeometry(attribute))?;
    let values: Vec<f64> = text
        .split('\\')
        .filter_map(|part| part.trim().parse::<f64>().ok())
        .collect();
    if values.is_empty() {
        return Err(VolumeError::MissingGeometry(attribute));
    }
    Ok(values)
}

#[cfg(not(target_arch = "wasm32"))]
fn read_orientation(object: &DefaultDicomObject) -> Result<(Vec3, Vec3), VolumeError> {
    let values = read_multi_f64(
        object,
        tags::IMAGE_ORIENTATION_PATIENT,
        "ImageOrientationPatient",
    )?;
    if values.len() < 6 {
        return Err(VolumeError::MissingGeometry("ImageOrientationPatient"));
    }
    let row_vector = normalize3([values[0], values[1], values[2]]);
    let col_vector = normalize3([values[3], values[4], values[5]]);
    Ok((row_vector, col_vector))
}

#[cfg(not(target_arch = "wasm32"))]
fn read_position(object: &DefaultDicomObject) -> Result<Vec3, VolumeError> {
    let values = read_multi_f64(object, tags::IMAGE_POSITION_PATIENT, "ImagePositionPatient")?;
    if values.len() < 3 {
        return Err(VolumeError::MissingGeometry("ImagePositionPatient"));
    }
    Ok([values[0], values[1], values[2]])
}

/// Returns `(rowSpacingMm, colSpacingMm)` - DICOM `PixelSpacing` order: value[0] is the physical
/// distance between adjacent ROWS (the step along `col_vector`), value[1] between adjacent
/// COLUMNS (the step along `row_vector`). This row/column-vs-vector pairing is the single most
/// common source of MPR aspect-ratio bugs, so it's spelled out at every call site rather than
/// left implicit.
#[cfg(not(target_arch = "wasm32"))]
fn read_pixel_spacing(object: &DefaultDicomObject) -> Result<(f64, f64), VolumeError> {
    let values = read_multi_f64(object, tags::PIXEL_SPACING, "PixelSpacing")?;
    if values.len() < 2 {
        return Err(VolumeError::MissingGeometry("PixelSpacing"));
    }
    Ok((values[0], values[1]))
}

#[cfg(not(target_arch = "wasm32"))]
struct SourceSlice {
    row_vector: Vec3,
    col_vector: Vec3,
    position: Vec3,
    row_spacing_mm: f64,
    col_spacing_mm: f64,
    metadata: RenderMetadata,
    modality: Option<String>,
    frame_of_reference_uid: Option<String>,
    series_instance_uid: Option<String>,
    study_instance_uid: Option<String>,
}

fn read_optional_str(object: &DefaultDicomObject, tag: Tag) -> Option<String> {
    let value = object.get(tag)?.to_str().ok()?;
    let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
    (!value.is_empty()).then(|| value.to_owned())
}

/// Reads and decodes one slice: its geometry plus its modality-LUT-applied values, narrowed to
/// `f32` right away so the wider decode buffer lives only as long as this call.
#[cfg(not(target_arch = "wasm32"))]
fn read_source_slice(path: &Path) -> Result<(SourceSlice, Vec<f32>), VolumeError> {
    let object = read_dicom_file(path)?;
    if is_multi_frame(&object) {
        return Err(VolumeError::MultiFrameSource);
    }
    let (row_vector, col_vector) = read_orientation(&object)?;
    let position = read_position(&object)?;
    let (row_spacing_mm, col_spacing_mm) = read_pixel_spacing(&object)?;
    let modality = read_optional_str(&object, tags::MODALITY);
    let frame_of_reference_uid = read_optional_str(&object, tags::FRAME_OF_REFERENCE_UID);
    let series_instance_uid = read_optional_str(&object, tags::SERIES_INSTANCE_UID);
    let study_instance_uid = read_optional_str(&object, tags::STUDY_INSTANCE_UID);
    let (metadata, values) = decode_frame_grayscale_values(&object, 0)?;
    drop(object);
    if !matches!(
        metadata.photometric_interpretation.as_str(),
        "MONOCHROME1" | "MONOCHROME2"
    ) {
        return Err(VolumeError::UnsupportedPhotometricInterpretation(
            metadata.photometric_interpretation.clone(),
        ));
    }
    let values: Vec<f32> = values.into_iter().map(|value| value as f32).collect();
    Ok((
        SourceSlice {
            row_vector,
            col_vector,
            position,
            row_spacing_mm,
            col_spacing_mm,
            metadata,
            modality,
            frame_of_reference_uid,
            series_instance_uid,
            study_instance_uid,
        },
        values,
    ))
}

/// Reorders `samples`' planes in place so that plane `k` holds what was plane `order[k]`, with one
/// plane of scratch space (cycle-following permutation).
#[cfg(not(target_arch = "wasm32"))]
fn permute_planes_in_place(samples: &mut [f32], plane_len: usize, order: &[usize]) {
    let mut placed = vec![false; order.len()];
    let mut scratch = vec![0f32; plane_len];
    for start in 0..order.len() {
        if placed[start] || order[start] == start {
            placed[start] = true;
            continue;
        }
        scratch.copy_from_slice(&samples[start * plane_len..(start + 1) * plane_len]);
        let mut destination = start;
        loop {
            placed[destination] = true;
            let source = order[destination];
            if source == start {
                samples[destination * plane_len..(destination + 1) * plane_len]
                    .copy_from_slice(&scratch);
                break;
            }
            samples.copy_within(
                source * plane_len..(source + 1) * plane_len,
                destination * plane_len,
            );
            destination = source;
        }
    }
}

/// Reads every file, sorts them into spatial (not necessarily on-disk-list) order by projecting
/// `ImagePositionPatient` onto the stack's shared slice normal, and assembles a `Volume`. Files
/// can be classic one-slice-per-file images or multi-frame objects (Enhanced CT/MR/PET: one file
/// is enough), whose per-frame Plane Position / Plane Orientation / Pixel Measures and Pixel Value
/// Transformation functional groups are honoured. A sheared (gantry-tilted) stack is desheared
/// onto an orthogonal grid (`Volume::desheared`).
/// Rejects (rather than silently mis-rendering) a series whose slices don't share a consistent
/// `ImageOrientationPatient`/dimensions - slices in different planes (a multi-orientation or
/// non-parallel series) aren't one resamplable lattice.
///
/// Memory: every slice is decoded straight into its plane of one preallocated `f32` buffer (in
/// file order), then the planes are sorted in place, so the peak is the volume itself plus one
/// in-flight slice decode per worker thread - not a decoded copy of every slice next to it.
#[cfg(not(target_arch = "wasm32"))]
pub fn build_volume<P: AsRef<Path> + Sync>(file_paths: &[P]) -> Result<Volume, VolumeError> {
    if file_paths.is_empty() {
        return Err(VolumeError::Empty);
    }
    match build_volume_from_single_frame_files(file_paths) {
        Err(VolumeError::MultiFrameSource) => build_volume_from_frames(file_paths),
        Err(VolumeError::TooFewSlices { .. }) if file_paths.len() == 1 => {
            build_volume_from_frames(file_paths)
        }
        other => other,
    }
}

/// The classic path: one slice per file (CT/MR/PT Image Storage and friends).
#[cfg(not(target_arch = "wasm32"))]
fn build_volume_from_single_frame_files<P: AsRef<Path> + Sync>(
    file_paths: &[P],
) -> Result<Volume, VolumeError> {
    if file_paths.len() < 2 {
        if let Some(path) = file_paths.first() {
            // A lone file can still be a whole volume: an Enhanced CT/MR/PET object.
            let object = read_dicom_file_deferring_bulk_data(path.as_ref())?;
            if object
                .as_ref()
                .is_some_and(|(object, _)| is_multi_frame(object))
            {
                return Err(VolumeError::MultiFrameSource);
            }
        }
        return Err(VolumeError::TooFewSlices {
            found: file_paths.len(),
            required: 2,
        });
    }

    // The first slice fixes Rows/Columns, and with them the buffer size.
    let (first, first_values) = read_source_slice(file_paths[0].as_ref())?;
    let rows = first.metadata.rows;
    let cols = first.metadata.cols;
    let plane_len = rows as usize * cols as usize;
    if first_values.len() != plane_len {
        return Err(VolumeError::InconsistentDimensions);
    }
    let mut samples = vec![0f32; plane_len * file_paths.len()];
    samples[..plane_len].copy_from_slice(&first_values);
    drop(first_values);

    // Reading + decoding each slice is the expensive part of building a volume (DICOM parse plus
    // transfer-syntax decompression per file), and slices are independent of each other until the
    // sort/consistency checks below, so read them concurrently rather than one at a time.
    let results: Vec<Result<SourceSlice, VolumeError>> = samples[plane_len..]
        .par_chunks_mut(plane_len)
        .zip(file_paths[1..].par_iter())
        .map(|(plane, path)| {
            let (slice, values) = read_source_slice(path.as_ref())?;
            if slice.metadata.rows != rows
                || slice.metadata.cols != cols
                || values.len() != plane_len
            {
                return Err(VolumeError::InconsistentDimensions);
            }
            plane.copy_from_slice(&values);
            Ok(slice)
        })
        .collect();
    let mut slices: Vec<SourceSlice> = Vec::with_capacity(file_paths.len());
    slices.push(first);
    for result in results {
        slices.push(result?);
    }

    let row_vector = slices[0].row_vector;
    let col_vector = slices[0].col_vector;
    for slice in &slices[1..] {
        if !vectors_close(slice.row_vector, row_vector, ORIENTATION_EPSILON)
            || !vectors_close(slice.col_vector, col_vector, ORIENTATION_EPSILON)
        {
            return Err(VolumeError::InconsistentGeometry(
                "ImageOrientationPatient differs between slices (non-parallel or multi-orientation stack)"
                    .to_owned(),
            ));
        }
    }

    let slice_normal = normalize3(cross3(row_vector, col_vector));

    let mut order: Vec<usize> = (0..slices.len()).collect();
    order.sort_by(|&a, &b| {
        let za = dot3(slices[a].position, slice_normal);
        let zb = dot3(slices[b].position, slice_normal);
        za.partial_cmp(&zb).unwrap_or(std::cmp::Ordering::Equal)
    });

    let slice_zs: Vec<f64> = order
        .iter()
        .map(|&i| dot3(slices[i].position, slice_normal))
        .collect();
    let z_span = slice_zs[slice_zs.len() - 1] - slice_zs[0];
    if z_span.abs() < 1e-3 {
        return Err(VolumeError::InconsistentGeometry(
            "all slices project to the same spatial position along the stack normal".to_owned(),
        ));
    }

    let origin = slices[order[0]].position;
    let row_spacing_mm = slices[order[0]].row_spacing_mm;
    let col_spacing_mm = slices[order[0]].col_spacing_mm;

    permute_planes_in_place(&mut samples, plane_len, &order);

    let positions: Vec<Vec3> = order.iter().map(|&i| slices[i].position).collect();
    let first = &slices[order[0]];
    let mut volume = Volume {
        samples,
        rows: rows as u32,
        cols: cols as u32,
        num_slices: order.len() as u32,
        origin,
        row_vector,
        col_vector,
        slice_normal,
        col_spacing_mm,
        row_spacing_mm,
        slice_zs,
        modality: first.modality.clone(),
        frame_of_reference_uid: first.frame_of_reference_uid.clone(),
        series_instance_uid: first.series_instance_uid.clone(),
        study_instance_uid: first.study_instance_uid.clone(),
        gantry_tilt_deg: 0.0,
        desheared: false,
    };
    deshear_if_needed(&mut volume, &positions)?;
    Ok(volume)
}

/// Whether `object` holds more than one frame or Enhanced-style functional groups (Enhanced
/// CT/MR/PET, Legacy Converted Enhanced, a multi-frame secondary capture, ...).
#[cfg(not(target_arch = "wasm32"))]
fn is_multi_frame(object: &DefaultDicomObject) -> bool {
    let frames = object
        .get(tags::NUMBER_OF_FRAMES)
        .and_then(|element| element.to_str().ok())
        .and_then(|text| text.trim().parse::<u32>().ok())
        .unwrap_or(1);
    frames > 1
        || object
            .get(tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
            .is_some()
}

fn number_of_frames(object: &DefaultDicomObject) -> usize {
    object
        .get(tags::NUMBER_OF_FRAMES)
        .and_then(|element| element.to_str().ok())
        .and_then(|text| text.trim().parse::<usize>().ok())
        .unwrap_or(1)
        .max(1)
}

/// One functional group macro's item for `frame_index`: the per-frame group's item when it holds
/// `sequence_tag`, else the shared group's (PS3.3 C.7.6.16).
fn functional_group_item(
    object: &DefaultDicomObject,
    frame_index: usize,
    sequence_tag: Tag,
) -> Option<&dcmnorm_object::InMemDicomObject> {
    let lookup = |group_tag: Tag, item_index: usize| {
        object
            .get(group_tag)?
            .value()
            .items()?
            .get(item_index)?
            .get(sequence_tag)?
            .value()
            .items()?
            .first()
    };
    lookup(tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE, frame_index)
        .or_else(|| lookup(tags::SHARED_FUNCTIONAL_GROUPS_SEQUENCE, 0))
}

fn multi_f64_in(item: &dcmnorm_object::InMemDicomObject, tag: Tag) -> Option<Vec<f64>> {
    let text = item.get(tag)?.to_str().ok()?;
    let values: Vec<f64> = text
        .split('\\')
        .filter_map(|part| part.trim().parse::<f64>().ok())
        .collect();
    (!values.is_empty()).then_some(values)
}

/// Geometry of one frame: the Plane Position / Plane Orientation / Pixel Measures functional
/// groups (per-frame first, then shared), falling back to the top-level attributes a classic or
/// legacy multi-frame object carries.
fn frame_geometry(
    object: &DefaultDicomObject,
    frame_index: usize,
) -> Result<(Vec3, Vec3, Vec3, f64, f64), VolumeError> {
    let from_group = |sequence: Tag, tag: Tag| {
        functional_group_item(object, frame_index, sequence)
            .and_then(|item| multi_f64_in(item, tag))
    };
    let orientation = match from_group(
        tags::PLANE_ORIENTATION_SEQUENCE,
        tags::IMAGE_ORIENTATION_PATIENT,
    ) {
        Some(values) => values,
        None => read_multi_f64(
            object,
            tags::IMAGE_ORIENTATION_PATIENT,
            "ImageOrientationPatient",
        )?,
    };
    if orientation.len() < 6 {
        return Err(VolumeError::MissingGeometry("ImageOrientationPatient"));
    }
    let row_vector = normalize3([orientation[0], orientation[1], orientation[2]]);
    let col_vector = normalize3([orientation[3], orientation[4], orientation[5]]);

    let position = match from_group(tags::PLANE_POSITION_SEQUENCE, tags::IMAGE_POSITION_PATIENT) {
        Some(values) => {
            if values.len() < 3 {
                return Err(VolumeError::MissingGeometry("ImagePositionPatient"));
            }
            [values[0], values[1], values[2]]
        }
        None => {
            let base_values =
                read_multi_f64(object, tags::IMAGE_POSITION_PATIENT, "ImagePositionPatient")?;
            if base_values.len() < 3 {
                return Err(VolumeError::MissingGeometry("ImagePositionPatient"));
            }
            let base = [base_values[0], base_values[1], base_values[2]];
            if number_of_frames(object) > 1 {
                let normal = normalize3(cross3(row_vector, col_vector));
                if let Ok(offsets) = read_multi_f64(
                    object,
                    tags::GRID_FRAME_OFFSET_VECTOR,
                    "GridFrameOffsetVector",
                ) {
                    if let Some(&offset_mm) = offsets.get(frame_index) {
                        add3(base, scale3(normal, offset_mm))
                    } else {
                        base
                    }
                } else if let Ok(spacings) =
                    read_multi_f64(object, tags::SPACING_BETWEEN_SLICES, "SpacingBetweenSlices")
                {
                    if let Some(&spacing_mm) =
                        spacings.first().filter(|v| v.is_finite() && **v != 0.0)
                    {
                        add3(base, scale3(normal, spacing_mm * frame_index as f64))
                    } else {
                        base
                    }
                } else {
                    base
                }
            } else {
                base
            }
        }
    };
    let spacing = match from_group(tags::PIXEL_MEASURES_SEQUENCE, tags::PIXEL_SPACING) {
        Some(values) => values,
        None => read_multi_f64(object, tags::PIXEL_SPACING, "PixelSpacing")?,
    };
    if spacing.len() < 2 {
        return Err(VolumeError::MissingGeometry("PixelSpacing"));
    }
    Ok((row_vector, col_vector, position, spacing[0], spacing[1]))
}

struct FrameSource {
    file: usize,
    frame: usize,
    row_vector: Vec3,
    col_vector: Vec3,
    position: Vec3,
    row_spacing_mm: f64,
    col_spacing_mm: f64,
}

struct FileHeader {
    frames: Vec<FrameSource>,
    rows: u16,
    cols: u16,
    modality: Option<String>,
    frame_of_reference_uid: Option<String>,
    series_instance_uid: Option<String>,
    study_instance_uid: Option<String>,
}

fn extract_file_header(
    object: &DefaultDicomObject,
    file: usize,
) -> Result<FileHeader, VolumeError> {
    let rows = object
        .get(tags::ROWS)
        .and_then(|element| element.uint16().ok())
        .ok_or(VolumeError::MissingGeometry("Rows"))?;
    let cols = object
        .get(tags::COLUMNS)
        .and_then(|element| element.uint16().ok())
        .ok_or(VolumeError::MissingGeometry("Columns"))?;
    let mut frames = Vec::new();
    for frame in 0..number_of_frames(object) {
        let (row_vector, col_vector, position, row_spacing_mm, col_spacing_mm) =
            frame_geometry(object, frame)?;
        frames.push(FrameSource {
            file,
            frame,
            row_vector,
            col_vector,
            position,
            row_spacing_mm,
            col_spacing_mm,
        });
    }
    Ok(FileHeader {
        frames,
        rows,
        cols,
        modality: read_optional_str(object, tags::MODALITY),
        frame_of_reference_uid: read_optional_str(object, tags::FRAME_OF_REFERENCE_UID),
        series_instance_uid: read_optional_str(object, tags::SERIES_INSTANCE_UID),
        study_instance_uid: read_optional_str(object, tags::STUDY_INSTANCE_UID),
    })
}

#[cfg(not(target_arch = "wasm32"))]
fn read_file_header(path: &Path, file: usize) -> Result<FileHeader, VolumeError> {
    let object = match read_dicom_file_deferring_bulk_data(path)? {
        Some((object, _)) => object,
        None => read_dicom_file(path)?,
    };
    extract_file_header(&object, file)
}

struct VolumePlan<'a> {
    rows: u16,
    cols: u16,
    row_vector: Vec3,
    col_vector: Vec3,
    slice_normal: Vec3,
    frames: Vec<&'a FrameSource>,
    kept: Vec<usize>,
    slice_zs: Vec<f64>,
}

fn plan_volume_from_headers(headers: &[FileHeader]) -> Result<VolumePlan<'_>, VolumeError> {
    if headers.is_empty() {
        return Err(VolumeError::Empty);
    }
    let (rows, cols) = (headers[0].rows, headers[0].cols);
    if headers
        .iter()
        .any(|header| header.rows != rows || header.cols != cols)
    {
        return Err(VolumeError::InconsistentDimensions);
    }
    let frames: Vec<&FrameSource> = headers
        .iter()
        .flat_map(|header| header.frames.iter())
        .collect();
    if frames.len() < 2 {
        return Err(VolumeError::TooFewSlices {
            found: frames.len(),
            required: 2,
        });
    }
    let row_vector = frames[0].row_vector;
    let col_vector = frames[0].col_vector;
    if frames.iter().any(|frame| {
        !vectors_close(frame.row_vector, row_vector, ORIENTATION_EPSILON)
            || !vectors_close(frame.col_vector, col_vector, ORIENTATION_EPSILON)
    }) {
        return Err(VolumeError::InconsistentGeometry(
            "ImageOrientationPatient differs between frames (non-parallel or multi-orientation stack)".to_owned(),
        ));
    }
    let slice_normal = normalize3(cross3(row_vector, col_vector));

    let mut order: Vec<usize> = (0..frames.len()).collect();
    order.sort_by(|&a, &b| {
        dot3(frames[a].position, slice_normal)
            .partial_cmp(&dot3(frames[b].position, slice_normal))
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.cmp(&b))
    });
    let mut kept: Vec<usize> = Vec::with_capacity(order.len());
    for index in order {
        if let Some(&last) = kept.last() {
            if norm3(sub3(frames[index].position, frames[last].position)) < 1e-3 {
                continue;
            }
        }
        kept.push(index);
    }
    if kept.len() < 2 {
        return Err(VolumeError::InconsistentGeometry(
            "all frames project to the same spatial position along the stack normal".to_owned(),
        ));
    }
    let slice_zs: Vec<f64> = kept
        .iter()
        .map(|&index| dot3(frames[index].position, slice_normal))
        .collect();
    if (slice_zs[slice_zs.len() - 1] - slice_zs[0]).abs() < 1e-3 {
        return Err(VolumeError::InconsistentGeometry(
            "all frames project to the same spatial position along the stack normal".to_owned(),
        ));
    }

    Ok(VolumePlan {
        rows,
        cols,
        row_vector,
        col_vector,
        slice_normal,
        frames,
        kept,
        slice_zs,
    })
}

/// Cheap metadata-only check: returns `true` if `object` is a monochrome multi-frame DICOM object
/// with consistent 3D slice geometry spanning at least two distinct spatial positions (so
/// [`build_volume_from_objects`] can assemble an MPR volume from it). Does not decode pixels.
pub fn can_build_volume_from_object(object: &DefaultDicomObject) -> bool {
    if number_of_frames(object) < 2 {
        return false;
    }
    let photometric = read_optional_str(object, tags::PHOTOMETRIC_INTERPRETATION);
    if !matches!(photometric.as_deref(), Some("MONOCHROME1" | "MONOCHROME2")) {
        return false;
    }
    let Ok(header) = extract_file_header(object, 0) else {
        return false;
    };
    plan_volume_from_headers(&[header]).is_ok()
}

/// Assembles a [`Volume`] directly from already-parsed in-memory DICOM objects (either a single
/// volumetric multi-frame object or a stack of single-frame/multi-frame objects). Works on both
/// native and `wasm32` targets.
pub fn build_volume_from_objects(objects: &[&DefaultDicomObject]) -> Result<Volume, VolumeError> {
    if objects.is_empty() {
        return Err(VolumeError::Empty);
    }
    let headers: Vec<FileHeader> = objects
        .iter()
        .enumerate()
        .map(|(file, object)| extract_file_header(object, file))
        .collect::<Result<_, _>>()?;
    let plan = plan_volume_from_headers(&headers)?;

    let plane_len = plan.rows as usize * plan.cols as usize;
    let mut samples = vec![0f32; plane_len * plan.kept.len()];
    {
        let mut per_file: Vec<Vec<(usize, &mut [f32])>> =
            (0..headers.len()).map(|_| Vec::new()).collect();
        for (plane, &index) in samples.chunks_mut(plane_len).zip(plan.kept.iter()) {
            per_file[plan.frames[index].file].push((plan.frames[index].frame, plane));
        }

        let decode_file =
            |(file, planes): (usize, Vec<(usize, &mut [f32])>)| -> Result<(), VolumeError> {
                let object = if planes.len() > 1 {
                    ensure_native_render_object(objects[file])?
                } else {
                    std::borrow::Cow::Borrowed(objects[file])
                };
                let object = object.as_ref();
                let decode_frame =
                    |(frame, plane): (usize, &mut [f32])| -> Result<(), VolumeError> {
                        let (metadata, values) = decode_frame_grayscale_values(object, frame)?;
                        if !matches!(
                            metadata.photometric_interpretation.as_str(),
                            "MONOCHROME1" | "MONOCHROME2"
                        ) {
                            return Err(VolumeError::UnsupportedPhotometricInterpretation(
                                metadata.photometric_interpretation.clone(),
                            ));
                        }
                        if values.len() != plane.len() {
                            return Err(VolumeError::InconsistentDimensions);
                        }
                        for (destination, value) in plane.iter_mut().zip(values) {
                            *destination = value as f32;
                        }
                        Ok(())
                    };
                #[cfg(not(target_arch = "wasm32"))]
                {
                    planes.into_par_iter().try_for_each(decode_frame)
                }
                #[cfg(target_arch = "wasm32")]
                {
                    planes.into_iter().try_for_each(decode_frame)
                }
            };

        #[cfg(not(target_arch = "wasm32"))]
        {
            per_file
                .into_par_iter()
                .enumerate()
                .filter(|(_, planes)| !planes.is_empty())
                .try_for_each(decode_file)?;
        }
        #[cfg(target_arch = "wasm32")]
        {
            per_file
                .into_iter()
                .enumerate()
                .filter(|(_, planes)| !planes.is_empty())
                .try_for_each(decode_file)?;
        }
    }

    let first = plan.frames[plan.kept[0]];
    let header = &headers[first.file];
    let positions: Vec<Vec3> = plan
        .kept
        .iter()
        .map(|&index| plan.frames[index].position)
        .collect();
    let mut volume = Volume {
        samples,
        rows: u32::from(plan.rows),
        cols: u32::from(plan.cols),
        num_slices: plan.kept.len() as u32,
        origin: first.position,
        row_vector: plan.row_vector,
        col_vector: plan.col_vector,
        slice_normal: plan.slice_normal,
        col_spacing_mm: first.col_spacing_mm,
        row_spacing_mm: first.row_spacing_mm,
        slice_zs: plan.slice_zs,
        modality: header.modality.clone(),
        frame_of_reference_uid: header.frame_of_reference_uid.clone(),
        series_instance_uid: header.series_instance_uid.clone(),
        study_instance_uid: header.study_instance_uid.clone(),
        gantry_tilt_deg: 0.0,
        desheared: false,
    };
    deshear_if_needed(&mut volume, &positions)?;
    Ok(volume)
}

/// Assembles a [`Volume`] directly from in-memory DICOM byte slices (either a single volumetric
/// multi-frame object or a stack of single-frame/multi-frame DICOM files). Works on both native
/// and `wasm32` targets.
pub fn build_volume_from_bytes(files: &[&[u8]]) -> Result<Volume, VolumeError> {
    if files.is_empty() {
        return Err(VolumeError::Empty);
    }
    let objects: Vec<DefaultDicomObject> = files
        .iter()
        .copied()
        .map(read_dicom_bytes)
        .collect::<Result<_, _>>()?;
    let refs: Vec<&DefaultDicomObject> = objects.iter().collect();
    build_volume_from_objects(&refs)
}

/// The per-frame path: any mix of single-frame and multi-frame files (an Enhanced CT/MR/PET
/// object, several of them, or a Legacy Converted Enhanced series). Two passes - every file's
/// header first (bulk data deferred, so this reads no pixels) to learn every frame's geometry
/// and sort them, then each needed frame is decoded straight into its sorted plane - so the
/// peak is the volume plus one file in flight per worker, as in the classic path. Each frame's
/// own Pixel Value Transformation (rescale) applies. Frames that repeat a position already taken
/// (further temporal positions, echoes or stacks of a 4D object) are skipped: the volume holds
/// the first frame, in file and frame order, at each position.
#[cfg(not(target_arch = "wasm32"))]
fn build_volume_from_frames<P: AsRef<Path> + Sync>(
    file_paths: &[P],
) -> Result<Volume, VolumeError> {
    let headers: Vec<FileHeader> = file_paths
        .par_iter()
        .enumerate()
        .map(|(file, path)| read_file_header(path.as_ref(), file))
        .collect::<Result<_, _>>()?;
    let (rows, cols) = (headers[0].rows, headers[0].cols);
    if headers
        .iter()
        .any(|header| header.rows != rows || header.cols != cols)
    {
        return Err(VolumeError::InconsistentDimensions);
    }
    let frames: Vec<&FrameSource> = headers
        .iter()
        .flat_map(|header| header.frames.iter())
        .collect();
    if frames.len() < 2 {
        return Err(VolumeError::TooFewSlices {
            found: frames.len(),
            required: 2,
        });
    }
    let row_vector = frames[0].row_vector;
    let col_vector = frames[0].col_vector;
    if frames.iter().any(|frame| {
        !vectors_close(frame.row_vector, row_vector, ORIENTATION_EPSILON)
            || !vectors_close(frame.col_vector, col_vector, ORIENTATION_EPSILON)
    }) {
        return Err(VolumeError::InconsistentGeometry(
            "ImageOrientationPatient differs between frames (non-parallel or multi-orientation stack)".to_owned(),
        ));
    }
    let slice_normal = normalize3(cross3(row_vector, col_vector));

    // Stable sort by position along the normal, then keep the first frame at each position.
    let mut order: Vec<usize> = (0..frames.len()).collect();
    order.sort_by(|&a, &b| {
        dot3(frames[a].position, slice_normal)
            .partial_cmp(&dot3(frames[b].position, slice_normal))
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.cmp(&b))
    });
    let mut kept: Vec<usize> = Vec::with_capacity(order.len());
    for index in order {
        if let Some(&last) = kept.last() {
            if norm3(sub3(frames[index].position, frames[last].position)) < 1e-3 {
                continue;
            }
        }
        kept.push(index);
    }
    if kept.len() < 2 {
        return Err(VolumeError::InconsistentGeometry(
            "all frames project to the same spatial position along the stack normal".to_owned(),
        ));
    }
    let slice_zs: Vec<f64> = kept
        .iter()
        .map(|&index| dot3(frames[index].position, slice_normal))
        .collect();
    if (slice_zs[slice_zs.len() - 1] - slice_zs[0]).abs() < 1e-3 {
        return Err(VolumeError::InconsistentGeometry(
            "all frames project to the same spatial position along the stack normal".to_owned(),
        ));
    }

    let plane_len = rows as usize * cols as usize;
    let mut samples = vec![0f32; plane_len * kept.len()];
    {
        // Hand each file its own disjoint planes, then decode files (and their frames) in parallel.
        let mut per_file: Vec<Vec<(usize, &mut [f32])>> =
            (0..headers.len()).map(|_| Vec::new()).collect();
        for (plane, &index) in samples.chunks_mut(plane_len).zip(kept.iter()) {
            per_file[frames[index].file].push((frames[index].frame, plane));
        }
        per_file
            .into_par_iter()
            .enumerate()
            .filter(|(_, planes)| !planes.is_empty())
            .try_for_each(|(file, planes)| -> Result<(), VolumeError> {
                let object = read_dicom_file(file_paths[file].as_ref())?;
                // A compressed multi-frame object is decompressed once, not once per frame.
                let object = if planes.len() > 1 {
                    ensure_native_render_object(&object)?
                } else {
                    std::borrow::Cow::Borrowed(&object)
                };
                let object = object.as_ref();
                planes
                    .into_par_iter()
                    .try_for_each(|(frame, plane)| -> Result<(), VolumeError> {
                        let (metadata, values) = decode_frame_grayscale_values(object, frame)?;
                        if !matches!(
                            metadata.photometric_interpretation.as_str(),
                            "MONOCHROME1" | "MONOCHROME2"
                        ) {
                            return Err(VolumeError::UnsupportedPhotometricInterpretation(
                                metadata.photometric_interpretation.clone(),
                            ));
                        }
                        if values.len() != plane.len() {
                            return Err(VolumeError::InconsistentDimensions);
                        }
                        for (destination, value) in plane.iter_mut().zip(values) {
                            *destination = value as f32;
                        }
                        Ok(())
                    })
            })?;
    }

    let first = frames[kept[0]];
    let header = &headers[first.file];
    let positions: Vec<Vec3> = kept.iter().map(|&index| frames[index].position).collect();
    let mut volume = Volume {
        samples,
        rows: u32::from(rows),
        cols: u32::from(cols),
        num_slices: kept.len() as u32,
        origin: first.position,
        row_vector,
        col_vector,
        slice_normal,
        col_spacing_mm: first.col_spacing_mm,
        row_spacing_mm: first.row_spacing_mm,
        slice_zs,
        modality: header.modality.clone(),
        frame_of_reference_uid: header.frame_of_reference_uid.clone(),
        series_instance_uid: header.series_instance_uid.clone(),
        study_instance_uid: header.study_instance_uid.clone(),
        gantry_tilt_deg: 0.0,
        desheared: false,
    };
    deshear_if_needed(&mut volume, &positions)?;
    Ok(volume)
}

/// Each sorted slice's in-plane offset from the first slice, in pixels `(columns, rows)`: the
/// part of `position_k - position_0` that lies in the slice plane instead of along the normal.
/// All zeros for an ordinary stack; for a gantry-tilted CT it grows by `spacing * tan(tilt)` per
/// slice along the tilt direction.
fn in_plane_offsets_px(volume: &Volume, positions: &[Vec3]) -> Vec<(f64, f64)> {
    let first = positions[0];
    positions
        .iter()
        .map(|&position| {
            let delta = sub3(position, first);
            (
                dot3(delta, volume.row_vector) / volume.col_spacing_mm,
                dot3(delta, volume.col_vector) / volume.row_spacing_mm,
            )
        })
        .collect()
}

/// Gantry tilt (and any other stack whose `ImagePositionPatient` step leaves the slice normal):
/// the slices are parallel planes, but each one's origin drifts within the plane, so placing
/// slice k at `origin + z_k * normal` (what every sampler assumes) shears the volume. This
/// resamples every slice in-plane (bilinear, a pure 2D shift - each slice already lies in its
/// true plane, so no interpolation across slices is involved) onto one orthogonal grid spanned
/// by `row_vector`, `col_vector` and `slice_normal`, covering the union of every slice's
/// footprint. Afterwards the volume is an exact orthogonal lattice and the reformat, texture
/// export and registration code paths need no shear awareness.
///
/// Memory: a desheared volume briefly holds both the source planes and the (possibly larger)
/// desheared grid; ordinary stacks never allocate here.
fn deshear_if_needed(volume: &mut Volume, positions: &[Vec3]) -> Result<(), VolumeError> {
    let offsets = in_plane_offsets_px(volume, positions);
    let max_offset = offsets
        .iter()
        .map(|&(du, dv)| du.abs().max(dv.abs()))
        .fold(0.0, f64::max);
    if max_offset <= SHEAR_TOLERANCE_PX {
        return Ok(());
    }

    let n = positions.len();
    let along = volume.slice_zs[n - 1] - volume.slice_zs[0];
    let drift = sub3(
        sub3(positions[n - 1], positions[0]),
        scale3(volume.slice_normal, along),
    );
    volume.gantry_tilt_deg = norm3(drift).atan2(along.abs()).to_degrees();

    let min_du = offsets.iter().map(|o| o.0).fold(f64::INFINITY, f64::min);
    let max_du = offsets
        .iter()
        .map(|o| o.0)
        .fold(f64::NEG_INFINITY, f64::max);
    let min_dv = offsets.iter().map(|o| o.1).fold(f64::INFINITY, f64::min);
    let max_dv = offsets
        .iter()
        .map(|o| o.1)
        .fold(f64::NEG_INFINITY, f64::max);
    let old_cols = volume.cols as usize;
    let old_rows = volume.rows as usize;
    // The union grid starts at the smallest offset (rounded down to a whole pixel, so the first
    // slice still lands on exact pixel centres) and ends past the largest one.
    let start_u = min_du.floor();
    let start_v = min_dv.floor();
    let new_cols = old_cols + (max_du.ceil() - start_u) as usize;
    let new_rows = old_rows + (max_dv.ceil() - start_v) as usize;
    if (new_cols * new_rows) as f64 > MAX_DESHEAR_PLANE_GROWTH * (old_cols * old_rows) as f64
        || new_cols > u16::MAX as usize
        || new_rows > u16::MAX as usize
    {
        return Err(VolumeError::InconsistentGeometry(format!(
            "slice positions drift {max_offset:.0} pixels within the slice plane - too far for one tilted acquisition"
        )));
    }

    let background = volume.samples.iter().copied().fold(f32::INFINITY, f32::min);
    let background = if background.is_finite() {
        background
    } else {
        0.0
    };
    let old_plane = old_cols * old_rows;
    let new_plane = new_cols * new_rows;
    let mut desheared = vec![background; new_plane * n];
    let source = &volume.samples;
    let deshear_slice = |(k, plane): (usize, &mut [f32])| {
        let (du, dv) = offsets[k];
        let src = &source[k * old_plane..(k + 1) * old_plane];
        for r in 0..new_rows {
            // Source pixel of grid pixel (r, c) in slice k: grid point + start - slice offset.
            let row_f = r as f64 + start_v - dv;
            if row_f < -0.5 || row_f > old_rows as f64 - 0.5 {
                continue;
            }
            let row_f = row_f.clamp(0.0, (old_rows - 1) as f64);
            let r0 = row_f.floor() as usize;
            let r1 = (r0 + 1).min(old_rows - 1);
            let tr = (row_f - r0 as f64) as f32;
            for c in 0..new_cols {
                let col_f = c as f64 + start_u - du;
                if col_f < -0.5 || col_f > old_cols as f64 - 0.5 {
                    continue;
                }
                let col_f = col_f.clamp(0.0, (old_cols - 1) as f64);
                let c0 = col_f.floor() as usize;
                let c1 = (c0 + 1).min(old_cols - 1);
                let tc = (col_f - c0 as f64) as f32;
                let top = src[r0 * old_cols + c0] * (1.0 - tc) + src[r0 * old_cols + c1] * tc;
                let bottom = src[r1 * old_cols + c0] * (1.0 - tc) + src[r1 * old_cols + c1] * tc;
                plane[r * new_cols + c] = top * (1.0 - tr) + bottom * tr;
            }
        }
    };
    #[cfg(not(target_arch = "wasm32"))]
    desheared
        .par_chunks_mut(new_plane)
        .enumerate()
        .for_each(deshear_slice);
    #[cfg(target_arch = "wasm32")]
    desheared
        .chunks_mut(new_plane)
        .enumerate()
        .for_each(deshear_slice);

    volume.origin = add3(
        add3(
            volume.origin,
            scale3(volume.row_vector, start_u * volume.col_spacing_mm),
        ),
        scale3(volume.col_vector, start_v * volume.row_spacing_mm),
    );
    volume.samples = desheared;
    volume.cols = new_cols as u32;
    volume.rows = new_rows as u32;
    volume.desheared = true;
    Ok(())
}

/// Returns the fractional slice index for a world-space projection `z` along `slice_normal`, or
/// `None` if `z` is more than one slice spacing beyond either end of the stack (treated as
/// outside the volume rather than clamped/repeated, so a plane that partly leaves the acquired
/// volume renders a clean background instead of a smeared repeat of the edge slice).
fn fractional_slice_index(slice_zs: &[f64], z: f64) -> Option<f64> {
    let n = slice_zs.len();
    let nominal_spacing = if n > 1 {
        ((slice_zs[n - 1] - slice_zs[0]) / (n - 1) as f64)
            .abs()
            .max(1e-6)
    } else {
        1.0
    };
    let margin = nominal_spacing;
    if z < slice_zs[0] - margin || z > slice_zs[n - 1] + margin {
        return None;
    }
    if n == 1 {
        return Some(0.0);
    }

    match slice_zs
        .binary_search_by(|probe| probe.partial_cmp(&z).unwrap_or(std::cmp::Ordering::Equal))
    {
        Ok(index) => Some(index as f64),
        Err(index) => {
            if index == 0 {
                let t = (z - slice_zs[0]) / (slice_zs[1] - slice_zs[0]).max(1e-9);
                Some(t) // may be slightly negative within `margin`, which `Volume::voxel` clamps
            } else if index >= n {
                let last = n - 1;
                let t = (z - slice_zs[last - 1]) / (slice_zs[last] - slice_zs[last - 1]).max(1e-9);
                Some((last - 1) as f64 + t)
            } else {
                let z0 = slice_zs[index - 1];
                let z1 = slice_zs[index];
                let t = (z - z0) / (z1 - z0).max(1e-9);
                Some((index - 1) as f64 + t)
            }
        }
    }
}

fn sample_nearest(volume: &Volume, row_f: f64, col_f: f64, slice_f: f64) -> f64 {
    f64::from(volume.voxel(
        row_f.round() as i64,
        col_f.round() as i64,
        slice_f.round() as i64,
    ))
}

fn sample_trilinear(volume: &Volume, row_f: f64, col_f: f64, slice_f: f64) -> f64 {
    let row0 = row_f.floor();
    let col0 = col_f.floor();
    let slice0 = slice_f.floor();
    let row_t = row_f - row0;
    let col_t = col_f - col0;
    let slice_t = slice_f - slice0;
    let (row0, col0, slice0) = (row0 as i64, col0 as i64, slice0 as i64);

    let corner =
        |dr: i64, dc: i64, ds: i64| f64::from(volume.voxel(row0 + dr, col0 + dc, slice0 + ds));

    let c00 = corner(0, 0, 0) * (1.0 - col_t) + corner(0, 1, 0) * col_t;
    let c10 = corner(1, 0, 0) * (1.0 - col_t) + corner(1, 1, 0) * col_t;
    let c01 = corner(0, 0, 1) * (1.0 - col_t) + corner(0, 1, 1) * col_t;
    let c11 = corner(1, 0, 1) * (1.0 - col_t) + corner(1, 1, 1) * col_t;

    let c0 = c00 * (1.0 - row_t) + c10 * row_t;
    let c1 = c01 * (1.0 - row_t) + c11 * row_t;

    c0 * (1.0 - slice_t) + c1 * slice_t
}

/// Transforms one world (patient/LPS mm) point into `volume`'s own voxel index space and samples
/// it, or returns `None` if the point falls outside the volume (beyond a 1-voxel margin) or the
/// slice stack. The single-point primitive both a thin-plane reformat and a thick slab (many
/// points along the plane's normal, see `sample_slab`) are built from.
fn sample_volume_at_world_point(
    volume: &Volume,
    world: Vec3,
    interpolation: Interpolation,
) -> Option<f64> {
    let delta = sub3(world, volume.origin);
    let col_f = dot3(delta, volume.row_vector) / volume.col_spacing_mm;
    let row_f = dot3(delta, volume.col_vector) / volume.row_spacing_mm;
    let z_projection = dot3(delta, volume.slice_normal) + volume.slice_zs[0];

    let margin = 1.0;
    let in_plane_bounds = col_f >= -margin
        && col_f <= (volume.cols as f64 - 1.0) + margin
        && row_f >= -margin
        && row_f <= (volume.rows as f64 - 1.0) + margin;
    if !in_plane_bounds {
        return None;
    }

    fractional_slice_index(&volume.slice_zs, z_projection).map(|slice_f| match interpolation {
        Interpolation::Nearest => sample_nearest(volume, row_f, col_f, slice_f),
        Interpolation::Trilinear => sample_trilinear(volume, row_f, col_f, slice_f),
    })
}

/// Samples `n_samples` points spanning `thickness_mm`, centered on `center`, along `normal` -
/// note this is the REFORMAT PLANE's own normal (`cross(row_dir, col_dir)`), not necessarily
/// `volume.slice_normal`: for an oblique/coronal/sagittal reformat the two differ, so moving
/// along the slab generally shifts all three of the volume's row/col/slice coordinates at once,
/// not just depth - each sample needs the full `sample_volume_at_world_point` transform, not a
/// cheap z-only adjustment. Points outside the volume are skipped rather than treated as zero;
/// `None` only if every sample in the slab misses the volume entirely.
fn sample_slab(
    volume: &Volume,
    center: Vec3,
    normal: Vec3,
    n_samples: usize,
    step_mm: f64,
    interpolation: Interpolation,
    projection: SlabProjection,
) -> Option<f64> {
    let half_span_mm = step_mm * (n_samples - 1) as f64 / 2.0;
    let mut min_value = f64::INFINITY;
    let mut max_value = f64::NEG_INFINITY;
    let mut sum = 0.0;
    let mut count = 0usize;

    for index in 0..n_samples {
        let offset_mm = -half_span_mm + step_mm * index as f64;
        let point = add3(center, scale3(normal, offset_mm));
        if let Some(value) = sample_volume_at_world_point(volume, point, interpolation) {
            min_value = min_value.min(value);
            max_value = max_value.max(value);
            sum += value;
            count += 1;
        }
    }

    if count == 0 {
        return None;
    }

    Some(match projection {
        SlabProjection::MaximumIntensity => max_value,
        SlabProjection::MinimumIntensity => min_value,
        SlabProjection::Average => sum / count as f64,
    })
}

/// Resamples one plane (or, with `params.slab_thickness_mm > 0.0`, a thick slab projected down to
/// one plane) through `volume` and returns the RAW rescaled values (e.g. Hounsfield units for
/// CT) row-major, `params.output_width * params.output_height` long - no VOI windowing, no 8-bit
/// encoding. This is the shared sampling primitive behind both `reformat_plane` (which windows
/// and encodes the result into a normal 2D image) and whole-volume/DICOM-series export (which
/// wants the true intensity values, not a windowed render). Samples outside the volume are
/// background-filled with the minimum in-bounds value found (same convention `reformat_plane` has
/// always used), or `0.0` if every sample in the plane misses the volume entirely.
pub fn reformat_plane_values(
    volume: &Volume,
    params: &PlaneParams,
) -> Result<Vec<f32>, VolumeError> {
    if params.output_width == 0
        || params.output_height == 0
        || params.output_width > u16::MAX as u32
        || params.output_height > u16::MAX as u32
    {
        return Err(VolumeError::InvalidOutputDimensions);
    }
    if params.slab_thickness_mm < 0.0 {
        return Err(VolumeError::InvalidSlabThickness);
    }

    let row_dir = normalize3(params.row_dir);
    let col_dir = normalize3(params.col_dir);
    let normal = normalize3(cross3(row_dir, col_dir));
    let width = params.output_width as usize;
    let height = params.output_height as usize;
    let half_width = params.output_width as f64 / 2.0;
    let half_height = params.output_height as f64 / 2.0;

    // Sampling a thick slab at native voxel resolution keeps thin structures (e.g. a small
    // vessel in an MIP) from being skipped between samples, while the upper clamp keeps a very
    // thick slab (e.g. a whole-volume MIP) bounded in cost rather than sampling thousands of
    // points per output pixel.
    let slab_active = params.slab_thickness_mm > 0.0;
    let (slab_n_samples, slab_step_mm) = if slab_active {
        let step = volume.min_spacing_mm().max(0.05);
        let n = (((params.slab_thickness_mm / step).round() as i64) + 1).clamp(2, 128) as usize;
        (n, params.slab_thickness_mm / (n - 1) as f64)
    } else {
        (1, 0.0)
    };

    let mut values: Vec<Option<f64>> = Vec::with_capacity(width * height);
    for row in 0..height {
        for col in 0..width {
            let offset = add3(
                scale3(row_dir, (col as f64 - half_width) * params.spacing_mm),
                scale3(col_dir, (row as f64 - half_height) * params.spacing_mm),
            );
            let world = add3(params.origin, offset);

            let sample = if slab_active {
                sample_slab(
                    volume,
                    world,
                    normal,
                    slab_n_samples,
                    slab_step_mm,
                    params.interpolation,
                    params.slab_projection,
                )
            } else {
                sample_volume_at_world_point(volume, world, params.interpolation)
            };

            values.push(sample);
        }
    }

    let background = values
        .iter()
        .filter_map(|value| *value)
        .fold(f64::INFINITY, f64::min);
    let background = if background.is_finite() {
        background
    } else {
        0.0
    };
    Ok(values
        .into_iter()
        .map(|value| value.unwrap_or(background) as f32)
        .collect())
}

/// Resamples one plane (or thick slab) through `volume` and applies VOI windowing, returning
/// 8-bit grayscale pixels (`params.output_width * params.output_height` bytes) with no PNG/JPEG
/// encoding overhead.
pub fn reformat_plane_pixels(
    volume: &Volume,
    params: &PlaneParams,
) -> Result<Vec<u8>, VolumeError> {
    let values = reformat_plane_values(volume, params)?;
    let filled: Vec<f64> = values.into_iter().map(|value| value as f64).collect();
    Ok(apply_voi_window(
        &filled,
        params.window_center,
        params.window_width,
    ))
}

/// Resamples one plane (or, with `params.slab_thickness_mm > 0.0`, a thick slab projected down
/// to one plane) through `volume` and encodes it exactly like a normal 2D render
/// (`encode_rendered_frame`), so callers (the Node bindings, the CLI) get back the same
/// `RenderFrameOutput` shape 2D rendering already produces.
pub fn reformat_plane(
    volume: &Volume,
    params: &PlaneParams,
    output_format: RenderOutputFormat,
    jpeg_quality: u8,
) -> Result<RenderFrameOutput, VolumeError> {
    let rendered = reformat_plane_pixels(volume, params)?;
    let frame = RenderedFramePixels {
        width: params.output_width as u16,
        height: params.output_height as u16,
        samples_per_pixel: 1,
        bytes: rendered,
    };
    encode_rendered_frame(&frame, output_format, jpeg_quality).map_err(VolumeError::from)
}

/// Resamples `volume`'s ENTIRE native voxel grid (not an oblique plane/slab - see
/// `reformat_plane_values` for that) down to a coarser `target_cols`x`target_rows`x`target_slices`
/// uniform grid, covering the same physical extent. Used by `super::texture_export` to fit a
/// volume within a client GPU's texture-size limit, or to produce a small, fast "progressive"
/// first pass before the full-resolution texture arrives.
///
/// Each target axis is sampled at points evenly spaced across `[0, native_dim - 1]` in that axis's
/// own native voxel-index space (not world space - there's no need to round-trip through
/// `sample_volume_at_world_point`'s world-to-voxel transform when we're already working in voxel
/// indices on both ends), so the corner voxels of the coarse grid land exactly on the corner
/// voxels of the native grid. A target dimension of `1` samples the native axis's midpoint.
pub fn resample_volume(
    volume: &Volume,
    target_cols: u32,
    target_rows: u32,
    target_slices: u32,
    interpolation: Interpolation,
) -> Vec<f32> {
    let target_cols = target_cols.max(1);
    let target_rows = target_rows.max(1);
    let target_slices = target_slices.max(1);

    let col_step = if target_cols > 1 {
        (volume.cols as f64 - 1.0) / (target_cols as f64 - 1.0)
    } else {
        0.0
    };
    let row_step = if target_rows > 1 {
        (volume.rows as f64 - 1.0) / (target_rows as f64 - 1.0)
    } else {
        0.0
    };
    let slice_step = if target_slices > 1 {
        (volume.num_slices as f64 - 1.0) / (target_slices as f64 - 1.0)
    } else {
        0.0
    };

    let axis_coordinate = |target_index: u32, target_len: u32, step: f64, native_len: u32| -> f64 {
        if target_len > 1 {
            target_index as f64 * step
        } else {
            (native_len as f64 - 1.0) / 2.0
        }
    };

    // An irregularly spaced stack is resampled by POSITION along the normal (target slices evenly
    // spaced in millimetres across the stack's span), not by slice index: the output is a uniform
    // lattice, and its consumers (the GPU texture) assume exactly that.
    let irregular = volume.has_irregular_spacing();
    let first_z = volume.slice_zs[0];
    let span = volume.slice_zs[volume.slice_zs.len() - 1] - first_z;
    let slice_coordinate = |target_slice: u32| -> f64 {
        if irregular && target_slices > 1 {
            let z = first_z + span * target_slice as f64 / (target_slices as f64 - 1.0);
            fractional_slice_index(&volume.slice_zs, z).unwrap_or(0.0)
        } else {
            axis_coordinate(target_slice, target_slices, slice_step, volume.num_slices)
        }
    };

    let plane = target_cols as usize * target_rows as usize;
    let mut out = vec![0f32; plane * target_slices as usize];
    let resample_slice = |(target_slice, out_plane): (usize, &mut [f32])| {
        let slice_f = slice_coordinate(target_slice as u32);
        for target_row in 0..target_rows {
            let row_f = axis_coordinate(target_row, target_rows, row_step, volume.rows);
            for target_col in 0..target_cols {
                let col_f = axis_coordinate(target_col, target_cols, col_step, volume.cols);
                let value = match interpolation {
                    Interpolation::Nearest => sample_nearest(volume, row_f, col_f, slice_f),
                    Interpolation::Trilinear => sample_trilinear(volume, row_f, col_f, slice_f),
                };
                out_plane[target_row as usize * target_cols as usize + target_col as usize] =
                    value as f32;
            }
        }
    };
    #[cfg(not(target_arch = "wasm32"))]
    out.par_chunks_mut(plane)
        .enumerate()
        .for_each(resample_slice);
    #[cfg(target_arch = "wasm32")]
    out.chunks_mut(plane).enumerate().for_each(resample_slice);
    out
}

/// The three canonical LPS-aligned views ("axial" reuses the volume's own acquisition basis;
/// "coronal"/"sagittal" are fixed patient-anatomy planes, independent of acquisition angle).
/// Matches the convention the viewer's own client-side snap buttons use, so CLI, server, and
/// client can never visually disagree about what "coronal" means. LPS convention: +X = Left,
/// +Y = Posterior, +Z = Head (consistent with the viewer's existing orientation-HUD labeling).
pub fn canonical_view_basis(view: &str, volume: &Volume) -> Result<(Vec3, Vec3), VolumeError> {
    match view {
        "axial" => Ok((volume.row_vector, volume.col_vector)),
        "coronal" => Ok(([1.0, 0.0, 0.0], [0.0, 0.0, -1.0])),
        "sagittal" => Ok(([0.0, 1.0, 0.0], [0.0, 0.0, -1.0])),
        other => Err(VolumeError::InconsistentGeometry(format!(
            "unknown MPR view '{other}'; expected axial, coronal, or sagittal"
        ))),
    }
}

/// Applies a yaw/pitch/roll rotation (degrees, about the fixed patient/LPS Z/X/Y axes
/// respectively) on top of an existing `(row_dir, col_dir)` basis - the "arbitrary oblique camera
/// angle" case for `--mpr-rotation`. Both vectors are carried through the identical fixed-axis
/// rotation sequence, which is what guarantees the result stays orthonormal (a rotation preserves
/// the angle - and thus orthogonality - between any two vectors it's applied to; composing each
/// step around the *other*, already-rotated vector instead would not).
pub fn rotate_basis(
    row_dir: Vec3,
    col_dir: Vec3,
    yaw_deg: f64,
    pitch_deg: f64,
    roll_deg: f64,
) -> (Vec3, Vec3) {
    const X_AXIS: Vec3 = [1.0, 0.0, 0.0];
    const Y_AXIS: Vec3 = [0.0, 1.0, 0.0];
    const Z_AXIS: Vec3 = [0.0, 0.0, 1.0];

    let apply = |v: Vec3| -> Vec3 {
        let v = rotate_about_axis(v, Z_AXIS, yaw_deg);
        let v = rotate_about_axis(v, X_AXIS, pitch_deg);
        rotate_about_axis(v, Y_AXIS, roll_deg)
    };

    (normalize3(apply(row_dir)), normalize3(apply(col_dir)))
}

/// Rodrigues' rotation formula: rotates vector `v` by `degrees` about unit axis `axis`.
fn rotate_about_axis(v: Vec3, axis: Vec3, degrees: f64) -> Vec3 {
    if degrees.abs() < 1e-9 {
        return v;
    }
    let radians = degrees.to_radians();
    let (sin, cos) = radians.sin_cos();
    let term1 = scale3(v, cos);
    let term2 = scale3(cross3(axis, v), sin);
    let term3 = scale3(axis, dot3(axis, v) * (1.0 - cos));
    add3(add3(term1, term2), term3)
}

#[cfg(test)]
mod tests {

    #[test]
    fn permute_planes_in_place_applies_every_cycle_shape() {
        let plane_len = 3;
        for order in [
            vec![0, 1, 2, 3, 4, 5],
            vec![5, 4, 3, 2, 1, 0],
            vec![1, 2, 3, 4, 5, 0],
            vec![2, 0, 1, 5, 3, 4],
            vec![0, 2, 1, 3, 5, 4],
        ] {
            let mut samples: Vec<f32> = (0..order.len())
                .flat_map(|plane| (0..plane_len).map(move |i| (plane * 10 + i) as f32))
                .collect();
            super::permute_planes_in_place(&mut samples, plane_len, &order);
            for (destination, &source) in order.iter().enumerate() {
                for i in 0..plane_len {
                    assert_eq!(
                        samples[destination * plane_len + i],
                        (source * 10 + i) as f32,
                        "order {order:?}"
                    );
                }
            }
        }
    }

    use super::*;

    /// A 4x4x4 volume with axis-aligned geometry and `samples[idx] == idx as f32`, so every
    /// voxel has a distinct, hand-computable value - lets these tests assert exact sample
    /// identity instead of just "some plausible-looking output".
    fn axis_aligned_test_volume() -> Volume {
        let rows = 4u32;
        let cols = 4u32;
        let num_slices = 4u32;
        let plane = (rows * cols) as usize;
        let mut samples = vec![0f32; plane * num_slices as usize];
        for index in 0..samples.len() {
            samples[index] = index as f32;
        }
        Volume {
            samples,
            rows,
            cols,
            num_slices,
            origin: [0.0, 0.0, 0.0],
            row_vector: [1.0, 0.0, 0.0],
            col_vector: [0.0, 1.0, 0.0],
            slice_normal: [0.0, 0.0, 1.0],
            col_spacing_mm: 1.0,
            row_spacing_mm: 1.0,
            slice_zs: vec![0.0, 1.0, 2.0, 3.0],
            modality: None,
            frame_of_reference_uid: None,
            series_instance_uid: None,
            study_instance_uid: None,
            gantry_tilt_deg: 0.0,
            desheared: false,
        }
    }

    fn voxel_index(rows: u32, cols: u32, row: u32, col: u32, slice: u32) -> f32 {
        (slice * rows * cols + row * cols + col) as f32
    }

    #[test]
    fn voxel_clamps_out_of_range_indices() {
        let volume = axis_aligned_test_volume();
        assert_eq!(volume.voxel(-5, -5, -5), volume.voxel(0, 0, 0));
        assert_eq!(volume.voxel(100, 100, 100), volume.voxel(3, 3, 3));
    }

    #[test]
    fn sample_nearest_returns_exact_voxel_at_integer_coordinates() {
        let volume = axis_aligned_test_volume();
        for slice in 0..4u32 {
            for row in 0..4u32 {
                for col in 0..4u32 {
                    let sampled = sample_nearest(&volume, row as f64, col as f64, slice as f64);
                    assert_eq!(sampled, f64::from(voxel_index(4, 4, row, col, slice)));
                }
            }
        }
    }

    #[test]
    fn sample_trilinear_matches_nearest_at_integer_coordinates() {
        let volume = axis_aligned_test_volume();
        for (row, col, slice) in [(0.0, 0.0, 0.0), (1.0, 2.0, 3.0), (3.0, 3.0, 3.0)] {
            assert_eq!(
                sample_trilinear(&volume, row, col, slice),
                sample_nearest(&volume, row, col, slice)
            );
        }
    }

    #[test]
    fn sample_trilinear_interpolates_linearly_along_one_axis() {
        let volume = axis_aligned_test_volume();
        // Halfway between column 0 and column 1 (same row/slice) should average those two
        // voxels' values, since every other axis is held at an exact integer coordinate.
        let midpoint = sample_trilinear(&volume, 0.0, 0.5, 0.0);
        let left = f64::from(voxel_index(4, 4, 0, 0, 0));
        let right = f64::from(voxel_index(4, 4, 0, 1, 0));
        assert_eq!(midpoint, (left + right) / 2.0);
    }

    #[test]
    fn fractional_slice_index_interpolates_between_bracketing_slices() {
        let zs = [0.0, 1.0, 3.0, 6.0]; // deliberately irregular spacing
        assert_eq!(fractional_slice_index(&zs, 0.0), Some(0.0));
        assert_eq!(fractional_slice_index(&zs, 1.0), Some(1.0));
        // Halfway (by position, not by index) between slices 1 (z=1) and 2 (z=3).
        assert_eq!(fractional_slice_index(&zs, 2.0), Some(1.5));
        // Well beyond either end is out of the volume.
        assert_eq!(fractional_slice_index(&zs, -100.0), None);
        assert_eq!(fractional_slice_index(&zs, 100.0), None);
    }

    #[test]
    fn reformat_plane_axial_reproduces_expected_voxels_at_known_pixel_centers() {
        let volume = axis_aligned_test_volume();
        // output=4x4 (even) makes `(index - width/2.0)` land on exact integers, so the sampled
        // world points line up exactly on volume voxel centers with no interpolation ambiguity.
        let params = PlaneParams {
            origin: [1.0, 1.0, 1.0], // world point under output pixel (col=2, row=2)
            row_dir: [1.0, 0.0, 0.0],
            col_dir: [0.0, 1.0, 0.0],
            output_width: 4,
            output_height: 4,
            spacing_mm: 1.0,
            // Covers the fixture's full [0, 63] value range tightly, so adjacent sample values
            // map to visibly distinct bytes instead of collapsing under coarse quantization.
            window_center: Some(31.5),
            window_width: Some(64.0),
            interpolation: Interpolation::Nearest,
            slab_thickness_mm: 0.0,
            slab_projection: SlabProjection::MaximumIntensity,
        };

        let output = reformat_plane(&volume, &params, RenderOutputFormat::Raw, 90).unwrap();
        assert_eq!(output.width, 4);
        assert_eq!(output.height, 4);
        assert_eq!(output.bytes.len(), 16);

        // Center pixel (col=2,row=2) samples world=origin exactly -> volume voxel (row=1,col=1,slice=1).
        // Pixel (col=1,row=1) samples one voxel step back in every axis -> voxel (row=0,col=0,slice=1).
        let center_byte = output.bytes[2 * 4 + 2];
        let back_byte = output.bytes[1 * 4 + 1];
        let expected_center = f64::from(voxel_index(4, 4, 1, 1, 1));
        let expected_back = f64::from(voxel_index(4, 4, 0, 0, 1));
        assert!(expected_center > expected_back, "test fixture assumption");
        assert!(
            center_byte > back_byte,
            "windowed byte at the higher-valued voxel should also be higher (center={center_byte}, back={back_byte})"
        );
    }

    #[test]
    fn sample_slab_combines_multiple_depths_per_projection_method() {
        let volume = axis_aligned_test_volume();
        // For this fixture's axis-aligned basis, [0,0,1] happens to equal volume.slice_normal
        // too, so a 3-sample slab centered on voxel (row=1,col=1,slice=1) lands exactly on
        // slices 0, 1, 2 at that same row/col - voxel_index gives 5, 21, 37 respectively.
        let normal = [0.0, 0.0, 1.0];
        let center = [1.0, 1.0, 1.0];

        let mip = sample_slab(
            &volume,
            center,
            normal,
            3,
            1.0,
            Interpolation::Nearest,
            SlabProjection::MaximumIntensity,
        );
        let minip = sample_slab(
            &volume,
            center,
            normal,
            3,
            1.0,
            Interpolation::Nearest,
            SlabProjection::MinimumIntensity,
        );
        let average = sample_slab(
            &volume,
            center,
            normal,
            3,
            1.0,
            Interpolation::Nearest,
            SlabProjection::Average,
        );

        assert_eq!(mip, Some(37.0));
        assert_eq!(minip, Some(5.0));
        assert_eq!(average, Some((5.0 + 21.0 + 37.0) / 3.0));
    }

    #[test]
    fn sample_slab_skips_out_of_volume_samples_and_returns_none_if_all_miss() {
        let volume = axis_aligned_test_volume();
        // Centered on the volume's edge slice with a wide slab - half the samples fall outside.
        let normal = [0.0, 0.0, 1.0];
        let center = [1.0, 1.0, 0.0];

        let result = sample_slab(
            &volume,
            center,
            normal,
            5,
            1.0,
            Interpolation::Nearest,
            SlabProjection::MaximumIntensity,
        );
        assert!(
            result.is_some(),
            "slab should still combine the in-bounds samples"
        );

        let far_outside = [1.0, 1.0, 1000.0];
        let none_in_bounds = sample_slab(
            &volume,
            far_outside,
            normal,
            3,
            1.0,
            Interpolation::Nearest,
            SlabProjection::Average,
        );
        assert_eq!(none_in_bounds, None);
    }

    #[test]
    fn reformat_plane_with_a_thick_slab_differs_from_a_thin_plane() {
        let volume = axis_aligned_test_volume();
        // Fixed (not auto-normalized) window/level, so an absolute raw-value shift from the slab
        // is actually visible in the output bytes - auto min-max normalization would otherwise
        // hide it, since in this fixture every voxel value increases uniformly with slice index
        // (samples[idx] == idx), so a slab's max-vs-thin-plane difference is the SAME additive
        // shift at every pixel, which robust per-image normalization cancels out entirely.
        let base_params = PlaneParams {
            origin: [1.0, 1.0, 1.0],
            row_dir: [1.0, 0.0, 0.0],
            col_dir: [0.0, 1.0, 0.0],
            output_width: 4,
            output_height: 4,
            spacing_mm: 1.0,
            window_center: Some(31.5),
            window_width: Some(64.0),
            interpolation: Interpolation::Nearest,
            slab_thickness_mm: 0.0,
            slab_projection: SlabProjection::MaximumIntensity,
        };

        let thin = reformat_plane(&volume, &base_params, RenderOutputFormat::Raw, 90).unwrap();
        let thick_params = PlaneParams {
            slab_thickness_mm: 2.0,
            ..base_params
        };
        let thick_mip =
            reformat_plane(&volume, &thick_params, RenderOutputFormat::Raw, 90).unwrap();

        // The MIP slab spans slices {0,1,2} at every pixel (this reformat plane sits exactly on
        // volume.slice_normal), and values increase monotonically with slice index in this
        // fixture, so MIP == "the thin plane one slice further in" everywhere - strictly higher
        // at every non-clipped pixel, never lower.
        for (thick_byte, thin_byte) in thick_mip.bytes.iter().zip(thin.bytes.iter()) {
            assert!(thick_byte >= thin_byte, "MIP slab must never be dimmer than the thin plane (thick={thick_byte}, thin={thin_byte})");
        }
        assert_ne!(
            thick_mip.bytes, thin.bytes,
            "a 2mm MIP slab should differ from the thin plane somewhere"
        );
    }

    #[test]
    fn reformat_plane_rejects_negative_slab_thickness() {
        let volume = axis_aligned_test_volume();
        let params = PlaneParams {
            origin: [1.0, 1.0, 1.0],
            row_dir: [1.0, 0.0, 0.0],
            col_dir: [0.0, 1.0, 0.0],
            output_width: 4,
            output_height: 4,
            spacing_mm: 1.0,
            window_center: None,
            window_width: None,
            interpolation: Interpolation::Nearest,
            slab_thickness_mm: -5.0,
            slab_projection: SlabProjection::MaximumIntensity,
        };

        let result = reformat_plane(&volume, &params, RenderOutputFormat::Raw, 90);
        assert!(matches!(result, Err(VolumeError::InvalidSlabThickness)));
    }

    #[test]
    fn canonical_view_basis_returns_orthonormal_vectors() {
        let volume = axis_aligned_test_volume();
        for view in ["axial", "coronal", "sagittal"] {
            let (row_dir, col_dir) = canonical_view_basis(view, &volume).unwrap();
            assert!(
                (norm3(row_dir) - 1.0).abs() < 1e-9,
                "{view} row_dir not unit length"
            );
            assert!(
                (norm3(col_dir) - 1.0).abs() < 1e-9,
                "{view} col_dir not unit length"
            );
            assert!(
                dot3(row_dir, col_dir).abs() < 1e-9,
                "{view} row_dir/col_dir not orthogonal"
            );
        }
        assert!(canonical_view_basis("oblique-nonsense", &volume).is_err());
    }

    #[test]
    fn rotate_basis_preserves_orthonormality() {
        let (row_dir, col_dir) = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
        for (yaw, pitch, roll) in [(30.0, 0.0, 0.0), (0.0, 45.0, 0.0), (17.0, -22.0, 63.0)] {
            let (rotated_row, rotated_col) = rotate_basis(row_dir, col_dir, yaw, pitch, roll);
            assert!((norm3(rotated_row) - 1.0).abs() < 1e-9);
            assert!((norm3(rotated_col) - 1.0).abs() < 1e-9);
            assert!(
                dot3(rotated_row, rotated_col).abs() < 1e-9,
                "rotation broke orthogonality at yaw={yaw} pitch={pitch} roll={roll}"
            );
        }
    }

    #[test]
    fn resample_volume_at_native_dims_reproduces_every_voxel_exactly() {
        let volume = axis_aligned_test_volume();
        let resampled = resample_volume(&volume, 4, 4, 4, Interpolation::Nearest);
        assert_eq!(resampled, volume.samples);
    }

    #[test]
    fn resample_volume_downsamples_a_linear_ramp_correctly() {
        // Samples increase by 1 for each unit step in col (see axis_aligned_test_volume's
        // samples[idx]==idx layout with cols=4). Downsampling cols 4->2 places the two output
        // columns exactly on native columns 0 and 3 (the corners), so this also exercises that
        // corner-alignment guarantee, not just the interpolation math.
        let volume = axis_aligned_test_volume();
        let resampled = resample_volume(&volume, 2, 4, 4, Interpolation::Trilinear);
        assert_eq!(resampled.len(), 2 * 4 * 4);
        // row=0,slice=0: native col 0 -> voxel_index(...,col=0)=0; native col 3 -> voxel_index(...,col=3)=3.
        assert_eq!(resampled[0], voxel_index(4, 4, 0, 0, 0));
        assert_eq!(resampled[1], voxel_index(4, 4, 0, 3, 0));
    }

    #[test]
    fn resample_volume_to_a_single_voxel_per_axis_samples_the_midpoint() {
        let volume = axis_aligned_test_volume();
        let resampled = resample_volume(&volume, 1, 1, 1, Interpolation::Nearest);
        assert_eq!(resampled.len(), 1);
        // Midpoint of [0,3] on every axis is 1.5, which nearest-rounds to voxel (1 or 2, ...) -
        // just assert it's some genuine in-range voxel value, not a default/zeroed placeholder.
        assert!(resampled[0] >= 0.0 && resampled[0] <= 63.0);
    }

    #[test]
    fn build_volume_rejects_empty_and_single_file_lists() {
        assert!(matches!(build_volume::<&str>(&[]), Err(VolumeError::Empty)));
        // One single-frame image is not a volume (one Enhanced multi-frame object can be).
        let single = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test/files/ct.dcm");
        assert!(matches!(
            build_volume(&[&single]),
            Err(VolumeError::TooFewSlices {
                found: 1,
                required: 2
            })
        ));
        assert!(matches!(
            build_volume(&["does-not-exist.dcm"]),
            Err(VolumeError::Read(_))
        ));
    }
}