oxigaf-render 0.1.2

Differentiable 3D Gaussian Splatting rasterizer (wgpu)
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
//! Quantized compressed Gaussian storage for memory reduction.
//!
//! Provides per-field quantization (positions → i16, rotations → i8,
//! scales → u8, opacities → u8) and LBG vector quantization for
//! spherical-harmonics coefficients.

use rayon::prelude::*;
use thiserror::Error;

// ────────────────────────────────────────────────────────────────
// Error type
// ────────────────────────────────────────────────────────────────

/// Errors that can occur during Gaussian compression / decompression.
#[derive(Debug, Error)]
pub enum CompressionError {
    /// Input slice is empty when at least one element is required.
    #[error("empty input: at least one Gaussian is required")]
    EmptyInput,

    /// Two arrays have different lengths when they must match.
    #[error("length mismatch for {field}: expected {expected}, got {got}")]
    LengthMismatch {
        /// Name of the field/array that was mismatched.
        field: &'static str,
        /// Expected length.
        expected: usize,
        /// Actual length found.
        got: usize,
    },

    /// Codebook size is invalid.
    #[error("invalid codebook size {size}: {reason}")]
    InvalidCodebookSize { size: usize, reason: &'static str },
}

// ────────────────────────────────────────────────────────────────
// Scene bounds
// ────────────────────────────────────────────────────────────────

/// Axis-aligned bounding box of the scene, used for position quantization.
#[derive(Debug, Clone)]
pub struct SceneBounds {
    /// Minimum corner [x_min, y_min, z_min].
    pub min: [f32; 3],
    /// Maximum corner [x_max, y_max, z_max].
    pub max: [f32; 3],
}

impl SceneBounds {
    /// Compute bounds from a slice of positions.  Returns `None` if empty.
    pub fn from_positions(positions: &[[f32; 3]]) -> Option<Self> {
        if positions.is_empty() {
            return None;
        }
        let mut mn = positions[0];
        let mut mx = positions[0];
        for p in positions.iter().skip(1) {
            for i in 0..3 {
                if p[i] < mn[i] {
                    mn[i] = p[i];
                }
                if p[i] > mx[i] {
                    mx[i] = p[i];
                }
            }
        }
        Some(Self { min: mn, max: mx })
    }

    /// Expand each bound outward by `margin` (useful to avoid clipping).
    pub fn expand(mut self, margin: f32) -> Self {
        for i in 0..3 {
            self.min[i] -= margin;
            self.max[i] += margin;
        }
        self
    }

    /// Returns `true` if `p` lies within [min, max] (inclusive).
    pub fn contains(&self, p: &[f32; 3]) -> bool {
        for ((&pv, &mn), &mx) in p.iter().zip(self.min.iter()).zip(self.max.iter()) {
            if pv < mn || pv > mx {
                return false;
            }
        }
        true
    }
}

// ────────────────────────────────────────────────────────────────
// Scalar quantization helpers
// ────────────────────────────────────────────────────────────────

/// Map `v` in `[lo, hi]` to `i16` in `[i16::MIN, i16::MAX]`.
///
/// When `lo == hi` the range is degenerate; returns 0.
fn quantize_i16(v: f32, lo: f32, hi: f32) -> i16 {
    if (hi - lo).abs() < f32::EPSILON {
        return 0;
    }
    let t = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
    // Map [0,1] → [i16::MIN, i16::MAX]
    let scaled = t * 65535.0 - 32768.0;
    // Round to nearest (not truncate) to halve the worst-case quantization
    // error and avoid a systematic bias toward `lo`.
    scaled.round().clamp(i16::MIN as f32, i16::MAX as f32) as i16
}

/// Dequantize `i16` back to `f32` in `[lo, hi]`.
fn dequantize_i16(q: i16, lo: f32, hi: f32) -> f32 {
    let t = (q as f32 + 32768.0) / 65535.0;
    lo + t * (hi - lo)
}

/// Map `v` in `[-1, 1]` to `i8` in `[i8::MIN, i8::MAX]`.
///
/// Values outside `[-1, 1]` are clamped.
fn quantize_i8(v: f32) -> i8 {
    let t = (v.clamp(-1.0, 1.0) + 1.0) / 2.0; // [0, 1]
    let scaled = t * 255.0 - 128.0;
    // Round to nearest (not truncate) to halve the worst-case quantization
    // error and avoid a systematic bias toward zero.
    scaled.round().clamp(i8::MIN as f32, i8::MAX as f32) as i8
}

/// Dequantize `i8` back to `f32` in `[-1, 1]`.
fn dequantize_i8(q: i8) -> f32 {
    let t = (q as f32 + 128.0) / 255.0; // [0, 1]
    t * 2.0 - 1.0
}

/// Map `v` in `[lo, hi]` to `u8` in `[0, 255]`.
///
/// When `lo == hi` the range is degenerate; returns 128.
fn quantize_u8(v: f32, lo: f32, hi: f32) -> u8 {
    if (hi - lo).abs() < f32::EPSILON {
        return 128;
    }
    let t = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
    // Round to nearest (not truncate) to halve the worst-case quantization
    // error and avoid a systematic downward bias.
    (t * 255.0).round().clamp(0.0, 255.0) as u8
}

/// Dequantize `u8` back to `f32` in `[lo, hi]`.
fn dequantize_u8(q: u8, lo: f32, hi: f32) -> f32 {
    let t = q as f32 / 255.0;
    lo + t * (hi - lo)
}

// ────────────────────────────────────────────────────────────────
// RMS error helper
// ────────────────────────────────────────────────────────────────

fn rms_error_f32(a: &[f32], b: &[f32]) -> f32 {
    if a.is_empty() {
        return 0.0;
    }
    let mse = a
        .iter()
        .zip(b.iter())
        .map(|(x, y)| (x - y).powi(2))
        .sum::<f32>()
        / a.len() as f32;
    mse.sqrt()
}

// ────────────────────────────────────────────────────────────────
// Compressed positions
// ────────────────────────────────────────────────────────────────

/// Positions quantized to 3 × i16 per Gaussian.
#[derive(Debug, Clone)]
pub struct CompressedPositions {
    /// Quantized position data.
    pub data: Vec<[i16; 3]>,
    /// Scene bounds used for quantization.
    pub bounds: SceneBounds,
}

impl CompressedPositions {
    /// Compress positions using scene bounds.
    pub fn compress(positions: &[[f32; 3]], bounds: &SceneBounds) -> Self {
        let data = positions
            .iter()
            .map(|p| {
                [
                    quantize_i16(p[0], bounds.min[0], bounds.max[0]),
                    quantize_i16(p[1], bounds.min[1], bounds.max[1]),
                    quantize_i16(p[2], bounds.min[2], bounds.max[2]),
                ]
            })
            .collect();
        Self {
            data,
            bounds: bounds.clone(),
        }
    }

    /// Decompress back to f32 positions.
    pub fn decompress(&self) -> Vec<[f32; 3]> {
        self.data
            .iter()
            .map(|q| {
                [
                    dequantize_i16(q[0], self.bounds.min[0], self.bounds.max[0]),
                    dequantize_i16(q[1], self.bounds.min[1], self.bounds.max[1]),
                    dequantize_i16(q[2], self.bounds.min[2], self.bounds.max[2]),
                ]
            })
            .collect()
    }

