wgpu-3dgs-core 0.7.0

A 3D Gaussian splatting library written in Rust using 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
use std::{
    io::{Read, Write},
    ops::RangeInclusive,
};

use flate2::{read::GzDecoder, write::GzEncoder};
use itertools::Itertools;

use crate::{
    Gaussian, GaussianToSpzOptions, IterGaussian, ReadIterGaussian, SpzGaussiansFromIterError,
    WriteIterGaussian,
};

macro_rules! gaussian_field {
    (
        #[docname = $docname:literal]
        $name:ident {
            $(
                $(#[doc = $doc:literal])?
                $variant:ident $(($ty:ty))?
            ),+ $(,)?
        }
    ) => {
        paste::paste! {
            macro_rules! noop {
                ($tt:tt) => {};
                ($tt:tt _) => {_};
            }

            #[doc = "A single SPZ Gaussian "]
            #[doc = $docname]
            #[doc = " field."]
            #[derive(Debug, Clone, PartialEq)]
            pub enum [< SpzGaussian $name >]  {
                $(
                    $(#[doc = $doc])?
                    $variant $(($ty))?,
                )+
            }

            #[doc = "Reference to SPZ Gaussian "]
            #[doc = $docname]
            #[doc = " field."]
            #[derive(Debug, Clone, Copy, PartialEq)]
            pub enum [< SpzGaussian $name Ref>]<'a> {
                $(
                    $(#[doc = $doc])?
                    $variant $((&'a $ty))?,
                )+
            }

            #[doc = "Iterator over SPZ Gaussian "]
            #[doc = $docname]
            #[doc = " references."]
            pub enum [< SpzGaussian $name Iter >]<'a> {
                $(
                    $(#[doc = $doc])?
                    $variant $((std::slice::Iter<'a, $ty>))?,
                )+
            }

            impl<'a> Iterator for [< SpzGaussian $name Iter >]<'a> {
                type Item = [< SpzGaussian $name Ref >]<'a>;

                fn next(&mut self) -> Option<Self::Item> {
                    macro_rules! body {
                        ($variant_:ident, $ty_:ty, $iter:expr) => {
                            $iter.next().map(|v| [< SpzGaussian $name Ref >]:: $variant_ (v))
                        };
                        ($variant_:ident) => {
                            Some([< SpzGaussian $name Ref >]:: $variant_)
                        };
                    }

                    match self {
                        $(
                            #[allow(clippy::redundant_pattern)]
                            [< SpzGaussian $name Iter >]:: $variant $( (iter @ noop!($ty _)) )? => {
                                body!($variant $(, $ty, iter )?)
                            }
                        )+
                    }
                }

                fn size_hint(&self) -> (usize, Option<usize>) {
                    match self {
                        $(
                            #[allow(clippy::redundant_pattern)]
                            [< SpzGaussian $name Iter >]:: $variant $( (iter @ noop!($ty _)) )? => {
                                #[allow(unused_variables)]
                                let len = 0;
                                $(
                                    noop!($ty);
                                    let len = iter.len();
                                )?
                                (len, Some(len))
                            }
                        )+
                    }
                }
            }

            impl<'a> ExactSizeIterator for [< SpzGaussian $name Iter >]<'a> {}

            #[doc = "Representation of SPZ Gaussians "]
            #[doc = $docname]
            #[doc = "s."]
            #[derive(Debug, Clone, PartialEq)]
            pub enum [< SpzGaussians $name s>] {
                $(
                    $(#[doc = $doc])?
                    $variant $((Vec<$ty>))?,
                )+
            }

            impl [< SpzGaussians $name s>] {
                /// Get the number of elements.
                pub fn len(&self) -> usize {
                    match self {
                        $(
                            #[allow(clippy::redundant_pattern)]
                            [< SpzGaussians $name s>]:: $variant $( (vec @ noop!($ty _)) )? => {
                                #[allow(unused_variables)]
                                let len = 0;
                                $(
                                    noop!($ty);
                                    let len = vec.len();
                                )?
                                len
                            }
                        )+
                    }
                }

                /// Check if empty.
                pub fn is_empty(&self) -> bool {
                    self.len() == 0
                }

                /// Get an iterator over references.
                pub fn iter<'a>(&'a self) -> [< SpzGaussian $name Iter >]<'a> {
                    macro_rules! body {
                        ($variant_:ident, $ty_:ty, $vec:expr) => {
                            [< SpzGaussian $name Iter >]:: $variant_ ( $vec.iter() )
                        };
                        ($variant_:ident) => {
                            [< SpzGaussian $name Iter >]:: $variant_
                        };
                    }

                    match self {
                        $(
                            #[allow(clippy::redundant_pattern)]
                            [< SpzGaussians $name s>]:: $variant $( (vec @ noop!($ty _)) )? => {
                                body!($variant $(, $ty, vec )?)
                            }
                        )+
                    }
                }
            }

            impl FromIterator<[< SpzGaussian $name >]> for Result<
                [< SpzGaussians $name s>],
                $crate::error::SpzGaussiansCollectError<[< SpzGaussian $name >]>
            > {
                fn from_iter<I: IntoIterator<Item = [< SpzGaussian $name >]>>(iter: I) -> Self {
                    let mut iter = iter.into_iter();
                    let Some(first) = iter.next() else {
                        return Err($crate::error::SpzGaussiansCollectError::EmptyIterator);
                    };

                    #[allow(unused_variables)]
                    let first_value = ();
                    match first {
                        $(
                            #[allow(clippy::redundant_pattern)]
                            [< SpzGaussian $name >]:: $variant $( (first_value @ noop!($ty _)) )? => {
                                #[allow(unused_variables)]
                                let value = ();
                                #[allow(unused_variables)]
                                let vec = std::iter::once(Ok(first_value))
                                    .chain(
                                        iter.map(|v| {
                                            match v {
                                                [< SpzGaussian $name >]:: $variant $( (
                                                    value @ noop!($ty _)
                                                ) )? => Ok(value),
                                                other => Err(
                                                    $crate::error::SpzGaussiansCollectError::InvalidMixedVariant {
                                                        first_variant: [< SpzGaussian $name >]:: $variant $( (
                                                            { noop!($ty); first_value }
                                                        ) )?,
                                                        current_variant: other,
                                                    }
                                                ),
                                            }
                                        })
                                    )
                                    .collect::<Result<Vec<_>, _>>()?;
                                Ok([< SpzGaussians $name s>]:: $variant $( ({ noop!($ty); vec }) )?)
                            }
                        )+
                    }
                }
            }
        }
    }
}

gaussian_field! {
    #[docname = "position"]
    Position {
        #[doc = "(x, y, z) each as 16-bit floating point."]
        Float16([u16; 3]),
        #[doc = "(x, y, z) each as 24-bit fixed point signed integer."]
        FixedPoint24([[u8; 3]; 3]),
    }
}

gaussian_field! {
    #[docname = "rotation"]
    Rotation {
        #[doc = "(x, y, z) each as 8-bit signed integer."]
        QuatFirstThree([u8; 3]),
        #[doc = "Smallest 3 components each as 10-bit signed integer. 2 bits for index of omitted component."]
        QuatSmallestThree([u8; 4]),
    }
}

gaussian_field! {
    #[docname = "SH coefficients"]
    Sh {
        Zero,
        One([[u8; 3]; 3]),
        Two([[u8; 3]; 8]),
        Three([[u8; 3]; 15]),
    }
}

impl SpzGaussianSh {
    /// Get the SH degree.
    pub fn degree(&self) -> SpzGaussianShDegree {
        match self {
            SpzGaussianSh::Zero => unsafe { SpzGaussianShDegree::new_unchecked(0) },
            SpzGaussianSh::One(_) => unsafe { SpzGaussianShDegree::new_unchecked(1) },
            SpzGaussianSh::Two(_) => unsafe { SpzGaussianShDegree::new_unchecked(2) },
            SpzGaussianSh::Three(_) => unsafe { SpzGaussianShDegree::new_unchecked(3) },
        }
    }

    /// Get an iterator over SH coefficients.
    pub fn iter(&self) -> impl Iterator<Item = &[u8; 3]> {
        match self {
            SpzGaussianSh::Zero => [].iter(),
            SpzGaussianSh::One(sh) => sh.iter(),
            SpzGaussianSh::Two(sh) => sh.iter(),
            SpzGaussianSh::Three(sh) => sh.iter(),
        }
    }

    /// Get an iterator over mutable SH coefficients.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut [u8; 3]> {
        match self {
            SpzGaussianSh::Zero => [].iter_mut(),
            SpzGaussianSh::One(sh) => sh.iter_mut(),
            SpzGaussianSh::Two(sh) => sh.iter_mut(),
            SpzGaussianSh::Three(sh) => sh.iter_mut(),
        }
    }
}

impl SpzGaussianShRef<'_> {
    /// Get the SH degree.
    pub fn degree(&self) -> SpzGaussianShDegree {
        match self {
            SpzGaussianShRef::Zero => unsafe { SpzGaussianShDegree::new_unchecked(0) },
            SpzGaussianShRef::One(_) => unsafe { SpzGaussianShDegree::new_unchecked(1) },
            SpzGaussianShRef::Two(_) => unsafe { SpzGaussianShDegree::new_unchecked(2) },
            SpzGaussianShRef::Three(_) => unsafe { SpzGaussianShDegree::new_unchecked(3) },
        }
    }

    /// Get an iterator over SH coefficients.
    pub fn iter(&self) -> impl Iterator<Item = &[u8; 3]> + '_ {
        match self {
            SpzGaussianShRef::Zero => [].iter(),
            SpzGaussianShRef::One(sh) => sh.iter(),
            SpzGaussianShRef::Two(sh) => sh.iter(),
            SpzGaussianShRef::Three(sh) => sh.iter(),
        }
    }
}

impl SpzGaussiansShs {
    /// Get the SH degree.
    pub fn degree(&self) -> SpzGaussianShDegree {
        match self {
            SpzGaussiansShs::Zero => unsafe { SpzGaussianShDegree::new_unchecked(0) },
            SpzGaussiansShs::One(_) => unsafe { SpzGaussianShDegree::new_unchecked(1) },
            SpzGaussiansShs::Two(_) => unsafe { SpzGaussianShDegree::new_unchecked(2) },
            SpzGaussiansShs::Three(_) => unsafe { SpzGaussianShDegree::new_unchecked(3) },
        }
    }
}

/// The SPZ Gaussian spherical harmonics degrees.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SpzGaussianShDegree(u8);

impl SpzGaussianShDegree {
    /// Create a new SPZ Gaussian SH degree.
    ///
    /// Returns [`None`] if the degree is not in the range of [`SpzGaussiansHeader::SUPPORTED_SH_DEGREES`].
    pub const fn new(sh_deg: u8) -> Option<Self> {
        match sh_deg {
            0..=3 => Some(Self(sh_deg)),
            _ => None,
        }
    }

    /// Create a new SPZ Gaussian SH degree without checking.
    ///
    /// # Safety
    ///
    /// The degree must be in the range of [`SpzGaussiansHeader::SUPPORTED_SH_DEGREES`].
    pub const unsafe fn new_unchecked(sh_deg: u8) -> Self {
        Self(sh_deg)
    }

    /// Get the degree.
    pub const fn get(&self) -> u8 {
        self.0
    }

    /// Get the number of SH coefficients.
    pub const fn num_coefficients(&self) -> usize {
        match self.0 {
            0 => 0,
            1 => 3,
            2 => 8,
            3 => 15,
            _ => unreachable!(),
        }
    }
}

impl Default for SpzGaussianShDegree {
    fn default() -> Self {
        // SAFETY: 3 is in the range of [0, 3].
        unsafe { Self::new_unchecked(3) }
    }
}

/// A single SPZ Gaussian.
///
/// This is usually only used for [`SpzGaussians::from_iter`].
#[derive(Debug, Clone, PartialEq)]
pub struct SpzGaussian {
    pub position: SpzGaussianPosition,
    pub scale: [u8; 3],
    pub rotation: SpzGaussianRotation,
    pub alpha: u8,
    pub color: [u8; 3],
    pub sh: SpzGaussianSh,
}

impl SpzGaussian {
    /// Get a [`SpzGaussianRef`] reference to this Gaussian.
    pub fn as_ref(&self) -> SpzGaussianRef<'_> {
        SpzGaussianRef {
            position: match &self.position {
                SpzGaussianPosition::Float16(v) => SpzGaussianPositionRef::Float16(v),
                SpzGaussianPosition::FixedPoint24(v) => SpzGaussianPositionRef::FixedPoint24(v),
            },
            scale: &self.scale,
            rotation: match &self.rotation {
                SpzGaussianRotation::QuatFirstThree(v) => SpzGaussianRotationRef::QuatFirstThree(v),
                SpzGaussianRotation::QuatSmallestThree(v) => {
                    SpzGaussianRotationRef::QuatSmallestThree(v)
                }
            },
            alpha: &self.alpha,
            color: &self.color,
            sh: match &self.sh {
                SpzGaussianSh::Zero => SpzGaussianShRef::Zero,
                SpzGaussianSh::One(v) => SpzGaussianShRef::One(v),
                SpzGaussianSh::Two(v) => SpzGaussianShRef::Two(v),
                SpzGaussianSh::Three(v) => SpzGaussianShRef::Three(v),
            },
        }
    }
}

/// Reference to a SPZ Gaussian.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SpzGaussianRef<'a> {
    pub position: SpzGaussianPositionRef<'a>,
    pub scale: &'a [u8; 3],
    pub rotation: SpzGaussianRotationRef<'a>,
    pub alpha: &'a u8,
    pub color: &'a [u8; 3],
    pub sh: SpzGaussianShRef<'a>,
}

