geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
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
//! SPZ compressed Gaussian splat encoder.
//!
//! Emits the packed stream consumed by `KHR_gaussian_splatting_compression_spz_2`.
//! Despite the extension's `_2` suffix, the payload is an SPZ **stream version 3**
//! packet: header, then per-attribute planes, gzip-compressed as a whole. Version 3
//! is what stores rotations with the smallest-three quaternion encoding, matching
//! the reference `3DGS-PLY-3DTiles-Converter` and the renderer plugin.
//!
//! Layout (little-endian, planes are contiguous and point-major):
//!
//! | Field | Bytes | Notes |
//! |---|---|---|
//! | magic | 4 | `0x5053474e` (`NGSP`) |
//! | version | 4 | 3 |
//! | `num_points` | 4 | |
//! | `sh_degree` | 1 | 0–3 |
//! | `fractional_bits` | 1 | 12 |
//! | flags | 1 | bit 0 = antialiased |
//! | reserved | 1 | 0 |
//! | positions | 9·N | 24-bit fixed point, 12 fractional bits |
//! | opacity | 1·N | sigmoid, scaled to 0–255 |
//! | colour | 3·N | `sh0 · 0.15 · 255 + 127.5` |
//! | scale | 3·N | `(log_scale + 10) · 16` |
//! | rotation | 4·N | smallest-three quaternion |
//! | rest SH | 3·(C−1)·N | `c · 128 + 128`, bucket-quantised |

use std::io::Write as _;

use flate2::Compression as GzLevel;
use flate2::write::GzEncoder;
use geolith::error::{GeolithError, Result};

use crate::splat::ply::SplatCloud;

/// SPZ magic number, `NGSP` in little-endian byte order.
const SPZ_MAGIC: u32 = 0x5053_474e;

/// SPZ stream version carried inside `KHR_gaussian_splatting_compression_spz_2`.
const SPZ_STREAM_VERSION: u32 = 3;

/// Fixed-point fractional bits used for positions.
const FRACTIONAL_BITS: u8 = 12;

/// Largest magnitude representable by a signed 24-bit fixed-point position.
const FIXED24_LIMIT: i32 = (1 << 23) - 1;

/// Header length in bytes.
const HEADER_BYTES: usize = 16;

/// Scale applied to spherical harmonic DC terms when packing colour.
const COLOR_SCALE: f32 = 0.15;

/// Lower bound of the quantised log-scale range.
const SCALE_LOG_MIN: f32 = -10.0;

/// Quantisation step applied to log-scales.
const SCALE_LOG_QUANTIZATION: f32 = 16.0;

/// Reciprocal square root of two, the smallest-three quaternion component bound.
const SQRT_HALF: f32 = std::f32::consts::FRAC_1_SQRT_2;

/// Magnitude scale for smallest-three quaternion components (2^9 − 1).
const MAG_SCALE: f32 = 511.0;

/// Logistic sigmoid.
#[must_use]
fn sigmoid(x: f32) -> f32 {
    1.0 / (1.0 + (-x).exp())
}

/// Quantise an opacity logit to a byte.
#[must_use]
fn quantize_opacity(logit: f32) -> u8 {
    let alpha = sigmoid(logit).clamp(0.0, 1.0);
    f32::round(alpha * 255.0).clamp(0.0, 255.0) as u8
}

/// Quantise a spherical harmonic DC term to a colour byte.
#[must_use]
fn quantize_color(coefficient: f32) -> u8 {
    let scaled = coefficient * COLOR_SCALE * 255.0 + 0.5 * 255.0;
    f32::round(scaled).clamp(0.0, 255.0) as u8
}

/// Quantise a natural-log scale to a byte.
#[must_use]
fn quantize_scale(log_scale: f32) -> u8 {
    let scaled = (log_scale - SCALE_LOG_MIN) * SCALE_LOG_QUANTIZATION;
    f32::round(scaled).clamp(0.0, 255.0) as u8
}

/// Quantise a higher-order spherical harmonic coefficient to a byte.
#[must_use]
fn quantize_rest_sh(coefficient: f32) -> u8 {
    f32::round(coefficient * 128.0 + 128.0).clamp(0.0, 255.0) as u8
}