    /// Number of compressed Gaussians.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if no Gaussians are stored.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Total bytes used by the quantized data.
    pub fn bytes(&self) -> usize {
        self.data.len() * 6
    }
}

// ────────────────────────────────────────────────────────────────
// Compressed rotations
// ────────────────────────────────────────────────────────────────

/// Unit quaternions quantized to 4 × i8 per Gaussian.
#[derive(Debug, Clone)]
pub struct CompressedRotations {
    /// Quantized quaternion data (components in [-1, 1]).
    pub data: Vec<[i8; 4]>,
}

impl CompressedRotations {
    /// Compress quaternion rotations.
    pub fn compress(rotations: &[[f32; 4]]) -> Self {
        let data = rotations
            .iter()
            .map(|r| {
                [
                    quantize_i8(r[0]),
                    quantize_i8(r[1]),
                    quantize_i8(r[2]),
                    quantize_i8(r[3]),
                ]
            })
            .collect();
        Self { data }
    }

    /// Decompress back to f32 quaternions.
    ///
    /// Each component is independently dequantized to ~1/128 resolution, so
    /// the raw result is not unit length; it is renormalized here so that
    /// consumers building a rotation matrix from it (which do not
    /// renormalize themselves, matching the GPU `quat_to_mat` shader) get a
    /// proper rotation rather than a scaled-and-sheared matrix.
    pub fn decompress(&self) -> Vec<[f32; 4]> {
        self.data
            .iter()
            .map(|q| {
                let x = dequantize_i8(q[0]);
                let y = dequantize_i8(q[1]);
                let z = dequantize_i8(q[2]);
                let w = dequantize_i8(q[3]);
                let n = (x * x + y * y + z * z + w * w).sqrt();
                if n < 1e-6 {
                    [0.0, 0.0, 0.0, 1.0]
                } else {
                    [x / n, y / n, z / n, w / n]
                }
            })
            .collect()
    }

    /// Number of compressed Gaussians.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if no Gaussians are stored.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Total bytes used by the quantized data.
    pub fn bytes(&self) -> usize {
        self.data.len() * 4
    }
}

// ────────────────────────────────────────────────────────────────
// Compressed scales
// ────────────────────────────────────────────────────────────────

/// Log-scales quantized to 3 × u8 per Gaussian.
#[derive(Debug, Clone)]
pub struct CompressedScales {
    /// Quantized log-scale data.
    pub data: Vec<[u8; 3]>,
    /// Minimum log-scale value (across all dimensions and Gaussians).
    pub log_min: f32,
    /// Maximum log-scale value.
    pub log_max: f32,
}

impl CompressedScales {
    /// Compress log-scale values.
    pub fn compress(scales: &[[f32; 3]]) -> Self {
        if scales.is_empty() {
            return Self {
                data: Vec::new(),
                log_min: 0.0,
                log_max: 0.0,
            };
        }
        // Find global min/max across all axes.
        let mut log_min = f32::INFINITY;
        let mut log_max = f32::NEG_INFINITY;
        for s in scales {
            for &v in s {
                if v < log_min {
                    log_min = v;
                }
                if v > log_max {
                    log_max = v;
                }
            }
        }
        let data = scales
            .iter()
            .map(|s| {
                [
                    quantize_u8(s[0], log_min, log_max),
                    quantize_u8(s[1], log_min, log_max),
                    quantize_u8(s[2], log_min, log_max),
                ]
            })
            .collect();
        Self {
            data,
            log_min,
            log_max,
        }
    }

    /// Decompress back to f32 log-scales.
    pub fn decompress(&self) -> Vec<[f32; 3]> {
        self.data
            .iter()
            .map(|q| {
                [
                    dequantize_u8(q[0], self.log_min, self.log_max),
                    dequantize_u8(q[1], self.log_min, self.log_max),
                    dequantize_u8(q[2], self.log_min, self.log_max),
                ]
            })
            .collect()
    }

    /// Number of compressed Gaussians.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if no Gaussians are stored.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Total bytes used by the quantized data.
    pub fn bytes(&self) -> usize {
        self.data.len() * 3
    }
}

// ────────────────────────────────────────────────────────────────
// Compressed opacities
// ────────────────────────────────────────────────────────────────

/// Logit-space opacities quantized to 1 × u8 per Gaussian.
#[derive(Debug, Clone)]
pub struct CompressedOpacities {
    /// Quantized opacity data.
    pub data: Vec<u8>,
    /// Minimum logit value.
    pub logit_min: f32,
    /// Maximum logit value.
    pub logit_max: f32,
}

impl CompressedOpacities {
    /// Compress logit-space opacities.
    pub fn compress(opacities: &[f32]) -> Self {
        if opacities.is_empty() {
            return Self {
                data: Vec::new(),
                logit_min: 0.0,
                logit_max: 0.0,
            };
        }
        let mut logit_min = f32::INFINITY;
        let mut logit_max = f32::NEG_INFINITY;
        for &v in opacities {
            if v < logit_min {
                logit_min = v;
            }
            if v > logit_max {
                logit_max = v;
            }
        }
        let data = opacities
            .iter()
            .map(|&v| quantize_u8(v, logit_min, logit_max))
            .collect();
        Self {
            data,
            logit_min,
            logit_max,
        }
    }

    /// Decompress back to f32 logit-space opacities.
    pub fn decompress(&self) -> Vec<f32> {
        self.data
            .iter()
            .map(|&q| dequantize_u8(q, self.logit_min, self.logit_max))
            .collect()
    }

    /// Number of compressed Gaussians.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if no Gaussians are stored.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Total bytes used by the quantized data.
    pub fn bytes(&self) -> usize {
        self.data.len()
    }
}

// ────────────────────────────────────────────────────────────────
// SH codebook (LBG vector quantization)
// ────────────────────────────────────────────────────────────────

/// LBG-style codebook for spherical-harmonics coefficients.
#[derive(Debug, Clone)]
pub struct ShCodebook {
    /// Codebook entries; each has length `sh_len`.
    pub entries: Vec<Vec<f32>>,
    /// Number of SH coefficients per Gaussian.
    pub sh_len: usize,
}

impl ShCodebook {
    /// Build a codebook using simplified LBG (binary split + k-means).
    ///
    /// `k` must be a power of two between 2 and 256 (inclusive).
    ///
    /// # Errors
    ///
    /// Returns [`CompressionError::EmptyInput`] if `sh_coeffs` is empty,
    /// [`CompressionError::InvalidCodebookSize`] if `k` is not a power of
    /// two in `[2, 256]`, or [`CompressionError::LengthMismatch`] if the SH
    /// vectors do not all share the same length.
    pub fn build(sh_coeffs: &[Vec<f32>], k: usize) -> Result<Self, CompressionError> {
        if sh_coeffs.is_empty() {
            return Err(CompressionError::EmptyInput);
        }

        // Validate k is power of 2 and in [2, 256].
        if !(2..=256).contains(&k) || (k & (k - 1)) != 0 {
            return Err(CompressionError::InvalidCodebookSize {
                size: k,
                reason: "must be a power of two between 2 and 256",
            });
        }

        // All SH vectors must share the same length; otherwise `compute_mean`
        // and `sq_dist` would silently zip to the shorter length, biasing
        // centroids, and `decode` would silently change the SH coefficient
        // count of the ragged Gaussians.
        let sh_len = sh_coeffs[0].len();
        if let Some(bad) = sh_coeffs.iter().position(|v| v.len() != sh_len) {
            return Err(CompressionError::LengthMismatch {
                field: "sh_coeffs (ragged: per-Gaussian SH vector lengths differ)",
                expected: sh_len,
                got: sh_coeffs[bad].len(),
            });
        }
        let n = sh_coeffs.len();

        // Cap effective k to number of inputs to avoid degenerate codebooks.
        let effective_k = k.min(n);

        // Start: single centroid = mean of all vectors.
        let mean = compute_mean(sh_coeffs, sh_len);
        let mut codebook: Vec<Vec<f32>> = vec![mean];

        // Binary split until we reach effective_k.
        while codebook.len() < effective_k {
            let current_len = codebook.len();
            let mut new_entries: Vec<Vec<f32>> = Vec::with_capacity(current_len * 2);
            for entry in &codebook {
                let (a, b) = split_entry(entry);
                new_entries.push(a);
                new_entries.push(b);
            }
            codebook = new_entries;
            // Trim if we overshoot (shouldn't happen with power-of-2 k).
            codebook.truncate(effective_k);
            // Refine with k-means.
            codebook = kmeans_refine(sh_coeffs, codebook, sh_len, 20);
        }

        Ok(Self {
            entries: codebook,
            sh_len,
        })
    }

