use std::collections::VecDeque; use std::sync::atomic::{AtomicU32, Ordering}; use super::*; use ombre::collections::{IntMap, IntSet}; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct NodeId(u32); impl NodeId { /// Get the next unique identifier. fn next() -> Self { static NEXT: AtomicU32 = AtomicU32::new(1); NodeId(NEXT.fetch_add(1, Ordering::SeqCst)) } pub(super) fn new(n: u32) -> Option { if n > 0 { Some(Self(n)) } else { None } } } impl From for u32 { fn from(value: NodeId) -> Self { value.0 } } #[derive(Debug, Default)] pub enum Object { #[default] Null, Mesh { bindings: Bindings<2, 2>, selection: Vec, vertices: Vec, elements: usize, style: RenderStyle, mode: InteractionMode, }, #[allow(dead_code)] Light, } #[derive(Debug)] pub struct Node { pub id: NodeId, pub object: Object, #[allow(dead_code)] pub transform: Transform3D, pub children: IntSet, } impl Node { pub fn new(object: Object) -> Self { Self { id: NodeId::next(), object, transform: Transform3D::default(), children: IntSet::default(), } } } /// Scene graph. #[derive(Debug)] pub struct Graph { root: NodeId, nodes: IntMap, } impl Default for Graph { fn default() -> Self { Self::new(Node::new(Object::Null)) } } impl Graph { pub fn new(root: Node) -> Self { Self { root: root.id, nodes: IntMap::from_iter([(root.id, root)]), } } pub fn get(&self, id: &NodeId) -> Option<&Node> { self.nodes.get(id) } pub fn root(&self) -> &Node { &self.nodes[&self.root] } pub fn insert(&mut self, node: Node, parent: NodeId) -> bool { if let Some(parent) = self.nodes.get_mut(&parent) { parent.children.insert(node.id); self.nodes.insert(node.id, node); return true; } false } pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut Node> { self.nodes.get_mut(id) } #[allow(dead_code)] pub fn remove(&mut self, id: NodeId) -> Option { if let Some(node) = self.nodes.remove(&id) { for child in node.children.iter().copied() { self.remove(child); } for node in self.nodes.values_mut() { node.children.remove(&id); } return Some(node); } None } pub fn iter(&self) -> Iter<'_> { Iter { graph: self, queue: VecDeque::from(vec![self.root]), } } } /// Graph iterator. pub struct Iter<'a> { graph: &'a Graph, queue: VecDeque, } impl<'a> Iterator for Iter<'a> { type Item = &'a Node; fn next(&mut self) -> Option { self.queue.pop_front().and_then(|id| { if let Some(node) = self.graph.get(&id) { for child_id in &node.children { self.queue.push_back(*child_id); } return Some(node); } None }) } }