impl SpzGaussianRef<'_> {
    /// Convert to [`SpzGaussian`].
    pub fn to_inner_owned(&self) -> SpzGaussian {
        SpzGaussian {
            position: match self.position {
                SpzGaussianPositionRef::Float16(v) => SpzGaussianPosition::Float16(*v),
                SpzGaussianPositionRef::FixedPoint24(v) => SpzGaussianPosition::FixedPoint24(*v),
            },
            scale: *self.scale,
            rotation: match self.rotation {
                SpzGaussianRotationRef::QuatFirstThree(v) => {
                    SpzGaussianRotation::QuatFirstThree(*v)
                }
                SpzGaussianRotationRef::QuatSmallestThree(v) => {
                    SpzGaussianRotation::QuatSmallestThree(*v)
                }
            },
            alpha: *self.alpha,
            color: *self.color,
            sh: match self.sh {
                SpzGaussianShRef::Zero => SpzGaussianSh::Zero,
                SpzGaussianShRef::One(v) => SpzGaussianSh::One(*v),
                SpzGaussianShRef::Two(v) => SpzGaussianSh::Two(*v),
                SpzGaussianShRef::Three(v) => SpzGaussianSh::Three(*v),
            },
        }
    }
}

/// Header of SPZ Gaussians file.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SpzGaussiansHeaderPod {
    pub magic: u32,
    pub version: u32,
    pub num_points: u32,
    pub sh_degree: SpzGaussianShDegree,
    pub fractional_bits: u8,
    pub flags: u8,
    pub reserved: u8,
}