    /// Encode each SH vector as an index into the codebook.
    pub fn encode(&self, sh_coeffs: &[Vec<f32>]) -> Vec<u8> {
        // O(N*K*L) nearest-centroid search; data points are independent so
        // this parallelizes trivially across all available threads.
        sh_coeffs
            .par_iter()
            .map(|v| {
                let mut best_idx = 0usize;
                let mut best_dist = f32::INFINITY;
                for (i, entry) in self.entries.iter().enumerate() {
                    let d = sq_dist(v, entry);
                    if d < best_dist {
                        best_dist = d;
                        best_idx = i;
                    }
                }
                // Safe: entries.len() <= 256 per construction.
                (best_idx & 0xFF) as u8
            })
            .collect()
    }

    /// Decode indices back to SH vectors.
    pub fn decode(&self, indices: &[u8]) -> Vec<Vec<f32>> {
        indices
            .iter()
            .map(|&idx| {
                let i = (idx as usize).min(self.entries.len().saturating_sub(1));
                self.entries[i].clone()
            })
            .collect()
    }

    /// Total bytes used by the codebook (f32 storage).
    pub fn bytes(&self) -> usize {
        self.entries.len() * self.sh_len * 4
    }
}

// ── LBG internals ──────────────────────────────────────────────

/// Compute the mean vector of a slice of equal-length vectors.
fn compute_mean(vecs: &[Vec<f32>], sh_len: usize) -> Vec<f32> {
    let mut sum = vec![0.0f32; sh_len];
    for v in vecs {
        for (s, &x) in sum.iter_mut().zip(v.iter()) {
            *s += x;
        }
    }
    let n = vecs.len() as f32;
    sum.iter().map(|&s| s / n).collect()
}

/// Split a codebook entry into two by nudging ± epsilon on every dimension.
fn split_entry(entry: &[f32]) -> (Vec<f32>, Vec<f32>) {
    const EPS: f32 = 1e-4;
    let a = entry.iter().map(|&x| x + EPS).collect();
    let b = entry.iter().map(|&x| x - EPS).collect();
    (a, b)
}

/// Squared Euclidean distance between two equal-length vectors.
fn sq_dist(a: &[f32], b: &[f32]) -> f32 {
    a.iter()
        .zip(b.iter())
        .map(|(&x, &y)| (x - y) * (x - y))
        .sum()
}

/// Assign each data vector to its nearest centroid.
/// Returns `(assignments, per-centroid total distortion)`.
fn assign_to_centroids(data: &[Vec<f32>], codebook: &[Vec<f32>]) -> (Vec<usize>, Vec<f32>) {
    let k = codebook.len();
    // The O(N*K*L) nearest-centroid search dominates k-means cost; each data
    // point is independent, so run it across all available threads. The
    // per-centroid distortion accumulation stays a cheap sequential O(N)
    // fold over the (index, distance) pairs so the result is deterministic.
    let per_point: Vec<(usize, f32)> = data
        .par_iter()
        .map(|v| {
            let mut best_idx = 0usize;
            let mut best_dist = f32::INFINITY;
            for (i, entry) in codebook.iter().enumerate() {
                let d = sq_dist(v, entry);
                if d < best_dist {
                    best_dist = d;
                    best_idx = i;
                }
            }
            (best_idx, best_dist)
        })
        .collect();

    let mut assignments = vec![0usize; data.len()];
    let mut distortions = vec![0.0f32; k];
    for (idx, &(best_idx, best_dist)) in per_point.iter().enumerate() {
        assignments[idx] = best_idx;
        distortions[best_idx] += best_dist;
    }
    (assignments, distortions)
}

/// Run at most `max_iter` iterations of k-means refinement.
///
/// Dead centroids (no assigned vectors) are reinitialized from the data
/// point that is farthest from its assigned centroid in the cluster with
/// the highest total distortion.  This ensures the codebook never
/// collapses to fewer entries than requested.
fn kmeans_refine(
    data: &[Vec<f32>],
    mut codebook: Vec<Vec<f32>>,
    sh_len: usize,
    max_iter: usize,
) -> Vec<Vec<f32>> {
    let k = codebook.len();
    if k == 0 || data.is_empty() {
        return codebook;
    }

    // Relative tolerance on total squared-error distortion: once an
    // iteration improves the k-means objective by less than this fraction,
    // the codebook is close enough to its fixed point that further
    // O(N*K*L) passes are not worth their cost. This is in addition to (not
    // a replacement for) the exact-stagnation `changed` check below, and is
    // only consulted *after* dead-centroid reinitialization and the live
    // centroid update below have both run for the current iteration, so an
    // iteration that is "converged" in aggregate distortion still gets its
    // dead centroids fixed before we decide whether to stop.
    const CONVERGENCE_TOL: f32 = 1e-5;
    let mut prev_total_distortion: Option<f32> = None;

    for _iter in 0..max_iter {
        let (assignments, distortions) = assign_to_centroids(data, &codebook);
        let total_distortion: f32 = distortions.iter().sum();

        // Recompute centroids from assignments.
        let mut sums: Vec<Vec<f32>> = vec![vec![0.0f32; sh_len]; k];
        let mut counts: Vec<usize> = vec![0usize; k];
        for (idx, &c) in assignments.iter().enumerate() {
            for (s, &x) in sums[c].iter_mut().zip(data[idx].iter()) {
                *s += x;
            }
            counts[c] += 1;
        }

        let mut changed = false;

        // Handle dead centroids: reinitialize from largest-distortion cluster.
        let dead_centroid_indices: Vec<usize> = (0..k).filter(|&i| counts[i] == 0).collect();

        for dead_idx in dead_centroid_indices {
            // Find the cluster with the highest total distortion to steal from.
            let donor_cluster = (0..k)
                .filter(|&i| counts[i] > 1) // must have at least 2 points
                .max_by(|&a, &b| {
                    distortions[a]
                        .partial_cmp(&distortions[b])
                        .unwrap_or(std::cmp::Ordering::Equal)
                });
            if let Some(donor) = donor_cluster {
                // Find the farthest data point from the donor centroid.
                let farthest_idx = assignments
                    .iter()
                    .enumerate()
                    .filter(|(_, &c)| c == donor)
                    .max_by(|(ia, _), (ib, _)| {
                        sq_dist(&data[*ia], &codebook[donor])
                            .partial_cmp(&sq_dist(&data[*ib], &codebook[donor]))
                            .unwrap_or(std::cmp::Ordering::Equal)
                    })
                    .map(|(i, _)| i);
                if let Some(fi) = farthest_idx {
                    codebook[dead_idx] = data[fi].clone();
                    changed = true;
                }
            }
        }

        // Update live centroids.
        for i in 0..k {
            if counts[i] == 0 {
                continue;
            }
            let new_centroid: Vec<f32> = sums[i].iter().map(|&s| s / counts[i] as f32).collect();
            let delta = sq_dist(&new_centroid, &codebook[i]);
            if delta > 1e-10 {
                changed = true;
            }
            codebook[i] = new_centroid;
        }

        if !changed {
            break;
        }

        // Convergence-tolerance early exit (see comment above): checked
        // last so it never skips a dead-centroid reinit or live-centroid
        // update for the current iteration.
        if let Some(prev) = prev_total_distortion {
            let denom = prev.max(1e-12);
            if ((prev - total_distortion).abs() / denom) < CONVERGENCE_TOL {
                break;
            }
        }
        prev_total_distortion = Some(total_distortion);
    }

    codebook
}

// ────────────────────────────────────────────────────────────────
// SH compression enum
// ────────────────────────────────────────────────────────────────

/// Compressed representation of SH coefficients.
#[derive(Debug, Clone)]
pub enum ShCompressed {
    /// No compression — raw f32 per Gaussian.
    Raw(Vec<Vec<f32>>),
    /// Codebook-compressed with per-Gaussian indices.
    Codebook {
        /// The LBG codebook.
        codebook: ShCodebook,
        /// Per-Gaussian codebook index.
        indices: Vec<u8>,
    },
}

// ────────────────────────────────────────────────────────────────
// Compressed Gaussian model
// ────────────────────────────────────────────────────────────────

/// A fully compressed Gaussian model ready for storage or streaming.
#[derive(Debug, Clone)]
pub struct CompressedGaussianModel {
    /// Quantized positions.
    pub positions: CompressedPositions,
    /// Quantized rotations.
    pub rotations: CompressedRotations,
    /// Quantized log-scales.
    pub scales: CompressedScales,
    /// Quantized logit-opacities.
    pub opacities: CompressedOpacities,
    /// Compressed SH coefficients (raw or codebook).
    pub sh_compressed: ShCompressed,
    /// SH degree used (0–3).
    pub sh_degree: u32,
    /// Number of Gaussians.
    pub num_gaussians: usize,
}

impl CompressedGaussianModel {
    /// Total bytes occupied by all compressed fields.
    pub fn total_bytes(&self) -> usize {
        let sh_bytes = match &self.sh_compressed {
            ShCompressed::Raw(raw) => raw.iter().map(|v| v.len() * 4).sum::<usize>(),
            ShCompressed::Codebook { codebook, indices } => codebook.bytes() + indices.len(),
        };
        self.positions.bytes()
            + self.rotations.bytes()
            + self.scales.bytes()
            + self.opacities.bytes()
            + sh_bytes
    }
}

// ────────────────────────────────────────────────────────────────
// Decompressed arrays
// ────────────────────────────────────────────────────────────────

/// All Gaussian arrays after decompression.
#[derive(Debug)]
pub struct DecompressedArrays {
    /// Positions.
    pub positions: Vec<[f32; 3]>,
    /// Rotation quaternions.
    pub rotations: Vec<[f32; 4]>,
    /// Log-scales.
    pub scales: Vec<[f32; 3]>,
    /// Logit-opacities.
    pub opacities: Vec<f32>,
    /// SH coefficients per Gaussian.
    pub sh_coeffs: Vec<Vec<f32>>,
}

// ────────────────────────────────────────────────────────────────
// Compression config
// ────────────────────────────────────────────────────────────────

/// Configuration for Gaussian compression.
#[derive(Debug, Clone)]
pub struct CompressionConfig {
    /// How much to expand scene bounds before quantizing (default: 0.1).
    pub position_margin: f32,
    /// Whether to use codebook for SH coefficients (default: true).
    pub use_sh_codebook: bool,
    /// Number of codebook entries; must be a power of two (default: 256).
    pub sh_codebook_size: usize,
}

impl Default for CompressionConfig {
    fn default() -> Self {
        Self {
            position_margin: 0.1,
            use_sh_codebook: true,
            sh_codebook_size: 256,
        }
    }
}

// ────────────────────────────────────────────────────────────────
// Compression statistics
// ────────────────────────────────────────────────────────────────

/// Statistics reported after compression.
#[derive(Debug, Clone)]
pub struct CompressionStats {
    /// Uncompressed size in bytes (f32 storage).
    pub original_bytes: usize,
    /// Compressed size in bytes.
    pub compressed_bytes: usize,
    /// `original_bytes / compressed_bytes`.
    pub compression_ratio: f32,
    /// RMS error from position quantization.
    pub position_error_rms: f32,
    /// RMS error from rotation quantization.
    pub rotation_error_rms: f32,
    /// RMS error from scale quantization.
    pub scale_error_rms: f32,
    /// RMS error from opacity quantization.
    pub opacity_error_rms: f32,
    /// RMS error from SH compression.
    pub sh_error_rms: f32,
}

impl CompressionStats {
    /// Format a human-readable summary.
    pub fn format_summary(&self) -> String {
        format!(
            "Compression: {:.1}× ({} → {} bytes)\n\
             RMS errors — pos: {:.6}, rot: {:.6}, scale: {:.6}, opacity: {:.6}, sh: {:.6}",
            self.compression_ratio,
            self.original_bytes,
            self.compressed_bytes,
            self.position_error_rms,
            self.rotation_error_rms,
            self.scale_error_rms,
            self.opacity_error_rms,
            self.sh_error_rms,
        )
    }
}

// ────────────────────────────────────────────────────────────────
// Main compression / decompression functions
// ────────────────────────────────────────────────────────────────

/// Compress all Gaussian arrays into a `CompressedGaussianModel`.
///
/// Returns the compressed model and compression statistics.
pub fn compress_gaussians(
    positions: &[[f32; 3]],
    rotations: &[[f32; 4]],
    scales: &[[f32; 3]],
    opacities: &[f32],
    sh_coeffs: &[Vec<f32>],
    sh_degree: u32,
    config: &CompressionConfig,
) -> Result<(CompressedGaussianModel, CompressionStats), CompressionError> {
    let n = positions.len();
    if n == 0 {
        return Err(CompressionError::EmptyInput);
    }
    // Validate lengths.
    for (name, got) in [
        ("rotations", rotations.len()),
        ("scales", scales.len()),
        ("opacities", opacities.len()),
    ] {
        if got != n {
            return Err(CompressionError::LengthMismatch {
                field: name,
                expected: n,
                got,
            });
        }
    }
    if !sh_coeffs.is_empty() && sh_coeffs.len() != n {
        return Err(CompressionError::LengthMismatch {
            field: "sh_coeffs",
            expected: n,
            got: sh_coeffs.len(),
        });
    }
    // SH vectors must all share the same length; a ragged input would
    // otherwise silently bias `sh_len_per`'s byte accounting below and any
    // codebook built from it (see `ShCodebook::build`).
    if let Some(bad) = sh_coeffs
        .first()
        .map(|first| first.len())
        .and_then(|sh_len| sh_coeffs.iter().position(|v| v.len() != sh_len))
    {
        return Err(CompressionError::LengthMismatch {
            field: "sh_coeffs (ragged: per-Gaussian SH vector lengths differ)",
            expected: sh_coeffs[0].len(),
            got: sh_coeffs[bad].len(),
        });
    }

    // Validate codebook size.
    if config.use_sh_codebook && !sh_coeffs.is_empty() {
        let k = config.sh_codebook_size;
        if !(2..=256).contains(&k) || (k & (k - 1)) != 0 {
            return Err(CompressionError::InvalidCodebookSize {
                size: k,
                reason: "must be a power of two between 2 and 256",
            });
        }
    }

    // Uncompressed size: f32 per element.
    let sh_len_per = if sh_coeffs.is_empty() {
        0
    } else {
        sh_coeffs[0].len()
    };
    let original_bytes = (n * 3 + n * 4 + n * 3 + n + n * sh_len_per) * 4;

    // ── Compress positions ───────────────────────────────────────
    let bounds = SceneBounds::from_positions(positions)
        .ok_or(CompressionError::EmptyInput)?
        .expand(config.position_margin);
    let comp_pos = CompressedPositions::compress(positions, &bounds);

    // ── Compress rotations ───────────────────────────────────────
    let comp_rot = CompressedRotations::compress(rotations);

    // ── Compress scales ──────────────────────────────────────────
    let comp_scales = CompressedScales::compress(scales);

    // ── Compress opacities ───────────────────────────────────────
    let comp_opacities = CompressedOpacities::compress(opacities);

    // ── Compress SH ─────────────────────────────────────────────
    let sh_compressed = if sh_coeffs.is_empty() {
        ShCompressed::Raw(Vec::new())
    } else if config.use_sh_codebook {
        match ShCodebook::build(sh_coeffs, config.sh_codebook_size) {
            Ok(codebook) => {
                let indices = codebook.encode(sh_coeffs);
                ShCompressed::Codebook { codebook, indices }
            }
            // sh_coeffs/k were already validated above, so this should not
            // happen in practice; fall back to lossless raw storage rather
            // than failing the whole compression.
            Err(_) => ShCompressed::Raw(sh_coeffs.to_vec()),
        }
    } else {
        ShCompressed::Raw(sh_coeffs.to_vec())
    };

    // ── RMS errors ───────────────────────────────────────────────
    let pos_recon = comp_pos.decompress();
    let rot_recon = comp_rot.decompress();
    let scale_recon = comp_scales.decompress();
    let opacity_recon = comp_opacities.decompress();

    let pos_flat_orig: Vec<f32> = positions.iter().flat_map(|p| p.iter().copied()).collect();
    let pos_flat_recon: Vec<f32> = pos_recon.iter().flat_map(|p| p.iter().copied()).collect();
    let rot_flat_orig: Vec<f32> = rotations.iter().flat_map(|r| r.iter().copied()).collect();
    let rot_flat_recon: Vec<f32> = rot_recon.iter().flat_map(|r| r.iter().copied()).collect();
    let scale_flat_orig: Vec<f32> = scales.iter().flat_map(|s| s.iter().copied()).collect();
    let scale_flat_recon: Vec<f32> = scale_recon.iter().flat_map(|s| s.iter().copied()).collect();

    let position_error_rms = rms_error_f32(&pos_flat_orig, &pos_flat_recon);
    let rotation_error_rms = rms_error_f32(&rot_flat_orig, &rot_flat_recon);
    let scale_error_rms = rms_error_f32(&scale_flat_orig, &scale_flat_recon);
    let opacity_error_rms = rms_error_f32(opacities, &opacity_recon);

    let sh_error_rms = if sh_coeffs.is_empty() {
        0.0
    } else {
        let sh_recon = match &sh_compressed {
            ShCompressed::Raw(raw) => raw.clone(),
            ShCompressed::Codebook { codebook, indices } => codebook.decode(indices),
        };
        let orig_flat: Vec<f32> = sh_coeffs.iter().flat_map(|v| v.iter().copied()).collect();
        let recon_flat: Vec<f32> = sh_recon.iter().flat_map(|v| v.iter().copied()).collect();
        rms_error_f32(&orig_flat, &recon_flat)
    };

    // ── Build model ──────────────────────────────────────────────
    let model = CompressedGaussianModel {
        positions: comp_pos,
        rotations: comp_rot,
        scales: comp_scales,
        opacities: comp_opacities,
        sh_compressed,
        sh_degree,
        num_gaussians: n,
    };

    let compressed_bytes = model.total_bytes();
    let compression_ratio = if compressed_bytes > 0 {
        original_bytes as f32 / compressed_bytes as f32
    } else {
        1.0
    };

    let stats = CompressionStats {
        original_bytes,
        compressed_bytes,
        compression_ratio,
        position_error_rms,
        rotation_error_rms,
        scale_error_rms,
        opacity_error_rms,
        sh_error_rms,
    };

    Ok((model, stats))
}

/// Decompress a `CompressedGaussianModel` back to raw arrays.
pub fn decompress_gaussians(
    model: &CompressedGaussianModel,
) -> Result<DecompressedArrays, CompressionError> {
    let positions = model.positions.decompress();
    let rotations = model.rotations.decompress();
    let scales = model.scales.decompress();
    let opacities = model.opacities.decompress();

    let sh_coeffs = match &model.sh_compressed {
        ShCompressed::Raw(raw) => raw.clone(),
        ShCompressed::Codebook { codebook, indices } => codebook.decode(indices),
    };

    // Validate consistency. A `CompressedGaussianModel` can be constructed
    // directly (all fields are public) or deserialized from a truncated
    // file, so every array must be checked against `num_gaussians` here —
    // not just positions — or a mismatched array panics or silently drops
    // Gaussians at the first consumer that zips them together.
    let n = model.num_gaussians;
    for (field, len) in [
        ("positions", positions.len()),
        ("rotations", rotations.len()),
        ("scales", scales.len()),
        ("opacities", opacities.len()),
    ] {
        if len != n {
            return Err(CompressionError::LengthMismatch {
                field,
                expected: n,
                got: len,
            });
        }
    }
    // `sh_coeffs` is documented to be empty when the model carries no SH
    // data at all (see `ShCompressed::Raw(Vec::new())` in
    // `compress_gaussians`), so only enforce the length when non-empty.
    if !sh_coeffs.is_empty() && sh_coeffs.len() != n {
        return Err(CompressionError::LengthMismatch {
            field: "sh_coeffs",
            expected: n,
            got: sh_coeffs.len(),
        });
    }

    Ok(DecompressedArrays {
        positions,
        rotations,
        scales,
        opacities,
        sh_coeffs,
    })
}

// ────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────

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