/// Encode a position component as 24-bit fixed point.
///
/// # Errors
///
/// Returns [`GeolithError::SplatTiles`] when the tile-local coordinate exceeds
/// the representable range, which signals that the caller failed to rebase
/// positions before packing.
fn quantize_position(local: f32) -> Result<[u8; 3]> {
    let fixed = f32::round(local * f32::from(1_u16 << FRACTIONAL_BITS)) as i64;
    if fixed.unsigned_abs() > FIXED24_LIMIT as u64 {
        let limit = f64::from(FIXED24_LIMIT) / f64::from(1_u32 << FRACTIONAL_BITS);
        return Err(GeolithError::SplatTiles(format!(
            "tile-local coordinate {local} exceeds the SPZ 24-bit fixed-point range +/-{limit:.3}"
        )));
    }
    let fixed = fixed as i32;
    Ok([
        (fixed & 0xFF) as u8,
        ((fixed >> 8) & 0xFF) as u8,
        ((fixed >> 16) & 0xFF) as u8,
    ])
}

/// Pack a quaternion using the smallest-three encoding.
///
/// The largest component is dropped and reconstructed by the decoder from the
/// unit-length constraint; its index and the sign of each retained component
/// are packed alongside 9-bit magnitudes.
#[must_use]
fn pack_quaternion_smallest_three(quaternion: [f32; 4]) -> [u8; 4] {
    let [mut x, mut y, mut z, mut w] = quaternion;
    let len2 = x * x + y * y + z * z + w * w;
    if len2 < 1e-40 {
        (x, y, z, w) = (0.0, 0.0, 0.0, 1.0);
    } else {
        let inv = 1.0 / len2.sqrt();
        x *= inv;
        y *= inv;
        z *= inv;
        w *= inv;
    }

    let components = [x, y, z, w];
    let mut largest = 0_usize;
    for index in 1..4 {
        if components[index].abs() > components[largest].abs() {
            largest = index;
        }
    }
    let negate = components[largest] < 0.0;

    let mut packed = largest as u32;
    for (index, value) in components.iter().enumerate() {
        if index == largest {
            continue;
        }
        let neg_bit = u32::from((*value < 0.0) != negate);
        let magnitude = (MAG_SCALE * (value.abs() / SQRT_HALF) + 0.5).floor();
        let magnitude = (magnitude.clamp(0.0, MAG_SCALE)) as u32;
        packed = (packed << 10) | (neg_bit << 9) | magnitude;
    }

    packed.to_le_bytes()
}