/// Header of SPZ Gaussians file.
///
/// This is the validated version of [`SpzGaussiansHeaderPod`]. This is simply a wrapper around
/// [`SpzGaussiansHeaderPod`] that ensures the values are valid, we could also implement
/// specialized structs for each field but it would be overkill for now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpzGaussiansHeader(SpzGaussiansHeaderPod);

impl SpzGaussiansHeader {
    /// The magic number for SPZ Gaussians files.
    pub const MAGIC: u32 = 0x5053474e; // "NGSP"

    /// The supported SPZ versions.
    pub const SUPPORTED_VERSIONS: RangeInclusive<u32> = 1..=3;

    /// The supported SH degrees.
    pub const SUPPORTED_SH_DEGREES: RangeInclusive<u8> = 0..=3;

    /// Create a [`SpzGaussiansHeader`].
    ///
    /// Returns an error if the header is invalid.
    pub fn new(
        version: u32,
        num_points: u32,
        sh_degree: SpzGaussianShDegree,
        fractional_bits: u8,
        antialiased: bool,
    ) -> Result<Self, std::io::Error> {
        Self::try_from_pod(SpzGaussiansHeaderPod {
            magic: Self::MAGIC,
            version,
            num_points,
            sh_degree,
            fractional_bits,
            flags: if antialiased { 0x1 } else { 0x0 },
            reserved: 0,
        })
    }