    // ── Scalar quantization roundtrips ──────────────────────────

    #[test]
    fn test_quantize_i16_roundtrip() {
        let lo = -5.0f32;
        let hi = 5.0f32;
        for &v in &[-5.0f32, -2.5, 0.0, 2.5, 5.0] {
            let q = quantize_i16(v, lo, hi);
            let r = dequantize_i16(q, lo, hi);
            // Round-to-nearest halves the worst-case error vs. truncation
            // (0.5 LSB instead of 1 LSB).
            let max_err = (hi - lo) / 65535.0 / 2.0;
            assert!(
                (v - r).abs() <= max_err + 1e-6,
                "i16 roundtrip: orig={v}, recon={r}, max_err={max_err}"
            );
        }
    }

    #[test]
    fn test_quantize_i8_roundtrip() {
        for &v in &[-1.0f32, -0.5, 0.0, 0.5, 1.0] {
            let q = quantize_i8(v);
            let r = dequantize_i8(q);
            // i8 has 256 levels over range [-1, 1], so step ≈ 2/255 ≈ 0.00784;
            // round-to-nearest halves the worst case to ≈ 0.00392.
            assert!((v - r).abs() < 0.0045, "i8 roundtrip: orig={v}, recon={r}");
        }
    }

    #[test]
    fn test_quantize_u8_roundtrip() {
        let lo = 0.0f32;
        let hi = 1.0f32;
        for &v in &[0.0f32, 0.25, 0.5, 0.75, 1.0] {
            let q = quantize_u8(v, lo, hi);
            let r = dequantize_u8(q, lo, hi);
            // Round-to-nearest halves the worst-case error vs. truncation.
            let max_err = (hi - lo) / 255.0 / 2.0;
            assert!(
                (v - r).abs() <= max_err + 1e-6,
                "u8 roundtrip: orig={v}, recon={r}"
            );
        }
    }

