use geolith::error::Result;
use serde_json::{Value, json};
const COMPONENT_TYPE_FLOAT: u32 = 5126;
const COMPONENT_TYPE_UNSIGNED_BYTE: u32 = 5121;
const PRIMITIVE_MODE_POINTS: u32 = 0;
const SH_DEGREE_1_COEFS: usize = 3;
const SH_DEGREE_2_COEFS: usize = 5;
const SH_DEGREE_3_COEFS: usize = 7;
pub const EXT_GAUSSIAN_SPLATTING: &str = "KHR_gaussian_splatting";
pub const EXT_SPZ_2: &str = "KHR_gaussian_splatting_compression_spz_2";
pub const EXT_MATERIALS_UNLIT: &str = "KHR_materials_unlit";
#[must_use]
const fn pad4(length: usize) -> usize {
match length % 4 {
0 => 0,
rem => 4 - rem,
}
}
#[must_use]
pub fn tile_node_matrix(translation: [f64; 3]) -> [f64; 16] {
let rotation = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]];
let mut translated = [0.0_f64; 3];
for (row, axis) in rotation.iter().enumerate() {
translated[row] =
axis[0] * translation[0] + axis[1] * translation[1] + axis[2] * translation[2];
}
[
rotation[0][0],
rotation[1][0],
rotation[2][0],
0.0,
rotation[0][1],
rotation[1][1],
rotation[2][1],
0.0,
rotation[0][2],
rotation[1][2],
rotation[2][2],
0.0,
translated[0],
translated[1],
translated[2],
1.0,
]
}
struct AccessorSet {
accessors: Vec<Value>,
attributes: serde_json::Map<String, Value>,
}
fn build_accessors(splat_count: usize, sh_degree: u8) -> AccessorSet {
let mut accessors = Vec::new();
let mut attributes = serde_json::Map::new();
let mut push =
|accessor: Value, name: &str, attributes: &mut serde_json::Map<String, Value>| {
accessors.push(accessor);
attributes.insert(name.to_owned(), json!(accessors.len() - 1));
};
push(
json!({
"componentType": COMPONENT_TYPE_FLOAT,
"count": splat_count,
"type": "VEC3",
"min": [-1.0, -1.0, -1.0],
"max": [1.0, 1.0, 1.0],
}),
"POSITION",
&mut attributes,
);
push(
json!({
"componentType": COMPONENT_TYPE_UNSIGNED_BYTE,
"count": splat_count,
"type": "VEC4",
"normalized": true,
}),
"COLOR_0",
&mut attributes,
);
push(
json!({
"componentType": COMPONENT_TYPE_FLOAT,
"count": splat_count,
"type": "VEC3",
}),
"KHR_gaussian_splatting:SCALE",
&mut attributes,
);
push(
json!({
"componentType": COMPONENT_TYPE_FLOAT,
"count": splat_count,
"type": "VEC4",
}),
"KHR_gaussian_splatting:ROTATION",
&mut attributes,
);
let bands: [(u8, usize); 3] = [
(1, SH_DEGREE_1_COEFS),
(2, SH_DEGREE_2_COEFS),
(3, SH_DEGREE_3_COEFS),
];
for (degree, coefficients) in bands {
if sh_degree < degree {
continue;
}
for index in 0..coefficients {
push(
json!({
"componentType": COMPONENT_TYPE_FLOAT,
"count": splat_count,
"type": "VEC4",
}),
&format!("KHR_gaussian_splatting:SH_DEGREE_{degree}_COEF_{index}"),
&mut attributes,
);
}
}
AccessorSet {
accessors,
attributes,
}
}
#[must_use]
pub fn build_splat_gltf(
spz_byte_length: usize,
splat_count: usize,
sh_degree: u8,
node_matrix: [f64; 16],
) -> Value {
let AccessorSet {
accessors,
attributes,
} = build_accessors(splat_count, sh_degree);
let bin_length = spz_byte_length + pad4(spz_byte_length);
json!({
"asset": { "version": "2.0", "copyright": geolith::attribution::CREDIT },
"extensionsUsed": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2, EXT_MATERIALS_UNLIT],
"extensionsRequired": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
"scene": 0,
"scenes": [{ "nodes": [0] }],
"nodes": [{ "mesh": 0, "matrix": node_matrix.to_vec() }],
"materials": [{ "extensions": { EXT_MATERIALS_UNLIT: {} } }],
"meshes": [{
"primitives": [{
"mode": PRIMITIVE_MODE_POINTS,
"attributes": attributes,
"material": 0,
"extensions": {
EXT_GAUSSIAN_SPLATTING: {
"kernel": "ellipse",
"projection": "perspective",
"extensions": {
EXT_SPZ_2: { "bufferView": 0 }
}
}
}
}]
}],
"buffers": [{ "byteLength": bin_length }],
"bufferViews": [{
"buffer": 0,
"byteOffset": 0,
"byteLength": spz_byte_length,
}],
"accessors": accessors,
})
}
pub fn write_splat_glb(
spz_bytes: &[u8],
splat_count: usize,
sh_degree: u8,
node_matrix: [f64; 16],
) -> Result<Vec<u8>> {
let gltf = build_splat_gltf(spz_bytes.len(), splat_count, sh_degree, node_matrix);
let json_chunk = serde_json::to_vec(&gltf)?;
let json_pad = pad4(json_chunk.len());
let bin_pad = pad4(spz_bytes.len());
let json_length = json_chunk.len() + json_pad;
let bin_length = spz_bytes.len() + bin_pad;
let total = 12 + 8 + json_length + 8 + bin_length;
let mut glb = Vec::with_capacity(total);
glb.extend_from_slice(b"glTF");
glb.extend_from_slice(&2_u32.to_le_bytes());
glb.extend_from_slice(&(total as u32).to_le_bytes());
glb.extend_from_slice(&(json_length as u32).to_le_bytes());
glb.extend_from_slice(b"JSON");
glb.extend_from_slice(&json_chunk);
glb.extend(std::iter::repeat_n(b' ', json_pad));
glb.extend_from_slice(&(bin_length as u32).to_le_bytes());
glb.extend_from_slice(b"BIN\0");
glb.extend_from_slice(spz_bytes);
glb.extend(std::iter::repeat_n(0_u8, bin_pad));
Ok(glb)
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_glb_json(glb: &[u8]) -> Value {
let json_length = u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
let start = 20;
serde_json::from_slice(&glb[start..start + json_length]).expect("valid json chunk")
}
#[test]
fn pad4_rounds_up_to_four_byte_alignment() {
assert_eq!(pad4(0), 0);
assert_eq!(pad4(1), 3);
assert_eq!(pad4(2), 2);
assert_eq!(pad4(3), 1);
assert_eq!(pad4(4), 0);
}
#[test]
fn glb_container_header_is_well_formed() {
let glb = write_splat_glb(&[1, 2, 3], 4, 0, tile_node_matrix([0.0; 3])).expect("writes");
assert_eq!(&glb[0..4], b"glTF");
assert_eq!(
u32::from_le_bytes(glb[4..8].try_into().expect("version")),
2
);
assert_eq!(
u32::from_le_bytes(glb[8..12].try_into().expect("length")) as usize,
glb.len(),
"declared length matches the actual container"
);
assert_eq!(&glb[16..20], b"JSON");
}
#[test]
fn glb_chunks_are_four_byte_aligned() {
for payload_len in 1..=9 {
let spz = vec![7_u8; payload_len];
let glb = write_splat_glb(&spz, 1, 0, tile_node_matrix([0.0; 3])).expect("writes");
assert_eq!(
glb.len() % 4,
0,
"payload of {payload_len} bytes must still align"
);
let json_length =
u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
assert_eq!(json_length % 4, 0, "JSON chunk is padded");
let bin_header = 20 + json_length;
assert_eq!(&glb[bin_header + 4..bin_header + 8], b"BIN\0");
}
}
#[test]
fn spz_payload_is_embedded_verbatim() {
let spz: Vec<u8> = (0..16).collect();
let glb = write_splat_glb(&spz, 2, 0, tile_node_matrix([0.0; 3])).expect("writes");
let json_length = u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
let bin_start = 20 + json_length + 8;
assert_eq!(&glb[bin_start..bin_start + spz.len()], &spz[..]);
}
#[test]
fn gltf_declares_the_required_extensions() {
let glb = write_splat_glb(&[0; 8], 3, 0, tile_node_matrix([0.0; 3])).expect("writes");
let gltf = parse_glb_json(&glb);
let required = gltf["extensionsRequired"]
.as_array()
.expect("extensionsRequired");
assert!(required.iter().any(|v| v == EXT_GAUSSIAN_SPLATTING));
assert!(
required.iter().any(|v| v == EXT_SPZ_2),
"the renderer plugin rejects tiles without spz_2"
);
let used = gltf["extensionsUsed"].as_array().expect("extensionsUsed");
assert!(used.iter().any(|v| v == EXT_MATERIALS_UNLIT));
}
#[test]
fn primitive_points_at_the_spz_buffer_view() {
let glb = write_splat_glb(&[0; 8], 3, 0, tile_node_matrix([0.0; 3])).expect("writes");
let gltf = parse_glb_json(&glb);
let primitive = &gltf["meshes"][0]["primitives"][0];
assert_eq!(primitive["mode"], PRIMITIVE_MODE_POINTS);
assert_eq!(
primitive["extensions"][EXT_GAUSSIAN_SPLATTING]["extensions"][EXT_SPZ_2]["bufferView"],
0
);
assert_eq!(
primitive["extensions"][EXT_GAUSSIAN_SPLATTING]["kernel"],
"ellipse"
);
assert_eq!(gltf["bufferViews"][0]["byteLength"], 8);
}
#[test]
fn the_asset_carries_the_credit() {
let gltf = build_splat_gltf(16, 5, 0, tile_node_matrix([0.0; 3]));
assert_eq!(gltf["asset"]["copyright"], "© geolith");
assert_eq!(gltf["asset"]["version"], "2.0");
}
#[test]
fn base_attributes_are_always_declared() {
let gltf = build_splat_gltf(16, 5, 0, tile_node_matrix([0.0; 3]));
let attributes = &gltf["meshes"][0]["primitives"][0]["attributes"];
for name in [
"POSITION",
"COLOR_0",
"KHR_gaussian_splatting:SCALE",
"KHR_gaussian_splatting:ROTATION",
] {
assert!(!attributes[name].is_null(), "missing attribute {name}");
}
assert_eq!(gltf["accessors"][0]["count"], 5);
}
#[test]
fn spherical_harmonic_attributes_scale_with_degree() {
let counts = [0_u8, 1, 2, 3].map(|degree| {
let gltf = build_splat_gltf(16, 2, degree, tile_node_matrix([0.0; 3]));
gltf["meshes"][0]["primitives"][0]["attributes"]
.as_object()
.expect("attributes")
.len()
});
assert_eq!(counts[0], 4, "degree 0 declares only the base attributes");
assert_eq!(counts[1], 7);
assert_eq!(counts[2], 12);
assert_eq!(counts[3], 19);
}
#[test]
fn degree_three_declares_every_band_attribute() {
let gltf = build_splat_gltf(16, 2, 3, tile_node_matrix([0.0; 3]));
let attributes = &gltf["meshes"][0]["primitives"][0]["attributes"];
assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_1_COEF_2"].is_null());
assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_2_COEF_4"].is_null());
assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_3_COEF_6"].is_null());
}
#[test]
fn node_matrix_is_column_major_with_flipped_axes() {
let matrix = tile_node_matrix([0.0, 0.0, 0.0]);
assert_eq!(matrix.len(), 16);
assert_eq!(matrix[0], 1.0);
assert_eq!(matrix[5], -1.0, "Y is flipped to reach glTF Y-up");
assert_eq!(matrix[10], -1.0, "Z is flipped to reach glTF Y-up");
assert_eq!(matrix[15], 1.0);
}
#[test]
fn node_matrix_rotates_the_translation_into_the_gltf_basis() {
let matrix = tile_node_matrix([2.0, 3.0, 4.0]);
assert_eq!(matrix[12], 2.0);
assert_eq!(matrix[13], -3.0, "translation follows the Y flip");
assert_eq!(matrix[14], -4.0, "translation follows the Z flip");
}
#[test]
fn buffer_byte_length_includes_alignment_padding() {
let gltf = build_splat_gltf(5, 1, 0, tile_node_matrix([0.0; 3]));
assert_eq!(
gltf["buffers"][0]["byteLength"], 8,
"5 bytes pad up to an 8-byte buffer"
);
assert_eq!(gltf["bufferViews"][0]["byteLength"], 5);
}
}