mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e445e4b965 | ||
|
|
45e3626579 | ||
|
|
b8b92cb822 | ||
|
|
f8d5dc1a21 |
No files matched your search
@@ -608,27 +608,39 @@ impl NodeNetwork {
|
||||
|
||||
/// Check there are no cycles in the graph (this should never happen).
|
||||
pub fn is_acyclic(&self) -> bool {
|
||||
let mut dependencies: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
|
||||
for (node_id, node) in &self.nodes {
|
||||
dependencies.insert(
|
||||
*node_id,
|
||||
node.inputs
|
||||
.iter()
|
||||
.filter_map(|input| if let NodeInput::Node { node_id, .. } = input { Some(*node_id) } else { None })
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
while !dependencies.is_empty() {
|
||||
let Some((&disconnected, _)) = dependencies.iter().find(|(_, l)| l.is_empty()) else {
|
||||
error!("Dependencies {dependencies:?}");
|
||||
return false;
|
||||
};
|
||||
dependencies.remove(&disconnected);
|
||||
for connections in dependencies.values_mut() {
|
||||
connections.retain(|&id| id != disconnected);
|
||||
// Count how many node-type inputs reference each node (its in-degree)
|
||||
let mut in_degree: HashMap<NodeId, usize> = self.nodes.keys().map(|&id| (id, 0)).collect();
|
||||
for node in self.nodes.values() {
|
||||
for input in &node.inputs {
|
||||
if let NodeInput::Node { node_id, .. } = input
|
||||
&& let Some(degree) = in_degree.get_mut(node_id)
|
||||
{
|
||||
*degree += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
|
||||
// Seed the queue with all nodes that have zero in-degree
|
||||
let mut queue: Vec<NodeId> = in_degree.iter().filter(|&(_, °)| deg == 0).map(|(&id, _)| id).collect();
|
||||
let mut visited = 0;
|
||||
|
||||
// Process nodes with zero in-degree, decrementing dependents
|
||||
while let Some(node_id) = queue.pop() {
|
||||
visited += 1;
|
||||
let Some(node) = self.nodes.get(&node_id) else { continue };
|
||||
for input in &node.inputs {
|
||||
if let NodeInput::Node { node_id: upstream_id, .. } = input
|
||||
&& let Some(degree) = in_degree.get_mut(upstream_id)
|
||||
{
|
||||
*degree -= 1;
|
||||
if *degree == 0 {
|
||||
queue.push(*upstream_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visited == self.nodes.len()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -951,71 +963,97 @@ impl NodeNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_id_node(&mut self, id: NodeId) -> Result<(), String> {
|
||||
let node = self.nodes.get(&id).ok_or_else(|| format!("Node with id {id} does not exist"))?.clone();
|
||||
if let DocumentNodeImplementation::ProtoNode(ident) = &node.implementation
|
||||
&& *ident == graphene_core::ops::identity::IDENTIFIER
|
||||
{
|
||||
assert_eq!(node.inputs.len(), 1, "Id node has more than one input");
|
||||
if let NodeInput::Node { node_id, output_index, .. } = node.inputs[0] {
|
||||
let node_input_output_index = output_index;
|
||||
// TODO fix
|
||||
if let Some(input_node) = self.nodes.get_mut(&node_id) {
|
||||
for &dep in &node.original_location.dependants[0] {
|
||||
input_node.original_location.dependants[output_index].push(dep);
|
||||
}
|
||||
}
|
||||
|
||||
let input_node_id = node_id;
|
||||
for output in self.nodes.values_mut() {
|
||||
for (index, input) in output.inputs.iter_mut().enumerate() {
|
||||
if let NodeInput::Node {
|
||||
node_id: output_node_id,
|
||||
output_index: output_output_index,
|
||||
..
|
||||
} = input && *output_node_id == id
|
||||
{
|
||||
*output_node_id = input_node_id;
|
||||
*output_output_index = node_input_output_index;
|
||||
|
||||
let input_source = &mut output.original_location.inputs_source;
|
||||
for source in node.original_location.inputs(index) {
|
||||
input_source.insert(source, index);
|
||||
}
|
||||
}
|
||||
}
|
||||
for node_input in self.exports.iter_mut() {
|
||||
if let NodeInput::Node { node_id, output_index, .. } = node_input
|
||||
&& *node_id == id
|
||||
{
|
||||
*node_id = input_node_id;
|
||||
*output_index = node_input_output_index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.nodes.remove(&id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Strips out any [`graphene_core::ops::IdentityNode`]s that are unnecessary.
|
||||
/// This is done in a single batch pass rather than per-node to avoid O(N×M) iteration.
|
||||
pub fn remove_redundant_id_nodes(&mut self) {
|
||||
let id_nodes = self
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, node)| {
|
||||
matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::identity::IDENTIFIER)
|
||||
&& node.inputs.len() == 1
|
||||
&& matches!(node.inputs[0], NodeInput::Node { .. })
|
||||
})
|
||||
.map(|(id, _)| *id)
|
||||
.collect::<Vec<_>>();
|
||||
for id in id_nodes {
|
||||
if let Err(e) = self.remove_id_node(id) {
|
||||
log::warn!("{e}")
|
||||
// Step 1: Identify all identity nodes and build a remapping table.
|
||||
// Each identity node maps to its upstream (node_id, output_index).
|
||||
let mut remap: HashMap<NodeId, (NodeId, usize)> = HashMap::new();
|
||||
for (id, node) in &self.nodes {
|
||||
if matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::identity::IDENTIFIER)
|
||||
&& node.inputs.len() == 1
|
||||
&& let NodeInput::Node { node_id, output_index, .. } = node.inputs[0]
|
||||
{
|
||||
remap.insert(*id, (node_id, output_index));
|
||||
}
|
||||
}
|
||||
|
||||
if remap.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 2: Resolve transitive chains (identity → identity → real node).
|
||||
// Use path compression so each identity node maps directly to the final real node.
|
||||
let resolved: HashMap<NodeId, (NodeId, usize)> = remap
|
||||
.keys()
|
||||
.map(|&id| {
|
||||
let mut current = id;
|
||||
let mut output_index = 0;
|
||||
while let Some(&(next_id, next_output_index)) = remap.get(¤t) {
|
||||
current = next_id;
|
||||
output_index = next_output_index;
|
||||
}
|
||||
(id, (current, output_index))
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Step 3: Propagate dependant metadata from each identity node to its resolved upstream node.
|
||||
// Collect the metadata first to avoid borrow conflicts.
|
||||
let dependant_updates: Vec<(NodeId, usize, Vec<NodeId>)> = resolved
|
||||
.iter()
|
||||
.filter_map(|(id_node, (target_id, target_output_index))| {
|
||||
let node = self.nodes.get(id_node)?;
|
||||
let deps = node.original_location.dependants.first().cloned().unwrap_or_default();
|
||||
if deps.is_empty() { None } else { Some((*target_id, *target_output_index, deps)) }
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (target_id, target_output_index, deps) in dependant_updates {
|
||||
if let Some(input_node) = self.nodes.get_mut(&target_id) {
|
||||
while input_node.original_location.dependants.len() <= target_output_index {
|
||||
input_node.original_location.dependants.push(Vec::new());
|
||||
}
|
||||
input_node.original_location.dependants[target_output_index].extend(deps);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: Collect inputs_source metadata from identity nodes for use during rewriting.
|
||||
let id_node_locations: HashMap<NodeId, OriginalLocation> = resolved.keys().filter_map(|id| Some((*id, self.nodes.get(id)?.original_location.clone()))).collect();
|
||||
|
||||
// Step 5: Single pass over all non-identity nodes to rewrite references.
|
||||
for (_, node) in self.nodes.iter_mut() {
|
||||
for (index, input) in node.inputs.iter_mut().enumerate() {
|
||||
if let NodeInput::Node {
|
||||
node_id: output_node_id,
|
||||
output_index: output_output_index,
|
||||
..
|
||||
} = input && let Some(&(resolved_id, resolved_output_index)) = resolved.get(output_node_id)
|
||||
{
|
||||
// Propagate inputs_source metadata from the identity node
|
||||
if let Some(id_location) = id_node_locations.get(output_node_id) {
|
||||
for source in id_location.inputs(index) {
|
||||
node.original_location.inputs_source.insert(source, index);
|
||||
}
|
||||
}
|
||||
|
||||
*output_node_id = resolved_id;
|
||||
*output_output_index = resolved_output_index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6: Rewrite exports.
|
||||
for export in self.exports.iter_mut() {
|
||||
if let NodeInput::Node { node_id, output_index, .. } = export {
|
||||
if let Some(&(resolved_id, resolved_output_index)) = resolved.get(node_id) {
|
||||
*node_id = resolved_id;
|
||||
*output_index = resolved_output_index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 7: Remove all identity nodes.
|
||||
self.nodes.retain(|id, _| !resolved.contains_key(id));
|
||||
}
|
||||
|
||||
/// Converts the `DocumentNode`s with a `DocumentNodeImplementation::Extract` into a `ClonedNode` that returns
|
||||
|
||||
@@ -17,8 +17,8 @@ impl Compiler {
|
||||
let proto_networks = network.into_proto_networks();
|
||||
|
||||
proto_networks.map(move |mut proto_network| {
|
||||
proto_network.insert_context_nullification_nodes()?;
|
||||
proto_network.generate_stable_node_ids();
|
||||
let outwards_edges = proto_network.insert_context_nullification_nodes()?;
|
||||
proto_network.generate_stable_node_ids(&outwards_edges);
|
||||
Ok(proto_network)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ pub use core_types::registry::*;
|
||||
use core_types::*;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
|
||||
@@ -232,49 +232,19 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
/// Construct a hashmap containing a list of the nodes that depend on this proto network.
|
||||
pub fn collect_outwards_edges(&self) -> HashMap<NodeId, Vec<NodeId>> {
|
||||
let mut edges: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
|
||||
for (id, node) in &self.nodes {
|
||||
if let ConstructionArgs::Nodes(ref_nodes) = &node.construction_args {
|
||||
for ref_id in ref_nodes {
|
||||
self.check_ref(ref_id, id);
|
||||
edges.entry(*ref_id).or_default().push(*id)
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
/// Convert all node IDs to be stable (based on the hash generated by [`ProtoNode::stable_node_id`]).
|
||||
/// This function requires that the graph be topologically sorted.
|
||||
pub fn generate_stable_node_ids(&mut self) {
|
||||
debug_assert!(self.is_topologically_sorted());
|
||||
let outwards_edges = self.collect_outwards_edges();
|
||||
|
||||
/// This function requires that the graph be topologically sorted with dense sequential IDs (0..N).
|
||||
/// Accepts pre-computed outwards edges to avoid redundant graph traversal.
|
||||
pub fn generate_stable_node_ids(&mut self, outwards_edges: &Vec<Vec<NodeId>>) {
|
||||
for index in 0..self.nodes.len() {
|
||||
let Some(sni) = self.nodes[index].1.stable_node_id() else {
|
||||
panic!("failed to generate stable node id for node {:#?}", self.nodes[index].1);
|
||||
};
|
||||
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
|
||||
self.replace_node_id(outwards_edges, NodeId(index as u64), sni);
|
||||
self.nodes[index].0 = sni;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Remove
|
||||
/// Create a hashmap with the list of nodes this proto network depends on/uses as inputs.
|
||||
pub fn collect_inwards_edges(&self) -> HashMap<NodeId, Vec<NodeId>> {
|
||||
let mut edges: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
|
||||
for (id, node) in &self.nodes {
|
||||
if let ConstructionArgs::Nodes(ref_nodes) = &node.construction_args {
|
||||
for ref_id in ref_nodes {
|
||||
self.check_ref(ref_id, id);
|
||||
edges.entry(*id).or_default().push(*ref_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
fn collect_inwards_edges_with_mapping(&self) -> (Vec<Vec<usize>>, FxHashMap<NodeId, usize>) {
|
||||
let id_map: FxHashMap<_, _> = self.nodes.iter().enumerate().map(|(idx, (id, _))| (*id, idx)).collect();
|
||||
|
||||
@@ -294,9 +264,32 @@ impl ProtoNetwork {
|
||||
(inwards_edges, id_map)
|
||||
}
|
||||
|
||||
/// Returns true if node IDs are already dense sequential indices (0, 1, 2, ..., N-1).
|
||||
fn has_dense_ids(&self) -> bool {
|
||||
self.nodes.iter().enumerate().all(|(idx, (id, _))| id.0 as usize == idx)
|
||||
}
|
||||
|
||||
/// Collect inwards edges when node IDs are already dense sequential (0..N), skipping HashMap construction.
|
||||
fn collect_inwards_edges_dense(&self) -> Vec<Vec<usize>> {
|
||||
let mut inwards_edges = vec![Vec::new(); self.nodes.len()];
|
||||
for (node_id, node) in &self.nodes {
|
||||
let node_index = node_id.0 as usize;
|
||||
|
||||
if let ConstructionArgs::Nodes(ref_nodes) = &node.construction_args {
|
||||
for ref_id in ref_nodes {
|
||||
self.check_ref(ref_id, node_id);
|
||||
inwards_edges[node_index].push(ref_id.0 as usize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inwards_edges
|
||||
}
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||
/// Returns the outwards edges of the final sorted graph for reuse by subsequent passes.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<Vec<Vec<NodeId>>, String> {
|
||||
// Perform topological sort once
|
||||
self.reorder_ids()?;
|
||||
|
||||
@@ -305,7 +298,8 @@ impl ProtoNetwork {
|
||||
// Perform topological sort a second time to integrate the new nodes
|
||||
self.reorder_ids()?;
|
||||
|
||||
Ok(())
|
||||
// Compute outwards edges on the now-sorted dense graph (node IDs are 0..N)
|
||||
Ok(self.collect_outwards_edges_dense())
|
||||
}
|
||||
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId {
|
||||
@@ -425,13 +419,11 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
/// Update all of the references to a node ID in the graph with a new ID named `compose_node_id`.
|
||||
fn replace_node_id(&mut self, outwards_edges: &HashMap<NodeId, Vec<NodeId>>, node_id: NodeId, replacement_node_id: NodeId) {
|
||||
// Update references in other nodes to use the new node
|
||||
if let Some(referring_nodes) = outwards_edges.get(&node_id) {
|
||||
for &referring_node_id in referring_nodes {
|
||||
let (_, referring_node) = &mut self.nodes[referring_node_id.0 as usize];
|
||||
referring_node.map_ids(|id| if id == node_id { replacement_node_id } else { id })
|
||||
}
|
||||
/// Uses dense Vec-indexed outwards edges (requires sequential node IDs 0..N).
|
||||
fn replace_node_id(&mut self, outwards_edges: &[Vec<NodeId>], node_id: NodeId, replacement_node_id: NodeId) {
|
||||
for &referring_node_id in &outwards_edges[node_id.0 as usize] {
|
||||
let (_, referring_node) = &mut self.nodes[referring_node_id.0 as usize];
|
||||
referring_node.map_ids(|id| if id == node_id { replacement_node_id } else { id })
|
||||
}
|
||||
|
||||
if self.output == node_id {
|
||||
@@ -445,12 +437,26 @@ impl ProtoNetwork {
|
||||
});
|
||||
}
|
||||
|
||||
/// Collect outwards edges using dense Vec indexing. Requires node IDs to be sequential 0..N
|
||||
/// (i.e., the graph has been through `reorder_ids`).
|
||||
fn collect_outwards_edges_dense(&self) -> Vec<Vec<NodeId>> {
|
||||
let mut edges = vec![Vec::new(); self.nodes.len()];
|
||||
for (id, node) in &self.nodes {
|
||||
if let ConstructionArgs::Nodes(ref_nodes) = &node.construction_args {
|
||||
for ref_id in ref_nodes {
|
||||
self.check_ref(ref_id, id);
|
||||
edges[ref_id.0 as usize].push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
// Based on https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
|
||||
// This approach excludes nodes that are not connected
|
||||
pub fn topological_sort(&self) -> Result<(Vec<NodeId>, FxHashMap<NodeId, usize>), String> {
|
||||
let (inwards_edges, id_map) = self.collect_inwards_edges_with_mapping();
|
||||
fn topological_sort_from_edges(&self, inwards_edges: &[Vec<usize>], output_index: usize) -> Result<Vec<NodeId>, String> {
|
||||
let mut sorted = Vec::with_capacity(self.nodes.len());
|
||||
let mut stack = vec![id_map[&self.output]];
|
||||
let mut stack = vec![output_index];
|
||||
let mut state = vec![NodeState::Unvisited; self.nodes.len()];
|
||||
|
||||
while let Some(&node_index) = stack.last() {
|
||||
@@ -480,36 +486,29 @@ impl ProtoNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
Ok((sorted, id_map))
|
||||
Ok(sorted)
|
||||
}
|
||||
|
||||
fn is_topologically_sorted(&self) -> bool {
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
let inwards_edges = self.collect_inwards_edges();
|
||||
for (id, _) in &self.nodes {
|
||||
for &dependency in inwards_edges.get(id).unwrap_or(&Vec::new()) {
|
||||
if !visited.contains(&dependency) {
|
||||
dbg!(id, dependency);
|
||||
dbg!(&visited);
|
||||
dbg!(&self.nodes);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
visited.insert(*id);
|
||||
}
|
||||
true
|
||||
pub fn topological_sort(&self) -> Result<(Vec<NodeId>, FxHashMap<NodeId, usize>), String> {
|
||||
let (inwards_edges, id_map) = self.collect_inwards_edges_with_mapping();
|
||||
let output_index = id_map[&self.output];
|
||||
let sorted = self.topological_sort_from_edges(&inwards_edges, output_index)?;
|
||||
Ok((sorted, id_map))
|
||||
}
|
||||
|
||||
/// Sort the nodes vec so it is in a topological order. This ensures that no node takes an input from a node that is found later in the list.
|
||||
fn reorder_ids(&mut self) -> Result<(), String> {
|
||||
let (order, _id_map) = self.topological_sort()?;
|
||||
|
||||
// // Map of node ids to their current index in the nodes vector
|
||||
// let current_positions: FxHashMap<_, _> = self.nodes.iter().enumerate().map(|(pos, (id, _))| (*id, pos)).collect();
|
||||
|
||||
// // Map of node ids to their new index based on topological order
|
||||
let new_positions: FxHashMap<_, _> = order.iter().enumerate().map(|(pos, id)| (self.nodes[id.0 as usize].0, pos)).collect();
|
||||
// When node IDs are already dense sequential (0..N), skip building the FxHashMap id_map
|
||||
let (order, new_positions) = if self.has_dense_ids() {
|
||||
let inwards_edges = self.collect_inwards_edges_dense();
|
||||
let order = self.topological_sort_from_edges(&inwards_edges, self.output.0 as usize)?;
|
||||
let new_positions: FxHashMap<_, _> = order.iter().enumerate().map(|(pos, id)| (*id, pos)).collect();
|
||||
(order, new_positions)
|
||||
} else {
|
||||
let (order, _) = self.topological_sort()?;
|
||||
let new_positions: FxHashMap<_, _> = order.iter().enumerate().map(|(pos, id)| (self.nodes[id.0 as usize].0, pos)).collect();
|
||||
(order, new_positions)
|
||||
};
|
||||
// assert_eq!(id_map, current_positions);
|
||||
|
||||
// Create a new nodes vector based on the topological order
|
||||
@@ -941,10 +940,10 @@ mod test {
|
||||
#[test]
|
||||
fn stable_node_id_generation() {
|
||||
let mut construction_network = test_network();
|
||||
construction_network
|
||||
let outwards_edges = construction_network
|
||||
.insert_context_nullification_nodes()
|
||||
.expect("Error when calling 'insert_context_nullification_nodes' on 'construction_network.");
|
||||
construction_network.generate_stable_node_ids();
|
||||
construction_network.generate_stable_node_ids(&outwards_edges);
|
||||
assert_eq!(construction_network.nodes[0].1.identifier.as_str(), "value");
|
||||
let ids: Vec<_> = construction_network.nodes.iter().map(|(id, _)| *id).collect();
|
||||
|
||||
|
||||
Reference in new issue
Block a user