    // ── SceneBounds ─────────────────────────────────────────────

    #[test]
    fn test_scene_bounds_from_positions() {
        let positions = vec![[1.0f32, 2.0, 3.0], [-1.0, 0.0, 5.0], [0.5, -2.0, 4.0]];
        let bounds = SceneBounds::from_positions(&positions).unwrap();
        assert!((bounds.min[0] - (-1.0)).abs() < 1e-6);
        assert!((bounds.max[0] - 1.0).abs() < 1e-6);
        assert!((bounds.min[1] - (-2.0)).abs() < 1e-6);
        assert!((bounds.max[1] - 2.0).abs() < 1e-6);
        assert!((bounds.min[2] - 3.0).abs() < 1e-6);
        assert!((bounds.max[2] - 5.0).abs() < 1e-6);
    }

    #[test]
    fn test_scene_bounds_from_empty() {
        let bounds = SceneBounds::from_positions(&[]);
        assert!(bounds.is_none());
    }

    // ── CompressedPositions ─────────────────────────────────────

    #[test]
    fn test_compress_positions_roundtrip() {
        let positions = vec![
            [0.0f32, 0.0, 0.0],
            [1.0, 2.0, 3.0],
            [-1.0, -2.0, -3.0],
            [0.5, 1.5, 2.5],
        ];
        let bounds = SceneBounds::from_positions(&positions).unwrap().expand(0.1);
        let comp = CompressedPositions::compress(&positions, &bounds);
        let recon = comp.decompress();
        let range = 10.0f32; // roughly 2 * (max 3.0) + margin
        let max_err = range / 65535.0 + 1e-4;
        for (orig, rec) in positions.iter().zip(recon.iter()) {
            for i in 0..3 {
                assert!(
                    (orig[i] - rec[i]).abs() < max_err,
                    "pos roundtrip axis {i}: orig={}, recon={}",
                    orig[i],
                    rec[i]
                );
            }
        }
    }