    /// Validate and create a validated SPZ Gaussians header.
    pub fn try_from_pod(pod: SpzGaussiansHeaderPod) -> Result<Self, std::io::Error> {
        if pod.magic != Self::MAGIC {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "Invalid SPZ magic number: {:X}, expected {:X}",
                    pod.magic,
                    Self::MAGIC
                ),
            ));
        }

        if !Self::SUPPORTED_VERSIONS.contains(&pod.version) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "Unsupported SPZ version: {}, expected one of {:?}",
                    pod.version,
                    Self::SUPPORTED_VERSIONS
                ),
            ));
        }

        Ok(Self(pod))
    }

    /// Create a default [`SpzGaussiansHeader`] from number of points and SH degree.
    pub fn default(num_points: u32) -> Result<Self, std::io::Error> {
        Self::new(
            Self::SUPPORTED_VERSIONS
                .last()
                .expect("at least one supported version"),
            num_points,
            SpzGaussianShDegree::default(),
            12,
            false,
        )
    }

    /// Get the [`SpzGaussiansHeaderPod`].
    pub fn as_pod(&self) -> &SpzGaussiansHeaderPod {
        &self.0
    }

    /// Get the version of the SPZ file.
    pub fn version(&self) -> u32 {
        self.0.version
    }

    /// Set the number of points.
    ///
    /// Setting the number of points does not invalidate the header.
    pub fn set_num_points(&mut self, num_points: u32) {
        self.0.num_points = num_points;
    }

    /// Get the number of points in the SPZ file.
    pub fn num_points(&self) -> usize {
        self.0.num_points as usize
    }

    /// Get the SH degree of the SPZ file.
    pub fn sh_degree(&self) -> SpzGaussianShDegree {
        self.0.sh_degree
    }

    /// Get the number of SH coefficients.
    pub fn sh_num_coefficients(&self) -> usize {
        self.0.sh_degree.num_coefficients()
    }

    /// Get the number of fractional bits.
    pub fn fractional_bits(&self) -> u8 {
        self.0.fractional_bits
    }

    /// Check if the antialiased flag is set.
    pub fn is_antialiased(&self) -> bool {
        (self.0.flags & 0x1) != 0
    }

    /// Check if float16 encoding is used.
    pub fn uses_float16(&self) -> bool {
        self.version() == 1
    }

    /// Check if quaternion smallest three encoding is used.
    pub fn uses_quat_smallest_three(&self) -> bool {
        self.version() >= 3
    }
}

