Skip to main content

qualia_core_db/q42/m64_matter/
lrm3.rs

1//! Local Relative Metric (LRM3) Header Block for M64 Containers.
2//!
3//! Provides a 128-byte (2 × 64B cache line) header for micro-scale, medical,
4//! anatomical, and laboratory local reference frames (SRID = 0 = `M64_SRID_LOCAL_MICROMETER`).
5
6use crate::container_10d::crc32c::crc32c;
7use bytemuck::{Pod, Zeroable};
8use super::chunk_directory::M64Error;
9
10/// Magic identifier for LRM3 local relative metric block: ASCII `LRM3`.
11pub const LRM3_MAGIC: [u8; 4] = *b"LRM3";
12
13/// Current LRM3 format version.
14pub const LRM3_VERSION: u16 = 1;
15
16/// Exact byte length of the LRM3 header block (128 bytes = 2 × 64B cache lines).
17pub const LRM3_BLOCK_BYTES: usize = 128;
18
19/// Cartesian local metric frame in micrometers (default).
20pub const COORD_FRAME_CARTESIAN_MICROMETER: u8 = 0;
21/// Cylindrical local frame for tubular anatomical structures (e.g. vascular, neural).
22pub const COORD_FRAME_CYLINDRICAL_ANATOMY: u8 = 1;
23/// Spherical local frame for organoid/cellular centroid geometry.
24pub const COORD_FRAME_SPHERICAL_LOCAL: u8 = 2;
25
26/// 128-byte Local Relative Metric (LRM3) Header (2 × 64B cache lines).
27#[repr(C, align(64))]
28#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
29pub struct M64LocalMetricHeader {
30    /// 0x00..0x04: ASCII Magic `LRM3`
31    pub magic: [u8; 4],
32    /// 0x04..0x06: LRM3 version (1)
33    pub version: u16,
34    /// 0x06..0x07: Scale tier (S in 0..7)
35    pub scale_tier: u8,
36    /// 0x07..0x08: Coordinate frame kind (0=Cartesian, 1=Cylindrical, 2=Spherical)
37    pub coord_frame_kind: u8,
38    /// 0x08..0x10: Entity / specimen / patient DID hash anchor
39    pub anchor_did_hash: u64,
40    /// 0x10..0x28: World anchor origin offset in meters [x, y, z]
41    pub origin_offset_m: [f64; 3],
42    /// 0x28..0x38: Orientation quaternion [x, y, z, w] relative to anchor
43    pub orientation_quat: [f32; 4],
44    /// 0x38..0x44: Anisotropic scale in micrometers per integer unit [sx, sy, sz]
45    pub anisotropic_scale_um: [f32; 3],
46    /// 0x44..0x50: Bounding box minimum in micrometers [min_x, min_y, min_z]
47    pub bbox_min_um: [i32; 3],
48    /// 0x50..0x5C: Bounding box maximum in micrometers [max_x, max_y, max_z]
49    pub bbox_max_um: [i32; 3],
50    /// 0x5C..0x7C: Reserved for expansion (32 bytes)
51    pub reserved: [u8; 32],
52    /// 0x7C..0x80: CRC-32C checksum of bytes 0..124
53    pub header_crc32c: u32,
54}
55
56impl Default for M64LocalMetricHeader {
57    fn default() -> Self {
58        Self {
59            magic: LRM3_MAGIC,
60            version: LRM3_VERSION,
61            scale_tier: 0,
62            coord_frame_kind: COORD_FRAME_CARTESIAN_MICROMETER,
63            anchor_did_hash: 0,
64            origin_offset_m: [0.0, 0.0, 0.0],
65            orientation_quat: [0.0, 0.0, 0.0, 1.0],
66            anisotropic_scale_um: [1.0, 1.0, 1.0],
67            bbox_min_um: [0, 0, 0],
68            bbox_max_um: [0, 0, 0],
69            reserved: [0u8; 32],
70            header_crc32c: 0,
71        }
72    }
73}
74
75impl M64LocalMetricHeader {
76    /// Compute CRC-32C over the first 124 bytes of the header.
77    #[inline]
78    pub fn compute_crc32c(&self) -> u32 {
79        let bytes: &[u8; 128] = bytemuck::cast_ref(self);
80        crc32c(&bytes[..124])
81    }
82
83    /// Update `header_crc32c` with the computed CRC-32C.
84    #[inline]
85    pub fn update_crc(&mut self) {
86        self.header_crc32c = self.compute_crc32c();
87    }
88
89    /// Validate magic, version, and CRC-32C checksum.
90    #[inline]
91    pub fn validate(&self) -> Result<(), M64Error> {
92        if self.magic != LRM3_MAGIC {
93            return Err(M64Error::InvalidMagic);
94        }
95        if self.version != LRM3_VERSION {
96            return Err(M64Error::InvalidVersion(self.version));
97        }
98        let computed = self.compute_crc32c();
99        if self.header_crc32c == computed {
100            Ok(())
101        } else {
102            Err(M64Error::ChecksumMismatch {
103                stored: self.header_crc32c,
104                computed,
105            })
106        }
107    }
108
109    /// Convert local integer raw coordinates `[x, y, z]` to world coordinates in meters.
110    ///
111    /// Applies anisotropic micrometer scale, rotates by `orientation_quat`, and offsets
112    /// by `origin_offset_m`.
113    #[inline]
114    pub fn local_i32_to_meters(&self, xyz_raw: [i32; 3]) -> [f64; 3] {
115        // Convert to meters in local frame
116        let vx = (xyz_raw[0] as f64) * (self.anisotropic_scale_um[0] as f64) * 1e-6;
117        let vy = (xyz_raw[1] as f64) * (self.anisotropic_scale_um[1] as f64) * 1e-6;
118        let vz = (xyz_raw[2] as f64) * (self.anisotropic_scale_um[2] as f64) * 1e-6;
119
120        // Quaternion rotation: v' = v + 2*w*(q x v) + 2*(q x (q x v))
121        let qx = self.orientation_quat[0] as f64;
122        let qy = self.orientation_quat[1] as f64;
123        let qz = self.orientation_quat[2] as f64;
124        let qw = self.orientation_quat[3] as f64;
125
126        // t = 2 * (q x v)
127        let tx = 2.0 * (qy * vz - qz * vy);
128        let ty = 2.0 * (qz * vx - qx * vz);
129        let tz = 2.0 * (qx * vy - qy * vx);
130
131        // v' = v + w * t + (q x t)
132        let rx = vx + qw * tx + (qy * tz - qz * ty);
133        let ry = vy + qw * ty + (qz * tx - qx * tz);
134        let rz = vz + qw * tz + (qx * ty - qy * tx);
135
136        [
137            self.origin_offset_m[0] + rx,
138            self.origin_offset_m[1] + ry,
139            self.origin_offset_m[2] + rz,
140        ]
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn test_lrm3_header_size_and_alignment() {
150        assert_eq!(
151            std::mem::size_of::<M64LocalMetricHeader>(),
152            128,
153            "M64LocalMetricHeader must be exactly 128 bytes"
154        );
155        assert_eq!(
156            std::mem::align_of::<M64LocalMetricHeader>(),
157            64,
158            "M64LocalMetricHeader must be 64-byte aligned"
159        );
160    }
161
162    #[test]
163    fn test_lrm3_header_crc_roundtrip() {
164        let mut header = M64LocalMetricHeader::default();
165        header.anchor_did_hash = 0x1234_5678_9ABC_DEF0;
166        header.origin_offset_m = [10.0, 20.0, 30.0];
167        header.anisotropic_scale_um = [2.0, 2.0, 5.0];
168        header.bbox_min_um = [-1000, -1000, 0];
169        header.bbox_max_um = [1000, 1000, 5000];
170
171        header.update_crc();
172        assert_ne!(header.header_crc32c, 0);
173        assert!(header.validate().is_ok());
174
175        header.scale_tier ^= 1;
176        assert!(matches!(header.validate(), Err(M64Error::ChecksumMismatch { .. })));
177    }
178
179    #[test]
180    fn test_lrm3_coordinate_transformation() {
181        let mut header = M64LocalMetricHeader::default();
182        header.origin_offset_m = [100.0, 200.0, 300.0];
183        header.anisotropic_scale_um = [1.0, 1.0, 1.0]; // 1 um per unit
184        header.orientation_quat = [0.0, 0.0, 0.0, 1.0]; // identity
185
186        let world_m = header.local_i32_to_meters([1_000_000, 0, 0]); // 1 meter offset in X
187        assert!((world_m[0] - 101.0).abs() < 1e-9);
188        assert!((world_m[1] - 200.0).abs() < 1e-9);
189        assert!((world_m[2] - 300.0).abs() < 1e-9);
190    }
191}