/// Encode a splat cloud as a gzip-compressed SPZ packet.
///
/// Positions must already be tile-local; `antialiased` sets the header flag
/// that tells the renderer the splats were trained with antialiasing.
///
/// # Errors
///
/// Returns [`GeolithError::SplatTiles`] when the cloud has inconsistent
/// attribute lengths, an unsupported spherical harmonic degree, or a position
/// outside the fixed-point range.
pub fn encode_spz(cloud: &SplatCloud, antialiased: bool) -> Result<Vec<u8>> {
    let n = cloud.len();
    if cloud.colors.len() != n
        || cloud.opacities.len() != n
        || cloud.scales.len() != n
        || cloud.rotations.len() != n
    {
        return Err(GeolithError::SplatTiles(format!(
            "inconsistent splat attribute lengths: positions={n}, colors={}, \
             opacities={}, scales={}, rotations={}",
            cloud.colors.len(),
            cloud.opacities.len(),
            cloud.scales.len(),
            cloud.rotations.len()
        )));
    }
    if cloud.sh_degree > 3 {
        return Err(GeolithError::SplatTiles(format!(
            "SPZ supports spherical harmonic degree up to 3, got {}",
            cloud.sh_degree
        )));
    }

    let rest_per_channel = cloud.sh_rest_per_channel();
    let rest_stride = rest_per_channel * 3;
    if cloud.sh.len() != n * rest_stride {
        return Err(GeolithError::SplatTiles(format!(
            "spherical harmonic buffer has {} values, expected {}",
            cloud.sh.len(),
            n * rest_stride
        )));
    }

    let mut packet = Vec::with_capacity(HEADER_BYTES + n * (9 + 1 + 3 + 3 + 4 + rest_stride));

    packet.extend_from_slice(&SPZ_MAGIC.to_le_bytes());
    packet.extend_from_slice(&SPZ_STREAM_VERSION.to_le_bytes());
    packet.extend_from_slice(&(n as u32).to_le_bytes());
    packet.push(cloud.sh_degree);
    packet.push(FRACTIONAL_BITS);
    packet.push(u8::from(antialiased));
    packet.push(0);

    for position in &cloud.positions {
        for component in position {
            packet.extend_from_slice(&quantize_position(*component)?);
        }
    }

    for opacity in &cloud.opacities {
        packet.push(quantize_opacity(*opacity));
    }

    for color in &cloud.colors {
        for channel in color {
            packet.push(quantize_color(*channel));
        }
    }

    for scale in &cloud.scales {
        for axis in scale {
            packet.push(quantize_scale(*axis));
        }
    }

    for rotation in &cloud.rotations {
        packet.extend_from_slice(&pack_quaternion_smallest_three(*rotation));
    }

    for coefficient in &cloud.sh {
        packet.push(quantize_rest_sh(*coefficient));
    }

    let mut encoder = GzEncoder::new(Vec::with_capacity(packet.len() / 2), GzLevel::new(6));
    encoder.write_all(&packet)?;
    Ok(encoder.finish()?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Read as _;

    fn unit_cloud(n: usize) -> SplatCloud {
        SplatCloud {
            positions: (0..n).map(|i| [i as f32 * 0.5, 1.0, -1.0]).collect(),
            colors: vec![[0.5, -0.25, 1.0]; n],
            opacities: vec![2.0; n],
            scales: vec![[-3.0, -3.5, -4.0]; n],
            rotations: vec![[0.0, 0.0, 0.0, 1.0]; n],
            sh: Vec::new(),
            sh_degree: 0,
            vertical_axis: None,
        }
    }

    fn gunzip(bytes: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        flate2::read::GzDecoder::new(bytes)
            .read_to_end(&mut out)
            .expect("valid gzip stream");
        out
    }

    #[test]
    fn header_matches_the_spz_contract() {
        let packet = gunzip(&encode_spz(&unit_cloud(3), false).expect("encodes"));

        assert_eq!(
            u32::from_le_bytes(packet[0..4].try_into().expect("magic")),
            SPZ_MAGIC,
            "NGSP magic identifies the packet"
        );
        assert_eq!(
            u32::from_le_bytes(packet[4..8].try_into().expect("version")),
            3,
            "spz_2 carries an SPZ stream version 3 packet"
        );
        assert_eq!(
            u32::from_le_bytes(packet[8..12].try_into().expect("count")),
            3
        );
        assert_eq!(packet[12], 0, "sh degree");
        assert_eq!(packet[13], FRACTIONAL_BITS);
        assert_eq!(packet[14], 0, "antialiased flag clear");
        assert_eq!(packet[15], 0, "reserved byte");
    }

    #[test]
    fn antialiased_flag_is_recorded() {
        let packet = gunzip(&encode_spz(&unit_cloud(1), true).expect("encodes"));
        assert_eq!(packet[14], 1);
    }

    #[test]
    fn packet_length_grows_with_sh_degree() {
        let plain = gunzip(&encode_spz(&unit_cloud(5), false).expect("encodes"));
        assert_eq!(
            plain.len(),
            // The SPZ header is 16 bytes.
            16 + 5 * (9 + 1 + 3 + 3 + 4),
            "degree 0"
        );
        let mut cloud = unit_cloud(2);
        cloud.sh_degree = 1;
        cloud.sh = vec![0.25; 2 * 9];
        let packet = gunzip(&encode_spz(&cloud, false).expect("encodes"));
        let expected = 16 + 2 * (9 + 1 + 3 + 3 + 4 + 9);
        assert_eq!(packet.len(), expected);
        assert_eq!(packet[12], 1, "sh degree recorded in the header");
    }

    #[test]
    fn positions_are_24bit_fixed_point() {
        let mut cloud = unit_cloud(1);
        cloud.positions[0] = [1.0, 0.0, -1.0];
        let packet = gunzip(&encode_spz(&cloud, false).expect("encodes"));

        let x = i32::from_le_bytes([packet[16], packet[17], packet[18], 0]);
        assert_eq!(x, 1 << FRACTIONAL_BITS, "1.0 m maps to 4096 fixed units");

        let y = i32::from_le_bytes([packet[19], packet[20], packet[21], 0]);
        assert_eq!(y, 0);

        let z_raw = i32::from_le_bytes([packet[22], packet[23], packet[24], 0]);
        let z = (z_raw << 8) >> 8;
        assert_eq!(
            z,
            -(1 << FRACTIONAL_BITS),
            "negatives sign-extend correctly"
        );
    }

    #[test]
    fn positions_beyond_fixed_point_range_are_rejected() {
        let mut cloud = unit_cloud(1);
        cloud.positions[0] = [5000.0, 0.0, 0.0];
        let err = encode_spz(&cloud, false).expect_err("out of range");
        assert!(matches!(err, GeolithError::SplatTiles(_)), "{err}");
    }

    #[test]
    fn opacity_passes_through_the_sigmoid() {
        assert_eq!(quantize_opacity(0.0), 128, "logit 0 is alpha 0.5");
        assert_eq!(quantize_opacity(-40.0), 0);
        assert_eq!(quantize_opacity(40.0), 255);
    }

    #[test]
    fn colour_quantisation_matches_the_reference_formula() {
        assert_eq!(quantize_color(0.0), 128, "zero DC is mid grey");
        assert_eq!(quantize_color(-100.0), 0, "clamps rather than wrapping");
        assert_eq!(quantize_color(100.0), 255);

        // The SPZ reference scales DC by 0.15: 1.0 * 0.15 * 255 + 127.5 = 165.75.
        assert_eq!(quantize_color(1.0), 166);
    }

    #[test]
    fn scale_quantisation_matches_the_reference_formula() {
        assert_eq!(quantize_scale(SCALE_LOG_MIN), 0);
        assert_eq!(quantize_scale(-9.0), 16, "one log unit is 16 steps");
        assert_eq!(quantize_scale(100.0), 255, "clamps at the byte ceiling");
    }

    #[test]
    fn rest_sh_quantisation_centres_on_128() {
        assert_eq!(quantize_rest_sh(0.0), 128);
        assert_eq!(quantize_rest_sh(1.0), 255);
        assert_eq!(quantize_rest_sh(-1.0), 0);
    }

    #[test]
    fn identity_quaternion_packs_with_w_as_largest() {
        let packed = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
        let value = u32::from_le_bytes(packed);
        let largest = value >> 30;
        assert_eq!(largest, 3, "w is the dropped component");
    }

    #[test]
    fn quaternion_packing_is_sign_invariant() {
        let positive = pack_quaternion_smallest_three([0.1, 0.2, 0.3, 0.9]);
        let negated = pack_quaternion_smallest_three([-0.1, -0.2, -0.3, -0.9]);
        assert_eq!(
            positive, negated,
            "q and -q are the same rotation and must pack identically"
        );
    }

    #[test]
    fn quaternion_packing_normalises_input() {
        let unit = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
        let scaled = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 5.0]);
        assert_eq!(unit, scaled, "magnitude is normalised away");
    }

    #[test]
    fn degenerate_quaternion_falls_back_to_identity() {
        let degenerate = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 0.0]);
        let identity = pack_quaternion_smallest_three([0.0, 0.0, 0.0, 1.0]);
        assert_eq!(degenerate, identity);
    }

    #[test]
    fn inconsistent_attribute_lengths_are_rejected() {
        let mut cloud = unit_cloud(3);
        cloud.opacities.pop();
        let err = encode_spz(&cloud, false).expect_err("length mismatch");
        assert!(format!("{err}").contains("inconsistent"), "{err}");
    }

    #[test]
    fn mismatched_sh_buffer_is_rejected() {
        let mut cloud = unit_cloud(2);
        cloud.sh_degree = 1;
        cloud.sh = vec![0.0; 5];
        let err = encode_spz(&cloud, false).expect_err("sh length mismatch");
        assert!(format!("{err}").contains("spherical harmonic"), "{err}");
    }

    #[test]
    fn unsupported_sh_degree_is_rejected() {
        let mut cloud = unit_cloud(1);
        cloud.sh_degree = 4;
        assert!(encode_spz(&cloud, false).is_err());
    }

    #[test]
    fn empty_cloud_encodes_to_a_header_only_packet() {
        let packet = gunzip(&encode_spz(&SplatCloud::default(), false).expect("encodes"));
        assert_eq!(packet.len(), HEADER_BYTES);
        assert_eq!(
            u32::from_le_bytes(packet[8..12].try_into().expect("count")),
            0
        );
    }

    #[test]
    fn output_is_gzip_framed() {
        let bytes = encode_spz(&unit_cloud(2), false).expect("encodes");
        assert_eq!(
            &bytes[0..2],
            &[0x1F, 0x8B],
            "SPZ packets ship gzip-compressed"
        );
    }
}