impl SpzGaussiansPositions {
    /// Read positions from reader.
    pub fn read_from(
        reader: &mut impl Read,
        count: usize,
        uses_float16: bool,
    ) -> Result<Self, std::io::Error> {
        if uses_float16 {
            let mut positions = vec![[0u16; 3]; count];
            reader.read_exact(bytemuck::cast_slice_mut(&mut positions))?;
            Ok(SpzGaussiansPositions::Float16(positions))
        } else {
            let mut positions = vec![[[0u8; 3]; 3]; count];
            reader.read_exact(bytemuck::cast_slice_mut(&mut positions))?;
            Ok(SpzGaussiansPositions::FixedPoint24(positions))
        }
    }

    /// Write positions to writer.
    pub fn write_to(&self, writer: &mut impl Write) -> Result<(), std::io::Error> {
        match self {
            SpzGaussiansPositions::Float16(positions) => {
                writer.write_all(bytemuck::cast_slice(positions))
            }
            SpzGaussiansPositions::FixedPoint24(positions) => {
                writer.write_all(bytemuck::cast_slice(positions))
            }
        }
    }
}

impl SpzGaussiansRotations {
    /// Read rotations from reader.
    pub fn read_from(
        reader: &mut impl Read,
        count: usize,
        uses_quat_smallest_three: bool,
    ) -> Result<Self, std::io::Error> {
        if !uses_quat_smallest_three {
            let mut rots = vec![[0u8; 3]; count];
            reader.read_exact(bytemuck::cast_slice_mut(&mut rots))?;
            Ok(SpzGaussiansRotations::QuatFirstThree(rots))
        } else {
            let mut rots = vec![[0u8; 4]; count];
            reader.read_exact(bytemuck::cast_slice_mut(&mut rots))?;
            Ok(SpzGaussiansRotations::QuatSmallestThree(rots))
        }
    }