    // ── CompressedRotations ─────────────────────────────────────

    #[test]
    fn test_compress_rotations_roundtrip() {
        let rotations = vec![
            [0.0f32, 0.0, 0.0, 1.0],
            [0.5, 0.5, 0.5, 0.5],
            [-0.5, 0.5, -0.5, 0.5],
            [1.0f32 / 2.0f32.sqrt(), 0.0, 0.0, 1.0f32 / 2.0f32.sqrt()],
        ];
        let comp = CompressedRotations::compress(&rotations);
        let recon = comp.decompress();
        for (orig, rec) in rotations.iter().zip(recon.iter()) {
            for i in 0..4 {
                assert!(
                    (orig[i] - rec[i]).abs() < 0.01,
                    "rot roundtrip axis {i}: orig={}, recon={}",
                    orig[i],
                    rec[i]
                );
            }
        }
    }

    #[test]
    fn test_compress_rotations_decompress_is_normalized() {
        // Independent per-component i8 quantization does not preserve unit
        // length; `decompress` must renormalize so a consumer that builds a
        // rotation matrix straight from the result (as the GPU shader does,
        // without renormalizing itself) gets a proper rotation.
        let rotations = vec![
            [0.0f32, 0.0, 0.0, 1.0],
            [0.5, 0.5, 0.5, 0.5],
            [-0.5, 0.5, -0.5, 0.5],
            [1.0f32 / 2.0f32.sqrt(), 0.0, 0.0, 1.0f32 / 2.0f32.sqrt()],
            [0.1, 0.2, 0.3, 0.9],
        ];
        let comp = CompressedRotations::compress(&rotations);
        let recon = comp.decompress();
        for q in &recon {
            let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
            assert!(
                (norm - 1.0).abs() < 1e-5,
                "decompressed quaternion should be unit length, got |q|={norm} for {q:?}"
            );
        }
    }

    #[test]
    fn test_compress_rotations_decompress_extreme_values_stay_finite_and_normalized() {
        // Directly-constructed (not via `compress`) extreme i8 quadruples
        // must still dequantize+renormalize to a finite unit quaternion,
        // never NaN — exercising the same divide-by-norm path that a
        // near-zero-norm input would hit via the `n < 1e-6` fallback.
        let comp = CompressedRotations {
            data: vec![[i8::MIN, i8::MIN, i8::MIN, i8::MIN], [0, 0, 0, i8::MIN]],
        };
        let recon = comp.decompress();
        for q in &recon {
            let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
            for &v in q {
                assert!(v.is_finite(), "expected finite component, got {v}");
            }
            assert!(
                (norm - 1.0).abs() < 1e-5,
                "expected unit-length fallback/renormalization, got |q|={norm}"
            );
        }
    }

    // ── CompressedScales ────────────────────────────────────────

    #[test]
    fn test_compress_scales_roundtrip() {
        let scales = vec![[-3.0f32, -2.0, -1.0], [-0.5, 0.0, 0.5], [1.0, 2.0, 3.0]];
        let comp = CompressedScales::compress(&scales);
        let recon = comp.decompress();
        let range = comp.log_max - comp.log_min;
        let max_err = range / 255.0 + 1e-5;
        for (orig, rec) in scales.iter().zip(recon.iter()) {
            for i in 0..3 {
                assert!(
                    (orig[i] - rec[i]).abs() < max_err,
                    "scale roundtrip axis {i}: orig={}, recon={}",
                    orig[i],
                    rec[i]
                );
            }
        }
    }

