1use crate::value::Value;
6use std::collections::BTreeMap;
7
8#[derive(Debug, Clone, PartialEq)]
14pub struct NestedRealm {
15 pub depth: u32,
17 pub realm_usri: String,
19 pub time_dilation: f64,
22 pub parent_context: u64,
24}
25
26impl NestedRealm {
27 pub fn new(depth: u32, realm_usri: &str, time_dilation: f64, parent_context: u64) -> Self {
29 Self {
30 depth,
31 realm_usri: realm_usri.into(),
32 time_dilation,
33 parent_context,
34 }
35 }
36
37 pub fn context_hash(&self) -> u64 {
43 let mut h: u64 = 0xcbf29ce484222325;
44 for b in self.parent_context.to_le_bytes() {
45 h ^= b as u64;
46 h = h.wrapping_mul(0x100000001b3);
47 }
48 for b in self.realm_usri.as_bytes() {
49 h ^= *b as u64;
50 h = h.wrapping_mul(0x100000001b3);
51 }
52 for b in self.depth.to_le_bytes() {
53 h ^= b as u64;
54 h = h.wrapping_mul(0x100000001b3);
55 }
56 h
57 }
58
59 pub fn parent_to_nested_time(&self, parent_tau_secs: f64) -> f64 {
62 parent_tau_secs * self.time_dilation
63 }
64
65 pub fn nested_to_parent_time(&self, nested_tau_secs: f64) -> f64 {
67 nested_tau_secs / self.time_dilation
68 }
69
70 pub fn to_value(&self) -> Value {
72 let mut rec = BTreeMap::new();
73 rec.insert("depth".into(), Value::U64(self.depth as u64));
74 rec.insert("realm_usri".into(), Value::String(self.realm_usri.clone()));
75 rec.insert("time_dilation".into(), Value::F64(self.time_dilation));
76 rec.insert("context_hash".into(), Value::U64(self.context_hash()));
77 Value::Record(rec)
78 }
79}
80
81#[derive(Debug, Clone)]
83pub struct NestingStack {
84 realms: Vec<NestedRealm>,
85}
86
87impl NestingStack {
88 pub fn new() -> Self {
90 Self { realms: Vec::new() }
91 }
92
93 pub fn push(&mut self, realm_usri: &str, time_dilation: f64) -> &NestedRealm {
95 let depth = self.realms.len() as u32;
96 let parent_context = self.realms.last().map(|r| r.context_hash()).unwrap_or(0); self.realms.push(NestedRealm::new(
98 depth,
99 realm_usri,
100 time_dilation,
101 parent_context,
102 ));
103 self.realms.last().unwrap()
104 }
105
106 pub fn pop(&mut self) -> Option<NestedRealm> {
108 self.realms.pop()
109 }
110
111 pub fn depth(&self) -> u32 {
113 self.realms.len() as u32
114 }
115
116 pub fn current(&self) -> Option<&NestedRealm> {
118 self.realms.last()
119 }
120
121 pub fn cumulative_time_dilation(&self) -> f64 {
123 self.realms.iter().map(|r| r.time_dilation).product()
124 }
125
126 pub fn base_to_current_time(&self, base_tau_secs: f64) -> f64 {
128 base_tau_secs * self.cumulative_time_dilation()
129 }
130}
131
132impl Default for NestingStack {
133 fn default() -> Self {
134 Self::new()
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq)]
141pub struct FloatingOriginFrame {
142 pub anchor_id: u64,
144 pub healpix_index: u64,
146 pub octree_cell: [i64; 3],
148 pub local_origin_m: [f64; 3],
150 pub residual_m: [f64; 3],
152 pub reanchor_count: u64,
154}
155
156impl FloatingOriginFrame {
157 pub fn new(octree_cell: [i64; 3], residual_m: [f64; 3]) -> Self {
159 let healpix_index = compute_healpix_index(octree_cell, 64);
160 let anchor_id = compute_sector_anchor_id(octree_cell, healpix_index);
161 Self {
162 anchor_id,
163 healpix_index,
164 octree_cell,
165 local_origin_m: [0.0, 0.0, 0.0],
166 residual_m,
167 reanchor_count: 0,
168 }
169 }
170}
171
172pub fn compute_healpix_index(octree_cell: [i64; 3], nside: u64) -> u64 {
174 let nside = nside.max(1);
175 let x = octree_cell[0] as f64;
176 let y = octree_cell[1] as f64;
177 let z = octree_cell[2] as f64;
178 let r = (x * x + y * y + z * z).sqrt();
179 if r == 0.0 {
180 return 0;
181 }
182 let cos_theta = (z / r).clamp(-1.0, 1.0);
183 let phi = y.atan2(x).rem_euclid(2.0 * std::f64::consts::PI);
184 let base_pix = ((phi / (2.0 * std::f64::consts::PI)) * 12.0).floor() as u64 % 12;
185 let z_band = (((1.0 - cos_theta) * 0.5) * (nside as f64)).floor() as u64 % nside;
186 let az_band = ((phi / (2.0 * std::f64::consts::PI)) * (nside as f64)).floor() as u64 % nside;
187 base_pix * nside * nside + z_band * nside + az_band
188}
189
190fn compute_sector_anchor_id(octree_cell: [i64; 3], healpix_index: u64) -> u64 {
191 let mut h: u64 = 0xcbf29ce484222325;
192 for coord in octree_cell {
193 for b in coord.to_le_bytes() {
194 h ^= b as u64;
195 h = h.wrapping_mul(0x100000001b3);
196 }
197 }
198 for b in healpix_index.to_le_bytes() {
199 h ^= b as u64;
200 h = h.wrapping_mul(0x100000001b3);
201 }
202 h
203}
204
205pub fn reanchor_origin(
210 current: &FloatingOriginFrame,
211 step_delta_m: [f64; 3],
212 sector_radius_m: f64,
213) -> FloatingOriginFrame {
214 let radius = sector_radius_m.abs().max(1.0);
215 let candidate = [
216 current.local_origin_m[0] + step_delta_m[0],
217 current.local_origin_m[1] + step_delta_m[1],
218 current.local_origin_m[2] + step_delta_m[2],
219 ];
220 let dist_sq = candidate[0] * candidate[0]
221 + candidate[1] * candidate[1]
222 + candidate[2] * candidate[2];
223 if dist_sq >= radius * radius {
224 let mut next_cell = current.octree_cell;
225 let mut moved = false;
226 for i in 0..3 {
227 let steps = (candidate[i] / radius).trunc() as i64;
228 if steps != 0 {
229 next_cell[i] = next_cell[i].saturating_add(steps);
230 moved = true;
231 }
232 }
233 if !moved {
234 let mut dom = 0;
235 if candidate[1].abs() > candidate[dom].abs() {
236 dom = 1;
237 }
238 if candidate[2].abs() > candidate[dom].abs() {
239 dom = 2;
240 }
241 let dir = if candidate[dom] >= 0.0 { 1 } else { -1 };
242 next_cell[dom] = next_cell[dom].saturating_add(dir);
243 }
244 let healpix_index = compute_healpix_index(next_cell, 64);
245 let anchor_id = compute_sector_anchor_id(next_cell, healpix_index);
246 FloatingOriginFrame {
247 anchor_id,
248 healpix_index,
249 octree_cell: next_cell,
250 local_origin_m: [0.0, 0.0, 0.0],
251 residual_m: current.residual_m,
252 reanchor_count: current.reanchor_count + 1,
253 }
254 } else {
255 FloatingOriginFrame {
256 anchor_id: current.anchor_id,
257 healpix_index: current.healpix_index,
258 octree_cell: current.octree_cell,
259 local_origin_m: candidate,
260 residual_m: current.residual_m,
261 reanchor_count: current.reanchor_count,
262 }
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn nested_realm_context_hash() {
272 let r = NestedRealm::new(
273 1,
274 "urn:omni:v1:simulation:holodeck:vicorian-london",
275 20.0,
276 0,
277 );
278 let h = r.context_hash();
279 assert_eq!(h, r.context_hash());
280 assert_ne!(h, 0);
281 }
282
283 #[test]
284 fn context_hash_isolates_levels() {
285 let r1 = NestedRealm::new(1, "urn:omni:v1:simulation:A", 1.0, 0);
286 let r2 = NestedRealm::new(1, "urn:omni:v1:simulation:B", 1.0, 0);
287 assert_ne!(r1.context_hash(), r2.context_hash());
288 }
289
290 #[test]
291 fn time_dilation_accelerated() {
292 let r = NestedRealm::new(1, "dream", 20.0, 0);
293 assert!((r.parent_to_nested_time(1.0) - 20.0).abs() < 1e-10);
294 assert!((r.nested_to_parent_time(20.0) - 1.0).abs() < 1e-10);
295 }
296
297 #[test]
298 fn time_dilation_decelerated() {
299 let r = NestedRealm::new(1, "slow", 0.1, 0);
300 assert!((r.parent_to_nested_time(1.0) - 0.1).abs() < 1e-10);
301 }
302
303 #[test]
304 fn nesting_stack_push_pop() {
305 let mut stack = NestingStack::new();
306 assert_eq!(stack.depth(), 0);
307 stack.push("level1", 10.0);
308 assert_eq!(stack.depth(), 1);
309 stack.push("level2", 2.0);
310 assert_eq!(stack.depth(), 2);
311 stack.pop();
312 assert_eq!(stack.depth(), 1);
313 }
314
315 #[test]
316 fn cumulative_time_dilation() {
317 let mut stack = NestingStack::new();
318 stack.push("level1", 10.0);
319 stack.push("level2", 2.0);
320 assert!((stack.cumulative_time_dilation() - 20.0).abs() < 1e-10);
321 }
322
323 #[test]
324 fn base_to_current_time() {
325 let mut stack = NestingStack::new();
326 stack.push("dream", 20.0);
327 assert!((stack.base_to_current_time(1.0) - 20.0).abs() < 1e-10);
328 }
329
330 #[test]
331 fn nesting_context_chains() {
332 let mut stack = NestingStack::new();
333 stack.push("level1", 1.0);
334 let ctx1 = stack.current().unwrap().context_hash();
335 stack.push("level2", 1.0);
336 let ctx2 = stack.current().unwrap().context_hash();
337 assert_ne!(ctx1, ctx2);
338 assert_ne!(ctx1, 0);
339 assert_ne!(ctx2, 0);
340 }
341
342 #[test]
343 fn nested_realm_to_value() {
344 let r = NestedRealm::new(2, "urn:omni:v1:simulation:test", 5.0, 12345);
345 let v = r.to_value();
346 match v {
347 Value::Record(rec) => {
348 assert_eq!(rec.get("depth"), Some(&Value::U64(2)));
349 assert_eq!(rec.get("time_dilation"), Some(&Value::F64(5.0)));
350 assert!(rec.contains_key("context_hash"));
351 }
352 _ => panic!("expected Record"),
353 }
354 }
355
356 #[test]
357 fn nested_context_hash_is_non_commutative() {
358 let mut stack_ab = NestingStack::new();
359 stack_ab.push("urn:omni:v1:simulation:A", 1.0);
360 stack_ab.push("urn:omni:v1:simulation:B", 1.0);
361 let hash_ab = stack_ab.current().unwrap().context_hash();
362
363 let mut stack_ba = NestingStack::new();
364 stack_ba.push("urn:omni:v1:simulation:B", 1.0);
365 stack_ba.push("urn:omni:v1:simulation:A", 1.0);
366 let hash_ba = stack_ba.current().unwrap().context_hash();
367
368 assert_ne!(
369 hash_ab, hash_ba,
370 "ordered realm paths [A, B] and [B, A] must not collide"
371 );
372 }
373
374 #[test]
375 fn earth_to_alpha_centauri_floating_origin_preserves_sub_mm_residual() {
376 const ALPHA_CENTAURI_M: f64 = 4.1343e16;
378 let ingested_residual_m = [0.000_42, -0.000_19, 0.000_73]; let naive_global = std::hint::black_box(ALPHA_CENTAURI_M + ingested_residual_m[0]);
382 let naive_recovered = naive_global - ALPHA_CENTAURI_M;
383 let naive_err = (naive_recovered - ingested_residual_m[0]).abs();
384 assert!(
385 naive_err > 1e-4,
386 "naive global f64 at 4.13e16 m loses sub-millimeter precision (err = {naive_err})"
387 );
388
389 let sector_radius_m = 4.1343e14; let step_delta_m = [sector_radius_m, 1.0e13, -2.0e13];
392 let mut frame = FloatingOriginFrame::new([0, 0, 0], ingested_residual_m);
393 let initial_anchor = frame.anchor_id;
394
395 for _ in 0..100 {
396 frame = reanchor_origin(&frame, step_delta_m, sector_radius_m);
397 assert_eq!(frame.local_origin_m, [0.0, 0.0, 0.0]);
398 }
399
400 assert_eq!(frame.reanchor_count, 100);
401 assert_eq!(frame.octree_cell[0], 100);
402 assert_ne!(frame.anchor_id, initial_anchor);
403 assert_ne!(frame.healpix_index, 0);
404 for axis in 0..3 {
405 let err = (frame.residual_m[axis] - ingested_residual_m[axis]).abs();
406 assert!(
407 err < 1e-12,
408 "FloatingOriginFrame must preserve sub-millimeter residual on axis {axis}, got err {err}"
409 );
410 }
411 }
412}