    /// Write rotations to writer.
    pub fn write_to(&self, writer: &mut impl Write) -> Result<(), std::io::Error> {
        match self {
            SpzGaussiansRotations::QuatFirstThree(rots) => {
                writer.write_all(bytemuck::cast_slice(rots))
            }
            SpzGaussiansRotations::QuatSmallestThree(rots) => {
                writer.write_all(bytemuck::cast_slice(rots))
            }
        }
    }
}

impl SpzGaussiansShs {
    /// Read SH coefficients from reader.
    pub fn read_from(
        reader: &mut impl Read,
        count: usize,
        sh_degree: SpzGaussianShDegree,
    ) -> Result<Self, std::io::Error> {
        match sh_degree.get() {
            0 => Ok(SpzGaussiansShs::Zero),
            1 => {
                let mut sh_coeffs = vec![[[0u8; 3]; 3]; count];
                reader.read_exact(bytemuck::cast_slice_mut(&mut sh_coeffs))?;
                Ok(SpzGaussiansShs::One(sh_coeffs))
            }
            2 => {
                let mut sh_coeffs = vec![[[0u8; 3]; 8]; count];
                reader.read_exact(bytemuck::cast_slice_mut(&mut sh_coeffs))?;
                Ok(SpzGaussiansShs::Two(sh_coeffs))
            }
            3 => {
                let mut sh_coeffs = vec![[[0u8; 3]; 15]; count];
                reader.read_exact(bytemuck::cast_slice_mut(&mut sh_coeffs))?;
                Ok(SpzGaussiansShs::Three(sh_coeffs))
            }
            _ => {
                // SAFETY: SpzGaussianShDegree guarantees the degree is in [0, 3].
                unreachable!()
            }
        }
    }

    /// Write SH coefficients to writer.
    pub fn write_to(&self, writer: &mut impl Write) -> Result<(), std::io::Error> {
        match self {
            SpzGaussiansShs::Zero => Ok(()),
            SpzGaussiansShs::One(sh_coeffs) => writer.write_all(bytemuck::cast_slice(sh_coeffs)),
            SpzGaussiansShs::Two(sh_coeffs) => writer.write_all(bytemuck::cast_slice(sh_coeffs)),
            SpzGaussiansShs::Three(sh_coeffs) => writer.write_all(bytemuck::cast_slice(sh_coeffs)),
        }
    }
}

/// A collection of Gaussians in SPZ format.
#[derive(Debug, Clone, PartialEq)]
pub struct SpzGaussians {
    pub header: SpzGaussiansHeader,

    pub positions: SpzGaussiansPositions,

    /// `(x, y, z)` each as 8-bit log-encoded integer.
    pub scales: Vec<[u8; 3]>,

    pub rotations: SpzGaussiansRotations,

    /// 8-bit unsigned integer.
    pub alphas: Vec<u8>,

    /// `(r, g, b)` each as 8-bit unsigned integer.
    pub colors: Vec<[u8; 3]>,

    pub shs: SpzGaussiansShs,
}

impl SpzGaussians {
    /// Get the number of Gaussians.
    pub fn len(&self) -> usize {
        self.header.num_points()
    }

    /// Check if there are no Gaussians.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Read a SPZ from a decompressed buffer.
    ///
    /// `reader` should be decompressed SPZ buffer.
    pub fn read_decompressed(reader: &mut impl Read) -> Result<Self, std::io::Error> {
        let header = Self::read_header(reader)?;
        Self::read_gaussians(reader, header)
    }

    /// Read a SPZ header.
    ///
    /// `reader` should be decompressed SPZ buffer.
    pub fn read_header(reader: &mut impl Read) -> Result<SpzGaussiansHeader, std::io::Error> {
        let mut header_bytes = [0u8; std::mem::size_of::<SpzGaussiansHeaderPod>()];
        reader.read_exact(&mut header_bytes)?;
        let header: SpzGaussiansHeaderPod = bytemuck::cast(header_bytes);
        SpzGaussiansHeader::try_from_pod(header)
    }