    // ── CompressedOpacities ─────────────────────────────────────

    #[test]
    fn test_compress_opacities_roundtrip() {
        let opacities = vec![-5.0f32, -2.0, 0.0, 2.0, 5.0];
        let comp = CompressedOpacities::compress(&opacities);
        let recon = comp.decompress();
        let range = comp.logit_max - comp.logit_min;
        let max_err = range / 255.0 + 1e-5;
        for (orig, rec) in opacities.iter().zip(recon.iter()) {
            assert!(
                (orig - rec).abs() < max_err,
                "opacity roundtrip: orig={orig}, recon={rec}"
            );
        }
    }

    // ── ShCodebook ──────────────────────────────────────────────

    #[test]
    fn test_sh_codebook_build_simple() {
        // Two very different vectors, codebook of size 2.
        let sh_coeffs = vec![vec![1.0f32, 0.0, 0.0], vec![0.0f32, 0.0, 1.0]];
        let codebook = ShCodebook::build(&sh_coeffs, 2);
        assert!(codebook.is_ok());
        let cb = codebook.unwrap();
        assert_eq!(cb.entries.len(), 2);
        assert_eq!(cb.sh_len, 3);
    }

    #[test]
    fn test_sh_codebook_build_rejects_ragged_vectors() {
        // Second vector has a different length than the first.
        let sh_coeffs = vec![vec![1.0f32, 0.0, 0.0], vec![0.0f32, 1.0]];
        let result = ShCodebook::build(&sh_coeffs, 2);
        assert!(matches!(
            result,
            Err(CompressionError::LengthMismatch { .. })
        ));
    }

    #[test]
    fn test_sh_codebook_build_doc_range_matches_code() {
        // The doc says k must be a power of two in [2, 256]; k=2 (the
        // documented lower bound) must actually be accepted.
        let sh_coeffs = vec![vec![1.0f32, 0.0], vec![0.0f32, 1.0]];
        assert!(ShCodebook::build(&sh_coeffs, 2).is_ok());
        // Non-power-of-two and out-of-range sizes are rejected with a
        // reason, not silently swallowed.
        assert!(matches!(
            ShCodebook::build(&sh_coeffs, 3),
            Err(CompressionError::InvalidCodebookSize { .. })
        ));
        assert!(matches!(
            ShCodebook::build(&sh_coeffs, 512),
            Err(CompressionError::InvalidCodebookSize { .. })
        ));
    }

    #[test]
    fn test_sh_codebook_encode_decode() {
        // Create two clusters of 4 vectors each.
        let cluster_a = vec![1.0f32, 0.0];
        let cluster_b = vec![0.0f32, 1.0];
        let mut sh_coeffs: Vec<Vec<f32>> = Vec::new();
        for _ in 0..4 {
            sh_coeffs.push(cluster_a.clone());
        }
        for _ in 0..4 {
            sh_coeffs.push(cluster_b.clone());
        }
        let codebook = ShCodebook::build(&sh_coeffs, 2).unwrap();
        let indices = codebook.encode(&sh_coeffs);
        let decoded = codebook.decode(&indices);
        // All decoded vectors should be close to the original cluster center.
        for (orig, dec) in sh_coeffs.iter().zip(decoded.iter()) {
            let dist: f32 = orig
                .iter()
                .zip(dec.iter())
                .map(|(a, b)| (a - b).powi(2))
                .sum();
            assert!(dist.sqrt() < 0.05, "SH decode error too large: {dist}");
        }
    }

    // ── Full pipeline ───────────────────────────────────────────

    #[test]
    fn test_compress_gaussians_full_pipeline() {
        let n = 10usize;
        let positions: Vec<[f32; 3]> = (0..n)
            .map(|i| [i as f32 * 0.1, i as f32 * 0.2, i as f32 * 0.3])
            .collect();
        let rotations: Vec<[f32; 4]> = (0..n).map(|_| [0.0, 0.0, 0.0, 1.0]).collect();
        let scales: Vec<[f32; 3]> = (0..n).map(|i| [-1.0 + i as f32 * 0.1; 3]).collect();
        let opacities: Vec<f32> = (0..n).map(|i| i as f32 * 0.1 - 0.5).collect();
        let sh_len = 9usize;
        let sh_coeffs: Vec<Vec<f32>> = (0..n).map(|_| vec![0.0f32; sh_len]).collect();

        let config = CompressionConfig {
            use_sh_codebook: false,
            ..Default::default()
        };

        let result = compress_gaussians(
            &positions, &rotations, &scales, &opacities, &sh_coeffs, 1, &config,
        );
        assert!(
            result.is_ok(),
            "compress_gaussians failed: {:?}",
            result.err()
        );
        let (model, stats) = result.unwrap();
        assert_eq!(model.num_gaussians, n);
        assert!(stats.original_bytes > 0);
        assert!(stats.compressed_bytes > 0);
    }

    // ── CompressionStats ────────────────────────────────────────

    #[test]
    fn test_compression_stats_ratio() {
        let n = 100usize;
        let positions: Vec<[f32; 3]> = (0..n).map(|i| [i as f32; 3]).collect();
        let rotations: Vec<[f32; 4]> = (0..n).map(|_| [0.0, 0.0, 0.0, 1.0]).collect();
        let scales: Vec<[f32; 3]> = (0..n).map(|_| [-1.0, -1.5, -2.0]).collect();
        let opacities: Vec<f32> = (0..n).map(|i| i as f32 * 0.02 - 1.0).collect();
        let sh_len = 27usize;
        let sh_coeffs: Vec<Vec<f32>> = (0..n).map(|i| vec![(i as f32) * 0.01; sh_len]).collect();

        let config = CompressionConfig {
            sh_codebook_size: 64,
            ..Default::default()
        };
        let (_, stats) = compress_gaussians(
            &positions, &rotations, &scales, &opacities, &sh_coeffs, 2, &config,
        )
        .unwrap();

        assert!(
            stats.compressed_bytes < stats.original_bytes,
            "compressed ({}) should be smaller than original ({})",
            stats.compressed_bytes,
            stats.original_bytes
        );
        assert!(stats.compression_ratio > 1.0, "ratio should be > 1");
    }

    #[test]
    fn test_compression_stats_format_summary() {
        let stats = CompressionStats {
            original_bytes: 1000,
            compressed_bytes: 250,
            compression_ratio: 4.0,
            position_error_rms: 0.001,
            rotation_error_rms: 0.005,
            scale_error_rms: 0.002,
            opacity_error_rms: 0.003,
            sh_error_rms: 0.010,
        };
        let s = stats.format_summary();
        assert!(s.contains("4.0"), "summary should contain ratio: {s}");
        assert!(
            s.contains("1000"),
            "summary should contain original bytes: {s}"
        );
        assert!(
            s.contains("250"),
            "summary should contain compressed bytes: {s}"
        );
    }

    // ── RMS error helper ────────────────────────────────────────

