Skip to main content

qualia_core_db/container_10d/
surface_reading.rs

1//! Per-vertex surface colour reading.
2//!
3//! The quantized mesh section stores positions only. One organ albedo painted
4//! in the shader is still one flat colour, even when a light shades the
5//! faces. This section is the reading on the part: one RGBA8 sample per
6//! vertex, in the same order as the mesh. It is not a texture, not a normal,
7//! and not a game-specific dialect.
8
9/// Magic `SRD1`.
10pub const SURFACE_READING_MAGIC: &[u8; 4] = b"SRD1";
11
12/// Byte size of an `SRD1` section for `vertex_count` readings
13/// (8-byte header + 4 bytes per RGBA8 vertex).
14pub fn encoded_len(vertex_count: usize) -> usize {
15    8 + vertex_count * 4
16}
17
18/// Quantize authored readings to RGBA8. Length must match the mesh.
19pub fn encode_surface_reading(reading: &[[f32; 4]]) -> Vec<u8> {
20    let mut out = Vec::with_capacity(encoded_len(reading.len()));
21    out.extend_from_slice(SURFACE_READING_MAGIC);
22    out.extend_from_slice(&(reading.len() as u32).to_le_bytes());
23    for sample in reading {
24        for channel in sample {
25            let q = (channel.clamp(0.0, 1.0) * 255.0).round() as u8;
26            out.push(q);
27        }
28    }
29    out
30}
31
32/// `None` when the payload is not a surface reading or the count is short.
33pub fn decode_surface_reading(payload: &[u8]) -> Option<Vec<[f32; 4]>> {
34    if payload.len() < 8 || &payload[..4] != SURFACE_READING_MAGIC {
35        return None;
36    }
37    let count = u32::from_le_bytes(payload[4..8].try_into().ok()?) as usize;
38    if payload.len() < 8 + count * 4 {
39        return None;
40    }
41    let mut out = Vec::with_capacity(count);
42    for i in 0..count {
43        let o = 8 + i * 4;
44        out.push([
45            payload[o] as f32 / 255.0,
46            payload[o + 1] as f32 / 255.0,
47            payload[o + 2] as f32 / 255.0,
48            payload[o + 3] as f32 / 255.0,
49        ]);
50    }
51    Some(out)
52}