    /// Read the SPZ Gaussians.
    ///
    /// `reader` should be decompressed SPZ buffer positioned after the header.
    ///
    /// `header` may be parsed by calling [`SpzGaussians::read_header`].
    pub fn read_gaussians(
        reader: &mut impl Read,
        header: SpzGaussiansHeader,
    ) -> Result<Self, std::io::Error> {
        let count = header.num_points();
        let uses_float16 = header.uses_float16();
        let uses_quat_smallest_three = header.uses_quat_smallest_three();

        let positions = SpzGaussiansPositions::read_from(reader, count, uses_float16)?;

        let mut alphas = vec![0u8; count];
        reader.read_exact(bytemuck::cast_slice_mut(&mut alphas))?;

        let mut colors = vec![[0u8; 3]; count];
        reader.read_exact(bytemuck::cast_slice_mut(&mut colors))?;

        let mut scales = vec![[0u8; 3]; count];
        reader.read_exact(bytemuck::cast_slice_mut(&mut scales))?;

        let rotations = SpzGaussiansRotations::read_from(reader, count, uses_quat_smallest_three)?;

        let shs = SpzGaussiansShs::read_from(reader, count, header.sh_degree())?;

        Ok(SpzGaussians {
            header,
            positions,
            scales,
            rotations,
            alphas,
            colors,
            shs,
        })
    }

    /// Write the Gaussians to a SPZ buffer.
    ///
    /// `writer` will receive the decompressed SPZ buffer.
    pub fn write_decompressed(&self, writer: &mut impl Write) -> Result<(), std::io::Error> {
        writer.write_all(bytemuck::cast_slice(std::slice::from_ref(
            self.header.as_pod(),
        )))?;

        self.positions.write_to(writer)?;

        writer.write_all(bytemuck::cast_slice(&self.alphas))?;

        writer.write_all(bytemuck::cast_slice(&self.colors))?;

        writer.write_all(bytemuck::cast_slice(&self.scales))?;

        self.rotations.write_to(writer)?;

        self.shs.write_to(writer)?;

        Ok(())
    }

    /// Convert from a slice of [`Gaussian`]s.
    pub fn from_gaussians(gaussians: impl IntoIterator<Item = impl AsRef<Gaussian>>) -> Self {
        Self::from_gaussians_with_options(
            gaussians,
            &SpzGaussiansFromGaussianSliceOptions::default(),
        )
        .expect("valid default options")
    }

    /// Convert from a slice of [`Gaussian`]s with options.
    pub fn from_gaussians_with_options(
        gaussians: impl IntoIterator<Item = impl AsRef<Gaussian>>,
        options: &SpzGaussiansFromGaussianSliceOptions,
    ) -> Result<Self, std::io::Error> {
        let mut header = SpzGaussiansHeader::new(
            options.version,
            0,
            options.sh_degree,
            options.fractional_bits,
            options.antialiased,
        )?;

        let gaussians = gaussians
            .into_iter()
            .map(|g| {
                g.as_ref().to_spz(
                    &header,
                    &GaussianToSpzOptions {
                        sh_quantize_bits: options.sh_quantize_bits,
                    },
                )
            })
            .collect::<Vec<_>>();

        header.set_num_points(gaussians.len() as u32);

        Ok(Self::from_iter(header, gaussians)
            .expect("gaussians from valid Gaussians with valid header are valid"))
    }

