Compare commits

..
Author SHA1 Message Date
Timon 6015864c1f Animate the glide of moved nodes and the hover of connectors in the graph UI 2026-12-06 18:00:24 +00:00
Timon 64a767b94e Draw overlays that change without new artwork, and composite once per overlay change while the graph is open 2026-12-06 17:57:47 +00:00
Timon 2e26ebf123 Pass no graph UI config in the clipping tests (fixup for the graph UI commit on the new master) 2026-12-06 17:57:47 +00:00
Timon df1434ddff Implement Graphene base graph UI 2026-12-06 17:57:47 +00:00
Timon 13bb1687b9 Add the graph-ui crate, which draws the node graph with Graphene 2026-12-06 17:57:47 +00:00
Timon 674221fbc3 Add transient nodes that are exempt from versions and migration checks (#5098)
* Add the transient node attribute for nodes that are never saved

* Refuse to save transient nodes

* Leave transient nodes out of the migration checks and the corpus coverage

* Mark the render chain, scope and resource nodes as transient

* Document the transient attribute
2026-12-06 17:23:44 +00:00
Dennis Kobert 1300b4f92a Identify conversion nodes via node macro annotations (#5083)
Flag adapter nodes and register them by identifier
2026-12-06 13:57:52 +00:00
Timon c0778752ab Fix running out of GPU memory from textures allocated outside the shared texture cache (#5070)
* Give the Vello renderer the executor and pool textures with mip levels

* Take split and grown render targets from the texture pool (fixup #4821, #5063)

* Take the premultiplied render target from the texture pool (fixup #4807)

* Premultiply textures drawn as images into texture pool copies (fixup #4807)

* Take effect textures from the texture pool (fixup #4976, #5023)

* Park generator tiles in the texture pool (fixup #5008, #5009, #5010)

* Park image uploads and adjusted copies in the texture pool (fixup #4807, #4855, #4908, #4997, #5037)

* Park adjustment uploads in the texture pool (fixup #4997)

* Take effect row textures and Mandelbrot reference orbits from the texture pool (fixup #5010)

* Review
2026-12-06 13:49:37 +00:00
Timon 27cded81af Utilize executor multi-output capabilities in runtime (#5084)
* Free executor nodes once no output reaches them, and let an export keep its output instead of blocking the runtime

* Answer an export on a channel of its own, so the viewport's answers stay in order

* Render a copy's SVG as an export of the copied layers' own network

* Record in the executor which paths' types changed, to be taken with take_type_changes

* Prepare every network in the node graph executor, and send the runtime the thumbnail sources instead of the previews and layers
2026-12-06 13:48:46 +00:00
d5fdb12320 Desktop: Fix rendering getting stuck on stale WGPU surfaces (#4966)
Reconfigure WGPU surface and request redraw on Outdated

Co-authored-by: Carlos Ferrabone <[email protected]>
Co-authored-by: Timon <[email protected]>
2026-12-06 13:42:47 +00:00
Dennis Kobert 436c943196 Hash vector modifications deterministically instead of with a random ID (#5082) 2026-12-05 12:33:12 +01:00
Keavon Chambers 5add0191f4 Make middle-clicking a node toggle its visibility in the node graph, Inspector, and Layers panels (#5080) 2026-12-04 16:22:27 -08:00
Timon c7e9aaa016 Fix value nodes leaking source map rows on every graph compile (#5078)
* Fix value nodes leaking source map rows on every graph compile

* Update the flatten test for value nodes without a document path
2026-12-04 19:22:18 +00:00
Keavon Chambers 9c9b393420 Rename the 'Add Noise' node to 'Speckle' (#5073) 2026-12-04 10:27:02 +00:00
Keavon Chambers 01c5455ecf Fix the 'Clipping Mask' node not clipping endless color, gradient, and generator layers (#5072) 2026-12-04 01:21:12 -08:00
Keavon Chambers 41586d6967 Add the blend modes Linear Burn, Darker Color, Linear Dodge (Add), Lighter Color, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, and Divide (#5067)
Allow layers to use every blend mode
2026-12-03 15:56:34 -08:00
Keavon Chambers 7c37cc504b Fix how Darker Color, Lighter Color, Hard Mix, and Color Dodge blend (#5066) 2026-12-03 14:48:39 -08:00
Keavon Chambers e30bf2e987 New node: 'Blend If' (#5065)
Add Blend If, hiding content by its own tones and those beneath it
2026-12-03 04:03:46 -08:00
Timon c8e8fbf8d1 Park render cache tiles out of view in the texture pool (#5060) 2026-12-03 11:28:26 +00:00
Keavon Chambers 9517b006fa New node: 'Background Blur' (#5063)
Add a Background Blur effect that blurs what lies beneath the content
2026-12-03 02:35:26 -08:00
Keavon Chambers cfb45f2d54 Make snap targets woken during a drag go back to sleep when the drag ends (#5064) 2026-12-02 17:05:58 -08:00
Keavon Chambers e27119b58b Change the 'Mask' node's Luminance weights to 0.3, 0.59, 0.11, and add a Luminance (SVG) mode (#5062) 2026-12-02 14:50:26 -08:00
195 changed files with 19068 additions and 8768 deletions

No files matched your search

+1 -7
View File
@@ -150,20 +150,14 @@ jobs:
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
- name: 📤 Publish to Cloudflare Pages
if: inputs.merge_queue == false
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
id: cloudflare
continue-on-error: ${{ github.event_name != 'push' }}
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
# Passed through the environment so a branch name can't inject shell syntax
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
echo "No Cloudflare API token available (fork PR), skipping deploy."
exit 0
fi
if [ "${{ github.event_name }}" = "push" ]; then
DEPLOY_BRANCH="master"
else
@@ -51,6 +51,8 @@ jobs:
with:
# Cache on Cargo.lock file
cache-on-failure: true
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
save-if: ${{ github.event_name == 'push' }}
- name: Install gungraun-runner and valgrind
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
Generated
+41
View File
@@ -2498,6 +2498,7 @@ dependencies = [
"futures",
"glam",
"graph-craft",
"graph-ui-types",
"graphene-animation",
"graphene-application-io",
"graphene-canvas-utils",
@@ -2535,6 +2536,44 @@ dependencies = [
"smallvec",
]
[[package]]
name = "graph-ui"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graph-craft",
"graph-ui-icons",
"graph-ui-types",
"graphene-std",
"graphic-types",
"node-macro",
"rendering",
"svg-convert",
"text-nodes",
"vector-types",
"vello_gpu",
]
[[package]]
name = "graph-ui-icons"
version = "0.0.0"
[[package]]
name = "graph-ui-types"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"graph-layout",
"graphene-hash",
"graphic-types",
"serde",
"tsify",
"wasm-bindgen",
]
[[package]]
name = "graphene-animation"
version = "0.0.0"
@@ -2873,6 +2912,7 @@ dependencies = [
"glam",
"graph-craft",
"graph-layout",
"graph-ui",
"graphene-hash",
"graphene-std",
"graphite-proc-macros",
@@ -6021,6 +6061,7 @@ dependencies = [
"graphene-resource",
"graphic-types",
"kurbo",
"linesweeper",
"log",
"num-traits",
"parley",
+6
View File
@@ -34,6 +34,9 @@ members = [
"node-graph/libraries/*",
"node-graph/nodes/*",
"node-graph/graph-craft",
"node-graph/graph-ui",
"node-graph/graph-ui/icons",
"node-graph/graph-ui/types",
"node-graph/graphene-cli",
"node-graph/nodes/gstd",
"node-graph/interpreted-executor",
@@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
math-nodes = { path = "node-graph/nodes/math" }
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
graph-craft = { path = "node-graph/graph-craft" }
graph-ui = { path = "node-graph/graph-ui" }
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
graph-ui-types = { path = "node-graph/graph-ui/types" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
+5 -2
View File
@@ -234,7 +234,11 @@ impl RenderState {
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
WgpuCurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.executor.context().device, &self.config);
window.request_redraw();
return Ok(());
}
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
};
@@ -327,7 +331,6 @@ impl RenderState {
pub(crate) enum RenderError {
OutdatedUITextureError,
SurfaceLost,
SurfaceOutdated,
SurfaceTimeout,
SurfaceValidation,
}
+7 -1
View File
@@ -44,6 +44,8 @@ pub enum ConversionError {
IndexOverflow(usize),
#[error("Node ID {0} is used by more than one node in the document")]
DuplicateNodeId(u64),
#[error("The transient node {0} cannot be saved")]
TransientNode(String),
}
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
@@ -559,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
}
// Nodes the binary doesn't register, such as in tests, are at their first version
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1);
let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
let (version, flags) = registered.unwrap_or((1, Default::default()));
if flags.transient {
return Err(ConversionError::TransientNode(identifier_str));
}
let EncodedDeclaration { id, hash, bytes, proto } =
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
@@ -657,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
}
#[test]
fn a_transient_node_is_rejected() {
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
let metadata = NodeMetadata {
display_name: "Transient",
category: "",
icon: None,
fields: Vec::new(),
description: "",
inspector: None,
context_features: Vec::new(),
flags: NodeFlags {
transient: true,
..Default::default()
},
version: 1,
output_fields: None,
};
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
let mut network = create_simple_network();
network.nodes.insert(
NodeId(100),
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
},
);
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
}
/// A node input referencing a node in a different network can't be remapped to a valid local runtime
/// ID, so conversion must reject it rather than emit a dangling reference.
#[test]
@@ -3,3 +3,4 @@
use migration_core::rename;
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
@@ -1,3 +1 @@
//! Migrations of the nodes in `graphene_std`.
mod renames;
@@ -1,13 +0,0 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
rename!("graphene_std::render_node::RenderNode"@1 => @2);
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
rename!("graphene_std::render_node::RenderNode"@2 => @3);
+15 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
// Removal failing only leaves a temporary directory behind
let _ = std::fs::remove_dir_all(&directory);
let baseline_nodes = baseline_nodes?;
let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
let problems = api_problems(&baseline_nodes, &current, &migrations);
if !problems.is_empty() {
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
// Moving a module keeps the function and its API, which is what a rename looks like
let moved = current
.iter()
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
.find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
problems.push(match moved {
Some(new) => format!(
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
});
continue;
};
if new.transient {
continue;
}
if new.version < version {
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
@@ -123,6 +126,7 @@ mod tests {
NodeSource {
identifier: identifier.to_string(),
version,
transient: false,
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
file: PathBuf::from("lib.rs"),
signature: signature.to_string(),
@@ -168,6 +172,15 @@ mod tests {
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
}
#[test]
fn a_node_turned_transient_needs_no_migration() {
let transient = NodeSource {
transient: true,
..node("a::b", 1, "(x: f64, y: f64)")
};
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
}
#[test]
fn a_bump_needs_a_migration_from_the_baseline_version() {
let bumped = [node("a::b", 3, "(x: f64)")];
+1
View File
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
.into_iter()
.filter(|node| !node.transient)
.map(|node| (node.identifier, node.version))
.collect();
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
+24
View File
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
/// function name with a `Node` suffix.
pub identifier: String,
pub version: u32,
pub transient: bool,
pub function: String,
pub file: PathBuf,
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
let mut path = module_path.join("::");
let mut version = 1;
let mut transient = false;
for argument in arguments {
transient |= argument.path().is_ident("transient");
let syn::Meta::List(list) = argument else { continue };
if list.path.is_ident("path") {
path = list.tokens.to_string().replace(' ', "");
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
Some(NodeSource {
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
version,
transient,
function: function_name,
file: file.to_path_buf(),
signature,
@@ -171,4 +175,24 @@ mod tests {
assert!(!node.signature.contains("cache"), "{}", node.signature);
assert!(node.signature.contains("image"), "{}", node.signature);
}
#[test]
fn the_transient_attribute_is_read() {
let transient: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(transient, memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let saved: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(category(""), memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
assert!(node(&transient).transient);
assert!(!node(&saved).transient);
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
let nodes = find_nodes(&workspace.join(NODE_CRATES))?;
let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
let migrations = workspace.join(MIGRATIONS);
match (command, arguments) {
+2 -1
View File
@@ -14,7 +14,7 @@ publish.workspace = true
workspace = true
[features]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "graph-ui/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
[dependencies]
# Local dependencies
@@ -35,6 +35,7 @@ preprocessor = { workspace = true }
math-parser = { workspace = true }
snapping = { workspace = true }
wgpu-executor = { workspace = true }
graph-ui = { workspace = true, features = ["serde"] }
# Workspace dependencies
js-sys = { workspace = true }
+1 -3
View File
@@ -1,5 +1,5 @@
// GRAPH
pub const GRID_SIZE: u32 = 24;
pub const GRID_SIZE: u32 = graph_ui::metrics::GRID_SIZE as u32;
pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2;
pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120;
@@ -11,8 +11,6 @@ pub const STACK_VERTICAL_GAP: i32 = 3;
pub const LAYER_INDENT_OFFSET: i32 = 8;
/// Horizontal grid width of a non-layer node in a chain.
pub const NODE_CHAIN_WIDTH: i32 = 7;
/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance.
pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
// VIEWPORT
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
+1 -3
View File
@@ -80,10 +80,8 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateLayerPanel,
))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateVisibleNodes,
NodeGraphMessageDiscriminant::UpdateLayersInView,
))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::SendSelectedNodes,
@@ -665,6 +665,18 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
}
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
let mut editor = create_editor_with_three_layers().await;
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
}
/// - paste
/// - assert that ellipse was copied
#[tokio::test]
@@ -1,8 +1,8 @@
use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use graph_ui::wire::WireStyle;
#[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> {
@@ -254,16 +254,16 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
let graph_wire_style = RadioInput::new(vec![
RadioEntryData::new(GraphWireStyle::Direct.to_string())
.label(GraphWireStyle::Direct.to_string())
.tooltip_label(GraphWireStyle::Direct.to_string())
.tooltip_description(GraphWireStyle::Direct.tooltip_description())
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::Direct }.into()),
RadioEntryData::new(GraphWireStyle::GridAligned.to_string())
.label(GraphWireStyle::GridAligned.to_string())
.tooltip_label(GraphWireStyle::GridAligned.to_string())
.tooltip_description(GraphWireStyle::GridAligned.tooltip_description())
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()),
RadioEntryData::new("Direct")
.label("Direct")
.tooltip_label("Direct")
.tooltip_description("Wires bend to run at an angle directly between nodes.")
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::Direct }.into()),
RadioEntryData::new("Grid-Aligned")
.label("Grid-Aligned")
.tooltip_label("Grid-Aligned")
.tooltip_description("Wires follow the grid, running in straight lines between nodes.")
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::GridAligned }.into()),
])
.selected_index(Some(preferences.graph_wire_style as u32))
.sizing(WidgetSizing::default().shrink(false))
@@ -5,11 +5,9 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
};
use crate::messages::portfolio::document::node_graph::graph_ui::GraphNameField;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuInformation, FrontendNodeType, FrontendRemoteCursor};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction};
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
@@ -65,8 +63,6 @@ pub enum FrontendMessage {
SendUIMetadata {
#[serde(rename = "nodeDescriptions")]
node_descriptions: Vec<(String, String)>,
#[serde(rename = "nodeIcons")]
node_icons: Vec<(String, IconName)>,
#[serde(rename = "nodeTypes")]
node_types: Vec<FrontendNodeType>,
},
@@ -121,11 +117,6 @@ pub enum FrontendMessage {
preferences: PreferencesMessageHandler,
},
TriggerTextCommit,
/// Asks the frontend to enter inline-rename mode for a layer in the graph view.
TriggerEditLayerNameInGraph {
#[serde(rename = "nodeId")]
node_id: NodeId,
},
TriggerVisitLink {
url: String,
},
@@ -158,34 +149,11 @@ pub enum FrontendMessage {
ColorPickerStartHistoryTransaction,
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
ColorPickerCommitHistoryTransaction,
UpdateImportsExports {
/// If the primary import is not visible, then it is None.
imports: Vec<Option<FrontendGraphOutput>>,
/// If the primary export is not visible, then it is None.
exports: Vec<Option<FrontendGraphInput>>,
/// The primary import location.
#[serde(rename = "importPosition")]
import_position: (i32, i32),
/// The primary export location.
#[serde(rename = "exportPosition")]
export_position: (i32, i32),
/// The document network does not have an add import or export button.
#[serde(rename = "addImportExport")]
add_import_export: bool,
},
UpdateInSelectedNetwork {
#[serde(rename = "inSelectedNetwork")]
in_selected_network: bool,
},
/// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable.
UpdateNetworkReadOnly {
#[serde(rename = "readOnly")]
read_only: bool,
},
UpdateBox {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateRemoteCursors {
cursors: Vec<FrontendRemoteCursor>,
},
@@ -199,6 +167,14 @@ pub enum FrontendMessage {
UpdateGraphViewOverlay {
open: bool,
},
UpdateGraphTooltip {
label: String,
description: String,
},
UpdateGraphNameField {
field: Option<GraphNameField>,
opens: bool,
},
UpdateWorkspacePanelLayout {
#[serde(rename = "panelLayout")]
panel_layout: WorkspacePanelLayout,
@@ -225,36 +201,6 @@ pub enum FrontendMessage {
source: String,
result: Option<String>,
},
UpdateImportReorderIndex {
#[serde(rename = "importIndex")]
index: Option<usize>,
},
UpdateExportReorderIndex {
#[serde(rename = "exportIndex")]
index: Option<usize>,
},
/// The wire a dragged node would be inserted onto if dropped now, keyed by the node and index of the input it feeds (the max node ID for an export).
UpdateWireInsertionPreview {
wire: Option<(NodeId, usize)>,
},
/// How far each node, and the imports and exports, gliding into the place it moved to is drawn from that place, in node graph space.
UpdateGlideOffsets {
nodes: Vec<(NodeId, (f64, f64))>,
imports: (f64, f64),
exports: (f64, f64),
},
/// The connector a press at the pointer would grab, by its center in node graph space.
UpdateHoveredConnector {
center: Option<(f64, f64)>,
},
UpdateLayerWidths {
#[serde(rename = "layerWidths")]
layer_widths: HashMap<NodeId, u32>,
#[serde(rename = "chainWidths")]
chain_widths: HashMap<NodeId, u32>,
#[serde(rename = "hasLeftInputWire")]
has_left_input_wire: HashMap<NodeId, bool>,
},
UpdateDocumentArtwork {
svg: String,
},
@@ -300,25 +246,9 @@ pub enum FrontendMessage {
#[serde(rename = "setColorChoice")]
set_color_choice: Option<PrimarySecondary>,
},
UpdateGraphFadeArtwork {
percentage: f64,
},
UpdateMouseCursor {
cursor: MouseCursorIcon,
},
UpdateNodeGraphNodes {
nodes: Vec<FrontendNode>,
},
UpdateNodeGraphErrorDiagnostics {
errors: Vec<NodeGraphErrorDiagnostic>,
},
UpdateVisibleNodes {
nodes: Vec<NodeId>,
},
UpdateNodeGraphWires {
wires: Vec<WirePathUpdate>,
},
ClearAllNodeGraphWires,
UpdateNodeGraphSelection {
selected: Vec<NodeId>,
},
@@ -335,27 +265,15 @@ pub enum FrontendMessage {
height: u32,
pixels: serde_bytes::ByteBuf,
},
UpdateNodeThumbnailCanvases {
UpdateNodeThumbnailCanvas {
id: NodeId,
#[serde(rename = "layersPanelCanvasId")]
layers_panel_canvas_id: u64,
#[serde(rename = "nodeGraphCanvasId")]
node_graph_canvas_id: u64,
#[serde(rename = "canvasId")]
canvas_id: u64,
},
UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")]
open_documents: Vec<DocumentInfo>,
},
UpdateWirePathInProgress {
#[serde(rename = "wirePath")]
wire_path: Option<WirePath>,
/// Where the wire meets the connector it's dragged from, in node graph space.
#[serde(rename = "draggedFrom")]
dragged_from: Option<(f64, f64)>,
/// Where the wire's loose end meets a connector it has snapped onto, in node graph space.
#[serde(rename = "snappedTo")]
snapped_to: Option<(f64, f64)>,
},
UpdatePlatform {
platform: AppWindowPlatform,
},
@@ -878,6 +878,22 @@ pub struct SliderMarker {
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
#[serde(rename = "betweenNeighbors")]
between_neighbors: bool,
/// How this marker and the next may pass each other.
#[serde(rename = "overlapNext")]
overlap_next: MarkerOverlap,
}
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MarkerOverlap {
/// Neither may pass the other.
#[default]
Never,
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
NextOnly,
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
Freely,
}
impl SliderMarker {
@@ -890,6 +906,7 @@ impl SliderMarker {
paired_with_next: false,
dashed_to_next: false,
between_neighbors: false,
overlap_next: MarkerOverlap::Never,
}
}
@@ -907,6 +924,11 @@ impl SliderMarker {
self.dashed_to_next = true;
self
}
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
self.overlap_next = overlap;
self
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -5,10 +5,14 @@ use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::application_io::Texture;
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List};
use graphene_std::math_nodes::{color_value, gradient_value};
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::style::RenderMode;
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
#[derive(Clone, Copy, Debug)]
@@ -136,6 +140,111 @@ fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
}
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
#[derive(Clone, Copy, Debug)]
enum Endless {
Color,
Gradient,
NoisePattern,
}
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
editor
}
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
let node = match endless {
Endless::Color => color_value::IDENTIFIER,
Endless::Gradient => gradient_value::IDENTIFIER,
Endless::NoisePattern => noise_pattern::IDENTIFIER,
};
let node_type = DefinitionIdentifier::ProtoNode(node);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
}
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.expect("a document is open");
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).expect("the active document exists");
let submitted = executor
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO, None)
.expect("the evaluation is submitted");
let mut messages = editor.dispatch(submitted);
editor.runtime.update();
let frame = editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
(messages, frame)
}
#[tokio::test]
async fn endless_layers_clip_to_the_shape_beneath_them() {
let size = UVec2::new(256, 256);
let frame_pixels = async |editor: &mut EditorTestUtils| {
let (_, frame) = evaluate_viewport(editor, size).await;
let frame = frame.expect("the viewport presents a frame");
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
};
let pixel = |pixels: &[u8], x: u32, y: u32| {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
let rectangle_alone = frame_pixels(&mut editor).await;
add_clipped_endless_layer(&mut editor, endless).await;
let clipped = frame_pixels(&mut editor).await;
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
assert_eq!(
pixel(&clipped, x, y),
pixel(&rectangle_alone, x, y),
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
);
}
// In SVG Preview, the endless content is drawn only within the rectangle's mask
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
add_clipped_endless_layer(&mut editor, endless).await;
let (messages, _) = evaluate_viewport(&mut editor, size).await;
let svg = messages
.into_iter()
.find_map(|message| match message {
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
_ => None,
})
.expect("the viewport's artwork is sent as SVG");
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
assert!(
!draws_endless_content(unmasked) && draws_endless_content(masked),
"{endless:?}: the content is drawn within the mask: {svg}"
);
}
}
#[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
@@ -35,8 +35,8 @@ use graphene_std::vector::style::{
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
MaskMode, MinimumMaximumMode, NoiseDistribution,
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
};
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
use kurbo::BezPath;
@@ -1277,6 +1277,7 @@ impl_table_item_layout_for_choice_enum!(
WarpStyle,
WaveType,
DisplaceMode,
BlendIfChannel,
EffectKind,
Generator,
GlowSource,
@@ -1472,6 +1473,7 @@ macro_rules! known_item_types {
WarpStyle,
WaveType,
DisplaceMode,
BlendIfChannel,
DashPattern,
BoxCorners,
TransferCurve,
@@ -211,11 +211,6 @@ pub enum DocumentMessage {
SetGraphFadeArtwork {
percentage: f64,
},
/// Renames a layer in the network the node graph is showing, which may be a subgraph.
SetLayerNameInGraph {
node_id: NodeId,
name: String,
},
SetLayersPanelHoveredLayer {
id: Option<NodeId>,
},
@@ -1,4 +1,5 @@
use super::DocumentHistory;
use super::node_graph::graph_ui::GraphUiPart;
use super::node_graph::{document_node_definitions, node_inspector};
use super::utility_types::error::EditorError;
use super::utility_types::layers_in_view::LayersInView;
@@ -199,7 +200,7 @@ pub struct DocumentMessageHandler {
/// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport.
#[serde(skip)]
layers_panel_hovered_layer: Option<LayerNodeIdentifier>,
/// The layers the frontend shows in view, the only ones it's sent the details and thumbnails of.
/// The layers in view in the Layers panel or the node graph, the only ones thumbnails are rendered for.
#[serde(skip)]
pub layers_in_view: LayersInView,
/// Whether or not the editor has executed the network to render the document yet. If this is opened as an inactive tab, it won't be loaded initially because the active tab is prioritized.
@@ -680,7 +681,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.breadcrumb_network_path.push(node_id);
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::ZoomCanvasToFitAll);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
@@ -699,20 +699,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.network_interface.cancel_drag(&self.selection_network_path);
self.node_graph_handler.select_if_not_dragged = None;
self.node_graph_handler.nodes_added_in_drag = false;
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
self.node_graph_handler.graph_ui.stop_animations(responses);
responses.add(NodeGraphMessage::UpdateWireInsertionPreview);
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
// Abort dragging a dot out of a connector, before the dot has appeared
else if self.node_graph_handler.dot_drag_out.is_some() {
self.node_graph_handler.dot_drag_out = None;
}
// Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() {
self.node_graph_handler.box_selection_start = None;
else if self.node_graph_handler.box_selection.is_some() {
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.node_graph_handler.selection_before_pointer_down.clone(),
});
responses.add(FrontendMessage::UpdateBox { box_selection: None });
self.node_graph_handler.set_box_selection(None, responses);
}
// Abort wire in progress of being connected
else if self.node_graph_handler.wire_in_progress_from_connector.is_some() {
@@ -744,7 +744,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
}
self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::PTZUpdate);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
@@ -800,24 +799,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::GraphViewOverlay { open } => {
let opened = !self.graph_view_overlay_open && open;
self.graph_view_overlay_open = open;
self.node_graph_handler.graph_ui.graph_view_toggled(responses);
responses.add(FrontendMessage::UpdateGraphViewOverlay { open });
responses.add(FrontendMessage::UpdateGraphFadeArtwork {
percentage: self.graph_fade_artwork_percentage,
});
// Update the tilt menu bar buttons to be disabled when the graph is open
responses.add(MenuBarMessage::SendLayout);
responses.add(DocumentMessage::RenderRulers);
responses.add(DocumentMessage::RenderScrollbars);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
if opened {
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
}
if open {
responses.add(ToolMessage::DeactivateTools);
responses.add(OverlaysMessage::Draw); // Clear the overlays
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
responses.add(NodeGraphMessage::UpdateGraphBarRight);
responses.add(NodeGraphMessage::SendGraph);
@@ -827,6 +823,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
if self.end_node_graph_wire_in_progress(responses) {
responses.add(DocumentMessage::AbortTransaction);
}
self.node_graph_handler.abort_node_drag(&mut self.network_interface, &self.selection_network_path, responses);
responses.add(ToolMessage::ActivateTool { tool_type: *current_tool });
responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed
@@ -1545,6 +1542,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.chain_node_range_selection_reference = Some(node_id);
}
DocumentMessage::SetActivePanel { active_panel } => {
let selection_network_path = self.selection_network_path.clone();
match active_panel {
PanelType::Document => {
if self.graph_view_overlay_open {
@@ -1558,7 +1556,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
responses.add(InspectorMessage::Refresh);
responses.add(NodeGraphMessage::UpdateLayerPanel);
responses.add(NodeGraphMessage::UpdateInSelectedNetwork);
if self.graph_view_overlay_open && self.selection_network_path != selection_network_path {
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
}
DocumentMessage::SetBlendModeForSelectedLayers { blend_mode } => {
for layer in self.network_interface.selected_nodes().selected_layers_except_artboards(&self.network_interface) {
@@ -1567,15 +1567,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
DocumentMessage::SetGraphFadeArtwork { percentage } => {
self.graph_fade_artwork_percentage = percentage;
responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage });
}
DocumentMessage::SetLayerNameInGraph { node_id, name } => {
responses.add(NodeGraphMessage::SetDisplayName {
node_id,
network_path: self.breadcrumb_network_path.clone(),
alias: name,
skip_adding_history_step: false,
});
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
DocumentMessage::SetLayersPanelHoveredLayer { id } => {
let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked);
@@ -2087,6 +2079,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::UpdateBoxSelection);
responses.add(NodeGraphMessage::UpdateHoveredConnector);
responses.add(NodeGraphMessage::UpdateImportsExports);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
responses.add(FrontendMessage::UpdateNodeGraphTransform {
translation: transform.translation.into(),
@@ -2711,8 +2704,6 @@ impl DocumentMessageHandler {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
/// Keeps the graph showing the open network across a reconcile, which can rebuild its view state or remove it.
@@ -2768,8 +2759,6 @@ impl DocumentMessageHandler {
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
pub fn serialize_document(&self) -> String {
@@ -3067,9 +3056,6 @@ impl DocumentMessageHandler {
}
pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
// Settled before storage moves, so the glide's offsets don't outlive the step
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string);
// Alone, the step enters history first so it stays on the History panel once undone
if !self.is_in_session() {
@@ -3082,8 +3068,6 @@ impl DocumentMessageHandler {
}
pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string);
if self.history.redo() {
self.follow_storage_changes(stored_name, responses);
@@ -3093,8 +3077,6 @@ impl DocumentMessageHandler {
/// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo.
fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified;
if open_transaction_has_edits {
// Staged so they are taken back with the steps before them
@@ -3123,7 +3105,6 @@ impl DocumentMessageHandler {
return;
}
self.end_history_preview(viewport, responses);
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort);
self.apply_history_line_change(document_id, rev, change, byte_store, responses);
}
@@ -3138,7 +3119,7 @@ impl DocumentMessageHandler {
}
let Some(past) = self.history.interface_at(rev) else { return };
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
self.node_graph_handler.graph_ui.stop_animations(responses);
responses.add(EventMessage::ToolAbort);
let replaced = self.install_history_snapshot(past, viewport);
let current = self.history_preview.take().map_or(replaced, |preview| preview.current);
@@ -3191,8 +3172,6 @@ impl DocumentMessageHandler {
fn show_installed_interface(&self, responses: &mut VecDeque<Message>) {
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
@@ -3228,6 +3207,7 @@ impl DocumentMessageHandler {
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
self.node_graph_handler.graph_ui.stop_animations(responses);
if let Some(gdd) = self.history.storage_mut() {
let changes = gdd.take_remote_changes();
self.pending_remote.extend(changes);
@@ -4138,7 +4118,7 @@ impl DocumentMessageHandler {
})
.unwrap_or((None, None, None));
let blend_mode_menu_entries = BlendMode::list_svg_subset()
let blend_mode_menu_entries = BlendMode::list()
.iter()
.map(|modes| {
modes
@@ -4155,7 +4135,7 @@ impl DocumentMessageHandler {
let widgets = vec![
DropdownInput::new(blend_mode_menu_entries)
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
.disabled(disabled)
.draw_icon(false)
.sizing(WidgetSizing::default().grow(false))
@@ -5128,7 +5108,7 @@ mod document_message_handler_tests {
let document = portfolio.documents.get_mut(&document_id).unwrap();
portfolio
.executor
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO)
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO, None)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
@@ -1,11 +1,11 @@
use crate::application::Environment;
use crate::consts::{
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
};
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
@@ -34,6 +34,8 @@ pub struct NavigationMessageHandler {
abortable_pan_start: Option<f64>,
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
artwork_behind_graph: bool,
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
graph_middle_click_start: Option<ViewportPosition>,
}
#[message_handler_data]
@@ -99,6 +101,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
return;
};
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
}
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
@@ -341,6 +347,13 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
responses.add(ToolMessage::UpdateCursor);
responses.add(ToolMessage::UpdateHints);
responses.add(NavigateToolMessage::End);
// Not a pan after all, but a middle click in the graph
let middle_click_start = self.graph_middle_click_start.take();
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
responses.add(NodeGraphMessage::MiddleClick);
}
}
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
self.finish_operation_with_click = false;
@@ -417,6 +430,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
}
}
NavigationMessage::PointerMove { snap } => {
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
self.graph_middle_click_start = None;
}
match self.navigation_operation {
NavigationOperation::None => {}
NavigationOperation::Pan { .. } => {
@@ -3,18 +3,20 @@ mod document_node_derive;
use super::node_inspector::choice::enum_choice;
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::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
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 graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
use graph_craft::{concrete, list};
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
use graphene_std::vector::Vector;
use graphene_std::*;
use std::collections::{HashMap, VecDeque};
@@ -37,11 +39,6 @@ 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;
@@ -53,11 +50,11 @@ impl NodeInspectorContext<'_> {
}
/// Input position of the location 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_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
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 = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
/// Input position of the control path parameter on the "Blend" network node template.
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
/// The key used to access definitions for a network node or proto node.
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
@@ -109,7 +106,8 @@ pub struct DocumentNodeDefinition {
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
pub identifier: &'static str,
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
/// 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.
pub version: u32,
/// The default [`NodeTemplate`] this definition instantiates.
@@ -137,9 +135,529 @@ 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.
/// 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.
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
document_node_derive::derive_definitions()
let custom = vec![
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)
}
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
@@ -157,6 +675,7 @@ fn static_node_inspector() -> NodeInspector {
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
@@ -218,10 +737,91 @@ 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();
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
// 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(unit) = field.unit {
number_input = number_input.unit(unit);
}
@@ -352,6 +952,57 @@ fn static_input_inspector() -> InputInspector {
"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,
false,
)])
}),
);
map.insert(
"noise_inspector_scale".to_string(),
Box::new(|node_id, index, context| {
@@ -524,7 +1175,6 @@ fn static_input_inspector() -> InputInspector {
"Y",
"",
None,
None,
false,
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
)])
@@ -541,7 +1191,6 @@ fn static_input_inspector() -> InputInspector {
"Y",
"",
None,
None,
false,
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
)])
@@ -648,7 +1297,6 @@ fn static_input_inspector() -> InputInspector {
"Y",
" px",
None,
None,
false,
false,
)])
@@ -664,7 +1312,6 @@ fn static_input_inspector() -> InputInspector {
"H",
"x",
None,
None,
false,
false,
)])
@@ -785,7 +1432,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, None, false, false)])
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
}),
);
map
@@ -993,13 +1640,6 @@ pub fn network_node_identifiers() -> impl Iterator<Item = &'static str> {
})
}
pub fn collect_node_icons() -> Vec<(String, IconName)> {
DOCUMENT_NODE_TYPES
.iter()
.filter_map(|(identifier, definition)| Some((identifier.serialized(), definition.icon?.to_string())))
.collect()
}
impl DocumentNodeDefinition {
/// Converts the [DocumentNodeDefinition] type to a [NodeTemplate], using the provided `input_override` and falling back to the default inputs.
/// `input_override` does not have to be the correct length.
@@ -1033,18 +1673,6 @@ mod test {
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId;
// A `#[graph]` 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() {
// Released before resolving, since building the catalog locks the registry too
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
for identifier in identifiers {
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
}
}
#[test]
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
use glam::{DAffine2, UVec2};
@@ -1185,36 +1813,21 @@ mod test_type_constraints {
#[test]
fn every_definition_default_value_satisfies_its_constraint() {
// 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);
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);
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
for (index, (constraint, input)) in constraints.iter().zip(&definition.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);
}
}
}
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"));
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
}
#[test]
@@ -1231,7 +1844,7 @@ mod test_type_constraints {
#[test]
fn single_protonode() {
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::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)));
@@ -1245,7 +1858,7 @@ mod test_type_constraints {
#[test]
fn single_protonode2() {
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_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)));
@@ -1254,8 +1867,8 @@ mod test_type_constraints {
#[test]
fn network() {
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_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_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,17 +1,11 @@
use super::DocumentNodeDefinition;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
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 crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::{HashMap, HashSet};
/// 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> {
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let mut definitions_map = HashMap::new();
// Add the protonodes from the macro.
@@ -81,7 +75,16 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
input_metadata: input_metadata(fields),
// 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(),
output_names,
..Default::default()
},
@@ -93,242 +96,25 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
);
}
let graphs = GRAPH_METADATA.lock().unwrap().clone();
add_graph_definitions(graphs, &mut definitions_map);
// 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);
}
definitions_map
}
/// 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]` 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 by `#[graph]`, 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 by `#[graph]`.
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();
if let Some(call_argument) = &node.call_argument {
template.call_argument = call_argument.clone();
}
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 = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
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, which the macro already prevents for the graphs it builds
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);
}
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();
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.
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
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 ty = match default {
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
NodeInput::Import { import_type, .. } => import_type.clone(),
_ => generic!(T),
};
NodeInput::value(graph_value(value, &ty), 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
}
/// Converts a value written in a graph definition to the type of the input it feeds.
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
// An integer literal feeds an integer input as an integer, and any other as a number
let is_integer = *element_type(ty) == concrete!(i64);
match value {
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
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.
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &mut node_template.implementation {
NodeTemplateImplementation::Network(network_template) => {
@@ -342,190 +128,13 @@ 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;
if node_template.display_name.is_empty() {
node_template.display_name = definition_template.display_name.clone();
}
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",
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,
category: "Test",
icon: None,
description: "",
version: 1,
layer: false,
imports: vec![number_import()],
exports: vec![GraphExportMetadata {
name: "Out",
description: "",
source: GraphInputSource::Node { node: 0, output: 0 },
}],
nodes: vec![GraphNodeMetadata {
implementation,
inputs,
position: None,
layer: false,
display_name: None,
hidden: false,
locked: false,
pinned: false,
call_argument: None,
}],
}
}
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", math_nodes::as_number::IDENTIFIER.into(), 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", math_nodes::as_number::IDENTIFIER.into(), 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", math_nodes::as_number::IDENTIFIER.into(), from_import());
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), 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 an_integer_value_takes_the_type_of_the_input_it_feeds() {
let integer = Type::Item(Box::new(concrete!(i64)));
let number = Type::Item(Box::new(concrete!(f64)));
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
}
#[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", math_nodes::as_number::IDENTIFIER.into(), 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::subgraphs::artboard::LocationInput::INDEX;
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, &[]));
}
}
@@ -0,0 +1,514 @@
mod animation;
mod name_field;
mod pointer;
pub use name_field::{GraphName, GraphNameField, edited_name};
pub use pointer::{PointerHits, connector_under_pointer, tooltip_target};
use super::node_graph_message_handler::NodeGraphMessageHandler;
use super::utility_types::FrontendGraphDataType;
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NetworkConnectorKey, NodeNetworkInterface, OutputConnector, Previewing};
use crate::messages::prelude::{Message, PortfolioMessage, Responses};
use glam::DVec2;
use graph_craft::document::NodeId;
use graph_ui::GraphUiConfig;
use graph_ui::animation::{Glided, Glides};
use graph_ui::card::{Card, Connector, DataType, Selection};
use graph_ui::dot::Dot;
use graph_ui::error_badge::ErrorBadge;
use graph_ui::geometry::NodeGeometry;
use graph_ui::highlights::{self, Highlights, NodePart};
use graph_ui::layer::Layer;
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind, network_connector_row_offset};
use graph_ui::placed::Placed;
use graph_ui::replicated_map::{Keyed, ReplicatedMap, ReplicatedMapEdit};
use graph_ui::scene::GraphUiSceneEdit;
use graph_ui::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle};
use pointer::TooltipTarget;
use std::collections::{BTreeSet, HashMap, VecDeque};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConnectorKey {
Input(InputConnector),
Output(OutputConnector),
}
impl From<NetworkConnectorKey> for ConnectorKey {
fn from(connector: NetworkConnectorKey) -> Self {
match connector {
NetworkConnectorKey::Import(index) => ConnectorKey::Output(OutputConnector::Import(index)),
NetworkConnectorKey::Export(index) => ConnectorKey::Input(InputConnector::Export(index)),
}
}
}
impl From<ConnectorKey> for highlights::ConnectorKey {
fn from(connector: ConnectorKey) -> Self {
match connector {
ConnectorKey::Input(input) => highlights::ConnectorKey::Input(input_key(input)),
ConnectorKey::Output(output) => highlights::ConnectorKey::Output(output_key(output)),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GraphUiPart {
All,
NetworkConnectors,
Errors,
InsertionTarget,
Moved { nodes: Vec<NodeId> },
}
pub struct GraphUiSceneBuilder<'a> {
network_interface: &'a NodeNetworkInterface,
network_path: &'a [NodeId],
node_graph_handler: &'a NodeGraphMessageHandler,
selected_nodes: Vec<NodeId>,
selected: Selection,
}
impl<'a> GraphUiSceneBuilder<'a> {
pub fn of(document: &'a DocumentMessageHandler) -> Self {
let network_interface = &document.network_interface;
let network_path = document.breadcrumb_network_path();
Self {
network_interface,
network_path,
node_graph_handler: &document.node_graph_handler,
selected_nodes: network_interface.selected_nodes_in_nested_network(network_path).unwrap_or_default().0,
selected: if network_path == document.selection_network_path() {
Selection::Active
} else {
Selection::Inactive
},
}
}
pub fn update(&self, part: GraphUiPart, scene: &mut GraphUiSceneEdit) {
match part {
GraphUiPart::All => {
let dragging = self.network_interface.dragging(self.network_path);
let glides = &self.node_graph_handler.graph_ui.glides;
replace_rows(self.cards(), dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards);
replace_rows(self.layers(), dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers);
replace_rows(self.dots(), dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots);
place_wires(self.wires(), scene);
scene.network_connectors.replace_all(self.network_connectors());
scene.errors.replace_all(self.errors());
}
GraphUiPart::NetworkConnectors => scene.network_connectors.replace_all(self.network_connectors()),
GraphUiPart::Errors => scene.errors.replace_all(self.errors()),
GraphUiPart::InsertionTarget => self.update_insertion_target(scene),
GraphUiPart::Moved { nodes } => self.update_moved(scene, nodes),
}
}
fn nodes(&self) -> impl Iterator<Item = NodeId> + '_ {
self.network_interface.nested_network(self.network_path).into_iter().flat_map(|network| network.nodes.keys().copied())
}
fn selection(&self, key: NodeId) -> Selection {
if self.selected_nodes.contains(&key) { self.selected } else { Selection::None }
}
fn cards(&self) -> Vec<Placed<Card>> {
self.nodes().filter_map(|key| self.card(key)).collect()
}
fn card(&self, key: NodeId) -> Option<Placed<Card>> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
if network_interface.is_layer(&key, network_path) || network_interface.is_redirect_dot(&key, network_path) {
return None;
}
let NodeGeometry { cell, shape, .. } = self.geometry(key)?;
let name = network_interface.display_name(&key, network_path);
let look = Card {
key,
shape,
name,
icon: network_interface.node_icon(&key, network_path),
primary_input: self.input(key, 0),
primary_output: self.output(key, 0),
secondary_inputs: (1..network_interface.number_of_inputs(&key, network_path)).filter_map(|index| self.input(key, index)).collect(),
secondary_outputs: (1..network_interface.number_of_outputs(&key, network_path)).filter_map(|index| self.output(key, index)).collect(),
selection: self.selection(key),
visible: network_interface.is_visible(&key, network_path),
previewed: network_interface.previewing(network_path).previews(key),
};
Some(Placed { cell, look })
}
fn geometry(&self, key: NodeId) -> Option<NodeGeometry> {
self.network_interface.with_layout(self.network_path, |layout| layout.geometry(&key)).flatten()
}
fn layers(&self) -> Vec<Placed<Layer>> {
self.nodes().filter_map(|key| self.layer(key)).collect()
}
fn layer(&self, key: NodeId) -> Option<Placed<Layer>> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
if !network_interface.is_layer(&key, network_path) {
return None;
}
let NodeGeometry { cell, chain_length, shape, .. } = self.geometry(key)?;
let look = Layer {
key,
shape,
chain_length,
name: network_interface.display_name(&key, network_path),
renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::Layer(key)),
has_left_input_wire: network_interface.has_left_input_wire(&key, network_path),
primary_input: self.input(key, 0),
primary_output: self.output(key, 0),
secondary_input: (1..network_interface.number_of_inputs(&key, network_path)).find_map(|index| self.input(key, index)),
primary_input_connected_to_layer: network_interface.primary_input_connected_to_layer(&key, network_path),
primary_output_connected_to_layer: network_interface.primary_output_connected_to_layer(&key, network_path),
visible: network_interface.is_visible(&key, network_path),
read_only: network_interface.is_read_only(network_path),
selection: self.selection(key),
previewed: network_interface.previewing(network_path).previews(key),
};
Some(Placed { cell, look })
}
fn dots(&self) -> Vec<Placed<Dot>> {
self.nodes().filter_map(|key| self.dot(key)).collect()
}
fn dot(&self, key: NodeId) -> Option<Placed<Dot>> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
if !network_interface.is_redirect_dot(&key, network_path) {
return None;
}
let input = self.input(key, 0);
let output = self.output(key, 0);
let NodeGeometry { cell, shape, .. } = self.geometry(key)?;
let look = Dot {
key,
shape,
data_type: output.as_ref().map_or(DataType::General, |output| output.data_type),
wired: input.is_some_and(|input| input.connected) || output.is_some_and(|output| output.connected),
selected: self.selected_nodes.contains(&key),
previewed: network_interface.previewing(network_path).previews(key),
};
Some(Placed { cell, look })
}
fn wires(&self) -> Vec<Wire> {
let inputs = self.network_interface.node_graph_input_connectors(self.network_path).into_iter();
inputs.filter_map(|input| self.wire(input)).chain(self.preview_wire()).collect()
}
fn wire(&self, input: InputConnector) -> Option<Wire> {
let output = self.network_interface.upstream_output_connector(&input, self.network_path)?;
let to = input_key(input);
Some(self.wire_row(WireKey::Input(to), output, to))
}
fn preview_wire(&self) -> Option<Wire> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let input = InputConnector::Export(0);
let Previewing::Yes { previewed } = network_interface.previewing(network_path) else { return None };
if network_interface.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
return None;
}
Some(self.wire_row(WireKey::Preview, previewed.to_connector(), input_key(input)))
}
fn wire_row(&self, key: WireKey, output: OutputConnector, to: InputKey) -> Wire {
let output_type = self.network_interface.output_type(&output, self.network_path);
Wire {
key,
from: output_key(output),
to,
data_type: data_type(output_type.displayed_type()),
list: output_type.is_list(),
insertion_target: Some(key) == self.insertion_target(),
}
}
fn insertion_target(&self) -> Option<WireKey> {
self.node_graph_handler.wire_insertion_preview.map(|input| WireKey::Input(input_key(input)))
}
fn network_connectors(&self) -> Vec<NetworkConnector> {
[NetworkConnectorKind::Import, NetworkConnectorKind::Export]
.into_iter()
.flat_map(|kind| self.network_connectors_of(kind))
.collect()
}
fn network_connectors_of(&self, kind: NetworkConnectorKind) -> Vec<NetworkConnector> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let count = match kind {
NetworkConnectorKind::Import => network_interface.number_of_imports(network_path),
NetworkConnectorKind::Export => network_interface.number_of_exports(network_path),
};
let row = |key: NetworkConnectorKey, position: DVec2, connector: Option<Connector>| NetworkConnector {
key,
position: position.as_ivec2(),
connector,
editable: !network_path.is_empty(),
renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::NetworkConnector(key)),
};
let named = (0..count).filter_map(|index| {
let key = NetworkConnectorKey::new(kind, index);
Some(row(key, self.position(key.into())?, Some(self.connector(key.into())?)))
});
let empty = network_interface.empty_import_export_connectors(kind == NetworkConnectorKind::Import, network_path);
named
.chain(empty.into_iter().map(|(index, position)| row(NetworkConnectorKey::new(kind, index), position, None)))
.collect()
}
fn errors(&self) -> Vec<ErrorBadge> {
let errors = self.node_graph_handler.node_graph_errors(self.network_interface, self.network_path);
errors.into_iter().map(|(key, text)| ErrorBadge { key, text }).collect()
}
fn update_moved(&self, scene: &mut GraphUiSceneEdit, nodes: Vec<NodeId>) {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let downstream_layers = nodes.iter().filter_map(|node| network_interface.downstream_layer_for_chain_node(node, network_path));
let rows: BTreeSet<NodeId> = nodes.iter().copied().chain(downstream_layers).collect();
self.place_node_rows(rows, scene);
scene.network_connectors.replace_all(self.network_connectors());
place_wires(all_wires(scene), scene);
}
fn place_node_rows(&self, nodes: impl IntoIterator<Item = NodeId>, scene: &mut GraphUiSceneEdit) {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let dragging = network_interface.dragging(network_path);
let glides = &self.node_graph_handler.graph_ui.glides;
for node in nodes {
let Some(NodeGeometry { cell, chain_length, .. }) = self.geometry(node) else { continue };
let placed = replace_row(node, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards, |card| {
(card.cell != cell).then(|| Placed { cell, look: card.look.clone() })
}) || replace_row(node, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers, |layer| {
let has_left_input_wire = network_interface.has_left_input_wire(&node, network_path);
let changed = (layer.cell, layer.look.chain_length, layer.look.has_left_input_wire) != (cell, chain_length, has_left_input_wire);
let look = || Layer {
chain_length,
has_left_input_wire,
..layer.look.clone()
};
changed.then(|| Placed { cell, look: look() })
}) || replace_row(node, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots, |dot| {
(dot.cell != cell).then(|| Placed { cell, look: dot.look.clone() })
});
if !placed {
self.put_node_rows(node, dragging, scene);
}
}
}
fn put_node_rows(&self, node: NodeId, dragging: bool, scene: &mut GraphUiSceneEdit) {
let glides = &self.node_graph_handler.graph_ui.glides;
if let Some(card) = self.card(node) {
place_row(card, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards);
}
if let Some(layer) = self.layer(node) {
place_row(layer, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers);
}
if let Some(dot) = self.dot(node) {
place_row(dot, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots);
}
}
fn input(&self, node: NodeId, index: usize) -> Option<Connector> {
self.connector(ConnectorKey::Input(InputConnector::node_at_index(node, index)))
}
fn output(&self, node: NodeId, index: usize) -> Option<Connector> {
self.connector(ConnectorKey::Output(OutputConnector::node(node, index)))
}
fn connector(&self, key: ConnectorKey) -> Option<Connector> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let (name, connector_type, connected) = match key {
ConnectorKey::Input(input) => network_interface.graph_ui_input(&input, network_path),
ConnectorKey::Output(output) => network_interface.graph_ui_output(&output, network_path),
}?;
Some(Connector {
index: match key {
ConnectorKey::Input(input) => input.input_index(),
ConnectorKey::Output(output) => output.index(),
} as u32,
name,
data_type: data_type(connector_type.displayed_type()),
connected,
})
}
fn position(&self, key: ConnectorKey) -> Option<DVec2> {
match key {
ConnectorKey::Input(input) => self.network_interface.input_position(&input, self.network_path),
ConnectorKey::Output(output) => self.network_interface.output_position(&output, self.network_path),
}
}
fn update_insertion_target(&self, scene: &mut GraphUiSceneEdit) {
let target = self.insertion_target();
let wires = all_wires(scene).into_iter().map(|wire| Wire {
insertion_target: Some(wire.key) == target,
..wire
});
place_wires(wires.collect(), scene);
}
}
fn stays<T: Keyed<Key = NodeId> + PartialEq>(row: &T, dragging: bool, glides: &Glides, settled: &ReplicatedMap<T>) -> bool {
!glides.rows.contains_key(&Glided::Node(row.key())) && (!dragging || settled.get(&row.key()) == Some(row))
}
fn replace_rows<T: Keyed<Key = NodeId> + PartialEq>(rows: Vec<T>, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit<T>, moving: &mut ReplicatedMapEdit<T>) {
let (still, moved): (Vec<T>, Vec<T>) = rows.into_iter().partition(|row| stays(row, dragging, glides, settled));
settled.replace_all(still);
moving.replace_all(moved);
}
fn place_row<T: Keyed<Key = NodeId> + PartialEq>(row: T, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit<T>, moving: &mut ReplicatedMapEdit<T>) {
let key = row.key();
if stays(&row, dragging, glides, settled) {
moving.remove(&key);
settled.put(row);
} else {
settled.remove(&key);
moving.put(row);
}
}
fn replace_row<T: Keyed<Key = NodeId> + PartialEq>(
node: NodeId,
dragging: bool,
glides: &Glides,
settled: &mut ReplicatedMapEdit<T>,
moving: &mut ReplicatedMapEdit<T>,
replaced: impl FnOnce(&T) -> Option<T>,
) -> bool {
let Some(row) = moving.get(&node).or_else(|| settled.get(&node)) else { return false };
if let Some(row) = replaced(row) {
place_row(row, dragging, glides, settled, moving);
}
true
}
fn all_wires(scene: &GraphUiSceneEdit) -> Vec<Wire> {
scene.settled.wires.iter().chain(scene.moving.wires.iter()).cloned().collect()
}
fn place_wires(wires: Vec<Wire>, scene: &mut GraphUiSceneEdit) {
let settled = |node: NodeId| scene.settled.cards.get(&node).is_some() || scene.settled.layers.get(&node).is_some() || scene.settled.dots.get(&node).is_some();
let between_settled_nodes = |wire: &Wire| match (wire.from, wire.to) {
(OutputKey::Node { node: from, .. }, InputKey::Node { node: to, .. }) => settled(from) && settled(to),
_ => false,
};
let (tiled, loose): (Vec<Wire>, Vec<Wire>) = wires.into_iter().partition(|wire| !wire.insertion_target && between_settled_nodes(wire));
scene.settled.wires.replace_all(tiled);
scene.moving.wires.replace_all(loose);
}
#[derive(Clone, Debug, Default)]
pub struct GraphUiState {
highlights: Highlights,
glides: Glides,
animating: bool,
pub(super) time: f64,
tooltip: Option<(Option<TooltipTarget>, String, String)>,
editing_name: Option<GraphName>,
name_field: Option<(GraphName, GraphNameField)>,
error_text_sizes: HashMap<String, DVec2>,
}
impl GraphUiState {
pub fn change_highlights(&mut self, change: impl FnOnce(&mut Highlights), responses: &mut VecDeque<Message>) {
let mut highlights = self.highlights.clone();
change(&mut highlights);
if self.highlights != highlights {
self.start_grows(&mut highlights);
self.highlights = highlights;
self.follow_animations(responses);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
}
}
pub fn config(document: &DocumentMessageHandler, wire_style: WireStyle) -> Option<GraphUiConfig> {
let node_graph_handler = &document.node_graph_handler;
let graph_metadata = document.network_interface.network_metadata(document.breadcrumb_network_path());
graph_metadata.filter(|_| document.graph_view_overlay_open).map(|metadata| {
let view = metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
GraphUiConfig {
view,
fade_artwork: document.graph_fade_artwork_percentage / 100.,
wire_in_progress: wire_in_progress(node_graph_handler),
reorder_bar: reorder_bar(document),
box_selection: node_graph_handler
.box_selection
.filter(|(_, dragged)| *dragged)
.map(|(corners, _)| corners.map(|corner| view.transform_point2(corner).max(DVec2::ZERO).floor())),
highlights: node_graph_handler.graph_ui.highlights.clone(),
wire_style,
glides: node_graph_handler.graph_ui.glides.clone(),
}
})
}
fn reorder_bar(document: &DocumentMessageHandler) -> Option<(NetworkConnectorKind, DVec2)> {
let node_graph_handler = &document.node_graph_handler;
let index = node_graph_handler.end_index?;
let kind = if node_graph_handler.reordering_import.is_some() {
NetworkConnectorKind::Import
} else if node_graph_handler.reordering_export.is_some() {
NetworkConnectorKind::Export
} else {
return None;
};
let (imports, exports) = document.network_interface.import_export_position(document.breadcrumb_network_path())?;
let first_row_center = match kind {
NetworkConnectorKind::Import => imports,
NetworkConnectorKind::Export => exports,
};
Some((kind, first_row_center.as_dvec2() + DVec2::new(0., network_connector_row_offset(index))))
}
fn wire_in_progress(node_graph_handler: &NodeGraphMessageHandler) -> Option<WireInProgress> {
Some(WireInProgress {
ends: node_graph_handler.wire_in_progress_ends?,
data_type: data_type(node_graph_handler.wire_in_progress_type),
})
}
fn output_key(output: OutputConnector) -> OutputKey {
match output {
OutputConnector::Node { node_id, output_index } => OutputKey::Node { node: node_id, index: output_index },
OutputConnector::Import(index) => OutputKey::Import(index),
}
}
fn input_key(input: InputConnector) -> InputKey {
match input {
InputConnector::Node { node_id, input_index } => InputKey::Node { node: node_id, index: input_index },
InputConnector::Export(index) => InputKey::Export(index),
}
}
fn data_type(data_type: FrontendGraphDataType) -> DataType {
match data_type {
FrontendGraphDataType::General => DataType::General,
FrontendGraphDataType::Number => DataType::Number,
FrontendGraphDataType::Artboard => DataType::Artboard,
FrontendGraphDataType::Graphic => DataType::Graphic,
FrontendGraphDataType::Raster => DataType::Raster,
FrontendGraphDataType::Vector => DataType::Vector,
FrontendGraphDataType::Color => DataType::Color,
FrontendGraphDataType::Gradient => DataType::Gradient,
FrontendGraphDataType::Typography => DataType::Typography,
FrontendGraphDataType::Invalid => DataType::Invalid,
}
}
@@ -0,0 +1,88 @@
use super::*;
use crate::messages::prelude::{BroadcastMessage, EventMessage, NodeGraphMessage};
use graph_ui::animation::{Animation, GROW_DURATION, Glided};
use graph_ui::highlights::ConnectorKey;
impl GraphUiState {
pub fn glide(&mut self, moves: impl IntoIterator<Item = (Glided, DVec2)>, responses: &mut VecDeque<Message>) {
for (row, moved) in moves {
let from = moved + self.glides.offset(row, self.time);
match Animation::glide(from, self.time) {
Some(glide) => self.glides.rows.insert(row, glide),
None => self.glides.rows.remove(&row),
};
}
self.follow_animations(responses);
}
pub fn stop_animations(&mut self, responses: &mut VecDeque<Message>) {
if !self.glides.rows.is_empty() {
self.glides.rows.clear();
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
if !self.highlights.grows.is_empty() {
self.highlights.grows.clear();
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
self.follow_animations(responses);
}
pub fn animation_tick(&mut self, graph_open: bool, responses: &mut VecDeque<Message>) {
if !self.animating {
responses.add(animation_frames(false));
return;
}
if !graph_open {
self.stop_animations(responses);
return;
}
let time = self.time;
self.highlights.grows.retain(|_, grow| !ended(grow, time));
if !self.glides.rows.is_empty() && self.glides.rows.values().all(|glide| ended(glide, time)) {
self.glides.rows.clear();
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
self.follow_animations(responses);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
pub(super) fn start_grows(&self, highlights: &mut Highlights) {
let keys: BTreeSet<ConnectorKey> = self.highlights.connectors().chain(highlights.connectors()).collect();
for key in keys {
let grows = highlights.connector(key).is_grown();
if self.highlights.connector(key).is_grown() == grows {
continue;
}
let (from, to) = (self.highlights.grown(key, self.time), if grows { 1. } else { 0. });
let grow = Animation {
from,
to,
start: self.time,
end: self.time + GROW_DURATION * (to - from).abs(),
};
highlights.grows.insert(key, grow);
}
}
pub(super) fn follow_animations(&mut self, responses: &mut VecDeque<Message>) {
let animating = !self.glides.rows.is_empty() || !self.highlights.grows.is_empty();
if self.animating == animating {
return;
}
self.animating = animating;
responses.add(animation_frames(animating));
}
}
fn animation_frames(subscribed: bool) -> BroadcastMessage {
let (on, send) = (EventMessage::AnimationFrame, Box::new(NodeGraphMessage::AnimationTick.into()));
match subscribed {
true => BroadcastMessage::SubscribeEvent { on, send },
false => BroadcastMessage::UnsubscribeEvent { on, send },
}
}
fn ended<T>(animation: &Animation<T>, time: f64) -> bool {
time >= animation.end || time < animation.start
}
@@ -0,0 +1,108 @@
use super::*;
use crate::messages::prelude::FrontendMessage;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum GraphName {
Layer(NodeId),
NetworkConnector(NetworkConnectorKey),
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct GraphNameField {
pub name: String,
pub x: f64,
pub top: f64,
#[serde(rename = "alignRight")]
pub align_right: bool,
pub dimmed: bool,
}
impl GraphUiSceneBuilder<'_> {
fn name_field(&self, name: GraphName) -> Option<GraphNameField> {
match name {
GraphName::Layer(key) => {
let layer = self.layer(key)?;
let [top_left, _] = layer.name_box();
Some(GraphNameField {
name: layer.look.name,
x: top_left.x,
top: top_left.y,
align_right: false,
dimmed: !layer.look.visible,
})
}
GraphName::NetworkConnector(key) => self.network_connector_name_field(key),
}
}
fn network_connector_name_field(&self, key: NetworkConnectorKey) -> Option<GraphNameField> {
let row = self.network_connectors().into_iter().find(|row| row.key == key && row.editable)?;
let connector = row.connector.as_ref()?;
let [top_left, _] = row.name_box(0.);
Some(GraphNameField {
name: connector.name.clone(),
x: top_left.x,
top: top_left.y,
align_right: key.kind() == NetworkConnectorKind::Import,
dimmed: false,
})
}
}
impl GraphUiState {
pub fn begin_name_edit(&mut self, name: GraphName, responses: &mut VecDeque<Message>) {
if self.editing_name != Some(name) {
self.editing_name = Some(name);
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
}
pub fn end_name_edit(&mut self) -> Option<GraphName> {
self.editing_name.take()
}
pub fn update_name_field(&mut self, field: Option<GraphNameField>, responses: &mut VecDeque<Message>) {
let shown = self.name_field.as_ref();
let same_row = |(name, field): &(GraphName, GraphNameField)| match (name, shown) {
(GraphName::NetworkConnector(_), Some((shown, shown_field))) if shown == name => shown_field.name == field.name,
_ => true,
};
let edited = self.editing_name.zip(field).filter(same_row);
if edited.is_none() {
self.editing_name = None;
}
if edited == self.name_field {
return;
}
let sent = self.name_field.as_ref().map(|(name, _)| *name);
let opens = edited.as_ref().is_some_and(|(name, _)| sent != Some(*name));
self.name_field.clone_from(&edited);
responses.add(FrontendMessage::UpdateGraphNameField {
field: edited.map(|(_, field)| field),
opens,
});
}
pub fn leave_network(&mut self, responses: &mut VecDeque<Message>) {
if self.editing_name.is_some() || self.name_field.is_some() {
self.drop_name_edit(responses);
}
}
pub fn graph_view_toggled(&mut self, responses: &mut VecDeque<Message>) {
self.tooltip = None;
self.drop_name_edit(responses);
}
fn drop_name_edit(&mut self, responses: &mut VecDeque<Message>) {
self.editing_name = None;
self.name_field = None;
responses.add(FrontendMessage::UpdateGraphNameField { field: None, opens: false });
}
}
pub fn edited_name(document: &DocumentMessageHandler) -> Option<GraphNameField> {
let name = document.node_graph_handler.graph_ui.editing_name?;
GraphUiSceneBuilder::of(document).name_field(name)
}
@@ -0,0 +1,260 @@
use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::LayerClickTargetTypes;
use crate::messages::prelude::FrontendMessage;
use graph_ui::metrics::{CARD_ROW_PADDING, GRID_SIZE};
use graph_ui::{error_badge, error_text_size};
use std::cell::OnceCell;
impl GraphUiState {
pub fn part_under_pointer(&mut self, hits: &PointerHits, errors: &[(NodeId, String)], pointer_free: bool) -> Option<NodePart> {
if let Some(badge) = self.error_badge_under(hits, errors) {
return Some(NodePart::ErrorBadge(badge));
}
let (network_interface, network_path) = (hits.network_interface, hits.network_path);
let dot = hits.node().filter(|node_id| network_interface.is_redirect_dot(node_id, network_path));
if let Some(dot) = dot {
if !pointer_free {
return None;
}
if hits.output() == Some(OutputConnector::node(dot, 0)) {
return Some(NodePart::DotOutput(dot));
}
let pulls_a_wire_in = hits.input() == Some(InputConnector::node_at_index(dot, 0));
return (!pulls_a_wire_in).then_some(NodePart::Dot(dot));
}
let visibility = hits.visibility().map(NodePart::Visibility);
let lock = || hits.lock().map(NodePart::Lock);
let grip = || hits.grip().map(NodePart::Grip);
visibility.or_else(lock).or_else(grip)
}
fn error_badge_under(&mut self, hits: &PointerHits, errors: &[(NodeId, String)]) -> Option<NodeId> {
let mut badges: Vec<&(NodeId, String)> = errors.iter().collect();
badges.sort_by_key(|(key, _)| (self.highlights.badge_hovered(*key), *key));
let text_sizes = &mut self.error_text_sizes;
text_sizes.retain(|text, _| badges.iter().any(|(_, badge_text)| badge_text == text));
let mut text_size = |text: &String| match text_sizes.get(text) {
Some(size) => *size,
None => *text_sizes.entry(text.clone()).or_insert_with(|| error_text_size(text)),
};
let geometry = |key: &NodeId| hits.network_interface.with_layout(hits.network_path, |layout| layout.geometry(key)).flatten();
let mut covers = |(key, text): &(NodeId, String)| geometry(key).is_some_and(|geometry| error_badge::covers(geometry.error_badge_anchor(), text_size(text), hits.point));
badges.into_iter().rev().find(|badge| covers(badge)).map(|(key, _)| *key)
}
pub fn set_tooltip(&mut self, target: Option<TooltipTarget>, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
let (label, description) = target.map(|target| tooltip_text(target, network_interface, network_path)).unwrap_or_default();
let tooltip = (target, label, description);
if self.tooltip.as_ref() == Some(&tooltip) {
return;
}
let (_, label, description) = self.tooltip.insert(tooltip).clone();
responses.add(FrontendMessage::UpdateGraphTooltip { label, description });
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TooltipTarget {
Name(NetworkConnectorKey),
AddConnector(NetworkConnectorKey),
Connector(ConnectorKey),
Visibility(NodeId),
Lock(NodeId),
Grip(NodeId),
Dot(NodeId),
Row { node: NodeId, row: usize },
Node(NodeId),
}
pub struct PointerHits<'a> {
network_interface: &'a NodeNetworkInterface,
network_path: &'a [NodeId],
viewport_location: DVec2,
point: DVec2,
found: FoundHits,
}
#[derive(Default)]
struct FoundHits {
name: OnceCell<Option<NetworkConnectorKey>>,
empty_connector: OnceCell<Option<NetworkConnectorKey>>,
node: OnceCell<Option<NodeId>>,
visibility: OnceCell<Option<NodeId>>,
lock: OnceCell<Option<NodeId>>,
grip: OnceCell<Option<NodeId>>,
input: OnceCell<Option<InputConnector>>,
output: OnceCell<Option<OutputConnector>>,
}
impl<'a> PointerHits<'a> {
pub fn new(network_interface: &'a NodeNetworkInterface, network_path: &'a [NodeId], viewport_location: DVec2, point: DVec2) -> Self {
Self {
network_interface,
network_path,
viewport_location,
point,
found: FoundHits::default(),
}
}
fn name(&self) -> Option<NetworkConnectorKey> {
*self.found.name.get_or_init(|| self.network_interface.import_export_name_from_point(self.point, self.network_path))
}
fn empty_connector(&self) -> Option<NetworkConnectorKey> {
*self.found.empty_connector.get_or_init(|| {
let empty = |is_import| self.network_interface.empty_import_export_connector_at(self.point, is_import, self.network_path);
let import = empty(true).map(|(index, _)| NetworkConnectorKey::Import(index));
import.or_else(|| empty(false).map(|(index, _)| NetworkConnectorKey::Export(index)))
})
}
fn node(&self) -> Option<NodeId> {
*self.found.node.get_or_init(|| self.network_interface.node_from_click(self.viewport_location, self.network_path))
}
fn visibility(&self) -> Option<NodeId> {
self.layer_button(&self.found.visibility, LayerClickTargetTypes::Visibility)
}
fn lock(&self) -> Option<NodeId> {
self.layer_button(&self.found.lock, LayerClickTargetTypes::Lock)
}
fn grip(&self) -> Option<NodeId> {
self.layer_button(&self.found.grip, LayerClickTargetTypes::Grip)
}
fn layer_button(&self, found: &OnceCell<Option<NodeId>>, button: LayerClickTargetTypes) -> Option<NodeId> {
*found.get_or_init(|| self.network_interface.layer_click_target_from_click(self.viewport_location, button, self.network_path))
}
fn input(&self) -> Option<InputConnector> {
*self.found.input.get_or_init(|| self.network_interface.input_port_from_click(self.viewport_location, self.network_path))
}
fn output(&self) -> Option<OutputConnector> {
*self
.found
.output
.get_or_init(|| self.network_interface.output_port_from_click(self.viewport_location, self.network_path))
}
}
pub fn connector_under_pointer(hits: &PointerHits) -> Option<ConnectorKey> {
if hits.name().is_some() || hits.visibility().is_some() || hits.lock().is_some() {
return None;
}
let input = || hits.input().map(ConnectorKey::Input);
let output = || hits.output().map(ConnectorKey::Output);
hits.empty_connector().map(ConnectorKey::from).or_else(input).or_else(output)
}
pub fn tooltip_target(hits: &PointerHits) -> Option<TooltipTarget> {
let (network_interface, network_path) = (hits.network_interface, hits.network_path);
if let Some(name) = hits.name() {
return Some(TooltipTarget::Name(name));
}
if let Some(add) = hits.empty_connector() {
return Some(TooltipTarget::AddConnector(add));
}
let node = hits.node();
if let Some(dot) = node.filter(|node| network_interface.is_redirect_dot(node, network_path)) {
return Some(TooltipTarget::Dot(dot));
}
let input = || hits.input().map(|input| TooltipTarget::Connector(ConnectorKey::Input(input)));
let output = || hits.output().map(|output| TooltipTarget::Connector(ConnectorKey::Output(output)));
let part = hits
.visibility()
.map(TooltipTarget::Visibility)
.or_else(|| hits.lock().map(TooltipTarget::Lock))
.or_else(input)
.or_else(output)
.or_else(|| hits.grip().map(TooltipTarget::Grip));
if part.is_some() {
return part;
}
let node = node?;
if network_interface.is_layer(&node, network_path) {
return Some(TooltipTarget::Node(node));
}
let point = hits.point;
let [min, max] = network_interface.node_bounding_box(&node, network_path)?;
let row = ((point.y - min.y) / GRID_SIZE).floor();
let on_row_name = point.x >= min.x + CARD_ROW_PADDING && point.x <= max.x - CARD_ROW_PADDING;
Some(if row >= 1. && on_row_name {
TooltipTarget::Row { node, row: row as usize }
} else {
TooltipTarget::Node(node)
})
}
fn tooltip_text(target: TooltipTarget, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (String, String) {
let input = |input: InputConnector| network_interface.input_tooltip(&input, network_path);
let output = |output: OutputConnector| network_interface.output_tooltip(&output, network_path);
let input_tooltip = |key: InputConnector| {
let lists_no_types = matches!(key, InputConnector::Node { .. });
input(key).map(|input| connector_tooltip(input.name, &input.description, input.resolved_type, &input.valid_types, input.connected, lists_no_types))
};
let output_tooltip = |key: OutputConnector| output(key).map(|output| connector_tooltip(output.name, &output.description, output.resolved_type, &output.possible_types, output.connected, false));
let label_only = |text: &str| (text.to_string(), String::new());
match target {
TooltipTarget::Name(NetworkConnectorKey::Import(index)) => (network_interface.displayed_import_name(index, network_path), network_interface.import_description(index, network_path)),
TooltipTarget::Name(NetworkConnectorKey::Export(index)) => (network_interface.displayed_export_name(index, network_path), network_interface.export_description(index, network_path)),
TooltipTarget::AddConnector(add) => {
let (label, description) = match add {
NetworkConnectorKey::Import(index) => (
if index == 0 { "Add Primary Import" } else { "Add Import" },
"Drag a wire from here and connect it to an input, or drop one here from an input.",
),
NetworkConnectorKey::Export(index) => (
if index == 0 { "Add Primary Export" } else { "Add Export" },
"Drag a wire from here and connect it to an output, or drop one here from an output.",
),
};
(label.to_string(), description.to_string())
}
TooltipTarget::Connector(ConnectorKey::Input(key)) => input_tooltip(key).unwrap_or_default(),
TooltipTarget::Connector(ConnectorKey::Output(key)) => output_tooltip(key).unwrap_or_default(),
TooltipTarget::Visibility(layer) => label_only(if network_interface.is_visible(&layer, network_path) { "Hide" } else { "Show" }),
TooltipTarget::Lock(_) => label_only("Unlock"),
TooltipTarget::Grip(_) => (String::new(), "Drag only this layer without pushing others outside the stack".to_string()),
TooltipTarget::Dot(dot) => output_tooltip(OutputConnector::node(dot, 0)).unwrap_or_else(|| label_only(&network_interface.display_name(&dot, network_path))),
TooltipTarget::Row { node, row } => {
let exposed = |index: &usize| network_interface.graph_ui_input(&InputConnector::node_at_index(node, *index), network_path).is_some();
let input_index = (1..network_interface.number_of_inputs(&node, network_path)).filter(exposed).nth(row - 1);
let named_input = input_index.map(|index| network_interface.displayed_input_name_and_description(&node, index, network_path));
let named_output = || {
network_interface
.graph_ui_output(&OutputConnector::node(node, row), network_path)
.map(|(name, ..)| (name, network_interface.output_description(&node, row, network_path)))
};
named_input.or_else(named_output).unwrap_or_default()
}
TooltipTarget::Node(node) => {
let (name, implementation_name) = (network_interface.display_name(&node, network_path), network_interface.implementation_name(&node, network_path));
let label = if name == implementation_name { name } else { format!("{implementation_name} ({name})") };
let definition = network_interface.reference(&node, network_path).and_then(|reference| resolve_document_node_type(&reference));
(label, definition.map(|definition| definition.description.trim().to_string()).unwrap_or_default())
}
}
}
fn connector_tooltip(name: String, description: &str, resolved_type: String, types: &[String], connected: bool, lists_no_types: bool) -> (String, String) {
let wired_type = connected.then(|| format!("Wired Type:\n`{resolved_type}`"));
let possible_types = if types.is_empty() {
lists_no_types.then(|| "Possible Types:\nNone".to_string())
} else {
Some(format!("Possible Types:\n{}", types.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join("\n")))
};
let types = [wired_type, possible_types].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
let description = [description.trim().to_string(), types].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n---\n");
(if name.is_empty() { resolved_type } else { name }, description)
}
@@ -1,4 +1,5 @@
pub mod document_node_definitions;
pub mod graph_ui;
mod node_graph_message;
mod node_graph_message_handler;
pub mod node_inspector;
@@ -1,8 +1,9 @@
use super::graph_ui::GraphName;
use super::utility_types::{Direction, NodeEvaluationError};
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, InputConnector, NetworkConnectorKey, NodeTemplate, OutputConnector};
use crate::messages::prelude::*;
use glam::IVec2;
use graph_craft::document::value::TaggedValue;
@@ -78,7 +79,7 @@ pub enum NodeGraphMessage {
},
/// Disconnects every wire an import feeds, or the wire feeding an export.
DisconnectImportExport {
index: ImportOrExport,
index: NetworkConnectorKey,
},
EnterNestedNetwork,
DuplicateSelectedNodes,
@@ -170,12 +171,11 @@ pub enum NodeGraphMessage {
PointerOutsideViewport {
shift: Key,
},
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
MiddleClick,
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
WireHoverTick,
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
SendGlide,
/// Sent every frame while nodes glide into their grid cells, to bring them closer.
GlideTick,
AnimationTick,
ShakeNode,
UpdateNodeGraphWidth,
RemoveImport {
@@ -186,7 +186,7 @@ pub enum NodeGraphMessage {
},
/// Removes an import or export, or hides it if it's the primary, since the primary slot always remains.
RemoveImportExport {
index: ImportOrExport,
index: NetworkConnectorKey,
},
ReorderImport {
start_index: usize,
@@ -207,11 +207,8 @@ pub enum NodeGraphMessage {
SelectedNodesSet {
nodes: Vec<NodeId>,
},
UnloadWires,
SendWires,
UpdateVisibleNodes,
UpdateLayersInView,
SendGraph,
SendNodePositions,
SetInputValue {
node_id: NodeId,
input_index: usize,
@@ -221,10 +218,11 @@ pub enum NodeGraphMessage {
input_connector: InputConnector,
input: NodeInput,
},
/// Asks the frontend to enter inline-rename mode for the given layer's display name in the graph view.
/// Triggered by double-clicking the layer's name area.
BeginEditLayerName {
node_id: NodeId,
BeginEditName {
name: GraphName,
},
EndEditName {
name: Option<String>,
},
SetDisplayName {
node_id: NodeId,
@@ -256,15 +254,11 @@ pub enum NodeGraphMessage {
NudgeSelectedNodes {
direction: Direction,
},
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
ShiftSelectedNodes {
direction: Direction,
glide: bool,
},
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
ShiftSelectedNodesByAmount {
graph_delta: IVec2,
glide: bool,
},
/// Draws the dragged nodes `offset` grid cells from where the drag started, stored once the drag finishes.
DragSelectedNodes {
@@ -278,19 +272,19 @@ pub enum NodeGraphMessage {
},
SetImportExportName {
name: String,
index: ImportOrExport,
index: NetworkConnectorKey,
},
SetImportExportNameImpl {
name: String,
index: ImportOrExport,
index: NetworkConnectorKey,
},
SetImportExportDescription {
description: String,
index: ImportOrExport,
index: NetworkConnectorKey,
},
SetImportExportDescriptionImpl {
description: String,
index: ImportOrExport,
index: NetworkConnectorKey,
},
ToggleSelectedAsLayersOrNodes,
ToggleSelectedLocked,
@@ -327,7 +321,6 @@ pub enum NodeGraphMessage {
network_path: Vec<NodeId>,
},
UpdateBoxSelection,
/// Shows hovered the connector a press at the pointer would grab, or none.
UpdateHoveredConnector,
/// Highlights the wire a dragged node would be inserted onto if dropped where it is, or stops highlighting one.
UpdateWireInsertionPreview,
@@ -352,7 +345,6 @@ pub enum NodeGraphMessage {
},
UpdateActionButtons,
UpdateGraphBarRight,
UpdateInSelectedNetwork,
UpdateHints,
SendSelectedNodes,
}
@@ -380,6 +372,7 @@ impl NodeGraphMessage {
| Self::MergeSelectedNodes
| Self::ReorderImport { .. }
| Self::ReorderExport { .. }
| Self::BeginEditName { .. }
| Self::SetImportExportName { .. }
| Self::SetImportExportNameImpl { .. }
| Self::SetImportExportDescription { .. }
@@ -416,7 +409,6 @@ impl NodeGraphMessage {
| Self::RemoveImportExport { .. }
| Self::SetInputValue { .. }
| Self::SetInput { .. }
| Self::BeginEditLayerName { .. }
| Self::MakeUnique { .. }
| Self::SetToNodeOrLayer { .. }
| Self::ShiftNodePosition { .. }
@@ -437,20 +429,18 @@ impl NodeGraphMessage {
| Self::PointerMove { .. }
| Self::PointerUp
| Self::PointerOutsideViewport { .. }
| Self::MiddleClick
| Self::WireHoverTick
| Self::SendGlide
| Self::GlideTick
| Self::AnimationTick
| Self::UpdateNodeGraphWidth
| Self::RunDocumentGraph
| Self::ForceRunDocumentGraph
| Self::SelectedNodesAdd { .. }
| Self::SelectedNodesRemove { .. }
| Self::SelectedNodesSet { .. }
| Self::UnloadWires
| Self::SendWires
| Self::UpdateVisibleNodes
| Self::UpdateLayersInView
| Self::SendGraph
| Self::SendNodePositions
| Self::EndEditName { .. }
| Self::TogglePreview { .. }
| Self::TogglePreviewImpl { .. }
| Self::UpdateBoxSelection
@@ -464,7 +454,6 @@ impl NodeGraphMessage {
| Self::UpdateEvaluationErrors { .. }
| Self::UpdateActionButtons
| Self::UpdateGraphBarRight
| Self::UpdateInSelectedNetwork
| Self::UpdateHints
| Self::SendSelectedNodes => None,
}
File diff suppressed because it is too large. Load diff
@@ -41,7 +41,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
@@ -240,7 +240,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)]
#[derive(Clone, Copy, Default)]
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
@@ -252,50 +252,6 @@ 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.
@@ -349,12 +305,9 @@ 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().is_integer(integer);
let mut number_input = NumberInput::default();
if slider {
number_input = number_input.mode_range();
}
@@ -397,7 +350,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
}
};
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, 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| {
@@ -441,10 +394,7 @@ 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) => {
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::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &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)),
@@ -514,6 +464,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
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::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().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(),
@@ -954,7 +905,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
}
}
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 {
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
@@ -969,7 +920,7 @@ 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(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.max((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))))
@@ -980,7 +931,7 @@ 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(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.max((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()))))
@@ -995,7 +946,7 @@ 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(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.max((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))))
@@ -1006,7 +957,7 @@ 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(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.max((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()))))
@@ -1386,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
return LayoutGroup::row(vec![]);
};
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
let entries = BlendMode::list_svg_subset()
let entries = BlendMode::list()
.iter()
.map(|category| {
category
@@ -1403,9 +1354,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries)
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
.widget_instance(),
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
]);
}
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
@@ -1966,6 +1915,8 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
enum MarkerScale {
/// A 0..100 percentage, placed linearly.
Percent,
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
LevelPercent,
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
Gamma,
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
@@ -1975,7 +1926,7 @@ enum MarkerScale {
impl MarkerScale {
fn position(self, value: f64) -> f64 {
match self {
Self::Percent => value / 100.,
Self::Percent | Self::LevelPercent => value / 100.,
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
Self::Degrees => {
@@ -1989,7 +1940,7 @@ impl MarkerScale {
fn value(self, position: f64) -> f64 {
match self {
Self::Percent => (position * 100.).clamp(0., 100.),
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
Self::Degrees => (position * 360.).clamp(0., 360.),
@@ -1999,6 +1950,7 @@ impl MarkerScale {
fn number_input(self) -> NumberInput {
match self {
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
}
@@ -2023,6 +1975,8 @@ struct SliderSectionParam {
dash_to_next: bool,
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
between_neighbors: bool,
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
overlap_next: MarkerOverlap,
}
impl SliderSectionParam {
@@ -2035,6 +1989,7 @@ impl SliderSectionParam {
pair_with_next: false,
dash_to_next: false,
between_neighbors: false,
overlap_next: MarkerOverlap::Never,
}
}
@@ -2052,11 +2007,52 @@ impl SliderSectionParam {
self.dash_to_next = true;
self
}
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
self.overlap_next = overlap;
self
}
}
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
let mut lower = 0_f64;
let mut upper = 1_f64;
// A neighbor bounds the marker unless they overlap
if overlap(previous) == MarkerOverlap::Never
&& let Some(previous) = position(previous)
{
lower = lower.max(previous);
}
if overlap(Some(index)) == MarkerOverlap::Never
&& let Some(next) = position(next)
{
upper = upper.min(next);
}
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
if bounds_beyond(overlap(previous), overlap(before_previous))
&& let Some(before_previous) = position(before_previous)
{
lower = lower.max(before_previous);
}
if bounds_beyond(overlap(Some(index)), overlap(next))
&& let Some(after_next) = position(after_next)
{
upper = upper.min(after_next);
}
(lower, upper)
}
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
// Snapshot exposure and values before the mutable-borrow loop
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
@@ -2084,6 +2080,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
let mut marker_scales = Vec::new();
let mut marker_positions = Vec::new();
let mut marker_between = Vec::new();
let mut marker_overlaps = Vec::new();
let mut marker_colors_and_links = Vec::new();
for (i, param) in params.iter().enumerate() {
let (exposed, value) = exposure_and_value[i];
@@ -2096,13 +2093,21 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
marker_default_positions.push(param.scale.position(param.default_value));
marker_scales.push(param.scale);
marker_between.push(param.between_neighbors);
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
}
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
let cyclic = params.iter().any(|param| param.scale.cyclic());
if !cyclic {
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
if overlapping {
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
for i in 0..marker_positions.len() {
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
marker_positions[i] = marker_positions[i].max(lower);
}
} else if !cyclic {
let mut floor = 0.;
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
if between {
@@ -2123,8 +2128,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
let slider_markers: Vec<SliderMarker> = marker_positions
.iter()
.zip(&marker_colors_and_links)
.zip(&marker_between)
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
.zip(marker_between.iter().zip(&marker_overlaps))
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
let mut marker = SliderMarker::new(position, 0.5, handle_color);
if paired {
marker = marker.pair_with_next();
@@ -2135,6 +2140,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
if between {
marker = marker.between_neighbors();
}
marker = marker.overlap_next(overlap);
marker
})
.collect();
@@ -2156,6 +2162,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
let marker_scales = marker_scales.clone();
let marker_positions = marker_positions.clone();
let marker_between = marker_between.clone();
let marker_overlaps = marker_overlaps.clone();
move |update: &SliderInputUpdate| {
let i = match update {
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
@@ -2170,8 +2177,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
// nearest markers that bound it, which a marker placed between its neighbors never does
let bounding = |j: usize| between || !marker_between[j];
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
let (left, right) = if overlapping {
overlap_bounds(&marker_positions, &marker_overlaps, i)
} else {
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
(left, right)
};
let scale_position = match update {
SliderInputUpdate::MoveMarker { position, .. } if between => {
@@ -2596,6 +2608,105 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
layout
}
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::blending_nodes::blend_if::blend_if::*;
let channel = enum_choice::<BlendIfChannel>()
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
.inspector_row();
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
Some(TaggedValue::BlendIfChannel(channel)) => channel,
_ => BlendIfChannel::Gray,
};
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
BlendIfChannel::Gray => (
[
[
ContentFalloffStartInput.into(),
ContentRangeStartInput.into(),
ContentRangeEndInput.into(),
ContentFalloffEndInput.into(),
],
[
UnderlyingFalloffStartInput.into(),
UnderlyingRangeStartInput.into(),
UnderlyingRangeEndInput.into(),
UnderlyingFalloffEndInput.into(),
],
],
Color::WHITE,
),
BlendIfChannel::Red => (
[
[
RedContentFalloffStartInput.into(),
RedContentRangeStartInput.into(),
RedContentRangeEndInput.into(),
RedContentFalloffEndInput.into(),
],
[
RedUnderlyingFalloffStartInput.into(),
RedUnderlyingRangeStartInput.into(),
RedUnderlyingRangeEndInput.into(),
RedUnderlyingFalloffEndInput.into(),
],
],
Color::RED,
),
BlendIfChannel::Green => (
[
[
GreenContentFalloffStartInput.into(),
GreenContentRangeStartInput.into(),
GreenContentRangeEndInput.into(),
GreenContentFalloffEndInput.into(),
],
[
GreenUnderlyingFalloffStartInput.into(),
GreenUnderlyingRangeStartInput.into(),
GreenUnderlyingRangeEndInput.into(),
GreenUnderlyingFalloffEndInput.into(),
],
],
Color::GREEN,
),
BlendIfChannel::Blue => (
[
[
BlueContentFalloffStartInput.into(),
BlueContentRangeStartInput.into(),
BlueContentRangeEndInput.into(),
BlueContentFalloffEndInput.into(),
],
[
BlueUnderlyingFalloffStartInput.into(),
BlueUnderlyingRangeStartInput.into(),
BlueUnderlyingRangeEndInput.into(),
BlueUnderlyingFalloffEndInput.into(),
],
],
Color::BLUE,
),
};
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
let track = Gradient::from(vec![Color::BLACK, track_color]);
let mut layout = vec![channel];
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
let params = [
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
.dash_to_next()
.overlap_next(MarkerOverlap::Freely),
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
];
build_shared_slider_section(node_id, context, &track, &params, &mut layout);
}
layout
}
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::raster::vibrance::*;
@@ -2848,10 +2959,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, None, false, false);
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
widgets.extend([spacing, angles]);
} else {
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
widgets.push(spacing);
}
}
@@ -3314,20 +3425,40 @@ 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();
if let Some(default) = field.and_then(|field| field.default_type) {
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 {
break 'early_return default;
}
@@ -3343,21 +3474,12 @@ 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()
}
_ => {
// 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!(()))
}
_ => context
.network_interface
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
.compiled_nested_type()
.cloned()
.unwrap_or(concrete!(())),
};
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
@@ -3862,7 +3984,7 @@ pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorCon
if !matches!(mode, Some(DisplaceMode::Angle)) {
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, None, false, false));
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
}
let edge_mode = enum_choice::<GradientSpread>()
@@ -43,71 +43,27 @@ impl FrontendGraphDataType {
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendGraphInput {
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InputTooltip {
pub name: String,
pub description: String,
#[serde(rename = "resolvedType")]
pub resolved_type: String,
#[serde(rename = "validTypes")]
pub valid_types: Vec<String>,
/// Whether a wire feeds this input.
pub connected: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendGraphOutput {
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OutputTooltip {
pub name: String,
pub description: String,
#[serde(rename = "resolvedType")]
pub resolved_type: String,
/// Every type this output could produce given its node's current inputs, or empty where that isn't known.
#[serde(rename = "possibleTypes")]
pub possible_types: Vec<String>,
/// Whether this output feeds at least one wire.
pub connected: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendNode {
pub id: graph_craft::document::NodeId,
#[serde(rename = "isLayer")]
pub is_layer: bool,
#[serde(rename = "canBeLayer")]
pub can_be_layer: bool,
/// Whether the node is a redirect dot, which is a Passthrough node drawn as a small dot bending the wire running through it.
#[serde(rename = "isRedirectDot")]
pub is_redirect_dot: bool,
pub reference: Option<String>,
#[serde(rename = "displayName")]
pub display_name: String,
#[serde(rename = "implementationName")]
pub implementation_name: String,
#[serde(rename = "primaryInput")]
pub primary_input: Option<FrontendGraphInput>,
#[serde(rename = "exposedInputs")]
pub exposed_inputs: Vec<FrontendGraphInput>,
#[serde(rename = "primaryOutput")]
pub primary_output: Option<FrontendGraphOutput>,
#[serde(rename = "exposedOutputs")]
pub exposed_outputs: Vec<FrontendGraphOutput>,
#[serde(rename = "primaryInputConnectedToLayer")]
pub primary_input_connected_to_layer: bool,
#[serde(rename = "primaryOutputConnectedToLayer")]
pub primary_output_connected_to_layer: bool,
pub position: (i32, i32),
pub previewed: bool,
pub visible: bool,
pub locked: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum InputTypeConstraint {
@@ -135,19 +91,6 @@ pub struct DragStart {
pub stored: IVec2,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BoxSelection {
#[serde(rename = "startX")]
pub start_x: u32,
#[serde(rename = "startY")]
pub start_y: u32,
#[serde(rename = "endX")]
pub end_x: u32,
#[serde(rename = "endY")]
pub end_y: u32,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data")]
@@ -180,6 +123,10 @@ pub enum ContextMenuData {
exposed: bool,
/// Whether any wire is attached to it within the subgraph.
connected: bool,
description: String,
/// Where the description popover points, in node graph coordinates.
#[serde(rename = "descriptionAnchor")]
description_anchor: (f64, f64),
},
}
@@ -196,16 +143,6 @@ pub struct ContextMenuInformation {
pub context_menu_data: ContextMenuData,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct NodeGraphErrorDiagnostic {
/// The node the error is shown beside, which it follows as the node glides into place.
#[serde(rename = "nodeId")]
pub node_id: NodeId,
pub position: (i32, i32),
pub error: String,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeEvaluationError {
pub node_path: Vec<NodeId>,
@@ -24,9 +24,12 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
OverlaysMessage::Draw => {
use super::utility_types::OverlayContext;
if context.graph_open {
return;
}
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
if visibility_settings.all() && !context.graph_open {
if visibility_settings.all() {
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
@@ -1,9 +1,11 @@
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
use super::test_support::open_demo;
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::portfolio::document::utility_types::network_interface::Part;
use glam::DVec2;
use graph_ui::geometry::WireEnd;
use graph_ui::router::route;
use graph_ui::wire::WireStyle;
use graphene_std::uuid::NodeId;
use std::time::Instant;
@@ -19,38 +21,6 @@ const DEMOS: [&str; 8] = [
];
const REPETITIONS: u32 = 200;
#[test]
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
for demo in DEMOS {
let document = open_demo(demo);
let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() {
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
let on_port = |wanted: Part, anchor: Option<DVec2>| {
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
match (port, anchor) {
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
(Some(port), Some(anchor)) => port.contains(anchor),
(None, None) => true,
_ => false,
}
};
for index in 0..interface.number_of_inputs(node_id, &[]) {
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
}
for index in 0..interface.number_of_outputs(node_id, &[]) {
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
}
}
}
}
#[test]
#[ignore]
fn time_the_layout_click_targets_and_hit_tests() {
@@ -81,7 +51,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now();
for _ in 0..REPETITIONS {
for input in &inputs {
std::hint::black_box(interface.wire_update_from_input(input, GraphWireStyle::default(), &GlideOffsets::default(), &[]));
std::hint::black_box(interface.vector_wire_from_input(input, WireStyle::default(), &[]));
}
}
let all_wires = start.elapsed() / REPETITIONS;
@@ -104,25 +74,16 @@ fn time_the_layout_click_targets_and_hit_tests() {
let types = start.elapsed() / REPETITIONS;
let endpoints: Vec<_> = connected
.iter()
.filter_map(|(input, output)| Some((interface.output_position(output, &[])?, interface.input_position(input, &[])?)))
.filter_map(|(input, output)| Some([interface.output_position(output, &[])?, interface.input_position(input, &[])?].map(|position| WireEnd { position, vertical: false })))
.collect();
let start = Instant::now();
for _ in 0..REPETITIONS {
for (output, input) in &endpoints {
std::hint::black_box(crate::messages::portfolio::document::utility_types::wires::build_vector_wire(
*output,
*input,
false,
false,
GraphWireStyle::default(),
));
for ends in &endpoints {
std::hint::black_box(route(*ends, WireStyle::default()));
}
}
let paths = start.elapsed() / REPETITIONS;
let built: Vec<_> = endpoints
.iter()
.map(|(output, input)| crate::messages::portfolio::document::utility_types::wires::build_vector_wire(*output, *input, false, false, GraphWireStyle::default()))
.collect();
let built: Vec<_> = endpoints.iter().map(|ends| route(*ends, WireStyle::default())).collect();
let start = Instant::now();
for _ in 0..REPETITIONS {
for path in &built {
@@ -2,13 +2,13 @@ use crate::messages::prelude::*;
use graph_craft::document::NodeId;
use std::collections::{HashMap, HashSet};
/// The layers the frontend shows in view, as rows of the Layers panel and as nodes in the node graph, which are the only ones it's sent the thumbnails of.
/// The latest thumbnail of every layer waits here for whenever the layer comes into view.
/// The layers in view in the Layers panel and the node graph, which the graph runtime renders thumbnails for.
/// The latest thumbnail of each waits here, and goes to the frontend while its layer has a row in view in the Layers panel.
#[derive(Debug, Clone, Default)]
pub struct LayersInView {
/// The layers with a row in view in the Layers panel, which is also sent their details.
layers_panel: HashSet<NodeId>,
/// The nodes in view in the node graph while it's open.
/// The layers in view in the node graph while it's open.
node_graph: HashSet<NodeId>,
/// The message with the latest thumbnail of each layer, as rendered by the graph runtime.
thumbnails: HashMap<NodeId, FrontendMessage>,
@@ -29,27 +29,26 @@ impl LayersInView {
/// Sets the layers with a row in view in the Layers panel, sending the thumbnails it lacks for them.
pub fn set_layers_panel(&mut self, layers: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
self.layers_panel = layers;
self.send_thumbnails_in_view(responses);
self.send_thumbnails_in_layers_panel(responses);
responses.add(PortfolioMessage::SubmitThumbnailsInView);
}
/// Sets the nodes in view in the node graph, sending the thumbnails it lacks for those that are layers.
/// Sets the nodes in view in the node graph, which draws the thumbnails of those that are layers itself.
pub fn set_node_graph(&mut self, nodes: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
self.node_graph = nodes;
self.send_thumbnails_in_view(responses);
responses.add(PortfolioMessage::SubmitThumbnailsInView);
}
pub fn thumbnail_layer(message: &FrontendMessage) -> Option<NodeId> {
match message {
FrontendMessage::UpdateNodeThumbnailCanvases { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id),
FrontendMessage::UpdateNodeThumbnailCanvas { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id),
_ => None,
}
}
/// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view.
/// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view in the Layers panel.
pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: FrontendMessage, responses: &mut VecDeque<Message>) {
if self.in_view(&layer) {
if self.layers_panel.contains(&layer) {
responses.add(thumbnail.clone());
self.thumbnails_sent.insert(layer);
} else {
@@ -79,13 +78,8 @@ impl LayersInView {
}
}
fn in_view(&self, layer: &NodeId) -> bool {
self.layers_panel.contains(layer) || self.node_graph.contains(layer)
}
// O(layers in view)
fn send_thumbnails_in_view(&mut self, responses: &mut VecDeque<Message>) {
for &layer in self.layers_panel.iter().chain(&self.node_graph) {
fn send_thumbnails_in_layers_panel(&mut self, responses: &mut VecDeque<Message>) {
for &layer in &self.layers_panel {
if self.thumbnails_sent.contains(&layer) {
continue;
}
@@ -136,7 +130,7 @@ mod tests {
assert_eq!(thumbnails_sent(responses), vec![(layer, "latest".to_string())], "coming into view, only the latest thumbnail is sent");
let mut responses = VecDeque::new();
layers_in_view.set_node_graph(HashSet::from([layer]), &mut responses);
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
assert!(thumbnails_sent(responses).is_empty(), "a thumbnail the frontend already has isn't sent again");
}
@@ -6,4 +6,3 @@ pub mod network_interface;
pub mod nodes;
pub mod text_metrics;
pub mod transformation;
pub mod wires;
@@ -9,12 +9,12 @@ pub(crate) use catalog::shipped_node_id;
pub(crate) use derived_ids::derived_node_id;
#[cfg(test)]
mod characterization_tests;
mod connectors;
mod derived_ids;
mod deserialization;
pub mod editor_delta;
#[cfg(test)]
mod editor_delta_tests;
mod frontend;
mod geometry;
mod hit_tests;
mod invalidation;
@@ -22,7 +22,6 @@ mod layout;
mod layout_pass;
mod memo_network;
mod mutations;
mod node_parts;
mod queries;
mod reconcile;
mod resolved_types;
@@ -36,8 +35,8 @@ mod validation;
mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use graph_ui::geometry::{Part, PartTarget};
pub use layout_pass::NetworkLayout;
pub use node_parts::{Part, PartTarget};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
@@ -50,21 +49,22 @@ use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelati
use super::misc::PTZ;
use super::nodes::SelectedNodes;
use crate::consts::{
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, HALF_GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH,
STACK_VERTICAL_GAP,
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, STACK_VERTICAL_GAP,
};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::node_graph::utility_types::{InputTooltip, OutputTooltip};
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
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;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, LiftedNetwork, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graph_ui::geometry::is_thick_wire;
use graph_ui::router::route;
use graph_ui::wire::WireStyle;
use graphene_std::Appearance;
use graphene_std::math::quad::Quad;
use graphene_std::registry::MULTI_OUTPUT_NODES;
@@ -73,7 +73,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;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::ops::Deref;
@@ -478,8 +478,8 @@ mod network_interface_tests {
let mut interface = NodeNetworkInterface::from_trees(network, network_metadata);
assert_eq!(interface.validate_invariants(), Vec::<String>::new());
interface.set_import_export_name("Shared".into(), ImportOrExport::Import(0), &[NodeId(10)]);
interface.set_import_export_name("Result".into(), ImportOrExport::Export(0), &[NodeId(10)]);
interface.set_import_export_name("Shared".into(), NetworkConnectorKey::Import(0), &[NodeId(10)]);
interface.set_import_export_name("Result".into(), NetworkConnectorKey::Export(0), &[NodeId(10)]);
let view = interface.view(&[]).unwrap();
assert_eq!(view.persistent_input_metadata(&NodeId(11), 0).unwrap().input_name, "Shared");
@@ -74,20 +74,6 @@ impl NodeNetworkInterface {
}
}
pub fn glide_offsets(&self, network_path: &[NodeId]) -> GlideOffsets {
self.network_metadata(network_path)
.map(|network_metadata| network_metadata.transient_metadata.glide_offsets.borrow().clone())
.unwrap_or_default()
}
pub fn set_glide_offsets(&self, glide_offsets: GlideOffsets, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in set_glide_offsets");
return;
};
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
}
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
@@ -279,10 +265,6 @@ impl NodeNetworkInterface {
}
}
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
}
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in layer_width");
@@ -312,29 +294,6 @@ impl NodeNetworkInterface {
}
}
pub fn get_input_center(&self, input: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
self.input_position(input, network_path)
}
pub fn get_output_center(&self, output: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
self.output_position(output, network_path)
}
/// The wire into the input as the frontend draws it, with its ends following anything drawn gliding into place.
pub fn wire_update_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let wire = self.wire_path_from_input(input, graph_wire_style, false, glide_offsets, network_path)?;
let (id, input_index) = match input {
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
};
Some(WirePathUpdate {
id,
input_index,
wire_path_update: Some(wire),
})
}
pub fn all_input_connectors(&self, network_path: &[NodeId]) -> Vec<InputConnector> {
let mut input_connectors = Vec::new();
let Some(network) = self.nested_network(network_path) else {
@@ -359,119 +318,24 @@ impl NodeNetworkInterface {
.collect()
}
/// Maps to the frontend representation of a wire start. Includes disconnected value wire inputs.
pub fn node_graph_wire_inputs(&self, network_path: &[NodeId]) -> Vec<(NodeId, usize)> {
self.node_graph_input_connectors(network_path)
.iter()
.map(|input| match input {
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
})
.chain(std::iter::once((NodeId(u64::MAX), u32::MAX as usize)))
.collect()
}
/// The dashed wire from the previewed node to the export, drawn alongside the export's own wire.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
if self.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in preview: {input:?}");
return None;
};
let input_position = input_position + glide_offsets.input(&input);
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
return None;
};
let output_position = output_position + glide_offsets.output(&upstream_output);
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
let output_type = self.output_type(&upstream_output, network_path);
let data_type = output_type.displayed_type();
let is_list = output_type.is_list();
let wire_path_update = Some(WirePath {
path_string,
data_type,
thick,
dashed: true,
is_list,
center_path_string,
});
Some(WirePathUpdate {
id: NodeId(u64::MAX),
input_index: u32::MAX as usize,
wire_path_update,
})
}
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
self.gliding_vector_wire_from_input(input, wire_style, &GlideOffsets::default(), network_path)
}
/// Like [`Self::vector_wire_from_input`], but with its ends following anything drawn gliding into place.
pub(crate) fn gliding_vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
let Some(input_position) = self.get_input_center(input, network_path) else {
/// Returns the wire subpath and whether the wire should be thick, or None if nothing feeds the input.
pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: WireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> {
let Some(to) = self.input_end(input, network_path) else {
log::error!("Could not get dom rect for wire end: {input:?}");
return None;
};
let input_position = input_position + glide_offsets.input(input);
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
return Some((BezPath::new(), BezPath::new(), false));
};
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
let upstream_output = self.upstream_output_connector(input, network_path)?;
let Some(from) = self.output_end(&upstream_output, network_path) else {
log::error!("Could not get output port for wire start: {upstream_output:?}");
return None;
};
let output_position = output_position + glide_offsets.output(&upstream_output);
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
Some((vector_wire, center_line, thick))
}
pub fn wire_path_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePath> {
let (vector_wire, center_line, thick) = self.gliding_vector_wire_from_input(input, graph_wire_style, glide_offsets, network_path)?;
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
let (data_type, is_list) = self
.upstream_output_connector(input, network_path)
.map(|output| {
let output_type = self.output_type(&output, network_path);
(output_type.displayed_type(), output_type.is_list())
})
.unwrap_or((FrontendGraphDataType::General, false));
Some(WirePath {
path_string,
data_type,
thick,
dashed,
is_list,
center_path_string,
})
Some((route([from, to], wire_style), is_thick_wire([from, to])))
}
/// The node's body, ports, and handles, built where it is drawn now.
/// The box around the node's body where it sits in its grid cell, in node graph space.
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
let body = self.with_layout(network_path, |layout| layout.geometry(node_id)).flatten()?.body();
Some([body.min, body.max])
}
}
@@ -1,5 +1,5 @@
use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
ChainInsertionPoint, FlowType, InputConnector, LayerClickTargetTypes, NetworkConnectorKey, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
};
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
@@ -7,10 +7,10 @@ use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::test_utils::test_prelude::*;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeInput};
use graph_ui::wire::WireStyle;
use graphene_std::uuid::NodeId;
fn assert_invariants(editor: &EditorTestUtils, context: &str) {
@@ -1190,12 +1190,7 @@ async fn a_stack_closes_up_over_a_deleted_layer_and_a_nudge_moves_the_rest_one_r
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third] }).await;
let network_interface = &editor.active_document().network_interface;
let before = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
editor
.handle_message(NodeGraphMessage::ShiftSelectedNodes {
direction: Direction::Down,
glide: false,
})
.await;
editor.handle_message(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down }).await;
let network_interface = &editor.active_document().network_interface;
let after = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
assert_eq!(after.y - before.y, 1, "A single nudge should move the layer exactly one unit");
@@ -1452,13 +1447,13 @@ async fn editing_import_and_export_descriptions_stores_them_on_the_subgraph_node
editor
.handle_message(NodeGraphMessage::SetImportExportDescription {
description: "The artwork to add.".to_string(),
index: ImportOrExport::Import(1),
index: NetworkConnectorKey::Import(1),
})
.await;
editor
.handle_message(NodeGraphMessage::SetImportExportDescription {
description: "The combined result.".to_string(),
index: ImportOrExport::Export(0),
index: NetworkConnectorKey::Export(0),
})
.await;
@@ -2442,14 +2437,14 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() {
// Level with the wire between the other two
network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]);
assert_eq!(
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]),
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]),
Some((dragged, 0, InputConnector::node_at_index(consumer, 0))),
"the wire it overlaps is the one a drop would insert it onto"
);
network_interface.set_absolute_position(&dragged, IVec2::new(8, 10), &[]);
assert_eq!(
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]),
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]),
None,
"clear of every wire it previews nothing"
);
@@ -2457,7 +2452,7 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() {
// With a node already taking its output, a drop would not insert it
network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(source, 0), NodeInput::node(dragged, 0), &[]);
assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), None);
assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]), None);
}
fn passthrough_definition() -> DefinitionIdentifier {
@@ -2613,7 +2608,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_vec2::IDENTIFIER), 10, 0)
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::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;
@@ -2864,7 +2859,7 @@ async fn double_click_in_graph(editor: &mut EditorTestUtils, point: DVec2, secon
fn wire_middle(network_interface: &NodeNetworkInterface, input: InputConnector) -> DVec2 {
use kurbo::ParamCurveArclen;
let (wire, _, _) = network_interface.vector_wire_from_input(&input, GraphWireStyle::Direct, &[]).expect("the wire should have a path");
let (wire, _) = network_interface.vector_wire_from_input(&input, WireStyle::Direct, &[]).expect("the wire should have a path");
let longest_segment = wire
.segments()
.max_by(|a, b| a.arclen(kurbo::DEFAULT_ACCURACY).total_cmp(&b.arclen(kurbo::DEFAULT_ACCURACY)))
@@ -3399,6 +3394,63 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
);
}
#[tokio::test]
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
let graph_pan = |editor: &EditorTestUtils| {
editor
.active_document()
.network_interface
.network_metadata(&[])
.unwrap()
.persistent_metadata
.navigation_metadata
.node_graph_ptz
.pan
};
let layer_in_viewport = |editor: &EditorTestUtils| {
let network_interface = &editor.active_document().network_interface;
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
(0..=(max.x - min.x) as i32)
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
.expect("the layer should be pressable")
};
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
editor_position: position,
mouse_keys,
..Default::default()
};
// Pressed and released with a wobble too small to count as a drag
let start = layer_in_viewport(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
// Dragged away and back before the release
let start = layer_in_viewport(&editor);
let pan_before = graph_pan(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
editor.handle_message(DocumentMessage::Undo).await;
assert!(is_visible(&editor), "one undo should revert the middle click");
}
#[tokio::test]
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
let mut editor = EditorTestUtils::create();
@@ -3654,96 +3706,18 @@ fn a_wire_is_found_near_its_path_but_not_away_from_it() {
let input = InputConnector::node_at_index(consumer, 0);
let on_wire = wire_middle(&network_interface, input);
assert_eq!(network_interface.wire_input_from_point(on_wire, 6., GraphWireStyle::Direct, &[]), Some(input));
assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., GraphWireStyle::Direct, &[]), None);
}
#[tokio::test]
async fn a_dragged_layer_keeps_its_wires_where_it_is_drawn_in_the_frame_it_moves() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, ..) = layer_with_chain(&mut editor).await;
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let left_input = InputConnector::layer_secondary_input(layer);
let network_interface = &editor.active_document().network_interface;
let wire_before = network_interface.wire_path_from_input(&left_input, GraphWireStyle::default(), false, &GlideOffsets::default(), &[]);
let bounds = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let press = DVec2::new(bounds[1].x - 30., (bounds[0].y + bounds[1].y) / 2.);
let node_graph_to_viewport = network_interface
.network_metadata(&[])
.expect("the network should have metadata")
.persistent_metadata
.navigation_metadata
.node_graph_to_viewport;
let pressed = node_graph_to_viewport.transform_point2(press);
editor.move_mouse(pressed.x, pressed.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor
.handle_message(NodeGraphMessage::PointerDown {
shift_click: false,
control_click: false,
alt_click: false,
right_click: false,
})
.await;
// One grid cell right, through the input preprocessor so the frontend messages of the move itself are returned
let moved = node_graph_to_viewport.transform_point2(press + DVec2::new(GRID_SIZE as f64, 0.));
let editor_mouse_state = EditorPointerState {
editor_position: moved,
mouse_keys: MouseKeys::LEFT,
..Default::default()
};
let messages = editor
.handle_message(InputPreprocessorMessage::PointerMove {
editor_mouse_state,
modifier_keys: ModifierKeys::empty(),
})
.await;
// Still drawn a whole cell back as it starts gliding, so the last wire sent to its left input is the one from before the move
let last_wire_sent = messages
.into_iter()
.filter_map(|message| match message {
FrontendMessage::UpdateNodeGraphWires { wires } => Some(wires),
_ => None,
})
.flatten()
.rfind(|wire| wire.id == layer && wire.input_index == 1)
.and_then(|wire| wire.wire_path_update);
assert_eq!(last_wire_sent.map(|wire| wire.path_string), wire_before.map(|wire| wire.path_string));
}
/// Nudges the only node of a new document while its graph is open, so the node starts gliding into the cell it moved to.
async fn gliding_nudged_node(editor: &mut EditorTestUtils) -> NodeId {
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await;
assert!(
!editor.active_document().network_interface.glide_offsets(&[]).is_empty(),
"the nudged node should be gliding: fixture is wrong"
);
node
}
#[tokio::test]
async fn redoing_a_nudge_undone_while_it_glides_leaves_nothing_gliding() {
let mut editor = EditorTestUtils::create();
gliding_nudged_node(&mut editor).await;
editor.handle_message(DocumentMessage::Undo).await;
editor.handle_message(DocumentMessage::Redo).await;
assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty());
assert_eq!(network_interface.wire_input_from_point(on_wire, 6., WireStyle::Direct, &[]), Some(input));
assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., WireStyle::Direct, &[]), None);
}
#[tokio::test]
async fn undoing_a_nudge_keeps_the_node_it_moved() {
let mut editor = EditorTestUtils::create();
let node = gliding_nudged_node(&mut editor).await;
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await;
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.position(&node, &[]), Some(IVec2::ZERO));
@@ -3765,17 +3739,6 @@ async fn undoing_right_after_creating_a_node_removes_only_that_node() {
assert_eq!(nodes.keys().copied().collect::<Vec<_>>(), vec![kept]);
}
#[tokio::test]
async fn entering_a_node_while_its_network_glides_settles_it() {
let mut editor = EditorTestUtils::create();
gliding_nudged_node(&mut editor).await;
let merge = editor.create_node_by_name_at(merge_definition(), 20, 0).await;
editor.enter_editable_network(merge).await;
assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty());
}
#[tokio::test]
async fn resting_a_wire_on_an_exposed_input_reveals_nothing_that_would_move_it_from_under_the_pointer() {
let mut editor = EditorTestUtils::create();
@@ -1,56 +1,20 @@
//! The shapes the node graph frontend is sent: one entry per visible port, carrying its type, its
//! name and whether it's connected. Read-only projections of the graph, rather than a source of truth.
//! The connectors the graph UI's rows and tooltips are built from: one entry per visible port, carrying its type,
//! its name and whether it's connected. Read-only projections of the graph, rather than a source of truth.
use super::resolved_types::TypeSource;
use super::*;
impl NodeNetworkInterface {
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
return Vec::new();
};
let mut frontend_imports = (0..node.inputs.len())
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected = self.upstream_output_connector(input_connector, network_path).is_some();
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => (self.displayed_export_name(*export_index, network_path), self.export_description(*export_index, network_path)),
/// Returns None if there is an error, it is a hidden primary export, or a hidden or missing input
pub fn input_tooltip(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<InputTooltip> {
let (name, input_type, connected) = self.graph_ui_input(input_connector, network_path)?;
let description = match input_connector {
InputConnector::Node { node_id, input_index } => self
.persistent_input_metadata(node_id, *input_index, network_path)
.map(|metadata| metadata.input_description.clone())
.unwrap_or_default(),
InputConnector::Export(export_index) => self.export_description(*export_index, network_path),
};
let valid_types = match input_connector {
InputConnector::Node { .. } => self.potential_valid_input_types(input_connector, network_path),
// An export takes any type itself, so it's limited only by what its subgraph node's output feeds, or at the document's root, what can be rendered
@@ -60,22 +24,47 @@ impl NodeNetworkInterface {
.filter(|valid_type| !valid_type.nested_type().is_generic())
.collect(),
};
let valid_types = distinct_type_names(&valid_types);
Some(FrontendGraphInput {
data_type,
resolved_type,
Some(InputTooltip {
resolved_type: input_type.resolved_type_node_string(),
name,
description,
valid_types,
valid_types: distinct_type_names(&valid_types),
connected,
})
}
/// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
pub fn output_tooltip(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<OutputTooltip> {
let (name, output_type, connected) = self.graph_ui_output(output_connector, network_path)?;
let description = match output_connector {
OutputConnector::Node { node_id, output_index } => self.output_description(node_id, *output_index, network_path),
OutputConnector::Import(import_index) => self.import_description(*import_index, network_path),
};
Some(OutputTooltip {
resolved_type: output_type.resolved_type_node_string(),
name,
description,
possible_types: distinct_type_names(&self.possible_output_types(output_connector, network_path)),
connected,
})
}
pub fn graph_ui_input(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> {
// Return None if it is a hidden or missing input
if !self.input_from_connector(input_connector, network_path).is_some_and(|input| input.is_exposed()) {
return None;
}
let name = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path).0,
InputConnector::Export(export_index) => self.displayed_export_name(*export_index, network_path),
};
let connected = self.upstream_output_connector(input_connector, network_path).is_some();
Some((name, self.input_type(input_connector, network_path), connected))
}
pub fn graph_ui_output(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> {
let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector {
let name = match output_connector {
OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
@@ -85,8 +74,7 @@ impl NodeNetworkInterface {
let output_names = self.view(network_path).ok()?.output_names(node_id).ok()?;
let output_name = output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
(output_name, self.output_description(node_id, *output_index, network_path))
if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() }
}
OutputConnector::Import(import_index) => {
// Return None if it is an import in the document network
@@ -98,24 +86,13 @@ impl NodeNetworkInterface {
return None;
};
(self.displayed_import_name(*import_index, network_path), self.import_description(*import_index, network_path))
self.displayed_import_name(*import_index, network_path)
}
};
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let possible_types = distinct_type_names(&self.possible_output_types(output_connector, network_path));
let connected = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).is_some_and(|inputs| !inputs.is_empty()))
.unwrap_or_default();
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
possible_types,
connected,
})
Some((name, output_type, connected))
}
/// Returns the input name to display in the Inspector. If the input has no name then its type is used.
@@ -4,56 +4,13 @@
//! the caller decides whether to cache the result.
use super::*;
use graph_ui::label_width;
use graph_ui::metrics::{LAYER_GRIP_WIDTH, LAYER_NAME_LEFT};
use graph_ui::network_connector::{NetworkConnectorKind, network_connector_name_box, network_connector_row_offset};
impl NodeNetworkInterface {
pub(super) fn node_input_anchor(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> Option<DVec2> {
let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64;
let grid = GRID_SIZE as f64;
let inputs = &self.document_node(node_id, network_path)?.inputs;
if self.is_redirect_dot(node_id, network_path) {
return (input_index == 0).then_some(top_left + DVec2::new(0., grid));
}
if self.is_layer(node_id, network_path) {
return match input_index {
0 => Some(top_left + DVec2::new(2. * grid, 2. * grid + 8.)),
1 if inputs.iter().filter(|input| input.is_exposed()).count() > 1 => Some(top_left + DVec2::new(0., grid)),
_ => None,
};
}
if !inputs.get(input_index)?.is_exposed() {
return None;
}
let row = inputs.iter().take(input_index).enumerate().filter(|(index, input)| *index == 0 || input.is_exposed()).count();
Some(top_left + DVec2::new(0., grid * (row as f64 + 1.)))
}
pub(super) fn node_output_anchor(&self, node_id: &NodeId, output_index: usize, network_path: &[NodeId]) -> Option<DVec2> {
let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64;
let grid = GRID_SIZE as f64;
if self.is_redirect_dot(node_id, network_path) {
return (output_index == 0).then_some(top_left + DVec2::new(0., grid));
}
if self.is_layer(node_id, network_path) {
return (output_index == 0).then_some(top_left + DVec2::new(2. * grid, -8.));
}
let hidden = output_index == 0 && self.hidden_primary_output(node_id, network_path);
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
}
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
/// Laid out as the frontend draws them, just past the connector.
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
// How far past the port's center the name begins
const IMPORT_NAME_INSET: f64 = 8.;
const EXPORT_NAME_INSET: f64 = 9.;
const FONT_SIZE: f64 = 14.;
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(NetworkConnectorKey, [DVec2; 2])> {
if network_path.is_empty() {
return Vec::new();
}
@@ -72,16 +29,13 @@ impl NodeNetworkInterface {
return Vec::new();
};
let half_row = DVec2::new(0., HALF_GRID_SIZE as f64);
let imports = import_centers.into_iter().map(|(import_index, center)| {
let name_width = text_width(&self.displayed_import_name(import_index, network_path), FONT_SIZE);
let name_right = center - DVec2::new(IMPORT_NAME_INSET, 0.);
(ImportOrExport::Import(import_index), [name_right - DVec2::new(name_width, 0.) - half_row, name_right + half_row])
let name_width = label_width(&self.displayed_import_name(import_index, network_path));
(NetworkConnectorKey::Import(import_index), network_connector_name_box(NetworkConnectorKind::Import, center, name_width))
});
let exports = export_centers.into_iter().map(|(export_index, center)| {
let name_width = text_width(&self.displayed_export_name(export_index, network_path), FONT_SIZE);
let name_left = center + DVec2::new(EXPORT_NAME_INSET, 0.);
(ImportOrExport::Export(export_index), [name_left - half_row, name_left + DVec2::new(name_width, 0.) + half_row])
let name_width = label_width(&self.displayed_export_name(export_index, network_path));
(NetworkConnectorKey::Export(export_index), network_connector_name_box(NetworkConnectorKind::Export, center, name_width))
});
imports.chain(exports).collect()
}
@@ -98,13 +52,13 @@ impl NodeNetworkInterface {
if !network_path.is_empty() {
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
for import_index in import_start_index..self.number_of_imports(network_path) {
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_export_row_offset(import_index)));
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., network_connector_row_offset(import_index)));
}
}
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
for export_index in export_start_index..network.exports.len() {
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., import_export_row_offset(export_index)));
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., network_connector_row_offset(export_index)));
}
Some(import_export_ports)
@@ -133,7 +87,7 @@ impl NodeNetworkInterface {
connectors.push((0, first_row_center));
}
let next_index = count.max(1);
connectors.push((next_index, first_row_center + DVec2::new(0., import_export_row_offset(next_index) + GRID_SIZE as f64)));
connectors.push((next_index, first_row_center + DVec2::new(0., network_connector_row_offset(next_index) + GRID_SIZE as f64)));
connectors
}
@@ -149,26 +103,21 @@ impl NodeNetworkInterface {
if y < first_row_center + GRID_SIZE as f64 {
return Some(0);
}
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
Some((1..row_count).find(|&row| first_row_center + network_connector_row_offset(row) > y).unwrap_or(row_count))
}
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
/// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
let thumbnail_width = 3. * GRID_SIZE as f64;
let layer_text = self.display_name(node_id, network_path);
let text_width = text_width(&layer_text, FONT_SIZE);
let text_width = label_width(&layer_text);
let grip_padding = 4.;
let grip_width = 8.;
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
let layer_width_pixels = LAYER_NAME_LEFT + text_width + grip_padding + LAYER_GRIP_WIDTH + lock_icon_width + icon_overhang_width;
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
@@ -258,9 +207,3 @@ impl NodeNetworkInterface {
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
}
}
/// How far below the first import or export the one at `index` sits, with a grid cell of space separating the primary from the secondary ones.
fn import_export_row_offset(index: usize) -> f64 {
let rows = if index == 0 { 0 } else { index + 1 };
(rows * GRID_SIZE as usize) as f64
}
@@ -1,4 +1,5 @@
use super::*;
use graph_ui::geometry::WireEnd;
use graphene_std::vector::misc::dvec2_to_point;
use kurbo::{DEFAULT_ACCURACY, ParamCurveNearest};
@@ -51,13 +52,10 @@ impl NodeNetworkInterface {
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
/// grid cell, and an input by its index rather than the row a node draws it in.
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
self.with_layout(network_path, |layout| {
layout.find_part(node_id, |target| {
layout.find_part(node_id, |geometry, target| {
let part = match target.part {
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
Part::Input(place) => Part::Input(geometry.input_at(place)? as u32),
part => part,
};
find(part, target)
@@ -74,13 +72,11 @@ impl NodeNetworkInterface {
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
// Each node is pressed where it's drawn, even while gliding into its grid cell
let glide_offsets = self.glide_offsets(network_path);
let reaching = self.nodes_reaching(point, network_path);
let clicked_nodes = self.with_layout(network_path, |layout| {
reaching
.into_iter()
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
.filter(|node_id| layout.geometry(node_id).is_some_and(|geometry| geometry.body().contains(point)))
.collect::<Vec<_>>()
})?;
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
@@ -103,7 +99,6 @@ impl NodeNetworkInterface {
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
let wanted = match click_target_type {
LayerClickTargetTypes::Visibility => Part::Visibility,
@@ -113,7 +108,6 @@ impl NodeNetworkInterface {
};
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
.is_some()
})
@@ -121,28 +115,18 @@ impl NodeNetworkInterface {
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
pub fn empty_import_export_connector_at(&self, point: DVec2, is_import: bool, network_path: &[NodeId]) -> Option<(usize, DVec2)> {
let glide_offsets = self.glide_offsets(network_path);
let point = point - if is_import { glide_offsets.imports } else { glide_offsets.exports };
// The same reach as an import (output) or export (input) port's click target
self.empty_import_export_connectors(is_import, network_path)
.into_iter()
.find(|(_, center)| port_click_target(side_port_bounds(*center, !is_import)).intersect_point_no_stroke(point))
self.empty_import_export_connectors(is_import, network_path).into_iter().find(|(index, center)| match is_import {
true => PartTarget::output_port(*center, *index as u32).contains(point),
false => PartTarget::input_port(*center, *index as u32).contains(point),
})
}
/// The import or export with its name under `point`, given in node graph space.
pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<ImportOrExport> {
let glide_offsets = self.glide_offsets(network_path);
pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<NetworkConnectorKey> {
self.import_export_name_bounds(network_path)
.into_iter()
.find(|(import_or_export, [name_min, name_max])| {
let point = point
- match import_or_export {
ImportOrExport::Import(_) => glide_offsets.imports,
ImportOrExport::Export(_) => glide_offsets.exports,
};
name_min.cmple(point).all() && point.cmple(*name_max).all()
})
.find(|(_, [name_min, name_max])| name_min.cmple(point).all() && point.cmple(*name_max).all())
.map(|(import_or_export, _)| import_or_export)
}
@@ -170,14 +154,13 @@ impl NodeNetworkInterface {
}
/// The input fed by a wire passing within `tolerance` of the point (in node graph space), for placing a dot on it. Only wires a dot can bend are found.
pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<InputConnector> {
pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: WireStyle, network_path: &[NodeId]) -> Option<InputConnector> {
let target = dvec2_to_point(point);
let glide_offsets = self.glide_offsets(network_path);
self.node_graph_input_connectors(network_path)
.into_iter()
.filter(|input| self.can_bend_wire_into(input, network_path))
.filter_map(|input| {
let (wire, _, _) = self.gliding_vector_wire_from_input(&input, wire_style, &glide_offsets, network_path)?;
let (wire, _) = self.vector_wire_from_input(&input, wire_style, network_path)?;
let distance = wire
.segments()
.map(|segment| segment.nearest(target, DEFAULT_ACCURACY).distance_sq.sqrt())
@@ -196,13 +179,11 @@ impl NodeNetworkInterface {
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
let covering_dot = self.redirect_dot_from_click(click, network_path);
self.nodes_reaching(point, network_path)
.iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| match part {
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
_ => None,
@@ -210,11 +191,9 @@ impl NodeNetworkInterface {
})
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
.or_else(|| {
self.with_import_export_ports(network_path, |import_export_ports| {
import_export_ports.clicked_input_port_from_point(point - glide_offsets.exports).map(InputConnector::Export)
})
.flatten()
.filter(|_| covering_dot.is_none())
self.with_import_export_ports(network_path, |import_export_ports| import_export_ports.clicked_input_port_from_point(point).map(InputConnector::Export))
.flatten()
.filter(|_| covering_dot.is_none())
})
}
@@ -226,14 +205,12 @@ impl NodeNetworkInterface {
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
// A redirect dot is drawn above everything else, so where it covers other ports, only its own can be pressed
let covering_dot = self.redirect_dot_from_click(click, network_path);
self.nodes_reaching(point, network_path)
.iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| match part {
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
_ => None,
@@ -242,7 +219,7 @@ impl NodeNetworkInterface {
.next()
.or_else(|| {
self.with_import_export_ports(network_path, |import_export_ports| {
import_export_ports.clicked_output_port_from_point(point - glide_offsets.imports).map(OutputConnector::Import)
import_export_ports.clicked_output_port_from_point(point).map(OutputConnector::Import)
})
.flatten()
.filter(|_| covering_dot.is_none())
@@ -250,20 +227,30 @@ impl NodeNetworkInterface {
}
pub fn input_position(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
match input_connector {
InputConnector::Node { node_id, input_index } => self.node_input_anchor(node_id, *input_index, network_path),
InputConnector::Export(export_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
.flatten(),
}
Some(self.input_end(input_connector, network_path)?.position)
}
pub fn output_position(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
Some(self.output_end(output_connector, network_path)?.position)
}
pub fn input_end(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<WireEnd> {
match input_connector {
InputConnector::Node { node_id, input_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.input_end(*input_index)).flatten(),
InputConnector::Export(export_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
.flatten()
.map(|position| WireEnd { position, vertical: false }),
}
}
pub fn output_end(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<WireEnd> {
match output_connector {
OutputConnector::Node { node_id, output_index } => self.node_output_anchor(node_id, *output_index, network_path),
OutputConnector::Node { node_id, output_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.output_end(*output_index)).flatten(),
OutputConnector::Import(import_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.output_port_position(*import_index))
.flatten(),
.flatten()
.map(|position| WireEnd { position, vertical: false }),
}
}
@@ -323,49 +310,10 @@ impl NodeNetworkInterface {
Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box())
}
pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap<NodeId, u32>, HashMap<NodeId, u32>, HashMap<NodeId, bool>) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in collect_layer_widths");
return (HashMap::new(), HashMap::new(), HashMap::new());
};
let nodes = network_metadata
.persistent_metadata
.node_metadata
.keys()
.filter_map(|node_id| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None })
.collect::<Vec<_>>();
let layer_widths = nodes
.iter()
.filter_map(|node_id| self.layer_width(node_id, network_path).map(|layer_width| (*node_id, layer_width)))
.collect::<HashMap<NodeId, u32>>();
let chain_widths = nodes.iter().map(|node_id| (*node_id, self.chain_width(node_id, network_path))).collect::<HashMap<NodeId, u32>>();
let has_left_input_wire = nodes
.iter()
.map(|node_id| {
(
*node_id,
!self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
.skip(1)
.all(|node_id| self.is_chain(&node_id, network_path)),
)
})
.collect::<HashMap<NodeId, bool>>();
(layer_widths, chain_widths, has_left_input_wire)
pub fn has_left_input_wire(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
!self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
.skip(1)
.all(|node_id| self.is_chain(&node_id, network_path))
}
}
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
let mut current_row = 0;
for (index, input) in inputs.iter().enumerate() {
if input.is_exposed() && current_row == row {
return Some(index);
}
if index == 0 || input.is_exposed() {
current_row += 1;
}
}
None
}
@@ -1,7 +1,8 @@
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
use super::*;
use glam::UVec2;
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
use graph_ui::geometry::{NodeGeometry, NodeShape};
use graph_ui::metrics::CARD_GRID_WIDTH;
use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -90,11 +91,6 @@ impl NetworkLayout {
.sum()
}
/// How many nodes the layer's chain holds.
pub fn chain_length(&self, layer: &NodeId) -> u32 {
self.node(layer).map_or(0, |node| node.chain_length)
}
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
pub fn bounds(&self) -> [DVec2; 2] {
self.bounds
@@ -105,18 +101,17 @@ impl NetworkLayout {
self.clearance
}
/// The node's body where it sits in its grid cell, in node graph space.
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
Some(self.placed(*self.indices.get(node_id)?).body())
pub fn geometry(&self, node_id: &NodeId) -> Option<NodeGeometry> {
Some(self.geometry_at(*self.indices.get(node_id)?))
}
/// The first of the node's parts, its body last, that `find` picks something from.
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
let placed = self.placed(*self.indices.get(node_id)?);
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&NodeGeometry, &PartTarget) -> Option<R>) -> Option<R> {
let geometry = self.geometry(node_id)?;
let mut found = None;
placed.parts(|target| {
geometry.parts(|target| {
if found.is_none() {
found = find(&target);
found = find(&geometry, &target);
}
});
found
@@ -131,13 +126,13 @@ impl NetworkLayout {
point.cmpge(min).all() && point.cmplt(max).all()
}
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
let node_layout = self.layout.node(index);
PlacedNode {
node: &self.graph[index],
shape: &self.shapes[index.index()],
position: node_layout.position,
chain_length: node_layout.chain_length,
fn geometry_at(&self, index: NodeIndex) -> NodeGeometry {
let node = self.layout.node(index);
NodeGeometry {
cell: node.position,
kind: self.graph[index].kind,
chain_length: node.chain_length,
shape: self.shapes[index.index()].clone(),
}
}
@@ -148,7 +143,7 @@ impl NetworkLayout {
let mut bounds: Option<[DVec2; 2]> = None;
let mut clearance = ImportExportClearance::default();
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
let body = self.placed(index).body();
let body = self.geometry_at(index).body();
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
if self.graph[index].kind == NodeKind::Waypoint {
@@ -220,11 +215,8 @@ impl NodeNetworkInterface {
}
pub(crate) fn nodes_reaching(&self, point: DVec2, network_path: &[NodeId]) -> Vec<NodeId> {
let glide_offsets = self.glide_offsets(network_path);
self.with_layout(network_path, |layout| {
layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point - glide_offsets.node(node_id))).copied().collect()
})
.unwrap_or_default()
self.with_layout(network_path, |layout| layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point)).copied().collect())
.unwrap_or_default()
}
pub(crate) fn drag_preview(&self, network_path: &[NodeId]) -> (IVec2, bool) {
@@ -260,6 +252,10 @@ impl NodeNetworkInterface {
transient.layout.unload();
}
pub(crate) fn dragging(&self, network_path: &[NodeId]) -> bool {
self.network_metadata(network_path).is_some_and(|network_metadata| network_metadata.transient_metadata.drag.is_some())
}
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
pub fn shift_selected_nodes(&mut self, offset: IVec2, keep_upstream: bool, network_path: &[NodeId]) {
self.cancel_drag(network_path);
@@ -420,11 +416,12 @@ impl NodeNetworkInterface {
};
let (kind, size) = match (is_layer, is_redirect_dot) {
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
(false, true) => (NodeKind::Waypoint, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))),
};
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
let node = Node {
placement,
kind,
@@ -433,9 +430,9 @@ impl NodeNetworkInterface {
held: false,
};
let shape = NodeShape {
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
size,
exposed_inputs: inputs.iter().enumerate().filter(|(_, input)| input.is_exposed()).map(|(index, _)| index).collect(),
outputs: self.number_of_outputs(node_id, network_path) as u32,
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
primary_output_hidden,
name_width,
locked: self.is_locked(node_id, network_path),
@@ -444,7 +441,6 @@ impl NodeNetworkInterface {
}
}
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
pub(crate) struct LaidOutNodes {
pub(crate) node_ids: Vec<NodeId>,
pub(crate) indices: HashMap<NodeId, NodeIndex>,
@@ -827,10 +827,10 @@ impl NodeNetworkInterface {
/// Wires the output into the inputs through one new redirect dot placed midway between them, which fans out to the inputs.
fn create_wires_through_dot(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) {
let output_center = self.get_output_center(output_connector, network_path);
let output_center = self.output_position(output_connector, network_path);
let input_centers = input_connectors
.iter()
.map(|input_connector| self.get_input_center(input_connector, network_path))
.map(|input_connector| self.input_position(input_connector, network_path))
.collect::<Option<Vec<_>>>();
let center = match output_center.zip(input_centers) {
Some((output_center, input_centers)) => {
@@ -1164,7 +1164,7 @@ impl NodeNetworkInterface {
self.invalidate_node_appearance(node_id, network_path);
}
pub fn set_import_export_name(&mut self, name: String, index: ImportOrExport, network_path: &[NodeId]) {
pub fn set_import_export_name(&mut self, name: String, index: NetworkConnectorKey, network_path: &[NodeId]) {
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
log::error!("Could not get encapsulating network in set_import_export_name");
return;
@@ -1176,8 +1176,8 @@ impl NodeNetworkInterface {
};
let name_changed = match index {
ImportOrExport::Import(import_index) => node.set_input_name(import_index, name),
ImportOrExport::Export(export_index) => node.set_output_name(export_index, name),
NetworkConnectorKey::Import(import_index) => node.set_input_name(import_index, name),
NetworkConnectorKey::Export(export_index) => node.set_output_name(export_index, name),
};
if name_changed {
@@ -1185,7 +1185,7 @@ impl NodeNetworkInterface {
}
}
pub fn set_import_export_description(&mut self, description: String, index: ImportOrExport, network_path: &[NodeId]) {
pub fn set_import_export_description(&mut self, description: String, index: NetworkConnectorKey, network_path: &[NodeId]) {
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
log::error!("Could not get encapsulating network in set_import_export_description");
return;
@@ -1197,8 +1197,8 @@ impl NodeNetworkInterface {
};
let description_changed = match index {
ImportOrExport::Import(import_index) => node.set_input_description(import_index, description),
ImportOrExport::Export(export_index) => node.set_output_description(export_index, description),
NetworkConnectorKey::Import(import_index) => node.set_input_description(import_index, description),
NetworkConnectorKey::Export(export_index) => node.set_output_description(export_index, description),
};
if description_changed {
@@ -1,231 +0,0 @@
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
use glam::{DVec2, IVec2};
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
const GRID: f64 = GRID_SIZE as f64;
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
const SIDE_PORT_INWARD_REACH: f64 = 8.;
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
const GRIP_WIDTH: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
/// What a node draws beyond the size the layout gives it.
#[derive(Clone, Copy, Debug, Default)]
pub struct NodeShape {
/// How many inputs have a port, which doesn't count a hidden primary input.
pub inputs: u32,
pub outputs: u32,
/// Whether a node's primary input has no port, though its row is still drawn.
pub primary_input_hidden: bool,
pub primary_output_hidden: bool,
/// The width of a layer's name in pixels.
pub name_width: f64,
pub locked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
/// A rounded rectangle of a node that reacts to the pointer.
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
/// A port on the left side of a node, reaching further out than over the node.
fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Input(input),
}
}
/// A port on the right side of a node, reaching further out than over the node.
fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Output(output),
}
}
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
/// Whether `point` is inside the rounded rectangle.
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
#[derive(Clone, Copy, Debug)]
pub struct PlacedNode<'a> {
pub node: &'a Node,
pub shape: &'a NodeShape,
pub position: IVec2,
pub chain_length: u32,
}
impl PlacedNode<'_> {
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
pub fn body(&self) -> PartTarget {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
match self.node.kind {
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: top_left - DVec2::new(self.chain_width(), 0.),
max: top_left + size,
corner_radius: 10.,
part: Part::Body,
},
NodeKind::Node => {
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
PartTarget {
min: body_top_left,
max: body_top_left + size - DVec2::new(0., GRID),
corner_radius: 3.,
part: Part::Body,
}
}
}
}
/// Calls `visit` with each part, the body last.
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.node.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.top_left() + DVec2::new(0., GRID);
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let width = self.node.size.x as f64 * GRID;
let row_center = |row: u32| GRID * (row as f64 + 1.);
let first_input_row = u32::from(self.shape.primary_input_hidden);
for row in first_input_row..first_input_row + self.shape.inputs {
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
}
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
}
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
let icon_half_size = DVec2::splat(HALF_GRID);
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
if self.shape.locked {
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
}
let icons_width = if self.shape.locked { GRID } else { 0. };
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
let handle_top = top_left.y + HALF_GRID;
let handle_bottom = top_left.y + GRID + HALF_GRID;
visit(PartTarget {
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
max: DVec2::new(grip_right, handle_bottom),
corner_radius: 0.,
part: Part::Grip,
});
let name_left = top_left.x + NAME_LEFT_OFFSET;
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, handle_top),
max: DVec2::new(name_right, handle_bottom),
corner_radius: 3.,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.position.as_dvec2() * GRID
}
fn has_side_input(&self) -> bool {
self.shape.inputs > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
}
}
@@ -1,6 +1,9 @@
use super::*;
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> {
@@ -261,16 +264,6 @@ impl NodeNetworkInterface {
layers
}
/// The width in grid cells of a layer's chain area: one cell plus a chain width per chained node, or zero for a layer without a displayed chain input.
pub fn chain_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
if self.number_of_displayed_inputs(node_id, network_path) <= 1 {
return 0;
}
let chain_length = self.with_layout(network_path, |layout| layout.chain_length(node_id)).unwrap_or_default();
chain_length * NODE_CHAIN_WIDTH as u32 + 1
}
/// Check if the specified node id is connected to the output
pub fn connected_to_output(&self, target_node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "connected_to_output", |view| Ok(view.connected_to_output(target_node_id))).unwrap_or_default()
@@ -826,27 +819,17 @@ 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 node (named with a leading `_`), which is never exposed to the graph.
/// Whether the input is internal state of its proto 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 {
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
}
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro 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 Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
return false;
};
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
(field.name == input_name).then(|| field.clone())
node_metadata
.get(proto_node_identifier)
.and_then(|metadata| metadata.fields.get(index))
.is_some_and(|field| field.internal)
}
/// 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.
@@ -1086,7 +1069,7 @@ impl NodeNetworkInterface {
/// Whether the artboard layer clips the content inside it to its bounds.
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
self.document_node(&artboard.to_node(), &[])
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
}
@@ -116,12 +116,7 @@ impl Iterator for FlowIter<'_> {
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ImportOrExport {
Import(usize),
Export(usize),
}
pub use graph_ui::network_connector::NetworkConnectorKey;
/// The primary input (index 0) of any node: a chain node's horizontal wire continuing from the left, or a layer's vertical stack wire from the sibling rendered below it.
pub const PRIMARY_INPUT_INDEX: usize = 0;
@@ -265,29 +260,10 @@ pub(crate) enum DotSide {
Outgoing,
}
/// The corners of the click target for a connector on a node or layer's left or right side, or an import or export.
/// It fills its row's height and reaches further away from the node than into it, leaving the node body grabbable.
pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
const INWARD_REACH: f64 = 8.;
const OUTWARD_REACH: f64 = 12.;
const HALF_HEIGHT: f64 = 12.;
// Inputs face left and outputs face right
let (left_reach, right_reach) = if is_input { (OUTWARD_REACH, INWARD_REACH) } else { (INWARD_REACH, OUTWARD_REACH) };
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
}
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
const CORNER_RADIUS: f64 = 4.;
let path = rounded_rectangle_path(corner1, corner2, [CORNER_RADIUS; 4]);
ClickTarget::new_with_path(path, 0.)
}
#[derive(Debug, Clone)]
pub struct Ports {
pub(crate) input_ports: Vec<(usize, ClickTarget)>,
pub(crate) output_ports: Vec<(usize, ClickTarget)>,
pub(crate) input_ports: Vec<(usize, PartTarget)>,
pub(crate) output_ports: Vec<(usize, PartTarget)>,
/// Where a wire attaches to an input port with a click target not centered on that point.
pub(crate) input_anchors: Vec<(usize, DVec2)>,
/// Where a wire attaches to an output port with a click target not centered on that point.
@@ -310,30 +286,30 @@ impl Ports {
}
}
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, PartTarget)> {
self.input_ports.iter()
}
pub fn output_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
pub fn output_ports(&self) -> impl Iterator<Item = &(usize, PartTarget)> {
self.output_ports.iter()
}
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
self.input_ports.push((input_index, PartTarget::input_port(center, input_index as u32)));
self.input_anchors.push((input_index, center));
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
self.output_ports.push((output_index, PartTarget::output_port(center, output_index as u32)));
self.output_anchors.push((output_index, center));
}
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
self.input_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port))
}
pub fn clicked_output_port_from_point(&self, point: DVec2) -> Option<usize> {
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
self.output_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port))
}
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
@@ -663,57 +639,6 @@ pub struct NodeNetworkTransientMetadata {
pub(crate) drag: Option<super::layout_pass::DragPreview>,
/// The import and export connector click targets, with the generation of the layout they were placed by.
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
}
/// How far the nodes, imports, and exports gliding into the grid cells they just moved to are drawn from those cells, in node graph space.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GlideOffsets {
pub nodes: HashMap<NodeId, DVec2>,
pub imports: DVec2,
pub exports: DVec2,
}
impl GlideOffsets {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.imports == DVec2::ZERO && self.exports == DVec2::ZERO
}
pub fn node(&self, node_id: &NodeId) -> DVec2 {
self.nodes.get(node_id).copied().unwrap_or_default()
}
pub fn input(&self, input: &InputConnector) -> DVec2 {
match input {
InputConnector::Node { node_id, .. } => self.node(node_id),
InputConnector::Export(_) => self.exports,
}
}
pub fn output(&self, output: &OutputConnector) -> DVec2 {
match output {
OutputConnector::Node { node_id, .. } => self.node(node_id),
OutputConnector::Import(_) => self.imports,
}
}
/// Shrinks every offset to the given fraction of itself, settling those left too small to see.
pub fn shrink(&mut self, remaining_fraction: f64) {
const SMALLEST_VISIBLE_OFFSET: f64 = 0.5;
let shrink = |offset: &mut DVec2| {
*offset *= remaining_fraction;
if offset.length() < SMALLEST_VISIBLE_OFFSET {
*offset = DVec2::ZERO;
}
};
self.nodes.values_mut().for_each(shrink);
self.nodes.retain(|_, offset| *offset != DVec2::ZERO);
shrink(&mut self.imports);
shrink(&mut self.exports);
}
}
/// What the imports and exports keep their distance from horizontally, in node graph space. They keep a few grid cells from the sides of a node,
@@ -773,11 +698,51 @@ 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),
}
@@ -814,6 +779,40 @@ 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);
}
@@ -472,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 `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.
// 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.
NodeReplacement {
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
aliases: &[
"graphene_math_nodes::Vec2ValueNode",
"graphene_core::ops::ConstructVector2",
@@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
aliases: &["math_nodes::CombineVec2Node"],
},
// ================================
@@ -1576,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::vec2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
];
for (old_reference, new_identifier) in split_wrapper_replacements {
@@ -1641,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::vec2_to_numbers::IDENTIFIER, "Extract XY"))
Some((*node_id, path, graphene_std::math_nodes::vec_2_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 {
@@ -2931,8 +2931,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::vec2_value::IDENTIFIER) && inputs_count == 3 {
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
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);
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);
@@ -5230,11 +5230,7 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network 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");
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).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, &[]);
@@ -5251,7 +5247,7 @@ mod tests {
panic!("Blend should stay a network node")
};
assert_eq!(
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
);
}
@@ -5268,11 +5264,7 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network 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");
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).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, &[]);
@@ -5282,7 +5274,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, edited_subtract_id);
let edited_subtract = derived_node_id(*definition, NodeId(5));
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
}
@@ -5364,15 +5356,8 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Regex Find should be a network node")
};
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);
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);
document.network_interface.insert_node(node_id, node_template, &[]);
migrate(&mut document);
@@ -5386,9 +5371,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", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
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", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::Integer(0))
);
}
@@ -1,3 +1,4 @@
use super::document::node_graph::graph_ui::GraphUiPart;
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::history::HistoryMessage;
use super::persistent_state::PersistentStateMessage;
@@ -157,11 +158,6 @@ pub enum PortfolioMessage {
artboard_name: Option<String>,
artboard_count: usize,
},
RenderOverlays {
#[serde(skip, default = "OverlayContext::default")]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
context: OverlayContext,
},
SubmitActiveGraphRender,
SubmitGraphRender {
document_id: DocumentId,
@@ -175,6 +171,14 @@ pub enum PortfolioMessage {
SubmitInspectContextOverrides {
overrides: graphene_std::ContextOverrides,
},
UpdateGraphUi {
part: GraphUiPart,
},
RenderOverlays {
#[serde(skip, default = "OverlayContext::default")]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
context: OverlayContext,
},
PollNodeGraphEvaluation,
ToggleResetNodesToDefinitionsOnOpen,
ToggleRulers,
@@ -14,6 +14,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions;
use crate::messages::portfolio::document::node_graph::graph_ui;
use crate::messages::portfolio::document_storage_io::{
DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file,
remove_stored_document,
@@ -216,7 +217,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Send the information for tooltips and categories for each node/input.
responses.add(FrontendMessage::SendUIMetadata {
node_descriptions: document_node_definitions::collect_node_descriptions(),
node_icons: document_node_definitions::collect_node_icons(),
node_types: document_node_definitions::collect_node_types(),
});
@@ -898,18 +898,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// The document we are leaving won't get the pointer up that ends a wire drag in its graph, so abort the drag there before switching
if self.active_document_id != Some(document_id)
&& let Some(document) = self.active_document_mut()
&& document.end_node_graph_wire_in_progress(responses)
{
responses.add(DocumentMessage::AbortTransaction);
responses.add(PortfolioMessage::SelectDocument { document_id });
return;
}
// The document we are leaving won't get the frames that settle what glides in its graph, so it settles at once
if self.active_document_id != Some(document_id)
&& let Some(document) = self.active_document_mut()
{
document.node_graph_handler.stop_gliding(&document.network_interface, responses);
document.node_graph_handler.graph_ui.stop_animations(responses);
let wire_ended = document.end_node_graph_wire_in_progress(responses);
if wire_ended {
responses.add(DocumentMessage::AbortTransaction);
}
let network_path = document.selection_network_path().to_vec();
if wire_ended || document.node_graph_handler.abort_node_drag(&mut document.network_interface, &network_path, responses) {
responses.add(PortfolioMessage::SelectDocument { document_id });
return;
}
}
// Auto-save the document we are leaving
@@ -958,8 +957,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(DocumentMessage::GraphViewOverlay { open: node_graph_open });
if node_graph_open {
responses.add(NodeGraphMessage::UpdateGraphBarRight);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires)
} else {
responses.add(PortfolioMessage::UpdateDocumentWidgets);
}
@@ -997,7 +994,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
artboard_name,
artboard_count,
};
let result = self.executor.submit_document_export(document, document_id, export_config);
let result = self.executor.submit_document_export(document, export_config);
if let Err(description) = result {
responses.add(DialogMessage::DisplayDialogError {
@@ -1012,6 +1009,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
#[cfg(not(target_family = "wasm"))]
responses.add(FrontendMessage::WakeNodeRuntime);
}
PortfolioMessage::UpdateGraphUi { part } => {
let Some(document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else {
return;
};
let edited = graph_ui::edited_name(document);
document.node_graph_handler.graph_ui.update_name_field(edited, responses);
let builder = graph_ui::GraphUiSceneBuilder::of(document);
if self.executor.update_graph_ui(|scene| builder.update(part, scene)) {
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
}
PortfolioMessage::SubmitActiveGraphRender => {
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false });
@@ -1025,9 +1033,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
// 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() {
let graph_ui_config = graph_ui::config(document, preferences.graph_wire_style);
if graph_ui_config.is_none() && document.resources.awaiting_resources() {
return;
}
@@ -1051,12 +1058,20 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// TODO: See #3796.
#[cfg(not(target_family = "wasm"))]
responses.add_front(FrontendMessage::UpdateViewportHolePunch {
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview,
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview || graph_ui_config.is_some(),
});
let result = self
.executor
.submit_node_graph_evaluation(document, document_id, physical_resolution, scale, timing_information, node_to_inspect, ignore_hash, pointer_position);
let result = self.executor.submit_node_graph_evaluation(
document,
document_id,
physical_resolution,
scale,
timing_information,
node_to_inspect,
ignore_hash,
pointer_position,
graph_ui_config,
);
match result {
Err(description) => {
@@ -1124,18 +1139,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
}
PortfolioMessage::SubmitClipboardSvg { id } => {
let layers = self.active_document().map(|document| {
let selected = document.partition_selection().layers;
let mut layers = document
.metadata()
.all_layers()
.filter(|layer| selected.contains(layer))
.map(|layer| layer.to_node())
.collect::<Vec<_>>();
layers.reverse();
layers
});
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
responses.add(ClipboardMessage::Rendered { id, svg: None });
return;
};
let selected = document.partition_selection().layers;
let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
layers.reverse();
responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
@@ -1,6 +1,6 @@
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use graph_ui::wire::WireStyle;
#[impl_message(Message, Preferences)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -22,7 +22,7 @@ pub enum PreferencesMessage {
zoom_with_scroll: bool,
},
GraphWireStyle {
style: GraphWireStyle,
style: WireStyle,
},
ViewportZoomWheelRate {
rate: f64,
@@ -1,9 +1,9 @@
use crate::consts::{UI_SCALE_DEFAULT, VIEWPORT_ZOOM_WHEEL_RATE};
use crate::messages::input_mapper::key_mapping::MappingVariant;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::tool::utility_types::ToolType;
use graph_ui::wire::WireStyle;
#[derive(ExtractField)]
pub struct PreferencesMessageContext<'a> {
@@ -17,7 +17,7 @@ pub struct PreferencesMessageHandler {
pub selection_mode: SelectionMode,
pub zoom_with_scroll: bool,
pub brush_tool: bool,
pub graph_wire_style: GraphWireStyle,
pub graph_wire_style: WireStyle,
pub viewport_zoom_wheel_rate: f64,
pub ui_scale: f64,
pub disable_ui_acceleration: bool,
@@ -51,7 +51,7 @@ impl Default for PreferencesMessageHandler {
selection_mode: SelectionMode::Touched,
zoom_with_scroll: matches!(MappingVariant::default(), MappingVariant::ZoomWithScroll),
brush_tool: false,
graph_wire_style: GraphWireStyle::default(),
graph_wire_style: WireStyle::default(),
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT,
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
@@ -126,8 +126,7 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
}
PreferencesMessage::GraphWireStyle { style } => {
self.graph_wire_style = style;
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
PreferencesMessage::ViewportZoomWheelRate { rate } => {
self.viewport_zoom_wheel_rate = rate;
@@ -175,6 +175,8 @@ pub struct SnapSession {
gesture: Option<Gesture>,
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
awake: Vec<Awake>,
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
woken_in_gesture: Vec<Awake>,
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
position_sources: HashMap<u64, Vec<LayerId>>,
rest: Option<Rest>,
@@ -495,13 +497,17 @@ impl SnapSession {
landed
}
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
pub fn end_gesture(&mut self) {
self.gesture = None;
self.constructions = None;
self.rest = None;
self.crossings.clear();
self.forget();
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
self.awake.retain(|target| !woken_in_gesture.contains(target));
self.forget_targets_gone_to_sleep();
}
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
@@ -545,11 +551,14 @@ impl SnapSession {
if let Awake::Position { id, .. } = target {
self.position_sources.insert(id, sources.clone());
}
if self.gesture.is_some() {
self.woken_in_gesture.push(target);
}
self.awake.push(target);
}
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
self.awake.drain(..over_the_limit);
self.forget_sources_of_sleeping_positions();
self.forget_targets_gone_to_sleep();
self.constructions = None;
true
@@ -563,6 +572,7 @@ impl SnapSession {
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
pub fn sleep_all(&mut self) {
self.awake.clear();
self.woken_in_gesture.clear();
self.position_sources.clear();
self.constructions = None;
@@ -583,10 +593,12 @@ impl SnapSession {
.collect()
}
fn forget_sources_of_sleeping_positions(&mut self) {
/// Lets go of what is kept about woken targets that have since gone back to sleep.
fn forget_targets_gone_to_sleep(&mut self) {
let awake = &self.awake;
self.position_sources
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
self.woken_in_gesture.retain(|target| awake.contains(target));
}
/// The woken targets, oldest first.
@@ -721,7 +733,7 @@ impl SnapSession {
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
});
self.forget_sources_of_sleeping_positions();
self.forget_targets_gone_to_sleep();
}
}
@@ -1100,6 +1112,45 @@ mod tests {
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
}
#[tokio::test]
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(100., 100., 300., 240.).await;
editor.draw_rect(500., 100., 700., 240.).await;
let mut session = SnapSession::default();
let input = InputPreprocessorMessageHandler::default();
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
for (index, position) in along_edges.into_iter().enumerate() {
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
}
assert_eq!(session.woken_in_gesture, session.awake);
}
#[tokio::test]
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(100., 100., 300., 240.).await;
let mut session = SnapSession::default();
// The top edge is woken before the gesture, and the right edge during it
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
let woken_before = session.awake.clone();
let input = InputPreprocessorMessageHandler::default();
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
assert_eq!(session.awake.len(), 2);
session.end_gesture();
assert_eq!(session.awake, woken_before);
}
#[tokio::test]
async fn only_the_latest_few_woken_targets_stay_awake() {
let mut editor = EditorTestUtils::create();
+251 -145
View File
@@ -1,23 +1,30 @@
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::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::list;
use graph_craft::proto::GraphErrors;
use graph_ui::GraphUiConfig;
use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit};
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List};
use graphene_std::math::quad::Quad;
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, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
use std::any::Any;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
@@ -27,10 +34,11 @@ mod recompile_tests;
mod runtime;
pub use runtime::*;
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub struct ExecutionRequest {
execution_id: u64,
render_config: RenderConfig,
graph_ui_config: Option<GraphUiConfig>,
}
pub struct ExecutionResponse {
@@ -97,7 +105,8 @@ impl std::fmt::Display for EvaluationErrors {
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CompilationResponse {
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>,
result: Result<(), String>,
resolved_types: ResolvedDocumentNodeTypesDelta,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
}
@@ -112,20 +121,26 @@ pub enum NodeGraphUpdate {
},
/// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg {
Export {
id: u64,
svg: Option<String>,
result: Box<ExecutionResult>,
},
}
#[derive(Debug)]
pub struct NodeGraphExecutor {
sender: Sender<GraphRuntimeRequest>,
receiver: Receiver<NodeGraphUpdate>,
current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>,
pending: Option<(u64, ExecutionContext)>,
current_export_id: u64,
exports: HashMap<u64, ExportTarget>,
node_graph_hash: u64,
graph_ui_scene: GraphUiScene,
/// The document whose network the graph runtime was last sent.
node_graph_document: Option<DocumentId>,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
@@ -146,9 +161,14 @@ pub struct NodeGraphExecutor {
gradient_migration_attempted: HashSet<DocumentId>,
}
#[derive(Debug)]
enum ExportTarget {
File(ExportConfig),
Clipboard(u64),
}
#[derive(Debug, Clone)]
struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId,
/// The view the render was asked for, which the footprints it reports back are measured in.
document_to_viewport: DAffine2,
@@ -183,7 +203,10 @@ impl NodeGraphExecutor {
futures: Default::default(),
pending: None,
current_execution_id: 0,
current_export_id: 0,
exports: HashMap::new(),
node_graph_hash: 0,
graph_ui_scene: GraphUiScene::default(),
node_graph_document: None,
previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(),
@@ -196,21 +219,35 @@ impl NodeGraphExecutor {
(node_executor, node_runtime)
}
/// Forgets which canvas images the frontend holds, for a frontend that started over without them.
pub fn forget_canvas_images(&mut self) {
self.canvas_images_sent.clear();
}
/// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
fn queue_execution(&mut self, render_config: RenderConfig, graph_ui_config: Option<GraphUiConfig>) -> u64 {
let execution_id = self.current_execution_id;
self.current_execution_id += 1;
let request = ExecutionRequest { execution_id, render_config };
let request = ExecutionRequest {
execution_id,
render_config,
graph_ui_config,
};
self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request");
execution_id
}
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
let id = self.current_export_id;
self.current_export_id += 1;
let request = GraphRuntimeRequest::Export {
id,
render_config,
network,
resources,
};
self.sender.send(request).map_err(|e| e.to_string())?;
self.exports.insert(id, target);
Ok(())
}
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
log::error!("Failed to send the overlays: {error}");
@@ -229,13 +266,29 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides");
}
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
if document_id.is_none() || self.node_graph_document != document_id {
return ClipboardMessage::Rendered { id, svg: None }.into();
}
pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
return no_svg;
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
Message::NoOp
let viewport = Footprint {
resolution: (max - min).round().as_uvec2(),
transform: DAffine2::from_translation(-min),
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: 1.,
export_format: ExportFormat::Svg,
for_export: true,
..Default::default()
};
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
Ok(()) => Message::NoOp,
Err(_) => no_svg,
}
}
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -245,8 +298,9 @@ impl NodeGraphExecutor {
}
let layers = document.layers_in_view.all_in_view();
let layers_panel = document.layers_in_view.layers_panel().clone();
self.sender
.send(GraphRuntimeRequest::ThumbnailsInView { layers, document_id })
.send(GraphRuntimeRequest::ThumbnailsInView { layers, layers_panel, document_id })
.expect("Failed to send the thumbnails in view");
}
@@ -260,9 +314,11 @@ impl NodeGraphExecutor {
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();
let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &previewed, &layers);
let thumbnails = thumbnail_sources(&network, &layers);
self.node_graph_hash = graph_hash;
self.node_graph_document = Some(document_id);
@@ -272,8 +328,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed,
layers,
thumbnails,
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
@@ -306,6 +361,7 @@ impl NodeGraphExecutor {
}
/// Adds an evaluate request for whatever current network is cached.
#[allow(clippy::too_many_arguments)]
pub(crate) fn submit_current_node_graph_evaluation(
&mut self,
document: &mut DocumentMessageHandler,
@@ -314,6 +370,7 @@ impl NodeGraphExecutor {
viewport_scale: f64,
time: TimingInformation,
pointer: DVec2,
graph_ui_config: Option<GraphUiConfig>,
) -> Result<Message, String> {
let viewport = Footprint {
transform: document.metadata().document_to_viewport,
@@ -332,12 +389,11 @@ impl NodeGraphExecutor {
};
// Execute the node graph
let execution_id = self.queue_execution(render_config);
let execution_id = self.queue_execution(render_config, graph_ui_config);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
@@ -359,9 +415,10 @@ impl NodeGraphExecutor {
node_to_inspect: Vec<NodeId>,
ignore_hash: bool,
pointer: DVec2,
graph_ui_config: Option<GraphUiConfig>,
) -> Result<Message, String> {
self.update_node_graph(document, document_id, node_to_inspect, ignore_hash)?;
self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer)
self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer, graph_ui_config)
}
#[allow(clippy::too_many_arguments)]
@@ -399,12 +456,11 @@ impl NodeGraphExecutor {
};
// Execute the node graph
let execution_id = self.queue_execution(render_config);
let execution_id = self.queue_execution(render_config, None);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
@@ -415,10 +471,9 @@ impl NodeGraphExecutor {
}
/// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let resources = document.resources.registry.clone();
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
let mut network = document.network_interface.document_network().clone();
prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg
@@ -452,34 +507,12 @@ impl NodeGraphExecutor {
time: Default::default(),
pointer: DVec2::ZERO,
export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true,
for_eyedropper: false,
};
// Execute the node graph
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: Some(export_config),
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
},
));
Ok(())
self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
}
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
@@ -491,8 +524,8 @@ impl NodeGraphExecutor {
}
let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
for response in results.by_ref() {
let results = self.receiver.try_iter().collect::<Vec<_>>();
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse {
@@ -516,7 +549,7 @@ impl NodeGraphExecutor {
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
if execution_context.measure_fill.is_none() {
self.pending = Some((execution_id, execution_context.clone()));
}
execution_context
@@ -539,7 +572,9 @@ impl NodeGraphExecutor {
if let Some(bake_target) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
let measured = observations.remove(&ObservationKey::FillMeasurement);
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Fallback(..))
.then_some(measured)
.flatten();
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
}
continue;
@@ -570,8 +605,8 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw);
// A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
// A pending graph keeps the last frame, and the errors shown with it; a provisional frame keeps the errors
if !matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) {
let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| {
@@ -644,11 +679,8 @@ impl NodeGraphExecutor {
log::error!("Node graph evaluation failed:\n{message}");
}
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
}
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
continue;
}
};
@@ -666,10 +698,8 @@ impl NodeGraphExecutor {
}
document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(None, _) => {}
if let Some(node_graph_output) = node_graph_output {
self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
}
responses.add(DeferMessage::TriggerGraphRun {
execution_id,
@@ -691,49 +721,42 @@ impl NodeGraphExecutor {
node_graph_errors,
node_graph_warnings,
result,
resolved_types,
} = execution_response;
// TODO: Eventually remove this document upgrade code
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
if self.gradient_migration.is_some() {
if let Err((_, e)) = &result {
if let Err(e) = &result {
log::trace!("Gradient migration measurement compile: {e}");
}
continue;
}
let type_delta = match result {
Err((incomplete_delta, e)) => {
// Clear the click targets while the graph is in an un-renderable state
if let Err(e) = &result {
// Clear the click targets while the graph is in an un-renderable state
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_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}");
} else {
log::trace!("{e}");
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: incomplete_delta,
node_graph_errors,
node_graph_warnings,
});
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}");
} else {
log::trace!("{e}");
}
Ok(result) => result,
};
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: type_delta,
resolved_types,
node_graph_errors,
node_graph_warnings,
});
if result.is_err() {
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
}
}
NodeGraphUpdate::EyedropperPreview(raster) => {
let (data, width, height) = raster.to_flat_u8();
@@ -756,33 +779,7 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses);
}
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
}
}
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let execution_context = self.execution_context(execution_response.execution_id);
if execution_context.is_some_and(|context| context.document_id == document_id) {
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
}
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
responses.add(export_failure_dialog(None));
}
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
}
NodeGraphUpdate::Thumbnails {
responses: thumbnails,
document_id: thumbnails_document,
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
_ => {}
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
}
}
@@ -798,15 +795,6 @@ impl NodeGraphExecutor {
}
}
/// What an execution was submitted for, while it's still queued or pending.
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
self.futures
.iter()
.chain(&self.pending)
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
.map(|(_, execution_context)| execution_context)
}
// TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
@@ -841,6 +829,23 @@ impl NodeGraphExecutor {
true
}
pub fn update_graph_ui(&mut self, change: impl FnOnce(&mut GraphUiSceneEdit)) -> bool {
let mut edit = std::mem::take(&mut self.graph_ui_scene).edit();
change(&mut edit);
let (scene, delta) = edit.finish();
self.graph_ui_scene = scene;
let changed = !delta.is_empty();
if changed {
self.sender.send(GraphRuntimeRequest::GraphUi(delta)).expect("Failed to send the graph UI delta");
}
changed
}
pub fn forget_canvas_images(&mut self) {
self.canvas_images_sent.clear();
}
// TODO: Eventually remove this document upgrade code
/// Run the graph with its export chain redirected down to the (possibly nested) Fill at `network_path`/`fill_node_id`
/// (so its branch evaluates even when hidden or orphaned) and that node inspected, so its evaluated geometry returns
@@ -876,6 +881,10 @@ impl NodeGraphExecutor {
return;
}
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone();
let fill_measurement = Observation {
node_path: full_path,
@@ -887,8 +896,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
thumbnails,
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
}))
.is_err()
@@ -916,11 +924,10 @@ impl NodeGraphExecutor {
for_export: false,
for_eyedropper: false,
};
let execution_id = self.queue_execution(render_config);
let execution_id = self.queue_execution(render_config, None);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
document_to_viewport: viewport.transform,
measure_fill: Some((network_path, fill_node_id, gradient)),
@@ -1080,6 +1087,51 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
}
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let Some(target) = self.exports.remove(&export_id) else { return };
let failure = match (result, &target) {
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
return match target {
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
ExportTarget::Clipboard(id) => {
let svg = match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Some(svg),
_ => None,
};
responses.add(ClipboardMessage::Rendered { id, svg });
}
};
}
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
(ExecutionResult::Panic(payload), _) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Some(format!("Panicked: {}", message.unwrap_or("no message")))
}
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
};
if let Some(message) = &failure {
log::error!("Node graph evaluation failed:\n{message}");
}
match target {
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}),
ExportTarget::Clipboard(id) => {
responses.add(ClipboardMessage::Rendered { id, svg: None });
if let Some(description) = failure {
let title = "Unable to copy as SVG".to_string();
responses.add(DialogMessage::DisplayDialogError { title, description });
}
}
}
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let ExportConfig {
file_type,
@@ -1179,6 +1231,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
}
}
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
apply_previews(network, previewed);
write_layer_paths(network, layers);
}
/// Replaces each network's primary export with its previewed node.
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
for (network_path, previewed) in previewed {
let Some(nested) = network.nested_network_mut(network_path) else { continue };
let Some(export) = nested.exports.first_mut() else { continue };
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
}
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
// O(layers * depth)
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
layers.iter().filter_map(source).collect()
}
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
let metadata = interface.document_metadata();
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
artboards if artboards == layers.len() => list!(Artboard),
_ => return None,
};
let mut network = interface.document_network().clone();
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
let mut below = NodeInput::type_default(stack, true);
let mut bounds = None;
for &layer in layers {
let mut node = network.nodes.get(&layer.to_node())?.clone();
*node.inputs.first_mut()? = below;
let copy = NodeId::new();
network.nodes.insert(copy, node);
below = NodeInput::node(copy, 0);
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
true => metadata.downstream_transform_to_document(layer).inverse(),
false => DAffine2::IDENTITY,
};
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
}
network.exports = vec![below];
Some((network, bounds?))
}
// TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
@@ -1200,14 +1307,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None
}
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}
}
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));
@@ -1265,6 +1364,10 @@ mod test {
self.evaluation_errors.take()
}
pub fn graph_ui_scene(&self) -> &GraphUiScene {
&self.graph_ui_scene
}
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache.
@@ -1273,14 +1376,17 @@ mod test {
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network);
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
thumbnails,
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
@@ -11,15 +11,15 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
}
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
/// for one more update, so a first update clears those of the graph before it.
/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
/// an update replaces for one more update, so a first update clears the nodes of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await;
compile_and_run(editor).await;
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::document::NodeId;
use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::gradient::Gradient;
@@ -12,13 +12,12 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::transform::{Footprint, RenderQuality};
use graphene_std::renderer::Render;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::layer_content;
use std::collections::{HashMap, HashSet, VecDeque};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::sync::Arc;
mod atlas;
@@ -41,22 +40,17 @@ pub struct Thumbnails {
sources: HashMap<NodeId, NodeId>,
/// The layers whose content changed since their thumbnail was last rendered.
stale: HashSet<NodeId>,
/// The layers whose thumbnails the frontend shows, the only ones rendered.
in_view: HashSet<NodeId>,
in_layers_panel: HashSet<NodeId>,
stale_in_layers_panel: HashSet<NodeId>,
/// The device pixel ratio thumbnails are rendered at.
scale: f64,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
canvases: HashMap<NodeId, ThumbnailCanvases>,
canvases: HashMap<NodeId, CanvasHandle>,
/// The layers whose thumbnails were sent to a page that can't show the runtime's canvases.
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
sent: HashSet<NodeId>,
}
/// A layer's thumbnail is shown in both the Layers panel and the node graph, but a canvas element can only be in one place.
#[cfg(all(target_family = "wasm", feature = "wasm"))]
struct ThumbnailCanvases {
layers_panel: CanvasHandle,
node_graph: CanvasHandle,
graphics: Arc<BTreeMap<NodeId, Graphic>>,
}
impl Thumbnails {
@@ -64,8 +58,14 @@ impl Thumbnails {
Self { scale: 1., ..Default::default() }
}
pub fn set_in_view(&mut self, layers: HashSet<NodeId>) {
pub fn set_in_view(&mut self, layers: HashSet<NodeId>, layers_panel: HashSet<NodeId>) {
self.stale.extend(self.stale_in_layers_panel.extract_if(|layer| layers_panel.contains(layer)));
self.in_view = layers;
self.in_layers_panel = layers_panel;
}
pub fn graphics(&self) -> Arc<BTreeMap<NodeId, Graphic>> {
self.graphics.clone()
}
/// Whether the layer's thumbnail is waiting to be rendered.
@@ -83,17 +83,15 @@ impl Thumbnails {
}
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
// O(layers * depth)
let sources: HashMap<NodeId, NodeId> = layer_paths
.iter()
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
.collect();
pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
let source_map = executor.tree().source_map();
let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
self.stale.extend(changed.map(|(layer, _)| *layer));
self.stale.retain(|layer| sources.contains_key(layer));
self.stale_in_layers_panel.retain(|layer| sources.contains_key(layer));
self.sources = sources;
}
@@ -115,11 +113,13 @@ impl Thumbnails {
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
self.sent.retain(|layer| keep_sourced(layer));
Arc::make_mut(&mut self.graphics).retain(|layer, _| sources.contains_key(layer));
dropped
}
/// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view.
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) {
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) -> bool {
let mut contents = HashMap::new();
for layer in std::mem::take(&mut self.stale) {
let Some(&source) = self.sources.get(&layer) else { continue };
@@ -136,10 +136,12 @@ impl Thumbnails {
contents.insert(layer, content);
}
if contents.is_empty() {
return;
return false;
}
self.stale_in_layers_panel.extend(contents.keys().filter(|layer| !self.in_layers_panel.contains(layer)));
self.render_with_vello(&contents, editor_api, responses).await;
true
}
/// Renders the thumbnails into atlases with Vello and shows them.
@@ -167,39 +169,55 @@ impl Thumbnails {
}
};
self.show_atlas(&layout, texture, executor, responses).await;
self.keep_cells(&layout, &texture, executor);
let shown: Vec<(usize, NodeId)> = layout.layers.iter().copied().enumerate().filter(|(_, layer)| self.in_layers_panel.contains(layer)).collect();
if !shown.is_empty() {
self.show_atlas(&layout, &shown, texture, executor, responses).await;
}
}
}
/// Reads the atlas back and draws each cell into the canvases the layer's rows show.
/// Copies each layer's cell out of the atlas into a texture of its own for the node graph.
fn keep_cells(&mut self, layout: &ThumbnailAtlasLayout, atlas: &Texture, executor: &wgpu_executor::WgpuExecutor) {
let mut encoder = executor.context().device.create_command_encoder(&Default::default());
for (index, &layer) in layout.layers.iter().enumerate() {
let cell = executor.request_texture(layout.cell_size);
let mut source = atlas.as_image_copy();
let origin = layout.cell_origin(index);
(source.origin.x, source.origin.y) = (origin.x, origin.y);
encoder.copy_texture_to_texture(source, cell.as_image_copy(), cell.size());
Arc::make_mut(&mut self.graphics).insert(layer, Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(cell))));
}
executor.context().queue.submit([encoder.finish()]);
}
/// Reads the atlas back and draws each shown cell into the canvas the layer's row in the Layers panel shows.
#[cfg(all(target_family = "wasm", feature = "wasm"))]
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8();
for (index, &layer) in layout.layers.iter().enumerate() {
for &(index, layer) in shown {
let cell_pixels = layout.cell_pixels(&pixels, index);
let Ok(image) = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&cell_pixels), layout.cell_size.x, layout.cell_size.y) else {
continue;
};
let canvases = self.canvases(layer);
for canvas in [&mut canvases.layers_panel, &mut canvases.node_graph] {
canvas.set_resolution(layout.cell_size);
let _ = canvas.context().put_image_data(&image, 0, 0);
}
let canvas = self.canvas(layer);
canvas.set_resolution(layout.cell_size);
let _ = canvas.context().put_image_data(&image, 0, 0);
responses.push_back(canvases.update_message(layer));
responses.push_back(canvas_message(layer, canvas));
}
}
/// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each layer its cell's pixels.
/// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each shown layer its cell's pixels.
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8();
for (index, &layer) in layout.layers.iter().enumerate() {
for &(index, layer) in shown {
self.sent.insert(layer);
responses.push_back(FrontendMessage::UpdateNodeThumbnailPixels {
id: layer,
@@ -211,23 +229,14 @@ impl Thumbnails {
}
#[cfg(all(target_family = "wasm", feature = "wasm"))]
fn canvases(&mut self, layer: NodeId) -> &mut ThumbnailCanvases {
self.canvases.entry(layer).or_insert_with(|| ThumbnailCanvases {
layers_panel: CanvasHandle::new(),
node_graph: CanvasHandle::new(),
})
fn canvas(&mut self, layer: NodeId) -> &mut CanvasHandle {
self.canvases.entry(layer).or_insert_with(CanvasHandle::new)
}
}
#[cfg(all(target_family = "wasm", feature = "wasm"))]
impl ThumbnailCanvases {
fn update_message(&mut self, layer: NodeId) -> FrontendMessage {
FrontendMessage::UpdateNodeThumbnailCanvases {
id: layer,
layers_panel_canvas_id: self.layers_panel.id(),
node_graph_canvas_id: self.node_graph.id(),
}
}
fn canvas_message(layer: NodeId, canvas: &mut CanvasHandle) -> FrontendMessage {
FrontendMessage::UpdateNodeThumbnailCanvas { id: layer, canvas_id: canvas.id() }
}
enum ThumbnailContent {
@@ -276,11 +285,11 @@ impl ThumbnailContent {
}
}
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
/// The area the content covers once rendered, counting the effects drawn through maps and images.
fn content_bounds(&self) -> RenderBoundingBox {
match self {
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
// The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
@@ -289,7 +298,7 @@ impl ThumbnailContent {
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] {
let bounds = match self.content_bounds(true) {
let bounds = match self.content_bounds() {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE],
};
@@ -297,45 +306,6 @@ impl ThumbnailContent {
}
}
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
let contents: Vec<ThumbnailContent> = layers
.iter()
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
.collect();
let bounds = contents
.iter()
.filter_map(|content| match content.content_bounds(false) {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
_ => None,
})
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
let render_params = RenderParams {
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
for content in &contents {
content.graphic().render_svg(&mut render, &render_params);
}
if render.svg.is_empty() {
return None;
}
render.format_svg(bounds[0], bounds[1]);
Some(render.svg.to_svg_string())
}
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?;
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
/// Converts the other kinds of graphical content into a graphic.
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
macro_rules! downcast_into_graphic {
@@ -398,8 +368,7 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
#[cfg(test)]
mod tests {
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::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
use crate::test_utils::test_prelude::*;
use glam::UVec2;
use graph_craft::document::NodeId;
@@ -412,7 +381,7 @@ mod tests {
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
@@ -430,20 +399,8 @@ 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", extend_id))]);
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
assert_eq!(
editor.runtime.thumbnails.sources.get(&layer).copied(),
+25 -22
View File
@@ -75,7 +75,7 @@ impl EditorTestUtils {
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO, None) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
self.runtime.update();
@@ -90,13 +90,22 @@ impl EditorTestUtils {
return Err(TestGraphError::Evaluation(errors));
}
for message in frontend_messages {
message.check_node_graph_error();
}
self.check_node_graph_errors();
Ok(instrumented)
}
fn check_node_graph_errors(&self) {
let document = self.active_document();
if !document.graph_view_overlay_open {
return;
}
let errors = document.node_graph_handler.node_graph_errors(&document.network_interface, document.breadcrumb_network_path());
if !errors.is_empty() {
panic!("errors: {errors:?}");
}
}
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
const MAX_ITERATIONS: usize = 16;
@@ -283,12 +292,11 @@ impl EditorTestUtils {
/// Sets the clock to a time in milliseconds and runs one animation frame, as the frontend does on each `requestAnimationFrame`.
pub async fn animation_frame(&mut self, timestamp: u64) {
let messages = Box::new([
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
AnimationMessage::IncrementFrameCounter.into(),
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
]);
self.handle_message(Message::Batched { messages }).await;
self.handle_message(animation_frame_batch(timestamp)).await;
}
pub fn dispatch_animation_frame(&mut self, timestamp: u64) {
self.dispatch(animation_frame_batch(timestamp));
}
pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
@@ -447,17 +455,13 @@ impl EditorTestUtils {
}
}
pub trait FrontendMessageTestUtils {
fn check_node_graph_error(&self);
}
impl FrontendMessageTestUtils for FrontendMessage {
fn check_node_graph_error(&self) {
let FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors } = self else { return };
if !errors.is_empty() {
panic!("errors: {errors:?}");
}
}
fn animation_frame_batch(timestamp: u64) -> Message {
let messages = Box::new([
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
AnimationMessage::IncrementFrameCounter.into(),
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
]);
Message::Batched { messages }
}
#[derive(Debug)]
@@ -554,7 +558,6 @@ impl Spawn for BlockingSpawner {
#[cfg(test)]
pub mod test_prelude {
pub use super::FrontendMessageTestUtils;
pub use crate::application::Editor;
pub use crate::float_eq;
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
+2 -16
View File
@@ -680,7 +680,7 @@
{:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
<div class="render-status-outline failed"></div>
{/if}
{#if $document.renderStatus === "Error"}
{#if $document.renderStatus === "Error" && !$document.graphViewOverlayOpen}
<LayoutCol class="render-status-overlay">
<TextLabel>
<p>
@@ -703,7 +703,7 @@
{/if}
</div>
<div class="graph-view" class:open={$document.graphViewOverlayOpen} style:--fade-artwork={`${$document.fadeArtwork}%`} data-graph>
<div class="graph-view" class:open={$document.graphViewOverlayOpen}>
<Graph />
</div>
</LayoutCol>
@@ -1005,7 +1005,6 @@
.graph-view {
pointer-events: none;
transition: opacity 0.2s;
opacity: 0;
&.open {
@@ -1013,21 +1012,8 @@
pointer-events: auto;
opacity: 1;
}
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--color-2-mildblack);
opacity: var(--fade-artwork);
pointer-events: none;
}
}
.fade-artwork,
.graph {
position: absolute;
top: 0;
@@ -2,6 +2,8 @@
import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
import type { DragToggleListener } from "/src/managers/drag-toggle";
import { inspectorLayout } from "/src/stores/portfolio";
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -23,7 +25,15 @@
let lastDragClientY = 0;
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
// Everything one middle-button drag across the section headers paints is one history step
const dragToggleListener: DragToggleListener = {
groups: ["inspector-section-visibility"],
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
};
onMount(() => {
createDragToggleManager(dragToggleListener);
addEventListener("pointermove", draggingPointerMove);
addEventListener("pointerup", draggingPointerUp);
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
@@ -36,6 +46,8 @@
});
onDestroy(() => {
destroyDragToggleManager(dragToggleListener);
removeEventListener("pointermove", draggingPointerMove);
removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointercancel", abortDrag);
+24 -1
View File
@@ -331,6 +331,7 @@
}
const dragToggleListener: DragToggleListener = {
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
activeGroupChanged: (group) => {
activeDragToggleGroup = group;
},
@@ -342,6 +343,15 @@
editor.toggleNodeVisibilityLayerPanel(id);
}
// Middle-clicking one of the chain's node buttons toggles that node's visibility
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
if (e.button !== 1) return;
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
}
function toggleLayerLock(id: bigint) {
editor.toggleLayerLock(id);
}
@@ -1194,6 +1204,7 @@
on:pointerdown={(e) => layerPointerDown(e, listing)}
on:click={(e) => selectLayerWithModifiers(e, listing)}
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
on:pointerenter={() => hoverRow(index)}
on:pointerleave={() => (hoveredRowIndex = undefined)}
>
@@ -1236,7 +1247,7 @@
{/if}
<div class="thumbnail">
{#if $nodeGraph.thumbnailCanvases.has(listing.id)}
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)?.layersPanelCanvasId} />
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)} />
{:else if $thumbnailImages.has(listing.id)}
<ThumbnailImage image={$thumbnailImages.get(listing.id)} />
{/if}
@@ -1343,6 +1354,8 @@
data-chain-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
/>
{/if}
{/if}
@@ -1359,12 +1372,17 @@
: entry.chainExpanded
? "Stop listing this layer's chain one node per row."
: "List this layer's chain one node per row, beneath the layer."}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
on:click={(e) => {
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
if (entry.chainNodes.length === 0) return;
e.stopPropagation();
editor.toggleLayerChainExpanded(listing.id);
}}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
}}
>
<IconLabel
icon={entry.iconName}
@@ -1395,10 +1413,15 @@
data-chain-row-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
on:pointerdown={(e) => {
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
}}
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
}}
on:dblclick={(e) => {
// Only the node's icon opens it in the graph
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
File diff suppressed because it is too large. Load diff
@@ -1,28 +0,0 @@
<script lang="ts">
import type { Readable } from "svelte/store";
import type { WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
export let wire: Readable<WirePath>;
export let thick: boolean;
export let undimmed: boolean;
$: dataColor = `var(--color-data-${$wire.dataType.toLowerCase()})`;
$: dataColorDim = `var(--color-data-${$wire.dataType.toLowerCase()}-dim)`;
$: dasharray = `3,${$wire.dashed ? 2 : 0}`;
</script>
{#if $wire.thick === thick}
<g class:dashed={$wire.dashed} class:undimmed>
{#if thick}
<path d={$wire.pathString} style:--data-line-width="8px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
<path d={$wire.centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={dasharray} />
{:else if $wire.isList}
<!-- A rank-1 List wire reads as two parallel lines: a triple-width data line split down the middle by a 1x background-colored overlay -->
<path d={$wire.pathString} style:--data-line-width="4px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
<path d={$wire.pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={dasharray} />
{:else}
<path d={$wire.pathString} style:--data-line-width="2px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
{/if}
</g>
{/if}
@@ -41,6 +41,12 @@
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
}
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
if (e.button !== 1 || widgetData.disabled) return;
editor.toggleNodeVisibilityInspector(widgetData.id);
}
</script>
<!-- TODO: Implement collapsable sections with the Inspector system -->
@@ -76,7 +82,16 @@
{/if}
{/each}
{:else}
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
<button
class="header"
class:expanded
class:expandable
data-inspector-reorder-handle={reorderable ? "" : undefined}
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
onclick={toggleExpandedWithModifiers}
onauxclick={toggleVisibilityWithMiddleClick}
>
<div
class="icon-slot"
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
@@ -140,7 +140,9 @@
const reorder = allowReorder && allowSelect;
let held = position;
if (!reorder && !allowWrap) {
if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) {
held = holdWithOverlaps(first, last, position);
} else if (!reorder && !allowWrap) {
const lower = neighborBound(first, -1) ?? 0;
const upper = (neighborBound(last, 1) ?? 1) - spacing;
held = Math.max(lower, Math.min(upper, position));
@@ -156,6 +158,33 @@
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
}
// Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them
function holdWithOverlaps(first: number, last: number, position: number): number {
const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last);
const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never");
const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely";
let lower = 0;
let upper = 1;
for (let k = first; k <= last; k += 1) {
const offset = markers[k].position - markers[first].position;
lower = Math.max(lower, -offset);
upper = Math.min(upper, 1 - offset);
// A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it
const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1];
const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1];
lowerBounds.filter(outsideRun).forEach((i) => {
lower = Math.max(lower, markers[i].position - offset);
});
upperBounds.filter(outsideRun).forEach((i) => {
upper = Math.min(upper, markers[i].position - offset);
});
}
return Math.max(lower, Math.min(upper, position));
}
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
function neighborBound(index: number, step: -1 | 1): number | undefined {
for (let i = index + step; i >= 0 && i < markers.length; i += step) {
@@ -657,7 +686,10 @@
}
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext);
// A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter(
({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position,
);
onMount(() => {
document.addEventListener("keydown", deleteShortcut);
+81 -25
View File
@@ -8,21 +8,30 @@
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
//
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
// rather than a click. Their gesture engages on the press, which toggles the source at once.
export type DragToggleListener = {
// The groups whose gestures this listener is told about
groups: string[];
// Given the group of the pressed button, and undefined once the press ends
activeGroupChanged?: (activeGroup: string | undefined) => void;
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
engagedChanged?: (engaged: boolean) => void;
};
const MIDDLE_BUTTON = 1;
const listeners = new Set<DragToggleListener>();
let activeGroup: string | undefined = undefined;
let middleButtonGesture = false;
let source: HTMLElement | undefined = undefined;
let startingState: string | undefined = undefined;
let visited = new WeakSet<Element>();
let engaged = false;
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
let suppressNextAuxClick = false;
export function createDragToggleManager(listener: DragToggleListener) {
listeners.add(listener);
@@ -38,12 +47,13 @@ export function createDragToggleManager(listener: DragToggleListener) {
window.addEventListener("blur", onPointerUp);
// Capture phase on click suppresses the natural source-click before the button's handler runs
window.addEventListener("click", onClickCapture, true);
window.addEventListener("auxclick", onAuxClickCapture, true);
}
}
export function destroyDragToggleManager(listener: DragToggleListener) {
// A consumer leaving mid-gesture still hears it end
if (engaged) listener.engagedChanged?.(false);
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
listeners.delete(listener);
// Uninstall the window event listeners only once the last consumer leaves
@@ -54,83 +64,120 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
window.removeEventListener("pointercancel", onPointerUp);
window.removeEventListener("blur", onPointerUp);
window.removeEventListener("click", onClickCapture, true);
window.removeEventListener("auxclick", onAuxClickCapture, true);
activeGroup = undefined;
middleButtonGesture = false;
source = undefined;
startingState = undefined;
visited = new WeakSet();
engaged = false;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
}
}
function notifyActiveGroupChange(group: string | undefined) {
activeGroup = group;
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
function listenersOfGroup(group: string): DragToggleListener[] {
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
}
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
function notifyActiveGroupChange(group: string | undefined) {
const previousGroup = activeGroup;
activeGroup = group;
const notifiedGroup = group || previousGroup;
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
}
function groupAttribute(middleButton: boolean): string {
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
}
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
if (!(target instanceof Element)) return undefined;
const found = target.closest("[data-drag-toggle-group]");
const found = target.closest(`[${groupAttribute(middleButton)}]`);
return found instanceof HTMLElement ? found : undefined;
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0) return;
suppressNextClickFromSource = undefined;
function memberState(member: HTMLElement): string | undefined {
return member.getAttribute("data-drag-toggle-state") || undefined;
}
const found = findMember(e.target || undefined);
function toggle(member: HTMLElement) {
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
else member.click();
}
function engage() {
if (!activeGroup || !source) return;
engaged = true;
visited.add(source);
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
if (memberState(source) === startingState) toggle(source);
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
const middleButton = e.button === MIDDLE_BUTTON;
const found = findMember(e.target || undefined, middleButton);
if (!found) return;
// Stop the event so sibling drag/select handlers on ancestors don't also engage
e.stopPropagation();
middleButtonGesture = middleButton;
source = found;
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
startingState = memberState(found);
visited = new WeakSet();
engaged = false;
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
if (middleButton) engage();
}
function onPointerMove(e: PointerEvent) {
if (!activeGroup || !source) return;
const member = findMember(e.target || undefined);
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
const member = findMember(e.target || undefined, middleButtonGesture);
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
if (member === source || visited.has(member)) return;
// First crossing engages the drag and toggles the source as part of the operation
if (!engaged) {
engaged = true;
visited.add(source);
listeners.forEach((listener) => listener.engagedChanged?.(true));
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
}
if (!engaged) engage();
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
if (memberState(member) !== startingState) return;
visited.add(member);
member.click();
toggle(member);
}
function onPointerUp(e: Event) {
if (!activeGroup) return;
const endedGroup = activeGroup;
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
// An engaged drag already toggled the source, so its release's click won't toggle it again
if (engaged && source && e.type === "pointerup") {
if (middleButtonGesture) suppressNextAuxClick = true;
else suppressNextClickFromSource = source;
}
const wasEngaged = engaged;
middleButtonGesture = false;
source = undefined;
startingState = undefined;
visited = new WeakSet();
engaged = false;
notifyActiveGroupChange(undefined);
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
}
function onClickCapture(e: Event) {
@@ -141,6 +188,15 @@ function onClickCapture(e: Event) {
suppressNextClickFromSource = undefined;
}
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
function onAuxClickCapture(e: MouseEvent) {
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
suppressNextAuxClick = false;
e.stopPropagation();
e.preventDefault();
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => {
const carried = Array.from(listeners);
-10
View File
@@ -14,7 +14,6 @@ type DocumentStoreState = {
workingColorsLayout: Layout;
nodeGraphControlBarLayout: Layout;
graphViewOverlayOpen: boolean;
fadeArtwork: number;
renderStatus: RenderStatus;
};
const initialState: DocumentStoreState = {
@@ -24,7 +23,6 @@ const initialState: DocumentStoreState = {
workingColorsLayout: createLayout(),
nodeGraphControlBarLayout: createLayout(),
graphViewOverlayOpen: false,
fadeArtwork: 100,
renderStatus: "Rendering",
};
@@ -44,13 +42,6 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) {
subscriptionsRouter = subscriptions;
subscriptions.subscribeFrontendMessage("UpdateGraphFadeArtwork", (data) => {
update((state) => {
state.fadeArtwork = data.percentage;
return state;
});
});
subscriptions.subscribeLayoutUpdate("ToolOptions", (data) => {
patchLayout(get(store).toolOptionsLayout, data);
});
@@ -99,7 +90,6 @@ export function destroyDocumentStore() {
const subscriptions = subscriptionsRouter;
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork");
subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay");
subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus");
subscriptions.unsubscribeFrontendMessage("UpdateRemoteCursors");
+9 -214
View File
@@ -1,59 +1,27 @@
import { get, writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { IconName } from "/src/icons";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageBody } from "/src/subscriptions-router";
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { ContextMenuInformation, FrontendNodeType } from "/wrapper/pkg/graphite_wasm_wrapper";
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
export type NodeGraphTransform = { scale: number; x: number; y: number };
export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId: number };
type NodeGraphStoreState = {
box: BoxSelection | undefined;
contextMenuInformation: ContextMenuInformation | undefined;
errors: NodeGraphErrorDiagnostic[];
layerWidths: Map<bigint, number>;
chainWidths: Map<bigint, number>;
hasLeftInputWire: Map<bigint, boolean>;
nodes: Map<bigint, FrontendNode>;
wirePathInProgress: WirePath | undefined;
wireInProgressDraggedFrom: [number, number] | undefined;
wireInProgressSnappedTo: [number, number] | undefined;
hoveredConnector: [number, number] | undefined;
nodeDescriptions: Map<string, string>;
nodeIcons: Map<string, IconName>;
nodeTypes: FrontendNodeType[];
thumbnailCanvases: Map<bigint, ThumbnailCanvases>;
thumbnailCanvases: Map<bigint, number>;
selected: bigint[];
inSelectedNetwork: boolean;
readOnly: boolean;
reorderImportIndex: number | undefined;
reorderExportIndex: number | undefined;
};
const initialState: NodeGraphStoreState = {
box: undefined,
contextMenuInformation: undefined,
errors: [],
layerWidths: new Map(),
chainWidths: new Map(),
hasLeftInputWire: new Map(),
nodes: new Map(),
wirePathInProgress: undefined,
wireInProgressDraggedFrom: undefined,
wireInProgressSnappedTo: undefined,
hoveredConnector: undefined,
nodeDescriptions: new Map(),
nodeIcons: new Map(),
nodeTypes: [],
thumbnailCanvases: new Map(),
selected: [],
inSelectedNetwork: true,
readOnly: false,
reorderImportIndex: undefined,
reorderExportIndex: undefined,
};
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
@@ -83,36 +51,14 @@ const store: Writable<NodeGraphStoreState> = import.meta.hot?.data?.store || wri
if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store;
// Separate transform store so pan/zoom updates don't trigger re-rendering the entire node graph
// Separate transform store so a pan or zoom re-renders only the menus and fields placed in graph space
const transformStore: Writable<NodeGraphTransform> = import.meta.hot?.data?.transformStore || writable<NodeGraphTransform>({ scale: 1, x: 0, y: 0 });
if (import.meta.hot) import.meta.hot.data.transformStore = transformStore;
// Separate imports/exports store so viewport-anchored position updates don't trigger node re-renders
const importsExportsStore: Writable<MessageBody<"UpdateImportsExports"> | undefined> = import.meta.hot?.data?.importsExportsStore || writable(undefined);
if (import.meta.hot) import.meta.hot.data.importsExportsStore = importsExportsStore;
// Kept apart from the node graph state so a thumbnail update doesn't re-render every node
// Kept apart from the node graph state so a thumbnail update doesn't re-render every row of the Layers panel
const thumbnailImagesStore: Writable<Map<bigint, ImageData>> = import.meta.hot?.data?.thumbnailImagesStore || writable(new Map());
if (import.meta.hot) import.meta.hot.data.thumbnailImagesStore = thumbnailImagesStore;
// Separate visible nodes store so viewport culling changes don't trigger full node re-renders
const visibleNodesStore: Writable<Set<bigint>> = import.meta.hot?.data?.visibleNodesStore || writable(new Set());
if (import.meta.hot) import.meta.hot.data.visibleNodesStore = visibleNodesStore;
// Separate wires store so wire path updates (e.g. export connector movement during pan) don't trigger node re-renders.
// It only changes when wires are added or removed, since each wire's path is kept in its own store so updating it only re-renders that wire.
const wiresStore: Writable<Map<bigint, Map<number, Writable<WirePath>>>> = import.meta.hot?.data?.wiresStore || writable(new Map());
if (import.meta.hot) import.meta.hot.data.wiresStore = wiresStore;
// Separate wire insertion preview store so the wires don't re-render with every node graph update
const wireInsertionPreviewStore: Writable<[bigint, number] | undefined> = import.meta.hot?.data?.wireInsertionPreviewStore || writable(undefined);
if (import.meta.hot) import.meta.hot.data.wireInsertionPreviewStore = wireInsertionPreviewStore;
// Separate glide offsets store so the per-frame offsets of whatever is gliding into the place it moved to don't trigger full node re-renders
export type GlideOffsets = { nodes: Map<bigint, [number, number]>; imports: [number, number]; exports: [number, number] };
const glideOffsetsStore: Writable<GlideOffsets> = import.meta.hot?.data?.glideOffsetsStore || writable<GlideOffsets>({ nodes: new Map(), imports: [0, 0], exports: [0, 0] });
if (import.meta.hot) import.meta.hot.data.glideOffsetsStore = glideOffsetsStore;
export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
destroyNodeGraphStore();
@@ -121,19 +67,11 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
subscriptions.subscribeFrontendMessage("SendUIMetadata", (data) => {
update((state) => {
state.nodeDescriptions = new Map(data.nodeDescriptions);
state.nodeIcons = new Map(data.nodeIcons);
state.nodeTypes = data.nodeTypes;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateBox", (data) => {
update((state) => {
state.box = data.box;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
update((state) => {
state.contextMenuInformation = data.contextMenuInformation;
@@ -141,42 +79,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
});
});
subscriptions.subscribeFrontendMessage("UpdateImportReorderIndex", (data) => {
update((state) => {
state.reorderImportIndex = data.importIndex;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateExportReorderIndex", (data) => {
update((state) => {
state.reorderExportIndex = data.exportIndex;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateWireInsertionPreview", (data) => {
wireInsertionPreviewStore.set(data.wire);
});
subscriptions.subscribeFrontendMessage("UpdateHoveredConnector", (data) => {
update((state) => {
state.hoveredConnector = data.center;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateImportsExports", (data) => {
importsExportsStore.set(data);
});
subscriptions.subscribeFrontendMessage("UpdateInSelectedNetwork", (data) => {
update((state) => {
state.inSelectedNetwork = data.inSelectedNetwork;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateNetworkReadOnly", (data) => {
update((state) => {
state.readOnly = data.readOnly;
@@ -184,86 +86,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
});
});
subscriptions.subscribeFrontendMessage("UpdateLayerWidths", (data) => {
update((state) => {
state.layerWidths = data.layerWidths;
state.chainWidths = data.chainWidths;
state.hasLeftInputWire = data.hasLeftInputWire;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateNodeGraphNodes", (data) => {
update((state) => {
state.nodes.clear();
data.nodes.forEach((node) => {
state.nodes.set(node.id, node);
});
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics", (data) => {
update((state) => {
state.errors = data.errors;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
const newNodes = new Set<bigint>(data.nodes);
// Short-circuit when the visible set hasn't changed to avoid unnecessary re-renders
let changed = false;
const unsubscribe = visibleNodesStore.subscribe((current) => {
if (current.size !== newNodes.size) {
changed = true;
} else {
newNodes.forEach((node) => {
if (!current.has(node)) changed = true;
});
}
});
unsubscribe();
if (!changed) return;
visibleNodesStore.set(newNodes);
});
subscriptions.subscribeFrontendMessage("UpdateGlideOffsets", (data) => {
glideOffsetsStore.set({ nodes: new Map(data.nodes), imports: data.imports, exports: data.exports });
});
subscriptions.subscribeFrontendMessage("UpdateNodeGraphWires", (data) => {
const wires = get(wiresStore);
let wiresChanged = false;
data.wires.forEach(({ id, inputIndex, wirePathUpdate }) => {
let inputMap = wires.get(id);
const wire = inputMap?.get(inputIndex);
if (wirePathUpdate === undefined) {
if (inputMap?.delete(inputIndex)) wiresChanged = true;
} else if (wire) {
wire.set(wirePathUpdate);
} else {
if (!inputMap) {
inputMap = new Map();
wires.set(id, inputMap);
}
inputMap.set(inputIndex, writable(wirePathUpdate));
wiresChanged = true;
}
});
if (wiresChanged) wiresStore.set(wires);
});
subscriptions.subscribeFrontendMessage("ClearAllNodeGraphWires", () => {
wiresStore.set(new Map());
});
subscriptions.subscribeFrontendMessage("UpdateNodeGraphSelection", (data) => {
update((state) => {
state.selected = data.selected;
@@ -275,14 +97,11 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
transformStore.set({ scale: data.scale, x: data.translation[0], y: data.translation[1] });
});
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvases", (data) => {
const { id, ...canvases } = data;
const current = get(store).thumbnailCanvases.get(id);
if (current?.layersPanelCanvasId === canvases.layersPanelCanvasId && current?.nodeGraphCanvasId === canvases.nodeGraphCanvasId) return;
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvas", (data) => {
if (get(store).thumbnailCanvases.get(data.id) === data.canvasId) return;
update((state) => {
state.thumbnailCanvases.set(id, canvases);
state.thumbnailCanvases.set(data.id, data.canvasId);
return state;
});
});
@@ -303,16 +122,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
});
});
subscriptions.subscribeFrontendMessage("UpdateWirePathInProgress", (data) => {
update((state) => {
state.wirePathInProgress = data.wirePath;
state.wireInProgressDraggedFrom = data.draggedFrom;
state.wireInProgressSnappedTo = data.snappedTo;
return state;
});
});
return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore };
return { subscribe, transformStore, thumbnailImagesStore };
}
export function destroyNodeGraphStore() {
@@ -320,28 +130,13 @@ export function destroyNodeGraphStore() {
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
subscriptions.unsubscribeFrontendMessage("UpdateBox");
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
subscriptions.unsubscribeFrontendMessage("UpdateWireInsertionPreview");
subscriptions.unsubscribeFrontendMessage("UpdateHoveredConnector");
subscriptions.unsubscribeFrontendMessage("UpdateImportsExports");
subscriptions.unsubscribeFrontendMessage("UpdateInSelectedNetwork");
subscriptions.unsubscribeFrontendMessage("UpdateNetworkReadOnly");
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
subscriptions.unsubscribeFrontendMessage("ClearAllNodeGraphWires");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphSelection");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphTransform");
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvases");
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvas");
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailPixels");
subscriptions.unsubscribeFrontendMessage("ClearNodeThumbnails");
subscriptions.unsubscribeFrontendMessage("UpdateWirePathInProgress");
}
export function closeContextMenu() {
+22 -7
View File
@@ -29,7 +29,7 @@ type Listener = { eventName: keyof DocumentEventMap; action(event: Event): void;
const tooltipEventListeners: Listener[] = [
{ eventName: "mouseover", action: onMouseOver },
{ eventName: "mousemove", action: onMouseMove },
{ eventName: "mouseleave", action: onMouseLeave },
{ eventName: "mouseleave", action: closeTooltip },
{ eventName: "mousedown", action: closeTooltip },
// Heard on the way down, since a floating menu or a field with its menu open stops these from bubbling up
{ eventName: "keydown", action: closeTooltip, capture: true },
@@ -38,6 +38,7 @@ const tooltipEventListeners: Listener[] = [
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
let tooltipTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
let latestMouseMove: MouseEvent | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<TooltipStoreState> = import.meta.hot?.data?.store || writable<TooltipStoreState>(initialState);
@@ -107,12 +108,29 @@ function onMouseOver(e: MouseEvent) {
// Listen for mouse movements to schedule and position the tooltip, or hide it immediately upon further movement
function onMouseMove(e: MouseEvent) {
latestMouseMove = e;
// Hide the tooltip now that the cursor has moved
update((state) => {
state.visible = false;
return state;
});
scheduleTooltip(e);
}
// For an element whose tooltip changes while the cursor rests on it
export function retargetTooltip(element: Element | undefined) {
update((state) => {
state.visible = false;
state.element = element;
return state;
});
if (latestMouseMove) scheduleTooltip(latestMouseMove);
}
function scheduleTooltip(e: MouseEvent) {
// Before we schedule a new future tooltip appearance, we clear the existing one
if (tooltipTimeout) clearTimeout(tooltipTimeout);
@@ -131,14 +149,11 @@ function onMouseMove(e: MouseEvent) {
}, SHOW_TOOLTIP_DELAY_MS);
}
// Hide tooltip and cancel any pending timeout when the mouse leaves the application window
function onMouseLeave() {
if (tooltipTimeout) clearTimeout(tooltipTimeout);
closeTooltip();
}
// Stop showing a tooltip if the user clicks or presses a key, and require the user to first move out of the element before it can re-appear
function closeTooltip() {
if (tooltipTimeout) clearTimeout(tooltipTimeout);
latestMouseMove = undefined;
update((state) => {
state.visible = false;
state.element = undefined;
+2 -2
View File
@@ -188,9 +188,9 @@ export function onPointerUp(e: PointerEvent, editor: EditorWrapper) {
export function onPotentialDoubleClick(e: MouseEvent, editor: EditorWrapper) {
if (isObserveOnly(e) || textToolInteractiveInputElement || inPointerLock) return;
// Allow only events within the viewport or node graph boundaries
// Allow only events within the viewport or node graph boundaries, but not in a text field laid over them
const isTargetingCanvas = e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
if (!(isTargetingCanvas instanceof Element)) return;
if (!(isTargetingCanvas instanceof Element) || targetIsTextField(e.target || undefined)) return;
// Allow only double-clicks (2, 4, etc.), not 0 for a canceled click
if (e.detail === 0 || e.detail % 2 === 1) return;
+25 -26
View File
@@ -19,8 +19,9 @@ mod editor_commands {
use editor::messages::input_mapper::utility_types::keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use editor::messages::portfolio::document::node_graph::graph_ui::GraphName;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::document::utility_types::network_interface::NetworkConnectorKey;
use editor::messages::portfolio::ingest::utility_types::DataTransferItem;
use editor::messages::portfolio::utility_types::PanelGroupId;
use editor::messages::prelude::*;
@@ -673,11 +674,6 @@ mod editor_commands {
.into()
}
/// Set the name for a layer in the network shown by the node graph, which may be a subgraph
fn set_layer_name_in_graph(id: u64, name: String) -> Message {
DocumentMessage::SetLayerNameInGraph { node_id: NodeId(id), name }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
@@ -800,29 +796,20 @@ mod editor_commands {
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
}
/// Set the name of an import.
fn set_import_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
}
.into()
fn begin_network_connector_name_edit(is_import: bool, index: usize) -> Message {
let name = GraphName::NetworkConnector(if is_import { NetworkConnectorKey::Import(index) } else { NetworkConnectorKey::Export(index) });
NodeGraphMessage::BeginEditName { name }.into()
}
/// Set the name of an export.
fn set_export_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
}
.into()
fn end_graph_name_edit(name: Option<String>) -> Message {
NodeGraphMessage::EndEditName { name }.into()
}
/// Set the description of an import.
fn set_import_description(index: usize, description: String) -> Message {
NodeGraphMessage::SetImportExportDescription {
description,
index: ImportOrExport::Import(index),
index: NetworkConnectorKey::Import(index),
}
.into()
}
@@ -831,7 +818,7 @@ mod editor_commands {
fn set_export_description(index: usize, description: String) -> Message {
NodeGraphMessage::SetImportExportDescription {
description,
index: ImportOrExport::Export(index),
index: NetworkConnectorKey::Export(index),
}
.into()
}
@@ -841,7 +828,10 @@ mod editor_commands {
Message::Batched {
messages: Box::new([
DocumentMessage::AddTransaction.into(),
NodeGraphMessage::RemoveImportExport { index: ImportOrExport::Import(index) }.into(),
NodeGraphMessage::RemoveImportExport {
index: NetworkConnectorKey::Import(index),
}
.into(),
]),
}
}
@@ -851,7 +841,10 @@ mod editor_commands {
Message::Batched {
messages: Box::new([
DocumentMessage::AddTransaction.into(),
NodeGraphMessage::RemoveImportExport { index: ImportOrExport::Export(index) }.into(),
NodeGraphMessage::RemoveImportExport {
index: NetworkConnectorKey::Export(index),
}
.into(),
]),
}
}
@@ -899,7 +892,10 @@ mod editor_commands {
Message::Batched {
messages: Box::new([
DocumentMessage::AddTransaction.into(),
NodeGraphMessage::DisconnectImportExport { index: ImportOrExport::Import(index) }.into(),
NodeGraphMessage::DisconnectImportExport {
index: NetworkConnectorKey::Import(index),
}
.into(),
]),
}
}
@@ -909,7 +905,10 @@ mod editor_commands {
Message::Batched {
messages: Box::new([
DocumentMessage::AddTransaction.into(),
NodeGraphMessage::DisconnectImportExport { index: ImportOrExport::Export(index) }.into(),
NodeGraphMessage::DisconnectImportExport {
index: NetworkConnectorKey::Export(index),
}
.into(),
]),
}
}
+2 -24
View File
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
}
```
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 the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
Only the definitions of built-in nodes made from a nested network 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`.
## Inspector
@@ -127,29 +127,7 @@ 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`, `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 uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` 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. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
```rs
/// Loads an image from a given URL.
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
pub fn load_image(
_: (),
/// The web address or local asset path of the image to load.
#[name("URL")]
url: Item<String>,
) -> out!(
/// The loaded image.
image,
) {
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
}
```
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
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]`.
## Executing a document `NodeNetwork`
+1
View File
@@ -41,6 +41,7 @@ raster-nodes = { workspace = true, features = ["serde"] }
vector-nodes = { workspace = true, features = ["serde"] }
graphic-types = { workspace = true, features = ["serde"] }
text-nodes = { workspace = true, features = ["serde"] }
graph-ui-types = { workspace = true }
# Workspace dependencies
log = { workspace = true }
@@ -360,15 +360,11 @@ impl NodeNetwork {
};
let value_node_id = gen_id();
let merged_node_id = map_ids(id, value_node_id);
let mut original_location = OriginalLocation {
path: Some(path.to_vec()),
let original_location = OriginalLocation {
dependants: vec![vec![id]],
..Default::default()
};
if let Some(path) = &mut original_location.path {
path.push(value_node_id);
}
collection.insert(
merged_node_id,
DocumentNode {
@@ -63,7 +63,6 @@ fn flatten_add_expected() -> NodeNetwork {
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(4)]),
dependants: vec![vec![NodeId(10)]],
..Default::default()
},
@@ -110,6 +110,8 @@ macro_rules! tagged_value {
Runtime(RuntimeHandle),
#[serde(skip)]
EditorApi(Arc<PlatformEditorApi>),
#[serde(skip)]
GraphUi(graph_ui_types::TaggedGraphUiValue),
/// Only used by the `resource` node, should never be serialized
#[serde(skip)]
ResourceHash(ResourceHash),
@@ -144,6 +146,7 @@ macro_rules! tagged_value {
Self::Runtime(runtime) => runtime.cache_hash(state),
Self::RenderOutput(x) => x.cache_hash(state),
Self::EditorApi(x) => x.cache_hash(state),
Self::GraphUi(x) => x.cache_hash(state),
Self::ResourceHash(x) => x.cache_hash(state),
}
}
@@ -208,6 +211,7 @@ macro_rules! tagged_value {
Self::SourceId(source) => Box::new(Item::new_from_element(source)),
Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)),
Self::EditorApi(x) => Box::new(Item::new_from_element(x)),
Self::GraphUi(x) => x.to_dynany(),
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
}
}
@@ -268,6 +272,7 @@ macro_rules! tagged_value {
Self::SourceId(source) => Arc::new(Item::new_from_element(source)),
Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)),
Self::EditorApi(x) => Arc::new(Item::new_from_element(x)),
Self::GraphUi(x) => x.to_any(),
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
}
}
@@ -300,6 +305,7 @@ macro_rules! tagged_value {
Self::SourceId(_) => item!(SourceId),
Self::Runtime(_) => item!(RuntimeHandle),
Self::EditorApi(_) => item!(Arc<PlatformEditorApi>),
Self::GraphUi(x) => x.ty(),
Self::ResourceHash(_) => item!(ResourceHash),
};
@@ -458,6 +464,7 @@ macro_rules! tagged_value {
Self::SourceId(source) => format!("SourceId({source:?})"),
Self::Runtime(_) => "Runtime".to_string(),
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
Self::GraphUi(_) => "GraphUi".to_string(),
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
}
}
@@ -551,6 +558,7 @@ tagged_value! {
WarpStyle(graphic_types::WarpStyle),
WaveType(graphic_types::WaveType),
DisplaceMode(graphic_types::DisplaceMode),
BlendIfChannel(graphic_types::BlendIfChannel),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
+36
View File
@@ -0,0 +1,36 @@
[package]
name = "graph-ui"
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
[features]
serde = ["graph-ui-types/serde"]
wasm = ["graph-ui-types/wasm"]
[dependencies]
# Local dependencies
core-types = { workspace = true }
graph-craft = { workspace = true }
graph-ui-icons = { workspace = true }
graph-ui-types = { workspace = true }
graphene-std = { workspace = true }
graphic-types = { workspace = true }
node-macro = { workspace = true }
rendering = { workspace = true }
svg-convert = { workspace = true }
text-nodes = { workspace = true }
vector-types = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
vello_gpu = { workspace = true }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "graph-ui-icons"
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
+39
View File
@@ -0,0 +1,39 @@
// TODO(Timon): Replace with generalized icon crate
use std::fmt::Write;
use std::path::PathBuf;
const FOLDERS: [&str; 2] = ["16x16-nodes", "16x16-ui-general"];
fn main() {
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../..");
let assets = root.join("branding/assets");
let mut sources = Vec::new();
println!("cargo:rerun-if-changed={}", assets.display());
if assets.is_dir() {
for folder in FOLDERS {
for entry in std::fs::read_dir(assets.join(folder)).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_some_and(|extension| extension == "svg") {
sources.push((icon_name(&path.file_stem().unwrap().to_string_lossy()), path));
}
}
}
} else {
println!("cargo:warning=No branding folder, icons will be missing");
}
sources.sort();
let mut table = String::from("static SOURCES: &[(&str, &str)] = &[\n");
for (name, path) in &sources {
writeln!(table, "\t({name:?}, include_str!({:?})),", path.display().to_string()).unwrap();
}
table.push_str("];\n");
std::fs::write(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("icons.rs"), table).unwrap();
}
fn icon_name(file_stem: &str) -> String {
let capitalized = |word: &str| word[..1].to_uppercase() + &word[1..];
file_stem.split('-').filter(|word| !word.is_empty()).map(capitalized).collect()
}
+8
View File
@@ -0,0 +1,8 @@
// TODO(Timon): Replace with generalized icon crate
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
pub fn svg(name: &str) -> Option<&'static str> {
let index = SOURCES.binary_search_by_key(&name, |&(name, _)| name).ok()?;
Some(SOURCES[index].1)
}
+266
View File
@@ -0,0 +1,266 @@
use crate::metrics::{BORDER_DASHES, BORDER_WIDTH};
use glam::DVec2;
use std::f64::consts::{FRAC_PI_2, PI};
use std::ops::Range;
use vello_gpu::kurbo::{Arc, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez};
const MEASURE_TOLERANCE: f64 = 0.5;
const MEASURE_DEPTH: u32 = 20;
const ARC_TOLERANCE: f64 = 0.1;
struct Measured {
distance: f64,
segment: usize,
t: f64,
}
pub(crate) fn dashed(path: &BezPath, [dash, gap]: [f64; 2]) -> BezPath {
let mut dashes = BezPath::new();
for contour in contours(path) {
let measured = measure(&contour);
let Some(length) = measured.last().map(|last| last.distance) else { continue };
let mut distance = 0.;
for (index, interval) in [dash, gap].into_iter().cycle().enumerate() {
if distance >= length {
break;
}
if index % 2 == 0 {
piece(&contour, &measured, distance..(distance + interval).min(length), &mut dashes);
}
distance += interval;
}
}
dashes
}
fn contours(path: &BezPath) -> Vec<Vec<PathSeg>> {
let mut contours: Vec<Vec<PathSeg>> = Vec::new();
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
for element in path.elements() {
let segment = match *element {
PathEl::MoveTo(point) => {
contours.push(Vec::new());
(start, last) = (point, point);
continue;
}
PathEl::LineTo(point) => PathSeg::Line(Line::new(last, point)),
PathEl::QuadTo(control, point) => PathSeg::Cubic(QuadBez::new(last, control, point).raise()),
PathEl::CurveTo(first, second, point) => PathSeg::Cubic(CubicBez::new(last, first, second, point)),
PathEl::ClosePath => PathSeg::Line(Line::new(last, start)),
};
last = segment.end();
if let Some(contour) = contours.last_mut() {
contour.push(segment);
}
}
contours
}
fn measure(contour: &[PathSeg]) -> Vec<Measured> {
let mut measured = Vec::new();
let mut distance = 0.;
for (segment, piece) in contour.iter().enumerate() {
distance = match piece {
PathSeg::Cubic(cubic) => measure_cubic(*cubic, distance, 0_f64..1., MEASURE_DEPTH, segment, &mut measured),
_ => chord(piece.start(), piece.end(), distance, segment, 1., &mut measured),
};
}
measured
}
fn measure_cubic(cubic: CubicBez, distance: f64, range: Range<f64>, depth: u32, segment: usize, measured: &mut Vec<Measured>) -> f64 {
let strays = |control: Point, fraction: f64| {
let on_chord = cubic.p0.lerp(cubic.p3, fraction);
(control.x - on_chord.x).abs().max((control.y - on_chord.y).abs()) > MEASURE_TOLERANCE
};
if depth == 0 || !(strays(cubic.p1, 1. / 3.) || strays(cubic.p2, 2. / 3.)) {
return chord(cubic.p0, cubic.p3, distance, segment, range.end, measured);
}
let (first, second) = cubic.subdivide();
let middle = (range.start + range.end) / 2.;
let distance = measure_cubic(first, distance, range.start..middle, depth - 1, segment, measured);
measure_cubic(second, distance, middle..range.end, depth - 1, segment, measured)
}
fn chord(from: Point, to: Point, distance: f64, segment: usize, t: f64, measured: &mut Vec<Measured>) -> f64 {
let next = distance + from.distance(to);
if next > distance {
measured.push(Measured { distance: next, segment, t });
}
next
}
fn at(measured: &[Measured], distance: f64) -> (usize, f64) {
let index = measured.partition_point(|entry| entry.distance < distance).min(measured.len() - 1);
let entry = &measured[index];
let (start_distance, start_t) = match index.checked_sub(1).map(|previous| &measured[previous]) {
Some(previous) if previous.segment == entry.segment => (previous.distance, previous.t),
Some(previous) => (previous.distance, 0.),
None => (0., 0.),
};
(entry.segment, start_t + (entry.t - start_t) * (distance - start_distance) / (entry.distance - start_distance))
}
fn piece(contour: &[PathSeg], measured: &[Measured], range: Range<f64>, dashes: &mut BezPath) {
let (start_segment, start_t) = at(measured, range.start);
let (end_segment, end_t) = at(measured, range.end);
dashes.move_to(contour[start_segment].eval(start_t));
let mut push = |segment: usize, range: Range<f64>| match contour[segment].subsegment(range) {
PathSeg::Line(line) => dashes.line_to(line.p1),
PathSeg::Quad(quad) => dashes.quad_to(quad.p1, quad.p2),
PathSeg::Cubic(cubic) => dashes.curve_to(cubic.p1, cubic.p2, cubic.p3),
};
if start_segment == end_segment {
push(start_segment, start_t..end_t);
return;
}
push(start_segment, start_t..1.);
for segment in start_segment + 1..end_segment {
push(segment, 0. ..1.);
}
push(end_segment, 0. ..end_t);
}
enum BorderPart {
Line(DVec2, DVec2),
Corner(DVec2, f64),
}
pub(crate) fn border(min: DVec2, max: DVec2, radius: f64, gaps: &[[DVec2; 2]], dashed: bool) -> BezPath {
let inset = BORDER_WIDTH / 2.;
let arc_radius = radius - inset;
let corner_length = flattened_arc_length(radius, [0., FRAC_PI_2]);
let [left, top] = (min + inset).to_array();
let [right, bottom] = (max - inset).to_array();
let parts = [
BorderPart::Line(DVec2::new(left + arc_radius, top), DVec2::new(right - arc_radius, top)),
BorderPart::Corner(DVec2::new(right - arc_radius, top + arc_radius), -FRAC_PI_2),
BorderPart::Line(DVec2::new(right, top + arc_radius), DVec2::new(right, bottom - arc_radius)),
BorderPart::Corner(DVec2::new(right - arc_radius, bottom - arc_radius), 0.),
BorderPart::Line(DVec2::new(right - arc_radius, bottom), DVec2::new(left + arc_radius, bottom)),
BorderPart::Corner(DVec2::new(left + arc_radius, bottom - arc_radius), FRAC_PI_2),
BorderPart::Line(DVec2::new(left, bottom - arc_radius), DVec2::new(left, top + arc_radius)),
BorderPart::Corner(DVec2::new(left + arc_radius, top + arc_radius), PI),
];
let length = |part: &BorderPart| match part {
BorderPart::Line(from, to) => from.distance(*to),
BorderPart::Corner(..) => corner_length,
};
let point = |part: &BorderPart, fraction: f64| match *part {
BorderPart::Line(from, to) => from.lerp(to, fraction),
BorderPart::Corner(center, start_angle) => center + arc_radius * DVec2::from_angle(start_angle + fraction * FRAC_PI_2),
};
let starts: Vec<f64> = parts.iter().scan(0., |start, part| Some(std::mem::replace(start, *start + length(part)))).collect();
let perimeter: f64 = parts.iter().map(length).sum();
let mut left_out: Vec<[f64; 2]> = parts
.iter()
.zip(&starts)
.flat_map(|(part, &start)| {
let straight = matches!(part, BorderPart::Line(..));
let inside = gaps.iter().filter_map(move |&gap| fractions_inside(|fraction| point(part, fraction), straight, gap));
inside.map(move |[from, to]| [start + from * length(part), start + to * length(part)])
})
.collect();
left_out.sort_by(|a, b| a[0].total_cmp(&b[0]));
let shown = if dashed {
let [dash, gap] = BORDER_DASHES;
let length = perimeter.floor();
let fewer = (length / (dash + gap)).floor();
let gaps = [fewer, fewer + 1.].map(|count| (length - count * dash) / count);
let (count, gap) = if gaps[1] > 0. && (gaps[1] - gap).abs() <= (gaps[0] - gap).abs() {
(fewer + 1., gaps[1])
} else {
(fewer, gaps[0])
};
(0..count as usize).map(|index| [index as f64 * (dash + gap), index as f64 * (dash + gap) + dash]).collect()
} else {
vec![[0., perimeter]]
};
let visible = shown.into_iter().flat_map(|[mut from, to]| {
let mut pieces = Vec::new();
for &[gap_from, gap_to] in &left_out {
if gap_from < to && gap_to > from {
pieces.extend((gap_from > from).then_some([from, gap_from]));
from = from.max(gap_to);
}
}
pieces.extend((from < to).then_some([from, to]));
pieces
});
let mut border = BezPath::new();
for [from, to] in visible {
let mut started = false;
for (part, start) in parts.iter().zip(&starts) {
if length(part) == 0. {
continue;
}
let [a, b] = [from, to].map(|at| ((at - start) / length(part)).clamp(0., 1.));
if b <= a {
continue;
}
if !started {
border.move_to(<(f64, f64)>::from(point(part, a)));
started = true;
}
match *part {
BorderPart::Line(..) => border.line_to(<(f64, f64)>::from(point(part, b))),
BorderPart::Corner(center, start_angle) => {
border.extend(Arc::new(<(f64, f64)>::from(center), (arc_radius, arc_radius), start_angle + a * FRAC_PI_2, (b - a) * FRAC_PI_2, 0.).append_iter(ARC_TOLERANCE))
}
}
}
}
border
}
fn flattened_arc_length(radius: f64, [from, to]: [f64; 2]) -> f64 {
let point = |angle: f64| radius * DVec2::from_angle(angle);
let middle = (from + to) / 2.;
let bulge = point(middle) - (point(from) + point(to)) / 2.;
if bulge.abs().max_element() > MEASURE_TOLERANCE {
flattened_arc_length(radius, [from, middle]) + flattened_arc_length(radius, [middle, to])
} else {
point(from).distance(point(to))
}
}
fn fractions_inside(point: impl Fn(f64) -> DVec2, straight: bool, [low, high]: [DVec2; 2]) -> Option<[f64; 2]> {
let mut range = [0_f64, 1_f64];
for axis in 0..2 {
let value = |fraction: f64| point(fraction)[axis];
let [start, end] = [value(0.), value(1.)];
if start.min(end) > high[axis] || start.max(end) < low[axis] {
return None;
}
if start == end {
continue;
}
let fraction_at = |bound: f64| {
if (bound - start) * (end - start) <= 0. {
return 0.;
}
if (bound - end) * (end - start) >= 0. {
return 1.;
}
if straight {
return (bound - start) / (end - start);
}
let [mut before, mut after] = [0_f64, 1_f64];
for _ in 0..f64::MANTISSA_DIGITS {
let middle = (before + after) / 2.;
if (value(middle) - bound) * (end - start) < 0. {
before = middle;
} else {
after = middle;
}
}
after
};
let [a, b] = [fraction_at(low[axis]), fraction_at(high[axis])];
range = [range[0].max(a.min(b)), range[1].min(a.max(b))];
}
(range[0] < range[1]).then_some(range)
}
+90
View File
@@ -0,0 +1,90 @@
// TODO(Timon): Replace with generalized icon crate
use crate::card::DataType;
use crate::look::data_type_colors;
use crate::metrics::ICON_SIZE;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::color::SRGBA8;
use core_types::list::List;
use glam::DAffine2;
use graphic_types::{IntoGraphicList, Vector};
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::{LazyLock, Mutex};
use svg_convert::Options;
#[derive(Clone)]
pub struct Icon {
pub(crate) shapes: List<Vector>,
pub(crate) overflows: bool,
}
type Converted = HashMap<SRGBA8, HashMap<String, Option<Icon>>>;
static CONVERTED: LazyLock<Mutex<Converted>> = LazyLock::new(Mutex::default);
pub fn icon(name: &str, current: SRGBA8) -> Option<Icon> {
let mut converted = CONVERTED.lock().unwrap();
let converted = converted.entry(current).or_default();
if let Some(icon) = converted.get(name) {
return icon.clone();
}
let icon = graph_ui_icons::svg(name).and_then(|svg| convert(svg, current));
converted.insert(name.to_string(), icon.clone());
icon
}
fn convert(svg: &str, current: SRGBA8) -> Option<Icon> {
let mut style_sheet = format!("svg {{ fill: {}; }}", hex_color(current));
for (class, _) in svg.split("class=\"").skip(1).filter_map(|rest| rest.split_once('"')) {
write!(style_sheet, " .{class} {{ fill: {}; }}", hex_color(class_color(class)?)).unwrap();
}
let options = Options {
style_sheet: Some(style_sheet),
..Options::default()
};
let shapes: List<Vector> = svg_convert::convert(svg, &options).ok()?.into_flattened_list();
let overflows = match shapes.bounding_box(DAffine2::IDENTITY, false) {
RenderBoundingBox::Rectangle([min, max]) => min.min_element() < 0. || max.max_element() > ICON_SIZE,
RenderBoundingBox::Infinite => true,
RenderBoundingBox::None => false,
};
Some(Icon { shapes, overflows })
}
fn hex_color(color: SRGBA8) -> String {
format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue)
}
fn class_color(class: &str) -> Option<SRGBA8> {
let token = class.strip_prefix("color-")?;
let Some(mix) = token.strip_prefix("mix-") else { return token_color(token) };
let (pair, percent) = mix.rsplit_once('-')?;
let percent: u16 = percent.parse().ok().filter(|&percent| percent <= 100)?;
let (a, b) = pair.match_indices('-').find_map(|(index, _)| Some((token_color(&pair[..index])?, token_color(&pair[index + 1..])?)))?;
let mix = |a: u8, b: u8| ((u16::from(a) * (100 - percent) + u16::from(b) * percent + 50) / 100) as u8;
Some(SRGBA8::new_opaque(mix(a.red, b.red), mix(a.green, b.green), mix(a.blue, b.blue)))
}
fn token_color(token: &str) -> Option<SRGBA8> {
if let Some((digit, _)) = token.split_once('-').filter(|(digit, _)| digit.len() == 1) {
let value = u8::from_str_radix(digit, 16).ok()? * 0x11;
return Some(SRGBA8::new_opaque(value, value, value));
}
let (name, dim) = token.strip_suffix("-dim").map_or((token, false), |name| (name, true));
let data_type = match name {
"general" => DataType::General,
"number" => DataType::Number,
"artboard" => DataType::Artboard,
"graphic" => DataType::Graphic,
"raster" => DataType::Raster,
"vector" => DataType::Vector,
"color" => DataType::Color,
"gradient" => DataType::Gradient,
"typography" => DataType::Typography,
_ => return None,
};
let [bright, dimmed] = data_type_colors(data_type);
Some(if dim { dimmed } else { bright })
}
+12
View File
@@ -0,0 +1,12 @@
use graph_ui_types::inputs;
pub use graph_ui_types::{GraphUiConfig, animation, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire};
pub use network::{network, render_config};
pub use text::{error_text_size, label_width};
mod dashes;
pub mod icons;
mod look;
mod network;
pub mod nodes;
pub mod router;
mod text;
+168
View File
@@ -0,0 +1,168 @@
use crate::card::{Connector, DataType};
use crate::highlights::Highlight;
use crate::icons;
use crate::metrics::{CHECKER_CELL, HOVERED_CONNECTOR_RING, HOVERED_CONNECTOR_SCALE, ICON_SIZE};
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::transform::ApplyTransform;
use glam::{DAffine2, DVec2};
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use std::sync::LazyLock;
use vector_types::vector::algorithms::shapes::rounded_rectangle_bezpath;
use vector_types::vector::style::{Stroke, StrokeJoin};
use vello_gpu::kurbo::{Affine, BezPath, Rect, Shape};
pub(crate) const CARD_OPACITY: f32 = 0.33;
pub(crate) const GRID_DOT_OPACITY: f32 = 0.2;
pub(crate) const BACKDROP: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
pub(crate) const SELECTED_DOT_RING_OPACITY: f32 = 0.5;
pub(crate) const BORDER: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
pub(crate) const PREVIEWED_BORDER: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
pub(crate) const TEXT: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
pub(crate) const LAYER_IN_INACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
pub(crate) const LAYER_IN_ACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x66, 0x66, 0x66);
pub(crate) const HIDDEN_CARD: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
pub(crate) const HIDDEN_TEXT: SRGBA8 = SRGBA8::new_opaque(0xaa, 0xaa, 0xaa);
pub(crate) const SEPARATOR: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
pub(crate) const HOVERED_BUTTON: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
pub(crate) const DISABLED_ICON: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
pub(crate) const BOX_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x00, 0xa8, 0xff);
pub(crate) const BOX_SELECTION_FILL_OPACITY: f32 = 0.05;
pub(crate) const ERROR_RED: SRGBA8 = SRGBA8::new_opaque(0xd6, 0x53, 0x6e);
pub(crate) const ERROR_TEXT: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
pub(crate) const ERROR_OPACITY: f64 = 0.5;
pub(crate) const WIRE_SPLIT: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
pub(crate) const THUMBNAIL_BACKGROUND: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
const CHECKER_LIGHT: SRGBA8 = SRGBA8::new_opaque(0xff, 0xff, 0xff);
const CHECKER_DARK: SRGBA8 = SRGBA8::new_opaque(0xcc, 0xcc, 0xcc);
pub(crate) const CIRCLE_TOLERANCE: f64 = 1e-3;
pub(crate) static CONNECTOR_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z"));
pub(crate) static STACK_OUTPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z"));
pub(crate) static STACK_INPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z"));
pub(crate) static STACK_OUTPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
parsed(
"M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 Z\
M5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z",
)
});
pub(crate) static STACK_INPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
parsed(
"M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 Z\
M5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z",
)
});
fn parsed(path_data: &str) -> BezPath {
BezPath::from_svg(path_data).expect("A connector outline is valid path data")
}
pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] {
let colors = match data_type {
DataType::General => [0xcfcfcf, 0x8a8a8a],
DataType::Number => [0xc9a699, 0x886b60],
DataType::Artboard => [0xfbf9eb, 0xb9b9a9],
DataType::Graphic => [0x68c587, 0x37754c],
DataType::Raster => [0xe4bb72, 0x9a7b43],
DataType::Vector => [0x65bbe5, 0x417892],
DataType::Color => [0xce6ea7, 0x924071],
DataType::Gradient => [0xaf81eb, 0x6c489b],
DataType::Typography => [0xeea7a7, 0x955252],
DataType::Invalid => [0xd6536e, 0xa7324a],
};
colors.map(|color| {
let [_, red, green, blue] = u32::to_be_bytes(color);
SRGBA8::new_opaque(red, green, blue)
})
}
pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight, grown: f64) -> List<Vector> {
drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight, grown)
}
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight, grown: f64) -> List<Vector> {
let [bright, dim] = data_type_colors(data_type);
let resting = if connected || highlight == Highlight::WireSource { bright } else { dim };
let ringed = highlight.is_grown();
if grown == 0. && !ringed {
return List::new_from_item(outlined(outline, top_left, resting));
}
let scale = 1. + (HOVERED_CONNECTOR_SCALE - 1.) * grown;
let grown_outline = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(scale, outline.bounding_box().center()) * outline.clone();
let grown_outline = Vector::item_from_bezpath(&grown_outline);
let mut graphic = List::new();
if ringed {
let ring = Stroke {
join: StrokeJoin::Round,
..Stroke::new(HOVERED_CONNECTOR_RING * scale)
};
graphic.push(painted(grown_outline.clone(), Coverage::new_stroke(&ring), dim.into()));
}
let channel = |from: u8, to: u8| (from as f64 + (to as f64 - from as f64) * grown).round() as u8;
let fill = SRGBA8::new(
channel(resting.red, bright.red),
channel(resting.green, bright.green),
channel(resting.blue, bright.blue),
channel(resting.alpha, bright.alpha),
);
graphic.push(painted(grown_outline, Coverage::new_fill(), fill.into()));
graphic
}
pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item<Vector> {
let mut outline = Vector::item_from_bezpath(outline);
outline.left_apply_transform(&DAffine2::from_translation(top_left));
painted(outline, Coverage::new_fill(), color.into())
}
pub(crate) fn rounded_rect(min: DVec2, max: DVec2, radii: [f64; 4]) -> Item<Vector> {
Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii))
}
pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List<Vector> {
let Some(icon) = icons::icon(name, current) else { return List::new() };
let mut graphic = icon.shapes;
if icon.overflows {
let mut clip = rounded_rect(DVec2::ZERO, DVec2::splat(ICON_SIZE), [0.; 4]);
stamp_coverage(&mut clip, Coverage::new_fill(), Graphic::VectorList(graphic), CoverPlacement::Above);
graphic = List::new_from_item(clip);
}
graphic.left_apply_transform(&DAffine2::from_translation(top_left));
graphic
}
pub(crate) fn text(outline: &List<Vector>, top_left: DVec2, color: SRGBA8) -> List<Vector> {
let glyphs = outline.clone().into_iter();
let mut glyphs: List<Vector> = glyphs.map(|glyph| painted(glyph, Coverage::new_fill(), color.into())).collect();
glyphs.left_apply_transform(&DAffine2::from_translation(top_left));
glyphs
}
pub(crate) fn checkerboard(min: DVec2, max: DVec2) -> List<Vector> {
let mut dark = BezPath::new();
let cells = ((max - min) / CHECKER_CELL).ceil().as_uvec2();
for (column, row) in (0..cells.y)
.flat_map(|row| (0..cells.x).map(move |column| (column, row)))
.filter(|(column, row)| (column + row) % 2 == 1)
{
let cell_min = min + DVec2::new(column as f64, row as f64) * CHECKER_CELL;
let cell_max = (cell_min + CHECKER_CELL).min(max);
dark.extend(Rect::new(cell_min.x, cell_min.y, cell_max.x, cell_max.y).path_elements(0.));
}
let light = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), CHECKER_LIGHT.into());
List::from_iter([light, painted(Vector::item_from_bezpath(&dark), Coverage::new_fill(), CHECKER_DARK.into())])
}
pub(crate) fn painted(mut item: Item<Vector>, coverage: Coverage, color: Color) -> Item<Vector> {
stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above);
item
}
pub(crate) fn image(content: Graphic, unit_square_to_place: DAffine2) -> Item<Vector> {
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
image.left_apply_transform(&unit_square_to_place);
stamp_coverage(&mut image, Coverage::new_fill(), content, CoverPlacement::Above);
image
}
+179
View File
@@ -0,0 +1,179 @@
use crate::GraphUiConfig;
use crate::inputs::{self, TaggedGraphUiValue, Thumbnails};
use crate::nodes::{
draw_backdrop, draw_box_selection, draw_cards, draw_dots, draw_errors, draw_gliding_wires, draw_grid, draw_grows, draw_highlights, draw_layers, draw_loose_wires, draw_moving,
draw_network_connectors, draw_raised, draw_reorder_bar, draw_thick_wires, draw_thumbnails, draw_wires, glide, texture_layer,
};
use crate::scene::GraphUiScene;
use core_types::registry::{FieldMetadata, NODE_METADATA, RegistryValueSource};
use core_types::transform::Footprint;
use core_types::{ContextFeatures, NodeCompileMetadata, ProtoNodeIdentifier};
use glam::DAffine2;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::graphic::extend;
use graphene_std::ops::passthrough;
use graphene_std::platform_application_io::wgpu_executor;
use graphene_std::render_cache::render_output_cache;
use graphene_std::render_node::{create_context, render, render_intermediate};
use std::sync::Arc;
pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbnails) -> NodeNetwork {
let layers = scene.settled().layers.iter().chain(&scene.moving().layers);
let layer_thumbnails = layers.filter_map(|layer| Some((layer.look.key, thumbnails.get(&layer.look.key)?.clone())));
let values = [
(inputs::SETTLED, TaggedGraphUiValue::Rows(scene.settled().clone())),
(inputs::MOVING, TaggedGraphUiValue::Rows(scene.moving().clone())),
(inputs::NETWORK_CONNECTORS, TaggedGraphUiValue::NetworkConnectors(scene.network_connectors().clone())),
(inputs::ERRORS, TaggedGraphUiValue::Errors(scene.errors().clone())),
(inputs::THUMBNAILS, TaggedGraphUiValue::Thumbnails(Arc::new(layer_thumbnails.collect()))),
(inputs::WIRE_IN_PROGRESS, TaggedGraphUiValue::WireInProgress(config.wire_in_progress)),
(inputs::REORDER_BAR, TaggedGraphUiValue::ReorderBar(config.reorder_bar)),
(inputs::BOX_SELECTION, TaggedGraphUiValue::BoxSelection(config.box_selection)),
(inputs::FADE_ARTWORK, TaggedGraphUiValue::FadeArtwork(config.fade_artwork)),
(inputs::WIRE_STYLE, TaggedGraphUiValue::WireStyle(config.wire_style)),
(inputs::HIGHLIGHTS, TaggedGraphUiValue::Highlights(config.highlights.clone())),
(inputs::GLIDES, TaggedGraphUiValue::Glides(config.glides.clone())),
];
let mut network = NodeNetwork::default();
for (scope, value) in values {
let ty = value.ty();
let id = add(&mut network, node(passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::GraphUi(value), false)]));
network.scope_injections.insert(scope.as_str().to_string(), (id, ty));
}
let [backdrop, grid] = [draw_backdrop::IDENTIFIER, draw_grid::IDENTIFIER].map(|identifier| drawn(&mut network, identifier));
let layers = tiled(&mut network, draw_thick_wires::IDENTIFIER, [draw_layers::IDENTIFIER]);
let [thumbnails, loose_wires] = [draw_thumbnails::IDENTIFIER, draw_loose_wires::IDENTIFIER].map(|identifier| drawn(&mut network, identifier));
let nodes = tiled(&mut network, draw_wires::IDENTIFIER, [draw_cards::IDENTIFIER, draw_dots::IDENTIFIER, draw_raised::IDENTIFIER]);
let above_nodes = [
draw_moving::IDENTIFIER,
draw_errors::IDENTIFIER,
draw_network_connectors::IDENTIFIER,
draw_highlights::IDENTIFIER,
draw_reorder_bar::IDENTIFIER,
draw_box_selection::IDENTIFIER,
];
let [moving, errors, network_connectors, highlights, reorder_bar, box_selection] = above_nodes.map(|identifier| drawn(&mut network, identifier));
let gliding = !config.glides.rows.is_empty();
let gliding_wires = gliding.then(|| drawn(&mut network, draw_gliding_wires::IDENTIFIER));
let grows = (!config.highlights.grows.is_empty()).then(|| drawn(&mut network, draw_grows::IDENTIFIER));
let mut glided = |drawing| match gliding {
true => add(&mut network, node(glide::IDENTIFIER, vec![NodeInput::node(drawing, 0), NodeInput::scope(inputs::GLIDES)])),
false => drawing,
};
let above = [
Some(grid),
Some(layers),
Some(thumbnails),
Some(loose_wires),
gliding_wires,
Some(nodes),
Some(glided(moving)),
Some(glided(errors)),
Some(glided(network_connectors)),
grows.map(&mut glided),
Some(glided(highlights)),
Some(reorder_bar),
Some(box_selection),
];
let stack = stacked(&mut network, backdrop, above.into_iter().flatten());
let frame = rendered(&mut network, stack);
// INDEX is never read; it forces a nullification and cache pair onto the render's wire, so its memo keys on the footprint and the render params only
let compile_metadata = Some(NodeCompileMetadata {
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
..Default::default()
});
let create_context = DocumentNode {
compile_metadata,
..node(create_context::IDENTIFIER, vec![NodeInput::node(frame, 0)])
};
let output = add(&mut network, create_context);
network.exports.push(NodeInput::node(output, 0));
network
}
pub fn render_config(config: &GraphUiConfig, request: RenderConfig) -> RenderConfig {
let view = config.view;
let translation = (view.translation * request.scale).round() / request.scale;
let viewport = Footprint {
transform: DAffine2 { translation, ..view },
resolution: request.viewport.resolution,
..Default::default()
};
RenderConfig {
viewport,
scale: request.scale,
time: request.time,
export_format: ExportFormat::Raster,
..Default::default()
}
}
fn node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
inputs,
..Default::default()
}
}
fn add(network: &mut NodeNetwork, node: DocumentNode) -> NodeId {
let id = NodeId(u64::MAX - network.nodes.len() as u64);
network.nodes.insert(id, node);
id
}
fn drawn(network: &mut NodeNetwork, identifier: ProtoNodeIdentifier) -> NodeId {
let scope = |field: &FieldMetadata| match &field.value_source {
RegistryValueSource::Scope(scope) => Ok(NodeInput::scope(*scope)),
source => Err(format!("The parameter {} of the drawing node {identifier} of the node graph reads {source:?}, not a scope", field.name)),
};
let scopes = NODE_METADATA
.lock()
.unwrap()
.get(&identifier)
.map(|metadata| metadata.fields.iter().map(scope).collect::<Result<Vec<_>, _>>());
let scopes = scopes.unwrap_or_else(|| panic!("The drawing node {identifier} of the node graph is not registered"));
let scopes = scopes.unwrap_or_else(|not_a_scope| panic!("{not_a_scope}"));
add(network, node(identifier, scopes))
}
fn stacked(network: &mut NodeNetwork, bottom: NodeId, above: impl IntoIterator<Item = NodeId>) -> NodeId {
let over = |below, layer| add(network, node(extend::IDENTIFIER, vec![NodeInput::node(below, 0), NodeInput::node(layer, 0)]));
above.into_iter().fold(bottom, over)
}
fn rendered(network: &mut NodeNetwork, content: NodeId) -> NodeId {
let intermediate = add(network, node(render_intermediate::IDENTIFIER, vec![NodeInput::node(content, 0)]));
let inputs = vec![
NodeInput::node(intermediate, 0),
NodeInput::scope(wgpu_executor::IDENTIFIER),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
];
add(network, node(render::IDENTIFIER, inputs))
}
fn tiled(network: &mut NodeNetwork, first: ProtoNodeIdentifier, rest: impl IntoIterator<Item = ProtoNodeIdentifier>) -> NodeId {
let bottom = drawn(network, first);
let above: Vec<NodeId> = rest.into_iter().map(|identifier| drawn(network, identifier)).collect();
let bands = stacked(network, bottom, above);
let region = rendered(network, bands);
// The cache's signature names the time and the pointer, which would put both into its key; it reads only the footprint and the render params
let compile_metadata = Some(NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
..Default::default()
});
let cache = DocumentNode {
compile_metadata,
..node(render_output_cache::IDENTIFIER, vec![NodeInput::node(region, 0), NodeInput::scope(wgpu_executor::IDENTIFIER)])
};
let cached = add(network, cache);
add(network, node(texture_layer::IDENTIFIER, vec![NodeInput::node(cached, 0)]))
}
+717
View File
@@ -0,0 +1,717 @@
use crate::animation::{Glided, Glides};
use crate::card::{Card, Connector, DataType, Selection};
use crate::dashes::{border, dashed};
use crate::dot::Dot;
use crate::error_badge::{self, ErrorBadge};
use crate::geometry::{WireEnd, is_thick_wire, node_geometry, wire_ends};
use crate::highlights::{ConnectorKey, Highlight, Highlights};
use crate::inputs::{self, Thumbnails};
use crate::layer::{Layer, LayerButton};
use crate::look::{
BACKDROP, BORDER, BOX_SELECTION, BOX_SELECTION_FILL_OPACITY, CARD_OPACITY, CIRCLE_TOLERANCE, CONNECTOR_OUTLINE, DISABLED_ICON, ERROR_OPACITY, ERROR_RED, ERROR_TEXT, GRID_DOT_OPACITY, HIDDEN_CARD,
HIDDEN_TEXT, HOVERED_BUTTON, LAYER_IN_ACTIVE_SELECTION, LAYER_IN_INACTIVE_SELECTION, PREVIEWED_BORDER, SELECTED_DOT_RING_OPACITY, SEPARATOR, STACK_INPUT_OUTLINE, STACK_INPUT_WIRE_END,
STACK_OUTPUT_OUTLINE, STACK_OUTPUT_WIRE_END, TEXT, THUMBNAIL_BACKGROUND, WIRE_SPLIT, checkerboard, connector, data_type_colors, drawn_connector, icon, image, outlined, painted, rounded_rect,
text,
};
use crate::metrics::{
BORDER_WIDTH, CARD_ICON_LEFT, CARD_NAME_LEFT, CARD_NAME_MAX_WIDTH, CARD_RADIUS, CARD_ROW_PADDING, CONNECTOR_GAP, CONNECTOR_SIZE, DOT_HOVERED_RING, DOT_OUTPUT_ARROW, DOT_PREVIEWED_RING_OFFSET,
DOT_RADIUS, DOT_SELECTED_RING, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_RADIUS, GRID_COLLAPSE_SPACING, GRID_SIZE, HOVERED_CONNECTOR_SCALE, ICON_SIZE, LAYER_BUTTON_RADIUS, LAYER_BUTTON_SIZE,
LAYER_GRIP_DOT_COUNT, LAYER_GRIP_DOT_RADIUS, LAYER_GRIP_DOT_SPACING, LAYER_GRIP_DOTS, LAYER_RADIUS, LAYER_THUMBNAIL_GAP, LAYER_THUMBNAIL_RADIUS, LIST_WIRE_WIDTH, THICK_WIRE_WIDTH, WIRE_DASHES,
WIRE_WIDTH,
};
use crate::network_connector::{self, NetworkConnector, NetworkConnectorKey, NetworkConnectorKind};
use crate::placed::Placed;
use crate::replicated_map::ReplicatedMap;
use crate::router::{build_thick_wire_center_line, route};
use crate::scene::Rows;
use crate::text::{Labels, error_text_size, paragraph_outline};
use crate::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle};
use core_types::color::SRGBA8;
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_TRANSFORM, Item, List};
use core_types::transform::ApplyTransform;
use core_types::uuid::NodeId;
use core_types::{Color, Ctx, ExtractFootprint, ExtractRealTime, ExtractVarArgs, Poll};
use glam::{DAffine2, DVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graphic_types::raster_types::Raster;
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use rendering::RenderParams;
use std::collections::{BTreeMap, BTreeSet};
use text_nodes::TextToVectorError;
use vector_types::vector::style::Stroke;
use vector_types::{Gradient, GradientInterpolation, GradientSpread, GradientStop};
use vello_gpu::kurbo::{BezPath, Circle, Rect, Shape, flatten};
const GRID_DOT_ROUNDING_BIAS: f64 = 1. / 64.;
const WIRE_FLATTENING_TOLERANCE: f64 = 0.02;
const ATTR_GLIDED: &str = "glided";
#[node_macro::node(transient)]
fn draw_backdrop(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::FADE_ARTWORK)] fade_artwork: Item<f64>) -> List<Vector> {
let (view, scale) = view_and_device_scale(&ctx);
let viewport_size = ctx.footprint().resolution.as_dvec2() / scale;
let opacity = fade_artwork.into_element() as f32;
let mut backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity));
backdrop.left_apply_transform(&view.inverse());
List::new_from_item(backdrop)
}
fn view_and_device_scale(ctx: &(impl ExtractFootprint + ExtractVarArgs)) -> (DAffine2, f64) {
let render_params: Option<&RenderParams> = ctx.vararg(0).ok().and_then(|render_params| render_params.downcast_ref());
let scale = render_params.expect("The render params are the first vararg").scale;
(DAffine2::from_scale(DVec2::splat(1. / scale)) * ctx.footprint().transform, scale)
}
#[node_macro::node(transient)]
fn draw_grid(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs) -> List<Vector> {
let (view, scale) = view_and_device_scale(&ctx);
let viewport_size = ctx.footprint().resolution.as_dvec2() / scale;
let mut dots = grid_dots(view, viewport_size, scale);
dots.left_apply_transform(&view.inverse());
dots
}
fn grid_dots(view: DAffine2, viewport_size: DVec2, scale: f64) -> List<Vector> {
let zoom = view.matrix2.x_axis.length();
let mut spacing = zoom * GRID_SIZE;
if !spacing.is_finite() || spacing <= 0. {
return List::new();
}
while spacing < GRID_COLLAPSE_SPACING {
spacing *= 2.;
}
let radius = ((1. + (zoom - 0.5 + 0.001).floor() / 2.) * scale).ceil() as u32;
let period = spacing * scale;
let origin = (view.translation * scale - radius as f64).rem_euclid(DVec2::splat(period)) - period - GRID_DOT_ROUNDING_BIAS;
let dot_color = Color::WHITE.with_alpha(GRID_DOT_OPACITY);
let stop = |column: u32, color| GradientStop {
position: column as f64 / period,
midpoint: 0.5,
color,
};
let mut dots = List::new();
for ([top, bottom], runs) in disc_columns(radius) {
let mut bands = BezPath::new();
for row in 0..=((viewport_size.y * scale - origin.y) / period).ceil() as u32 {
let y = (origin.y + row as f64 * period).round();
bands.extend(Rect::new(0., (y + top as f64) / scale, viewport_size.x, (y + bottom as f64) / scale).path_elements(0.));
}
let start = runs[0][0];
let stops = runs.iter().flat_map(|&[left, right]| [stop(left - start, dot_color), stop(right - start, Color::TRANSPARENT)]);
let mut columns = Item::new_from_element(Gradient::new(stops));
columns.set_attribute(ATTR_GRADIENT_SPREAD, GradientSpread::Repeat);
columns.set_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped);
columns.left_apply_transform(&DAffine2::from_scale_angle_translation(DVec2::splat(spacing), 0., DVec2::new((origin.x + start as f64) / scale, 0.)));
let mut group = Vector::item_from_bezpath(&bands);
stamp_coverage(&mut group, Coverage::new_fill(), Graphic::Gradient(columns), CoverPlacement::Above);
dots.push(group);
}
dots
}
fn disc_columns(radius: u32) -> BTreeMap<[u32; 2], Vec<[u32; 2]>> {
let lit = |column: u32, row: u32| (DVec2::new(column as f64, row as f64) + 0.5 - radius as f64).length() < radius as f64;
let mut runs_by_rows = BTreeMap::<[u32; 2], Vec<[u32; 2]>>::new();
for column in 0..2 * radius {
let top = (0..radius).take_while(|&row| !lit(column, row)).count() as u32;
let runs = runs_by_rows.entry([top, 2 * radius - top]).or_default();
match runs.last_mut() {
Some(run) if run[1] == column => run[1] += 1,
_ => runs.push([column, column + 1]),
}
}
runs_by_rows
}
#[node_macro::node(transient, memoize)]
fn draw_layers(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> Result<List<Vector>, TextToVectorError> {
joined(layers(rows.element()))
}
fn layers(rows: &Rows) -> impl Iterator<Item = Result<(NodeId, List<Vector>), TextToVectorError>> {
let mut labels = Labels::default();
rows.layers.iter().map(move |layer| Ok((layer.look.key, draw_layer(layer, &mut labels)?)))
}
fn joined(rows: impl Iterator<Item = Result<(NodeId, List<Vector>), TextToVectorError>>) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
for row in rows {
graphic.extend(row?.1);
}
Ok(graphic)
}
fn draw_layer(layer: &Placed<Layer>, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
let [min, max] = layer.body();
let fill = match (layer.look.selection, layer.look.visible) {
(Selection::Active, _) => LAYER_IN_ACTIVE_SELECTION.into(),
(Selection::Inactive, _) => LAYER_IN_INACTIVE_SELECTION.into(),
(Selection::None, true) => Color::BLACK,
(Selection::None, false) => HIDDEN_CARD.into(),
};
graphic.push(painted(rounded_rect(min, max, [LAYER_RADIUS; 4]), Coverage::new_fill(), fill.with_alpha(CARD_OPACITY)));
if !layer.look.renaming {
let [name, name_end] = layer.name_box();
let text_color = if layer.look.visible { TEXT } else { HIDDEN_TEXT };
graphic.extend(text(&labels.label(&layer.look.name, name_end.x - name.x)?.outline, name, text_color));
}
let [thumbnail_min, thumbnail_max] = layer.thumbnail();
let thumbnail = rounded_rect(thumbnail_min, thumbnail_max, [LAYER_THUMBNAIL_RADIUS; 4]);
graphic.push(painted(thumbnail, Coverage::new_fill(), THUMBNAIL_BACKGROUND.into()));
let thumbnail_border = Vector::item_from_bezpath(&border(thumbnail_min, thumbnail_max, LAYER_THUMBNAIL_RADIUS, &[], false));
graphic.push(painted(thumbnail_border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BORDER.into()));
let [image_min, image_max] = layer.thumbnail_image();
graphic.extend(checkerboard(image_min, image_max));
if let Some(output) = &layer.look.primary_output {
graphic.extend(stack_output(layer, output, Highlight::None, 0.));
}
match &layer.look.primary_input {
Some(input) => graphic.extend(stack_input(layer, input, Highlight::None, 0.)),
None => graphic.push(outlined(&STACK_INPUT_OUTLINE, layer.stack_input(), data_type_colors(DataType::General)[1])),
}
let [block_min, block_max] = layer.thumbnail_block();
let mut gaps = vec![[block_min - LAYER_THUMBNAIL_GAP, block_max + LAYER_THUMBNAIL_GAP], layer.visibility()];
gaps.extend(layer.left_input_wire().map(|wire| [wire - CONNECTOR_GAP / 2., wire + CONNECTOR_GAP / 2.]));
let border = Vector::item_from_bezpath(&border(min, max, LAYER_RADIUS, &gaps, layer.look.previewed));
let border_color = if layer.look.previewed { PREVIEWED_BORDER } else { BORDER };
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
Ok(graphic)
}
fn stack_output(layer: &Placed<Layer>, output: &Connector, highlight: Highlight, grown: f64) -> List<Vector> {
let mut graphic = connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output, highlight, grown);
if output.connected && layer.look.primary_output_connected_to_layer && highlight != Highlight::WireSource {
graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1]));
}
graphic
}
fn stack_input(layer: &Placed<Layer>, input: &Connector, highlight: Highlight, grown: f64) -> List<Vector> {
let mut graphic = connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input, highlight, grown);
if input.connected && layer.look.primary_input_connected_to_layer && highlight != Highlight::WireSource {
graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1]));
}
graphic
}
#[node_macro::node(transient)]
fn draw_thumbnails(_: impl Ctx, #[scope(inputs::THUMBNAILS)] thumbnails: Item<Thumbnails>, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
layer_thumbnails(thumbnails.element(), rows.element()).map(|(_, thumbnail)| thumbnail).collect()
}
fn layer_thumbnails<'a>(thumbnails: &'a Thumbnails, rows: &'a Rows) -> impl Iterator<Item = (NodeId, Item<Vector>)> + 'a {
let thumbnails = thumbnails.iter().filter_map(|(key, thumbnail)| Some((rows.layers.get(key)?, thumbnail)));
thumbnails.map(|(layer, thumbnail)| {
let [min, max] = layer.thumbnail_image();
(layer.look.key, image(thumbnail.clone(), DAffine2::from_scale_angle_translation(max - min, 0., min)))
})
}
#[node_macro::node(transient)]
fn texture_layer(ctx: impl Ctx + ExtractFootprint, rendered: Item<RenderOutput>) -> Poll<List<Vector>> {
let RenderOutputType::Texture(texture) = rendered.into_element().data else {
return Poll::error("A layer of the node graph was not rendered into a texture");
};
let footprint = ctx.footprint();
let viewport = footprint.transform.inverse() * DAffine2::from_scale(footprint.resolution.as_dvec2());
let texture = Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture)));
Poll::Final(List::new_from_item(image(texture, viewport)))
}
#[node_macro::node(transient, memoize)]
fn draw_raised(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
raised(rows.element()).flat_map(|(_, graphic)| graphic).collect()
}
fn raised(rows: &Rows) -> impl Iterator<Item = (NodeId, List<Vector>)> {
let raised_parts_of_layers = rows.layers.iter().map(|layer| (layer.look.key, draw_raised_parts_of_layer(layer)));
raised_parts_of_layers.chain(rows.cards.iter().map(|card| (card.look.key, draw_connectors_of_card(card))))
}
fn draw_raised_parts_of_layer(layer: &Placed<Layer>) -> List<Vector> {
let mut graphic = List::new();
if let Some(input) = &layer.look.secondary_input {
graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, Highlight::None, 0.));
}
graphic.extend(grip(layer, false));
for (_, place, icons) in layer_buttons(layer) {
graphic.extend(layer_button(layer, place, icons, false, false));
}
graphic
}
fn grip(layer: &Placed<Layer>, hovered: bool) -> List<Vector> {
let grip_color = match (hovered, layer.look.selection != Selection::None) {
(true, _) => Some(Color::WHITE),
(false, true) => Some(TEXT.into()),
(false, false) => None,
};
let Some(grip_color) = grip_color else { return List::new() };
let [grip, _] = layer.grip();
let mut dots = BezPath::new();
let [columns, rows] = LAYER_GRIP_DOT_COUNT;
for (column, row) in (0..rows).flat_map(|row| (0..columns).map(move |column| (column, row))) {
let center = grip + LAYER_GRIP_DOTS + DVec2::new(column as f64, row as f64) * LAYER_GRIP_DOT_SPACING;
dots.extend(Circle::new((center.x, center.y), LAYER_GRIP_DOT_RADIUS).path_elements(CIRCLE_TOLERANCE));
}
List::new_from_item(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color))
}
fn layer_buttons(layer: &Placed<Layer>) -> impl Iterator<Item = (LayerButton, [DVec2; 2], [&'static str; 2])> {
let lock = layer.lock().map(|lock| (LayerButton::Lock, lock, ["PadlockLocked", "PadlockUnlocked"]));
let eye = if layer.look.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] };
lock.into_iter().chain([(LayerButton::Visibility, layer.visibility(), eye)])
}
fn layer_button(layer: &Placed<Layer>, [min, max]: [DVec2; 2], [resting, hover]: [&str; 2], hovered: bool, clicked: bool) -> List<Vector> {
let mut graphic = List::new();
if hovered {
graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into()));
}
let name = if hovered && !clicked { hover } else { resting };
graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.look.read_only { DISABLED_ICON } else { TEXT }));
graphic
}
fn draw_connectors_of_card(card: &Placed<Card>) -> List<Vector> {
card.inputs()
.chain(card.outputs())
.flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output, Highlight::None, 0.))
.collect()
}
#[node_macro::node(transient, memoize)]
fn draw_thick_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>, #[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>) -> List<Vector> {
settled_wires(rows.element(), wire_style.into_element(), true)
}
#[node_macro::node(transient, memoize)]
fn draw_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>, #[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>) -> List<Vector> {
settled_wires(rows.element(), wire_style.into_element(), false)
}
fn settled_wires(rows: &Rows, wire_style: WireStyle, thick: bool) -> List<Vector> {
let settled = [rows];
let no_imports_or_exports = ReplicatedMap::default();
let wires = wires_with_ends(&rows.wires, &settled, &no_imports_or_exports).filter(|(_, ends)| is_thick_wire(*ends) == thick);
wires.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect()
}
#[node_macro::node(transient, memoize)]
fn draw_loose_wires(
_: impl Ctx,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
#[scope(inputs::WIRE_IN_PROGRESS)] wire_in_progress: Item<Option<WireInProgress>>,
#[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>,
#[scope(inputs::GLIDES)] glides: Item<Glides>,
) -> List<Vector> {
let (wire_style, glides) = (wire_style.into_element(), glides.element());
let rows = [moving.element(), settled.element()];
let loose = wires_with_ends(&moving.element().wires, &rows, network_connectors.element()).filter(|(wire, _)| !glides_an_end(wire, glides));
let mut graphic = wire_in_progress.into_element().map_or_else(List::new, draw_wire_in_progress);
graphic.extend(loose.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect());
graphic
}
#[node_macro::node(transient, memoize)]
fn draw_gliding_wires(
ctx: impl Ctx + ExtractRealTime,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
#[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>,
#[scope(inputs::GLIDES)] glides: Item<Glides>,
) -> List<Vector> {
let (wire_style, glides, time) = (wire_style.into_element(), glides.element(), ctx.try_real_time().unwrap_or_default());
let rows = [moving.element(), settled.element()];
let gliding = wires_with_ends(&moving.element().wires, &rows, network_connectors.element()).filter(|(wire, _)| glides_an_end(wire, glides));
let glided = gliding.flat_map(|(wire, [mut from, mut to])| {
from.position += glides.offset(wire.from, time);
to.position += glides.offset(wire.to, time);
draw_wire(wire, [from, to], wire_style)
});
glided.collect()
}
fn glides_an_end(wire: &Wire, glides: &Glides) -> bool {
[Glided::from(wire.from), Glided::from(wire.to)].iter().any(|end| glides.rows.contains_key(end))
}
fn wires_with_ends<'a>(wires: &'a ReplicatedMap<Wire>, rows: &'a [&'a Rows], network_connectors: &'a ReplicatedMap<NetworkConnector>) -> impl Iterator<Item = (&'a Wire, [WireEnd; 2])> {
wires.iter().filter_map(move |wire| Some((wire, wire_ends(wire, rows, network_connectors)?)))
}
fn draw_wire(wire: &Wire, ends: [WireEnd; 2], wire_style: WireStyle) -> List<Vector> {
let [bright, dim] = data_type_colors(wire.data_type);
let previewed = wire.key == WireKey::Preview;
let color = if previewed || wire.insertion_target { bright } else { dim };
let stroke = |path: &BezPath, width: f64, color: SRGBA8| painted(Vector::item_from_bezpath(path), Coverage::new_stroke(&Stroke::new(width)), color.into());
let drawn = |path: &BezPath| if previewed { flattened(&dashed(path, WIRE_DASHES)) } else { flattened(path) };
let path = drawn(&route(ends, wire_style));
if is_thick_wire(ends) {
let center_line = build_thick_wire_center_line(ends, wire_style);
List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(&center_line), WIRE_WIDTH, WIRE_SPLIT)])
} else if wire.list {
List::from_iter([stroke(&path, LIST_WIRE_WIDTH, color), stroke(&path, WIRE_WIDTH, WIRE_SPLIT)])
} else {
List::new_from_item(stroke(&path, WIRE_WIDTH, color))
}
}
fn draw_wire_in_progress(wire: WireInProgress) -> List<Vector> {
let path = route(wire.ends, WireStyle::Direct);
if path.elements().len() != 4 {
return List::new();
}
let [_, dim] = data_type_colors(wire.data_type);
let path = flattened(&path);
List::new_from_item(painted(Vector::item_from_bezpath(&path), Coverage::new_stroke(&Stroke::new(WIRE_WIDTH)), dim.into()))
}
fn flattened(path: &BezPath) -> BezPath {
let mut lines = BezPath::new();
flatten(path, WIRE_FLATTENING_TOLERANCE, |element| lines.push(element));
lines
}
#[node_macro::node(transient, memoize)]
fn draw_cards(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> Result<List<Vector>, TextToVectorError> {
joined(cards(rows.element()))
}
fn cards(rows: &Rows) -> impl Iterator<Item = Result<(NodeId, List<Vector>), TextToVectorError>> {
let mut labels = Labels::default();
rows.cards.iter().map(move |card| Ok((card.look.key, draw_card(card, &mut labels)?)))
}
fn draw_card(card: &Placed<Card>, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
let [min, max] = card.body();
let (card_color, text_color) = if card.look.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) };
let body = rounded_rect(min, max, [CARD_RADIUS; 4]);
graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY)));
let (header_tint, rows_tint) = match card.look.selection {
Selection::None => (0.05, 0.),
Selection::Inactive => (0.15, 0.1),
Selection::Active => (0.2, 0.15),
};
let header_bottom = if card.rows() == 1 { CARD_RADIUS } else { 0. };
let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [CARD_RADIUS, CARD_RADIUS, header_bottom, header_bottom]);
graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint)));
if card.look.selection != Selection::None && card.rows() > 1 {
let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., CARD_RADIUS, CARD_RADIUS]);
graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint)));
}
graphic.extend(icon(card.look.icon, min + DVec2::new(CARD_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color));
let name = labels.label(&card.look.name, CARD_NAME_MAX_WIDTH)?;
graphic.extend(text(&name.outline, min + DVec2::new(CARD_NAME_LEFT, 0.), text_color));
let width = max.x - min.x;
for row in 1..card.rows() as usize {
let (input, output) = (card.look.secondary_inputs.get(row - 1), card.look.secondary_outputs.get(row - 1));
let Some(connector) = input.or(output) else { continue };
let name = labels.label(&connector.name, width - 2. * CARD_ROW_PADDING)?;
let left = if input.is_some() { CARD_ROW_PADDING } else { width - CARD_ROW_PADDING - name.width };
graphic.extend(text(&name.outline, min + DVec2::new(left, row as f64 * GRID_SIZE), text_color));
}
let border_color = if card.look.previewed { PREVIEWED_BORDER } else { BORDER };
let gap = |edge: f64, (top_left, _): (DVec2, &Connector)| {
let center = DVec2::new(edge, top_left.y + CONNECTOR_SIZE / 2.);
[center - CONNECTOR_GAP / 2., center + CONNECTOR_GAP / 2.]
};
let gaps: Vec<[DVec2; 2]> = card.inputs().map(|input| gap(min.x, input)).chain(card.outputs().map(|output| gap(max.x, output))).collect();
let border = Vector::item_from_bezpath(&border(min, max, CARD_RADIUS, &gaps, card.look.previewed));
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
Ok(graphic)
}
#[node_macro::node(transient, memoize)]
fn draw_dots(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
dots(rows.element()).flat_map(|(_, graphic)| graphic).collect()
}
fn dots(rows: &Rows) -> impl Iterator<Item = (NodeId, List<Vector>)> {
rows.dots.iter().map(|dot| (dot.look.key, draw_dot(dot, [Highlight::None; 2])))
}
#[node_macro::node(transient, memoize)]
fn draw_moving(_: impl Ctx, #[scope(inputs::MOVING)] moving: Item<Rows>, #[scope(inputs::THUMBNAILS)] thumbnails: Item<Thumbnails>) -> Result<List<Vector>, TextToVectorError> {
let moving = moving.element();
let keyed = |(key, graphic): (NodeId, List<Vector>)| tagged(graphic, key);
let mut graphic = List::new();
for row in layers(moving) {
graphic.extend(keyed(row?));
}
for (key, thumbnail) in layer_thumbnails(thumbnails.element(), moving) {
graphic.extend(keyed((key, List::new_from_item(thumbnail))));
}
for row in cards(moving) {
graphic.extend(keyed(row?));
}
for row in dots(moving) {
graphic.extend(keyed(row));
}
for row in raised(moving) {
graphic.extend(keyed(row));
}
Ok(graphic)
}
#[node_macro::node(transient, memoize)]
fn glide(ctx: impl Ctx + ExtractRealTime, drawing: List<Vector>, #[scope(inputs::GLIDES)] glides: Item<Glides>) -> List<Vector> {
let (glides, time) = (glides.element(), ctx.try_real_time().unwrap_or_default());
let offset = |row: Option<Glided>| row.map_or(DVec2::ZERO, |row| glides.offset(row, time));
let offsets: Vec<DVec2> = drawing.iter_attribute_values_or_default::<Option<Glided>>(ATTR_GLIDED).map(offset).collect();
let mut glided = drawing;
glided.remove_attribute(ATTR_GLIDED);
for (transform, offset) in glided.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).zip(offsets) {
if offset != DVec2::ZERO {
*transform = DAffine2::from_translation(offset) * *transform;
}
}
glided
}
fn tagged(mut graphic: List<Vector>, row: impl Into<Glided>) -> List<Vector> {
graphic.set_attribute_values(ATTR_GLIDED, vec![Some(row.into()); graphic.len()]);
graphic
}
fn draw_dot(dot: &Placed<Dot>, [highlight, output_highlight]: [Highlight; 2]) -> List<Vector> {
let [wired, unwired] = data_type_colors(dot.look.data_type);
let center = dot.center();
let grown = highlight.is_grown();
let scale = if grown { HOVERED_CONNECTOR_SCALE } else { 1. };
let circle = |radius: f64| Vector::item_from_bezpath(&Circle::new((center.x, center.y), radius * scale).to_path(CIRCLE_TOLERANCE));
let output_shown = output_highlight != Highlight::None;
let fill = if dot.look.wired && !output_shown { wired } else { unwired };
let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into()));
let resting = [highlight, output_highlight] == [Highlight::None; 2];
if grown {
let offset = if dot.look.previewed { DOT_PREVIEWED_RING_OFFSET } else { 0. };
let ring = circle(DOT_RADIUS + offset + DOT_HOVERED_RING / 2.);
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_HOVERED_RING * scale)), unwired.into()));
} else if resting && dot.look.previewed {
let radius = DOT_RADIUS + DOT_PREVIEWED_RING_OFFSET + BORDER_WIDTH;
let ring = Vector::item_from_bezpath(&border(center - radius, center + radius, radius, &[], true));
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), wired.into()));
} else if resting && dot.look.selected {
let ring = circle(DOT_RADIUS + DOT_SELECTED_RING / 2.);
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_SELECTED_RING)), Color::WHITE.with_alpha(SELECTED_DOT_RING_OPACITY)));
}
if output_shown {
let grown = if output_highlight.is_grown() { 1. } else { 0. };
graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.look.data_type, true, output_highlight, grown));
}
graphic
}
#[node_macro::node(transient, memoize)]
fn draw_errors(
_: impl Ctx,
#[scope(inputs::ERRORS)] errors: Item<ReplicatedMap<ErrorBadge>>,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
) -> Result<List<Vector>, TextToVectorError> {
let rows = [moving.element(), settled.element()];
badges_with_anchors(errors.element().iter(), rows)
.map(|(error, anchor)| draw_error(error, anchor, false).map(|badge| badge.with_attribute(ATTR_GLIDED, Some(Glided::from(error.key)))))
.collect()
}
fn badges_with_anchors<'a>(errors: impl Iterator<Item = &'a ErrorBadge>, rows: [&'a Rows; 2]) -> impl Iterator<Item = (&'a ErrorBadge, DVec2)> {
errors.filter_map(move |error| Some((error, node_geometry(&rows, &error.key)?.error_badge_anchor())))
}
fn draw_error(error: &ErrorBadge, anchor: DVec2, hovered: bool) -> Result<Item<Vector>, TextToVectorError> {
let text_size = error_text_size(&error.text);
let [min, max] = error_badge::body(anchor, text_size);
let mut badge = List::new_from_item(painted(rounded_rect(min, max, [ERROR_RADIUS; 4]), Coverage::new_fill(), ERROR_RED.into()));
let corners = error_badge::tail(anchor);
let mut tail = BezPath::new();
tail.move_to((corners[0].x, corners[0].y));
for corner in &corners[1..] {
tail.line_to((corner.x, corner.y));
}
tail.close_path();
badge.push(painted(Vector::item_from_bezpath(&tail), Coverage::new_fill(), ERROR_RED.into()));
let outline = paragraph_outline(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?;
badge.extend(text(&outline, error_badge::text_top_left(anchor, text_size), ERROR_TEXT));
let mut grouped = rounded_rect(min, corners.into_iter().fold(max, DVec2::max), [0.; 4]);
stamp_coverage(&mut grouped, Coverage::new_fill(), Graphic::VectorList(badge), CoverPlacement::Above);
if !hovered {
grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY);
}
Ok(grouped)
}
#[node_macro::node(transient, memoize)]
fn draw_network_connectors(_: impl Ctx, #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>) -> Result<List<Vector>, TextToVectorError> {
let mut labels = Labels::default();
let mut graphic = List::new();
for row in network_connectors.element() {
graphic.extend(tagged(draw_network_connector(row, &mut labels)?, row.key));
}
Ok(graphic)
}
fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = row_connector(row, Highlight::None, 0.);
let Some(entry) = &row.connector else { return Ok(graphic) };
let name = labels.label(&entry.name, f64::INFINITY)?;
if !row.renaming {
let [top_left, _] = row.name_box(name.width);
graphic.extend(text(&name.outline, top_left, TEXT));
}
if row.editable && row.key.index() < 2 {
let [min, max] = row.separator(name.width);
graphic.push(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), SEPARATOR.into()));
}
Ok(graphic)
}
fn row_connector(row: &NetworkConnector, highlight: Highlight, grown: f64) -> List<Vector> {
match &row.connector {
Some(entry) => connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry, highlight, grown),
None => drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, highlight, grown),
}
}
#[node_macro::node(transient, memoize)]
fn draw_highlights(
_: impl Ctx,
#[scope(inputs::HIGHLIGHTS)] highlights: Item<Highlights>,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
#[scope(inputs::ERRORS)] errors: Item<ReplicatedMap<ErrorBadge>>,
) -> Result<List<Vector>, TextToVectorError> {
let highlights = highlights.element();
let rows = [moving.element(), settled.element()];
let mut graphic = List::new();
for dot in rows.iter().flat_map(|rows| &rows.dots) {
let looks = highlights.dot(dot.look.key);
if looks != [Highlight::None; 2] {
graphic.extend(tagged(draw_dot(dot, looks), dot.look.key));
}
}
let connectors: BTreeSet<ConnectorKey> = highlights.connectors().filter(|key| !highlights.grows.contains_key(key)).collect();
for key in connectors {
let highlight = highlights.connector(key);
if highlight == Highlight::None {
continue;
}
let grown = if highlight.is_grown() { 1. } else { 0. };
if let Some(drawn) = highlighted_connector(key, highlight, grown, rows, network_connectors.element()) {
graphic.extend(tagged(drawn, key));
}
}
for layer in rows.iter().flat_map(|rows| &rows.layers) {
let key = layer.look.key;
match highlights.layer_button(key) {
Some(LayerButton::Grip) => graphic.extend(tagged(grip(layer, true), key)),
Some(hovered) if !layer.look.read_only => {
for (_, place, icons) in layer_buttons(layer).filter(|(button, ..)| *button == hovered) {
graphic.extend(tagged(layer_button(layer, place, icons, true, highlights.clicked), key));
}
}
_ => {}
}
}
let hovered = errors.element().iter().filter(|error| highlights.badge_hovered(error.key));
for (error, anchor) in badges_with_anchors(hovered, rows) {
graphic.push(draw_error(error, anchor, true)?.with_attribute(ATTR_GLIDED, Some(Glided::from(error.key))));
}
Ok(graphic)
}
#[node_macro::node(transient, memoize)]
fn draw_grows(
ctx: impl Ctx + ExtractRealTime,
#[scope(inputs::HIGHLIGHTS)] highlights: Item<Highlights>,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
) -> List<Vector> {
let (highlights, time) = (highlights.element(), ctx.try_real_time().unwrap_or_default());
let rows = [moving.element(), settled.element()];
let mut graphic = List::new();
for &key in highlights.grows.keys() {
let (highlight, grown) = (highlights.connector(key), highlights.grown(key, time));
if highlight == Highlight::None && grown == 0. {
continue;
}
if let Some(drawn) = highlighted_connector(key, highlight, grown, rows, network_connectors.element()) {
graphic.extend(tagged(drawn, key));
}
}
graphic
}
fn highlighted_connector(key: ConnectorKey, highlight: Highlight, grown: f64, rows: [&Rows; 2], network_connectors: &ReplicatedMap<NetworkConnector>) -> Option<List<Vector>> {
let card = |node| rows.into_iter().find_map(|rows| rows.cards.get(&node));
let layer = |node| rows.into_iter().find_map(|rows| rows.layers.get(&node));
let indexed = |index: usize| move |found: &&Connector| found.index as usize == index;
let on_card = |(top_left, found): (DVec2, &Connector)| connector(&CONNECTOR_OUTLINE, top_left, found, highlight, grown);
match key {
ConnectorKey::Input(InputKey::Node { node, index }) => {
if let Some(card) = card(node) {
return card.inputs().find(|(_, input)| indexed(index)(input)).map(on_card);
}
let layer = layer(node)?;
if let Some(input) = layer.look.primary_input.as_ref().filter(indexed(index)) {
return Some(stack_input(layer, input, highlight, grown));
}
let input = layer.look.secondary_input.as_ref().filter(indexed(index))?;
Some(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, highlight, grown))
}
ConnectorKey::Output(OutputKey::Node { node, index }) => {
if let Some(card) = card(node) {
return card.outputs().find(|(_, output)| indexed(index)(output)).map(on_card);
}
let layer = layer(node)?;
layer.look.primary_output.as_ref().filter(indexed(index)).map(|output| stack_output(layer, output, highlight, grown))
}
ConnectorKey::Input(InputKey::Export(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Export(index))?, highlight, grown)),
ConnectorKey::Output(OutputKey::Import(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Import(index))?, highlight, grown)),
}
}
#[node_macro::node(transient)]
fn draw_reorder_bar(_: impl Ctx, #[scope(inputs::REORDER_BAR)] reorder_bar: Item<Option<(NetworkConnectorKind, DVec2)>>) -> List<Vector> {
let Some((kind, anchor)) = reorder_bar.into_element() else { return List::new() };
let [min, max] = network_connector::reorder_bar(kind, anchor);
List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE))
}
#[node_macro::node(transient)]
fn draw_box_selection(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::BOX_SELECTION)] box_selection: Item<Option<[DVec2; 2]>>) -> List<Vector> {
let Some([start, end]) = box_selection.into_element() else { return List::new() };
let min = start.min(end);
let max = min + (end - start).abs() + 2. * BORDER_WIDTH;
let fill = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::from(BOX_SELECTION).with_alpha(BOX_SELECTION_FILL_OPACITY));
let [inner_min, inner_max] = [min + BORDER_WIDTH / 2., max - BORDER_WIDTH / 2.];
let outline = Rect::new(inner_min.x, inner_min.y, inner_max.x, inner_max.y).to_path(0.);
let border = painted(Vector::item_from_bezpath(&outline), Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BOX_SELECTION.into());
let (view, _) = view_and_device_scale(&ctx);
let mut selection = List::from_iter([fill, border]);
selection.left_apply_transform(&view.inverse());
selection
}
@@ -1,72 +1,15 @@
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use crate::geometry::{WireEnd, is_thick_wire};
use crate::metrics::GRID_SIZE;
use crate::wire::WireStyle;
use glam::{DVec2, IVec2};
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
use graphene_std::vector::misc::dvec2_to_point;
use vello_gpu::kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WirePath {
#[serde(rename = "pathString")]
pub path_string: String,
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
pub thick: bool,
pub dashed: bool,
// A rank-1 `List<T>` wire renders as a doubled-up pair of parallel lines to distinguish it from a rank-0 `Item<T>` wire
#[serde(rename = "isList")]
pub is_list: bool,
// A thick wire's center line reaches past the wire into the cleaved connector slots, so it needs its own longer path; empty otherwise
#[serde(rename = "centerPathString")]
pub center_path_string: String,
}
pub fn route(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath {
let [output_position, input_position] = ends.map(|end| end.position);
let [vertical_out, vertical_in] = ends.map(|end| end.vertical);
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WirePathUpdate {
pub id: NodeId,
#[serde(rename = "inputIndex")]
pub input_index: usize,
// If none, then remove the wire from the map
#[serde(rename = "wirePathUpdate")]
pub wire_path_update: Option<WirePath>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Copy, Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub enum GraphWireStyle {
#[default]
Direct = 0,
GridAligned = 1,
}
impl std::fmt::Display for GraphWireStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GraphWireStyle::GridAligned => write!(f, "Grid-Aligned"),
GraphWireStyle::Direct => write!(f, "Direct"),
}
}
}
impl GraphWireStyle {
pub fn tooltip_description(&self) -> &'static str {
match self {
GraphWireStyle::GridAligned => "Wires follow the grid, running in straight lines between nodes.",
GraphWireStyle::Direct => "Wires bend to run at an angle directly between nodes.",
}
}
pub fn is_direct(&self) -> bool {
*self == GraphWireStyle::Direct
}
}
pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
let grid_spacing = 24.;
// A thick layer-stack wire (vertical at both ends) is skipped across a single straight grid cell where its connectors
// already meet, and otherwise trimmed 3px inward at each end since it overshoots the connectors.
let (output_position, input_position) = if vertical_out && vertical_in {
let (output_position, input_position) = if is_thick_wire(ends) {
if thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
@@ -76,12 +19,12 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
(output_position, input_position)
};
match graph_wire_style {
GraphWireStyle::Direct => {
match wire_style {
WireStyle::Direct => {
let horizontal_gap = (output_position.x - input_position.x).abs();
let vertical_gap = (output_position.y - input_position.y).abs();
let curve_length = grid_spacing;
let curve_length = GRID_SIZE;
let curve_falloff_rate = curve_length * std::f64::consts::TAU;
let horizontal_curve_amount = -(2_f64.powf((-10. * horizontal_gap) / curve_falloff_rate)) + 1.;
@@ -113,7 +56,7 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
wire.line_to(dvec2_to_point(locations[3]));
wire
}
GraphWireStyle::GridAligned => {
WireStyle::GridAligned => {
let locations = straight_wire_path(output_position, input_position, vertical_out, vertical_in);
straight_wire_to_bezpath(locations)
}
@@ -121,18 +64,18 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
}
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
let grid_spacing = 24.;
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= GRID_SIZE
}
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots.
pub(crate) fn build_thick_wire_center_line(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath {
let [output_position, input_position] = ends.map(|end| end.position);
if thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
let wire = route(ends, wire_style);
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
return BezPath::new();
};
@@ -150,7 +93,7 @@ pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec
}
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
let grid_spacing = 24;
let grid_spacing = GRID_SIZE as i32;
let line_width = 2;
let in_x = input_position.x.floor() as i32;
@@ -224,10 +167,6 @@ fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_ou
IVec2::new(x4, y3),
];
if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)];
}
// `outConnector` point and `inConnector` point lying on the same horizontal grid line and `outConnector` point lies to the right of `inConnector` point
if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)];
@@ -580,57 +519,3 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
path.line_to(to_point(*locations.last().unwrap()));
path
}
#[cfg(test)]
mod tests {
use super::*;
use kurbo::{Affine, ParamCurveNearest};
#[test]
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
let ends = [
(DVec2::new(120., 24.), DVec2::new(480., 96.), false, false),
(DVec2::new(-120., 48.), DVec2::new(240., -72.), false, false),
(DVec2::new(48., -8.), DVec2::new(48., 104.), true, true),
(DVec2::new(-312., 200.), DVec2::new(-24., 24.), true, false),
(DVec2::new(600., 24.), DVec2::new(-96., 48.), false, true),
(DVec2::new(130.5, 31.25), DVec2::new(-410.75, 77.5), false, false),
];
let shifts = [DVec2::new(-24. * 50., 24. * 37.), DVec2::new(24. * 13., -24. * 90.), DVec2::new(-24., -24.)];
for (output, input, vertical_out, vertical_in) in ends {
let wire = build_vector_wire(output, input, vertical_out, vertical_in, GraphWireStyle::GridAligned);
for shift in shifts {
let shifted = build_vector_wire(output + shift, input + shift, vertical_out, vertical_in, GraphWireStyle::GridAligned);
let moved = Affine::translate(Vec2::new(shift.x, shift.y)) * wire.clone();
assert_eq!(shifted, moved, "the wire from {output} to {input} should keep its shape when moved by {shift}");
}
}
}
#[test]
fn the_center_line_of_a_stack_wire_runs_inside_it() {
let ends = [
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
];
let half_wire_width = 4.;
for (output, input) in ends {
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
let wire = build_vector_wire(output, input, true, true, style);
let center_line = build_thick_wire_center_line(output, input, true, true, style);
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
for sample in samples {
let distance = wire
.segments()
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
.fold(f64::INFINITY, f64::min);
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
}
}
}
}
}
+86
View File
@@ -0,0 +1,86 @@
use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, GRID_SIZE, TEXT_SIZE};
use core_types::list::{ATTR_GEOMETRY_CACHE, List};
use glam::DVec2;
use graphic_types::Vector;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use text_nodes::{FALLBACK_FONT_RESOURCE, TextToVectorError, TypesettingConfig};
use vector_types::vector::GeometryCache;
#[derive(Debug)]
pub struct Label {
pub outline: List<Vector>,
pub width: f64,
}
#[derive(Debug, Default)]
pub struct Labels(HashMap<(String, u64), Label>);
impl Labels {
pub fn label(&mut self, text: &str, max_width: f64) -> Result<&Label, TextToVectorError> {
match self.0.entry((text.to_string(), max_width.to_bits())) {
Entry::Occupied(label) => Ok(label.into_mut()),
Entry::Vacant(label) => {
let text = ellipsized(text, max_width);
let (outline, width) = (outline(&text)?, label_width(&text));
Ok(label.insert(Label { outline, width }))
}
}
}
}
pub fn label_width(text: &str) -> f64 {
text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x
}
fn ellipsized(text: &str, max_width: f64) -> String {
if label_width(text) <= max_width {
return text.to_string();
}
let cut = |end: usize| format!("{}…", &text[..end]);
let ends: Vec<usize> = text.char_indices().map(|(end, _)| end).collect();
let fitting = ends.partition_point(|&end| label_width(&cut(end)) <= max_width);
cut(ends[fitting.saturating_sub(1)])
}
fn outline(text: &str) -> Result<List<Vector>, TextToVectorError> {
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).map(with_geometry_caches)
}
fn with_geometry_caches(mut outline: List<Vector>) -> List<Vector> {
for index in 0..outline.len() {
outline.set_attribute(ATTR_GEOMETRY_CACHE, index, GeometryCache::default());
}
outline
}
pub fn paragraph_size(text: &str, line_height: f64, max_width: f64) -> DVec2 {
let unwrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, None), true);
let wrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), true);
DVec2::new(unwrapped.x.min(max_width), wrapped.y)
}
pub fn error_text_size(text: &str) -> DVec2 {
paragraph_size(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)
}
pub fn paragraph_outline(text: &str, line_height: f64, max_width: f64) -> Result<List<Vector>, TextToVectorError> {
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), false).map(with_geometry_caches)
}
fn typesetting() -> TypesettingConfig {
TypesettingConfig {
font_size: TEXT_SIZE,
line_height_ratio: GRID_SIZE / TEXT_SIZE,
..Default::default()
}
}
fn paragraph_typesetting(line_height: f64, max_width: Option<f64>) -> TypesettingConfig {
TypesettingConfig {
font_size: TEXT_SIZE,
line_height_ratio: line_height / TEXT_SIZE,
max_width,
..Default::default()
}
}
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "graph-ui-types"
description = "The rows, scene and metrics of the node graph UI"
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
[features]
serde = ["dep:serde"]
wasm = ["dep:tsify", "dep:wasm-bindgen"]
[dependencies]
# Local dependencies
core-types = { workspace = true }
dyn-any = { workspace = true }
graph-layout = { workspace = true }
graphene-hash = { workspace = true }
graphic-types = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
serde = { workspace = true, optional = true }
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
+137
View File
@@ -0,0 +1,137 @@
use crate::highlights::ConnectorKey;
use crate::network_connector::NetworkConnectorKey;
use crate::wire::{InputKey, OutputKey};
use core_types::uuid::NodeId;
use dyn_any::DynAny;
use glam::DVec2;
use graphene_hash::CacheHash;
use std::collections::BTreeMap;
use std::ops::{Add, Mul, Sub};
pub const GROW_DURATION: f64 = 100.;
const GLIDE_TIME_CONSTANT: f64 = 30.;
const GLIDE_END_DISTANCE: f64 = 0.5;
const EASE: [f64; 4] = [0.25, 0.1, 0.25, 1.];
const EASE_STEPS: usize = 40;
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub struct Animation<T> {
pub from: T,
pub to: T,
pub start: f64,
pub end: f64,
}
#[derive(Clone, Copy, Debug)]
pub enum Curve {
Glide,
Ease,
}
impl<T: Copy + Add<Output = T> + Sub<Output = T> + Mul<f64, Output = T>> Animation<T> {
pub fn at(&self, time: f64, curve: Curve) -> T {
if time >= self.end {
return self.to;
}
if time <= self.start {
return self.from;
}
let duration = self.end - self.start;
let fraction = (time - self.start) / duration;
let progress = match curve {
Curve::Glide => {
let rate = duration / GLIDE_TIME_CONSTANT;
(1. - (-rate * fraction).exp()) / (1. - (-rate).exp())
}
Curve::Ease => ease(fraction),
};
self.from + (self.to - self.from) * progress
}
}
impl Animation<DVec2> {
pub fn glide(from: DVec2, start: f64) -> Option<Self> {
let distance = from.length();
(distance > GLIDE_END_DISTANCE).then(|| Self {
from,
to: DVec2::ZERO,
start,
end: start + GLIDE_TIME_CONSTANT * (distance / GLIDE_END_DISTANCE).ln(),
})
}
}
fn ease(fraction: f64) -> f64 {
let [x1, y1, x2, y2] = EASE;
let bezier = |s: f64, first: f64, second: f64| 3. * (1. - s) * (1. - s) * s * first + 3. * (1. - s) * s * s * second + s * s * s;
let [mut low, mut high] = [0., 1.];
for _ in 0..EASE_STEPS {
let middle = (low + high) / 2.;
if bezier(middle, x1, x2) < fraction {
low = middle;
} else {
high = middle;
}
}
bezier((low + high) / 2., y1, y2)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum Glided {
Node(NodeId),
Imports,
Exports,
}
impl From<NodeId> for Glided {
fn from(node: NodeId) -> Self {
Self::Node(node)
}
}
impl From<OutputKey> for Glided {
fn from(output: OutputKey) -> Self {
match output {
OutputKey::Node { node, .. } => Self::Node(node),
OutputKey::Import(_) => Self::Imports,
}
}
}
impl From<InputKey> for Glided {
fn from(input: InputKey) -> Self {
match input {
InputKey::Node { node, .. } => Self::Node(node),
InputKey::Export(_) => Self::Exports,
}
}
}
impl From<NetworkConnectorKey> for Glided {
fn from(key: NetworkConnectorKey) -> Self {
match key {
NetworkConnectorKey::Import(_) => Self::Imports,
NetworkConnectorKey::Export(_) => Self::Exports,
}
}
}
impl From<ConnectorKey> for Glided {
fn from(key: ConnectorKey) -> Self {
match key {
ConnectorKey::Input(input) => input.into(),
ConnectorKey::Output(output) => output.into(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)]
pub struct Glides {
pub rows: BTreeMap<Glided, Animation<DVec2>>,
}
impl Glides {
pub fn offset(&self, row: impl Into<Glided>, time: f64) -> DVec2 {
self.rows.get(&row.into()).map_or(DVec2::ZERO, |glide| glide.at(time, Curve::Glide))
}
}
+56
View File
@@ -0,0 +1,56 @@
use crate::geometry::NodeShape;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Card {
pub key: NodeId,
pub shape: NodeShape,
pub name: String,
pub icon: &'static str,
pub primary_input: Option<Connector>,
pub primary_output: Option<Connector>,
pub secondary_inputs: Vec<Connector>,
pub secondary_outputs: Vec<Connector>,
pub selection: Selection,
pub visible: bool,
pub previewed: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub enum Selection {
None,
Inactive,
Active,
}
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Connector {
pub index: u32,
pub name: String,
pub data_type: DataType,
pub connected: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub enum DataType {
General,
Number,
Artboard,
Graphic,
Raster,
Vector,
Color,
Gradient,
Typography,
Invalid,
}
impl Keyed for Card {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
+23
View File
@@ -0,0 +1,23 @@
use crate::card::DataType;
use crate::geometry::NodeShape;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Dot {
pub key: NodeId,
pub shape: NodeShape,
pub data_type: DataType,
pub wired: bool,
pub selected: bool,
pub previewed: bool,
}
impl Keyed for Dot {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
@@ -0,0 +1,40 @@
use crate::metrics::{ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE};
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use glam::DVec2;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct ErrorBadge {
pub key: NodeId,
pub text: String,
}
impl Keyed for ErrorBadge {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
pub fn body(anchor: DVec2, text_size: DVec2) -> [DVec2; 2] {
let size = text_size + 2. * ERROR_PADDING;
[anchor - DVec2::Y * size.y, anchor + DVec2::X * size.x]
}
pub fn text_top_left(anchor: DVec2, text_size: DVec2) -> DVec2 {
let [top_left, _] = body(anchor, text_size);
top_left + ERROR_PADDING
}
pub fn tail(anchor: DVec2) -> [DVec2; 3] {
let top_left = anchor + DVec2::X * ERROR_TAIL_LEFT;
[top_left, top_left + DVec2::X * ERROR_TAIL_SIZE.x, top_left + DVec2::new(ERROR_TAIL_SIZE.x / 2., ERROR_TAIL_SIZE.y)]
}
pub fn covers(anchor: DVec2, text_size: DVec2, point: DVec2) -> bool {
let [tail, ..] = tail(anchor);
let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all();
within(body(anchor, text_size)) || within([tail, tail + ERROR_TAIL_SIZE])
}
+493
View File
@@ -0,0 +1,493 @@
use crate::card::{Card, Connector};
use crate::dot::Dot;
use crate::layer::Layer;
use crate::metrics::{
CLICK_RADIUS, GRID_SIZE, INPUT_CONNECTOR_OFFSET, LAYER_BUTTON_SIZE, LAYER_CLICK_RADIUS, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET,
LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, OUTPUT_CONNECTOR_OFFSET, PORT_CLICK_RADIUS, SIDE_PORT_HALF_HEIGHT, SIDE_PORT_INWARD_REACH, SIDE_PORT_OUTWARD_REACH, STACK_ANCHOR_DISTANCE,
STACK_CONNECTOR_SIZE, STACK_PORT_HALF_SIZE, WAYPOINT_GUTTER_OFFSET, WAYPOINT_GUTTER_RADIUS, WAYPOINT_HALF_SIZE,
};
use crate::network_connector::{NetworkConnector, NetworkConnectorKey};
use crate::placed::Placed;
use crate::replicated_map::ReplicatedMap;
use crate::scene::Rows;
use crate::wire::{InputKey, OutputKey, Wire};
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2, UVec2};
use graph_layout::{CHAIN_WIDTH, NodeKind};
use graphene_hash::CacheHash;
use std::ops::Range;
use std::sync::Arc;
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct NodeShape {
pub size: UVec2,
pub exposed_inputs: Arc<[usize]>,
pub outputs: u32,
pub primary_output_hidden: bool,
pub name_width: f64,
pub locked: bool,
}
impl NodeShape {
fn inputs(&self) -> u32 {
self.exposed_inputs.len() as u32
}
fn primary_input_hidden(&self) -> bool {
self.exposed_inputs.first().is_some_and(|first| *first != 0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
fn over([min, max]: [DVec2; 2], corner_radius: f64, part: Part) -> Self {
Self { min, max, corner_radius, part }
}
pub fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: PORT_CLICK_RADIUS,
part: Part::Input(input),
}
}
pub fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: PORT_CLICK_RADIUS,
part: Part::Output(output),
}
}
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub struct WireEnd {
pub position: DVec2,
pub vertical: bool,
}
pub fn is_thick_wire([from, to]: [WireEnd; 2]) -> bool {
from.vertical && to.vertical
}
#[derive(Clone, Debug)]
pub struct NodeGeometry {
pub cell: IVec2,
pub kind: NodeKind,
pub chain_length: u32,
pub shape: NodeShape,
}
impl NodeGeometry {
pub fn body(&self) -> PartTarget {
match self.kind {
NodeKind::Waypoint => PartTarget::around(self.dot_center(), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: self.top_left() - DVec2::new(self.chain_width(), 0.),
max: self.top_left() + self.size(),
corner_radius: LAYER_CLICK_RADIUS,
part: Part::Body,
},
NodeKind::Node => PartTarget::over(self.card_body(), CLICK_RADIUS, Part::Body),
}
}
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
pub fn input_end(&self, index: usize) -> Option<WireEnd> {
let position = self.input_anchor(self.place_of_input(index)?)?;
let vertical = self.kind == NodeKind::Layer && index == 0;
Some(WireEnd { position, vertical })
}
pub fn output_end(&self, index: usize) -> Option<WireEnd> {
let position = self.output_anchor(u32::try_from(index).ok()?)?;
let vertical = self.kind == NodeKind::Layer;
Some(WireEnd { position, vertical })
}
pub fn input_at(&self, place: u32) -> Option<usize> {
match self.kind {
NodeKind::Node => {
let row = place.checked_sub(self.input_rows().start)?;
self.shape.exposed_inputs.get(row as usize).copied()
}
NodeKind::Layer | NodeKind::Waypoint => Some(place as usize),
}
}
pub fn error_badge_anchor(&self) -> DVec2 {
let offset = if self.kind == NodeKind::Layer {
DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.)
} else {
DVec2::ZERO
};
self.top_left() + offset
}
fn place_of_input(&self, index: usize) -> Option<u32> {
let place = match self.kind {
NodeKind::Node => {
let row = self.shape.exposed_inputs.iter().position(|exposed| *exposed == index)?;
self.input_rows().start as usize + row
}
NodeKind::Layer | NodeKind::Waypoint => index,
};
u32::try_from(place).ok()
}
fn input_anchor(&self, place: u32) -> Option<DVec2> {
match (self.kind, place) {
(NodeKind::Waypoint, 0) => Some(self.dot_center()),
(NodeKind::Layer, 0) => Some(self.stack_input_anchor()),
(NodeKind::Layer, 1) if self.has_side_input() => Some(self.side_input_anchor()),
(NodeKind::Node, row) if self.input_rows().contains(&row) => Some(self.row_input_anchor(row)),
_ => None,
}
}
fn output_anchor(&self, place: u32) -> Option<DVec2> {
match (self.kind, place) {
(NodeKind::Waypoint, 0) => Some(self.dot_center()),
(NodeKind::Layer, 0) => Some(self.stack_output_anchor()),
(NodeKind::Node, row) if self.output_rows().contains(&row) => Some(self.row_output_anchor(row)),
_ => None,
}
}
fn card_body(&self) -> [DVec2; 2] {
let top_left = self.top_left() + DVec2::new(0., GRID_SIZE / 2.);
[top_left, top_left + self.size() - DVec2::new(0., GRID_SIZE)]
}
fn layer_body(&self) -> [DVec2; 2] {
let top_left = self.top_left();
let chain_width = self.chain_width();
let left = if chain_width > 0. { -chain_width } else { LAYER_LEFT_MARGIN };
[top_left + DVec2::X * left, top_left + self.size()]
}
fn thumbnail_block(&self) -> [DVec2; 2] {
let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN;
[left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, self.size().y)]
}
fn visibility(&self) -> [DVec2; 2] {
let [_, max] = self.layer_body();
let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.middle() - LAYER_BUTTON_SIZE / 2.);
[top_left, top_left + LAYER_BUTTON_SIZE]
}
fn grip(&self) -> [DVec2; 2] {
let [right_of_grip, _] = self.lock().unwrap_or(self.visibility());
[right_of_grip - DVec2::X * LAYER_GRIP_WIDTH, right_of_grip + DVec2::Y * LAYER_BUTTON_SIZE]
}
fn lock(&self) -> Option<[DVec2; 2]> {
let [min, max] = self.visibility();
self.shape.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE])
}
fn dot_center(&self) -> DVec2 {
self.top_left() + DVec2::new(0., GRID_SIZE)
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.dot_center();
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
for row in self.input_rows() {
visit(PartTarget::input_port(self.row_input_anchor(row), row));
}
for row in self.output_rows() {
visit(PartTarget::output_port(self.row_output_anchor(row), row));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
visit(PartTarget::around(self.stack_input_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(self.side_input_anchor(), 1));
}
visit(PartTarget::around(self.stack_output_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Output(0)));
visit(PartTarget::over(self.visibility(), CLICK_RADIUS, Part::Visibility));
if let Some(lock) = self.lock() {
visit(PartTarget::over(lock, CLICK_RADIUS, Part::Lock));
}
let [grip_min, grip_max] = self.grip();
visit(PartTarget::over([grip_min, grip_max], 0., Part::Grip));
let name_left = self.top_left().x + LAYER_NAME_LEFT;
let name_right = (name_left + self.shape.name_width).min(grip_min.x);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, grip_min.y),
max: DVec2::new(name_right, grip_max.y),
corner_radius: CLICK_RADIUS,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.cell.as_dvec2() * GRID_SIZE
}
fn size(&self) -> DVec2 {
self.shape.size.as_dvec2() * GRID_SIZE
}
fn middle(&self) -> f64 {
self.top_left().y + self.size().y / 2.
}
fn input_rows(&self) -> Range<u32> {
let first = u32::from(self.shape.primary_input_hidden());
first..first + self.shape.inputs()
}
fn output_rows(&self) -> Range<u32> {
u32::from(self.shape.primary_output_hidden)..self.shape.outputs
}
fn row_input_anchor(&self, row: u32) -> DVec2 {
self.top_left() + DVec2::new(0., GRID_SIZE * (row as f64 + 1.))
}
fn row_output_anchor(&self, row: u32) -> DVec2 {
self.top_left() + DVec2::new(self.size().x, GRID_SIZE * (row as f64 + 1.))
}
fn stack_input_anchor(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x) / 2., max.y + STACK_ANCHOR_DISTANCE)
}
fn stack_output_anchor(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x) / 2., min.y - STACK_ANCHOR_DISTANCE)
}
fn side_input_anchor(&self) -> DVec2 {
DVec2::new(self.top_left().x, self.middle())
}
fn has_side_input(&self) -> bool {
self.shape.inputs() > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() {
(self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID_SIZE
} else {
0.
}
}
}
impl Placed<Card> {
fn geometry(&self) -> NodeGeometry {
NodeGeometry {
cell: self.cell,
kind: NodeKind::Node,
chain_length: 0,
shape: self.look.shape.clone(),
}
}
pub fn body(&self) -> [DVec2; 2] {
self.geometry().card_body()
}
pub fn rows(&self) -> u32 {
self.look.shape.size.y.saturating_sub(1)
}
pub fn inputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
let geometry = self.geometry();
rows(&self.look.primary_input, &self.look.secondary_inputs).map(move |(row, input)| (geometry.row_input_anchor(row) + INPUT_CONNECTOR_OFFSET, input))
}
pub fn outputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
let geometry = self.geometry();
rows(&self.look.primary_output, &self.look.secondary_outputs).map(move |(row, output)| (geometry.row_output_anchor(row) + OUTPUT_CONNECTOR_OFFSET, output))
}
}
fn rows<'a>(primary: &'a Option<Connector>, secondary: &'a [Connector]) -> impl Iterator<Item = (u32, &'a Connector)> {
primary.iter().map(|connector| (0, connector)).chain((1..).zip(secondary))
}
impl Placed<Layer> {
fn geometry(&self) -> NodeGeometry {
NodeGeometry {
cell: self.cell,
kind: NodeKind::Layer,
chain_length: self.look.chain_length,
shape: self.look.shape.clone(),
}
}
pub fn body(&self) -> [DVec2; 2] {
self.geometry().layer_body()
}
pub fn left_input_wire(&self) -> Option<DVec2> {
let geometry = self.geometry();
let [min, _] = geometry.layer_body();
(self.look.has_left_input_wire && geometry.chain_width() > 0.).then(|| DVec2::new(min.x, geometry.middle()))
}
pub fn thumbnail_block(&self) -> [DVec2; 2] {
self.geometry().thumbnail_block()
}
pub fn thumbnail(&self) -> [DVec2; 2] {
let [min, max] = self.thumbnail_block();
[min + DVec2::X * LAYER_THUMBNAIL_MARGIN, max - DVec2::X * LAYER_THUMBNAIL_MARGIN]
}
pub fn thumbnail_image(&self) -> [DVec2; 2] {
let [min, max] = self.thumbnail();
[min + LAYER_THUMBNAIL_IMAGE_INSET, max - LAYER_THUMBNAIL_IMAGE_INSET]
}
pub fn stack_output(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., min.y - STACK_CONNECTOR_SIZE.y)
}
pub fn stack_input(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., max.y)
}
pub fn secondary_input_connector(&self) -> DVec2 {
self.geometry().side_input_anchor() + INPUT_CONNECTOR_OFFSET
}
pub fn name_box(&self) -> [DVec2; 2] {
let geometry = self.geometry();
let top_left = DVec2::new(geometry.top_left().x + LAYER_NAME_LEFT, geometry.middle() - GRID_SIZE / 2.);
[top_left, top_left + DVec2::new(geometry.size().x - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN, GRID_SIZE)]
}
pub fn visibility(&self) -> [DVec2; 2] {
self.geometry().visibility()
}
pub fn grip(&self) -> [DVec2; 2] {
self.geometry().grip()
}
pub fn lock(&self) -> Option<[DVec2; 2]> {
self.geometry().lock()
}
}
impl Placed<Dot> {
fn geometry(&self) -> NodeGeometry {
NodeGeometry {
cell: self.cell,
kind: NodeKind::Waypoint,
chain_length: 0,
shape: self.look.shape.clone(),
}
}
pub fn center(&self) -> DVec2 {
self.geometry().dot_center()
}
}
impl Rows {
fn geometry(&self, node: &NodeId) -> Option<NodeGeometry> {
let card = || self.cards.get(node).map(Placed::<Card>::geometry);
let layer = || self.layers.get(node).map(Placed::<Layer>::geometry);
let dot = || self.dots.get(node).map(Placed::<Dot>::geometry);
card().or_else(layer).or_else(dot)
}
}
pub fn node_geometry(rows: &[&Rows], node: &NodeId) -> Option<NodeGeometry> {
rows.iter().find_map(|rows| rows.geometry(node))
}
pub fn wire_ends(wire: &Wire, rows: &[&Rows], network_connectors: &ReplicatedMap<NetworkConnector>) -> Option<[WireEnd; 2]> {
let from = match wire.from {
OutputKey::Node { node, index } => node_geometry(rows, &node)?.output_end(index)?,
OutputKey::Import(index) => network_connectors.get(&NetworkConnectorKey::Import(index))?.wire_end()?,
};
let to = match wire.to {
InputKey::Node { node, index } => node_geometry(rows, &node)?.input_end(index)?,
InputKey::Export(index) => network_connectors.get(&NetworkConnectorKey::Export(index))?.wire_end()?,
};
Some([from, to])
}
+111
View File
@@ -0,0 +1,111 @@
use crate::animation::{Animation, Curve};
use crate::layer::LayerButton;
use crate::wire::{InputKey, OutputKey};
use core_types::uuid::NodeId;
use dyn_any::DynAny;
use graphene_hash::CacheHash;
use std::collections::BTreeMap;
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub enum Highlight {
#[default]
None,
Hovered,
WireSource,
WireTarget,
}
impl Highlight {
pub fn is_grown(self) -> bool {
matches!(self, Self::Hovered | Self::WireTarget)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum ConnectorKey {
Input(InputKey),
Output(OutputKey),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, CacheHash)]
pub enum NodePart {
Dot(NodeId),
DotOutput(NodeId),
Visibility(NodeId),
Lock(NodeId),
Grip(NodeId),
ErrorBadge(NodeId),
}
#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)]
pub struct Highlights {
pub hovered_connector: Option<ConnectorKey>,
pub dragged_from: Option<ConnectorKey>,
pub snapped_to: Option<ConnectorKey>,
pub hovered_part: Option<NodePart>,
pub pressed_part: Option<NodePart>,
pub clicked: bool,
pub grows: BTreeMap<ConnectorKey, Animation<f64>>,
}
impl Highlights {
pub fn dot(&self, dot: NodeId) -> [Highlight; 2] {
let ends = [
ConnectorKey::Input(InputKey::Node { node: dot, index: 0 }),
ConnectorKey::Output(OutputKey::Node { node: dot, index: 0 }),
];
let body = if self.snapped_to.is_some_and(|key| ends.contains(&key)) {
Highlight::WireTarget
} else if [self.hovered_part, self.pressed_part].contains(&Some(NodePart::Dot(dot))) {
Highlight::Hovered
} else {
Highlight::None
};
let output = if self.dragged_from.is_some_and(|key| ends.contains(&key)) {
Highlight::WireSource
} else if self.hovered_part == Some(NodePart::DotOutput(dot)) {
Highlight::Hovered
} else {
Highlight::None
};
[body, output]
}
pub fn layer_button(&self, layer: NodeId) -> Option<LayerButton> {
match self.hovered_part? {
NodePart::Visibility(node) if node == layer => Some(LayerButton::Visibility),
NodePart::Lock(node) if node == layer => Some(LayerButton::Lock),
NodePart::Grip(node) if node == layer => Some(LayerButton::Grip),
_ => None,
}
}
pub fn connector(&self, key: ConnectorKey) -> Highlight {
let key = Some(key);
if key == self.snapped_to {
Highlight::WireTarget
} else if key == self.hovered_connector {
Highlight::Hovered
} else if key == self.dragged_from {
Highlight::WireSource
} else {
Highlight::None
}
}
pub fn connectors(&self) -> impl Iterator<Item = ConnectorKey> {
[self.hovered_connector, self.dragged_from, self.snapped_to].into_iter().flatten().chain(self.grows.keys().copied())
}
pub fn grown(&self, key: ConnectorKey, time: f64) -> f64 {
match self.grows.get(&key) {
Some(grow) => grow.at(time, Curve::Ease),
None if self.connector(key).is_grown() => 1.,
None => 0.,
}
}
pub fn badge_hovered(&self, badge: NodeId) -> bool {
self.hovered_part == Some(NodePart::ErrorBadge(badge))
}
}
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more