    #[test]
    fn test_rms_error_helper() {
        let a = vec![1.0f32, 2.0, 3.0];
        let b = vec![1.1f32, 2.0, 2.9];
        let rms = rms_error_f32(&a, &b);
        // errors: 0.1, 0.0, 0.1 → mse = 0.02/3 → rms ≈ 0.0816
        assert!((rms - (0.02f32 / 3.0).sqrt()).abs() < 1e-5, "rms={rms}");
    }

    #[test]
    fn test_rms_error_helper_empty() {
        let rms = rms_error_f32(&[], &[]);
        assert_eq!(rms, 0.0);
    }

    // ── Error cases ─────────────────────────────────────────────

    #[test]
    fn test_empty_input_error() {
        let result = compress_gaussians(&[], &[], &[], &[], &[], 0, &Default::default());
        assert!(matches!(result, Err(CompressionError::EmptyInput)));
    }

    #[test]
    fn test_length_mismatch_error() {
        let positions = vec![[0.0f32; 3]; 3];
        let rotations = vec![[0.0f32, 0.0, 0.0, 1.0]; 2]; // wrong length
        let scales = vec![[-1.0f32; 3]; 3];
        let opacities = vec![0.0f32; 3];
        let result = compress_gaussians(
            &positions,
            &rotations,
            &scales,
            &opacities,
            &[],
            0,
            &Default::default(),
        );
        assert!(matches!(
            result,
            Err(CompressionError::LengthMismatch { .. })
        ));
    }

    #[test]
    fn test_length_mismatch_error_names_field() {
        let positions = vec![[0.0f32; 3]; 3];
        let rotations = vec![[0.0f32, 0.0, 0.0, 1.0]; 2]; // wrong length
        let scales = vec![[-1.0f32; 3]; 3];
        let opacities = vec![0.0f32; 3];
        let result = compress_gaussians(
            &positions,
            &rotations,
            &scales,
            &opacities,
            &[],
            0,
            &Default::default(),
        );
        match result {
            Err(CompressionError::LengthMismatch { field, .. }) => {
                assert_eq!(field, "rotations", "error should name the short array")
            }
            other => panic!("expected LengthMismatch naming 'rotations', got {other:?}"),
        }
    }

    #[test]
    fn test_compress_gaussians_rejects_ragged_sh_vectors() {
        let n = 3usize;
        let positions: Vec<[f32; 3]> = vec![[0.0; 3]; n];
        let rotations: Vec<[f32; 4]> = vec![[0.0, 0.0, 0.0, 1.0]; n];
        let scales: Vec<[f32; 3]> = vec![[-1.0; 3]; n];
        let opacities: Vec<f32> = vec![0.0; n];
        // Second Gaussian's SH vector has a different length than the rest.
        let sh_coeffs: Vec<Vec<f32>> = vec![vec![0.0f32; 9], vec![0.0f32; 6], vec![0.0f32; 9]];
        let result = compress_gaussians(
            &positions,
            &rotations,
            &scales,
            &opacities,
            &sh_coeffs,
            1,
            &Default::default(),
        );
        assert!(matches!(
            result,
            Err(CompressionError::LengthMismatch { .. })
        ));
    }

    #[test]
    fn test_decompress_gaussians_rejects_truncated_rotations() {
        // Directly construct a model whose rotations array is shorter than
        // `num_gaussians` (as if deserialized from a truncated file).
        let positions = CompressedPositions::compress(
            &[[0.0f32; 3], [1.0, 1.0, 1.0]],
            &SceneBounds {
                min: [0.0; 3],
                max: [1.0; 3],
            },
        );
        let rotations = CompressedRotations::compress(&[[0.0, 0.0, 0.0, 1.0]]); // only 1, need 2
        let scales = CompressedScales::compress(&[[-1.0f32; 3], [-1.0; 3]]);
        let opacities = CompressedOpacities::compress(&[0.0f32, 0.0]);
        let model = CompressedGaussianModel {
            positions,
            rotations,
            scales,
            opacities,
            sh_compressed: ShCompressed::Raw(Vec::new()),
            sh_degree: 0,
            num_gaussians: 2,
        };
        let result = decompress_gaussians(&model);
        match result {
            Err(CompressionError::LengthMismatch { field, .. }) => {
                assert_eq!(field, "rotations")
            }
            other => panic!("expected LengthMismatch naming 'rotations', got {other:?}"),
        }
    }

    // ── Decompress roundtrip RMS ────────────────────────────────

    #[test]
    fn test_decompress_roundtrip_rms_error_small() {
        // Use values in typical ranges; expect RMS error < 0.01 for all fields.
        let n = 50usize;
        let positions: Vec<[f32; 3]> = (0..n)
            .map(|i| {
                let t = i as f32 / n as f32;
                [t * 2.0 - 1.0, t * 3.0 - 1.5, t * 4.0 - 2.0]
            })
            .collect();
        // Normalize rotations to unit quaternions.
        let rotations: Vec<[f32; 4]> = (0..n)
            .map(|i| {
                let t = i as f32 / n as f32;
                let q = [t - 0.5, 0.3, -0.2, (1.0f32 - t * 0.1).max(0.1)];
                let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
                [q[0] / norm, q[1] / norm, q[2] / norm, q[3] / norm]
            })
            .collect();
        let scales: Vec<[f32; 3]> = (0..n)
            .map(|i| {
                let t = i as f32 / n as f32;
                [-3.0 + t * 3.0; 3]
            })
            .collect();
        let opacities: Vec<f32> = (0..n).map(|i| (i as f32 / n as f32) * 6.0 - 3.0).collect();
        let sh_len = 9usize;
        let sh_coeffs: Vec<Vec<f32>> = (0..n)
            .map(|i| (0..sh_len).map(|j| (i + j) as f32 * 0.01).collect())
            .collect();

        let config = CompressionConfig {
            use_sh_codebook: false, // raw SH for exact roundtrip
            ..Default::default()
        };
        let (model, stats) = compress_gaussians(
            &positions, &rotations, &scales, &opacities, &sh_coeffs, 1, &config,
        )
        .unwrap();

        let arrays = decompress_gaussians(&model).unwrap();
        assert_eq!(arrays.positions.len(), n);
        assert_eq!(arrays.rotations.len(), n);

        // Position RMS < 0.01 (range ~ 6 / 65535 ≈ very small, but bounds add margin).
        assert!(
            stats.position_error_rms < 0.01,
            "position RMS too large: {}",
            stats.position_error_rms
        );
        // Rotation RMS < 0.01 (i8 over [-1,1]: step ≈ 0.008).
        assert!(
            stats.rotation_error_rms < 0.01,
            "rotation RMS too large: {}",
            stats.rotation_error_rms
        );
        // Scale and opacity RMS < 0.05 (u8 over ~6 unit range).
        assert!(
            stats.scale_error_rms < 0.05,
            "scale RMS too large: {}",
            stats.scale_error_rms
        );
        assert!(
            stats.opacity_error_rms < 0.05,
            "opacity RMS too large: {}",
            stats.opacity_error_rms
        );
        // SH is raw (no compression), so error is zero.
        assert!(
            stats.sh_error_rms < 1e-6,
            "sh RMS should be near zero: {}",
            stats.sh_error_rms
        );
    }
}