    /// Convert from an [`IntoIterator`] of [`SpzGaussian`]s.
    pub fn from_iter(
        header: SpzGaussiansHeader,
        iter: impl IntoIterator<Item = SpzGaussian>,
    ) -> Result<Self, SpzGaussiansFromIterError> {
        let (positions, scales, rotations, alphas, colors, shs) = iter
            .into_iter()
            .map(|spz| {
                (
                    spz.position,
                    spz.scale,
                    spz.rotation,
                    spz.alpha,
                    spz.color,
                    spz.sh,
                )
            })
            .multiunzip::<(Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>)>();

        let positions = positions
            .into_iter()
            .collect::<Result<_, _>>()
            .map_err(SpzGaussiansFromIterError::InvalidMixedPositionVariant)?;

        let rotations = rotations
            .into_iter()
            .collect::<Result<_, _>>()
            .map_err(SpzGaussiansFromIterError::InvalidMixedRotationVariant)?;

        let shs = shs
            .into_iter()
            .collect::<Result<_, _>>()
            .map_err(SpzGaussiansFromIterError::InvalidMixedShVariant)?;

        if positions.len() != header.num_points() {
            return Err(SpzGaussiansFromIterError::CountMismatch {
                actual_count: positions.len(),
                header_count: header.num_points(),
            });
        }

        if matches!(positions, SpzGaussiansPositions::Float16(_)) != header.uses_float16() {
            return Err(SpzGaussiansFromIterError::PositionFloat16Mismatch {
                is_float16: matches!(positions, SpzGaussiansPositions::Float16(_)),
                header_uses_float16: header.uses_float16(),
            });
        }

        if matches!(rotations, SpzGaussiansRotations::QuatSmallestThree(_))
            != header.uses_quat_smallest_three()
        {
            return Err(
                SpzGaussiansFromIterError::RotationQuatSmallestThreeMismatch {
                    is_quat_smallest_three: matches!(
                        rotations,
                        SpzGaussiansRotations::QuatSmallestThree(_)
                    ),
                    header_uses_quat_smallest_three: header.uses_quat_smallest_three(),
                },
            );
        }

        if shs.degree() != header.sh_degree() {
            return Err(SpzGaussiansFromIterError::ShDegreeMismatch {
                sh_degree: shs.degree(),
                header_sh_degree: header.sh_degree(),
            });
        }

        Ok(SpzGaussians {
            header,
            positions,
            scales,
            rotations,
            alphas,
            colors,
            shs,
        })
    }

    /// Get an iterator over Gaussian references.
    pub fn iter<'a>(&'a self) -> impl ExactSizeIterator<Item = SpzGaussianRef<'a>> + 'a {
        itertools::izip!(
            self.positions.iter(),
            self.scales.iter(),
            self.rotations.iter(),
            self.alphas.iter(),
            self.colors.iter(),
            self.shs.iter()
        )
        .map(
            |(position, scale, rotation, alpha, color, sh)| SpzGaussianRef {
                position,
                scale,
                rotation,
                alpha,
                color,
                sh,
            },
        )
    }
}

impl IterGaussian for SpzGaussians {
    fn iter_gaussian(&self) -> impl ExactSizeIterator<Item = Gaussian> + '_ {
        self.iter().map(|spz| Gaussian::from_spz(spz, &self.header))
    }
}

impl ReadIterGaussian for SpzGaussians {
    fn read_from(reader: &mut impl std::io::BufRead) -> std::io::Result<Self> {
        let mut decoder = GzDecoder::new(reader);
        Self::read_decompressed(&mut decoder)
    }
}

impl WriteIterGaussian for SpzGaussians {
    fn write_to(&self, writer: &mut impl std::io::Write) -> std::io::Result<()> {
        let mut encoder = GzEncoder::new(writer, flate2::Compression::default());
        self.write_decompressed(&mut encoder)?;
        encoder.finish()?;
        Ok(())
    }
}

impl<G: AsRef<Gaussian>> FromIterator<G> for SpzGaussians {
    fn from_iter<T: IntoIterator<Item = G>>(iter: T) -> Self {
        Self::from_gaussians(iter)
    }
}

/// Options for [`SpzGaussians::from_gaussians_with_options`].
///
/// The fields are not validated.
#[derive(Debug, Clone)]
pub struct SpzGaussiansFromGaussianSliceOptions {
    /// Version to use.
    pub version: u32,

    /// SH degree to use.
    pub sh_degree: SpzGaussianShDegree,

    /// Number of fractional bits to use for position fixed point encoding.
    pub fractional_bits: u8,

    /// Whether to use antialiased encoding.
    pub antialiased: bool,

    /// The quantization bits for each SH degree.
    pub sh_quantize_bits: [u32; 3],
}

impl Default for SpzGaussiansFromGaussianSliceOptions {
    fn default() -> Self {
        let default_header = SpzGaussiansHeader::default(0).expect("default header");
        let default_gaussian_to_spz_options = GaussianToSpzOptions::default();
        Self {
            version: default_header.version(),
            sh_degree: default_header.sh_degree(),
            fractional_bits: default_header.fractional_bits(),
            antialiased: default_header.is_antialiased(),
            sh_quantize_bits: default_gaussian_to_spz_options.sh_quantize_bits,
        }
    }
}