mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-02 00:01:59 -10:00
Add Graphviz output to graphene-cli (#4838)
* Add Graphviz output to graphene-cli * Review * Use compiler node IDs * Simplify proto dump and hash EditorApi and RuntimeHandle by content --------- Co-authored-by: Dennis Kobert <[email protected]>
This commit is contained in:
1 parent
75f0da035b
commit
c180edeced
6 files changed
+328
-18
No files matched your search
Generated
+1
@@ -2157,6 +2157,7 @@ dependencies = [
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"preprocessor",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"wgpu",
|
||||
"wgpu-executor",
|
||||
|
||||
@@ -36,6 +36,7 @@ wgpu = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
clap = { workspace = true, features = ["cargo", "derive"] }
|
||||
image = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
wgpu-executor = { workspace = true, optional = true }
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
use graphene_std::simplify_identifier_name;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::error::Error;
|
||||
use std::io::Write;
|
||||
|
||||
#[derive(Clone, Copy, Debug, clap::ValueEnum)]
|
||||
pub enum Format {
|
||||
Text,
|
||||
Dot,
|
||||
}
|
||||
|
||||
pub type Document = HashMap<Vec<NodeId>, (String, Option<ProtoNodeIdentifier>)>;
|
||||
|
||||
pub fn document(network: &NodeNetwork, mut names: HashMap<Vec<NodeId>, String>) -> Document {
|
||||
network
|
||||
.recursive_nodes()
|
||||
.map(|(id, node, mut path)| {
|
||||
path.push(*id);
|
||||
let identifier = node.implementation.get_proto_node().cloned();
|
||||
let name = names.remove(&path).or_else(|| identifier.as_ref().map(|identifier| simplify_identifier_name(identifier.as_str())));
|
||||
(path, (name.unwrap_or_else(|| id.to_string()), identifier))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn legacy_names(document: &str) -> HashMap<Vec<NodeId>, String> {
|
||||
fn collect(network: &serde_json::Value, path: &[NodeId], names: &mut HashMap<Vec<NodeId>, String>) {
|
||||
for entry in network["persistent_metadata"]["node_metadata"].as_array().into_iter().flatten() {
|
||||
let Some(id) = entry[0].as_u64() else { continue };
|
||||
let path = [path, &[NodeId(id)]].concat();
|
||||
let metadata = &entry[1]["persistent_metadata"];
|
||||
let nested = &metadata["network_metadata"];
|
||||
collect(nested, &path, names);
|
||||
let name = metadata["display_name"].as_str().filter(|name| !name.is_empty());
|
||||
if let Some(name) = name.or(nested["persistent_metadata"]["reference"].as_str()) {
|
||||
names.insert(path, name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut names = HashMap::new();
|
||||
if let Ok(document) = serde_json::from_str::<serde_json::Value>(document) {
|
||||
collect(&document["network_interface"]["network_metadata"], &[], &mut names);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
Document,
|
||||
Value,
|
||||
Convert,
|
||||
Nullify,
|
||||
Expand,
|
||||
Scope,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Document => "",
|
||||
Kind::Value => "+value",
|
||||
Kind::Convert => "+convert",
|
||||
Kind::Nullify => "+nullify",
|
||||
Kind::Expand => "+expand",
|
||||
Kind::Scope => "+scope",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Node<'a> {
|
||||
proto: &'a ProtoNode,
|
||||
kind: Kind,
|
||||
origins: Vec<&'a [NodeId]>,
|
||||
inputs: Vec<usize>,
|
||||
consumers: Vec<usize>,
|
||||
constant: bool,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
pub fn print(network: &ProtoNetwork, document: &Document, format: Format, upstream: Option<&str>, downstream: Option<&str>, depth: Option<usize>) -> Result<(), Box<dyn Error>> {
|
||||
let mut position: HashMap<NodeId, usize> = HashMap::new();
|
||||
let mut nodes: Vec<Node> = Vec::with_capacity(network.nodes.len());
|
||||
for (id, proto) in &network.nodes {
|
||||
let path = proto.original_location.path.as_deref().unwrap_or_default();
|
||||
let origin = (1..=path.len()).rev().map(|n| &path[..n]).find(|prefix| document.contains_key(*prefix)).unwrap_or_default();
|
||||
if let Some(&n) = position.get(id) {
|
||||
let origins = &mut nodes[n].origins;
|
||||
if !origins.contains(&origin) {
|
||||
origins.push(origin);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let n = nodes.len();
|
||||
position.insert(*id, n);
|
||||
let inputs: Vec<_> = match &proto.construction_args {
|
||||
ConstructionArgs::Nodes(ids) => ids.iter().map(|input| position[input]).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for &input in &inputs {
|
||||
nodes[input].consumers.push(n);
|
||||
}
|
||||
let kind = kind(proto, origin, document);
|
||||
let constant = matches!(kind, Kind::Value | Kind::Convert | Kind::Nullify) && inputs.iter().all(|&input| nodes[input].constant);
|
||||
nodes.push(Node {
|
||||
proto,
|
||||
kind,
|
||||
origins: vec![origin],
|
||||
inputs,
|
||||
consumers: Vec::new(),
|
||||
constant,
|
||||
id: id.0,
|
||||
});
|
||||
}
|
||||
|
||||
let output = position[&network.output];
|
||||
let id = |n: usize| nodes[n].id.to_string();
|
||||
let location = |path: &[NodeId]| (1..=path.len()).map(|n| document[&path[..n]].0.as_str()).collect::<Vec<_>>().join("/");
|
||||
|
||||
let matching = |query: &str| {
|
||||
let located = |origin: &&[NodeId]| !origin.is_empty() && location(origin).contains(query);
|
||||
[false, true]
|
||||
.into_iter()
|
||||
.map(|shared| {
|
||||
(0..nodes.len())
|
||||
.filter(|&n| {
|
||||
let node = &nodes[n];
|
||||
id(n).starts_with(query) || node.proto.identifier.as_str().contains(query) || if shared { node.origins.iter().any(located) } else { node.origins.iter().all(located) }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.find(|matches| !matches.is_empty())
|
||||
.ok_or_else(|| format!("No proto node matches \"{query}\""))
|
||||
};
|
||||
let mut selected = vec![upstream.is_none() && downstream.is_none(); nodes.len()];
|
||||
if let Some(query) = upstream {
|
||||
reach(&nodes, matching(query)?, depth, |node| &node.inputs, &mut selected);
|
||||
}
|
||||
if let Some(query) = downstream {
|
||||
reach(&nodes, matching(query)?, depth, |node| &node.consumers, &mut selected);
|
||||
}
|
||||
|
||||
let mut out = std::io::BufWriter::new(std::io::stdout().lock());
|
||||
match format {
|
||||
Format::Text => {
|
||||
for (n, node) in nodes.iter().enumerate().filter(|(n, _)| selected[*n]) {
|
||||
let arguments = match &node.proto.construction_args {
|
||||
ConstructionArgs::Nodes(_) => format!("({})", node.inputs.iter().map(|&input| id(input)).collect::<Vec<_>>().join(", ")),
|
||||
ConstructionArgs::Value(value) => format!("{{{}}}", summary(value, 80)),
|
||||
ConstructionArgs::Inline(inline) => format!("{{{}}}", inline.expr),
|
||||
};
|
||||
let shared = if node.origins.len() > 1 { "(shared)" } else { "" };
|
||||
let provenance = [node.kind.tag(), &location(node.origins[0]), shared]
|
||||
.into_iter()
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let identifier = simplify_identifier_name(node.proto.identifier.as_str());
|
||||
writeln!(out, "{} = {identifier}{arguments} : {} # {provenance}", id(n), node.proto.call_argument)?;
|
||||
}
|
||||
}
|
||||
Format::Dot => {
|
||||
let metadata = graphene_std::registry::NODE_METADATA.lock().unwrap();
|
||||
let field = |node: &Node, index: usize| {
|
||||
let field = metadata.get(&node.proto.identifier).and_then(|metadata| metadata.fields.get(index));
|
||||
field.map_or_else(|| index.to_string(), |field| field.name.trim().to_string())
|
||||
};
|
||||
let drawn = |n: usize| selected[n] && !nodes[n].constant;
|
||||
|
||||
let mut networks: BTreeMap<&[NodeId], Vec<usize>> = BTreeMap::new();
|
||||
for n in (0..nodes.len()).filter(|&n| drawn(n)) {
|
||||
let network = match nodes[n].origins.as_slice() {
|
||||
[origin] => origin.split_last().map_or(&[][..], |(_, parent)| parent),
|
||||
_ => &[],
|
||||
};
|
||||
networks.entry(network).or_default().push(n);
|
||||
}
|
||||
|
||||
writeln!(out, "digraph proto {{")?;
|
||||
writeln!(out, "\trankdir=LR")?;
|
||||
writeln!(out, "\tnode [shape=box fontname=monospace]")?;
|
||||
for (cluster, (path, members)) in networks.iter().enumerate() {
|
||||
let indent = if path.is_empty() { "\t" } else { "\t\t" };
|
||||
if !path.is_empty() {
|
||||
writeln!(out, "\tsubgraph cluster_{cluster} {{")?;
|
||||
writeln!(out, "\t\tlabel={:?}", location(path))?;
|
||||
}
|
||||
for &n in members {
|
||||
let node = &nodes[n];
|
||||
let identifier = simplify_identifier_name(node.proto.identifier.as_str());
|
||||
let name = document.get(node.origins[0]).map_or("", |(name, _)| name.as_str());
|
||||
let name = if name == identifier { "" } else { name };
|
||||
let mut label = vec![identifier, format!("{} : {}", id(n), node.proto.call_argument)];
|
||||
let provenance = [node.kind.tag(), name].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" ");
|
||||
label.extend((!provenance.is_empty()).then_some(provenance));
|
||||
for (index, &input) in node.inputs.iter().enumerate().filter(|(_, input)| nodes[**input].constant) {
|
||||
label.extend(constant(&nodes, input).map(|value| format!("{}: {}", field(node, index), summary(value, 40))));
|
||||
}
|
||||
let inserted = if node.kind == Kind::Document { "" } else { " style=\"filled,dashed\" fillcolor=lightgrey" };
|
||||
let output = if n == output { " peripheries=2" } else { "" };
|
||||
writeln!(out, "{indent}{:?} [label={:?}{inserted}{output}]", id(n), label.join("\n"))?;
|
||||
}
|
||||
if !path.is_empty() {
|
||||
writeln!(out, "\t}}")?;
|
||||
}
|
||||
}
|
||||
|
||||
let mut stubs = HashSet::new();
|
||||
for &n in networks.values().flatten() {
|
||||
for (index, &input) in nodes[n].inputs.iter().enumerate().filter(|(_, input)| !nodes[**input].constant) {
|
||||
if !selected[input] && stubs.insert(input) {
|
||||
let label = format!("{}\n{}", simplify_identifier_name(nodes[input].proto.identifier.as_str()), id(input));
|
||||
writeln!(out, "\t{:?} [label={label:?} style=dotted]", id(input))?;
|
||||
}
|
||||
writeln!(out, "\t{:?} -> {:?} [headlabel={:?}]", id(input), id(n), field(&nodes[n], index))?;
|
||||
}
|
||||
}
|
||||
writeln!(out, "}}")?;
|
||||
}
|
||||
}
|
||||
out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kind(proto: &ProtoNode, origin: &[NodeId], document: &Document) -> Kind {
|
||||
let path = proto.original_location.path.as_deref().unwrap_or_default();
|
||||
let appended = path.len() > origin.len();
|
||||
match &proto.construction_args {
|
||||
ConstructionArgs::Value(value) if matches!(**value, TaggedValue::ContextModification(_)) => Kind::Nullify,
|
||||
_ if appended && path.last() == Some(&NodeId(10)) => Kind::Nullify,
|
||||
_ if proto.original_location.auto_convert_index.is_some() => Kind::Convert,
|
||||
ConstructionArgs::Value(_) => Kind::Value,
|
||||
_ if origin.is_empty() => Kind::Scope,
|
||||
_ if document[origin].1.as_ref() == Some(&proto.identifier) => Kind::Document,
|
||||
_ => Kind::Expand,
|
||||
}
|
||||
}
|
||||
|
||||
fn constant<'a>(nodes: &[Node<'a>], mut n: usize) -> Option<&'a TaggedValue> {
|
||||
loop {
|
||||
match &nodes[n].proto.construction_args {
|
||||
ConstructionArgs::Value(value) => return Some(&**value),
|
||||
ConstructionArgs::Nodes(_) => n = *nodes[n].inputs.first()?,
|
||||
ConstructionArgs::Inline(_) => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reach<'a>(nodes: &'a [Node], seeds: Vec<usize>, depth: Option<usize>, edges: impl Fn(&'a Node) -> &'a [usize], selected: &mut [bool]) {
|
||||
let mut distances = vec![None; nodes.len()];
|
||||
let mut queue = VecDeque::new();
|
||||
for n in seeds {
|
||||
distances[n] = Some(0);
|
||||
queue.push_back((n, 0));
|
||||
}
|
||||
while let Some((n, distance)) = queue.pop_front() {
|
||||
selected[n] = true;
|
||||
if distances[n] < Some(distance) {
|
||||
continue;
|
||||
}
|
||||
for &next in edges(&nodes[n]) {
|
||||
let cost = usize::from(matches!(nodes[next].kind, Kind::Document | Kind::Scope));
|
||||
let distance = distance + cost;
|
||||
if depth.is_some_and(|depth| distance > depth) || distances[next].is_some_and(|known| known <= distance) {
|
||||
continue;
|
||||
}
|
||||
distances[next] = Some(distance);
|
||||
if cost == 0 { queue.push_front((next, distance)) } else { queue.push_back((next, distance)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn summary(value: &TaggedValue, limit: usize) -> String {
|
||||
let text = match value {
|
||||
TaggedValue::ContextModification(modification) if modification.features.is_empty() => "keep nothing".to_string(),
|
||||
TaggedValue::ContextModification(modification) => format!("keep {}", modification.features.iter_names().map(|(name, _)| name).collect::<Vec<_>>().join(" | ")),
|
||||
value => format!("{value:?}"),
|
||||
};
|
||||
let text = match text.split_once('(') {
|
||||
Some((variant, inner)) if inner.strip_prefix(variant).is_some_and(|rest| !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')) => inner.strip_suffix(')').unwrap_or(inner).to_string(),
|
||||
_ => text,
|
||||
};
|
||||
match text.char_indices().nth(limit) {
|
||||
Some((index, _)) => format!("{}…", &text[..index]),
|
||||
None => text,
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod dump;
|
||||
mod export;
|
||||
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
@@ -30,11 +31,23 @@ pub struct App {
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum Command {
|
||||
/// Help message for compile.
|
||||
#[clap(group(clap::ArgGroup::new("filter").args(["upstream", "downstream"]).multiple(true)))]
|
||||
Compile {
|
||||
/// Print proto network
|
||||
#[clap(long, short = 'p')]
|
||||
print_proto: bool,
|
||||
/// Print the proto network in this format
|
||||
#[clap(long, short = 'f', value_enum)]
|
||||
format: Option<dump::Format>,
|
||||
|
||||
/// Only print the nodes matching this query and their inputs: a node ID prefix, or part of an identifier or document location
|
||||
#[clap(long, requires = "format")]
|
||||
upstream: Option<String>,
|
||||
|
||||
/// Only print the nodes matching this query and the nodes using them
|
||||
#[clap(long, requires = "format")]
|
||||
downstream: Option<String>,
|
||||
|
||||
/// Follow at most this many document nodes from the matching nodes, passing the nodes inserted between them for free
|
||||
#[clap(long, requires = "filter")]
|
||||
depth: Option<usize>,
|
||||
|
||||
/// Path to the .graphite document
|
||||
document: PathBuf,
|
||||
@@ -141,17 +154,21 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
|
||||
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
|
||||
let node_network = match &gdd {
|
||||
let print = matches!(app.command, Command::Compile { format: Some(_), .. });
|
||||
let (node_network, names) = match &gdd {
|
||||
Some(gdd) => {
|
||||
let declarations = gdd.declarations(gdd).await;
|
||||
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
node_network
|
||||
let (node_network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?;
|
||||
let references = networks.into_iter().filter_map(|network| Some((network.network_path, network.reference?)));
|
||||
let names = nodes.into_iter().filter_map(|node| Some(([node.network_path, vec![node.local_id]].concat(), node.display_name?)));
|
||||
(node_network, print.then(|| references.chain(names).filter(|(_, name)| !name.is_empty()).collect()))
|
||||
}
|
||||
None => {
|
||||
let document_string = std::fs::read_to_string(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
||||
load_network(&document_string)
|
||||
(load_network(&document_string), print.then(|| dump::legacy_names(&document_string)))
|
||||
}
|
||||
};
|
||||
let document = names.map(|names| dump::document(&node_network, names));
|
||||
|
||||
log::info!("Creating GPU context");
|
||||
let mut application_io = PlatformApplicationIo::new().await;
|
||||
@@ -177,9 +194,11 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
match app.command {
|
||||
Command::Compile { print_proto, .. } => {
|
||||
if print_proto {
|
||||
println!("{proto_graph}");
|
||||
Command::Compile {
|
||||
format, upstream, downstream, depth, ..
|
||||
} => {
|
||||
if let Some((format, document)) = format.zip(document) {
|
||||
dump::print(&proto_graph, &document, format, upstream.as_deref(), downstream.as_deref(), depth)?;
|
||||
}
|
||||
}
|
||||
Command::Export {
|
||||
@@ -246,7 +265,7 @@ fn init_logging(log_level: u8) {
|
||||
};
|
||||
let colors = ColoredLevelConfig::new().debug(Color::Magenta).info(Color::Green).error(Color::Red);
|
||||
fern::Dispatch::new()
|
||||
.chain(std::io::stdout())
|
||||
.chain(std::io::stderr())
|
||||
.level_for("wgpu", log::LevelFilter::Error)
|
||||
.level_for("naga", log::LevelFilter::Error)
|
||||
.level_for("wgpu_hal", log::LevelFilter::Error)
|
||||
|
||||
@@ -5,7 +5,6 @@ use glam::DVec2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::ptr::addr_of;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use vector_types::vector::style::RenderMode;
|
||||
@@ -93,7 +92,7 @@ impl<Io: Default> Default for EditorApi<Io> {
|
||||
|
||||
impl<Io> Hash for EditorApi<Io> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.application_io.as_ref().map_or(0, |io| io as *const _ as usize).hash(state);
|
||||
self.application_io.is_some().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +104,7 @@ impl<Io> CacheHash for EditorApi<Io> {
|
||||
|
||||
impl<Io> PartialEq for EditorApi<Io> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.application_io.as_ref().map_or(0, |io| addr_of!(io) as usize) == other.application_io.as_ref().map_or(0, |io| addr_of!(io) as usize)
|
||||
self.application_io.is_some() == other.application_io.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,9 +58,7 @@ impl PartialEq for RuntimeHandle {
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
fn cache_hash<H: Hasher>(&self, state: &mut H) {
|
||||
state.write_usize(Arc::as_ptr(&self.0) as usize);
|
||||
}
|
||||
fn cache_hash<H: Hasher>(&self, _state: &mut H) {}
|
||||
}
|
||||
|
||||
pub struct AsyncRuntime(Arc<RuntimeInner>);
|
||||
|
||||
Reference in new issue
Block a user