Skip to main content

geolith_tiles_builder/splat/
spz.rs

1//! SPZ compressed Gaussian splat encoder.
2//!
3//! Emits the packed stream consumed by `KHR_gaussian_splatting_compression_spz_2`.
4//! Despite the extension's `_2` suffix, the payload is an SPZ **stream version 3**
5//! packet: header, then per-attribute planes, gzip-compressed as a whole. Version 3
6//! is what stores rotations with the smallest-three quaternion encoding, matching
7//! the reference `3DGS-PLY-3DTiles-Converter` and the renderer plugin.
8//!
9//! Layout (little-endian, planes are contiguous and point-major):
10//!
11//! | Field | Bytes | Notes |
12//! |---|---|---|
13//! | magic | 4 | `0x5053474e` (`NGSP`) |
14//! | version | 4 | 3 |
15//! | `num_points` | 4 | |
16//! | `sh_degree` | 1 | 0–3 |
17//! | `fractional_bits` | 1 | 12 |
18//! | flags | 1 | bit 0 = antialiased |
19//! | reserved | 1 | 0 |
20//! | positions | 9·N | 24-bit fixed point, 12 fractional bits |
21//! | opacity | 1·N | sigmoid, scaled to 0–255 |
22//! | colour | 3·N | `sh0 · 0.15 · 255 + 127.5` |
23//! | scale | 3·N | `(log_scale + 10) · 16` |
24//! | rotation | 4·N | smallest-three quaternion |
25//! | rest SH | 3·(C−1)·N | `c · 128 + 128`, bucket-quantised |
26
27use std::io::Write as _;
28
29use flate2::Compression as GzLevel;
30use flate2::write::GzEncoder;
31use geolith::error::{GeolithError, Result};
32
33use crate::splat::ply::SplatCloud;
34
35/// SPZ magic number, `NGSP` in little-endian byte order.
36const SPZ_MAGIC: u32 = 0x5053_474e;
37
38/// SPZ stream version carried inside `KHR_gaussian_splatting_compression_spz_2`.
39const SPZ_STREAM_VERSION: u32 = 3;
40
41/// Fixed-point fractional bits used for positions.
42const FRACTIONAL_BITS: u8 = 12;
43
44/// Largest magnitude representable by a signed 24-bit fixed-point position.
45const FIXED24_LIMIT: i32 = (1 << 23) - 1;
46
47/// Header length in bytes.
48const HEADER_BYTES: usize = 16;
49
50/// Scale applied to spherical harmonic DC terms when packing colour.
51const COLOR_SCALE: f32 = 0.15;
52
53/// Lower bound of the quantised log-scale range.
54const SCALE_LOG_MIN: f32 = -10.0;
55
56/// Quantisation step applied to log-scales.
57const SCALE_LOG_QUANTIZATION: f32 = 16.0;
58
59/// Reciprocal square root of two, the smallest-three quaternion component bound.
60const SQRT_HALF: f32 = std::f32::consts::FRAC_1_SQRT_2;
61
62/// Magnitude scale for smallest-three quaternion components (2^9 − 1).
63const MAG_SCALE: f32 = 511.0;
64
65/// Logistic sigmoid.
66#[must_use]
67fn sigmoid(x: f32) -> f32 {
68    1.0 / (1.0 + (-x).exp())
69}
70
71/// Quantise an opacity logit to a byte.
72#[must_use]
73fn quantize_opacity(logit: f32) -> u8 {
74    let alpha = sigmoid(logit).clamp(0.0, 1.0);
75    f32::round(alpha * 255.0).clamp(0.0, 255.0) as u8
76}
77
78/// Quantise a spherical harmonic DC term to a colour byte.
79#[must_use]
80fn quantize_color(coefficient: f32) -> u8 {
81    let scaled = coefficient * COLOR_SCALE * 255.0 + 0.5 * 255.0;
82    f32::round(scaled).clamp(0.0, 255.0) as u8
83}
84
85/// Quantise a natural-log scale to a byte.
86#[must_use]
87fn quantize_scale(log_scale: f32) -> u8 {
88    let scaled = (log_scale - SCALE_LOG_MIN) * SCALE_LOG_QUANTIZATION;
89    f32::round(scaled).clamp(0.0, 255.0) as u8
90}
91
92/// Quantise a higher-order spherical harmonic coefficient to a byte.
93#[must_use]
94fn quantize_rest_sh(coefficient: f32) -> u8 {
95    f32::round(coefficient * 128.0 + 128.0).clamp(0.0, 255.0) as u8
96}
97
98/// Encode a position component as 24-bit fixed point.
99///
100/// # Errors
101///
102/// Returns [`GeolithError::SplatTiles`] when the tile-local coordinate exceeds
103/// the representable range, which signals that the caller failed to rebase
104/// positions before packing.
105fn quantize_position(local: f32) -> Result<[u8; 3]> {
106    let fixed = f32::round(local * f32::from(1_u16 << FRACTIONAL_BITS)) as i64;
107    if fixed.unsigned_abs() > FIXED24_LIMIT as u64 {
108        let limit = f64::from(FIXED24_LIMIT) / f64::from(1_u32 << FRACTIONAL_BITS);
109        return Err(GeolithError::SplatTiles(format!(
110            "tile-local coordinate {local} exceeds the SPZ 24-bit fixed-point range +/-{limit:.3}"
111        )));
112    }
113    let fixed = fixed as i32;
114    Ok([
115        (fixed & 0xFF) as u8,
116        ((fixed >> 8) & 0xFF) as u8,
117        ((fixed >> 16) & 0xFF) as u8,
118    ])
119}
120
121/// Pack a quaternion using the smallest-three encoding.
122///
123/// The largest component is dropped and reconstructed by the decoder from the
124/// unit-length constraint; its index and the sign of each retained component
125/// are packed alongside 9-bit magnitudes.
126#[must_use]
127fn pack_quaternion_smallest_three(quaternion: [f32; 4]) -> [u8; 4] {
128    let [mut x, mut y, mut z, mut w] = quaternion;
129    let len2 = x * x + y * y + z * z + w * w;
130    if len2 < 1e-40 {
131        (x, y, z, w) = (0.0, 0.0, 0.0, 1.0);
132    } else {
133        let inv = 1.0 / len2.sqrt();
134        x *= inv;
135        y *= inv;
136        z *= inv;
137        w *= inv;
138    }
139
140    let components = [x, y, z, w];
141    let mut largest = 0_usize;
142    for index in 1..4 {
143        if components[index].abs() > components[largest].abs() {
144            largest = index;
145        }
146    }
147    let negate = components[largest] < 0.0;
148
149    let mut packed = largest as u32;
150    for (index, value) in components.iter().enumerate() {
151        if index == largest {
152            continue;
153        }
154        let neg_bit = u32::from((*value < 0.0) != negate);
155        let magnitude = (MAG_SCALE * (value.abs() / SQRT_HALF) + 0.5).floor();
156        let magnitude = (magnitude.clamp(0.0, MAG_SCALE)) as u32;
157        packed = (packed << 10) | (neg_bit << 9) | magnitude;
158    }
159
160    packed.to_le_bytes()
161}
162
163/// Encode a splat cloud as a gzip-compressed SPZ packet.
164///
165/// Positions must already be tile-local; `antialiased` sets the header flag
166/// that tells the renderer the splats were trained with antialiasing.
167///
168/// # Errors
169///
170/// Returns [`GeolithError::SplatTiles`] when the cloud has inconsistent
171/// attribute lengths, an unsupported spherical harmonic degree, or a position
172/// outside the fixed-point range.
173pub fn encode_spz(cloud: &SplatCloud, antialiased: bool) -> Result<Vec<u8>> {
174    let n = cloud.len();
175    if cloud.colors.len() != n
176        || cloud.opacities.len() != n
177        || cloud.scales.len() != n
178        || cloud.rotations.len() != n
179    {
180        return Err(GeolithError::SplatTiles(format!(
181            "inconsistent splat attribute lengths: positions={n}, colors={}, \
182             opacities={}, scales={}, rotations={}",
183            cloud.colors.len(),
184            cloud.opacities.len(),
185            cloud.scales.len(),
186            cloud.rotations.len()
187        )));
188    }
189    if cloud.sh_degree > 3 {
190        return Err(GeolithError::SplatTiles(format!(
191            "SPZ supports spherical harmonic degree up to 3, got {}",
192            cloud.sh_degree
193        )));
194    }
195
196    let rest_per_channel = cloud.sh_rest_per_channel();
197    let rest_stride = rest_per_channel * 3;
198    if cloud.sh.len() != n * rest_stride {
199        return Err(GeolithError::SplatTiles(format!(
200            "spherical harmonic buffer has {} values, expected {}",
201            cloud.sh.len(),
202            n * rest_stride
203        )));
204    }
205
206    let mut packet = Vec::with_capacity(HEADER_BYTES + n * (9 + 1 + 3 + 3 + 4 + rest_stride));
207
208    packet.extend_from_slice(&SPZ_MAGIC.to_le_bytes());
209    packet.extend_from_slice(&SPZ_STREAM_VERSION.to_le_bytes());
210    packet.extend_from_slice(&(n as u32).to_le_bytes());
211    packet.push(cloud.sh_degree);
212    packet.push(FRACTIONAL_BITS);
213    packet.push(u8::from(antialiased));
214    packet.push(0);
215
216    for position in &cloud.positions {
217        for component in position {
218            packet.extend_from_slice(&quantize_position(*component)?);
219        }
220    }
221
222    for opacity in &cloud.opacities {
223        packet.push(quantize_opacity(*opacity));
224    }
225
226    for color in &cloud.colors {
227        for channel in color {
228            packet.push(quantize_color(*channel));
229        }
230    }
231
232    for scale in &cloud.scales {
233        for axis in scale {
234            packet.push(quantize_scale(*axis));
235        }
236    }
237
238    for rotation in &cloud.rotations {
239        packet.extend_from_slice(&pack_quaternion_smallest_three(*rotation));
240    }
241
242    for coefficient in &cloud.sh {
243        packet.push(quantize_rest_sh(*coefficient));
244    }
245
246    let mut encoder = GzEncoder::new(Vec::with_capacity(packet.len() / 2), GzLevel::new(6));
247    encoder.write_all(&packet)?;
248    Ok(encoder.finish()?)
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use std::io::Read as _;
255
256    fn unit_cloud(n: usize) -> SplatCloud {
257        SplatCloud {
258            positions: (0..n).map(|i| [i as f32 * 0.5, 1.0, -1.0]).collect(),
259            colors: vec![[0.5, -0.25, 1.0]; n],
260            opacities: vec![2.0; n],
261            scales: vec![[-3.0, -3.5, -4.0]; n],
262            rotations: vec![[0.0, 0.0, 0.0, 1.0]; n],
263            sh: Vec::new(),
264            sh_degree: 0,
265            vertical_axis: None,
266        }
267    }
268
269    fn gunzip(bytes: &[u8]) -> Vec<u8> {
270        let mut out = Vec::new();
271        flate2::read::GzDecoder::new(bytes)
272            .read_to_end(&mut out)
273            .expect("valid gzip stream");
274        out
275    }
276
277    #[test]
278    fn header_matches_the_spz_contract() {
279        let packet = gunzip(&encode_spz(&unit_cloud(3), false).expect("encodes"));
280
281        assert_eq!(
282            u32::from_le_bytes(packet[0..4].try_into().expect("magic")),
283            SPZ_MAGIC,
284            "NGSP magic identifies the packet"
285        );
286        assert_eq!(
287            u32::from_le_bytes(packet[4..8].try_into().expect("version")),
288            3,
289            "spz_2 carries an SPZ stream version 3 packet"
290        );
291        assert_eq!(
292            u32::from_le_bytes(packet[8..12].try_into().expect("count")),
293            3
294        );
295        assert_eq!(packet[12], 0, "sh degree");
296        assert_eq!(packet[13], FRACTIONAL_BITS);
297        assert_eq!(packet[14], 0, "antialiased flag clear");
298        assert_eq!(packet[15], 0, "reserved byte");
299    }
300
301    #[test]
302    fn antialiased_flag_is_recorded() {
303        let packet = gunzip(&encode_spz(&unit_cloud(1), true).expect("encodes"));
304        assert_eq!(packet[14], 1);
305    }
306
307    #[test]
308    fn packet_length_grows_with_sh_degree() {
309        let plain = gunzip(&encode_spz(&unit_cloud(5), false).expect("encodes"));
310        assert_eq!(
311            plain.len(),
312            // The SPZ header is 16 bytes.
313            16 + 5 * (9 + 1 + 3 + 3 + 4),
314            "degree 0"
315        );
316        let mut cloud = unit_cloud(2);
317        cloud.sh_degree = 1;
318        cloud.sh = vec![0.25; 2 * 9];
319        let packet = gunzip(&encode_spz(&cloud, false).expect("encodes"));
320        let expected = 16 + 2 * (9 + 1 + 3 + 3 + 4 + 9);
321        assert_eq!(packet.len(), expected);
322        assert_eq!(packet[12], 1, "sh degree recorded in the header");
323    }
324
325    #[test]
326    fn positions_are_24bit_fixed_point() {
327        let mut cloud = unit_cloud(1);
328        cloud.positions[0] = [1.0, 0.0, -1.0];
329        let packet = gunzip(&encode_spz(&cloud, false).expect("encodes"));
330
331        let x = i32::from_le_bytes([packet[16], packet[17], packet[18], 0]);
332        assert_eq!(x, 1 << FRACTIONAL_BITS, "1.0 m maps to 4096 fixed units");
333
334        let y = i32::from_le_bytes([packet[19], packet[20], packet[21], 0]);
335        assert_eq!(y, 0);
336
337        let z_raw = i32::from_le_bytes([packet[22], packet[23], packet[24], 0]);
338        let z = (z_raw << 8) >> 8;
339        assert_eq!(
340            z,
341            -(1 << FRACTIONAL_BITS),
342            "negatives sign-extend correctly"
343        );
344    }
345
346    #[test]
347    fn positions_beyond_fixed_point_range_are_rejected() {
348        let mut cloud = unit_cloud(1);
349        cloud.positions[0] = [5000.0, 0.0, 0.0];
350        let err = encode_spz(&cloud, false).expect_err("out of range");
351        assert!(matches!(err, GeolithError::SplatTiles(_)), "{err}");
352    }
353
354    #[test]
355    fn opacity_passes_through_the_sigmoid() {
356        assert_eq!(quantize_opacity(0.0), 128, "logit 0 is alpha 0.5");
357        assert_eq!(quantize_opacity(-40.0), 0);
358        assert_eq!(quantize_opacity(40.0), 255);
359    }
360
361    #[test]
362    fn colour_quantisation_matches_the_reference_formula() {
363        assert_eq!(quantize_color(0.0), 128, "zero DC is mid grey");
364        assert_eq!(quantize_color(-100.0), 0, "clamps rather than wrapping");
365        assert_eq!(quantize_color(100.0), 255);
366
367        // The SPZ reference scales DC by 0.15: 1.0 * 0.15 * 255 + 127.5 = 165.75.
368        assert_eq!(quantize_color(1.0), 166);
369    }
370
371    #[test]
372    fn scale_quantisation_matches_the_reference_formula() {
373        assert_eq!(quantize_scale(SCALE_LOG_MIN), 0);
374        assert_eq!(quantize_scale(-9.0), 16, "one log unit is 16 steps");
375        assert_eq!(quantize_scale(100.0), 255, "clamps at the byte ceiling");
376    }
377
378    #[test]
379    fn rest_sh_quantisation_centres_on_128() {
380        assert_eq!(quantize_rest_sh(0.0), 128);
381        assert_eq!(quantize_rest_sh(1.0), 255);
382        assert_eq!(quantize_rest_sh(-1.0), 0);
383    }
384
385    #[test]
386    fn identity_quaternion_packs_with_w_as_largest() {
387        let packed = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
388        let value = u32::from_le_bytes(packed);
389        let largest = value >> 30;
390        assert_eq!(largest, 3, "w is the dropped component");
391    }
392
393    #[test]
394    fn quaternion_packing_is_sign_invariant() {
395        let positive = pack_quaternion_smallest_three([0.1, 0.2, 0.3, 0.9]);
396        let negated = pack_quaternion_smallest_three([-0.1, -0.2, -0.3, -0.9]);
397        assert_eq!(
398            positive, negated,
399            "q and -q are the same rotation and must pack identically"
400        );
401    }
402
403    #[test]
404    fn quaternion_packing_normalises_input() {
405        let unit = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
406        let scaled = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 5.0]);
407        assert_eq!(unit, scaled, "magnitude is normalised away");
408    }
409
410    #[test]
411    fn degenerate_quaternion_falls_back_to_identity() {
412        let degenerate = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 0.0]);
413        let identity = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
414        assert_eq!(degenerate, identity);
415    }
416
417    #[test]
418    fn inconsistent_attribute_lengths_are_rejected() {
419        let mut cloud = unit_cloud(3);
420        cloud.opacities.pop();
421        let err = encode_spz(&cloud, false).expect_err("length mismatch");
422        assert!(format!("{err}").contains("inconsistent"), "{err}");
423    }
424
425    #[test]
426    fn mismatched_sh_buffer_is_rejected() {
427        let mut cloud = unit_cloud(2);
428        cloud.sh_degree = 1;
429        cloud.sh = vec![0.0; 5];
430        let err = encode_spz(&cloud, false).expect_err("sh length mismatch");
431        assert!(format!("{err}").contains("spherical harmonic"), "{err}");
432    }
433
434    #[test]
435    fn unsupported_sh_degree_is_rejected() {
436        let mut cloud = unit_cloud(1);
437        cloud.sh_degree = 4;
438        assert!(encode_spz(&cloud, false).is_err());
439    }
440
441    #[test]
442    fn empty_cloud_encodes_to_a_header_only_packet() {
443        let packet = gunzip(&encode_spz(&SplatCloud::default(), false).expect("encodes"));
444        assert_eq!(packet.len(), HEADER_BYTES);
445        assert_eq!(
446            u32::from_le_bytes(packet[8..12].try_into().expect("count")),
447            0
448        );
449    }
450
451    #[test]
452    fn output_is_gzip_framed() {
453        let bytes = encode_spz(&unit_cloud(2), false).expect("encodes");
454        assert_eq!(
455            &bytes[0..2],
456            &[0x1F, 0x8B],
457            "SPZ packets ship gzip-compressed"
458        );
459    }
460}