Skip to main content

cvkg_core/
scene_graph.rs

1//! # Scene Graph and View Identity
2//!
3//! Manages the persistent identity of views across render frames, enabling
4//! advanced features like shared-element transitions (Bifrost Bridge).
5
6use std::collections::HashMap;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, Mutex, OnceLock};
9
10/// Global registry for tracking shared elements across views.
11pub static BIFROST_REGISTRY: OnceLock<Arc<Mutex<BifrostRegistry>>> = OnceLock::new();
12
13/// Get or initialize the global Bifrost registry.
14pub fn bifrost_registry() -> Arc<Mutex<BifrostRegistry>> {
15    BIFROST_REGISTRY
16        .get_or_init(|| Arc::new(Mutex::new(BifrostRegistry::new())))
17        .clone()
18}
19
20/// Unique identifier for a view node in the scene graph.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22#[allow(dead_code)]
23pub struct NodeId(u64);
24
25static NEXT_NODE_ID: AtomicU64 = AtomicU64::new(1);
26
27impl NodeId {
28    /// Generate a new, unique node ID.
29    pub fn generate() -> Self {
30        Self(NEXT_NODE_ID.fetch_add(1, Ordering::SeqCst))
31    }
32}
33
34/// Registry for mapping Bifrost Bridge IDs to persistent scene nodes.
35#[allow(dead_code)]
36pub struct BifrostRegistry {
37    /// Maps Bridge ID -> Persistent Node ID
38    bridges: HashMap<String, NodeId>,
39    /// Maps Node ID -> Last known geometry (Rect)
40    geometry_cache: HashMap<NodeId, crate::Rect>,
41}
42
43impl Default for BifrostRegistry {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl BifrostRegistry {
50    pub fn new() -> Self {
51        Self {
52            bridges: HashMap::new(),
53            geometry_cache: HashMap::new(),
54        }
55    }
56
57    /// Register or retrieve a persistent ID for a bridge name.
58    pub fn get_or_create_bridge(&mut self, bridge_id: &str) -> NodeId {
59        *self
60            .bridges
61            .entry(bridge_id.to_string())
62            .or_insert_with(NodeId::generate)
63    }
64
65    /// Store the geometry of a node for interpolation in the next frame.
66    pub fn update_geometry(&mut self, node_id: NodeId, rect: crate::Rect) {
67        self.geometry_cache.insert(node_id, rect);
68    }
69
70    /// Retrieve the last known geometry for a node.
71    pub fn get_geometry(&self, node_id: NodeId) -> Option<crate::Rect> {
72        self.geometry_cache.get(&node_id).copied()
73    }
74}