Compare commits

..
Author SHA1 Message Date
Dennis Kobert c54608c12d Refactor node graph macro 2026-11-30 17:51:01 +01:00
Keavon Chambers c403654745 Add a #[graph] macro for defining subgraph nodes as Rust functions 2026-11-26 12:28:05 -08:00
Keavon Chambers 6c3232ee8c Add a "New Custom Node" button to replace the 'Custom Node' catalog node (#5030) 2026-11-26 04:37:18 -08:00
Keavon Chambers 30164b921e New node: 'Feather' (#5028) 2026-11-26 02:30:33 -08:00
Keavon Chambers b10aa51efb Allow the 'Mask' node to mask any graphic with any other graphic (#5027) 2026-11-26 00:20:22 -08:00
Keavon Chambers 5d00e45354 Add gloss contours, bevel profiles, and textures to the 'Bevel & Emboss' node (#5026) 2026-11-25 22:16:50 -08:00
Keavon Chambers 69c0dd140d Add support to the 'Outline' node for any graphic as paint, plus contour gradients (#5025)
Allow any paint in the 'Outline' node and add contour gradients
2026-11-25 20:02:34 -08:00
Keavon Chambers 9a8269c953 Add a "Blend Mode" parameter to the 'Drop/Inner Shadow', 'Outer/Inner Glow', 'Satin', and 'Outline' effect nodes (#5024)
Add a "Blend Mode" parameter to the '* Shadow', '* Glow', 'Satin', and 'Outline' effect nodes
2026-11-25 18:59:28 -08:00
Timon 76361baaa1 Replace missing resource warnings with a 'Missing Resource' node that reports an error (#5018)
* Revert "Fix documents not rendering when a font or image is missing or fails to load (#4986)"

* Stop holding back rendering for resources that failed to load

* Recompile the graph when a resource loads

* Place a missing resource node for resources without a hash

* Evaluate a missing resource as the empty resource with its error

* Fix tests
2026-11-26 01:13:19 +00:00
Keavon Chambers f569120bf6 New node: 'Bevel & Emboss' (#5023)
New node: 'Bevel & Emboss', which gives graphics a raised or sunken look
2026-11-25 14:50:50 -08:00
Timon 0df1e16233 Move network output tracking out of the executor into a handle returned by updates (#5019)
* Let the dynamic executor hold several networks, each executed and kept alive by a handle to its output

* Review
2026-11-25 22:19:19 +00:00
Aditya Amol KuchekarandDennis Kobert 65bb0ff838 Fix dangling inputs when a History panel step is removed (#5017)
* Fix dangling inputs when a history step is removed

A node the line never saw gets a placeholder tombstone, which holds no
inputs, so reconnect returned nothing instead of falling back to the
primary input history kept. The input was left naming a node the
document no longer has, and that state is what history folds to.

* Share the history simulation harness and add a regression test

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-25 22:08:20 +00:00
Keavon Chambers d5a7504e3a New nodes: 'Inner Glow', 'Satin', and 'Outline' (#5022) 2026-11-25 14:14:26 -08:00
Keavon Chambers fa65c1f8dc Replace the 'Color Overlay' node with a 'Paint Overlay' node supporting any graphic (#5020)
Replace the 'Color Overlay' node with a 'Paint Overlay' node using any graphic
2026-11-25 13:54:46 -08:00
Keavon Chambers 264d8493ef Fix the color picker's gradient midpoint diamonds being invisible and undraggable 2026-11-25 04:13:33 -08:00
Timon 68b7c25f52 New node: 'SVG to Graphic' (#5016)
* Add svg-convert crate

* Add SVG to Graphic node

* Convert SVG group opacity

* Convert SVG text as outlines

* Convert nested SVG images

* Convert SVG strokes

* Convert SVG paint order

* Convert SVG blend modes

* Convert SVG gradients

* Convert SVG raster images

* Convert SVG clip paths

* Convert SVG even-odd fills

* Convert SVG masks

* Convert SVG blur and drop shadow filters

* Convert SVG patterns

* Paint a zero-length SVG linear gradient as the color of its last stop
2026-11-25 11:40:50 +00:00
Keavon Chambers 10b57c9719 Make the 'Scatter Points' node stable under local shape edits and much faster (#5013) 2026-11-25 02:40:11 -08:00
Keavon Chambers b1c0b6c173 Redesign the 'Mandelbrot' node with advanced fractal controls and deep zoom support (#5010)
Expand the 'Mandelbrot' node with fractal controls and deep zoom
2026-11-25 01:32:57 -08:00
Keavon Chambers 16fc449a3c Raise the canvas zoom limit and fix Ctrl+0 when nothing can be framed (#5015) 2026-11-25 06:18:45 +00:00
Timon 411d9f64b3 Fix the loading indicator not showing, and add a loading progress bar on web (#5012)
* Fix the loading indicator being hidden before the Wasm binary loads

* Center the loading indicator

* Show a download progress bar while the Wasm binary loads

* Show the progress bar as soon as the Wasm download starts

* Check for an update before starting the editor
2026-11-24 18:27:32 +00:00
176 changed files with 20948 additions and 4303 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
Generated
+26
View File
@@ -2534,6 +2534,18 @@ dependencies = [
"smallvec",
]
[[package]]
name = "graph-text"
version = "0.0.0"
dependencies = [
"convert_case 0.12.0",
"core-types",
"glam",
"log",
"proc-macro2",
"syn 3.0.9",
]
[[package]]
name = "graphene-animation"
version = "0.0.0"
@@ -2664,6 +2676,7 @@ dependencies = [
"futures",
"glam",
"graph-craft",
"graph-text",
"graphene-application-io",
"graphene-canvas-utils",
"graphene-core",
@@ -2679,6 +2692,7 @@ dependencies = [
"rendering",
"repeat-nodes",
"reqwest",
"svg-convert",
"text-nodes",
"thiserror 2.0.21",
"tokio",
@@ -7163,6 +7177,18 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "svg-convert"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graphic-types",
"kurbo",
"linesweeper",
"usvg",
]
[[package]]
name = "svgtypes"
version = "0.16.2"
+2
View File
@@ -93,12 +93,14 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" }
graph-text = { path = "node-graph/libraries/graph-text" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
svg-convert = { path = "node-graph/libraries/svg-convert" }
brush-nodes = { path = "node-graph/nodes/brush" }
blending-nodes = { path = "node-graph/nodes/blending" }
graphene-core = { path = "node-graph/nodes/gcore" }
BIN
View File
Binary file not shown.
+2
View File
@@ -52,9 +52,11 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
#[cfg(test)]
mod tests {
mod bookkeeping;
mod branch_simulation;
mod crdt;
mod history_simulation;
mod projection;
mod round_trip;
mod sessions;
mod simulation;
}
+2 -1
View File
@@ -382,7 +382,8 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
if !visited.insert(current) {
return None;
}
let (in_network, input) = match registry.removed_nodes.get(&current) {
// A placeholder knows nothing of the node's network or primary input, so what history kept decides instead
let (in_network, input) = match registry.removed_nodes.get(&current).filter(|tombstone| !tombstone.placeholder) {
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
None => known.primary.get(&current).cloned()?,
};
@@ -0,0 +1,238 @@
//! Deterministic simulation of a document whose chains branch off inputs past the primary one, with every history
//! operation mixed in. After every operation nothing may name a node the document no longer has.
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
/// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Place {
Export(u32),
Input(NodeId, u32),
}
fn place_value(registry: &Registry, place: Place) -> Option<NodeInput> {
match place {
Place::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
Place::Export(index) => registry.networks.get(&ROOT_NETWORK)?.exports.get(index as usize)?.target.clone(),
}
}
fn set_place(place: Place, input: NodeInput) -> RegistryDelta {
match place {
Place::Input(id, index) => RegistryDelta::ChangeNodeInput { id, index, new_input: input },
Place::Export(index) => RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index,
export: Some(input),
},
}
}
/// Every slot naming a node, and the node it names, in a fixed order.
fn naming_places(registry: &Registry) -> Vec<(Place, NodeId)> {
let mut places = Vec::new();
for (&id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = slot.input {
places.push((Place::Input(id, index as u32), named));
}
}
}
if let Some(network) = registry.networks.get(&ROOT_NETWORK) {
for (index, slot) in network.exports.iter().enumerate() {
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
places.push((Place::Export(index as u32), named));
}
}
}
places.sort();
places
}
/// The slot naming `node`, of which a document built this way has one.
fn consumer_place(registry: &Registry, node: NodeId) -> Option<Place> {
naming_places(registry).into_iter().find(|(_, named)| *named == node).map(|(place, _)| place)
}
/// Every node under `place`, through any input.
fn under(registry: &Registry, place: Place) -> Vec<NodeId> {
let mut seen: Vec<NodeId> = Vec::new();
let mut queue: Vec<NodeId> = Vec::new();
if let Some(NodeInput::Node { id, .. }) = place_value(registry, place) {
queue.push(id);
}
while let Some(id) = queue.pop() {
if seen.contains(&id) || !registry.node_instances.contains_key(&id) {
continue;
}
seen.push(id);
for slot in &registry.node_instances[&id].inputs {
if let NodeInput::Node { id: next, .. } = slot.input {
queue.push(next);
}
}
}
seen
}
/// Nodes chained off the export and off inputs past the primary one.
struct Branching;
impl Scenario for Branching {
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
let nodes = under(&registry, Place::Export(0));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let make = |first: NodeInput, second: NodeInput| {
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = first;
node.inputs[1].input = second;
node
};
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
let plain: Vec<NodeId> = nodes
.iter()
.copied()
.filter(|id| !matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect();
match random.below(12) {
// Draw a node on top of the chain off the export
0..=2 => {
let id = session.next_node_id();
let node = make(layers.first().map_or_else(|| value(0), |&top| on(top)), value(random.below(100)));
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
if let Some(&under) = layers.first() {
ops.push(super::crdt::change_node_attribute(under, "position", serde_json::json!(random.below(100))));
}
ops
}
// Hang a node on an input past the primary one, over whatever is there already
3..=5 => {
let Some(host) = random.pick(&nodes) else { return Vec::new() };
let id = session.next_node_id();
let first = match place_value(&registry, Place::Input(host, 1)) {
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
_ => value(0),
};
let node = make(first, value(random.below(100)));
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::ChangeNodeInput {
id: host,
index: 1,
new_input: on(id),
},
]);
ops
}
// Delete a node, reconnecting everything that named it to what it rested on
6..=7 => {
let Some(node) = random.pick(&plain) else { return Vec::new() };
let snapshot = registry.node_instances[&node].clone();
let mut ops: Vec<RegistryDelta> = naming_places(&registry)
.into_iter()
.filter(|(_, named)| *named == node)
.map(|(place, _)| set_place(place, below(&registry, node)))
.collect();
ops.push(RegistryDelta::RemoveNode { id: node, snapshot });
ops
}
// Move a node to the top of the chain off the export
8 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
let Some(place) = consumer_place(&registry, layer) else { return Vec::new() };
vec![
set_place(place, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a node's value
9..=10 => {
let Some(node) = random.pick(&plain) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: node,
index: 1,
new_input: value(random.below(100)),
}]
}
// Cut the chain off an input past the primary one, taking its nodes with it
_ => {
let hosts: Vec<NodeId> = nodes
.iter()
.copied()
.filter(|id| matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect();
let Some(host) = random.pick(&hosts) else { return Vec::new() };
let mut gone = under(&registry, Place::Input(host, 1));
// Nothing outside the cut may name a node inside it, or taking them would leave that naming nothing
let held = naming_places(&registry)
.into_iter()
.any(|(place, named)| gone.contains(&named) && place != Place::Input(host, 1) && !matches!(place, Place::Input(owner, _) if gone.contains(&owner)));
if held {
return Vec::new();
}
let mut ops = vec![RegistryDelta::ChangeNodeInput {
id: host,
index: 1,
new_input: value(random.below(100)),
}];
gone.sort();
for id in gone {
ops.push(RegistryDelta::RemoveNode {
id,
snapshot: registry.node_instances[&id].clone(),
});
}
ops
}
}
}
/// Nothing names a node the document no longer has, every node is built from a network it still has, and no node
/// input holds the empty export's value. A node may feed nothing or more than one input.
fn assert_well_formed(context: &str, registry: &Registry) {
for (place, named) in naming_places(registry) {
assert!(registry.node_instances.contains_key(&named), "{context}: {place:?} names {named:?}, which is gone");
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
for (index, slot) in node.inputs.iter().enumerate() {
assert_ne!(slot.input, empty_export(), "{context}: input {index} of {id:?} holds the empty export's value");
}
}
}
}
#[test]
fn history_operations_keep_a_branching_document_whole() {
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
for seed in 0..seeds {
simulate::<Branching>(seed, steps, &mut Vec::new());
}
}
@@ -1,64 +1,12 @@
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
//! head moves must hold the same document.
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation mixed in.
//! After every operation the document must still be a well-formed stack.
//!
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
use std::collections::HashSet;
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// The layers from the top of the stack down, following each layer's first input.
fn stack(registry: &Registry) -> Vec<NodeId> {
let mut layers = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
break;
}
layers.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
layers
}
/// What feeds into `layer` from below.
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
registry.node_instances[&layer].inputs[0].input.clone()
}
/// Points what sits directly above `layer`, a layer or the export, at `input`.
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
let layers = stack(registry);
@@ -76,365 +24,124 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
}
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
/// A single stack of layers off the export.
struct Stack;
fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
ops
}
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
}
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = std::collections::HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The layers live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
fn assert_consistent(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
impl Scenario for Stack {
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
ops
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
8 => {
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
continue;
};
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A layer the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A layer the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
}
#[test]
fn history_operations_keep_the_stack_whole_and_peers_converged() {
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
for seed in 0..seeds {
simulate(seed, steps, &mut Vec::new());
simulate::<Stack>(seed, steps, &mut Vec::new());
}
}
/// A seed fixes the run, so one that fails can be replayed.
#[test]
fn a_seed_fixes_the_history_run() {
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
let histories = |seed| simulate::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
for seed in 0..5 {
assert_eq!(histories(seed), histories(seed), "seed {seed}");
}
@@ -443,9 +150,7 @@ fn a_seed_fixes_the_history_run() {
#[test]
#[ignore]
fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
let mut log = Vec::new();
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let host = simulate(seed, steps, &mut log);
let host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
}
@@ -1033,6 +1033,33 @@ fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
}
/// Bringing back a step that writes to a node the line never had reconnects an input naming that node to what history
/// holds as its primary input, though the write leaves only a placeholder of it.
#[test]
fn bringing_back_a_step_reconnects_past_a_node_the_line_never_had() {
let (source, consumer) = (NodeId(1), NodeId(2));
let source_value = NodeInput::Value {
value: Value::from(serde_json::json!("under the source")),
exposed: false,
};
let mut source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
source_node.inputs[0].input = source_value.clone();
let mut consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
consumer_node.inputs[0].input = NodeInput::Node { id: source, index: 0 };
let mut session = Session::with_peer(PeerId(1));
let base = step(&mut session, add_network(5));
step(&mut session, RegistryDelta::AddNode { id: source, node: source_node });
session.commit_op_for_test(RegistryDelta::AddNode { id: consumer, node: consumer_node }).expect("commit");
let consumed = step(&mut session, change_node_attribute(source, "position", serde_json::json!(1)));
session.move_head_to(base).expect("go back to before the source");
session.restore_interaction(consumed).expect("bring the consumer back");
let registry = session.retired_registry();
assert!(registry.removed_nodes.get(&source).is_some_and(|tombstone| tombstone.placeholder));
assert_eq!(registry.node_instances[&consumer].inputs()[0].input, source_value);
}
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
/// peer id still undoes what its user did from the old one, and nobody else's.
#[test]
@@ -0,0 +1,315 @@
//! Shared harness of the deterministic history simulations: a seeded generator, every history operation the History
//! panel offers, and the checks each run makes after every operation.
use crate::{Network, NetworkId, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use std::collections::{HashMap, HashSet};
/// What every node's implementation names, so nodes need no proto-node declarations. The first node drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
pub(super) const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the document is empty, of another type than what a chain's bottom rests on.
pub(super) fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
pub(super) struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
pub(super) fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
pub(super) fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// A kind of document the simulation edits.
pub(super) trait Scenario {
/// One interaction's ops for a random edit, as the editor would stage them.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta>;
/// Panics with `context` when `registry` is not a document this scenario allows.
fn assert_well_formed(context: &str, registry: &Registry);
}
/// The nodes down the chain off the export, following each one's primary input.
pub(super) fn stack(registry: &Registry) -> Vec<NodeId> {
let mut nodes = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if nodes.contains(&id) {
break;
}
nodes.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
nodes
}
/// What feeds into `node` from below.
pub(super) fn below(registry: &Registry, node: NodeId) -> NodeInput {
registry.node_instances[&node].inputs[0].input.clone()
}
pub(super) fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
pub(super) fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// Reads a number from the environment variable `name`, so a run can be widened or replayed.
pub(super) fn from_env<T: std::str::FromStr>(name: &str, default: T) -> T {
std::env::var(name).ok().and_then(|text| text.parse().ok()).unwrap_or(default)
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The nodes the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The nodes the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The nodes live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
fn assert_consistent<S: Scenario>(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
S::assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
/// Runs `steps` random edits and history operations from `seed`. After each one the document must be well formed, the
/// snapshot must be what history folds to, and a peer following the host must hold the same document.
pub(super) fn simulate<S: Scenario>(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = S::random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
}
8 => {
let steps = line_steps(&host);
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&steps[1.min(steps.len())..]) else { continue };
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A node the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's nodes {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A node the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's nodes {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the nodes {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent::<S>(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
}
@@ -0,0 +1,80 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
TransferCurve(Vec<[f64; 2]>),
TypeDefault(Type),
}
/// Frozen mirror of the `Type` a paint input's lack of a paint stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
Item(Box<Type>),
}
#[derive(Serialize, Deserialize)]
struct TypeDescriptor {
name: String,
}
/// 'Bevel & Emboss' gained a texture with its depth, and a gloss contour and a slope contour with its range, set to no texture and straight contours across the whole slope to keep the bevel as it was.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@1 => @2)]
pub fn bevel_and_emboss_v1(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// The texture, its depth, the slope contour's range, the gloss and slope contours' antialiasing, and the gloss and slope contours.
fn added_inputs() -> [NodeInput; 7] {
let straight = || literal(Tagged::TransferCurve(vec![[0., 0.], [1., 1.]]));
let no_paint = Tagged::TypeDefault(Type::Item(Box::new(Type::Concrete(TypeDescriptor {
name: "graphic_types::graphic::Graphic".to_string(),
}))));
[
literal(no_paint),
literal(Tagged::Number(100.)),
literal(Tagged::Number(100.)),
literal(Tagged::Bool(false)),
literal(Tagged::Bool(false)),
straight(),
straight(),
]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(13, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV1, &contract());
check_undo(&BevelAndEmbossV1, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_options_that_leave_the_bevel_as_it_was() {
let inputs: Vec<_> = (0..13).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV1);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@1), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV1).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@2)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Drop Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
#[migration("blending_nodes::effects::DropShadowNode"@1 => @2)]
pub fn drop_shadow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DropShadowV1, &contract());
check_undo(&DropShadowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&DropShadowV1);
let drop_shadow = fixture.add(decl!("blending_nodes::effects::DropShadowNode"@1), inputs.clone());
let migrated = fixture.migrate(&DropShadowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, drop_shadow), Some(decl!("blending_nodes::effects::DropShadowNode"@2)));
assert_eq!(fixture.inputs(&migrated, drop_shadow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Inner Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
#[migration("blending_nodes::effects::InnerGlowNode"@1 => @2)]
pub fn inner_glow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerGlowV1, &contract());
check_undo(&InnerGlowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerGlowV1);
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@1), inputs.clone());
let migrated = fixture.migrate(&InnerGlowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@2)));
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Inner Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
#[migration("blending_nodes::effects::InnerShadowNode"@1 => @2)]
pub fn inner_shadow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerShadowV1, &contract());
check_undo(&InnerShadowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerShadowV1);
let inner_shadow = fixture.add(decl!("blending_nodes::effects::InnerShadowNode"@1), inputs.clone());
let migrated = fixture.migrate(&InnerShadowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, inner_shadow), Some(decl!("blending_nodes::effects::InnerShadowNode"@2)));
assert_eq!(fixture.inputs(&migrated, inner_shadow), expected);
}
}
@@ -0,0 +1,59 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
MaskMode(MaskMode),
}
#[derive(Serialize, Deserialize)]
enum MaskMode {
Luminance,
}
/// 'Mask' became an effect masking any graphic by any other, keeping its content and mask and gaining its mode, density, feather, and invert at their defaults.
#[migration("raster_nodes::std_nodes::MaskNode"@1 => "blending_nodes::masks::MaskNode"@2)]
pub fn mask_by_any_graphic(inputs: &mut Inputs) {
inputs.push(literal(Tagged::MaskMode(MaskMode::Luminance)));
inputs.push(literal(Tagged::Number(100.)));
inputs.push(literal(Tagged::Number(0.)));
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MaskByAnyGraphic, &contract());
check_undo(&MaskByAnyGraphic, &contract());
}
#[test]
fn keeps_the_content_and_mask_and_adds_the_defaults() {
let (content, stencil) = (literal(1.), literal(2.));
let mut fixture = Fixture::new(&MaskByAnyGraphic);
let mask = fixture.add(decl!("raster_nodes::std_nodes::MaskNode"@1), vec![content.clone(), stencil.clone()]);
let migrated = fixture.migrate(&MaskByAnyGraphic).unwrap();
assert_eq!(fixture.declaration_of(&migrated, mask), Some(decl!("blending_nodes::masks::MaskNode"@2)));
let defaults = [
literal(Tagged::MaskMode(MaskMode::Luminance)),
literal(Tagged::Number(100.)),
literal(Tagged::Number(0.)),
literal(Tagged::Bool(false)),
];
assert_eq!(fixture.inputs(&migrated, mask), [[content, stencil].as_slice(), &defaults].concat());
}
}
@@ -1,3 +1,13 @@
//! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1;
mod drop_shadow_v1;
mod inner_glow_v1;
mod inner_shadow_v1;
mod mask_by_any_graphic;
mod outer_glow_v1;
mod outline_v1;
mod outline_v2;
mod paint_overlay_from_color_overlay;
mod renames;
mod satin_v1;
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Outer Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
#[migration("blending_nodes::effects::OuterGlowNode"@1 => @2)]
pub fn outer_glow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OuterGlowV1, &contract());
check_undo(&OuterGlowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OuterGlowV1);
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@1), inputs.clone());
let migrated = fixture.migrate(&OuterGlowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@2)));
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Outline' gained a blend mode after its color, set to Normal, which composites the outline as before.
#[migration("blending_nodes::effects::OutlineNode"@1 => @2)]
pub fn outline_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV1, &contract());
check_undo(&OutlineV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV1);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@1), inputs.clone());
let migrated = fixture.migrate(&OutlineV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@2)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,45 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Outline' takes its color as any paint now, and gained a Contour Gradient option, set off to keep painting by the paint's own placement.
#[migration("blending_nodes::effects::OutlineNode"@2 => @3)]
pub fn outline_v2(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV2, &contract());
check_undo(&OutlineV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_contour_gradient_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV2);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@2), inputs.clone());
let migrated = fixture.migrate(&OutlineV2).unwrap();
let mut expected = inputs;
expected.push(literal(Tagged::Bool(false)));
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@3)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,43 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Node, migration};
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
attributes.remove(node.id(), DISPLAY_NAME);
}
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::TimeStamp;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
#[test]
fn rewrites_history() {
let contract = SourceContract {
display_names: &["Color Overlay"],
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
};
check_commutation(&PaintOverlayFromColorOverlay, &contract);
check_undo(&PaintOverlayFromColorOverlay, &contract);
}
#[test]
fn only_the_old_default_name_is_cleared() {
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
}
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Satin' gained a blend mode after its color, set to Normal to keep compositing the shading as before.
#[migration("blending_nodes::effects::SatinNode"@1 => @2)]
pub fn satin_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&SatinV1, &contract());
check_undo(&SatinV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&SatinV1);
let satin = fixture.add(decl!("blending_nodes::effects::SatinNode"@1), inputs.clone());
let migrated = fixture.migrate(&SatinV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, satin), Some(decl!("blending_nodes::effects::SatinNode"@2)));
assert_eq!(fixture.inputs(&migrated, satin), expected);
}
}
@@ -1,4 +1,3 @@
//! Migrations of the nodes in `graphene_std`.
mod rasterize_v1;
mod renames;
@@ -1,68 +0,0 @@
use migration_core::{Inputs, MigrationError, NodeInput, migration};
use serde::Serialize;
const EXECUTOR: u32 = 2;
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
#[derive(Serialize)]
enum Reflected {
DocumentNodePath,
}
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
if inputs.len() < EXECUTOR as usize {
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
}
if inputs.len() == EXECUTOR as usize {
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
}
inputs.push_reflection(Reflected::DocumentNodePath);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
fixture.inputs(&migrated, rasterize)
}
#[test]
fn rewrites_history() {
check_commutation(&RasterizeV1, &contract());
check_undo(&RasterizeV1, &contract());
}
#[test]
fn gives_the_node_its_path() {
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
}
#[test]
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
let inputs = vec![literal(1.), literal(2.)];
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
}
}
@@ -0,0 +1,131 @@
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, Inputs, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Integer(i64),
DVec2([f64; 2]),
MandelbrotFractal(MandelbrotFractal),
MandelbrotExterior(MandelbrotExterior),
MandelbrotInterior(MandelbrotInterior),
}
#[derive(Serialize, Deserialize)]
enum MandelbrotFractal {
ClassicMandelbrot,
}
#[derive(Serialize, Deserialize)]
enum MandelbrotExterior {
SmoothEscape,
}
#[derive(Serialize, Deserialize)]
enum MandelbrotInterior {
Flat,
}
/// How far the old unit square, which spanned the complex plane from -2 to 1, placed the plane's origin from the pattern's.
const OLD_ORIGIN: [f64; 2] = [2. / 3., 0.5];
/// 'Mandelbrot' gained a scale and settings for its fractal, its slice toward the Julia set, and its interior and exterior, and the complex plane's origin moved to the pattern's.
/// A third of a unit's scale and a Transform moving the pattern back to the old origin keep its look.
#[migration("raster_nodes::std_nodes::MandelbrotNode"@2 => @3)]
pub fn mandelbrot_v2(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
for input in new_inputs() {
inputs.push(input);
}
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let origin = downstream.add_node_keyed(
NewNode {
declaration: decl!("transform_nodes::transform_nodes::TransformNode"@1),
inputs: vec![
NodeInput::Node { id: node.id(), index: 0 },
literal(Tagged::DVec2(OLD_ORIGIN)),
literal(Tagged::Number(0.)),
literal(Tagged::DVec2([1., 1.])),
literal(Tagged::DVec2([0., 0.])),
],
},
"origin",
);
for consumer in consumers {
downstream.connect(OutputConnector { node: origin, output: 0 }, consumer);
}
// The Transform takes the pattern's place, with the pattern before it
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(origin, POSITION, &stored);
}
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
/// The settings 'Mandelbrot' gained, in the order of its parameters, with the scale matching the old unit square's three units of the plane.
fn new_inputs() -> [NodeInput; 10] {
[
literal(Tagged::MandelbrotFractal(MandelbrotFractal::ClassicMandelbrot)),
literal(Tagged::MandelbrotExterior(MandelbrotExterior::SmoothEscape)),
literal(Tagged::MandelbrotInterior(MandelbrotInterior::Flat)),
literal(Tagged::Integer(1)),
literal(Tagged::Number(1. / 3.)),
literal(Tagged::Integer(256)),
literal(Tagged::Number(2.)),
literal(Tagged::Number(0.)),
literal(Tagged::DVec2([0., 0.])),
literal(Tagged::DVec2([-0.8, 0.156])),
]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |_, _| literal(Tagged::None))
}
#[test]
fn rewrites_history() {
check_commutation(&MandelbrotV2, &contract());
check_undo(&MandelbrotV2, &contract());
}
#[test]
fn keeps_the_primary_input_and_adds_the_settings() {
let mut fixture = Fixture::new(&MandelbrotV2);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
let mut expected = vec![literal(Tagged::None)];
expected.extend(new_inputs());
assert_eq!(fixture.declaration_of(&migrated, mandelbrot), Some(decl!("raster_nodes::std_nodes::MandelbrotNode"@3)));
assert_eq!(fixture.inputs(&migrated, mandelbrot), expected);
}
#[test]
fn whatever_read_the_pattern_reads_it_moved_back_to_the_old_origin() {
let mut fixture = Fixture::new(&MandelbrotV2);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
let consumer = fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]);
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
let NodeInput::Node { id: origin, .. } = fixture.inputs(&migrated, consumer)[0] else {
panic!("the consumer should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, origin), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
let inputs = fixture.inputs(&migrated, origin);
assert_eq!(inputs[0], NodeInput::Node { id: mandelbrot, index: 0 });
assert_eq!(inputs[1], literal(Tagged::DVec2(OLD_ORIGIN)));
}
}
@@ -1,6 +1,7 @@
//! Migrations of the nodes in `raster_nodes`.
mod mandelbrot_v1;
mod mandelbrot_v2;
mod mix_colors_from_mix_node;
mod noise_pattern_v1;
mod pattern_square;
@@ -6,3 +6,5 @@ rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_n
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
rename!("core_types::vector::AreaNode"@1 => @2);
rename!("core_types::vector::CentroidNode"@1 => @2);
// Version 2 only lets its output carry an error, so stored nodes keep their layout
rename!("core_types::vector::ScatterPointsNode"@1 => @2);
+2 -1
View File
@@ -18,7 +18,8 @@ pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
pub const VIEWPORT_ZOOM_MOUSE_RATE: f64 = 1. / 400.;
pub const VIEWPORT_ZOOM_SCALE_MIN: f64 = 0.000_000_1;
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000.;
/// Deep enough to reach the limits of 64-bit precision, which still places each pixel precisely around document coordinates in the thousands.
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000_000_000.;
pub const VIEWPORT_ZOOM_MIN_FRACTION_COVER: f64 = 0.01;
pub const VIEWPORT_ZOOM_LEVELS: [f64; 74] = [
0.0001, 0.000125, 0.00016, 0.0002, 0.00025, 0.00032, 0.0004, 0.0005, 0.00064, 0.0008, 0.001, 0.0016, 0.002, 0.0025, 0.0032, 0.004, 0.005, 0.0064, 0.008, 0.01, 0.01125, 0.015, 0.02, 0.025, 0.03,
@@ -16,8 +16,8 @@ use graphene_std::gradient::Gradient;
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior,
NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::text::TextAlign;
@@ -33,7 +33,10 @@ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowTechnique, Graphic};
use graphene_std::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
MaskMode,
};
use kurbo::BezPath;
use std::any::Any;
use std::ops::Range;
@@ -436,6 +439,9 @@ macro_rules! inspectable_types {
List<CellularDistanceFunction>,
List<CellularReturnType>,
List<DomainWarpType>,
List<MandelbrotFractal>,
List<MandelbrotExterior>,
List<MandelbrotInterior>,
List<RealTimeMode>,
List<GridType>,
List<GridTopology>,
@@ -493,6 +499,9 @@ macro_rules! inspectable_types {
Item<CellularDistanceFunction>,
Item<CellularReturnType>,
Item<DomainWarpType>,
Item<MandelbrotFractal>,
Item<MandelbrotExterior>,
Item<MandelbrotInterior>,
Item<RealTimeMode>,
Item<GridType>,
Item<GridTopology>,
@@ -1259,8 +1268,13 @@ macro_rules! impl_table_item_layout_for_choice_enum {
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
BevelDirection,
BevelTechnique,
BevelStyle,
EffectKind,
Generator,
GlowSource,
MaskMode,
GradientForm,
GradientSpread,
GradientSpace,
@@ -1291,6 +1305,9 @@ impl_table_item_layout_for_choice_enum!(
CellularDistanceFunction,
CellularReturnType,
DomainWarpType,
MandelbrotFractal,
MandelbrotExterior,
MandelbrotInterior,
RealTimeMode,
GridType,
GridTopology,
@@ -1437,6 +1454,11 @@ macro_rules! known_item_types {
Effects,
Effect,
EffectKind,
GlowSource,
MaskMode,
BevelStyle,
BevelDirection,
BevelTechnique,
DashPattern,
BoxCorners,
TransferCurve,
@@ -1472,6 +1494,9 @@ macro_rules! known_item_types {
CellularDistanceFunction,
CellularReturnType,
DomainWarpType,
MandelbrotFractal,
MandelbrotExterior,
MandelbrotInterior,
RealTimeMode,
GridType,
GridTopology,
@@ -319,9 +319,6 @@ pub enum DocumentMessage {
UpdateTextFrames {
text_frames: HashMap<NodeId, DAffine2>,
},
UpdateFootprintAreas {
footprint_areas: HashMap<NodeId, DAffine2>,
},
UpdateClipTargets {
clip_targets: HashSet<NodeId>,
},
@@ -1914,9 +1914,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_text_frames(layer_text_frames);
}
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
self.network_interface.update_footprint_areas(footprint_areas);
}
DocumentMessage::UpdateClipTargets { clip_targets } => {
self.network_interface.update_clip_targets(clip_targets);
}
@@ -2159,15 +2156,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
} else {
self.network_interface.document_bounds_document_space(true)
};
if let Some(bounds) = bounds {
if self.document_ptz.flip {
responses.add(NavigationMessage::CanvasFlip);
}
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
} else {
warn!("Cannot zoom due to no bounds")
// With nothing to frame, like a generator's pattern filling the plane, a tiny area at the origin is framed, which centers the origin at 100%
let bounds = bounds.unwrap_or([DVec2::splat(-1.), DVec2::splat(1.)]);
if self.document_ptz.flip {
responses.add(NavigationMessage::CanvasFlip);
}
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
}
DocumentMessage::Noop => (),
}
@@ -4730,8 +4726,8 @@ pub fn navigation_controls(ptz: &PTZ, navigation_handler: &NavigationMessageHand
vec![
NumberInput::new(Some(navigation_handler.snapped_zoom(ptz.zoom()) * 100.))
.unit("%")
.min(0.000001)
.max(1000000.)
.min(crate::consts::VIEWPORT_ZOOM_SCALE_MIN * 100.)
.max(crate::consts::VIEWPORT_ZOOM_SCALE_MAX * 100.)
.tooltip_label(if node_graph { "Node Graph Zoom" } else { "Canvas Zoom" })
.sizing(WidgetSizing::default().min_width(80))
.on_update(|number_input: &NumberInput| {
@@ -4798,6 +4794,69 @@ mod document_message_handler_tests {
use crate::messages::portfolio::document::utility_types::misc::GridType;
use crate::test_utils::test_prelude::*;
#[tokio::test]
async fn zooming_to_fit_nothing_centers_the_origin_at_100_percent() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
// Zoomed, panned, and tilted away in a document with nothing to frame
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 7. }).await;
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(300., -200.) }).await;
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 0.5 }).await;
editor.handle_message(DocumentMessage::ZoomCanvasToFitAll).await;
let ptz = editor.active_document().document_ptz;
assert_eq!(ptz.zoom(), 1.);
assert_eq!(ptz.tilt(), 0.);
assert!(ptz.pan.length() < 1e-9, "the view is panned by {}", ptz.pan);
}
#[tokio::test]
async fn zooming_to_100_percent_reaches_it_with_only_a_tiny_shape_in_the_document() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
// A shape about a millionth of a unit across, drawn while zoomed far in
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 10_000_000. }).await;
editor.draw_ellipse(100., 100., 110., 110.).await;
assert!(editor.active_document().network_interface.document_bounds_document_space(true).is_some());
editor.handle_message(DocumentMessage::ZoomCanvasTo100Percent).await;
assert_eq!(editor.active_document().document_ptz.zoom(), 1.);
}
#[tokio::test]
async fn wheeling_in_at_the_deepest_zoom_leaves_the_view_in_place() {
use crate::consts::VIEWPORT_ZOOM_SCALE_MAX;
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: VIEWPORT_ZOOM_SCALE_MAX }).await;
let pan = editor.active_document().document_ptz.pan;
// Ctrl+wheel zooming in, which heads toward the pointer away from the viewport's center
let editor_mouse_state = EditorPointerState {
editor_position: DVec2::new(100., 100.),
scroll_delta: ScrollDelta { x: 0., y: -100., z: 0. },
..Default::default()
};
editor
.input(InputPreprocessorMessage::WheelScroll {
editor_mouse_state,
modifier_keys: ModifierKeys::CONTROL,
})
.await;
let ptz = editor.active_document().document_ptz;
assert_eq!(ptz.zoom(), VIEWPORT_ZOOM_SCALE_MAX);
assert_eq!(ptz.pan, pan);
}
#[tokio::test]
async fn deleting_the_bottom_layer_leaves_the_layer_above_it_the_empty_stack_value() {
let mut editor = EditorTestUtils::create();
@@ -211,22 +211,36 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
}
}
NavigationMessage::CanvasZoomDecrease { center_on_mouse } => {
let document_bounds = if !graph_view_overlay_open {
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
network_interface.document_bounds_viewport_space(true)
} else {
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
};
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
return;
};
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().rev().find(|scale| **scale < ptz.zoom()).unwrap_or(&ptz.zoom());
let new_scale = zoom_levels().take_while(|&scale| scale < ptz.zoom()).last().unwrap_or(ptz.zoom());
let new_scale = (new_scale * Self::clamp_zoom(new_scale, document_bounds, old_zoom, viewport)).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
if center_on_mouse {
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
}
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
}
NavigationMessage::CanvasZoomIncrease { center_on_mouse } => {
let document_bounds = if !graph_view_overlay_open {
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
network_interface.document_bounds_viewport_space(true)
} else {
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
};
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
return;
};
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().find(|scale| **scale > ptz.zoom()).unwrap_or(&ptz.zoom());
let new_scale = zoom_levels().find(|&scale| scale > ptz.zoom()).unwrap_or(ptz.zoom());
let new_scale = (new_scale * Self::clamp_zoom(new_scale, document_bounds, old_zoom, viewport)).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
if center_on_mouse {
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
}
@@ -250,25 +264,18 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
zoom_factor *= Self::clamp_zoom(ptz.zoom() * zoom_factor, document_bounds, old_zoom, viewport);
responses.add(self.center_zoom(viewport.size().into(), zoom_factor, ipp.mouse.position));
responses.add(NavigationMessage::CanvasZoomSet {
zoom_factor: ptz.zoom() * zoom_factor,
});
// Held to the zoom range before panning toward the pointer, so wheeling against a limit leaves the view in place
let zoom = (ptz.zoom() * zoom_factor).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
responses.add(self.center_zoom(viewport.size().into(), zoom / ptz.zoom(), ipp.mouse.position));
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: zoom });
}
// Sets exactly the zoom asked for, since the steps and gestures that keep the content from shrinking out of sight do so before sending it
NavigationMessage::CanvasZoomSet { zoom_factor } => {
let document_bounds = if !graph_view_overlay_open {
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
network_interface.document_bounds_viewport_space(true)
} else {
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
};
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
log::error!("Could not get mutable PTZ in CanvasZoomSet");
return;
};
let zoom = zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
let zoom = zoom * Self::clamp_zoom(zoom, document_bounds, old_zoom, viewport);
ptz.set_zoom(zoom);
ptz.set_zoom(zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX));
if graph_view_overlay_open {
responses.add(NodeGraphMessage::UpdateGraphBarRight);
} else {
@@ -591,8 +598,31 @@ impl NavigationMessageHandler {
pub fn snapped_zoom(navigation_operation: &NavigationOperation, zoom: f64) -> f64 {
if matches!(navigation_operation, NavigationOperation::Zoom { snap: true, .. }) {
*VIEWPORT_ZOOM_LEVELS.iter().min_by(|a, b| (**a - zoom).abs().partial_cmp(&(**b - zoom).abs()).unwrap()).unwrap_or(&zoom)
zoom_levels().min_by(|a, b| (a - zoom).abs().total_cmp(&(b - zoom).abs())).unwrap_or(zoom)
} else {
zoom
}
}
/// The preset zoom levels, ascending: the listed ones, then 1, 1.25, and 1.5625 times each power of two (as the list ends with) up to the deepest zoom.
fn zoom_levels() -> impl Iterator<Item = f64> {
let last_listed = VIEWPORT_ZOOM_LEVELS[VIEWPORT_ZOOM_LEVELS.len() - 1];
let doubling_steps = (0..).flat_map(|power| [1., 1.25, 1.5625].map(|step| 2_f64.powi(power) * step));
VIEWPORT_ZOOM_LEVELS
.into_iter()
.chain(doubling_steps.skip_while(move |&level| level <= last_listed).take_while(|&level| level < VIEWPORT_ZOOM_SCALE_MAX))
.chain([VIEWPORT_ZOOM_SCALE_MAX])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_zoom_levels_step_up_evenly_to_the_deepest_zoom() {
let levels: Vec<f64> = zoom_levels().collect();
assert!(levels.windows(2).all(|pair| pair[1] > pair[0] && pair[1] / pair[0] <= 1.6), "{levels:?}");
assert_eq!(levels.last(), Some(&VIEWPORT_ZOOM_SCALE_MAX));
}
}
@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
use crate::messages::frontend::IconName;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
use crate::node_graph_executor::NodeGraphExecutor;
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::{concrete, list};
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
use graphene_std::vector::Vector;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
use graphene_std::*;
use std::collections::{HashMap, VecDeque};
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
let widget_override = input_inspector_row.widget_override.clone()?;
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
if matches!(widget_override.as_str(), "number" | "vec2") {
return None;
}
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None;
@@ -54,6 +56,8 @@ impl NodeInspectorContext<'_> {
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
/// Input position of the clip parameter on the "Artboard" layer template.
pub const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
/// Input position of the control path parameter on the "Blend" network node template.
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
@@ -107,8 +111,7 @@ pub struct DocumentNodeDefinition {
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
pub identifier: &'static str,
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
pub version: u32,
/// The default [`NodeTemplate`] this definition instantiates.
@@ -136,541 +139,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
},
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
category: "Graphic",
icon: Some("NodeMerge"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
// Primary (bottom) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
..Default::default()
},
// Secondary (left) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
..Default::default()
},
NodeTemplate {
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
input_metadata: vec![
("Base", "The stack of layers below this one, which the content is placed above.").into(),
("Content", "The artwork this layer adds to the stack as a single item.").into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Artboard",
version: 1,
category: "Graphic",
icon: Some("NodeArtboard"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
NodeInput::import(item!(TaggedValue), 2),
NodeInput::import(item!(TaggedValue), 3),
NodeInput::import(item!(TaggedValue), 4),
NodeInput::import(item!(TaggedValue), 5),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
NodeInput::node(NodeId(0), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Artboard), true),
NodeInput::type_default(list!(Graphic), true),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
NodeInput::value(TaggedValue::Bool(true), false),
],
input_metadata: vec![
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
("Content", "Graphics to include within the artboard.").into(),
InputMetadata::with_name_description_override(
"Location",
"Coordinate of the top-left corner of the artboard within the document.",
WidgetOverride::Vec2(Vec2InputSettings {
x: "X".to_string(),
y: "Y".to_string(),
unit: " px".to_string(),
is_integer: true,
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Dimensions",
"Width and height of the artboard within the document.",
WidgetOverride::Vec2(Vec2InputSettings {
x: "W".to_string(),
y: "H".to_string(),
unit: " px".to_string(),
is_integer: true,
..Default::default()
}),
),
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Blend",
version: 1,
category: "Vector: Deform",
icon: Some("NodeBlend"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(16), 0)],
nodes: [
// 0: Separate Paths (split the vector into its individual paths)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
..Default::default()
},
// 1: Count (number of subpaths)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
..Default::default()
},
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: As Number (the integer count enters the network's decimal math)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
// 4: Multiply (total_instances = count × subpath_count)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
..Default::default()
},
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
// 7: Divide (index / count)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
..Default::default()
},
// 8: Floor (floor(index / count) = subpath index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(7), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
..Default::default()
},
// 9: Modulo (index % count = local index within subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
..Default::default()
},
// 10: Path Is Closed (check if current subpath is closed)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
..Default::default()
},
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
..Default::default()
},
// 12: Divide (local_index / denominator = within-subpath fraction)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
..Default::default()
},
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
// 14: Add (subpath_index + clamped fraction = progression)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
..Default::default()
},
// 15: Morph (content, progression, reverse, distribution, path)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
inputs: vec![
NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default()
},
// 16: Repeat
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
..Default::default()
},
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
],
input_metadata: vec![
("Content", "The vector objects to create intermediate shapes between.").into(),
(
"Count",
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
)
.into(),
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
(
"Path",
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
)
.into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Origins to Polyline",
version: 1,
category: "Vector: Path",
icon: Some("NodeOriginsToPolyline"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(7), 0)],
nodes: [
// 0: Read Vector
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
..Default::default()
},
// 1: Extract Transform
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
..Default::default()
},
// 2: Decompose Translation
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
..Default::default()
},
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(2), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
..Default::default()
},
// 4: Flatten Vector
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
..Default::default()
},
// 5: Map
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
..Default::default()
},
// 6: Combine Paths
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
..Default::default()
},
// 7: Points to Polyline
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Vector), true)],
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
output_names: vec!["Vector".to_string()],
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Load Image",
version: 1,
category: "Data: I/O",
icon: Some("NodeLoadImage"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Regex Find",
version: 1,
category: "String: Regex",
icon: Some("NodeRegexFind"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![
// Primary output: the whole match (String)
NodeInput::node(NodeId(1), 0),
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
NodeInput::node(NodeId(2), 0),
],
nodes: [
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
NodeTemplate {
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
input_metadata: vec![
("String", "The string to search within.").into(),
("Pattern", "The regular expression pattern to search for.").into(),
(
"Match Index",
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
)
.into(),
("Case Insensitive", "Match letters regardless of case.").into(),
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
],
output_names: vec!["Match".to_string(), "Captures".to_string()],
output_descriptions: vec![
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
"The text matched by each capture group in the pattern, in order.".to_string(),
],
..Default::default()
},
description: Cow::Borrowed(
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
),
inspector: None,
},
];
document_node_derive::post_process_nodes(custom)
document_node_derive::derive_definitions()
}
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
@@ -738,91 +209,10 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
"number".to_string(),
Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default();
if let Some(unit) = context
.network_interface
.input_data(&node_id, index, "unit", context.selection_network_path)
.and_then(|value| value.as_str())
{
number_input = number_input.unit(unit);
}
if let Some(min) = context
.network_interface
.input_data(&node_id, index, "min", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.min(min);
}
if let Some(max) = context
.network_interface
.input_data(&node_id, index, "max", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.max(max);
}
if let Some(step) = context
.network_interface
.input_data(&node_id, index, "step", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.step(step);
}
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
mode
}) {
number_input = number_input.mode(mode);
}
if let Some(range_min) = context
.network_interface
.input_data(&node_id, index, "range_min", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.range_min(Some(range_min));
}
if let Some(range_max) = context
.network_interface
.input_data(&node_id, index, "range_max", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.range_max(Some(range_max));
}
if let Some(is_integer) = context
.network_interface
.input_data(&node_id, index, "is_integer", context.selection_network_path)
.and_then(|value| value.as_bool())
{
number_input = number_input.is_integer(is_integer);
}
let blank_assist = context
.network_interface
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
.and_then(|value| value.as_bool())
.unwrap_or_else(|| {
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
true
});
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
number_input,
))])
}),
);
map.insert(
// The custom number input settings are only available on proto nodes
"optional_f64".to_string(),
Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default();
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
if let Some(field) = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
{
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
@@ -872,61 +262,51 @@ fn static_input_inspector() -> InputInspector {
))])
}),
);
map.insert(
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
"wrapping_range_slider".to_string(),
Box::new(|node_id, index, context| {
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
let field = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
let mut number_input = NumberInput::default().mode_increment();
let mut period = None;
if let Some(field) = field {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
if let Some(display_decimal_places) = field.number_display_decimal_places {
number_input = number_input.display_decimal_places(display_decimal_places);
}
if let Some(number_step) = field.number_step {
number_input = number_input.step(number_step);
}
period = field.number_soft_min.zip(field.number_soft_max);
}
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
let row = match period {
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
let default = node_inspector::definition_default_number(&parameter_widgets_info);
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
}
_ => {
log::error!("A wrapping range slider needs finite soft bounds at both ends");
node_inspector::number_widget(parameter_widgets_info, number_input)
}
};
Ok(vec![LayoutGroup::row(row)])
}),
);
map.insert(
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
"type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
let x = context
.network_interface
.input_data(&node_id, index, "x", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get x for vec2 input");
""
})
.to_string();
let y = context
.network_interface
.input_data(&node_id, index, "y", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get y for vec2 input");
""
})
.to_string();
let unit = context
.network_interface
.input_data(&node_id, index, "unit", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get unit for vec2 input");
""
})
.to_string();
let min = context
.network_interface
.input_data(&node_id, index, "min", context.selection_network_path)
.and_then(|value| value.as_f64());
let is_integer = context
.network_interface
.input_data(&node_id, index, "is_integer", context.selection_network_path)
.and_then(|value| value.as_bool())
.unwrap_or_default();
Ok(vec![node_inspector::vec2_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
&x,
&y,
&unit,
min,
is_integer,
)])
}),
);
map.insert(
"noise_inspector_scale".to_string(),
Box::new(|node_id, index, context| {
@@ -1077,6 +457,51 @@ fn static_input_inspector() -> InputInspector {
Ok(vec![cellular_return_type])
}),
);
map.insert(
"mandelbrot_inspector_frequency".to_string(),
Box::new(|node_id, index, context| {
let tendrils_or_rays = node_inspector::query_mandelbrot_tendrils_or_rays(node_id, context)?;
let frequency = node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(1.).max(64.).is_integer(true).disabled(!tendrils_or_rays),
);
Ok(vec![frequency.into()])
}),
);
map.insert(
"mandelbrot_inspector_mandelbrot_slice".to_string(),
Box::new(|node_id, index, context| {
let mandelbrot_to_julia = node_inspector::query_mandelbrot_to_julia(node_id, context)?;
let mandelbrot_slice = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(
mandelbrot_slice,
"X",
"Y",
"",
None,
None,
false,
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
)])
}),
);
map.insert(
"mandelbrot_inspector_julia_slice".to_string(),
Box::new(|node_id, index, context| {
let mandelbrot_to_julia = node_inspector::query_mandelbrot_to_julia(node_id, context)?;
let julia_slice = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(
julia_slice,
"X",
"Y",
"",
None,
None,
false,
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
)])
}),
);
map.insert(
"noise_inspector_cellular_jitter".to_string(),
Box::new(|node_id, index, context| {
@@ -1178,6 +603,8 @@ fn static_input_inspector() -> InputInspector {
"Y",
" px",
None,
None,
false,
false,
)])
}),
@@ -1192,6 +619,8 @@ fn static_input_inspector() -> InputInspector {
"H",
"x",
None,
None,
false,
false,
)])
}),
@@ -1311,7 +740,7 @@ fn static_input_inspector() -> InputInspector {
"vec2_uv".to_string(),
Box::new(|node_id, index, context| {
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
}),
);
map
@@ -1559,6 +988,29 @@ mod test {
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId;
// A graph text node with an inner node that has no definition is left out of the catalog with only a logged error
#[test]
fn every_registered_graph_has_a_definition() {
let sources = graphene_std::registry::GRAPH_SOURCES.lock().unwrap().len();
let graphs = &*graphene_std::graph_text::GRAPHS;
assert!(!graphs.is_empty(), "the graphs in `graphene_std` should be registered");
assert_eq!(graphs.len(), sources, "every registered graph should resolve");
for graph in graphs {
assert!(resolve_network_node_type(graph.identifier).is_some(), "the '{}' graph should have a definition", graph.identifier);
}
}
#[test]
fn input_index_constants_match_the_graphs() {
use graphene_std::graph_text::import_index;
assert_eq!(import_index("Artboard", "location"), Some(super::ARTBOARD_LOCATION_INPUT_INDEX));
assert_eq!(import_index("Artboard", "dimensions"), Some(super::ARTBOARD_DIMENSIONS_INPUT_INDEX));
assert_eq!(import_index("Artboard", "clip"), Some(super::ARTBOARD_CLIP_INPUT_INDEX));
assert_eq!(import_index("Blend", "path"), Some(super::BLEND_PATH_INPUT_INDEX));
}
#[test]
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
use glam::{DAffine2, UVec2};
@@ -1699,21 +1151,36 @@ mod test_type_constraints {
#[test]
fn every_definition_default_value_satisfies_its_constraint() {
let mut violations = Vec::new();
for definition in super::DOCUMENT_NODE_TYPES.values() {
let name = &definition.node_template.display_name;
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
if let Some(value) = input.as_value()
&& !constraint.accepts_default_value(&value.ty())
{
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
}
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
}
}
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
for (node_id, inner) in &network.nodes {
check(inner, &format!("{name}, node {node_id}"), violations);
}
}
}
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
let mut violations = Vec::new();
for definition in super::DOCUMENT_NODE_TYPES.values() {
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
}
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
}
#[test]
@@ -1730,7 +1197,7 @@ mod test_type_constraints {
#[test]
fn single_protonode() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
assert!(!constraint[0].satisfies(&concrete!(String)));
@@ -1744,7 +1211,7 @@ mod test_type_constraints {
#[test]
fn single_protonode2() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
@@ -1753,8 +1220,8 @@ mod test_type_constraints {
#[test]
fn network() {
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let inner_network = NodeNetworkTemplate {
@@ -1,11 +1,17 @@
use super::DocumentNodeDefinition;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
};
use glam::IVec2;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::{HashMap, HashSet};
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let mut definitions_map = HashMap::new();
// Add the protonodes from the macro.
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
input_metadata: input_metadata(fields),
output_names,
..Default::default()
},
@@ -96,25 +93,241 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
);
}
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
for mut network_node in custom {
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
}
}
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
}
add_graph_definitions(graph_text::GRAPHS.clone(), &mut definitions_map);
definitions_map
}
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
fields
.iter()
.map(|field| {
let (name, description) = (field.name, field.description);
match field.widget_override {
RegistryWidgetOverride::None => (name, description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
}
})
.collect()
}
/// Why a graph text node has no definition yet, or can't have one.
enum GraphDefinitionError {
/// A node inside it has no definition, which may be another graph not yet added.
MissingNode(String),
/// The graph's wiring is invalid, so it's left out of the catalog.
Invalid(String),
}
/// Adds the nodes defined as subgraphs in graph text, each once the definitions of the nodes inside it exist.
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
let mut identifier_counts = HashMap::new();
for graph in &graphs {
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
}
let mut rejected = HashSet::new();
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
.into_iter()
.filter(|graph| {
let taken = identifier_counts[graph.identifier] > 1;
if taken {
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
rejected.insert(graph.identifier);
}
!taken
})
.map(|graph| (graph, String::new()))
.collect();
loop {
let pending_count = pending_graphs.len();
let mut ready = Vec::new();
pending_graphs.retain_mut(|(graph, missing)| {
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
_ => None,
});
if let Some(inner_graph) = rejected_inner_graph {
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
rejected.insert(graph.identifier);
return false;
}
match graph_definition(graph, definitions_map) {
Ok(definition) => {
ready.push(definition);
false
}
Err(GraphDefinitionError::MissingNode(missing_node)) => {
*missing = missing_node;
true
}
Err(GraphDefinitionError::Invalid(reason)) => {
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
rejected.insert(graph.identifier);
false
}
}
});
for definition in ready {
let definition = prepare_network_definition(definition, definitions_map);
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
}
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
break;
}
}
for (graph, missing_node) in pending_graphs {
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
}
}
/// Fills a network definition's nested proto node metadata and points its network at the definition.
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
}
}
network_node
}
/// Builds the catalog definition of a node defined as a subgraph in graph text.
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
let mut nodes = HashMap::new();
for (index, node) in graph.nodes.iter().enumerate() {
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
let (identifier, name) = match &node.implementation {
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
};
let Some(definition) = definitions_map.get(&identifier) else {
return Err(GraphDefinitionError::MissingNode(name));
};
let mut template = definition.default_node_template();
template.visible = !node.hidden;
template.locked = node.locked;
template.pinned = node.pinned;
if let Some(display_name) = node.display_name {
template.display_name = display_name.to_string();
}
let position = IVec2::from(node.position);
template.node_type_metadata = if node.layer {
NodeTypePersistentMetadata::layer(position)
} else {
NodeTypePersistentMetadata::node(position)
};
for (input_index, source) in &node.inputs {
let Some(input) = template.inputs.get_mut(*input_index) else {
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
};
// An input the compiler fills in can't be set
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
return Err(GraphDefinitionError::Invalid(format!(
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
)));
}
*input = graph_input(source, input).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
}
nodes.insert(NodeId(index as u64), template);
}
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
let exports = graph
.exports
.iter()
.map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false)))
.collect::<Result<_, _>>()
.map_err(GraphDefinitionError::Invalid)?;
Ok(DocumentNodeDefinition {
identifier: graph.identifier,
version: graph.version,
category: graph.category,
icon: graph.icon,
description: Cow::Borrowed(graph.description),
inspector: None,
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
inputs,
input_metadata: input_metadata(&graph.imports),
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
node_type_metadata: if graph.layer {
NodeTypePersistentMetadata::layer(IVec2::ZERO)
} else {
NodeTypePersistentMetadata::node(IVec2::ZERO)
},
..Default::default()
},
})
}
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
/// A value must have the type of that default, if it has one.
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
Ok(match source {
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
GraphInputSource::Value { value, exposed } => {
let value = graph_value(value);
if let NodeInput::Value { tagged_value, .. } = default
&& **tagged_value != TaggedValue::None
&& element_type(&tagged_value.ty()) != element_type(&value.ty())
{
return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
}
NodeInput::value(value, exposed.unwrap_or(default.is_exposed()))
}
GraphInputSource::Scope(key) => NodeInput::scope(*key),
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
})
}
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
fn element_type(ty: &Type) -> Type {
let mut element = ty;
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
element = inner;
}
element.clone()
}
fn graph_value(value: &GraphValue) -> TaggedValue {
match value {
GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
GraphValue::Number(number) => TaggedValue::Number(*number),
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
GraphValue::String(string) => TaggedValue::String(string.clone()),
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
GraphValue::Color(color) => TaggedValue::Color(*color),
}
}
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &mut node_template.implementation {
NodeTemplateImplementation::Network(network_template) => {
@@ -128,13 +341,192 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
return;
};
// A display name, lock, or pin the network's author gave the node is kept
let definition_template = &definition.node_template;
node_template.display_name = definition_template.display_name.clone();
if node_template.display_name.is_empty() {
node_template.display_name = definition_template.display_name.clone();
}
node_template.input_metadata = definition_template.input_metadata.clone();
node_template.output_names = definition_template.output_names.clone();
node_template.locked = definition_template.locked;
node_template.pinned = definition_template.pinned;
node_template.locked |= definition_template.locked;
node_template.pinned |= definition_template.pinned;
}
NodeTemplateImplementation::Definition(_) => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
fn number_import() -> FieldMetadata {
FieldMetadata {
name: "Value",
identifier: "value",
description: "",
internal: false,
exposed: true,
widget_override: RegistryWidgetOverride::None,
value_source: RegistryValueSource::None,
default_colors: None,
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: false,
number_display_decimal_places: None,
number_step: None,
unit: None,
multiline: false,
progression: false,
constant: false,
labels: None,
integer: false,
blank_assist: true,
}
}
/// A graph exporting one node, which is fed by the given inputs.
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
GraphMetadata {
identifier,
path: identifier,
category: "Test",
icon: None,
description: "",
version: 1,
layer: false,
imports: vec![number_import()],
exports: vec![GraphExportMetadata {
name: "Out",
identifier: "out",
description: "",
source: GraphInputSource::Node { node: 0, output: 0 },
}],
nodes: vec![GraphNodeMetadata {
implementation,
inputs,
position: (0, 0),
layer: false,
display_name: None,
hidden: false,
locked: false,
pinned: false,
}],
}
}
fn from_import() -> Vec<(usize, GraphInputSource)> {
let ty = Type::Item(Box::new(concrete!(f64)));
vec![(0, GraphInputSource::Import { index: 0, ty })]
}
/// The definitions a test graph builds on: only the As Number proto node.
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
HashMap::from([(identifier, definition)])
}
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
}
#[test]
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
let inner = one_node_graph("Test Inner", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![outer, inner], &mut definitions_map);
assert!(has_graph(&definitions_map, "Test Inner"));
assert!(has_graph(&definitions_map, "Test Outer"));
}
#[test]
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
let mut inputs = from_import();
inputs.push((
100,
GraphInputSource::Value {
value: GraphValue::Number(1.),
exposed: None,
},
));
let graph = one_node_graph("Test Missing Input", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), inputs);
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map);
assert!(!has_graph(&definitions_map, "Test Missing Input"));
}
#[test]
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
let first = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
assert!(!has_graph(&definitions_map, "Test Twin"));
assert!(!has_graph(&definitions_map, "Test Dependent"));
}
#[test]
fn a_value_must_have_the_type_of_the_input_it_feeds() {
let number_input = NodeInput::value(TaggedValue::Number(0.), false);
let value = |value| GraphInputSource::Value { value, exposed: None };
assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
}
#[test]
fn imports_start_from_their_default_or_type() {
let unit_primary = FieldMetadata {
default_type: Some(concrete!(())),
..number_import()
};
let with_default = FieldMetadata {
value_source: RegistryValueSource::Default("2.5"),
..number_import()
};
let graph = GraphMetadata {
imports: vec![unit_primary, with_default],
..one_node_graph("Test Defaults", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import())
};
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map);
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
assert!(!inputs[0].is_exposed());
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
assert!(inputs[1].is_exposed());
}
#[test]
fn a_graph_nodes_widget_settings_come_from_its_import() {
use crate::messages::prelude::DocumentMessageHandler;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
let location = graphene_std::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
let field = document
.network_interface
.field_metadata(&node_id, location, &[])
.expect("the location input should have its import's settings");
assert_eq!(field.labels, Some(("X", "Y")));
assert!(field.integer);
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
}
}
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
xy: Option<(i32, i32)>,
add_transaction: bool,
},
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
CreateEmptySubgraph {
node_id: Option<NodeId>,
xy: Option<(i32, i32)>,
},
CreateWire {
output_connector: OutputConnector,
input_connector: InputConnector,
@@ -383,6 +388,7 @@ impl NodeGraphMessage {
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
Self::AddNodes { .. }
| Self::CreateNodeFromContextMenu { .. }
| Self::CreateEmptySubgraph { .. }
| Self::CreateWire { .. }
| Self::CreateWires { .. }
| Self::ConnectUpstreamOutputToInput { .. }
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
TransactionStatus,
};
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
@@ -422,6 +423,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
});
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
let node_id = node_id.unwrap_or_else(NodeId::new);
let (x, y) = xy.unwrap_or_else(|| {
network_interface
.node_graph_ptz(breadcrumb_network_path)
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
});
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id,
node_template: Box::new(NodeTemplate::empty_subgraph()),
});
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
log::error!("Failed to find upstream node for downstream_input");
@@ -769,24 +787,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
let encapsulating_node_id = NodeId::new();
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
let mut subgraph_template = NodeTemplate::empty_subgraph();
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
log::error!("Could not get center of selected_nodes");
return;
};
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id: encapsulating_node_id,
node_template: Box::new(default_node_template),
});
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: encapsulating_node_id,
network_path: selection_network_path.to_vec(),
alias: "Untitled Node".to_string(),
node_template: Box::new(subgraph_template),
});
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
@@ -3426,6 +3439,13 @@ impl NodeGraphMessageHandler {
})
.disabled(read_only)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("New Custom Node")
.tooltip_label("New Custom Node")
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
.disabled(read_only)
.widget_instance(),
//
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
//
@@ -23,8 +23,8 @@ use graph_craft::{Type, concrete, item};
use graphene_std::animation::RealTimeMode;
use graphene_std::color::SRGBA8;
use graphene_std::raster::{
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal,
MandelbrotInterior, NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, GlowTechnique, Graphic, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -238,7 +238,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
}
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)]
#[derive(Clone, Copy)]
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
@@ -250,6 +250,50 @@ pub(crate) struct ParameterOptions {
pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>,
pub step: Option<f64>,
pub labels: Option<(&'static str, &'static str)>,
pub integer: bool,
pub blank_assist: bool,
}
impl Default for ParameterOptions {
fn default() -> Self {
Self {
soft_min: None,
soft_max: None,
hard_min: None,
hard_max: None,
slider: false,
multiline: false,
progression: false,
unit: None,
display_decimal_places: None,
step: None,
labels: None,
integer: false,
blank_assist: true,
}
}
}
impl ParameterOptions {
/// The options a proto node's field or a graph's import gives its widget.
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
Self {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
labels: field.labels,
integer: field.integer,
blank_assist: field.blank_assist,
}
}
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
@@ -268,10 +312,18 @@ impl SliderRange {
fn value(self, position: f64) -> f64 {
(self.min + position * (self.max - self.min)).clamp(self.min, self.max)
}
/// The `value` moved into the bounds by whole periods of their width, for a periodic number like an angle.
fn wrapped(self, value: f64) -> f64 {
if (self.min..=self.max).contains(&value) {
return value;
}
self.min + (value - self.min).rem_euclid(self.max - self.min)
}
}
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
let identifier = parameter_widgets_info
.network_interface
.reference(&parameter_widgets_info.node_id, parameter_widgets_info.selection_network_path)?;
@@ -295,9 +347,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
unit,
display_decimal_places,
step,
labels,
integer,
blank_assist,
} = options;
let mut number_input = NumberInput::default();
let mut number_input = NumberInput::default().is_integer(integer);
if slider {
number_input = number_input.mode_range();
}
@@ -340,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
}
};
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
@@ -384,10 +439,14 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
Some(x) if id_is::<DVec2>(x) => {
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
}
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
// ============
// STRUCT TYPES
// ============
@@ -419,6 +478,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).inspector_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).inspector_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).inspector_row(),
Some(x) if id_is::<MandelbrotFractal>(x) => enum_choice::<MandelbrotFractal>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MandelbrotExterior>(x) => enum_choice::<MandelbrotExterior>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MandelbrotInterior>(x) => enum_choice::<MandelbrotInterior>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).inspector_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).inspector_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).inspector_row(),
@@ -439,6 +501,11 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -877,7 +944,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
}
}
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool) -> LayoutGroup {
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
@@ -892,8 +959,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(x)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
.on_commit(commit_value)
.widget_instance(),
@@ -902,8 +970,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(y)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -916,8 +985,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(x)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
.on_commit(commit_value)
.widget_instance(),
@@ -926,8 +996,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(y)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -1637,6 +1708,38 @@ pub fn query_node_and_input_info<'a>(node_id: NodeId, input_index: usize, contex
Ok((document_node, name, description))
}
/// Whether a Mandelbrot node's exterior or interior has tendrils or rays for Frequency to set, which a wired one may.
pub fn query_mandelbrot_tendrils_or_rays(node_id: NodeId, context: &NodeInspectorContext) -> Result<bool, String> {
let document_node = get_document_node(node_id, context)?;
let exterior = document_node.inputs.iter().find_map(|input| match input.as_value() {
Some(&TaggedValue::MandelbrotExterior(exterior)) => Some(exterior),
_ => None,
});
let interior = document_node.inputs.iter().find_map(|input| match input.as_value() {
Some(&TaggedValue::MandelbrotInterior(interior)) => Some(interior),
_ => None,
});
let exterior_uses_frequency = matches!(exterior, None | Some(MandelbrotExterior::Tendrils | MandelbrotExterior::Rays));
let interior_uses_frequency = matches!(interior, None | Some(MandelbrotInterior::Rays));
Ok(exterior_uses_frequency || interior_uses_frequency)
}
/// A Mandelbrot node's Mandelbrot-to-Julia percentage, unless it's wired.
pub fn query_mandelbrot_to_julia(node_id: NodeId, context: &NodeInspectorContext) -> Result<Option<f64>, String> {
let document_node = get_document_node(node_id, context)?;
Ok(
match document_node
.input(graphene_std::raster_nodes::std_nodes::mandelbrot::MandelbrotToJuliaInput)
.and_then(|input| input.as_value())
{
Some(&TaggedValue::Number(percent)) => Some(percent),
_ => None,
},
)
}
pub fn query_noise_pattern_state(node_id: NodeId, context: &NodeInspectorContext) -> Result<(bool, bool, bool, bool, bool, bool), String> {
let document_node = get_document_node(node_id, context)?;
let current_noise_type = document_node.inputs.iter().find_map(|input| match input.as_value() {
@@ -2338,13 +2441,14 @@ fn value_slider(
}
/// A row with a range slider and a 60px number input for the number at `parameter_widgets_info`. The slider's 0..1 position maps
/// to the number through `position_of` and `value_at`, and double-click restores `default`.
/// to the number through `position_of` and `value_at`, a typed number is stored as `typed_value` gives it, and double-click restores `default`.
fn slider_row(
parameter_widgets_info: ParameterWidgetsInfo,
number_props: NumberInput,
default: Option<f64>,
position_of: impl Fn(f64) -> f64,
value_at: impl Fn(f64) -> f64 + 'static + Send + Sync,
typed_value: impl Fn(f64) -> f64 + 'static + Send + Sync,
) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -2377,7 +2481,7 @@ fn slider_row(
number_props
.value(Some(current))
.sizing(WidgetSizing::fixed(60))
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(x.value.unwrap_or_default()), node_id, index))
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(typed_value(x.value.unwrap_or_default())), node_id, index))
.on_commit(commit_value)
.widget_instance(),
]);
@@ -2393,6 +2497,19 @@ pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo,
slider.default,
move |value| slider.position(value),
move |position| slider.value(position),
|value| value,
)
}
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
slider_row(
parameter_widgets_info,
number_props,
slider.default,
move |value| slider.position(slider.wrapped(value)),
move |position| slider.value(position),
move |value| slider.wrapped(value),
)
}
@@ -2721,10 +2838,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
NumberInput::default().label("H").min(0.).unit(" px"),
));
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false);
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
widgets.extend([spacing, angles]);
} else {
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false);
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
widgets.push(spacing);
}
}
@@ -2864,6 +2981,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
Some(1.),
|gamma| MarkerScale::Gamma.position(gamma),
|position| MarkerScale::Gamma.value(position),
|gamma| gamma,
);
vec![LayoutGroup::row(exposure), LayoutGroup::row(offset), LayoutGroup::row(gamma_correction)]
@@ -3186,40 +3304,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
}
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
log::error!("Could not get implementation for node {node_id}");
return Vec::new();
};
let mut options = ParameterOptions::default();
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
let proto_node_identifier = proto_node_identifier.clone();
let mut default_type = None;
if let Some(field) = graphene_std::registry::NODE_METADATA
.lock()
.unwrap()
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
default_type = field.default_type.clone();
}
if let Some(default) = default_type {
if let Some(default) = field.and_then(|field| field.default_type) {
break 'early_return default;
}
@@ -3235,12 +3333,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
let Some(input_type) = input_type else { return Vec::new() };
input_type.clone()
}
_ => context
.network_interface
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
.compiled_nested_type()
.cloned()
.unwrap_or(concrete!(())),
_ => {
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
Type::Item(element) => *element,
declared_type => declared_type,
});
context
.network_interface
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
.compiled_nested_type()
.cloned()
.or(declared_type)
.unwrap_or(concrete!(()))
}
};
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
@@ -638,6 +638,73 @@ fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static
VelloSceneBuilder::new(size.x as u16, size.y as u16, Affine::IDENTITY, MAX_TEXTURE_SIZE)
}
/// How closely the segments that [`pieces_in_view`] walks follow an overlay's curves, in logical pixels.
const OVERLAY_SHAPE_TOLERANCE: f64 = 0.1;
/// Whether `outer` contains all of `inner`.
fn rect_contains(outer: kurbo::Rect, inner: kurbo::Rect) -> bool {
inner.x0 >= outer.x0 && inner.y0 >= outer.y0 && inner.x1 <= outer.x1 && inner.y1 <= outer.y1
}
/// The parts of `path` that may show within `visible`, each with how far along its subpath it starts.
/// A segment crossing the edge of `visible` is split in half until each half lies inside or outside it, so one far larger than the viewport costs only the log of its size.
fn pieces_in_view(path: &BezPath, visible: kurbo::Rect) -> Vec<(f64, BezPath)> {
// Halves this small are kept whole, as are those split this many times
const SMALLEST_SPLIT: f64 = 1.;
const MAX_SPLITS: u32 = 64;
const ARC_LENGTH_ACCURACY: f64 = 1e-3;
let overlaps = |bounds: kurbo::Rect| bounds.x0 <= visible.x1 && bounds.x1 >= visible.x0 && bounds.y0 <= visible.y1 && bounds.y1 >= visible.y0;
let mut pieces: Vec<(f64, BezPath)> = Vec::new();
let (mut previous, mut subpath_start) = (kurbo::Point::ZERO, kurbo::Point::ZERO);
let mut distance = 0.;
// Whether the last piece ends where the next kept segment starts, so that segment extends it
let mut continuing = false;
for element in path.elements() {
let segment = match *element {
kurbo::PathEl::MoveTo(point) => {
(previous, subpath_start, distance, continuing) = (point, point, 0., false);
continue;
}
kurbo::PathEl::LineTo(point) => PathSeg::Line(kurbo::Line::new(previous, point)),
kurbo::PathEl::QuadTo(control, point) => PathSeg::Quad(kurbo::QuadBez::new(previous, control, point)),
kurbo::PathEl::CurveTo(control_start, control_end, point) => PathSeg::Cubic(kurbo::CubicBez::new(previous, control_start, control_end, point)),
kurbo::PathEl::ClosePath => PathSeg::Line(kurbo::Line::new(previous, subpath_start)),
};
previous = segment.end();
// Halves wait on a stack, the second beneath the first, so they're visited in order along the path
let mut pending = vec![(segment, 0)];
while let Some((segment, splits)) = pending.pop() {
let bounds = kurbo::Shape::bounding_box(&segment);
let kept = overlaps(bounds);
if kept && !rect_contains(visible, bounds) && bounds.width().max(bounds.height()) > SMALLEST_SPLIT && splits < MAX_SPLITS {
let (first, second) = segment.subdivide();
pending.push((second, splits + 1));
pending.push((first, splits + 1));
continue;
}
if kept {
if !continuing {
let mut piece = BezPath::new();
piece.move_to(segment.start());
pieces.push((distance, piece));
}
if let Some((_, piece)) = pieces.last_mut() {
piece.push(segment.as_path_el());
}
}
continuing = kept;
distance += kurbo::ParamCurveArclen::arclen(&segment, ARC_LENGTH_ACCURACY);
}
}
pieces
}
impl OverlayContextInternal {
fn new(viewport: ViewportMessageHandler) -> Self {
Self {
@@ -715,7 +782,7 @@ impl OverlayContextInternal {
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
}
self.scene.stroke(&stroke, transform, Self::parse_color(stroke_color), None, &path);
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
}
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
@@ -724,8 +791,6 @@ impl OverlayContextInternal {
#[allow(clippy::too_many_arguments)]
fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let transform = self.get_transform();
let start = self.snap_to_physical_pixel_center(start);
let end = self.snap_to_physical_pixel_center(end);
@@ -740,7 +805,7 @@ impl OverlayContextInternal {
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
}
self.scene.stroke(&stroke, transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &path);
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
}
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
@@ -860,6 +925,26 @@ impl OverlayContextInternal {
kurbo::Affine::scale(self.viewport.scale())
}
/// Strokes `shape`, given in logical pixels, dashing only the parts near the viewport when the stroke is dashed, since a shape reaching far past it
/// (as deep zoom makes them) would have more dashes than memory holds. Each part keeps the dash phase it has along the whole shape.
fn stroke_in_view(&mut self, stroke: &kurbo::Stroke, color: peniko::Color, shape: &impl kurbo::Shape) {
let transform = self.get_transform();
let margin = stroke.width + 1.;
let size = self.viewport.size().into_dvec2();
let visible = kurbo::Rect::new(-margin, -margin, size.x + margin, size.y + margin);
if stroke.dash_pattern.is_empty() || rect_contains(visible, shape.bounding_box()) {
self.scene.stroke(stroke, transform, color, None, shape);
return;
}
for (distance, piece) in pieces_in_view(&shape.to_path(OVERLAY_SHAPE_TOLERANCE), visible) {
let piece_stroke = stroke.clone().with_dashes(stroke.dash_offset + distance, stroke.dash_pattern.iter().copied());
self.scene.stroke(&piece_stroke, transform, color, None, &piece);
}
}
fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
let size = size.unwrap_or(MANIPULATOR_GROUP_MARKER_SIZE);
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
@@ -940,7 +1025,7 @@ impl OverlayContextInternal {
if let Some(dash_width) = dash_width {
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
}
self.scene.stroke(&stroke, transform, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), None, &arc);
self.stroke_in_view(&stroke, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), &arc);
}
fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
@@ -1431,3 +1516,39 @@ impl OverlayContextInternal {
(physical_corner / scale, physical_size / scale)
}
}
#[cfg(test)]
mod tests {
use super::*;
const VISIBLE: kurbo::Rect = kurbo::Rect::new(0., 0., 800., 600.);
#[test]
fn a_huge_line_keeps_only_its_part_in_view_at_its_distance_along_the_line() {
let mut path = BezPath::new();
path.move_to((-1e12, 300.));
path.line_to((1e12, 300.));
let pieces = pieces_in_view(&path, VISIBLE);
assert_eq!(pieces.len(), 1);
// The piece starts as far along as its start lies from the line's, so its dashes line up with the whole line's
let (distance, piece) = &pieces[0];
let start = piece.elements()[0].end_point().unwrap_or_default();
assert!((-2.0..=0.).contains(&start.x), "the piece starts at {start:?}");
assert!((distance - (start.x + 1e12)).abs() < 1e-3, "the piece starts {distance} along the line");
}
#[test]
fn a_huge_circle_through_the_view_keeps_a_few_short_pieces() {
let radius = 1e12;
let circle = kurbo::Circle::new((400. - radius, 300.), radius);
// The circle's path starts at its rightmost point, in view, so the part in view is split between its start and end
let pieces = pieces_in_view(&kurbo::Shape::to_path(&circle, OVERLAY_SHAPE_TOLERANCE), VISIBLE);
assert!((1..=2).contains(&pieces.len()), "{} pieces", pieces.len());
let elements: usize = pieces.iter().map(|(_, piece)| piece.elements().len()).sum();
assert!(elements < 1000, "{elements} elements");
}
}
@@ -22,7 +22,6 @@ pub struct ResourceMessageHandler {
pub embedded: EmbeddedResources,
#[serde(skip)]
pending_resolves: HashSet<ResourceId>,
/// Resources that failed to load, which rendering no longer waits on, even during a retry.
#[serde(skip)]
failed_resolves: HashSet<ResourceId>,
}
@@ -219,8 +218,6 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
ResourceMessage::ResolveFailed { resource_id } => {
self.pending_resolves.remove(&resource_id);
self.failed_resolves.insert(resource_id);
// Rendering stops waiting on the resource and draws a fallback in its place
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
@@ -236,20 +233,6 @@ impl ResourceMessageHandler {
self.registry.is_empty() && self.embedded.is_empty()
}
/// Whether a resource lacks its data and hasn't failed to load, which rendering waits for.
pub fn awaiting_resources(&self) -> bool {
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
}
/// Changes whenever a resource gains, loses, or changes its data. Summed per resource since the registry's order isn't stable. O(resolved resources).
pub fn resolved_hash(&self) -> u64 {
self.registry.resolved().fold(0, |sum, info| {
let mut hasher = DefaultHasher::new();
(info.id, info.hash).hash(&mut hasher);
sum.wrapping_add(hasher.finish())
})
}
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
let embedded = self
.registry
@@ -275,6 +258,18 @@ impl ResourceMessageHandler {
self.registry.delete(&id);
});
}
pub fn awaiting_resources(&self) -> bool {
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
}
pub fn resolved_hash(&self) -> u64 {
self.registry.resolved().fold(0, |sum, info| {
let mut hasher = DefaultHasher::new();
(info.id, info.hash).hash(&mut hasher);
sum.wrapping_add(hasher.finish())
})
}
}
// TODO: Eventually remove this document upgrade code
@@ -46,8 +46,6 @@ pub struct DocumentMetadata {
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
pub clip_targets: HashSet<NodeId>,
pub vector_modify: HashMap<NodeId, VectorGeometry>,
/// Per node with a footprint input, the unit square mapped onto its area in document space.
pub footprint_areas: HashMap<NodeId, DAffine2>,
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
@@ -57,7 +57,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
@@ -72,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
use graphene_std::vector::{Vector, VectorModificationType};
use kurbo::BezPath;
use memo_network::MemoNetwork;
use serde_json::{Value, json};
use serde_json::Value;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::ops::Deref;
@@ -1,4 +1,4 @@
use super::template::NodeTemplateImplementation;
use super::template::{NodeTemplate, NodeTemplateImplementation};
use super::{InputConnector, OutputConnector, catalog};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
let custom = NodeId::new();
let blend = NodeId::new();
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
panic!("the Blend should name a table entry")
@@ -2614,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let shaken = editor
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
.await;
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
@@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let path = [subgraph];
editor.enter_editable_network(subgraph).await;
@@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddImport).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
@@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
);
}
#[tokio::test]
async fn a_new_subgraph_is_its_own_definition() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &editor.active_document().network_interface;
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
}
#[tokio::test]
async fn cannot_preview_node_without_outputs() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
// Attempting to toggle preview on a node without outputs should not enable previewing
network_interface.toggle_preview(custom_node, &[]);
network_interface.toggle_preview(subgraph, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
}
@@ -1,9 +1,7 @@
use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
use std::hash::{Hash, Hasher};
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
impl NodeNetworkInterface {
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
@@ -802,7 +800,7 @@ impl NodeNetworkInterface {
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
}
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
self.reference(node_id, network_path)
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
@@ -829,17 +827,26 @@ impl NodeNetworkInterface {
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
}
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
return false;
};
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
}
node_metadata
.get(proto_node_identifier)
.and_then(|metadata| metadata.fields.get(index))
.is_some_and(|field| field.internal)
/// The metadata the node macro records for a proto node's parameter, or graph text describes for a graph node's import.
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
}
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
return None;
};
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
let field = graphene_std::graph_text::GRAPHS.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
(field.name == input_name).then(|| field.clone())
}
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
@@ -875,16 +882,16 @@ impl NodeNetworkInterface {
node.set_widget_override(index, widget_override);
}
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string())
.unwrap_or_else(|| "Subgraph".to_string())
}
/// The uneditable name in the Inspector which represents the function name of the node implementation.
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string())
.unwrap_or_else(|| "Subgraph".to_string())
}
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
@@ -138,7 +138,6 @@ impl NodeNetworkInterface {
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
self.document_metadata.footprint_areas.retain(|node, _| nodes.contains(node));
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
@@ -190,11 +189,6 @@ impl NodeNetworkInterface {
self.document_metadata.vector_modify = new_vector_modify;
}
/// Update the cached document space areas of the nodes with a footprint input
pub fn update_footprint_areas(&mut self, new_footprint_areas: HashMap<NodeId, DAffine2>) {
self.document_metadata.footprint_areas = new_footprint_areas;
}
/// Update the layer vector data (for layers without Path nodes)
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
self.document_metadata.mark_changed();
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
}
impl NodeTemplate {
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
pub fn empty_subgraph() -> Self {
Self {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
}
}
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
self.inputs.get(P::INDEX)
@@ -867,51 +867,11 @@ impl PartialEq for DocumentNodeMetadata {
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NumberInputSettings {
pub unit: Option<String>,
pub min: Option<f64>,
pub max: Option<f64>,
pub step: Option<f64>,
pub mode: NumberInputMode,
pub range_min: Option<f64>,
pub range_max: Option<f64>,
pub is_integer: bool,
pub blank_assist: bool,
}
impl Default for NumberInputSettings {
fn default() -> Self {
NumberInputSettings {
unit: None,
min: None,
max: None,
step: None,
mode: NumberInputMode::default(),
range_min: None,
range_max: None,
is_integer: false,
blank_assist: true,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct Vec2InputSettings {
pub x: String,
pub y: String,
pub unit: String,
pub min: Option<f64>,
pub is_integer: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum WidgetOverride {
None,
Hidden,
String(String),
Number(NumberInputSettings),
Vec2(Vec2InputSettings),
Custom(String),
}
@@ -948,40 +908,6 @@ impl InputPersistentMetadata {
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
self.widget_override = Some("string".to_string());
}
WidgetOverride::Number(mut number_inspector) => {
if let Some(unit) = number_inspector.unit.take() {
self.input_data.insert("unit".to_string(), json!(unit));
}
if let Some(min) = number_inspector.min.take() {
self.input_data.insert("min".to_string(), json!(min));
}
if let Some(max) = number_inspector.max.take() {
self.input_data.insert("max".to_string(), json!(max));
}
if let Some(step) = number_inspector.step.take() {
self.input_data.insert("step".to_string(), json!(step));
}
if let Some(range_min) = number_inspector.range_min.take() {
self.input_data.insert("range_min".to_string(), json!(range_min));
}
if let Some(range_max) = number_inspector.range_max.take() {
self.input_data.insert("range_max".to_string(), json!(range_max));
}
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
self.widget_override = Some("number".to_string());
}
WidgetOverride::Vec2(vec2_inspector) => {
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
if let Some(min) = vec2_inspector.min {
self.input_data.insert("min".to_string(), json!(min));
}
self.widget_override = Some("vec2".to_string());
}
WidgetOverride::Custom(lambda_name) => {
self.widget_override = Some(lambda_name);
}
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
.ok()
.flatten()
.map(|identifier| identifier.implementation_name_from_identifier())
.unwrap_or("Custom Node".to_string())
.unwrap_or("Subgraph".to_string())
}
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
@@ -12,6 +12,7 @@ use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::{Type, concrete, item, list};
use graphene_std::Color;
use graphene_std::NodeParameter;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::extract_xy::XY;
@@ -471,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
NodeReplacement {
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
aliases: &[
"graphene_math_nodes::Vec2ValueNode",
"graphene_core::ops::ConstructVector2",
@@ -483,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
aliases: &["math_nodes::CombineVec2Node"],
},
// ================================
@@ -538,8 +539,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::ChannelMixerNode",
],
},
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -547,6 +549,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
"raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
@@ -651,8 +654,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_raster_nodes::std_nodes::MandelbrotNode", "graphene_std::raster::MandelbrotNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::MaskNode", "graphene_std::raster::MaskNode", "graphene_std::raster::MaskImageNode"],
node: graphene_std::blending_nodes::masks::mask::IDENTIFIER,
aliases: &[
"raster_nodes::std_nodes::MaskNode",
"graphene_raster_nodes::std_nodes::MaskNode",
"graphene_std::raster::MaskNode",
"graphene_std::raster::MaskImageNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::posterize::IDENTIFIER,
@@ -1279,12 +1287,15 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *new == graphene_std::vector::weld::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Merge by Distance");
}
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
.network_interface
@@ -1565,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
let split_wrapper_replacements = [
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
];
for (old_reference, new_identifier) in split_wrapper_replacements {
@@ -1630,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
if EXTRACT_XY.contains(&name) {
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
} else if EXTRACT_CHANNEL.contains(&name) {
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
} else {
@@ -1760,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.collect();
migrate_custom_node_subgraphs(document);
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
let nodes = document
.network_interface
@@ -1898,6 +1911,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if let Some(size) = clipped_size {
fill_square_with_pattern(document, node_id, network_path, *size);
}
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
move_mandelbrot_to_old_origin(document, node_id, network_path);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
@@ -2031,6 +2047,46 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
Some(())
}
/// Keeps an old Mandelbrot's look now that the complex plane's origin is its pattern's, with a third of a unit's scale and a Transform moving the pattern back to where
/// the old unit square, which spanned the plane from -2 to 1, put that origin.
fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbrot_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*mandelbrot_node_id, 0)))
.cloned()
.unwrap_or_default();
let transform_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER))?.default_node_template();
let origin_transform_id = NodeId::new();
document.network_interface.insert_node(origin_transform_id, transform_template, network_path);
document.network_interface.set_input(
&InputConnector::node_at_index(*mandelbrot_node_id, graphene_std::raster_nodes::std_nodes::mandelbrot::ScaleInput::INDEX),
NodeInput::value(TaggedValue::Number(1. / 3.), false),
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(origin_transform_id, 1),
NodeInput::value(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5)), false),
network_path,
);
document
.network_interface
.set_input(&InputConnector::node_at_index(origin_transform_id, 0), NodeInput::node(*mandelbrot_node_id, 0), network_path);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(origin_transform_id, 0), network_path);
}
// The Transform takes the pattern's place, and the pattern moves before it
if let Some(position) = document.network_interface.position(mandelbrot_node_id, network_path) {
document.network_interface.set_absolute_position(&origin_transform_id, position, network_path);
document.network_interface.set_absolute_position(mandelbrot_node_id, position + IVec2::new(-7, 0), network_path);
}
Some(())
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -2157,6 +2213,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 3;
}
// 'Mask' gained its mode, density, feather, and invert inputs when it learned to mask any graphic, which take the definition's defaults
if reference == DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::masks::mask::IDENTIFIER) && inputs_count == 2 {
let definition = resolve_document_node_type(&reference)?;
let mut template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
inputs_count = 6;
}
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
@@ -2326,6 +2394,24 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 5;
}
// 'Drop Shadow', 'Inner Shadow', and 'Outer Glow' gained a blend mode after their color, set to Normal to keep compositing them as before
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
let lacks_blend_mode = |identifier: ProtoNodeIdentifier, count: usize| reference == DefinitionIdentifier::ProtoNode(identifier) && inputs_count == count;
if lacks_blend_mode(drop_shadow::IDENTIFIER, 8) || lacks_blend_mode(inner_shadow::IDENTIFIER, 7) || lacks_blend_mode(outer_glow::IDENTIFIER, 7) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
let index = if index < 2 { index } else { index + 1 };
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
let normal = NodeInput::value(TaggedValue::BlendMode(graphene_std::blending::BlendMode::Normal), false);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), normal, network_path);
inputs_count += 1;
}
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
@@ -2560,7 +2646,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
];
for (parameter, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -2771,8 +2856,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
@@ -3962,6 +4047,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(())
}
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in subgraphs {
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
document.network_interface.set_reference(&node_id, &network_path, None);
}
}
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
@@ -4514,6 +4618,45 @@ mod tests {
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
}
#[tokio::test]
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
let document = editor.active_document_mut();
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
panic!("the subgraph should name a definitions table entry")
};
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
let from_merging = NodeId::new();
let instance = NodeTemplate {
implementation: NodeTemplateImplementation::Definition(shared),
..Default::default()
};
document.network_interface.insert_node(from_merging, instance, &[]);
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
for node_id in [from_catalog, from_merging] {
assert!(
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
"the subgraph should still exist"
);
assert_eq!(interface.reference(&node_id, &[]), None);
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
}
}
#[tokio::test]
async fn a_rasterize_node_on_the_export_compiles() {
use crate::test_utils::test_prelude::*;
@@ -5000,7 +5143,11 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
let (&count_conversion_id, count_conversion) = network_template
.nodes
.iter_mut()
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
.expect("Blend should have a count conversion node");
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
document.network_interface.insert_node(node_id, node_template, &[]);
@@ -5017,7 +5164,7 @@ mod tests {
panic!("Blend should stay a network node")
};
assert_eq!(
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
);
}
@@ -5034,7 +5181,11 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
let (&edited_subtract_id, edited_subtract) = network_template
.nodes
.iter_mut()
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
.expect("Blend should have an open-path denominator node");
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
@@ -5044,7 +5195,7 @@ mod tests {
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
panic!("Blend should stay a network node")
};
let edited_subtract = derived_node_id(*definition, NodeId(5));
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
}
@@ -5126,8 +5277,15 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Regex Find should be a network node")
};
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
};
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
migrate(&mut document);
@@ -5141,9 +5299,9 @@ mod tests {
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
panic!("Regex Find should stay a network node")
};
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
assert_eq!(
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::Integer(0))
);
}
@@ -5669,6 +5827,54 @@ mod tests {
}
}
#[test]
fn shadows_and_glows_from_before_their_blend_mode_open_blending_normally() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::blending::BlendMode;
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
let saved_nodes = [(drop_shadow::IDENTIFIER, 8), (inner_shadow::IDENTIFIER, 7), (outer_glow::IDENTIFIER, 7)];
let template = |identifier: &ProtoNodeIdentifier| {
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier.clone())).expect("the definition should exist");
definition.default_node_template()
};
// Each node as saved before the blend mode, with each number marked by its index so the shift shows
let mut document = DocumentMessageHandler::default();
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
let mut inputs = template(identifier).inputs;
inputs.remove(2);
inputs.truncate(*count);
for (input_index, input) in inputs.iter_mut().enumerate() {
if matches!(input.as_value(), Some(TaggedValue::Number(_))) {
*input = NodeInput::value(TaggedValue::Number(input_index as f64), false);
}
}
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(identifier.clone()),
inputs,
..Default::default()
};
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
}
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
let node = opened.network_interface.document_node(&NodeId(index as u64 + 1), &[]).expect("the node should still exist");
let name = identifier.as_str();
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
for (input_index, input) in node.inputs.iter().enumerate().take(count + 1).skip(3) {
if let Some(TaggedValue::Number(number)) = input.as_value() {
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
}
}
}
}
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
#[test]
fn removed_nodes_open_as_their_stand_ins() {
@@ -6213,13 +6419,24 @@ mod tests {
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
assert_eq!(upstream(paint, 0), Some(pattern));
// The Mandelbrot is also moved back to where its old unit square put the complex plane's origin
let mut read = upstream(paint, 0).expect("the paint should read the pattern");
if pattern == mandelbrot {
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
read = upstream(read, 0).expect("the origin transform should read the pattern");
}
assert_eq!(read, pattern);
}
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
// Noise settings shift past the removed Clip toggle, and Mandelbrot gains its primary input and settings, its scale a third of a unit like its old unit square's
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 11);
assert_eq!(
value(mandelbrot, graphene_std::raster_nodes::std_nodes::mandelbrot::ScaleInput::INDEX),
Some(TaggedValue::Number(1. / 3.))
);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
@@ -989,16 +989,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} => {
let document_id = self.active_document_id.expect("Tried to render non-existent document");
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
// An export now would capture the fallbacks drawn in place of fonts and images still loading
if document.resources.awaiting_resources() {
responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: "The document's fonts or images are still loading. Try again once they finish.".to_string(),
});
return;
}
let export_config = ExportConfig {
name,
file_type,
@@ -1035,7 +1025,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
// Skip rendering while a resource is still loading, so its fallback isn't drawn in the meantime.
// Skip rendering while a resource is still loading, so its error isn't shown in the meantime.
// Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left.
if document.resources.awaiting_resources() {
return;
@@ -1,332 +0,0 @@
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, SelectedEdges};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::context::bake_footprint;
use graphene_std::platform_application_io::rasterize;
use graphene_std::renderer::Quad;
use graphene_std::transform::Footprint;
/// A transform cage that resizes and moves the area of the selected node with a footprint input.
#[derive(Clone, Debug, Default)]
pub struct FootprintCage {
target: Option<CageTarget>,
drag: Option<CageDrag>,
}
#[derive(Clone, Debug)]
struct CageTarget {
footprint_input: InputConnector,
area: Footprint,
/// Spans the area, with the unit square as its bounds.
bounding_box: BoundingBoxManager,
}
#[derive(Clone, Debug)]
struct CageDrag {
footprint_input: InputConnector,
original_area: Footprint,
unit_square_to_viewport: DAffine2,
kind: CageDragKind,
}
#[derive(Clone, Debug)]
enum CageDragKind {
Resize(SelectedEdges),
Move { grab: DVec2 },
}
impl FootprintCage {
/// Places the cage on the area of the selected node with a footprint input, or removes it if it is hidden or there is none.
pub fn refresh(&mut self, document: &DocumentMessageHandler, visible: bool) {
self.target = visible.then(|| Self::find_target(document)).flatten();
}
fn find_target(document: &DocumentMessageHandler) -> Option<CageTarget> {
let network_path = document.selection_network_path();
let network_interface = &document.network_interface;
let selected_nodes = network_interface.selected_nodes_in_nested_network(network_path)?;
let mut footprint_inputs = selected_nodes.selected_nodes().filter_map(|&node_id| footprint_input(node_id, network_interface, network_path));
let footprint_input = footprint_inputs.next()?;
if footprint_inputs.next().is_some() {
return None;
}
let node_id = footprint_input.node_id()?;
let input = network_interface.input_from_connector(&footprint_input, network_path)?;
let &TaggedValue::Footprint(area) = input.as_non_exposed_value()? else { return None };
let unit_square_to_document = *document.metadata().footprint_areas.get(&node_id)?;
let unit_square_to_viewport = document.metadata().document_to_viewport * unit_square_to_document;
if unit_square_to_viewport.matrix2.determinant() == 0. {
return None;
}
let bounding_box = BoundingBoxManager {
bounds: [DVec2::ZERO, DVec2::ONE],
transform: unit_square_to_viewport,
..Default::default()
};
Some(CageTarget { footprint_input, area, bounding_box })
}
pub fn overlays(&mut self, overlay_context: &mut OverlayContext) {
if let Some(target) = &mut self.target {
target.bounding_box.render_overlays(overlay_context, true);
}
}
/// The cursor for the part of the cage under the pointer, if any.
pub fn cursor(&self, input: &InputPreprocessorMessageHandler) -> Option<MouseCursorIcon> {
let target = self.target.as_ref()?;
let edge_cursor = target.bounding_box.get_cursor(input, false, false, None);
if edge_cursor != MouseCursorIcon::Default {
return Some(edge_cursor);
}
target.contains(input.mouse.position).then_some(MouseCursorIcon::Move)
}
/// Begins resizing or moving the area if the pointer is on the cage, returning whether it did.
pub fn begin_drag(&mut self, mouse: DVec2, responses: &mut VecDeque<Message>) -> bool {
let Some(target) = &self.target else { return false };
let bounding_box = &target.bounding_box;
let kind = if let Some((top, bottom, left, right)) = bounding_box.check_selected_edges(mouse) {
CageDragKind::Resize(SelectedEdges::new(top, bottom, left, right, bounding_box.bounds))
} else if target.contains(mouse) {
CageDragKind::Move {
grab: bounding_box.transform.inverse().transform_point2(mouse),
}
} else {
return false;
};
self.drag = Some(CageDrag {
footprint_input: target.footprint_input,
original_area: target.area,
unit_square_to_viewport: bounding_box.transform,
kind,
});
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Changed a Footprint".into() });
true
}
/// Moves or resizes the area to follow the pointer, keeping its pixel density.
pub fn update_drag(&mut self, mouse: DVec2, centered: bool, constrain: bool, responses: &mut VecDeque<Message>) {
let Some(drag) = &self.drag else { return };
let (position, size) = match &drag.kind {
CageDragKind::Resize(edges) => {
let center = drag.unit_square_to_viewport.transform_point2(DVec2::splat(0.5));
let (position, size) = edges.new_size(mouse, drag.unit_square_to_viewport, centered.then_some(center), constrain, None);
(position.min(position + size), size.abs())
}
CageDragKind::Move { grab } => {
let pointer = drag.unit_square_to_viewport.inverse().transform_point2(mouse);
(pointer - *grab, DVec2::ONE)
}
};
let original_area = drag.original_area;
let one_pixel = original_area.resolution.as_dvec2().recip();
let size = size.max(one_pixel);
let area = Footprint {
transform: original_area.transform * DAffine2::from_scale_angle_translation(size, 0., position),
resolution: (original_area.resolution.as_dvec2() * size).round().as_uvec2().max(UVec2::ONE),
..original_area
};
responses.add(NodeGraphMessage::SetInput {
input_connector: drag.footprint_input,
input: NodeInput::value(TaggedValue::Footprint(area), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Keeps the drag in place on the document while the viewport pans by `shift`.
pub fn pan(&mut self, shift: DVec2) {
if let Some(drag) = &mut self.drag {
drag.unit_square_to_viewport.translation += shift;
}
}
/// Finishes the drag, undoing its changes if it was aborted.
pub fn end_drag(&mut self, aborted: bool, responses: &mut VecDeque<Message>) {
if self.drag.take().is_none() {
return;
}
responses.add(if aborted { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction });
}
}
/// The input holding the footprint of a node that has one.
fn footprint_input(node_id: NodeId, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<InputConnector> {
let reference = network_interface.reference(&node_id, network_path)?;
if reference == DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER) {
Some(InputConnector::node(node_id, bake_footprint::FootprintInput))
} else if reference == DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER) {
Some(InputConnector::node(node_id, rasterize::FootprintInput))
} else {
None
}
}
impl CageTarget {
fn contains(&self, viewport_point: DVec2) -> bool {
(self.bounding_box.transform * Quad::from_box(self.bounding_box.bounds)).contains(viewport_point)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::test_prelude::*;
#[tokio::test]
async fn a_bake_footprint_node_in_a_layer_reports_where_its_area_lies() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let document = editor.active_document();
let input = document.network_interface.input_from_connector(&InputConnector::node(node_id, bake_footprint::FootprintInput), &[]);
let Some(&TaggedValue::Footprint(area)) = input.and_then(NodeInput::as_non_exposed_value) else {
panic!("the node should have a footprint value")
};
let metadata = document.metadata();
let baked_area = metadata.footprint_areas.get(&node_id).expect("the render should report where the node baked its area");
let layer_content_to_viewport = metadata.upstream_footprints.get(&layer.to_node()).expect("the render should report the layer's footprint").transform;
let expected = metadata.rendered_document_to_viewport.inverse() * layer_content_to_viewport * area.transform;
assert!(baked_area.abs_diff_eq(expected, 1e-9), "{baked_area:?} should be {expected:?}");
}
#[tokio::test]
async fn a_baked_area_moves_with_a_transform_applied_after_it() {
use graphene_std::transform_nodes::transform;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let bake_footprint_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
node_id: bake_footprint_node,
parent: layer,
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let untransformed = *editor.active_document().metadata().footprint_areas.get(&bake_footprint_node).expect("the area should be reported");
let transform_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(transform::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
node_id: transform_node,
parent: layer,
})
.await;
let translation = DVec2::new(100., 50.);
editor
.handle_message(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(transform_node, transform::TranslationInput),
input: NodeInput::value(TaggedValue::DVec2(translation), false),
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let transformed = *editor
.active_document()
.metadata()
.footprint_areas
.get(&bake_footprint_node)
.expect("the area should still be reported");
let expected = DAffine2::from_translation(translation) * untransformed;
assert!(transformed.abs_diff_eq(expected, 1e-9), "{transformed:?} should be {expected:?}");
}
/// Drags the cage of a 'Bake Footprint' node in a layer between two points of its unit square, giving its area before and after.
async fn drag_cage(from: DVec2, to: DVec2) -> (Footprint, Footprint) {
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::tool::utility_types::ToolType;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
let area = Footprint {
transform: DAffine2::from_scale(DVec2::splat(100.)),
resolution: UVec2::splat(200),
..Default::default()
};
let footprint_input = InputConnector::node(node_id, bake_footprint::FootprintInput);
editor
.handle_message(NodeGraphMessage::SetInput {
input_connector: footprint_input,
input: NodeInput::value(TaggedValue::Footprint(area), false),
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
let metadata = editor.active_document().metadata();
let unit_square_to_viewport = metadata.document_to_viewport * *metadata.footprint_areas.get(&node_id).expect("the area should be reported");
let (from, to) = (unit_square_to_viewport.transform_point2(from), unit_square_to_viewport.transform_point2(to));
editor.select_tool(ToolType::Select).await;
editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await;
editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await;
editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await;
let input = editor.active_document().network_interface.input_from_connector(&footprint_input, &[]);
let Some(&TaggedValue::Footprint(dragged)) = input.and_then(NodeInput::as_non_exposed_value) else {
panic!("the node should have a footprint value")
};
(area, dragged)
}
#[tokio::test]
async fn dragging_the_right_edge_of_the_cage_widens_the_area_and_its_resolution() {
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(1.5, 0.5)).await;
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(1.5, 1.));
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
assert_eq!(dragged.resolution, UVec2::new(300, 200));
}
#[tokio::test]
async fn dragging_the_right_edge_onto_the_left_one_keeps_one_pixel_of_width() {
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(0., 0.5)).await;
let one_pixel = 1. / area.resolution.x as f64;
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(one_pixel, 1.));
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
assert_eq!(dragged.resolution, UVec2::new(1, 200));
}
}
@@ -1,3 +1,2 @@
pub mod footprint_cage;
pub mod gizmo_manager;
pub mod shape_gizmos;
@@ -15,7 +15,6 @@ use crate::messages::tool::common_functionality::color_selector::{
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state,
};
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
use crate::messages::tool::common_functionality::gizmos::footprint_cage::FootprintCage;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::measure;
use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
@@ -506,7 +505,6 @@ enum SelectToolFsmState {
},
RotatingBounds,
DraggingPivot,
DraggingFootprintCage,
}
impl Default for SelectToolFsmState {
@@ -547,7 +545,6 @@ struct SelectToolData {
axis_align: bool,
non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>,
bounding_box_manager: Option<BoundingBoxManager>,
footprint_cage: FootprintCage,
cursor: MouseCursorIcon,
pivot_gizmo: PivotGizmo,
/// The pivot as it was when a drag of it began, restored if the drag is aborted.
@@ -957,9 +954,6 @@ impl Fsm for SelectToolFsmState {
(_, SelectToolMessage::Overlays { context: mut overlay_context }) => {
crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document);
tool_data.footprint_cage.refresh(document, overlay_context.visibility_settings.transform_cage());
tool_data.footprint_cage.overlays(&mut overlay_context);
let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count();
let paintable_layers_selected = has_paintable_selection(document);
tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected;
@@ -1394,10 +1388,6 @@ impl Fsm for SelectToolFsmState {
tool_data.drag_current = input.mouse.position;
tool_data.selection_mode = None;
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_none() && tool_data.footprint_cage.begin_drag(input.mouse.position, responses) {
return SelectToolFsmState::DraggingFootprintCage;
}
let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>();
let intersection = document.find_deepest(&intersection_list);
@@ -1630,18 +1620,6 @@ impl Fsm for SelectToolFsmState {
remove,
}
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerMove { modifier_keys }) => {
let (centered, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align));
tool_data.footprint_cage.update_drag(input.mouse.position, centered, constrain, responses);
let messages = [
SelectToolMessage::PointerOutsideViewport { modifier_keys: modifier_keys.clone() }.into(),
SelectToolMessage::PointerMove { modifier_keys }.into(),
];
tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses);
SelectToolFsmState::DraggingFootprintCage
}
(SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => {
if let Some(bounds) = &mut tool_data.bounding_box_manager {
resize_bounds(
@@ -1743,10 +1721,6 @@ impl Fsm for SelectToolFsmState {
.as_ref()
.map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge)));
if let Some(footprint_cage_cursor) = tool_data.footprint_cage.cursor(input) {
cursor = footprint_cage_cursor;
}
// Dragging the pivot overrules the other operations
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() {
cursor = MouseCursorIcon::Move;
@@ -1798,14 +1772,6 @@ impl Fsm for SelectToolFsmState {
self
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerOutsideViewport { .. }) => {
// Auto-panning
if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) {
tool_data.footprint_cage.pan(shift);
}
self
}
(SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => {
// Auto-panning
let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses);
@@ -1951,14 +1917,6 @@ impl Fsm for SelectToolFsmState {
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => {
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
tool_data.footprint_cage.end_drag(drag_too_small, responses);
responses.add(OverlaysMessage::Draw);
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => {
let quad = tool_data.selection_quad();
@@ -2048,13 +2006,6 @@ impl Fsm for SelectToolFsmState {
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::Abort) => {
tool_data.footprint_cage.end_drag(true, responses);
responses.add(OverlaysMessage::Draw);
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => {
responses.add(DocumentMessage::AbortTransaction);
tool_data.axis_align = false;
@@ -2224,13 +2175,6 @@ impl Fsm for SelectToolFsmState {
]);
hint_data.send_layout(responses);
}
SelectToolFsmState::DraggingFootprintCage => {
let hint_data = HintData(vec![
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
HintGroup(vec![HintInfo::keys([Key::Alt], "From Center"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]),
]);
hint_data.send_layout(responses);
}
SelectToolFsmState::RotatingBounds => {
let hint_data = HintData(vec![
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
+48 -22
View File
@@ -1,4 +1,5 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
@@ -6,27 +7,24 @@ use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::proto::{GraphErrorType, GraphErrors};
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::list::{Item, List};
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
mod observations;
#[cfg(test)]
mod recompile_tests;
mod runtime;
pub use observations::ObservationKey;
use observations::{path_content_observations, path_contents};
pub use runtime::*;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
@@ -45,6 +43,18 @@ pub struct ExecutionResponse {
observations: HashMap<ObservationKey, InspectResult>,
}
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
#[derive(Debug)]
pub enum ExecutionResult {
Pending,
@@ -274,7 +284,6 @@ impl NodeGraphExecutor {
self.inspect_context_overrides = ContextOverrides::default();
}
// The compile looks up each resource's data in the registry, so a resource that loads reruns it like an edit to the network does
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone();
@@ -632,7 +641,6 @@ impl NodeGraphExecutor {
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_footprint_areas(HashMap::new());
if let Some(message) = &message {
log::error!("Node graph evaluation failed:\n{message}");
}
@@ -692,13 +700,6 @@ impl NodeGraphExecutor {
if let Err((_, e)) = &result {
log::trace!("Gradient migration measurement compile: {e}");
}
// A fallback drawn in place of a missing font or image would be measured instead, so the fills wait for a later open
if node_graph_warnings.iter().any(|warning| matches!(warning.error, GraphErrorType::MissingResource { .. })) {
self.cancel_gradient_migration();
self.gradient_migration_attempted.insert(document_id);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
continue;
}
@@ -709,7 +710,6 @@ impl NodeGraphExecutor {
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_footprint_areas(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
@@ -1057,7 +1057,6 @@ impl NodeGraphExecutor {
outlines,
group_layers,
text_frames,
footprint_areas,
clip_targets,
vector_data,
appearance_attributes,
@@ -1065,9 +1064,6 @@ impl NodeGraphExecutor {
backgrounds: _,
} = render_output.metadata;
let viewport_to_document = document_to_viewport.inverse();
let footprint_areas = footprint_areas.into_iter().map(|(node_id, area)| (node_id, viewport_to_document * area)).collect();
// Run these update state messages immediately
responses.add(DocumentMessage::UpdateUpstreamTransforms {
upstream_footprints,
@@ -1078,7 +1074,6 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers });
responses.add(DocumentMessage::UpdateOutlines { outlines });
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateFootprintAreas { footprint_areas });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
@@ -1227,6 +1222,37 @@ fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
}
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
// Re-export for usage by tests in other modules
#[cfg(test)]
pub use test::Instrumented;
@@ -1,51 +0,0 @@
use super::{InspectResult, Observation, ObservedConnector};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use graph_craft::document::NodeId;
use graphene_std::list::{Item, List};
use graphene_std::vector::{Vector, VectorGeometry, path, paths_from_list_row_attributes};
use graphene_std::{ContextOverrides, NodeParameter};
use std::collections::HashMap;
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
pub(super) fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
pub(super) fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
+51 -136
View File
@@ -3,12 +3,12 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task};
use graph_craft::application_io::resource::{Resource, ResourceRegistry};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::ops::ConvertAsync;
@@ -18,7 +18,7 @@ use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer;
@@ -43,6 +43,7 @@ pub struct NodeRuntime {
pub(super) executor: DynamicExecutor,
#[cfg(not(test))]
executor: DynamicExecutor,
output: OutputHandle,
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
@@ -134,28 +135,6 @@ pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId
}
}
/// A warning for each input holding a resource the registry can't resolve, placed in the first instance of a network that several nodes share.
fn missing_resource_warnings(network: &NodeNetwork, resources: &ResourceRegistry) -> GraphErrors {
network
.recursive_nodes()
.flat_map(|(node_id, node, network_path)| {
node.inputs.iter().enumerate().filter_map(move |(index, input)| {
let NodeInput::Value { tagged_value, .. } = input else { return None };
let TaggedValue::Resource(resource_id) = &**tagged_value else { return None };
resources.hash(resource_id).is_none().then(|| GraphError {
node_path: [network_path.as_slice(), &[*node_id]].concat(),
identifier: match &node.implementation {
DocumentNodeImplementation::ProtoNode(identifier) => identifier.as_str().to_string().into(),
_ => Default::default(),
},
error: GraphErrorType::MissingResource { index },
})
})
})
.collect()
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportConfig {
pub name: String,
@@ -170,6 +149,7 @@ impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
Self {
executor: DynamicExecutor::default(),
output: OutputHandle::default(),
receiver,
sender,
editor_wake,
@@ -272,7 +252,7 @@ impl NodeRuntime {
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(&network);
let result = self.update_network(network.clone());
self.compile_failed = result.is_err();
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
@@ -485,7 +465,7 @@ impl NodeRuntime {
}
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
@@ -541,23 +521,12 @@ impl NodeRuntime {
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
}
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph.clone(), self.editor_api.clone(), self.async_runtime().handle());
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
// A missing resource compiles as the empty one, which its consumers draw with a fallback, and warns on the nodes using it
let resource_missing = std::cell::Cell::new(false);
let resolve_resource = |resource_id| {
self.resources.hash(&resource_id).or_else(|| {
resource_missing.set(true);
Some(Resource::empty().hash())
})
};
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &resolve_resource) {
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
}
if resource_missing.get() {
self.node_graph_warnings = missing_resource_warnings(graph, &self.resources);
}
// We assume only one output
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
@@ -572,10 +541,14 @@ impl NodeRuntime {
}
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings.extend(warnings);
self.node_graph_warnings = warnings;
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
let updated = self.executor.update(proto_network).map(|(output, types)| {
self.output = output;
types
});
let result = updated.map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
});
@@ -591,7 +564,7 @@ impl NodeRuntime {
paths.into()
};
let mut errors = Vec::new();
let output = self.executor.output();
let output = self.output.node();
let mut pending = vec![(vec![paths(output)], output, error)];
while let Some((mut trace, node, error)) = pending.pop() {
let passed = self.executor.trace_error(node, error);
@@ -908,59 +881,22 @@ mod tests {
}
#[tokio::test]
async fn a_missing_resource_renders_with_a_warning_on_its_node() {
async fn a_resource_that_loads_recompiles_the_unchanged_network() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use graph_craft::application_io::resource::ResourceId;
use graphene_std::raster_nodes::std_nodes::image;
let mut editor = editor().await;
// The layer shows an 'Image' node holding an image the document has no record of
let image_node = NodeId::new();
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(image_node),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the graph should render with the missing image left empty");
assert!(editor.portfolio_message_handler_mut().executor.take_evaluation_errors().is_none());
let resolved_types = &editor.active_document().network_interface.resolved_types;
assert!(resolved_types.node_graph_errors.is_empty(), "{:?}", resolved_types.node_graph_errors);
let warnings = resolved_types.node_graph_warnings.as_slice();
let expected = GraphErrorType::MissingResource { index: 1 };
assert!(matches!(warnings, [warning] if warning.node_path == [image_node] && warning.error == expected), "{warnings:?}");
}
#[tokio::test]
async fn a_resource_that_fails_to_load_renders_with_a_fallback_until_it_loads() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use crate::test_utils::test_prelude::{Color, Image};
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
use graphene_std::raster_nodes::std_nodes::image;
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back the graph's warnings and whether it drew an image.
async fn render_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> (GraphErrors, bool) {
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back whether it drew an image.
async fn image_drawn_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> bool {
editor.dispatch(message);
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
let image_drawn = messages
messages
.iter()
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()));
let resolved_types = &editor.active_document().network_interface.resolved_types;
assert!(resolved_types.node_graph_errors.is_empty(), "{:?}", resolved_types.node_graph_errors);
(resolved_types.node_graph_warnings.clone(), image_drawn)
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()))
}
let mut editor = editor().await;
@@ -987,71 +923,50 @@ mod tests {
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
let (warnings, _) = render_after(&mut editor, NodeGraphMessage::RunDocumentGraph).await;
assert!(warnings.is_empty(), "the graph shouldn't run while the image may still load: {warnings:?}");
// Failing to load sends the network while the image has no data
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
let (warnings, image_drawn) = render_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
let expected = GraphErrorType::MissingResource { index: 1 };
assert!(
matches!(warnings.as_slice(), [warning] if warning.node_path == [image_node] && warning.error == expected),
"{warnings:?}"
);
assert!(!image_drawn, "the image that failed to load should be left empty");
image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
// Loading it later, as a retry would, has to recompile the unchanged network
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
let hash = ResourceHash::from(data.as_ref());
editor.dispatch(ResourceStorageMessage::Store { data });
let resolved = ResourceMessage::Resolved { resource_id, source, hash }.into();
let (warnings, image_drawn) = render_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await;
assert!(warnings.is_empty(), "the warning should clear once the image loads: {warnings:?}");
assert!(image_drawn, "the image should be drawn once it loads");
assert!(image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await);
}
#[tokio::test]
async fn an_export_is_refused_while_its_resources_load() {
async fn a_missing_resource_renders_with_an_error_traced_through_its_node() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use graph_craft::application_io::resource::{DataSource, ResourceId};
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use graph_craft::application_io::resource::ResourceId;
use graphene_std::platform_application_io::MissingResourceError;
use graphene_std::raster_nodes::std_nodes::image;
/// Requests an export and lets the runtime evaluate whatever was sent, giving back whether it explained a refusal and whether it exported.
async fn refused_and_exported(editor: &mut EditorTestUtils) -> (bool, bool) {
let messages = editor.dispatch(PortfolioMessage::SubmitDocumentExport {
name: "export".to_string(),
file_type: FileType::Svg,
scale_factor: 1.,
bounds: ExportBounds::AllArtwork,
artboard_name: None,
artboard_count: 0,
});
let refused = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
editor.runtime.update();
editor.runtime.run().await;
(refused, exported(editor))
}
let mut editor = editor().await;
let document_id = editor.portfolio_message_handler().active_document_id.unwrap();
// An 'Image' node whose image is known only by where to load it from
let resource_id = ResourceId::new();
let source = DataSource::Url("https://example.com/image.png".parse().unwrap());
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source);
let template = resolve_proto_node_type(image::IDENTIFIER)
.unwrap()
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
editor.active_document_mut().network_interface.insert_node(NodeId::new(), template, &[]);
// The layer shows an 'Image' node holding an image the document has no record of
let image_node = NodeId::new();
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(image_node),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
let outcome = refused_and_exported(&mut editor).await;
assert_eq!(outcome, (true, false), "the export shouldn't capture the image's fallback while it may still load");
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
// Once the image fails to load, its fallback is all there is to export
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
editor.dispatch(PortfolioMessage::DocumentPassMessage { document_id, message: failed });
let outcome = refused_and_exported(&mut editor).await;
assert_eq!(outcome, (false, true), "the export should go ahead once nothing is left loading");
let errors = editor.portfolio_message_handler_mut().executor.take_evaluation_errors().unwrap();
assert!(
errors
.iter()
.any(|(error, trace)| error.is::<MissingResourceError>() && trace.iter().flatten().any(|path| **path == [image_node])),
"{errors:?}"
);
}
#[tokio::test]
@@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
#[cfg(test)]
mod tests {
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
use crate::test_utils::test_prelude::*;
use glam::UVec2;
use graph_craft::document::NodeId;
@@ -429,8 +430,20 @@ mod tests {
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
// The node adding Merge's content to the stack
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
panic!("Merge should be a network node")
};
let Some((&extend_id, _)) = merge_network
.nodes
.iter()
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
else {
panic!("Merge should extend the stack with its content")
};
compile_and_run(&mut editor).await;
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
assert_eq!(
editor.runtime.thumbnails.sources.get(&layer).copied(),
+11
View File
@@ -423,6 +423,17 @@ impl EditorTestUtils {
self.create_node(node_type, Some((x, y))).await
}
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
node_id: Some(node_id),
xy: Some((x, y)),
})
.await;
node_id
}
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
+16 -2
View File
@@ -34,12 +34,24 @@
background: #222;
}
body.loading-progress::before {
background-image:
url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='2' fill='%23eee'/></svg>"),
url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='2' fill='%23444'/></svg>");
background-position: left calc(50vw - 80px) top calc(50vh + 64px);
background-size:
calc(var(--loading-progress, 0) * 160px) 4px,
160px 4px;
background-repeat: no-repeat;
}
body::after {
content: "";
display: block;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 60px;
height: 60px;
border-radius: 50%;
@@ -50,6 +62,8 @@
@media (prefers-reduced-motion) {
border: none;
animation: none;
width: auto;
height: auto;
content: "Loading…";
font-family: Arial, sans-serif;
font-size: 24px;
@@ -58,10 +72,10 @@
@keyframes spinning-loading-indicator {
0% {
transform: translate(-30px, -30px) rotate(0deg);
transform: translate(-50%, -50%) rotate(0deg);
}
100% {
transform: translate(-30px, -30px) rotate(360deg);
transform: translate(-50%, -50%) rotate(360deg);
}
}
</style>
+11
View File
@@ -5,6 +5,7 @@
import type { MessageName, SubscriptionsRouter } from "/src/subscriptions-router";
import { joinSessionFromUrl, loadDemoArtwork } from "/src/utility-functions/network";
import { operatingSystem } from "/src/utility-functions/platform";
import { registerServiceWorker } from "/src/utility-functions/service-worker";
import { initWasm } from "/src/utility-functions/wasm-loader";
import { EditorWrapper, receiveNativeMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { FrontendMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -18,6 +19,10 @@
try {
// Initialize the editor wrapper
const wrapper = await initWasm();
// Register the service worker, except in dev mode and native builds
if (!import.meta.env.DEV && import.meta.env.MODE !== "native" && "serviceWorker" in navigator) registerServiceWorker();
for (const [name, f] of Object.entries(wrapper)) {
if (name.startsWith("__node_registry") || name.startsWith("__migration_registry")) f();
}
@@ -57,6 +62,12 @@
{/if}
<style lang="scss">
// Disable the loading indicator
body:has(.main-window, .startup-error)::before,
body:has(.main-window, .startup-error)::after {
content: none !important;
}
.startup-error {
position: absolute;
inset: 0;
-6
View File
@@ -82,12 +82,6 @@
<MainWindow />
<style lang="scss">
// Disable the spinning loading indicator
body::before,
body::after {
content: none !important;
}
:root {
--color-0-black: #000;
--color-1-nearblack: #111;
@@ -84,10 +84,12 @@
--row-height: 24px;
&:has(.slider-input) {
margin-top: 16px;
margin-top: 8px;
.number-input {
flex: 0 0 auto;
// Level with the gradient strip, below the slider's room for its midpoint diamonds
margin-top: 8px;
margin-left: 8px;
min-width: 0;
width: calc(24px + 8px + 24px);
@@ -670,7 +670,7 @@
<LayoutCol
class="slider-input"
classes={{ narrow, disabled, "range-slider": rangeSlider }}
classes={{ narrow, disabled, "range-slider": rangeSlider, "with-midpoints": showMidpoints }}
styles={{
"--gradient-start": trackStartCSS,
"--gradient-end": trackEndCSS,
@@ -830,11 +830,17 @@
opacity: 0.5;
}
// Room for the diamonds above the strip, inside the widget so rows that clip their overflow still show them
&.with-midpoints {
padding-top: 8px;
}
.midpoint-track {
position: absolute;
top: 0;
left: var(--marker-half-width);
right: var(--marker-half-width);
height: 8px;
.midpoint {
position: absolute;
+2 -1
View File
@@ -6,8 +6,9 @@ interface Window {
receiveNativeMessage?: (buffer: ArrayBuffer) => void;
}
// Build-time constant injected by the `wasmSplitting` plugin in `vite.config.ts`
// Build-time constants injected by plugins in `vite.config.ts`
declare const __WASM_PART_COUNT__: number;
declare const __WASM_SIZE__: number;
// Graphite's custom "pointerlockmove" event dispatched by input.ts for pointer lock in the CEF desktop app
interface WindowEventMap {
+8
View File
@@ -124,6 +124,7 @@ import NodeAsVector from "/../branding/assets/16x16-nodes/node-as-vector.svg";
import NodeAverage from "/../branding/assets/16x16-nodes/node-average.svg";
import NodeBakeTransform from "/../branding/assets/16x16-nodes/node-bake-transform.svg";
import NodeBasicBrush from "/../branding/assets/16x16-nodes/node-basic-brush.svg";
import NodeBevelAndEmboss from "/../branding/assets/16x16-nodes/node-bevel-and-emboss.svg";
import NodeBevel from "/../branding/assets/16x16-nodes/node-bevel.svg";
import NodeBlackAndWhite from "/../branding/assets/16x16-nodes/node-black-and-white.svg";
import NodeBlendMode from "/../branding/assets/16x16-nodes/node-blend-mode.svg";
@@ -223,6 +224,7 @@ import NodeImageToChannels from "/../branding/assets/16x16-nodes/node-image-to-c
import NodeImage from "/../branding/assets/16x16-nodes/node-image.svg";
import NodeIndexPoints from "/../branding/assets/16x16-nodes/node-index-points.svg";
import NodeIndices from "/../branding/assets/16x16-nodes/node-indices.svg";
import NodeInnerGlow from "/../branding/assets/16x16-nodes/node-inner-glow.svg";
import NodeInnerShadow from "/../branding/assets/16x16-nodes/node-inner-shadow.svg";
import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-transform.svg";
import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg";
@@ -277,6 +279,7 @@ import NodeOpacity from "/../branding/assets/16x16-nodes/node-opacity.svg";
import NodeOpenEnds from "/../branding/assets/16x16-nodes/node-open-ends.svg";
import NodeOriginsToPolyline from "/../branding/assets/16x16-nodes/node-origins-to-polyline.svg";
import NodeOuterGlow from "/../branding/assets/16x16-nodes/node-outer-glow.svg";
import NodeOutline from "/../branding/assets/16x16-nodes/node-outline.svg";
import NodePackStrips from "/../branding/assets/16x16-nodes/node-pack-strips.svg";
import NodePassthrough from "/../branding/assets/16x16-nodes/node-passthrough.svg";
import NodePathIsClosed from "/../branding/assets/16x16-nodes/node-path-is-closed.svg";
@@ -325,6 +328,7 @@ import NodeRoot from "/../branding/assets/16x16-nodes/node-root.svg";
import NodeRoundCorners from "/../branding/assets/16x16-nodes/node-round-corners.svg";
import NodeRound from "/../branding/assets/16x16-nodes/node-round.svg";
import NodeSamplePolyline from "/../branding/assets/16x16-nodes/node-sample-polyline.svg";
import NodeSatin from "/../branding/assets/16x16-nodes/node-satin.svg";
import NodeScatterPoints from "/../branding/assets/16x16-nodes/node-scatter-points.svg";
import NodeSelectiveColor from "/../branding/assets/16x16-nodes/node-selective-color.svg";
import NodeSeparatePaths from "/../branding/assets/16x16-nodes/node-separate-paths.svg";
@@ -415,6 +419,7 @@ export const ICON_16X16_NODES = {
NodeBakeTransform: { svg: NodeBakeTransform, size: 16 },
NodeBasicBrush: { svg: NodeBasicBrush, size: 16 },
NodeBevel: { svg: NodeBevel, size: 16 },
NodeBevelAndEmboss: { svg: NodeBevelAndEmboss, size: 16 },
NodeBlackAndWhite: { svg: NodeBlackAndWhite, size: 16 },
NodeBlend: { svg: NodeBlend, size: 16 },
NodeBlendMode: { svg: NodeBlendMode, size: 16 },
@@ -513,6 +518,7 @@ export const ICON_16X16_NODES = {
NodeImageToChannels: { svg: NodeImageToChannels, size: 16 },
NodeIndexPoints: { svg: NodeIndexPoints, size: 16 },
NodeIndices: { svg: NodeIndices, size: 16 },
NodeInnerGlow: { svg: NodeInnerGlow, size: 16 },
NodeInnerShadow: { svg: NodeInnerShadow, size: 16 },
NodeInvert: { svg: NodeInvert, size: 16 },
NodeInvertTransform: { svg: NodeInvertTransform, size: 16 },
@@ -567,6 +573,7 @@ export const ICON_16X16_NODES = {
NodeOpenEnds: { svg: NodeOpenEnds, size: 16 },
NodeOriginsToPolyline: { svg: NodeOriginsToPolyline, size: 16 },
NodeOuterGlow: { svg: NodeOuterGlow, size: 16 },
NodeOutline: { svg: NodeOutline, size: 16 },
NodePackStrips: { svg: NodePackStrips, size: 16 },
NodePassthrough: { svg: NodePassthrough, size: 16 },
NodePath: { svg: NodePath, size: 16 },
@@ -615,6 +622,7 @@ export const ICON_16X16_NODES = {
NodeRound: { svg: NodeRound, size: 16 },
NodeRoundCorners: { svg: NodeRoundCorners, size: 16 },
NodeSamplePolyline: { svg: NodeSamplePolyline, size: 16 },
NodeSatin: { svg: NodeSatin, size: 16 },
NodeScatterPoints: { svg: NodeScatterPoints, size: 16 },
NodeSelectiveColor: { svg: NodeSelectiveColor, size: 16 },
NodeSeparatePaths: { svg: NodeSeparatePaths, size: 16 },
-6
View File
@@ -2,12 +2,6 @@
import { mount, unmount } from "svelte";
import App from "/src/App.svelte";
import { registerServiceWorker } from "/src/utility-functions/service-worker";
// Register the service worker, except in dev mode and native (CEF) builds
if (!import.meta.env.DEV && import.meta.env.MODE !== "native" && "serviceWorker" in navigator) {
registerServiceWorker();
}
document.body.setAttribute("data-app-container", "");
+22 -17
View File
@@ -19,6 +19,11 @@ const DEFERRED_ENTRIES = new Map(DEFERRED_CACHE_MANIFEST.map((entry) => [new URL
// Caching strategies
// ==================
function withoutRedirect(response) {
if (!response.redirected) return response;
return new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers });
}
function isCacheable(response) {
// Cache normal successful responses and opaque responses (cross-origin no-cors, e.g. <link> stylesheets)
return response.ok || response.type === "opaque";
@@ -47,6 +52,20 @@ async function networkFirst(request, cacheName) {
}
}
async function latestIndexHtml(request) {
const cache = await caches.open(STATIC_CACHE_NAME);
const cached = await cache.match("/index.html");
if (!cached) return fetch(request);
if (!navigator.onLine) return cached;
const network = fetch("/", { cache: "no-cache" }).then(
(response) => (response.ok ? withoutRedirect(response) : cached),
() => cached,
);
const timeout = new Promise((resolve) => setTimeout(() => resolve(cached), 1000));
return Promise.race([network, timeout]);
}
// ================
// Lifecycle events
// ================
@@ -60,15 +79,7 @@ self.addEventListener("install", (event) => {
PRECACHE_MANIFEST.map(async (entry) => {
const response = await fetch(entry.url);
if (!response.ok) throw new Error(`Precache fetch failed for ${entry.url}: ${response.status}`);
// Strip the `redirected` flag which causes errors when served via respondWith
const cleaned = response.redirected
? new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
})
: response;
await cache.put(entry.url, cleaned);
await cache.put(entry.url, withoutRedirect(response));
}),
);
@@ -148,15 +159,9 @@ self.addEventListener("fetch", (event) => {
return;
}
// Navigation requests: serve cached index.html for all routes (SPA pattern)
// Navigation requests: serve index.html for all routes (SPA pattern)
if (request.mode === "navigate") {
event.respondWith(
(async () => {
const cache = await caches.open(STATIC_CACHE_NAME);
const cached = await cache.match("/index.html");
return cached || fetch(request);
})(),
);
event.respondWith(latestIndexHtml(request));
return;
}
@@ -1,16 +1,16 @@
export async function registerServiceWorker() {
try {
const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/" });
// When a new service worker is found, auto-reload once it activates
registration.addEventListener("updatefound", () => {
const newWorker = registration.installing;
newWorker?.addEventListener("statechange", () => {
// Only reload if there was a previous controller, meaning this is an update, not first install
if (newWorker.state === "activated" && navigator.serviceWorker.controller) window.location.reload();
});
navigator.serviceWorker.addEventListener("controllerchange", () => {
const controller = navigator.serviceWorker.controller;
const reloadIfRemoved = async () => {
if (controller?.state === "activated" && !(await caches.match(import.meta.url))) window.location.reload();
};
reloadIfRemoved();
controller?.addEventListener("statechange", reloadIfRemoved);
});
const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/" });
const activeWorker = registration.active || registration.waiting || registration.installing;
if (!activeWorker) return;
+46 -11
View File
@@ -4,22 +4,57 @@ import wasmBinaryUrl from "/wrapper/pkg/graphite_wasm_wrapper_bg.wasm?url";
// Initializes the editor's Wasm module, rejoining the parts that CI deployments split the binary into
// to fit under the single-file size limit (see `wasmSplitting` in `vite.config.ts`)
export async function initWasm() {
// Local and native builds keep the binary whole, letting the wasm-bindgen glue code load it directly
if (__WASM_PART_COUNT__ <= 1) return init();
if (__WASM_PART_COUNT__ <= 1 && __WASM_SIZE__ === 0) return init();
// Fetch all parts in parallel (served from the service worker's precache once it is installed)
const partRequests = [];
for (let index = 0; index < __WASM_PART_COUNT__; index += 1) {
partRequests.push(fetch(wasmBinaryUrl.replace(/\.wasm$/, `-part${index}.wasm`)));
}
const partResponses = await Promise.all(partRequests);
const partUrls = __WASM_PART_COUNT__ <= 1 ? [wasmBinaryUrl] : Array.from({ length: __WASM_PART_COUNT__ }, (_, index) => wasmBinaryUrl.replace(/\.wasm$/, `-part${index}.wasm`));
// Read the parts straight from the service worker's precache when it has them
const partResponses = (await cachedParts(partUrls)) || downloadParts(partUrls);
const failedResponse = partResponses.find((response) => !response.ok);
if (failedResponse) throw new Error(`Failed to fetch Wasm binary part (status ${failedResponse.status}): ${failedResponse.url}`);
// eslint-disable-next-line camelcase
if (partResponses.length === 1) return init({ module_or_path: await partResponses[0] });
// Rejoin the parts and hand them to wasm-bindgen as a single response, with the MIME type needed for streaming compilation
const parts = await Promise.all(partResponses.map((response) => response.blob()));
const parts = await Promise.all(partResponses.map(async (response) => (await response).blob()));
const joined = new Response(new Blob(parts), { headers: { "Content-Type": "application/wasm" } });
// eslint-disable-next-line camelcase
return init({ module_or_path: joined });
}
async function cachedParts(urls: string[]): Promise<Response[] | undefined> {
try {
const responses = await Promise.all(urls.map((url) => caches.match(url)));
if (responses.every((response): response is Response => response !== undefined)) return responses;
} catch {
// Cache Storage is unavailable, such as in some private windows
}
return undefined;
}
function downloadParts(urls: string[]): Promise<Response>[] {
const trackProgress = trackDownloadProgress();
return urls.map(async (url) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch Wasm binary part (status ${response.status}): ${response.url}`);
return trackProgress(response);
});
}
function trackDownloadProgress(): (response: Response) => Response {
let loadedBytes = 0;
document.body.style.setProperty("--loading-progress", "0");
document.body.classList.add("loading-progress");
return (response) => {
if (!response.body) return response;
const counter = new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
loadedBytes += chunk.byteLength;
document.body.style.setProperty("--loading-progress", String(Math.min(loadedBytes / __WASM_SIZE__, 1)));
controller.enqueue(chunk);
},
});
return new Response(response.body.pipeThrough(counter), { status: response.status, statusText: response.statusText, headers: response.headers });
};
}
+16 -1
View File
@@ -18,11 +18,12 @@ export default defineConfig(({ mode }) => {
wasmEditorReload(),
staticAssets(),
mode !== "native" && thirdPartyLicenses(),
mode !== "native" && wasmSize(),
mode !== "native" && wasmSplitting(),
mode !== "native" && serviceWorker(),
],
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
define: { __WASM_PART_COUNT__: "1" },
define: { __WASM_SIZE__: "0", __WASM_PART_COUNT__: "1" },
resolve: {
alias: [
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
@@ -177,6 +178,20 @@ function thirdPartyLicenses(): PluginOption {
};
}
function wasmSize(): PluginOption {
return {
name: "wasm-size",
config(_, { command }) {
if (command !== "build") return;
const wasmPath = path.resolve(projectRootDir, "wrapper/pkg/graphite_wasm_wrapper_bg.wasm");
if (!existsSync(wasmPath)) return;
return { define: { __WASM_SIZE__: String(statSync(wasmPath).size) } };
},
};
}
// Splits the Wasm binary into parts small enough for Cloudflare Pages' 25 MiB single-file limit, rejoined at runtime by `initWasm()` in `src/utility-functions/wasm-loader.ts`.
// Only active when the `SPLIT_WASM` environment variable is set, which CI does for deployments; local builds keep the single file.
function wasmSplitting(): PluginOption {
+35 -2
View File
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
}
```
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from its graph text (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
## Inspector
@@ -127,7 +127,40 @@ fn opacity<T>(
## Additional Macro Options
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
## Creating a node from a subgraph
A node built from other nodes is written in graph text, a Rust-like syntax parsed at runtime by the `graph-text` crate. Built-in graphs are registered with the `core_types::graph!` macro, which only records the text and where it's written. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
```rs
graph! {
#![syntax(1)]
use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
/// Loads an image from a given URL.
#[category("Data: I/O"), icon("NodeLoadImage")]
fn load_image@1(
_,
/// The web address or local asset path of the image to load.
#[name("URL")]
url,
) -> (
/// The loaded image.
image,
) {
load_resource(url) >> bytes_to_image()
}
}
```
The text starts with its syntax version, `#![syntax(1)]`. The `use` section names each node by its identifier's module path and function name, at the declaration version it was written for, and `as` renames one. A graph's own version follows its name, like `load_image@1`. The graph's attributes are `category`, `icon`, `name`, and `layer`, and its name (or the title derived from its function name) is its catalog identifier, which documents store.
The function's parameters are the subgraph's imports, written without types, and `_` is a primary import that takes nothing. An import inherits its type, default, description, and widget settings from the inner parameter of its own name that it feeds, or else from the first one, and its attributes override those: `name`, `expose`, `default`, `widget`, `unit`, `hard`, `soft`, `range`, `step`, `display_decimal_places`, `multiline`, `progression`, `labels`, `integer`, and `blank_assist`. The exports are named in parentheses after `->`.
In the body, `let` binds a node, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. A value has the type it's written with, so `1` is an integer and `1.` a number, and `#[exposed]` before an argument exposes its value. State methods after a call, each written once, set the node's display name (`.named("…")`) and flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`). Nodes are placed left of the node they feed, so positions are only written to adjust that, with `.offset(x, y)` or `.at(x, y)` in grid units. A graph's output name after a call or binding, like `.captures`, wires from that output instead of the primary one. The body ends with one value per export.
The `every_graph_resolves` test in `subgraphs.rs` reports any graph whose text doesn't resolve, with the place it's written. Every input a call leaves out keeps the default from the node's own definition.
## Executing a document `NodeNetwork`
+54 -1
View File
@@ -531,12 +531,20 @@ tagged_value! {
CellularDistanceFunction(raster_nodes::adjustments::CellularDistanceFunction),
CellularReturnType(raster_nodes::adjustments::CellularReturnType),
DomainWarpType(raster_nodes::adjustments::DomainWarpType),
MandelbrotFractal(raster_nodes::adjustments::MandelbrotFractal),
MandelbrotExterior(raster_nodes::adjustments::MandelbrotExterior),
MandelbrotInterior(raster_nodes::adjustments::MandelbrotInterior),
RelativeAbsolute(raster_nodes::adjustments::RelativeAbsolute),
SelectiveColorChoice(raster_nodes::adjustments::SelectiveColorChoice),
TonalRange(raster_nodes::adjustments::TonalRange),
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
GlowTechnique(graphic_types::GlowTechnique),
GlowSource(graphic_types::GlowSource),
MaskMode(graphic_types::MaskMode),
BevelStyle(graphic_types::BevelStyle),
BevelDirection(graphic_types::BevelDirection),
BevelTechnique(graphic_types::BevelTechnique),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
@@ -687,6 +695,46 @@ impl TaggedValue {
})
}
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
let mut choices = input.split("::");
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
if first == "StrokeAlign" {
return Some(match second {
"Center" => vector::style::StrokeAlign::Center,
"Inside" => vector::style::StrokeAlign::Inside,
"Outside" => vector::style::StrokeAlign::Outside,
_ => {
log::error!("Invalid StrokeAlign default type variant: {input}");
return None;
}
});
}
log::error!("Invalid StrokeAlign default type: {input}");
None
}
fn to_blend_mode(input: &str) -> Option<core_types::blending::BlendMode> {
use core_types::blending::BlendMode;
let Some(("BlendMode", variant)) = input.split_once("::").map(|(first, second)| (first.trim(), second.trim())) else {
log::error!("Invalid BlendMode default type: {input}");
return None;
};
// The variants hidden from the standard list are valid defaults too
let blend_mode = BlendMode::list()
.into_iter()
.flatten()
.chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha])
.find(|blend_mode| format!("{blend_mode:?}") == variant)
.copied();
if blend_mode.is_none() {
log::error!("Invalid BlendMode default type variant: {input}");
}
blend_mode
}
match ty {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
@@ -706,9 +754,14 @@ impl TaggedValue {
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
_ => return None,
_ => {
log::error!("No parser for a default value of type `{}`: {string}", concrete_type.name);
return None;
}
};
Some(ty)
}
-9
View File
@@ -602,10 +602,6 @@ pub enum GraphErrorType {
NonConstantInput {
index: usize,
},
/// The input's value refers to a resource the document can't resolve to its data.
MissingResource {
index: usize,
},
}
impl Debug for GraphErrorType {
// TODO: format with the document graph context so the input index is the same as in the graph UI.
@@ -654,11 +650,6 @@ impl Debug for GraphErrorType {
"Warning: an upstream node adapts to the visible canvas area, so this node's output changes when the view is panned or zoomed"
),
GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1),
GraphErrorType::MissingResource { index } => write!(
f,
"Warning: input {} needs a font, image, or other resource that can't be found, so a fallback is used in its place",
index + 1
),
}
}
}
+23 -12
View File
@@ -1,6 +1,5 @@
use crate::TokioSpawner;
use graph_craft::document::value::{DAffine2, DVec2, RenderOutputType, TaggedValue, UVec2};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::core_types::ops::ConvertAsync;
use graphene_std::core_types::transform::Footprint;
@@ -9,7 +8,7 @@ use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::{no_paths, paths_from_item_attributes};
use graphene_std::{NodeError, Poll};
use image::ImageFormat;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::error::Error;
use std::io::Cursor;
use std::path::{Path, PathBuf};
@@ -88,12 +87,12 @@ pub struct Framing {
impl ExportSettings {
/// Frame the artwork as it is at time zero, unless a size was given.
/// Every frame of an animation shares this framing, so they all have one size.
pub async fn framed(mut self, executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
pub async fn framed(mut self, executor: &DynamicExecutor, output: &OutputHandle, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
if self.size.0.is_some() && self.size.1.is_some() {
return Ok(self);
}
let [min, max] = artwork_bounds(executor, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
let [min, max] = artwork_bounds(executor, output, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
let resolution = ((max - min) * self.scale).round().max(DVec2::ONE).as_uvec2();
self.framing = Some(Framing {
transform: DAffine2::from_translation(min).inverse(),
@@ -105,7 +104,7 @@ impl ExportSettings {
/// The document-space bounds of every layer including its stroke, artboards included, from the metadata of an SVG render.
/// Content an artboard clips away still counts, since this has no layer tree to tell which artboard holds it.
async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
async fn artwork_bounds(executor: &DynamicExecutor, output: &OutputHandle, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
// An identity viewport, since the default one is degenerate and its transforms come out NaN
let render_config = RenderConfig {
viewport: Footprint {
@@ -118,7 +117,7 @@ async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spaw
for_export: true,
..Default::default()
};
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, runtime, spawner, render_config).await? else {
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, output, runtime, spawner, render_config).await? else {
return Err("The document did not render".into());
};
@@ -153,6 +152,7 @@ fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DV
/// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type.
pub(crate) async fn render_frame(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
settings: ExportSettings,
animation_time: Duration,
@@ -187,7 +187,7 @@ pub(crate) async fn render_frame(
}
// Execute the graph and extract its output
match execute_until_settled(executor, runtime, spawner, render_config).await? {
match execute_until_settled(executor, output, runtime, spawner, render_config).await? {
TaggedValue::RenderOutput(output) => match output.data {
RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)),
RenderOutputType::Texture(texture) => {
@@ -263,13 +263,14 @@ fn encode_raster(file_type: FileType, data: Vec<u8>, width: u32, height: u32, tr
pub async fn export_document(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
output_path: PathBuf,
settings: ExportSettings,
runtime: &AsyncRuntime,
spawner: &TokioSpawner,
) -> Result<(), Box<dyn Error>> {
let frame = render_frame(executor, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?;
let frame = render_frame(executor, output, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?;
write_frame(&output_path, settings, frame)?;
log::info!("Exported to: {}", output_path.display());
@@ -305,8 +306,10 @@ impl AnimationParams {
}
/// Export an animated GIF by rendering multiple frames at different animation times
#[allow(clippy::too_many_arguments)]
pub async fn export_gif(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
output_path: PathBuf,
settings: ExportSettings,
@@ -334,7 +337,7 @@ pub async fn export_gif(
log::debug!("Rendering frame {}/{} at time {:?}", frame_idx + 1, animation.frames, animation_time);
let RenderedFrame::Raster { data, width, height } = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await? else {
let RenderedFrame::Raster { data, width, height } = render_frame(executor, output, wgpu_executor, settings, animation_time, runtime, spawner).await? else {
return Err("A GIF frame must render as pixels".into());
};
@@ -355,8 +358,10 @@ pub async fn export_gif(
}
/// Export an animation as one numbered file per frame beside the output path (`name_000.png`, `name_001.png`, ..., zero-padded to fit the frame count).
#[allow(clippy::too_many_arguments)]
pub async fn export_image_sequence(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
output_path: PathBuf,
settings: ExportSettings,
@@ -378,7 +383,7 @@ pub async fn export_image_sequence(
// Print progress to stderr (overwrites previous line)
eprint!("\rRendering frame {}/{}...", frame_idx + 1, animation.frames);
let frame = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await?;
let frame = render_frame(executor, output, wgpu_executor, settings, animation_time, runtime, spawner).await?;
let frame_path = directory.join(format!("{stem}_{frame_idx:0digits$}.{extension}"));
write_frame(&frame_path, settings, frame)?;
}
@@ -390,8 +395,14 @@ pub async fn export_image_sequence(
Ok(())
}
pub async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result<TaggedValue, Box<dyn Error>> {
let execute = || executor.execute(render_config.into_context_with_generations(runtime.snapshot()));
pub async fn execute_until_settled(
executor: &DynamicExecutor,
output: &OutputHandle,
runtime: &AsyncRuntime,
spawner: &TokioSpawner,
render_config: RenderConfig,
) -> Result<TaggedValue, Box<dyn Error>> {
let execute = || executor.execute(output, render_config.into_context_with_generations(runtime.snapshot()));
let mut frame = execute()?;
while spawner.join().await {
frame = execute()?;
+10 -11
View File
@@ -12,7 +12,7 @@ use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork;
use graphene_std::application_io::ApplicationIo;
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_in_scope;
use std::collections::HashMap;
@@ -111,13 +111,6 @@ pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_ap
Ok(compiled_network.network)
}
pub fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
DynamicExecutor::new(proto_network).map_err(|errors| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n").into()
})
}
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await;
let spawner = Arc::new(TokioSpawner::default());
@@ -134,7 +127,11 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
impl CompiledDocument {
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
let executor = create_executor(self.proto_network)?;
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n")
})?;
self.runtime.update_sources(executor.sources());
let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone();
@@ -151,6 +148,7 @@ impl CompiledDocument {
Ok(Renderer {
executor,
output,
application_io: self.application_io,
runtime: self.runtime,
spawner: self.spawner,
@@ -162,6 +160,7 @@ impl CompiledDocument {
/// Executes a compiled document, polling its GPU device until dropped.
pub struct Renderer {
pub executor: DynamicExecutor,
pub output: OutputHandle,
pub runtime: AsyncRuntime,
pub spawner: Arc<TokioSpawner>,
application_io: Arc<PlatformApplicationIo>,
@@ -175,12 +174,12 @@ impl Renderer {
/// Fit `settings` to the artwork, unless they give a size.
pub async fn frame(&self, settings: export::ExportSettings) -> Result<export::ExportSettings, Box<dyn Error>> {
settings.framed(&self.executor, &self.runtime, &self.spawner).await
settings.framed(&self.executor, &self.output, &self.runtime, &self.spawner).await
}
/// Render one frame at `animation_time`.
pub async fn render(&self, settings: export::ExportSettings, animation_time: std::time::Duration) -> Result<export::RenderedFrame, Box<dyn Error>> {
export::render_frame(&self.executor, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
export::render_frame(&self.executor, &self.output, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
}
}
+3 -3
View File
@@ -198,14 +198,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
let settings = renderer.frame(settings).await?;
let animation = export::AnimationParams::new(fps, frames, duration);
if file_type == export::FileType::Gif {
export::export_gif(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
export::export_gif(executor, &renderer.output, wgpu_executor, output, settings, animation, runtime, spawner).await?;
} else if animation.frames > 1 {
if file_type == export::FileType::Ico {
return Err("ICO can't be exported as an image sequence".into());
}
export::export_image_sequence(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
export::export_image_sequence(executor, &renderer.output, wgpu_executor, output, settings, animation, runtime, spawner).await?;
} else {
export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?;
export::export_document(executor, &renderer.output, wgpu_executor, output, settings, runtime, spawner).await?;
}
}
Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } | Command::Host { .. } | Command::Join { .. } | Command::Watch { .. } => unreachable!("Handled before compiling"),
+14 -9
View File
@@ -2,10 +2,10 @@ use document_live::{Event, LiveDocument};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue, UVec2};
use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export};
use graphene_cli::{TokioSpawner, compile_graph, editor_api, export};
use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig};
use graphene_std::runtime::AsyncRuntime;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::error::Error;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -56,7 +56,7 @@ struct Viewer {
window: Option<Arc<dyn Window>>,
surface: Option<(WgpuSurface, wgpu::SurfaceConfiguration)>,
blitter: Option<TextureBlitter>,
executor: Option<DynamicExecutor>,
executor: Option<(DynamicExecutor, OutputHandle)>,
dirty: bool,
waiting: Vec<ResourceHash>,
}
@@ -132,13 +132,17 @@ impl Viewer {
Ok(proto) => proto,
Err(error) => return log::error!("Compile failed: {error}"),
};
match create_executor(proto) {
Ok(executor) => {
let mut executor = DynamicExecutor::default();
match executor.update(proto) {
Ok((output, _)) => {
self.graph_runtime.update_sources(executor.sources());
log::info!("Document compiled");
self.executor = Some(executor);
self.executor = Some((executor, output));
}
Err((_, errors)) => {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
log::error!("Executor creation failed: {}", messages.join("\n"));
}
Err(error) => log::error!("Executor creation failed: {error}"),
}
}
@@ -149,14 +153,15 @@ impl Viewer {
// Present even without a frame, since Wayland never shows a surface with no committed buffer
let frame = match &self.executor {
Some(executor) => {
Some((executor, output)) => {
let mut render_config = RenderConfig {
export_format: ExportFormat::Raster,
scale: 1.,
..Default::default()
};
render_config.viewport.resolution = UVec2::new(config.width, config.height);
match self.runtime.block_on(export::execute_until_settled(executor, &self.graph_runtime, &self.spawner, render_config))? {
let settled = export::execute_until_settled(executor, output, &self.graph_runtime, &self.spawner, render_config);
match self.runtime.block_on(settled)? {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(texture),
..
@@ -4,11 +4,11 @@ use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile};
use graphene_std::application_io::EditorApi;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::util::wrap_network_in_scope;
use std::path::Path;
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite"))))
.unwrap()
.network;
@@ -17,8 +17,9 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
(executor, proto_network)
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network.clone()).unwrap();
(executor, output, proto_network)
}
#[allow(dead_code, reason = "shared by the bench targets, only some of which call it, and each compiles this module separately")]
@@ -20,7 +20,7 @@ use graphene_std::uuid::NodeId;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use gungraun::{Callgrind, EntryPoint};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
@@ -43,6 +43,7 @@ pub struct Session {
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
output: OutputHandle,
/// The document graph for the measured update.
document: NodeNetwork,
}
@@ -60,6 +61,7 @@ impl Session {
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
output: OutputHandle::default(),
document: NodeNetwork::default(),
};
session.update(brush_layer(&BrushCache::default(), after));
@@ -71,7 +73,7 @@ impl Session {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig {
viewport: Footprint {
@@ -82,7 +84,7 @@ impl Session {
scale: 1.,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
let output = self.executor.tree().eval_tagged_value(self.output.node(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
@@ -8,9 +8,9 @@ fn subsequent_evaluations(c: &mut Criterion) {
let mut group = c.benchmark_group("Subsequent Evaluations");
let context = RenderConfig::default().into_context();
bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name);
let (executor, output, _) = setup_network(name);
let context = context.clone();
g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap()));
g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(output.node(), std::hint::black_box(&context)).unwrap()));
});
group.finish();
}
@@ -3,27 +3,28 @@ mod benchmark_util;
use benchmark_util::setup_network;
use graphene_std::application_io::RenderConfig;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::hint::black_box;
fn setup_run_cached(name: &str) -> DynamicExecutor {
let (executor, _) = setup_network(name);
fn setup_run_cached(name: &str) -> (DynamicExecutor, OutputHandle) {
let (executor, output, _) = setup_network(name);
// Warm up the cache by running once
let context = RenderConfig::default().into_context();
let _ = executor.tree().eval_tagged_value(executor.output(), &context);
let _ = executor.tree().eval_tagged_value(output.node(), &context);
executor
(executor, output)
}
#[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
pub fn run_cached(setup: (DynamicExecutor, OutputHandle)) -> (DynamicExecutor, OutputHandle) {
let (executor, output) = setup;
let context = RenderConfig::default().into_context();
black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap());
black_box(executor.tree().eval_tagged_value(output.node(), black_box(&context)).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
(executor, output)
}
library_benchmark_group!(name = run_cached_group; benchmarks = run_cached);
@@ -1,7 +1,5 @@
use criterion::measurement::Measurement;
use criterion::{BenchmarkGroup, Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile};
use graphene_std::transform::Footprint;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -12,9 +10,8 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
.unwrap()
.network;
let proto_network = compile(network);
let empty = ProtoNetwork::default();
let executor = DynamicExecutor::new(empty).unwrap();
let executor = DynamicExecutor::default();
c.bench_function(name, |b| {
b.iter_batched(
@@ -38,10 +35,11 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
.network;
let proto_network = compile(network);
let executor = DynamicExecutor::new(proto_network).unwrap();
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap();
let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
}
fn run_once_demo(c: &mut Criterion) {
let mut g = c.benchmark_group("Run Once no render");
@@ -12,7 +12,7 @@ fn run_once(c: &mut Criterion) {
g.bench_function(name, |b| {
b.iter_batched(
|| setup_network(name),
|(executor, _)| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap(),
|(executor, output, _)| executor.tree().eval_tagged_value(output.node(), std::hint::black_box(&context)).unwrap(),
criterion::BatchSize::SmallInput,
)
});
@@ -3,22 +3,23 @@ mod benchmark_util;
use benchmark_util::setup_network;
use graphene_std::application_io;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::hint::black_box;
fn setup_run_once(name: &str) -> DynamicExecutor {
let (executor, _) = setup_network(name);
executor
fn setup_run_once(name: &str) -> (DynamicExecutor, OutputHandle) {
let (executor, output, _) = setup_network(name);
(executor, output)
}
#[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
pub fn run_once(setup: (DynamicExecutor, OutputHandle)) -> (DynamicExecutor, OutputHandle) {
let (executor, output) = setup;
let context = application_io::RenderConfig::default().into_context();
black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap());
black_box(executor.tree().eval_tagged_value(output.node(), black_box(&context)).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
(executor, output)
}
library_benchmark_group!(name = run_once_group; benchmarks = run_once);
@@ -2,7 +2,6 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::proto::ProtoNetwork;
use interpreted_executor::dynamic_executor::DynamicExecutor;
fn update_executor(c: &mut Criterion) {
@@ -11,10 +10,8 @@ fn update_executor(c: &mut Criterion) {
g.bench_function(name, |b| {
b.iter_batched(
|| {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network)
let (_, _, proto_network) = setup_network(name);
(DynamicExecutor::default(), proto_network)
},
|(mut executor, network)| executor.update(std::hint::black_box(network)),
criterion::BatchSize::SmallInput,
@@ -7,10 +7,8 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
use std::hint::black_box;
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network)
let (_, _, proto_network) = setup_network(name);
(DynamicExecutor::default(), proto_network)
}
#[library_benchmark]
@@ -3,32 +3,41 @@ use core_types::{NodeError, Poll, SourceId, WasmNotSend};
use graph_craft::Type;
use graph_craft::document::value::{TaggedValue, UpcastNode};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Executor;
use graph_craft::proto::{Any, AnyInput, ConstructionArgs, GraphError, NodeContainer, ProtoNetwork, ProtoNode, SharedNode, SharedNodeContainer, TypeErasedBox, TypeErasedNode, TypingContext};
use graph_craft::proto::{GraphErrorType, GraphErrors};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, Weak};
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
#[derive(Clone)]
pub struct DynamicExecutor {
output: NodeId,
/// Stores all of the dynamic node structs.
tree: BorrowTree,
/// Stores the types of the proto nodes.
typing_context: TypingContext,
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
outputs: Vec<Weak<NodeId>>,
// Kept for one more update, so a node that comes back is reused
orphaned_nodes: HashSet<NodeId>,
}
#[derive(Clone, Debug, Default)]
pub struct OutputHandle(Arc<NodeId>);
impl OutputHandle {
pub fn node(&self) -> NodeId {
*self.0
}
}
impl Default for DynamicExecutor {
fn default() -> Self {
Self {
output: Default::default(),
tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
outputs: Vec::new(),
orphaned_nodes: HashSet::new(),
}
}
@@ -49,28 +58,24 @@ pub struct ResolvedDocumentNodeTypesDelta {
}
impl DynamicExecutor {
pub fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&proto_network)?;
let output = proto_network.output;
let tree = BorrowTree::new(proto_network, &typing_context)?;
Ok(Self {
tree,
output,
typing_context,
orphaned_nodes: HashSet::new(),
})
}
pub fn sources(&self) -> impl Iterator<Item = &SourceId> {
self.tree.sources.iter().map(|(_, source)| source)
}
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.output = proto_network.output;
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let (output, add) = self.insert_nodes(proto_network)?;
let remove = self.free_orphaned_nodes();
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
}
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let (output, add) = self.insert_nodes(proto_network)?;
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.typing_context.update(&proto_network).map_err(|e| {
// If there is an error then get types that have been resolved before the error
let add = proto_network
@@ -92,7 +97,31 @@ impl DynamicExecutor {
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
})?;
let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let output = proto_network.output;
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
self.outputs.retain(|output| output.strong_count() > 0);
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
let output = held.unwrap_or_else(|| {
let output = Arc::new(output);
self.outputs.push(Arc::downgrade(&output));
output
});
let add = self.document_node_types(add.into_iter()).collect();
Ok((OutputHandle(output), add))
}
fn free_orphaned_nodes(&mut self) -> Vec<Path> {
let mut kept = HashSet::new();
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
while let Some(node) = pending.pop() {
if kept.insert(node)
&& let Some((_, _, inputs)) = self.tree.nodes.get(&node)
{
pending.extend(inputs.iter());
}
}
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
for node_id in old_to_remove {
@@ -104,31 +133,23 @@ impl DynamicExecutor {
}
}
}
let add = self.document_node_types(add.into_iter()).collect();
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
remove
}
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let orphaned_nodes = std::mem::take(&mut self.orphaned_nodes);
let result = self.update(proto_network);
self.orphaned_nodes = orphaned_nodes;
result
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
self.tree.eval_tagged_value(output.node(), &input).map_err(|error| error.into())
}
pub fn input_type(&self) -> Option<Type> {
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
pub fn input_type(&self, output: &OutputHandle) -> Option<Type> {
self.typing_context.type_of(output.node()).map(|node_io| node_io.call_argument.clone())
}
pub fn tree(&self) -> &BorrowTree {
&self.tree
}
pub fn output(&self) -> NodeId {
self.output
}
pub fn output_type(&self) -> Option<Type> {
self.typing_context.type_of(self.output).map(|node_io| node_io.return_value.clone())
pub fn output_type(&self, output: &OutputHandle) -> Option<Type> {
self.typing_context.type_of(output.node()).map(|node_io| node_io.return_value.clone())
}
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
@@ -160,15 +181,6 @@ impl DynamicExecutor {
}
}
impl<I> Executor<I, Poll<TaggedValue>> for &DynamicExecutor
where
I: 'static + WasmNotSend,
{
fn execute(&self, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
self.tree.eval_tagged_value(self.output, &input).map_err(|error| error.into())
}
}
pub struct InputMapping {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -285,9 +297,8 @@ impl BorrowTree {
Ok(nodes)
}
/// Pushes new nodes into the tree and return orphaned nodes
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
/// Pushes new nodes into the tree
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Vec<Path>, GraphErrors> {
let mut new_nodes: Vec<_> = Vec::new();
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
for (id, node) in proto_network.nodes {
@@ -297,9 +308,8 @@ impl BorrowTree {
} else if self.update_source_map(id, typing_context, &node) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
}
old_nodes.remove(&id);
}
Ok((new_nodes, old_nodes))
Ok(new_nodes)
}
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> {
@@ -875,11 +875,12 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
#[test]
fn a_trace_leads_to_the_node_that_raised_the_error() {
let executor = DynamicExecutor::new(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
assert!(executor.trace_error(executor.output(), &error_traced_through(&[])).is_empty());
assert_eq!(*executor.trace_error(executor.output(), &error_traced_through(&[0])), [NodeId(0)]);
assert_eq!(*executor.trace_error(executor.output(), &error_traced_through(&[0, 0])), [NodeId(0)], "a value node has no inputs");
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)], "a value node has no inputs");
assert!(executor.trace_error(NodeId(0), &error_traced_through(&[])).is_empty());
assert!(
executor.trace_error(NodeId(0), &error_traced_through(&[0])).is_empty(),
@@ -892,14 +893,15 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]);
let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER;
let executor = DynamicExecutor::new(ProtoNetwork {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
})
.unwrap();
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap();
assert_eq!(*executor.trace_error(executor.output(), &error_traced_through(&[0, 0])), [NodeId(0)]);
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
}
#[test]
@@ -912,21 +914,19 @@ fn executor_panics_reach_the_host_with_the_original_payload() {
}
}
let mut executor = DynamicExecutor {
output: NodeId(0),
..Default::default()
};
let missing_output = (&executor).execute(()).unwrap_err();
let mut executor = DynamicExecutor::default();
let output = OutputHandle::default();
let missing_output = executor.execute(&output, ()).unwrap_err();
assert_eq!(missing_output.to_string(), "Output node not found in executor");
executor.tree.store_node(ObservedNode::new(Box::new(Panics)), NodeId(0), Box::default(), Box::default());
let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (&executor).execute(()))).unwrap_err();
let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| executor.execute(&output, ()))).unwrap_err();
assert_eq!(*payload.downcast::<u32>().unwrap(), 42);
}
#[test]
fn chained_fallbacks_both_reach_the_root() {
let executor = DynamicExecutor::new(ProtoNetwork {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: [
@@ -934,15 +934,16 @@ fn chained_fallbacks_both_reach_the_root() {
vec![(NodeId(3), throw_error_node([0, 1, 2, 1], 3)), (NodeId(4), throw_error_node([3, 1, 2, 1], 4))],
]
.concat(),
})
.unwrap();
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap();
let context: Context = None;
let Ok(Poll::Fallback(boxed)) = (&executor).execute(context) else {
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
panic!("Both nodes fall back, so the root should too")
};
let error = &boxed.1;
assert!(executor.trace_error(executor.output(), error).is_empty());
assert!(executor.trace_error(output.node(), error).is_empty());
let [upstream] = error.upstream() else {
panic!("The second node's error should carry the first node's error")
};
@@ -951,7 +952,7 @@ fn chained_fallbacks_both_reach_the_root() {
#[test]
fn an_error_after_a_fallback_keeps_both() {
let executor = DynamicExecutor::new(ProtoNetwork {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes: [
@@ -963,14 +964,15 @@ fn an_error_after_a_fallback_keeps_both() {
],
]
.concat(),
})
.unwrap();
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap();
let context: Context = None;
let Ok(Poll::Error(error)) = (&executor).execute(context) else {
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
panic!("The failing node should stop the frame")
};
assert!(executor.trace_error(executor.output(), &error).is_empty());
assert!(executor.trace_error(output.node(), &error).is_empty());
let [upstream] = error.upstream() else {
panic!("The failing node's error should carry the fallback before it")
};
@@ -979,7 +981,7 @@ fn an_error_after_a_fallback_keeps_both() {
#[test]
fn a_node_error_names_the_node_that_raised_it() {
let executor = DynamicExecutor::new(ProtoNetwork {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes: [
@@ -991,14 +993,15 @@ fn a_node_error_names_the_node_that_raised_it() {
],
]
.concat(),
})
.expect("The Throw Error nodes should resolve");
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve");
let context: Context = None;
let Ok(Poll::Error(error)) = (&executor).execute(context) else {
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
panic!("The failing node should stop the frame")
};
let origin = executor.trace_error(executor.output(), &error).last().copied();
let origin = executor.trace_error(output.node(), &error).last().copied();
assert_eq!(origin, Some(NodeId(4)), "The error should name the failing node, not the root that forwarded it");
let paths: Vec<_> = executor
.tree()
@@ -1028,11 +1031,11 @@ fn throw_error_node(inputs: [u64; 4], id: u64) -> ProtoNode {
node
}
fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], keep_value: bool) -> DynamicExecutor {
fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], keep_value: bool) -> (DynamicExecutor, OutputHandle) {
let mut handler_node = ProtoNode::value(ConstructionArgs::Nodes(handler_inputs.iter().copied().map(NodeId).collect()), vec![NodeId(6)]);
handler_node.identifier = handler;
DynamicExecutor::new(ProtoNetwork {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(6),
nodes: [
@@ -1045,40 +1048,42 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
],
]
.concat(),
})
.expect("The error handling nodes should resolve")
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The error handling nodes should resolve");
(executor, output)
}
#[test]
fn a_caught_error_does_not_reach_the_output() {
let context: Context = None;
for keep_value in [false, true] {
let executor = handled_error_network(graphene_core::poll::catch::IDENTIFIER, &[4, 5], keep_value);
assert!(matches!((&executor).execute(context.clone()), Ok(Poll::Final(_))), "Catch should hide the error");
let (executor, output) = handled_error_network(graphene_core::poll::catch::IDENTIFIER, &[4, 5], keep_value);
assert!(matches!(executor.execute(&output, context.clone()), Ok(Poll::Final(_))), "Catch should hide the error");
}
}
#[test]
fn suppress_error_hides_only_an_error_with_a_value() {
let context: Context = None;
let executor = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], true);
let (executor, output) = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], true);
assert!(
matches!((&executor).execute(context.clone()), Ok(Poll::Final(_))),
matches!(executor.execute(&output, context.clone()), Ok(Poll::Final(_))),
"Suppress Error should keep the value and hide the error"
);
let executor = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], false);
assert!(matches!((&executor).execute(context), Ok(Poll::Error(_))), "An error without a value should still stop the frame");
let (executor, output) = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], false);
assert!(matches!(executor.execute(&output, context), Ok(Poll::Error(_))), "An error without a value should still stop the frame");
}
#[test]
fn a_fallback_keeps_the_error_on_the_node_that_raised_it() {
let executor = handled_error_network(graphene_core::poll::fallback::IDENTIFIER, &[4, 5], false);
let (executor, output) = handled_error_network(graphene_core::poll::fallback::IDENTIFIER, &[4, 5], false);
let context: Context = None;
let Ok(Poll::Fallback(boxed)) = (&executor).execute(context) else {
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
panic!("Fallback should keep the frame going with the error")
};
assert_eq!(boxed.1.to_string(), "too small");
assert_eq!(*executor.trace_error(executor.output(), &boxed.1), [NodeId(4)], "The error should stay on the Throw Error node");
assert_eq!(*executor.trace_error(output.node(), &boxed.1), [NodeId(4)], "The error should stay on the Throw Error node");
}
#[test]
@@ -1187,16 +1192,63 @@ fn source_network(node: u64) -> ProtoNetwork {
#[test]
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
let mut executor = DynamicExecutor::new(source_network(0)).unwrap();
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test]
fn networks_are_executed_side_by_side_by_their_handles() {
let network = |node: u64| ProtoNetwork {
inputs: vec![],
output: NodeId(node),
nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
};
let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(network(0)).unwrap();
let (second, _) = executor.update(network(1)).unwrap();
let context: Context = None;
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
assert_eq!(executor.execute(&second, context).unwrap(), Poll::Final(TaggedValue::Number(1.)));
}
#[test]
fn an_output_that_is_already_held_shares_its_handle() {
let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(source_network(0)).unwrap();
let (second, _) = executor.update(source_network(0)).unwrap();
let (other, _) = executor.update(source_network(1)).unwrap();
assert!(Arc::ptr_eq(&first.0, &second.0));
assert!(!Arc::ptr_eq(&first.0, &other.0));
}
#[test]
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
for _ in 0..3 {
executor.update(source_network(2)).unwrap();
}
assert_eq!(kept(&executor), [true; 2]);
drop(output);
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [false; 2]);
}
#[test]
fn a_source_is_listed_for_as_long_as_its_node_lives() {
let mut executor = DynamicExecutor::new(source_network(0)).unwrap();
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
for _ in 0..3 {
executor.update(source_network(1)).unwrap();
+1 -1
View File
@@ -49,6 +49,6 @@ mod tests {
let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
}
}
@@ -5,7 +5,6 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::RenderOutput;
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
use graphene_animation::AnimationCurve;
use graphene_std::GlowTechnique;
use graphene_std::animation::RealTimeMode;
use graphene_std::any::DynAnyNode;
use graphene_std::brush::Stroke;
@@ -29,6 +28,7 @@ use graphene_std::vector::misc::{
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode};
use node_registry_macros::async_node;
use std::collections::HashMap;
use std::sync::Arc;
@@ -290,6 +290,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
AdjustmentChannel,
HueSaturationRange,
GlowTechnique,
GlowSource,
MaskMode,
BevelStyle,
BevelDirection,
BevelTechnique,
Stroke,
ScaleType,
ReferencePoint,
@@ -300,6 +305,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
CellularDistanceFunction,
CellularReturnType,
DomainWarpType,
MandelbrotFractal,
MandelbrotExterior,
MandelbrotInterior,
RealTimeMode,
GridType,
GridTopology,
@@ -261,12 +261,15 @@ mod tests {
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
}
// Color Dodge gives white for a white source, and Divide for a black backdrop
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
for source in [1., 1. - 1e-7, 1. + 2e-7] {
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
}
for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_divide(backdrop, 0.5), 1., "a backdrop of {backdrop}");
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
}
for source in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_divide(0.5, source), 1., "a source of {source}");
}
// Past the tolerance the modes follow their formulas
@@ -744,9 +744,15 @@ impl Color {
c_b - c_s
}
/// Per-channel "Divide" blend.
/// Per-channel "Divide" blend, where a black backdrop stays black and any other turns white when divided by black.
pub fn blend_divide(c_b: f32, c_s: f32) -> f32 {
if c_b.abs() <= BLEND_EDGE_TOLERANCE { 1. } else { c_b / c_s }
if c_b <= BLEND_EDGE_TOLERANCE {
0.
} else if c_s <= BLEND_EDGE_TOLERANCE {
1.
} else {
c_b / c_s
}
}
/// Runs `blend` on this color's and `c_s`'s gamma-encoded channels, which the component blend modes are defined on, keeping `c_s`'s alpha.
+4 -4
View File
@@ -32,10 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE,
ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START,
ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_TYPE,
};
pub use memo::MemoHash;
pub use num_traits;
@@ -40,9 +40,6 @@ pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
/// `List<NodeIdPath>` of the nodes with a footprint input this item passed through.
/// Each row's transform maps the unit square onto that node's area in this item's local space.
pub const ATTR_EDITOR_FOOTPRINT_AREAS: &str = "editor:footprint_areas";
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
pub const ATTR_START: &str = "start";
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
@@ -35,6 +35,8 @@ pub struct NodeFlags {
#[derive(Clone, Debug)]
pub struct FieldMetadata {
pub name: &'static str,
/// The parameter's name in the node function, which graph text uses to set it.
pub identifier: &'static str,
pub description: &'static str,
/// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph.
pub internal: bool,
@@ -60,6 +62,12 @@ pub struct FieldMetadata {
pub progression: bool,
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
pub constant: bool,
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
pub labels: Option<(&'static str, &'static str)>,
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
pub integer: bool,
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
pub blank_assist: bool,
}
#[derive(Clone, Debug)]
@@ -222,6 +230,146 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// The graph text of every `graph!` invocation, in registration order.
pub static GRAPH_SOURCES: LazyLock<Mutex<Vec<GraphSource>>> = LazyLock::new(|| Mutex::new(Vec::new()));
/// The text of one `graph!` invocation and where it's written, for error messages.
#[derive(Clone, Debug)]
pub struct GraphSource {
/// The module the graph is defined in, which qualifies its name in `use` paths.
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
pub column: u32,
pub text: &'static str,
}
/// Registers graph text as a built-in subgraph node, which the editor turns into a catalog definition.
///
/// Each invocation registers itself under a symbol named after its crate, line, and column, so two invocations at the
/// same line and column in different files of one crate fail to link.
#[macro_export]
macro_rules! graph {
($($source:tt)*) => {
const _: () = {
use $crate as gcore;
use gcore::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
#[unsafe(export_name = concat!("__node_registry_graph_", env!("CARGO_CRATE_NAME"), "_", line!(), "_", column!()))]
extern "C" fn register_graph() {
gcore::registry::GRAPH_SOURCES.lock().unwrap().push(gcore::registry::GraphSource {
module_path: module_path!(),
file: file!(),
line: line!(),
column: column!(),
text: stringify!($($source)*),
});
}
};
};
}
/// A node defined as a subgraph in graph text, which the editor turns into a catalog definition alongside the proto nodes.
#[derive(Clone, Debug)]
pub struct GraphMetadata {
/// The definition's identifier and display name.
pub identifier: &'static str,
/// The module path and function name that `use` paths in graph text name the graph by.
pub path: &'static str,
pub category: &'static str,
pub icon: Option<&'static str>,
pub description: &'static str,
/// The declaration version from `fn name@N`, starting at 1.
pub version: u32,
/// Whether a new instance starts as a layer, from `#[layer]`.
pub layer: bool,
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
pub imports: Vec<FieldMetadata>,
pub exports: Vec<GraphExportMetadata>,
/// The nodes inside the subgraph, where each node's position in this list is its ID.
pub nodes: Vec<GraphNodeMetadata>,
}
#[derive(Clone, Debug)]
pub struct GraphExportMetadata {
pub name: &'static str,
/// The export's name in graph text, which chooses it as an output.
pub identifier: &'static str,
pub description: &'static str,
pub source: GraphInputSource,
}
/// A node inside a subgraph defined in graph text.
#[derive(Clone, Debug)]
pub struct GraphNodeMetadata {
pub implementation: GraphNodeImplementation,
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
pub inputs: Vec<(usize, GraphInputSource)>,
/// The position in grid units.
pub position: (i32, i32),
pub layer: bool,
pub display_name: Option<&'static str>,
pub hidden: bool,
pub locked: bool,
pub pinned: bool,
}
/// What a node inside a subgraph is an instance of.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphNodeImplementation {
ProtoNode(ProtoNodeIdentifier),
/// Another subgraph node, named by its identifier.
Graph(&'static str),
}
/// What feeds an input, or an export, of a subgraph defined in graph text.
#[derive(Clone, Debug)]
pub enum GraphInputSource {
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
Node { node: usize, output: usize },
/// One of the subgraph's imports, with the type its wire records.
Import { index: usize, ty: Type },
/// A value. Without an exposure, the input keeps the one from the node's own definition.
Value { value: GraphValue, exposed: Option<bool> },
/// A scope input, from `scope("…")`.
Scope(&'static str),
/// The document path of the node, from `reflect(NodePath)`.
NodePath,
/// The source ID of the node, from `reflect(SourceId)`.
SourceId,
}
/// A value written in graph text, whose type is set by how it's written.
#[derive(Clone, Debug, PartialEq)]
pub enum GraphValue {
/// A number written without a fractional part.
Integer(i64),
Number(f64),
Bool(bool),
String(String),
Vec2(glam::DVec2),
Color(Color),
}
impl GraphValue {
pub fn vec2(x: f64, y: f64) -> Self {
Self::Vec2(glam::DVec2::new(x, y))
}
/// An opaque color from `rgb(0xRRGGBB)`.
pub fn rgb(hex: u32) -> Self {
let [_, red, green, blue] = hex.to_be_bytes();
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
}
/// A color with alpha from `rgba(0xRRGGBBAA)`.
pub fn rgba(hex: u32) -> Self {
let [red, green, blue, alpha] = hex.to_be_bytes();
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
}
}
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
+25 -135
View File
@@ -113,36 +113,7 @@ impl RuntimeInner {
}
}
pub struct Slots<T>(Arc<Mutex<SlotTable<T>>>);
struct SlotTable<T> {
slots: HashMap<u64, Slot<T>>,
/// The number of started evaluations, which orders them.
started: u64,
/// The value of the latest started evaluation that has landed, with its order.
latest: Option<(u64, T)>,
}
impl<T: Clone> SlotTable<T> {
fn start(&mut self) -> u64 {
self.started += 1;
self.started
}
fn land(&mut self, key: u64, order: u64, state: Poll<T>) {
let superseded = self.latest.as_ref().is_some_and(|(latest_order, _)| *latest_order > order);
if !superseded && let Some(value) = state.clone().value() {
self.latest = Some((order, value));
}
self.slots.insert(key, Slot::Ready(state));
}
/// The value a pending evaluation returns, preferring the latest landed value if `keep_previous` is set.
fn stand_in(&self, placeholder: Option<T>, keep_previous: bool) -> Poll<T> {
let previous = if keep_previous { self.latest.as_ref().map(|(_, value)| value.clone()) } else { None };
previous.or(placeholder).map_or(Poll::Pending, Poll::Partial)
}
}
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
enum Slot<T> {
Ready(Poll<T>),
@@ -159,11 +130,7 @@ impl<T> Drop for Slot<T> {
impl<T> Default for Slots<T> {
fn default() -> Self {
Self(Arc::new(Mutex::new(SlotTable {
slots: HashMap::new(),
started: 0,
latest: None,
})))
Self(Arc::default())
}
}
@@ -180,46 +147,42 @@ impl<T> std::fmt::Debug for Slots<T> {
}
impl<T: Clone + WasmNotSend + 'static> Slots<T> {
/// The landed state for `key`, or else starts its evaluation and returns its stand-in.
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, keep_previous: bool, future: impl FnOnce() -> F) -> Poll<T>
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, future: impl FnOnce() -> F) -> Poll<T>
where
F: Future<Output = Poll<T>> + WasmNotSend + 'static,
{
let order = {
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match table.slots.get(&key) {
Some(Slot::Ready(landed)) => return landed.clone(),
Some(Slot::Pending(_)) => return table.stand_in(placeholder, keep_previous),
None => table.start(),
}
};
match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
Some(Slot::Ready(landed)) => return landed.clone(),
Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial),
None => {}
}
// Fast path for futures that are ready immediately
// TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd
let mut future = Box::pin(future());
if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
self.0.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state.clone());
self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone()));
return state;
}
let (handle, registration) = AbortHandle::new_pair();
let table = Arc::downgrade(&self.0);
let slots = Arc::downgrade(&self.0);
runtime.spawn(
source,
Box::pin(async move {
if let Ok(state) = Abortable::new(future, registration).await
&& let Some(table) = table.upgrade()
&& let Some(slots) = slots.upgrade()
{
table.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state);
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
}
}),
);
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match table.slots.get(&key) {
let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match slots.get(&key) {
Some(Slot::Ready(landed)) => landed.clone(),
_ => {
table.slots.insert(key, Slot::Pending(handle));
table.stand_in(placeholder, keep_previous)
slots.insert(key, Slot::Pending(handle));
placeholder.map_or(Poll::Pending, Poll::Partial)
}
}
}
@@ -252,13 +215,6 @@ mod tests {
}
count
}
fn drain_newest_first(&self) {
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
for mut task in tasks.into_iter().rev() {
while !poll_once(&mut task) {}
}
}
}
struct BlockingSpawner;
@@ -320,7 +276,7 @@ mod tests {
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
assert_eq!(spawner.drain(), 0);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
@@ -341,77 +297,11 @@ mod tests {
Poll::Final(42u32)
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Partial(0));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice");
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
}
#[test]
fn a_slot_keeping_the_previous_value_serves_it_until_the_next_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = |value: u32| {
move || async move {
YieldOnce(false).await;
Poll::Final(value)
}
};
assert_eq!(
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)),
Poll::Partial(0),
"nothing landed yet, so the placeholder stands in"
);
spawner.drain();
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)), Poll::Final(1));
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Partial(1), "the previous value stands in");
spawner.drain();
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Final(2));
}
#[test]
fn an_older_response_landing_late_does_not_replace_the_previous_value() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = |value: u32| {
move || async move {
YieldOnce(false).await;
Poll::Final(value)
}
};
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1));
slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2));
spawner.drain_newest_first();
assert_eq!(slots.resolve(3, &runtime, SOURCE, Some(0), true, fetch(3)), Poll::Partial(2));
}
#[test]
fn a_fallback_response_stands_in_as_the_previous_value() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
slots.resolve(1, &runtime, SOURCE, Some(0), true, || async {
YieldOnce(false).await;
Poll::fallback(1, "failed")
});
spawner.drain();
let fetch = || async {
YieldOnce(false).await;
Poll::Final(2)
};
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch), Poll::Partial(1));
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
}
#[test]
@@ -424,7 +314,7 @@ mod tests {
Poll::Final(42u32)
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]);
}
@@ -438,11 +328,11 @@ mod tests {
Poll::Final(42u32)
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
let clone = slots.clone();
drop(slots);
assert_eq!(spawner.drain(), 1);
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Final(42));
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42));
}
#[test]
@@ -460,7 +350,7 @@ mod tests {
}
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
drop(slots);
assert_eq!(spawner.drain(), 1);
assert!(!finished.load(Ordering::Relaxed));
@@ -0,0 +1,26 @@
[package]
name = "graph-text"
description = "Parses the graph text format, which defines subgraph nodes in a Rust-like syntax"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Local dependencies
core-types = { workspace = true }
# Workspace dependencies
syn = { workspace = true }
proc-macro2 = { workspace = true }
glam = { workspace = true }
convert_case = { workspace = true }
log = { workspace = true }
@@ -0,0 +1,106 @@
//! The default placement of a graph's nodes, relative to the nodes they feed.
/// How far apart, in grid units, a node is placed from the node it feeds.
const COLUMN_WIDTH: i32 = 7;
/// A node's wires and its written placement, as the layout reads them.
pub struct LayoutNode {
/// The node feeding the primary input.
pub primary: Option<usize>,
/// The nodes feeding the other inputs, in the order they're written.
pub secondaries: Vec<usize>,
/// The absolute position from `.at(x, y)`, which replaces the default one.
pub at: Option<(i32, i32)>,
/// The nudge from `.offset(x, y)`, added to the default position.
pub offset: (i32, i32),
}
/// Places each node in the column left of the first node it feeds. A node feeding a primary input shares that node's row,
/// and one feeding another input goes in a new row below everything placed so far. Each export's node starts a new row.
pub fn layout(nodes: &[LayoutNode], roots: &[usize]) -> Vec<(i32, i32)> {
let mut placement = Placement {
nodes,
positions: vec![None; nodes.len()],
bottom: None,
};
for &root in roots {
let row = placement.next_row();
placement.place(root, 0, row);
}
for node in 0..nodes.len() {
let row = placement.next_row();
placement.place(node, 0, row);
}
placement.positions.into_iter().map(Option::unwrap_or_default).collect()
}
struct Placement<'a> {
nodes: &'a [LayoutNode],
positions: Vec<Option<(i32, i32)>>,
/// The lowest row used so far.
bottom: Option<i32>,
}
impl Placement<'_> {
fn next_row(&self) -> i32 {
self.bottom.map_or(0, |bottom| bottom + 1)
}
fn place(&mut self, node: usize, x: i32, y: i32) {
if self.positions[node].is_some() {
return;
}
let LayoutNode { primary, secondaries, at, offset } = &self.nodes[node];
let (x, y) = at.unwrap_or((x + offset.0, y + offset.1));
self.positions[node] = Some((x, y));
self.bottom = Some(self.bottom.map_or(y, |bottom| bottom.max(y)));
if let Some(primary) = primary {
self.place(*primary, x - COLUMN_WIDTH, y);
}
for &secondary in secondaries {
let row = self.next_row();
self.place(secondary, x - COLUMN_WIDTH, row);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn node(primary: Option<usize>, secondaries: Vec<usize>) -> LayoutNode {
LayoutNode {
primary,
secondaries,
at: None,
offset: (0, 0),
}
}
#[test]
fn chains_run_left_and_side_inputs_go_below() {
// Merge: `base >> as_graphic() >> extend(new = content >> into_group())`
let nodes = [node(None, vec![]), node(None, vec![]), node(Some(0), vec![1])];
assert_eq!(layout(&nodes, &[2]), [(-7, 0), (-7, 1), (0, 0)]);
}
#[test]
fn written_placement_moves_a_node_and_its_upstream() {
let mut offset = node(None, vec![]);
offset.offset = (0, 2);
let mut at = node(Some(0), vec![]);
at.at = Some((10, -4));
assert_eq!(layout(&[offset, at], &[1]), [(3, -2), (10, -4)]);
}
#[test]
fn each_export_and_unexported_node_starts_a_new_row() {
let nodes = [node(None, vec![]), node(None, vec![]), node(None, vec![])];
assert_eq!(layout(&nodes, &[0, 1]), [(0, 0), (0, 1), (0, 2)]);
}
}
+122
View File
@@ -0,0 +1,122 @@
//! Graph text, which defines a subgraph node in a Rust-like syntax that is parsed at runtime.
//!
//! Built-in graphs are written in `core_types::graph!` invocations, which register their text at startup.
mod layout;
mod resolve;
mod syntax;
use core_types::ProtoNodeIdentifier;
use core_types::registry::{GRAPH_SOURCES, GraphMetadata, GraphSource, NODE_METADATA, NodeMetadata};
use resolve::{Context, ResolveError};
use std::collections::HashMap;
use std::fmt;
use std::sync::LazyLock;
pub use syntax::SYNTAX_VERSION;
/// Every registered graph that resolves, in registration order. Resolved on first access, which must happen after
/// startup registration of the nodes and graphs completes. Each graph that fails is left out and its error logged.
pub static GRAPHS: LazyLock<Vec<GraphMetadata>> = LazyLock::new(|| {
let sources = GRAPH_SOURCES.lock().map(|sources| sources.clone()).unwrap_or_default();
let Ok(proto_nodes) = NODE_METADATA.lock() else {
log::error!("The node metadata is poisoned, so no graph resolves");
return Vec::new();
};
let (graphs, errors) = resolve_sources(&sources, &proto_nodes);
for error in errors {
log::error!("{error}");
}
graphs
});
/// The position of a registered graph's import, by the graph's identifier and the import's name.
pub fn import_index(graph: &str, import: &str) -> Option<usize> {
GRAPHS.iter().find(|metadata| metadata.identifier == graph)?.imports.iter().position(|field| field.identifier == import)
}
/// An error in graph text, with the place it's written.
#[derive(Debug)]
pub struct GraphTextError {
pub message: String,
pub file: &'static str,
pub line: u32,
pub column: u32,
/// The graph text from the error onward, which locates it within the text.
pub excerpt: String,
}
impl fmt::Display for GraphTextError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}:{}:{}: {} (at `{}`)", self.file, self.line, self.column, self.message, self.excerpt)
}
}
impl GraphTextError {
fn new(source: &GraphSource, error: syn::Error) -> Vec<Self> {
error
.into_iter()
.map(|error| {
let start = error.span().start();
let excerpt = source
.text
.lines()
.nth(start.line.saturating_sub(1))
.map(|line| line.chars().skip(start.column).take(40).collect::<String>())
.unwrap_or_default();
Self {
message: error.to_string(),
file: source.file,
line: source.line,
column: source.column,
excerpt: excerpt.trim().to_string(),
}
})
.collect()
}
}
/// Parses and resolves graph sources. A graph using another one resolves once that one has, whatever the order.
pub fn resolve_sources(sources: &[GraphSource], proto_nodes: &HashMap<ProtoNodeIdentifier, NodeMetadata>) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
let mut errors = Vec::new();
let mut pending = Vec::new();
for source in sources {
match syn::parse_str::<syntax::Source>(source.text) {
Ok(parsed) => pending.push((source, parsed, None)),
Err(error) => errors.extend(GraphTextError::new(source, error)),
}
}
let mut graphs = Vec::new();
loop {
let pending_count = pending.len();
let mut still_pending = Vec::new();
for (source, parsed, _) in pending {
let context = Context { proto_nodes, graphs: &graphs };
match resolve::resolve(&parsed, source.module_path, &context) {
Ok(graph) => graphs.push(graph),
Err(ResolveError::Invalid(error)) => errors.extend(GraphTextError::new(source, error)),
Err(ResolveError::Unresolved(error)) => still_pending.push((source, parsed, Some(error))),
}
}
pending = still_pending;
if pending.is_empty() || pending.len() == pending_count {
break;
}
}
for (source, _, error) in pending {
if let Some(error) = error {
errors.extend(GraphTextError::new(source, error));
}
}
(graphs, errors)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,749 @@
//! Resolves parsed graph text against the registered nodes and graphs, producing the graph's `GraphMetadata`.
use crate::layout::{LayoutNode, layout};
use crate::syntax::{Attribute, Expression, GraphItem, Import, Source, StateKind, Use, ValueKind, doc_comment};
use convert_case::{Case, Casing};
use core_types::registry::{
FieldMetadata, GraphExportMetadata, GraphInputSource, GraphMetadata, GraphNodeImplementation, GraphNodeMetadata, GraphValue, NodeMetadata, RegistryValueSource, RegistryWidgetOverride,
};
use core_types::{ProtoNodeIdentifier, Type, concrete, generic};
use proc_macro2::Span;
use std::collections::{HashMap, HashSet};
use syn::ext::IdentExt;
use syn::parse::{ParseStream, Parser};
use syn::{Error, Ident, LitBool, LitInt, LitStr, Token};
/// The registered nodes and the graphs resolved so far, which graph text can use.
pub struct Context<'a> {
pub proto_nodes: &'a HashMap<ProtoNodeIdentifier, NodeMetadata>,
pub graphs: &'a [GraphMetadata],
}
pub enum ResolveError {
/// A used name matches nothing yet, which may be a graph that resolves later.
Unresolved(Error),
Invalid(Error),
}
impl From<Error> for ResolveError {
fn from(error: Error) -> Self {
Self::Invalid(error)
}
}
/// What a used name refers to.
#[derive(Clone, Copy)]
enum Target<'a> {
ProtoNode(&'a ProtoNodeIdentifier, &'a NodeMetadata),
Graph(&'a GraphMetadata),
}
impl<'a> Target<'a> {
fn parameters(&self) -> &'a [FieldMetadata] {
match self {
Self::ProtoNode(_, metadata) => &metadata.fields,
Self::Graph(graph) => &graph.imports,
}
}
fn implementation(&self) -> GraphNodeImplementation {
match self {
Self::ProtoNode(identifier, _) => GraphNodeImplementation::ProtoNode((*identifier).clone()),
Self::Graph(graph) => GraphNodeImplementation::Graph(graph.identifier),
}
}
}
/// What feeds an input or export while the body is read.
#[derive(Clone)]
enum Feed {
/// A node's output, chosen by name, or else its primary output.
Node {
node: usize,
output: Option<usize>,
},
Import(usize),
Value {
value: GraphValue,
exposed: Option<bool>,
},
Scope(String),
NodePath,
SourceId,
}
struct Node<'a> {
target: Target<'a>,
name: Ident,
inputs: Vec<(usize, Feed)>,
states: Vec<StateKind>,
}
struct Resolver<'a> {
context: &'a Context<'a>,
graph_path: String,
uses: HashMap<String, &'a Use>,
used: HashSet<String>,
imports: &'a [Import],
bindings: HashMap<String, Feed>,
nodes: Vec<Node<'a>>,
/// The parameters of the inner inputs each import feeds, in the order they're written.
import_consumers: Vec<Vec<FieldMetadata>>,
}
/// Resolves a parsed graph text, given the module path its graph is defined in.
pub fn resolve(source: &Source, module_path: &str, context: &Context) -> Result<GraphMetadata, ResolveError> {
let graph = &source.graph;
let graph_path = format!("{module_path}::{}", graph.name);
let mut uses = HashMap::new();
for entry in &source.uses {
let local_name = entry.local_name();
if uses.insert(local_name.to_string(), entry).is_some() {
return Err(Error::new(local_name.span(), format!("`{local_name}` is used twice. Rename one with `as`")).into());
}
}
let mut resolver = Resolver {
context,
graph_path,
uses,
used: HashSet::new(),
imports: &graph.imports,
bindings: HashMap::new(),
nodes: Vec::new(),
import_consumers: vec![Vec::new(); graph.imports.len()],
};
for binding in &graph.bindings {
let name = binding.name.to_string();
if resolver.bindings.contains_key(&name) || resolver.import_index(&binding.name).is_some() {
return Err(Error::new(binding.name.span(), format!("`{name}` is already the name of a binding or import")).into());
}
let feed = resolver.read(&binding.value)?;
resolver.bindings.insert(name, feed);
}
let export_feeds = resolver.read_exports(&graph.result, graph.exports.len())?;
if let Some(unused) = source.uses.iter().find(|entry| !resolver.used.contains(&entry.local_name().to_string())) {
return Err(Error::new(unused.local_name().span(), format!("`{}` is used but never called", unused.local_name())).into());
}
resolver.build(graph, module_path, export_feeds)
}
impl<'a> Resolver<'a> {
fn import_index(&self, name: &Ident) -> Option<usize> {
self.imports.iter().position(|import| import.name.as_ref() == Some(name))
}
fn read(&mut self, expression: &'a Expression) -> Result<Feed, ResolveError> {
match expression {
Expression::Name(name) => {
if let Some(feed) = self.bindings.get(&name.to_string()) {
return Ok(feed.clone());
}
if let Some(index) = self.import_index(name) {
return Ok(Feed::Import(index));
}
Err(Error::new(name.span(), format!("`{name}` isn't a binding or import. Call a node with parentheses, like `{name}()`")).into())
}
Expression::Value(value) => Ok(Feed::Value {
value: match &value.kind {
ValueKind::Integer(integer) => GraphValue::Integer(*integer),
ValueKind::Number(number) => GraphValue::Number(*number),
ValueKind::Bool(boolean) => GraphValue::Bool(*boolean),
ValueKind::String(string) => GraphValue::String(string.clone()),
ValueKind::Vec2(x, y) => GraphValue::vec2(*x, *y),
},
exposed: None,
}),
Expression::Call(call) => self.read_call(call),
Expression::Feed { upstream, downstream, span } => {
let upstream_feed = self.read(upstream)?;
let Feed::Node { node, output } = self.read(downstream)? else {
return Err(Error::new(downstream.span(), "The right side of `>>` is a node, like `fill()`, or a binding naming one").into());
};
if let Feed::Node { node: upstream_node, .. } = upstream_feed
&& self.is_fed_by(upstream_node, node)
{
return Err(Error::new(*span, "This wire makes a loop, since the node on the right already feeds the left side").into());
}
let entry = &self.nodes[node];
if entry.target.parameters().is_empty() {
return Err(Error::new(entry.name.span(), format!("`{}` has no parameters, so `>>` has no input to feed", entry.name)).into());
}
if entry.inputs.iter().any(|(index, _)| *index == 0) {
let primary = &entry.target.parameters()[0];
let message = format!("The primary input of `{}`, `{}`, is already fed, so `>>` can't feed it too", entry.name, primary.identifier);
return Err(Error::new(*span, message).into());
}
self.connect(node, 0, upstream_feed);
Ok(Feed::Node { node, output })
}
Expression::Output { node, output } => {
let Feed::Node { node, output: None } = self.read(node)? else {
return Err(Error::new(output.span(), "Only a node has outputs to choose from, and only one can be chosen").into());
};
let Target::Graph(graph) = self.nodes[node].target else {
return Err(Error::new(output.span(), "Only a graph's outputs can be chosen by name").into());
};
let name = output.unraw().to_string();
let Some(index) = graph.exports.iter().position(|export| export.identifier == name) else {
return Err(Error::new(output.span(), format!("`{}` has no output named `{name}`", self.nodes[node].name)).into());
};
Ok(Feed::Node { node, output: Some(index) })
}
Expression::Tuple { span, .. } => Err(Error::new(*span, "A tuple only gives a graph's exports, as its final expression").into()),
}
}
fn read_exports(&mut self, result: &'a Expression, export_count: usize) -> Result<Vec<Feed>, ResolveError> {
let values: Vec<&Expression> = match result {
Expression::Tuple { elements, .. } => elements.iter().collect(),
single => vec![single],
};
if values.len() != export_count {
return Err(Error::new(result.span(), format!("The graph names {export_count} exports, but ends with {} values", values.len())).into());
}
values
.into_iter()
.map(|value| match self.read(value)? {
Feed::Import(_) | Feed::Scope(_) => Err(Error::new(value.span(), "An export can't come straight from an import or scope yet, so pass it through a node first").into()),
feed => Ok(feed),
})
.collect()
}
/// Whether `node` is `source` or feeds it through any chain of wires.
fn is_fed_by(&self, node: usize, source: usize) -> bool {
let mut visited = vec![false; self.nodes.len()];
let mut stack = vec![node];
while let Some(current) = stack.pop() {
if current == source {
return true;
}
if std::mem::replace(&mut visited[current], true) {
continue;
}
stack.extend(self.nodes[current].inputs.iter().filter_map(|(_, feed)| match feed {
Feed::Node { node, .. } => Some(*node),
_ => None,
}));
}
false
}
fn connect(&mut self, node: usize, input: usize, feed: Feed) {
if let Feed::Import(import) = feed {
let parameter = self.nodes[node].target.parameters()[input].clone();
self.import_consumers[import].push(parameter);
}
self.nodes[node].inputs.push((input, feed));
}
fn read_call(&mut self, call: &'a crate::syntax::Call) -> Result<Feed, ResolveError> {
let name = call.name.to_string();
if let Some(feed) = self.read_value_helper(call)? {
return Ok(feed);
}
let target = self.target(&call.name)?;
self.used.insert(name);
let mut inputs = Vec::new();
for argument in &call.arguments {
let parameter = match (&argument.parameter, &argument.value) {
(Some(parameter), _) => parameter,
(None, Expression::Name(shorthand)) => shorthand,
(None, value) => return Err(Error::new(value.span(), "Name each argument, like `weight = 6`, or write a bare name for the shorthand").into()),
};
let Some(index) = target.parameters().iter().position(|field| parameter == field.identifier) else {
return Err(Error::new(parameter.span(), format!("`{}` has no parameter named `{parameter}`", call.name)).into());
};
if inputs.iter().any(|(existing, _)| *existing == index) {
return Err(Error::new(parameter.span(), format!("`{parameter}` is already set in this call")).into());
}
let mut feed = self.read(&argument.value)?;
for attribute in &argument.attributes {
if attribute.name != "exposed" {
return Err(Error::new(attribute.name.span(), format!("Unknown argument attribute `#[{}]`", attribute.name)).into());
}
attribute.flag()?;
let Feed::Value { exposed, .. } = &mut feed else {
return Err(Error::new(attribute.name.span(), "Only a value can be exposed").into());
};
*exposed = Some(true);
}
inputs.push((index, feed));
}
self.nodes.push(Node {
target,
name: call.name.clone(),
inputs: Vec::new(),
states: call.states.iter().map(|state| state.kind.clone()).collect(),
});
let node = self.nodes.len() - 1;
for (index, feed) in inputs {
self.connect(node, index, feed);
}
Ok(Feed::Node { node, output: None })
}
/// Reads a call to `rgb`, `rgba`, `scope`, or `reflect`, which build values and input sources rather than nodes.
fn read_value_helper(&self, call: &crate::syntax::Call) -> Result<Option<Feed>, ResolveError> {
let name = call.name.to_string();
if !matches!(name.as_str(), "rgb" | "rgba" | "scope" | "reflect") {
return Ok(None);
}
let [argument] = call.arguments.as_slice() else {
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes one argument")).into());
};
if let Some(state) = call.states.first() {
return Err(Error::new(state.span, format!("`{name}(...)` is a value, so it has no node state")).into());
}
if argument.parameter.is_some() || !argument.attributes.is_empty() {
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes a plain argument")).into());
}
let value = &argument.value;
let feed = match (name.as_str(), value) {
("rgb", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFF_FFFF).contains(hex) => Feed::Value {
value: GraphValue::rgb(*hex as u32),
exposed: None,
},
("rgb", _) => return Err(Error::new(value.span(), "`rgb(...)` takes six hex digits, like `rgb(0xE85D75)`. Use `rgba(...)` to give an alpha too").into()),
("rgba", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFFFF_FFFF).contains(hex) => Feed::Value {
value: GraphValue::rgba(*hex as u32),
exposed: None,
},
("rgba", _) => return Err(Error::new(value.span(), "`rgba(...)` takes eight hex digits, like `rgba(0xE85D75FF)`").into()),
("scope", Expression::Value(crate::syntax::Value { kind: ValueKind::String(key), .. })) => Feed::Scope(key.clone()),
("scope", _) => return Err(Error::new(value.span(), "`scope(...)` takes the scope's key as a string").into()),
(_, Expression::Name(reflected)) if reflected == "NodePath" => Feed::NodePath,
(_, Expression::Name(reflected)) if reflected == "SourceId" => Feed::SourceId,
_ => return Err(Error::new(value.span(), "Reflect `NodePath` or `SourceId`").into()),
};
Ok(Some(feed))
}
/// The node or graph a called name refers to, through the `use` section.
fn target(&self, name: &Ident) -> Result<Target<'a>, ResolveError> {
let Some(entry) = self.uses.get(&name.to_string()) else {
return Err(Error::new(name.span(), format!("`{name}` isn't used. Add it to the `use` section, like `use path::{name}@1;`")).into());
};
let module_path = entry.module_path();
let proto_identifier = ProtoNodeIdentifier::with_owned_string(format!("{module_path}::{}Node", entry.name.to_string().to_case(Case::Pascal)));
if let Some((identifier, metadata)) = self.context.proto_nodes.get_key_value(&proto_identifier) {
check_version(entry, metadata.version)?;
return Ok(Target::ProtoNode(identifier, metadata));
}
let graph_path = format!("{module_path}::{}", entry.name);
if graph_path == self.graph_path {
return Err(Error::new(name.span(), "A graph can't contain itself").into());
}
if let Some(graph) = self.context.graphs.iter().find(|graph| graph.path == graph_path) {
check_version(entry, graph.version)?;
return Ok(Target::Graph(graph));
}
Err(ResolveError::Unresolved(Error::new(entry.name.span(), format!("No node or graph is named `{graph_path}`"))))
}
fn build(self, graph: &GraphItem, module_path: &str, export_feeds: Vec<Feed>) -> Result<GraphMetadata, ResolveError> {
let attributes = GraphAttributes::read(&graph.attributes)?;
let imports = graph
.imports
.iter()
.zip(&self.import_consumers)
.enumerate()
.map(|(index, (import, consumers))| import_metadata(index, import, consumers))
.collect::<syn::Result<Vec<_>>>()?;
let import_types: Vec<Type> = imports.iter().map(import_wire_type).collect();
let source = |feed: &Feed| match feed {
Feed::Node { node, output } => GraphInputSource::Node {
node: *node,
output: output.unwrap_or(0),
},
Feed::Import(index) => GraphInputSource::Import {
index: *index,
ty: import_types[*index].clone(),
},
Feed::Value { value, exposed } => GraphInputSource::Value {
value: value.clone(),
exposed: *exposed,
},
Feed::Scope(key) => GraphInputSource::Scope(leak(key.clone())),
Feed::NodePath => GraphInputSource::NodePath,
Feed::SourceId => GraphInputSource::SourceId,
};
let layout_nodes: Vec<LayoutNode> = self
.nodes
.iter()
.map(|node| {
let upstream = |input: &(usize, Feed)| match input.1 {
Feed::Node { node, .. } => Some(node),
_ => None,
};
LayoutNode {
primary: node.inputs.iter().filter(|input| input.0 == 0).find_map(upstream),
secondaries: node.inputs.iter().filter(|input| input.0 != 0).filter_map(upstream).collect(),
at: node.states.iter().find_map(|state| match state {
StateKind::At(x, y) => Some((*x, *y)),
_ => None,
}),
offset: node
.states
.iter()
.find_map(|state| match state {
StateKind::Offset(x, y) => Some((*x, *y)),
_ => None,
})
.unwrap_or_default(),
}
})
.collect();
let roots: Vec<usize> = export_feeds
.iter()
.filter_map(|feed| match feed {
Feed::Node { node, .. } => Some(*node),
_ => None,
})
.collect();
let positions = layout(&layout_nodes, &roots);
let nodes = self
.nodes
.iter()
.zip(positions)
.map(|(node, position)| GraphNodeMetadata {
implementation: node.target.implementation(),
inputs: node.inputs.iter().map(|(index, feed)| (*index, source(feed))).collect(),
position,
layer: node.states.contains(&StateKind::Layer),
display_name: node.states.iter().find_map(|state| match state {
StateKind::Named(name) => Some(leak(name.clone())),
_ => None,
}),
hidden: node.states.contains(&StateKind::Hidden),
locked: node.states.contains(&StateKind::Locked),
pinned: node.states.contains(&StateKind::Pinned),
})
.collect();
let exports = graph
.exports
.iter()
.zip(&export_feeds)
.map(|(export, feed)| {
let mut name = None;
for attribute in &export.attributes {
match attribute.name.to_string().as_str() {
"doc" => {}
"name" => set_once(&mut name, attribute, attribute.string()?)?,
other => return Err(Error::new(attribute.name.span(), format!("Unknown export attribute `#[{other}]`"))),
}
}
Ok(GraphExportMetadata {
name: leak(name.unwrap_or_else(|| derived_display_name(&export.name))),
identifier: leak(export.name.unraw().to_string()),
description: leak(doc_comment(&export.attributes)),
source: source(feed),
})
})
.collect::<syn::Result<Vec<_>>>()?;
let identifier = attributes.display_name.unwrap_or_else(|| graph.name.unraw().to_string().to_case(Case::Pascal).to_case(Case::Title));
Ok(GraphMetadata {
identifier: leak(identifier),
path: leak(format!("{module_path}::{}", graph.name)),
category: leak(attributes.category),
icon: attributes.icon.map(leak),
description: leak(doc_comment(&graph.attributes)),
version: graph.version,
layer: attributes.layer,
imports,
exports,
nodes,
})
}
}
fn check_version(entry: &Use, version: u32) -> syn::Result<()> {
if entry.version == version {
return Ok(());
}
Err(Error::new(entry.name.span(), format!("`{}` is at version {version}, not {}", entry.name, entry.version)))
}
/// Strings in the registry's metadata live for the whole program, which holds for graphs resolved once at startup.
fn leak(string: String) -> &'static str {
Box::leak(string.into_boxed_str())
}
/// The display name an identifier derives, in Title Case.
fn derived_display_name(ident: &Ident) -> String {
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
}
fn set_once<T>(slot: &mut Option<T>, attribute: &Attribute, value: T) -> syn::Result<()> {
if slot.is_some() {
return Err(Error::new(attribute.name.span(), format!("Multiple `{}` attributes are not allowed", attribute.name)));
}
*slot = Some(value);
Ok(())
}
struct GraphAttributes {
category: String,
icon: Option<String>,
display_name: Option<String>,
layer: bool,
}
impl GraphAttributes {
fn read(attributes: &[Attribute]) -> syn::Result<Self> {
let (mut category, mut icon, mut display_name, mut layer) = (None, None, None, None);
for attribute in attributes {
match attribute.name.to_string().as_str() {
"doc" => {}
"category" => set_once(&mut category, attribute, attribute.string()?)?,
"icon" => set_once(&mut icon, attribute, attribute.string()?)?,
"name" => set_once(&mut display_name, attribute, attribute.string()?)?,
"layer" => {
attribute.flag()?;
set_once(&mut layer, attribute, true)?;
}
other => {
return Err(Error::new(
attribute.name.span(),
format!("Unknown graph attribute `#[{other}]`. Expected `category(\"…\")`, `icon(\"…\")`, `name(\"…\")`, or `layer`"),
));
}
}
}
let Some(category) = category else {
return Err(Error::new(Span::call_site(), "A graph needs a category, like `#[category(\"Vector: Deform\")]`"));
};
Ok(Self {
category,
icon,
display_name,
layer: layer.unwrap_or_default(),
})
}
}
/// A parameter description with nothing set, which an import starts from when it feeds no input.
pub(crate) fn blank_field() -> FieldMetadata {
FieldMetadata {
name: "",
identifier: "",
description: "",
internal: false,
exposed: false,
widget_override: RegistryWidgetOverride::None,
value_source: RegistryValueSource::None,
default_colors: None,
default_type: None,
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: false,
number_display_decimal_places: None,
number_step: None,
unit: None,
multiline: false,
progression: false,
constant: false,
labels: None,
integer: false,
blank_assist: true,
}
}
/// An import's parameter description, inherited from an inner input it feeds and overridden by its own attributes.
/// That input is the one whose parameter has the import's name, or else the first one fed.
fn import_metadata(index: usize, import: &Import, consumers: &[FieldMetadata]) -> syn::Result<FieldMetadata> {
let Some(name) = &import.name else {
if let Some(attribute) = import.attributes.first() {
return Err(Error::new(attribute.name.span(), "An unused primary import takes no attributes"));
}
return Ok(FieldMetadata {
default_type: Some(concrete!(())),
..blank_field()
});
};
let identifier = name.unraw().to_string();
let inherited = consumers.iter().find(|consumer| consumer.identifier == identifier).or(consumers.first());
let mut field = FieldMetadata {
identifier: leak(identifier.clone()),
exposed: false,
internal: index > 0 && identifier.starts_with('_'),
constant: false,
..inherited.cloned().unwrap_or_else(blank_field)
};
let mut display_name = None;
let mut seen = HashSet::new();
for attribute in &import.attributes {
let attribute_name = attribute.name.to_string();
if attribute_name != "doc" && !seen.insert(attribute_name.clone()) {
return Err(Error::new(attribute.name.span(), format!("Multiple `{attribute_name}` attributes are not allowed")));
}
apply_import_attribute(&mut field, &mut display_name, attribute)?;
}
field.name = leak(display_name.unwrap_or_else(|| derived_display_name(name)));
let description = doc_comment(&import.attributes);
if !description.is_empty() {
field.description = leak(description);
}
Ok(field)
}
fn apply_import_attribute(field: &mut FieldMetadata, display_name: &mut Option<String>, attribute: &Attribute) -> syn::Result<()> {
let arguments = || attribute.list();
match attribute.name.to_string().as_str() {
"doc" => {}
"name" => *display_name = Some(attribute.string()?),
"expose" => {
attribute.flag()?;
field.exposed = true;
}
"default" => {
let tokens = arguments()?;
field.default_type = default_type(&tokens, field.default_type.take());
field.value_source = RegistryValueSource::Default(leak(tokens.to_string()));
field.default_colors = None;
}
"widget" => {
field.widget_override = (|input: ParseStream| {
let kind: Ident = input.parse()?;
let text = || -> syn::Result<&'static str> {
input.parse::<Token![=]>()?;
Ok(leak(input.parse::<LitStr>()?.value()))
};
match kind.to_string().as_str() {
"Hidden" => Ok(RegistryWidgetOverride::Hidden),
"String" => Ok(RegistryWidgetOverride::String(text()?)),
"Custom" => Ok(RegistryWidgetOverride::Custom(text()?)),
_ => Err(Error::new(kind.span(), "A widget is `Hidden`, `String = \"…\"`, or `Custom = \"…\"`")),
}
})
.parse2(arguments()?)?;
}
"unit" => field.unit = Some(leak(attribute.string()?)),
"hard" => (field.number_hard_min, field.number_hard_max) = parse_bounds.parse2(arguments()?)?,
"soft" => (field.number_soft_min, field.number_soft_max) = parse_bounds.parse2(arguments()?)?,
"range" => {
attribute.flag()?;
field.number_mode_range = true;
}
"step" => field.number_step = Some(parse_number.parse2(arguments()?)?),
"display_decimal_places" => field.number_display_decimal_places = Some(syn::parse2::<LitInt>(arguments()?)?.base10_parse()?),
"multiline" => {
attribute.flag()?;
field.multiline = true;
}
"progression" => {
attribute.flag()?;
field.progression = true;
}
"integer" => {
attribute.flag()?;
field.integer = true;
}
"labels" => {
field.labels = Some(
(|input: ParseStream| {
let x: LitStr = input.parse()?;
input.parse::<Token![,]>()?;
let y: LitStr = input.parse()?;
Ok((leak(x.value()), leak(y.value())))
})
.parse2(arguments()?)?,
);
}
"blank_assist" => field.blank_assist = syn::parse2::<LitBool>(arguments()?)?.value,
other => return Err(Error::new(attribute.name.span(), format!("Unknown import attribute `#[{other}]`"))),
}
Ok(())
}
/// The type a `#[default(...)]` is parsed as: a literal's own type, or else the bare element of the inherited type.
fn default_type(tokens: &proc_macro2::TokenStream, inherited: Option<Type>) -> Option<Type> {
if let Ok(literal) = syn::parse2::<crate::syntax::Value>(tokens.clone()) {
return Some(match literal.kind {
ValueKind::Integer(_) => concrete!(i64),
ValueKind::Number(_) => concrete!(f64),
ValueKind::Bool(_) => concrete!(bool),
ValueKind::String(_) => concrete!(String),
ValueKind::Vec2(..) => concrete!(glam::DVec2),
});
}
match inherited {
Some(Type::Item(element)) => Some(*element),
other => other,
}
}
/// The type an import's wire records, ranked as an `Item` when its default is a bare element.
fn import_wire_type(field: &FieldMetadata) -> Type {
match &field.default_type {
Some(ty @ (Type::Item(_) | Type::List(_) | Type::Fn(..) | Type::Generic(_))) => ty.clone(),
Some(unit) if *unit == concrete!(()) => unit.clone(),
Some(element) => Type::Item(Box::new(element.clone())),
None => generic!(T),
}
}
fn parse_number(input: ParseStream) -> syn::Result<f64> {
let negative = input.peek(Token![-]);
if negative {
input.parse::<Token![-]>()?;
}
let magnitude: f64 = match input.parse::<syn::Lit>()? {
syn::Lit::Int(integer) => integer.base10_parse()?,
syn::Lit::Float(float) => float.base10_parse()?,
other => return Err(Error::new(other.span(), "Expected a number")),
};
Ok(if negative { -magnitude } else { magnitude })
}
/// Reads `a..b`, where either end may be left out.
fn parse_bounds(input: ParseStream) -> syn::Result<(Option<f64>, Option<f64>)> {
let start = if input.peek(Token![..]) { None } else { Some(parse_number(input)?) };
input.parse::<Token![..]>()?;
let end = if input.is_empty() { None } else { Some(parse_number(input)?) };
Ok((start, end))
}
@@ -0,0 +1,780 @@
//! The grammar of graph text, parsed with syn from the tokens of a `graph!` invocation or a clipboard string.
use proc_macro2::{Span, TokenStream};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Error, Ident, Lit, LitInt, LitStr, Token, braced, bracketed, parenthesized};
/// The syntax version this parser reads, from the `#![syntax(N)]` header.
pub const SYNTAX_VERSION: u32 = 1;
/// A whole graph text: its header, its `use` section, and the graph it defines.
pub struct Source {
pub uses: Vec<Use>,
pub graph: GraphItem,
}
/// One node or graph named by the `use` section, like `math_nodes::add@1`.
pub struct Use {
pub module: Vec<Ident>,
pub name: Ident,
pub version: u32,
pub alias: Option<Ident>,
}
impl Use {
/// The name the body calls it by.
pub fn local_name(&self) -> &Ident {
self.alias.as_ref().unwrap_or(&self.name)
}
pub fn module_path(&self) -> String {
self.module.iter().map(Ident::to_string).collect::<Vec<_>>().join("::")
}
}
/// An attribute item like `category("Graphic")`, `layer`, or `doc = "…"`. One `#[...]` can hold several, separated by commas.
pub struct Attribute {
pub name: Ident,
pub arguments: AttributeArguments,
}
pub enum AttributeArguments {
None,
List(TokenStream),
Value(Lit),
}
impl Attribute {
/// The parenthesized arguments, or an error naming the attribute if it has none.
pub fn list(&self) -> syn::Result<TokenStream> {
match &self.arguments {
AttributeArguments::List(tokens) => Ok(tokens.clone()),
_ => Err(Error::new(self.name.span(), format!("`{}` takes arguments in parentheses", self.name))),
}
}
/// An error unless the attribute is written without arguments.
pub fn flag(&self) -> syn::Result<()> {
match &self.arguments {
AttributeArguments::None => Ok(()),
_ => Err(Error::new(self.name.span(), format!("`{}` takes no arguments", self.name))),
}
}
pub fn string(&self) -> syn::Result<String> {
syn::parse2::<LitStr>(self.list()?).map(|literal| literal.value())
}
}
pub struct GraphItem {
pub attributes: Vec<Attribute>,
pub name: Ident,
pub version: u32,
pub imports: Vec<Import>,
pub exports: Vec<Export>,
pub bindings: Vec<Binding>,
/// The final expression, which gives one value per export.
pub result: Expression,
}
pub struct Import {
pub attributes: Vec<Attribute>,
/// The import's name, or `None` for an unused primary import written `_`.
pub name: Option<Ident>,
}
pub struct Export {
pub attributes: Vec<Attribute>,
pub name: Ident,
}
pub struct Binding {
pub name: Ident,
pub value: Expression,
}
pub enum Expression {
Name(Ident),
Value(Value),
Call(Call),
/// `upstream >> downstream`, which feeds the upstream into the downstream node's primary input.
Feed {
upstream: Box<Expression>,
downstream: Box<Expression>,
span: Span,
},
/// A node's output chosen by name, like `.captures`.
Output {
node: Box<Expression>,
output: Ident,
},
Tuple {
elements: Vec<Expression>,
span: Span,
},
}
impl Expression {
pub fn span(&self) -> Span {
match self {
Self::Name(name) => name.span(),
Self::Value(value) => value.span,
Self::Call(call) => call.name.span(),
Self::Feed { span, .. } | Self::Tuple { span, .. } => *span,
Self::Output { output, .. } => output.span(),
}
}
}
pub struct Value {
pub kind: ValueKind,
pub span: Span,
}
pub enum ValueKind {
Integer(i64),
Number(f64),
Bool(bool),
String(String),
Vec2(f64, f64),
}
pub struct Call {
pub name: Ident,
pub arguments: Vec<Argument>,
pub states: Vec<State>,
}
pub struct Argument {
pub attributes: Vec<Attribute>,
/// The parameter set by `parameter = value`, or `None` for a positional argument, which for a node is the shorthand `name`.
pub parameter: Option<Ident>,
pub value: Expression,
}
/// A node state method after a call, like `.offset(0, 2)`.
pub struct State {
pub kind: StateKind,
pub span: Span,
}
#[derive(Clone, PartialEq)]
pub enum StateKind {
At(i32, i32),
Offset(i32, i32),
Named(String),
Hidden,
Locked,
Pinned,
Layer,
}
impl Parse for Source {
fn parse(input: ParseStream) -> syn::Result<Self> {
parse_header(input)?;
let mut uses = Vec::new();
while input.peek(Token![use]) {
uses.extend(parse_use(input)?);
}
let graph = input.parse()?;
if !input.is_empty() {
return Err(input.error("Graph text defines one graph"));
}
Ok(Self { uses, graph })
}
}
/// Reads `#![syntax(N)]`, which every graph text starts with.
fn parse_header(input: ParseStream) -> syn::Result<()> {
if !(input.peek(Token![#]) && input.peek2(Token![!])) {
return Err(input.error(format!("Graph text starts with its syntax version, like `#![syntax({SYNTAX_VERSION})]`")));
}
input.parse::<Token![#]>()?;
input.parse::<Token![!]>()?;
let content;
bracketed!(content in input);
let name: Ident = content.parse()?;
if name != "syntax" {
return Err(Error::new(name.span(), "The header is `#![syntax(N)]`"));
}
let arguments;
parenthesized!(arguments in content);
let literal: LitInt = arguments.parse()?;
let version: u32 = literal.base10_parse()?;
if version != SYNTAX_VERSION {
return Err(Error::new(literal.span(), format!("Syntax version {version} isn't supported, only {SYNTAX_VERSION} is")));
}
Ok(())
}
/// Reads `use path::name@N;` or `use path::{a@N, b@N as c};`.
fn parse_use(input: ParseStream) -> syn::Result<Vec<Use>> {
let use_token: Token![use] = input.parse()?;
let mut module = Vec::new();
let entries = loop {
if input.peek(syn::token::Brace) {
let content;
braced!(content in input);
break Punctuated::<UseEntry, Token![,]>::parse_terminated(&content)?.into_iter().collect::<Vec<_>>();
}
let segment: Ident = input.parse()?;
if input.peek(Token![::]) {
input.parse::<Token![::]>()?;
module.push(segment);
} else {
break vec![UseEntry::parse_after_name(segment, input)?];
}
};
input.parse::<Token![;]>()?;
if module.is_empty() {
return Err(Error::new(use_token.span, "Name a node by its full path, like `use math_nodes::add@1;`"));
}
Ok(entries
.into_iter()
.map(|entry| Use {
module: module.clone(),
name: entry.name,
version: entry.version,
alias: entry.alias,
})
.collect())
}
struct UseEntry {
name: Ident,
version: u32,
alias: Option<Ident>,
}
impl UseEntry {
fn parse_after_name(name: Ident, input: ParseStream) -> syn::Result<Self> {
let version = parse_version(input)?;
let alias = if input.peek(Token![as]) {
input.parse::<Token![as]>()?;
Some(input.parse()?)
} else {
None
};
Ok(Self { name, version, alias })
}
}
impl Parse for UseEntry {
fn parse(input: ParseStream) -> syn::Result<Self> {
let name = input.parse()?;
Self::parse_after_name(name, input)
}
}
/// Reads `@N`, the version a node or graph is declared or used at.
fn parse_version(input: ParseStream) -> syn::Result<u32> {
if !input.peek(Token![@]) {
return Err(input.error("Give the version, like `@1`"));
}
input.parse::<Token![@]>()?;
let literal: LitInt = input.parse()?;
if !literal.suffix().is_empty() {
return Err(Error::new(literal.span(), "Write the version without a type suffix"));
}
let version: u32 = literal.base10_parse()?;
if version == 0 {
return Err(Error::new(literal.span(), "Versions start at 1"));
}
Ok(version)
}
/// Reads any number of `#[...]` groups, each holding comma-separated attribute items.
fn parse_attributes(input: ParseStream) -> syn::Result<Vec<Attribute>> {
let mut attributes = Vec::new();
while input.peek(Token![#]) && !input.peek2(Token![!]) {
input.parse::<Token![#]>()?;
let content;
bracketed!(content in input);
while !content.is_empty() {
let name = content.call(Ident::parse_any)?;
let arguments = if content.peek(syn::token::Paren) {
let arguments;
parenthesized!(arguments in content);
AttributeArguments::List(arguments.parse()?)
} else if content.peek(Token![=]) {
content.parse::<Token![=]>()?;
AttributeArguments::Value(content.parse()?)
} else {
AttributeArguments::None
};
attributes.push(Attribute { name, arguments });
if content.is_empty() {
break;
}
content.parse::<Token![,]>()?;
}
}
Ok(attributes)
}
/// The `///` lines among the attributes, each trimmed and joined by line breaks.
pub fn doc_comment(attributes: &[Attribute]) -> String {
attributes
.iter()
.filter(|attribute| attribute.name == "doc")
.filter_map(|attribute| match &attribute.arguments {
AttributeArguments::Value(Lit::Str(text)) => Some(text.value().trim().to_string()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string()
}
impl Parse for GraphItem {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
input.parse::<Token![fn]>()?;
let name: Ident = input.parse()?;
let version = parse_version(input)?;
let parameters;
parenthesized!(parameters in input);
let imports = Punctuated::<Import, Token![,]>::parse_terminated(&parameters)?.into_iter().collect();
input.parse::<Token![->]>()?;
let exports: Vec<Export> = if input.peek(syn::token::Paren) {
let content;
parenthesized!(content in input);
Punctuated::<Export, Token![,]>::parse_terminated(&content)?.into_iter().collect()
} else {
vec![input.parse()?]
};
if exports.is_empty() {
return Err(Error::new(name.span(), "Name at least one export, like `-> (out)`"));
}
let body;
braced!(body in input);
let mut bindings = Vec::new();
while body.peek(Token![let]) {
bindings.push(body.parse()?);
}
if body.is_empty() {
return Err(Error::new(name.span(), "A graph ends its body with one value per export"));
}
let result = parse_expression(&body)?;
if body.peek(Token![;]) {
return Err(body.error("The graph ends with its exports, written without a semicolon"));
}
if !body.is_empty() {
return Err(body.error("Each statement in a graph is a `let` binding, followed by the exports it ends with"));
}
Ok(Self {
attributes,
name,
version,
imports,
exports,
bindings,
result,
})
}
}
impl Parse for Import {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
let name = if input.peek(Token![_]) {
input.parse::<Token![_]>()?;
None
} else {
Some(input.parse()?)
};
if input.peek(Token![:]) {
return Err(input.error("Imports take no type, since it's inferred from the inputs they feed"));
}
Ok(Self { attributes, name })
}
}
impl Parse for Export {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
let name = input.call(Ident::parse_any)?;
Ok(Self { attributes, name })
}
}
impl Parse for Binding {
fn parse(input: ParseStream) -> syn::Result<Self> {
input.parse::<Token![let]>()?;
let name = input.parse()?;
input.parse::<Token![=]>()?;
let value = parse_expression(input)?;
input.parse::<Token![;]>()?;
Ok(Self { name, value })
}
}
impl Parse for Expression {
fn parse(input: ParseStream) -> syn::Result<Self> {
parse_expression(input)
}
}
/// Reads a chain of `>>`, which binds loosest and groups from the left.
fn parse_expression(input: ParseStream) -> syn::Result<Expression> {
let mut expression = parse_postfix(input)?;
while input.peek(Token![>>]) {
let token: Token![>>] = input.parse()?;
let downstream = parse_postfix(input)?;
expression = Expression::Feed {
upstream: Box::new(expression),
downstream: Box::new(downstream),
span: token.span(),
};
}
Ok(expression)
}
/// Reads a primary expression followed by node state methods and output choices.
fn parse_postfix(input: ParseStream) -> syn::Result<Expression> {
let mut expression = parse_primary(input)?;
while input.peek(Token![.]) && !input.peek(Token![..]) {
input.parse::<Token![.]>()?;
let name = input.call(Ident::parse_any)?;
if !input.peek(syn::token::Paren) {
if matches!(expression, Expression::Output { .. }) {
return Err(Error::new(name.span(), "An output is already chosen here"));
}
expression = Expression::Output {
node: Box::new(expression),
output: name,
};
continue;
}
let arguments;
parenthesized!(arguments in input);
let call = match &mut expression {
Expression::Call(call) => call,
Expression::Output { .. } => {
return Err(Error::new(name.span(), "Node state goes before the output it chooses, like `regex_find().at(0, 0).captures`"));
}
_ => return Err(Error::new(name.span(), "Node state goes directly after the call it modifies, not on a binding")),
};
let state = parse_state(&name, &arguments)?;
if call.states.iter().any(|existing| std::mem::discriminant(&existing.kind) == std::mem::discriminant(&state.kind)) {
return Err(Error::new(name.span(), format!("`.{name}()` is already set on this node")));
}
call.states.push(state);
}
Ok(expression)
}
fn parse_state(name: &Ident, arguments: ParseStream) -> syn::Result<State> {
let method = name.to_string();
let no_arguments = || match arguments.is_empty() {
true => Ok(()),
false => Err(arguments.error(format!("`.{method}()` takes no arguments"))),
};
let coordinates = || -> syn::Result<(i32, i32)> {
let x = parse_grid_coordinate(arguments)?;
arguments.parse::<Token![,]>()?;
let y = parse_grid_coordinate(arguments)?;
if !arguments.is_empty() {
return Err(arguments.error("Give two coordinates in grid units"));
}
Ok((x, y))
};
let kind = match method.as_str() {
"at" => {
let (x, y) = coordinates()?;
StateKind::At(x, y)
}
"offset" => {
let (x, y) = coordinates()?;
StateKind::Offset(x, y)
}
"named" => {
let display_name: LitStr = arguments.parse()?;
StateKind::Named(display_name.value())
}
"hidden" => no_arguments().map(|_| StateKind::Hidden)?,
"locked" => no_arguments().map(|_| StateKind::Locked)?,
"pinned" => no_arguments().map(|_| StateKind::Pinned)?,
"layer" => no_arguments().map(|_| StateKind::Layer)?,
_ => {
return Err(Error::new(
name.span(),
format!("Unknown node state `.{method}()`. Parameters go inside the call's parentheses, like `node({method} = ...)`"),
));
}
};
Ok(State { kind, span: name.span() })
}
fn parse_grid_coordinate(input: ParseStream) -> syn::Result<i32> {
let negative = input.peek(Token![-]);
if negative {
input.parse::<Token![-]>()?;
}
let literal: LitInt = input.parse().map_err(|error| Error::new(error.span(), "Positions are integers in grid units"))?;
if !literal.suffix().is_empty() {
return Err(Error::new(literal.span(), "Write the position without a type suffix"));
}
let magnitude: i32 = literal.base10_parse()?;
Ok(if negative { -magnitude } else { magnitude })
}
fn parse_primary(input: ParseStream) -> syn::Result<Expression> {
let span = input.span();
if input.peek(syn::token::Paren) {
let content;
parenthesized!(content in input);
let elements = Punctuated::<Expression, Token![,]>::parse_terminated(&content)?;
if elements.is_empty() {
return Err(Error::new(span, "Empty parentheses aren't part of the graph syntax"));
}
if elements.len() == 1 && !elements.trailing_punct() {
return Ok(elements.into_iter().next().expect("there is one element"));
}
return Ok(Expression::Tuple {
elements: elements.into_iter().collect(),
span,
});
}
if input.peek(syn::token::Bracket) {
let content;
bracketed!(content in input);
let numbers = Punctuated::<Value, Token![,]>::parse_terminated(&content)?;
let components: Vec<f64> = numbers
.iter()
.filter_map(|number| match number.kind {
ValueKind::Number(number) => Some(number),
ValueKind::Integer(integer) => Some(integer as f64),
_ => None,
})
.collect();
let [x, y] = components.as_slice() else {
return Err(Error::new(span, "A value array is a two-number Vec2, like `[1., 2.]`"));
};
return Ok(Expression::Value(Value { kind: ValueKind::Vec2(*x, *y), span }));
}
if input.peek(Lit) || input.peek(Token![-]) {
return input.parse().map(Expression::Value);
}
if input.peek(Ident) {
let name: Ident = input.parse()?;
if !input.peek(syn::token::Paren) {
return Ok(Expression::Name(name));
}
let content;
parenthesized!(content in input);
let arguments = Punctuated::<Argument, Token![,]>::parse_terminated(&content)?.into_iter().collect();
return Ok(Expression::Call(Call { name, arguments, states: Vec::new() }));
}
Err(input.error("This isn't part of the graph syntax"))
}
impl Parse for Value {
fn parse(input: ParseStream) -> syn::Result<Self> {
let span = input.span();
let negative = input.peek(Token![-]);
if negative {
input.parse::<Token![-]>()?;
}
let literal: Lit = input.parse()?;
let kind = match &literal {
Lit::Int(integer) => {
if !integer.suffix().is_empty() {
return Err(Error::new(integer.span(), "Write the integer without a type suffix. Its type is `i64`"));
}
let value: i64 = integer.base10_parse()?;
ValueKind::Integer(if negative { -value } else { value })
}
Lit::Float(float) => {
if !float.suffix().is_empty() {
return Err(Error::new(float.span(), "Write the number without a type suffix. Its type is `f64`"));
}
let value: f64 = float.base10_parse()?;
ValueKind::Number(if negative { -value } else { value })
}
Lit::Bool(boolean) if !negative => ValueKind::Bool(boolean.value),
Lit::Str(string) if !negative => ValueKind::String(string.value()),
_ if negative => return Err(Error::new(literal.span(), "Only a number can be negated")),
_ => return Err(Error::new(literal.span(), "Unsupported literal")),
};
Ok(Self { kind, span })
}
}
impl Parse for Argument {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
let parameter = if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) {
let parameter = input.parse()?;
input.parse::<Token![=]>()?;
Some(parameter)
} else {
None
};
let value = parse_expression(input)?;
Ok(Self { attributes, parameter, value })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(text: &str) -> syn::Result<Source> {
syn::parse_str(text)
}
fn error_message(text: &str) -> String {
match parse(text) {
Ok(_) => panic!("the graph text should be rejected"),
Err(error) => error.to_string(),
}
}
#[test]
fn reads_the_header_uses_and_graph() {
let source = parse(
r#"
#![syntax(1)]
use graphic_nodes::graphic::{as_graphic@1, extend@2 as append};
use graphic_nodes::graphic::into_group@1;
/// Merges content.
#[category("Graphic"), layer]
fn merge@3(base, #[expose] content) -> (out) {
let grouped = content >> into_group();
base >> as_graphic() >> append(new = grouped)
}
"#,
)
.expect("the graph text should parse");
let uses: Vec<String> = source.uses.iter().map(|entry| format!("{}::{}@{}", entry.module_path(), entry.local_name(), entry.version)).collect();
assert_eq!(
uses,
["graphic_nodes::graphic::as_graphic@1", "graphic_nodes::graphic::append@2", "graphic_nodes::graphic::into_group@1"]
);
let graph = &source.graph;
assert_eq!(graph.name, "merge");
assert_eq!(graph.version, 3);
assert_eq!(doc_comment(&graph.attributes), "Merges content.");
assert_eq!(graph.imports.len(), 2);
assert_eq!(graph.bindings.len(), 1);
assert!(matches!(graph.result, Expression::Feed { .. }));
}
#[test]
fn reads_state_values_and_outputs() {
let source = parse(
r#"
#![syntax(1)]
use a::b::{f@1, g@1};
fn state@1(_, x) -> (match, other) {
let node = f(#[exposed] flag = false, offset = -2.5, size = [1, -2.], count = 3, label = "text", x).named("N").offset(0, -2).hidden();
(node.match, node >> g())
}
"#,
)
.expect("the graph text should parse");
let graph = &source.graph;
assert!(graph.imports[0].name.is_none());
assert_eq!(graph.exports[0].name, "match");
let Expression::Call(call) = &graph.bindings[0].value else {
panic!("the binding should be a call")
};
let kinds: Vec<StateKind> = call.states.iter().map(|state| state.kind.clone()).collect();
assert!(kinds == [StateKind::Named("N".into()), StateKind::Offset(0, -2), StateKind::Hidden]);
assert!(matches!(call.arguments[1].value, Expression::Value(Value { kind: ValueKind::Number(-2.5), .. })));
assert!(matches!(call.arguments[2].value, Expression::Value(Value { kind: ValueKind::Vec2(1., -2.), .. })));
assert!(matches!(call.arguments[3].value, Expression::Value(Value { kind: ValueKind::Integer(3), .. })));
assert!(call.arguments[5].parameter.is_none());
let Expression::Tuple { elements, .. } = &graph.result else {
panic!("the result should be a tuple")
};
assert!(matches!(&elements[0], Expression::Output { output, .. } if output == "match"));
}
#[test]
fn rejects_text_without_a_supported_header() {
assert!(error_message("fn a@1() -> (out) { b() }").contains("starts with its syntax version"));
assert!(error_message("#![syntax(2)] fn a@1() -> (out) { b() }").contains("isn't supported"));
}
#[test]
fn rejects_unversioned_and_unqualified_names() {
assert!(error_message("#![syntax(1)] use a::b; fn a@1() -> (out) { b() }").contains("Give the version"));
assert!(error_message("#![syntax(1)] use b@1; fn a@1() -> (out) { b() }").contains("full path"));
assert!(error_message("#![syntax(1)] fn a() -> (out) { b() }").contains("Give the version"));
assert!(error_message("#![syntax(1)] fn a@0() -> (out) { b() }").contains("start at 1"));
}
#[test]
fn rejects_typed_imports_and_suffixed_literals() {
assert!(error_message("#![syntax(1)] fn a@1(x: Item<f64>) -> (out) { b(x) }").contains("take no type"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1_u32) }").contains("without a type suffix"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1.5_f32) }").contains("without a type suffix"));
}
#[test]
fn rejects_misplaced_state() {
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { let n = b(); n.hidden() }").contains("not on a binding"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().out.hidden() }").contains("before the output"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().hidden().hidden() }").contains("already set"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().weight(2) }").contains("Unknown node state"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().at(1.5, 2) }").contains("integers in grid units"));
}
#[test]
fn rejects_a_semicolon_after_the_exports() {
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(); }").contains("without a semicolon"));
}
}
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more