Skip to main content

qualia_core_db/modalities/
differential_render.rs

1// Differential 3D Video Codec Modality (`differential_render.rs`)
2//
3// Implements the zero-heap causal delta stream and N3Logic optical topology compiler:
4// - 48-byte DeltaNQuin layout (SIMD-aligned to 16 bytes)
5// - Causal Epoch Watermarking for ReSTIR reservoir invalidation
6// - Two-tier Long-Term Reference (LTR) promotion and instant O(1) demotion
7// - Screen-space tile dirty bitmask accumulation
8
9use bytemuck::{Pod, Zeroable};
10
11pub const OP_DIFF_TRANSFORM_DELTA: u16 = 0x60;
12pub const OP_DIFF_RADIANCE_DELTA: u16 = 0x61;
13pub const OP_DIFF_ISOLATION_MASK: u16 = 0x62;
14pub const OP_DIFF_LTR_PROMOTION: u16 = 0x63;
15pub const OP_DIFF_EPOCH_WATERMARK: u16 = 0x64;
16pub const OP_DIFF_SALIENT_QP: u16 = 0x65;
17
18pub const SALIENCE_CLASS_A_FOCAL: u8 = 0;
19pub const SALIENCE_CLASS_B_DYNAMIC: u8 = 64;
20pub const SALIENCE_CLASS_C_AMBIENT: u8 = 192;
21pub const SALIENCE_CLASS_D_SUBPERCEPTUAL: u8 = 255;
22
23pub const MEDIUM_HOMOGENEOUS_AIR: u8 = 0;
24pub const MEDIUM_CLEAR_WATER: u8 = 1;
25pub const MEDIUM_TURBID_BLACKWATER: u8 = 2;
26pub const MEDIUM_MIST_FOG: u8 = 3;
27
28/// 48-byte DeltaNQuin Super-Quin representation for GPU/CPU zero-copy delta streams.
29///
30/// Layout: 12 words of u32 = 48 bytes, aligned to 16 bytes.
31#[repr(C, align(16))]
32#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
33pub struct DeltaNQuin {
34    // ── Word 0..1 (8 bytes): Identity & Opcode ──────────────────────────────────
35    pub subject_id: u32,
36    pub predicate_op: u16,
37    pub salience_qp: u8,
38    pub medium_branch: u8,
39
40    // ── Word 2..7 (24 bytes): Quantized 10D Delta Payload (Object) ──────────────
41    pub delta_pos: [f32; 3],
42    pub delta_vel_packed: [u16; 4],
43    pub rot_or_sh_delta: u32,
44
45    // ── Word 8..11 (16 bytes): Context, Clock & Parity ──────────────────────────
46    pub context_cell: u32,
47    pub lamport_epoch: u32,
48    pub dirty_tile_mask: u32,
49    pub ecc_parity: u32,
50}
51
52impl Default for DeltaNQuin {
53    fn default() -> Self {
54        Self {
55            subject_id: 0,
56            predicate_op: OP_DIFF_TRANSFORM_DELTA,
57            salience_qp: SALIENCE_CLASS_A_FOCAL,
58            medium_branch: 0,
59            delta_pos: [0.0; 3],
60            delta_vel_packed: [0; 4],
61            rot_or_sh_delta: 0,
62            context_cell: 0,
63            lamport_epoch: 0,
64            dirty_tile_mask: 0,
65            ecc_parity: 0,
66        }
67    }
68}
69
70impl DeltaNQuin {
71    /// Constructs a transform delta for an entity.
72    pub fn new_transform_delta(
73        subject_id: u32,
74        context_cell: u32,
75        delta_pos: [f32; 3],
76        vel_mps: [f32; 3],
77        lod_scale: f32,
78        epoch: u32,
79    ) -> Self {
80        let mut quin = Self {
81            subject_id,
82            predicate_op: OP_DIFF_TRANSFORM_DELTA,
83            salience_qp: SALIENCE_CLASS_A_FOCAL,
84            medium_branch: 0,
85            delta_pos,
86            delta_vel_packed: [
87                pack_f32_to_f16(vel_mps[0]),
88                pack_f32_to_f16(vel_mps[1]),
89                pack_f32_to_f16(vel_mps[2]),
90                pack_f32_to_f16(lod_scale),
91            ],
92            rot_or_sh_delta: 0,
93            context_cell,
94            lamport_epoch: epoch,
95            dirty_tile_mask: 0,
96            ecc_parity: 0,
97        };
98        quin.ecc_parity = quin.compute_parity();
99        quin
100    }
101
102    /// Constructs an N3Logic optical isolation bitmask delta.
103    pub fn new_optical_isolation(
104        cell_id: u32,
105        affected_tiles_bitmask: u32,
106        epoch: u32,
107    ) -> Self {
108        let mut quin = Self {
109            subject_id: cell_id,
110            predicate_op: OP_DIFF_ISOLATION_MASK,
111            salience_qp: SALIENCE_CLASS_C_AMBIENT,
112            medium_branch: 0,
113            delta_pos: [0.0; 3],
114            delta_vel_packed: [0; 4],
115            rot_or_sh_delta: 0,
116            context_cell: cell_id,
117            lamport_epoch: epoch,
118            dirty_tile_mask: affected_tiles_bitmask,
119            ecc_parity: 0,
120        };
121        quin.ecc_parity = quin.compute_parity();
122        quin
123    }
124
125    /// Computes XOR folding parity across all fields.
126    pub fn compute_parity(&self) -> u32 {
127        self.subject_id
128            ^ (self.predicate_op as u32)
129            ^ ((self.salience_qp as u32) << 16)
130            ^ ((self.medium_branch as u32) << 24)
131            ^ self.delta_pos[0].to_bits()
132            ^ self.delta_pos[1].to_bits()
133            ^ self.delta_pos[2].to_bits()
134            ^ ((self.delta_vel_packed[0] as u32) | ((self.delta_vel_packed[1] as u32) << 16))
135            ^ ((self.delta_vel_packed[2] as u32) | ((self.delta_vel_packed[3] as u32) << 16))
136            ^ self.rot_or_sh_delta
137            ^ self.context_cell
138            ^ self.lamport_epoch
139            ^ self.dirty_tile_mask
140    }
141
142    /// Verifies data integrity via XOR parity fold.
143    #[inline]
144    pub fn is_parity_valid(&self) -> bool {
145        self.ecc_parity == self.compute_parity()
146    }
147}
148
149/// Helper function to pack an f32 into an IEEE 754 half-precision u16.
150pub fn pack_f32_to_f16(val: f32) -> u16 {
151    let bits = val.to_bits();
152    let sign = (bits >> 31) & 0x1;
153    let exp = ((bits >> 23) & 0xFF) as i32;
154    let mant = bits & 0x7FFFFF;
155
156    if exp == 255 {
157        // Inf / NaN
158        return ((sign << 15) | 0x7C00 | (mant >> 13).min(0x3FF)) as u16;
159    }
160    let new_exp = exp - 127 + 15;
161    if new_exp >= 31 {
162        // Overflow to Inf
163        return ((sign << 15) | 0x7C00) as u16;
164    }
165    if new_exp <= 0 {
166        // Subnormal or underflow
167        return (sign << 15) as u16;
168    }
169    let new_mant = mant >> 13;
170    ((sign << 15) | ((new_exp as u32) << 10) | new_mant) as u16
171}
172
173/// Helper function to unpack an IEEE 754 half-precision u16 into an f32.
174pub fn unpack_f16_to_f32(h: u16) -> f32 {
175    let sign = ((h >> 15) & 0x1) as u32;
176    let exp = ((h >> 10) & 0x1F) as u32;
177    let mant = (h & 0x3FF) as u32;
178
179    if exp == 31 {
180        let f_exp = 255u32;
181        let f_mant = mant << 13;
182        return f32::from_bits((sign << 31) | (f_exp << 23) | f_mant);
183    }
184    if exp == 0 {
185        if mant == 0 {
186            return f32::from_bits(sign << 31);
187        }
188        // Subnormal
189        let mut m = mant;
190        let mut shift = 0;
191        while (m & 0x400) == 0 {
192            m <<= 1;
193            shift += 1;
194        }
195        let f_exp = (127 - 14 - shift) as u32;
196        let f_mant = (m & 0x3FF) << 13;
197        return f32::from_bits((sign << 31) | (f_exp << 23) | f_mant);
198    }
199    let f_exp = (exp + 127 - 15) as u32;
200    let f_mant = mant << 13;
201    f32::from_bits((sign << 31) | (f_exp << 23) | f_mant)
202}
203
204/// Evaluates a batch of differential quins, checking epoch watermarks and accumulating dirty tiles.
205///
206/// Respects QualiaDB zero-heap contract by writing into caller-supplied output buffers.
207pub fn evaluate_differential_frame(
208    delta_quins: &[DeltaNQuin],
209    active_epoch: u32,
210    out_dirty_tiles: &mut [u32],
211) -> Result<usize, &'static str> {
212    if delta_quins.is_empty() {
213        return Ok(0);
214    }
215
216    let mut dirty_count = 0usize;
217
218    for quin in delta_quins {
219        if !quin.is_parity_valid() {
220            return Err("ECC parity failure in DeltaNQuin packet");
221        }
222
223        // Causal Epoch Watermarking: Ignore state updates from outdated epochs
224        if quin.lamport_epoch < active_epoch {
225            continue;
226        }
227
228        match quin.predicate_op {
229            OP_DIFF_TRANSFORM_DELTA | OP_DIFF_RADIANCE_DELTA => {
230                // If tile mask provided, accumulate into caller's dirty tiles
231                if quin.dirty_tile_mask != 0 && dirty_count < out_dirty_tiles.len() {
232                    out_dirty_tiles[dirty_count] = quin.dirty_tile_mask;
233                    dirty_count += 1;
234                }
235            }
236            OP_DIFF_ISOLATION_MASK => {
237                // N3Logic optical topology update
238                if dirty_count < out_dirty_tiles.len() {
239                    out_dirty_tiles[dirty_count] = quin.dirty_tile_mask;
240                    dirty_count += 1;
241                }
242            }
243            OP_DIFF_LTR_PROMOTION => {
244                // LTR proxy activation: flags tile dirty on transition
245                if dirty_count < out_dirty_tiles.len() {
246                    out_dirty_tiles[dirty_count] = quin.dirty_tile_mask;
247                    dirty_count += 1;
248                }
249            }
250            _ => {}
251        }
252    }
253
254    Ok(dirty_count)
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use std::mem::{align_of, size_of};
261
262    #[test]
263    fn test_delta_nquin_size_and_alignment() {
264        assert_eq!(
265            size_of::<DeltaNQuin>(),
266            48,
267            "DeltaNQuin must be exactly 48 bytes"
268        );
269        assert_eq!(
270            align_of::<DeltaNQuin>(),
271            16,
272            "DeltaNQuin must be 16-byte aligned for GPU SIMD loading"
273        );
274    }
275
276    #[test]
277    fn test_f16_round_trip() {
278        let test_values = [0.0f32, 1.0f32, -1.0f32, 24.5f32, 0.0035f32, -120.75f32];
279        for &val in &test_values {
280            let packed = pack_f32_to_f16(val);
281            let unpacked = unpack_f16_to_f32(packed);
282            let error = (val - unpacked).abs();
283            assert!(
284                error < 0.1,
285                "f16 pack/unpack error {} too large for val {}",
286                error,
287                val
288            );
289        }
290    }
291
292    #[test]
293    fn test_causal_epoch_watermark_invalidation() {
294        let current_epoch = 120u32;
295        let stale_quin = DeltaNQuin {
296            subject_id: 101,
297            predicate_op: OP_DIFF_TRANSFORM_DELTA,
298            lamport_epoch: 110, // Stale!
299            dirty_tile_mask: 0x000000FF,
300            ..Default::default()
301        };
302        let mut stale_quin_valid = stale_quin;
303        stale_quin_valid.ecc_parity = stale_quin_valid.compute_parity();
304
305        let fresh_quin = DeltaNQuin {
306            subject_id: 102,
307            predicate_op: OP_DIFF_TRANSFORM_DELTA,
308            lamport_epoch: 121, // Fresh
309            dirty_tile_mask: 0x0000FF00,
310            ..Default::default()
311        };
312        let mut fresh_quin_valid = fresh_quin;
313        fresh_quin_valid.ecc_parity = fresh_quin_valid.compute_parity();
314
315        let mut output_tiles = [0u32; 16];
316        let count = evaluate_differential_frame(
317            &[stale_quin_valid, fresh_quin_valid],
318            current_epoch,
319            &mut output_tiles,
320        )
321        .expect("Evaluation failed");
322
323        assert_eq!(count, 1);
324        assert_eq!(output_tiles[0], 0x0000FF00);
325    }
326
327    #[test]
328    fn test_optical_isolation_delta() {
329        let quin = DeltaNQuin::new_optical_isolation(42, 0x0F0F0F0F, 10);
330        assert!(quin.is_parity_valid());
331        assert_eq!(quin.predicate_op, OP_DIFF_ISOLATION_MASK);
332        assert_eq!(quin.dirty_tile_mask, 0x0F0F0F0F);
333    }
334}