use crate::edge::Edge;
use crate::geometry::{Rect, Size2, Vec2};
use crate::ids::{EdgeId, NodeId, PortId};
use crate::node::{Node, NodeStatus};
use crate::port::{Port, PortDirection};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphError {
MissingNode(NodeId),
MissingPort(PortId),
MissingEdge(EdgeId),
DuplicateId(u64),
NodeInUse(NodeId),
PortInUse(PortId),
WouldCreateCycle {
parent: NodeId,
child: NodeId,
},
Format(String),
}
impl fmt::Display for GraphError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingNode(id) => write!(f, "missing node {id}"),
Self::MissingPort(id) => write!(f, "missing port {id}"),
Self::MissingEdge(id) => write!(f, "missing edge {id}"),
Self::DuplicateId(id) => write!(f, "duplicate id {id}"),
Self::NodeInUse(id) => write!(f, "node {id} still has edges or children"),
Self::PortInUse(id) => write!(f, "port {id} still has edges"),
Self::WouldCreateCycle { parent, child } => {
write!(f, "reparenting {child} under {parent} would create a cycle")
}
Self::Format(m) => write!(f, "invalid document: {m}"),
}
}
}
impl std::error::Error for GraphError {}
#[derive(Clone, Debug, Default)]
pub struct Graph {
pub(crate) nodes: HashMap<NodeId, Node>,
pub(crate) ports: HashMap<PortId, Port>,
pub(crate) edges: HashMap<EdgeId, Edge>,
pub(crate) order: Vec<NodeId>,
pub(crate) port_edges: HashMap<PortId, Vec<EdgeId>>,
pub(crate) children: HashMap<NodeId, Vec<NodeId>>,
next_id: u64,
revision: u64,
}
#[derive(Serialize, Deserialize)]
struct GraphDoc {
version: u32,
next_id: u64,
nodes: Vec<Node>,
ports: Vec<Port>,
edges: Vec<Edge>,
}
impl Graph {
pub fn new() -> Self {
Self {
next_id: 1,
..Default::default()
}
}
fn alloc(&mut self) -> u64 {
let id = self.next_id.max(1);
self.next_id = id + 1;
id
}
pub fn alloc_node_id(&mut self) -> NodeId {
NodeId(self.alloc())
}
pub fn alloc_port_id(&mut self) -> PortId {
PortId(self.alloc())
}
pub fn alloc_edge_id(&mut self) -> EdgeId {
EdgeId(self.alloc())
}
fn reserve(&mut self, raw: u64) {
if raw >= self.next_id {
self.next_id = raw + 1;
}
}
pub fn revision(&self) -> u64 {
self.revision
}
pub(crate) fn bump(&mut self) {
self.revision += 1;
}
pub fn node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(&id)
}
pub fn port(&self, id: PortId) -> Option<&Port> {
self.ports.get(&id)
}
pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
self.edges.get(&id)
}
pub fn node_count(&self) -> usize {
self.nodes.len()
}
pub fn edge_count(&self) -> usize {
self.edges.len()
}
pub fn nodes(&self) -> impl Iterator<Item = &Node> {
self.order.iter().filter_map(|id| self.nodes.get(id))
}
pub fn node_ids(&self) -> &[NodeId] {
&self.order
}
pub fn edges(&self) -> impl Iterator<Item = &Edge> {
self.edges.values()
}
pub fn ports_of(&self, node: NodeId) -> impl Iterator<Item = &Port> {
self.nodes
.get(&node)
.into_iter()
.flat_map(|n| n.inputs.iter().chain(n.outputs.iter()))
.filter_map(|p| self.ports.get(p))
}
pub fn edges_of_port(&self, port: PortId) -> &[EdgeId] {
self.port_edges.get(&port).map(Vec::as_slice).unwrap_or(&[])
}
pub fn connected_edges(&self, node: NodeId) -> Vec<EdgeId> {
let mut out: Vec<EdgeId> = self
.ports_of(node)
.flat_map(|p| self.edges_of_port(p.id).iter().copied())
.collect();
out.sort();
out.dedup();
out
}
pub fn incomers(&self, node: NodeId) -> Vec<NodeId> {
self.neighbours(node, PortDirection::Input)
}
pub fn outgoers(&self, node: NodeId) -> Vec<NodeId> {
self.neighbours(node, PortDirection::Output)
}
fn neighbours(&self, node: NodeId, dir: PortDirection) -> Vec<NodeId> {
let mut out: Vec<NodeId> = self
.ports_of(node)
.filter(|p| p.direction == dir)
.flat_map(|p| self.edges_of_port(p.id))
.filter_map(|e| self.edges.get(e))
.filter_map(|e| {
let other = if dir == PortDirection::Input {
e.from
} else {
e.to
};
self.ports.get(&other).map(|p| p.node)
})
.collect();
out.sort();
out.dedup();
out
}
pub fn edge_nodes(&self, edge: &Edge) -> Option<(NodeId, NodeId)> {
Some((
self.ports.get(&edge.from)?.node,
self.ports.get(&edge.to)?.node,
))
}
pub fn children_of(&self, parent: NodeId) -> &[NodeId] {
self.children.get(&parent).map(Vec::as_slice).unwrap_or(&[])
}
pub fn subtree(&self, root: NodeId) -> Vec<NodeId> {
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(id) = stack.pop() {
if self.nodes.contains_key(&id) {
out.push(id);
stack.extend(self.children_of(id).iter().rev());
}
}
out
}
pub fn is_ancestor(&self, ancestor: NodeId, mut node: NodeId) -> bool {
while let Some(p) = self.nodes.get(&node).and_then(|n| n.parent) {
if p == ancestor {
return true;
}
node = p;
}
false
}
pub fn world_pos(&self, id: NodeId) -> Option<Vec2> {
let mut node = self.nodes.get(&id)?;
let mut pos = node.pos;
while let Some(p) = node.parent {
node = self.nodes.get(&p)?;
pos = pos.plus(node.pos);
}
Some(pos)
}
pub fn world_rect(&self, id: NodeId) -> Option<Rect> {
Some(Rect::from_origin_size(
self.world_pos(id)?,
self.nodes.get(&id)?.size,
))
}
pub fn to_local(&self, world: Vec2, parent: Option<NodeId>) -> Option<Vec2> {
match parent {
None => Some(world),
Some(p) => Some(world.minus(self.world_pos(p)?)),
}
}
pub fn bounds(&self) -> Option<Rect> {
self.order
.iter()
.filter_map(|id| self.world_rect(*id))
.reduce(|a, b| a.union(b))
}
pub fn nodes_in_rect(&self, rect: &Rect, fully: bool) -> Vec<NodeId> {
self.order
.iter()
.copied()
.filter(|id| {
self.world_rect(*id).is_some_and(|r| {
if fully {
rect.contains_rect(&r)
} else {
rect.intersects(&r)
}
})
})
.collect()
}
pub fn node_at(&self, p: Vec2) -> Option<NodeId> {
self.order
.iter()
.rev()
.copied()
.find(|id| self.world_rect(*id).is_some_and(|r| r.contains(p)))
}
pub fn topo_order(&self) -> Result<Vec<NodeId>, NodeId> {
let mut indeg: HashMap<NodeId, usize> = self.order.iter().map(|id| (*id, 0)).collect();
let mut succ: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
for e in self.edges.values() {
if let Some((a, b)) = self.edge_nodes(e) {
succ.entry(a).or_default().push(b);
*indeg.entry(b).or_default() += 1;
}
}
let mut queue: VecDeque<NodeId> = self
.order
.iter()
.copied()
.filter(|id| indeg[id] == 0)
.collect();
let mut out = Vec::with_capacity(self.order.len());
while let Some(n) = queue.pop_front() {
out.push(n);
for m in succ.get(&n).into_iter().flatten() {
let d = indeg.get_mut(m).expect("indegree entry");
*d -= 1;
if *d == 0 {
queue.push_back(*m);
}
}
}
if out.len() == self.order.len() {
Ok(out)
} else {
let done: HashSet<NodeId> = out.into_iter().collect();
Err(*self
.order
.iter()
.find(|id| !done.contains(id))
.expect("cycle member"))
}
}
pub fn has_cycle(&self) -> bool {
self.topo_order().is_err()
}
pub fn would_create_cycle(&self, from: NodeId, to: NodeId) -> bool {
if from == to {
return true;
}
let mut seen = HashSet::new();
let mut stack = vec![to];
while let Some(n) = stack.pop() {
if n == from {
return true;
}
if seen.insert(n) {
stack.extend(self.outgoers(n));
}
}
false
}
pub fn set_status(&mut self, id: NodeId, status: NodeStatus) -> bool {
match self.nodes.get_mut(&id) {
Some(n) if n.status != status => {
n.status = status;
self.bump();
true
}
_ => false,
}
}
pub fn set_edge_state(&mut self, id: EdgeId, state: crate::edge::EdgeState) -> bool {
match self.edges.get_mut(&id) {
Some(e) if e.state != state => {
e.state = state;
self.bump();
true
}
_ => false,
}
}
pub fn bring_to_front(&mut self, id: NodeId) {
let tree = self.subtree(id);
let set: HashSet<NodeId> = tree.iter().copied().collect();
let mut moved: Vec<NodeId> = self
.order
.iter()
.copied()
.filter(|n| set.contains(n))
.collect();
self.order.retain(|n| !set.contains(n));
self.order.append(&mut moved);
self.bump();
}
pub(crate) fn insert_node(
&mut self,
mut node: Node,
ports: Vec<Port>,
) -> Result<(), GraphError> {
if self.nodes.contains_key(&node.id) {
return Err(GraphError::DuplicateId(node.id.0));
}
if let Some(p) = node.parent
&& !self.nodes.contains_key(&p)
{
return Err(GraphError::MissingNode(p));
}
for p in &ports {
if self.ports.contains_key(&p.id) {
return Err(GraphError::DuplicateId(p.id.0));
}
}
self.reserve(node.id.0);
node.inputs.clear();
node.outputs.clear();
for mut p in ports {
self.reserve(p.id.0);
p.node = node.id;
match p.direction {
PortDirection::Input => node.inputs.push(p.id),
PortDirection::Output => node.outputs.push(p.id),
}
self.ports.insert(p.id, p);
}
if let Some(p) = node.parent {
self.children.entry(p).or_default().push(node.id);
}
self.order.push(node.id);
self.nodes.insert(node.id, node);
self.bump();
Ok(())
}
pub(crate) fn take_node(&mut self, id: NodeId) -> Result<(Node, Vec<Port>), GraphError> {
if !self.nodes.contains_key(&id) {
return Err(GraphError::MissingNode(id));
}
if !self.children_of(id).is_empty() || !self.connected_edges(id).is_empty() {
return Err(GraphError::NodeInUse(id));
}
let node = self.nodes.remove(&id).expect("checked");
let ports = node
.inputs
.iter()
.chain(node.outputs.iter())
.filter_map(|p| {
self.port_edges.remove(p);
self.ports.remove(p)
})
.collect();
if let Some(p) = node.parent
&& let Some(list) = self.children.get_mut(&p)
{
list.retain(|c| *c != id);
}
self.children.remove(&id);
self.order.retain(|n| *n != id);
self.bump();
Ok((node, ports))
}
pub(crate) fn insert_edge(&mut self, edge: Edge) -> Result<(), GraphError> {
if self.edges.contains_key(&edge.id) {
return Err(GraphError::DuplicateId(edge.id.0));
}
for p in [edge.from, edge.to] {
if !self.ports.contains_key(&p) {
return Err(GraphError::MissingPort(p));
}
}
self.reserve(edge.id.0);
self.port_edges.entry(edge.from).or_default().push(edge.id);
self.port_edges.entry(edge.to).or_default().push(edge.id);
self.edges.insert(edge.id, edge);
self.bump();
Ok(())
}
pub(crate) fn take_edge(&mut self, id: EdgeId) -> Result<Edge, GraphError> {
let edge = self.edges.remove(&id).ok_or(GraphError::MissingEdge(id))?;
for p in [edge.from, edge.to] {
if let Some(list) = self.port_edges.get_mut(&p) {
list.retain(|e| *e != id);
}
}
self.bump();
Ok(edge)
}
pub(crate) fn move_in_order(&mut self, id: NodeId, index: usize) {
if let Some(cur) = self.order.iter().position(|n| *n == id) {
self.order.remove(cur);
let i = index.min(self.order.len());
self.order.insert(i, id);
}
}
pub(crate) fn node_mut(&mut self, id: NodeId) -> Result<&mut Node, GraphError> {
self.nodes.get_mut(&id).ok_or(GraphError::MissingNode(id))
}
pub(crate) fn set_parent(
&mut self,
id: NodeId,
parent: Option<NodeId>,
) -> Result<(), GraphError> {
if let Some(p) = parent {
if !self.nodes.contains_key(&p) {
return Err(GraphError::MissingNode(p));
}
if p == id || self.is_ancestor(id, p) {
return Err(GraphError::WouldCreateCycle {
parent: p,
child: id,
});
}
}
let old = self.node_mut(id)?.parent;
if let Some(o) = old
&& let Some(list) = self.children.get_mut(&o)
{
list.retain(|c| *c != id);
}
if let Some(p) = parent {
self.children.entry(p).or_default().push(id);
}
self.node_mut(id)?.parent = parent;
Ok(())
}
pub fn add_node_with(
&mut self,
kind: &str,
pos: Vec2,
size: Size2,
inputs: usize,
outputs: usize,
) -> (NodeId, Vec<PortId>, Vec<PortId>) {
let id = self.alloc_node_id();
let mut ports = Vec::new();
let mut ins = Vec::new();
let mut outs = Vec::new();
for _ in 0..inputs {
let pid = self.alloc_port_id();
ins.push(pid);
ports.push(Port::new(pid, id, PortDirection::Input));
}
for _ in 0..outputs {
let pid = self.alloc_port_id();
outs.push(pid);
ports.push(Port::new(pid, id, PortDirection::Output));
}
self.insert_node(Node::new(id, kind, pos, size), ports)
.expect("fresh ids");
(id, ins, outs)
}
pub fn connect(&mut self, from: PortId, to: PortId) -> Result<EdgeId, GraphError> {
let id = self.alloc_edge_id();
self.insert_edge(Edge::new(id, from, to))?;
Ok(id)
}
pub fn to_json(&self) -> serde_json::Value {
let mut edges: Vec<Edge> = self.edges.values().cloned().collect();
edges.sort_by_key(|e| e.id);
let mut ports: Vec<Port> = self.ports.values().cloned().collect();
ports.sort_by_key(|p| p.id);
let doc = GraphDoc {
version: crate::FORMAT_VERSION,
next_id: self.next_id,
nodes: self.nodes().cloned().collect(),
ports,
edges,
};
serde_json::to_value(doc).expect("graph is serialisable")
}
pub fn from_json(value: serde_json::Value) -> Result<Self, GraphError> {
let doc: GraphDoc =
serde_json::from_value(value).map_err(|e| GraphError::Format(e.to_string()))?;
if doc.version > crate::FORMAT_VERSION {
return Err(GraphError::Format(format!(
"unsupported version {}",
doc.version
)));
}
let mut g = Graph::new();
let mut ports_by_node: HashMap<NodeId, Vec<Port>> = HashMap::new();
for p in doc.ports {
ports_by_node.entry(p.node).or_default().push(p);
}
let parents: HashMap<NodeId, Option<NodeId>> =
doc.nodes.iter().map(|n| (n.id, n.parent)).collect();
let depth = |mut id: NodeId| {
let mut d = 0usize;
while let Some(Some(p)) = parents.get(&id) {
d += 1;
id = *p;
if d > parents.len() {
break;
}
}
d
};
let mut nodes = doc.nodes;
let order: Vec<NodeId> = nodes.iter().map(|n| n.id).collect();
nodes.sort_by_key(|n| depth(n.id));
for n in nodes {
let mut ports = ports_by_node.remove(&n.id).unwrap_or_default();
let rank: HashMap<PortId, usize> = n
.inputs
.iter()
.chain(n.outputs.iter())
.enumerate()
.map(|(i, p)| (*p, i))
.collect();
ports.sort_by_key(|p| rank.get(&p.id).copied().unwrap_or(usize::MAX));
g.insert_node(n, ports)?;
}
g.order = order;
for e in doc.edges {
g.insert_edge(e)?;
}
g.next_id = g.next_id.max(doc.next_id);
Ok(g)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn chain() -> (Graph, Vec<NodeId>) {
let mut g = Graph::new();
let sz = Size2::new(100.0, 40.0);
let (a, _, ao) = g.add_node_with("a", Vec2::new(0.0, 0.0), sz, 0, 1);
let (b, bi, bo) = g.add_node_with("b", Vec2::new(200.0, 0.0), sz, 1, 1);
let (c, ci, _) = g.add_node_with("c", Vec2::new(400.0, 0.0), sz, 1, 0);
g.connect(ao[0], bi[0]).unwrap();
g.connect(bo[0], ci[0]).unwrap();
(g, vec![a, b, c])
}
#[test]
fn neighbours_and_topology() {
let (g, n) = chain();
assert_eq!(g.incomers(n[1]), vec![n[0]]);
assert_eq!(g.outgoers(n[1]), vec![n[2]]);
assert_eq!(g.connected_edges(n[1]).len(), 2);
assert_eq!(g.topo_order().unwrap(), n);
assert!(g.would_create_cycle(n[2], n[0]));
assert!(!g.would_create_cycle(n[0], n[2]));
}
#[test]
fn nested_world_positions() {
let mut g = Graph::new();
let (group, _, _) = g.add_node_with(
"group",
Vec2::new(100.0, 50.0),
Size2::new(300.0, 200.0),
0,
0,
);
let (child, _, _) =
g.add_node_with("c", Vec2::new(10.0, 20.0), Size2::new(50.0, 20.0), 0, 0);
g.set_parent(child, Some(group)).unwrap();
assert_eq!(g.world_pos(child), Some(Vec2::new(110.0, 70.0)));
assert_eq!(g.children_of(group), &[child]);
assert_eq!(
g.set_parent(group, Some(child)),
Err(GraphError::WouldCreateCycle {
parent: child,
child: group
})
);
assert_eq!(g.node_at(Vec2::new(115.0, 75.0)), Some(child));
}
#[test]
fn remove_requires_detached() {
let (mut g, n) = chain();
assert_eq!(g.take_node(n[1]).unwrap_err(), GraphError::NodeInUse(n[1]));
}
#[test]
fn json_round_trip() {
let (mut g, n) = chain();
g.set_parent(n[2], Some(n[1])).unwrap();
let json = g.to_json();
let back = Graph::from_json(json.clone()).unwrap();
assert_eq!(back.to_json(), json);
assert_eq!(back.topo_order().unwrap(), n);
assert_eq!(back.children_of(n[1]), &[n[2]]);
}
#[test]
fn rect_queries() {
let (g, n) = chain();
let r = Rect::from_corners(Vec2::new(-10.0, -10.0), Vec2::new(250.0, 50.0));
assert_eq!(g.nodes_in_rect(&r, false), vec![n[0], n[1]]);
assert_eq!(g.nodes_in_rect(&r, true), vec![n[0]]);
assert_eq!(g.bounds().unwrap().max, Vec2::new(500.0, 40.0));
}
}