mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d27468144e | ||
|
|
33dd5e545a | ||
|
|
4f0d8c7f4c | ||
|
|
1335e9a0f8 | ||
|
|
89238b669a | ||
|
|
da2c5a2d13 | ||
|
|
c75ebbd143 | ||
|
|
addba860d3 | ||
|
|
9526711aa2 | ||
|
|
d8b9f67adb | ||
|
|
b149248db9 | ||
|
|
7b4dc4d8a7 | ||
|
|
feea64170a | ||
|
|
6541449a4a | ||
|
|
5e92356578 | ||
|
|
3ca1376f93 | ||
|
|
93d2738a23 | ||
|
|
9557c6adfc |
No files matched your search
@@ -7,6 +7,8 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
|
||||
workflow_dispatch: {}
|
||||
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
||||
concurrency:
|
||||
@@ -245,7 +247,8 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
||||
# A manual run has no base commit of its own, so it compares against master
|
||||
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -259,7 +262,9 @@ jobs:
|
||||
rustflags: ""
|
||||
|
||||
- name: 📥 Fetch the base commit
|
||||
run: git fetch --depth=1 origin "$BASE_SHA"
|
||||
run: |
|
||||
git fetch --depth=1 origin "$BASE_REF"
|
||||
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
|
||||
|
||||
- name: 🔬 Check migrations against the base commit
|
||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||
|
||||
Generated
+24
-6
@@ -590,6 +590,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -2535,17 +2536,34 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-text"
|
||||
name = "graph-ui"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"convert_case 0.12.0",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam",
|
||||
"log",
|
||||
"proc-macro2",
|
||||
"syn 3.0.9",
|
||||
"graph-craft",
|
||||
"graph-ui-icons",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"interpreted-executor",
|
||||
"node-macro",
|
||||
"preprocessor",
|
||||
"rendering",
|
||||
"svg-convert",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-ui-icons"
|
||||
version = "0.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "graphene-animation"
|
||||
version = "0.0.0"
|
||||
@@ -2676,7 +2694,6 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-text",
|
||||
"graphene-application-io",
|
||||
"graphene-canvas-utils",
|
||||
"graphene-core",
|
||||
@@ -5758,6 +5775,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+4
-1
@@ -34,6 +34,8 @@ members = [
|
||||
"node-graph/libraries/*",
|
||||
"node-graph/nodes/*",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/graph-ui",
|
||||
"node-graph/graph-ui/icons",
|
||||
"node-graph/graphene-cli",
|
||||
"node-graph/nodes/gstd",
|
||||
"node-graph/interpreted-executor",
|
||||
@@ -93,7 +95,6 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
|
||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||
graphene-animation = { path = "node-graph/libraries/animation" }
|
||||
core-types = { path = "node-graph/libraries/core-types" }
|
||||
graph-text = { path = "node-graph/libraries/graph-text" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
@@ -113,6 +114,8 @@ 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" }
|
||||
document-format = { path = "document/format" }
|
||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-container = { path = "document/container" }
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
|
||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
|
||||
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelAndEmbossV2, &contract());
|
||||
check_undo(&BevelAndEmbossV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
|
||||
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BevelAndEmbossV2);
|
||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use migration_core::{Inputs, NodeInput, encode, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
TypeDefault(Type),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `Type` an empty list of graphics stores.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Type {
|
||||
Concrete(TypeDescriptor),
|
||||
List(Box<Type>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeDescriptor {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
|
||||
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||
pub fn blur_v2(inputs: &mut Inputs) {
|
||||
inputs.insert(2, empty_radius_mask());
|
||||
}
|
||||
|
||||
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
|
||||
fn empty_radius_mask() -> NodeInput {
|
||||
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
|
||||
name: "graphic_types::graphic::Graphic".to_string(),
|
||||
}))));
|
||||
NodeInput::Value {
|
||||
value: encode(&no_graphics),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlurV2, &contract());
|
||||
check_undo(&BlurV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BlurV2);
|
||||
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&BlurV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, empty_radius_mask());
|
||||
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, blur), expected);
|
||||
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
|
||||
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
|
||||
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ConvolutionKernelV1, &contract());
|
||||
check_undo(&ConvolutionKernelV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
|
||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&ConvolutionKernelV1);
|
||||
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod bevel_and_emboss_v2;
|
||||
mod blur_v2;
|
||||
mod convolution_kernel_v1;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_shadow_v1;
|
||||
@@ -8,6 +11,8 @@ mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod outline_v3;
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod paint_overlay_v2;
|
||||
mod renames;
|
||||
mod satin_v1;
|
||||
@@ -0,0 +1,53 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Outline' defaults to fitting gradients without a transform across the content.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
|
||||
pub fn outline_v3(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV3, &contract());
|
||||
check_undo(&OutlineV3, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV3);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV3).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
|
||||
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
|
||||
pub fn paint_overlay_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PaintOverlayV2, &contract());
|
||||
check_undo(&PaintOverlayV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&PaintOverlayV2);
|
||||
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, overlay), expected);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ 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, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -196,10 +196,6 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
},
|
||||
UpdateClickTargets {
|
||||
#[serde(rename = "clickTargets")]
|
||||
click_targets: Option<FrontendClickTargets>,
|
||||
},
|
||||
UpdateGraphViewOverlay {
|
||||
open: bool,
|
||||
},
|
||||
|
||||
@@ -87,9 +87,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
||||
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
||||
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
||||
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
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::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Base {
|
||||
VectorLayer,
|
||||
ImageLayer,
|
||||
/// A group holding a vector layer, with the effect on the group.
|
||||
Group,
|
||||
}
|
||||
|
||||
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
|
||||
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
|
||||
if effect == blur::IDENTIFIER {
|
||||
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
|
||||
.upstream_node_id_from_protonode(effect)
|
||||
.expect("the layer has its blur");
|
||||
let value = Box::new(TaggedValue::Number(10.));
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: blur::RadiusInput::INDEX,
|
||||
value,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
|
||||
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
|
||||
|
||||
match base {
|
||||
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
|
||||
Base::VectorLayer | Base::Group => {
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
}
|
||||
}
|
||||
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
|
||||
if !matches!(base, Base::Group) {
|
||||
add_effect(&mut editor, base_layer, effect.clone()).await;
|
||||
}
|
||||
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
editor.select_primary_color(red).await;
|
||||
editor.select_secondary_color(red).await;
|
||||
editor.draw_rect(20., 20., 200., 200.).await;
|
||||
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::FillColorSet {
|
||||
layer: clipped_layer,
|
||||
color: Some(red),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
|
||||
|
||||
// Grouped once the red is clipped, the group takes the base's place beneath it
|
||||
if let Base::Group = base {
|
||||
let nodes = vec![base_layer.to_node()];
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
||||
let group = editor.get_selected_layer().await.expect("the group is selected");
|
||||
add_effect(&mut editor, group, effect).await;
|
||||
}
|
||||
|
||||
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
|
||||
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
|
||||
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
|
||||
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
|
||||
stack.push(clipped);
|
||||
stack
|
||||
}
|
||||
|
||||
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
|
||||
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||
// The clip's def in SVG carries out the blur but not the shadow
|
||||
let mut render = SvgRender::new();
|
||||
graphic.render_svg(
|
||||
&mut render,
|
||||
&RenderParams {
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let body = render.svg.to_svg_string();
|
||||
let reference = body.rfind("url(#mask-").expect("the red is clipped");
|
||||
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
|
||||
let defs = &render.svg_defs;
|
||||
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
|
||||
let def_end = ["</mask>", "</clipPath>"]
|
||||
.iter()
|
||||
.filter_map(|closing| defs[def_start..].find(closing))
|
||||
.min()
|
||||
.expect("the clip's def is closed");
|
||||
let clip = &defs[def_start..def_start + def_end];
|
||||
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
|
||||
|
||||
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
|
||||
let size = UVec2::new(256, 256);
|
||||
let executor = gpu_executor();
|
||||
let texture = executor
|
||||
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||
.expect("the clip renders");
|
||||
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
|
||||
let pixel = |x: u32, y: u32| -> [u8; 4] {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
let within = pixel(90, 90);
|
||||
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
|
||||
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
|
||||
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
|
||||
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
|
||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||
}
|
||||
|
||||
#[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)] {
|
||||
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
|
||||
let stack = clipped_stack(base, effect.clone()).await;
|
||||
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
|
||||
|
||||
// Flattened into one list of vectors, the base clips its sibling by the same rule
|
||||
if let Base::VectorLayer = base {
|
||||
let flattened: List<Vector> = stack.into_flattened_list();
|
||||
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use crate::node_graph_executor::InspectedContext;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::RadialBlurMethod;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -35,7 +36,7 @@ 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,
|
||||
MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
@@ -1271,16 +1272,19 @@ impl_table_item_layout_for_choice_enum!(
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
RadialBlurMethod,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
@@ -1456,9 +1460,11 @@ macro_rules! known_item_types {
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
RadialBlurMethod,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
@@ -1469,6 +1475,7 @@ macro_rules! known_item_types {
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
|
||||
@@ -304,8 +304,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let visibility_settings = self.overlays_visibility_settings;
|
||||
|
||||
// Send the overlays message to the overlays message handler
|
||||
self.overlays_message_handler
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
self.overlays_message_handler.process_message(
|
||||
message,
|
||||
responses,
|
||||
OverlaysMessageContext {
|
||||
visibility_settings,
|
||||
viewport,
|
||||
graph_open: self.graph_view_overlay_open,
|
||||
},
|
||||
);
|
||||
}
|
||||
DocumentMessage::Inspector(message) => {
|
||||
let context = InspectorMessageContext {
|
||||
@@ -2680,7 +2687,6 @@ impl DocumentMessageHandler {
|
||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||
self.network_interface.unload_import_export_ports(&path);
|
||||
self.network_interface.unload_all_nodes_bounding_box(&path);
|
||||
self.network_interface.unload_outward_wires(&path);
|
||||
}
|
||||
self.network_interface.load_structure();
|
||||
|
||||
-3
@@ -807,9 +807,6 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
// Set positions for all imported descendants in a single O(n) pass
|
||||
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
||||
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
||||
|
||||
// Invalidate caches once after all positions are set
|
||||
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
|
||||
}
|
||||
usvg::Node::Path(path) => {
|
||||
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#[cfg(test)]
|
||||
mod clipping_tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
|
||||
@@ -5,16 +5,19 @@ 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 +40,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;
|
||||
@@ -56,8 +54,6 @@ impl NodeInspectorContext<'_> {
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
/// Input position of the clip parameter on the "Artboard" layer template.
|
||||
pub const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
|
||||
@@ -111,7 +107,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.
|
||||
@@ -139,9 +136,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>>;
|
||||
@@ -172,6 +689,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
|
||||
map
|
||||
}
|
||||
|
||||
@@ -209,10 +727,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);
|
||||
}
|
||||
@@ -307,6 +906,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| {
|
||||
@@ -479,7 +1129,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -496,7 +1145,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -603,7 +1251,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -619,7 +1266,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -740,7 +1386,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
|
||||
@@ -988,29 +1634,6 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A graph text node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
let sources = graphene_std::registry::GRAPH_SOURCES.lock().unwrap().len();
|
||||
let graphs = &*graphene_std::graph_text::GRAPHS;
|
||||
assert!(!graphs.is_empty(), "the graphs in `graphene_std` should be registered");
|
||||
assert_eq!(graphs.len(), sources, "every registered graph should resolve");
|
||||
|
||||
for graph in graphs {
|
||||
assert!(resolve_network_node_type(graph.identifier).is_some(), "the '{}' graph should have a definition", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_index_constants_match_the_graphs() {
|
||||
use graphene_std::graph_text::import_index;
|
||||
|
||||
assert_eq!(import_index("Artboard", "location"), Some(super::ARTBOARD_LOCATION_INPUT_INDEX));
|
||||
assert_eq!(import_index("Artboard", "dimensions"), Some(super::ARTBOARD_DIMENSIONS_INPUT_INDEX));
|
||||
assert_eq!(import_index("Artboard", "clip"), Some(super::ARTBOARD_CLIP_INPUT_INDEX));
|
||||
assert_eq!(import_index("Blend", "path"), Some(super::BLEND_PATH_INPUT_INDEX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1151,36 +1774,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]
|
||||
@@ -1197,7 +1805,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)));
|
||||
@@ -1211,7 +1819,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)));
|
||||
@@ -1220,8 +1828,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 {
|
||||
|
||||
+30
-422
@@ -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,241 +96,25 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
||||
);
|
||||
}
|
||||
|
||||
add_graph_definitions(graph_text::GRAPHS.clone(), &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 text node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs in graph text, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph in graph text.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = IVec2::from(node.position);
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph
|
||||
.exports
|
||||
.iter()
|
||||
.map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false)))
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(GraphDefinitionError::Invalid)?;
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
/// A value must have the type of that default, if it has one.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
|
||||
Ok(match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let value = graph_value(value);
|
||||
if let NodeInput::Value { tagged_value, .. } = default
|
||||
&& **tagged_value != TaggedValue::None
|
||||
&& element_type(&tagged_value.ty()) != element_type(&value.ty())
|
||||
{
|
||||
return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
|
||||
}
|
||||
NodeInput::value(value, exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
})
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element.clone()
|
||||
}
|
||||
|
||||
fn graph_value(value: &GraphValue) -> TaggedValue {
|
||||
match value {
|
||||
GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
/// 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) => {
|
||||
@@ -341,192 +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",
|
||||
identifier: "value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
path: identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
identifier: "out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: (0, 0),
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
||||
let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_must_have_the_type_of_the_input_it_feeds() {
|
||||
let number_input = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let value = |value| GraphInputSource::Value { value, exposed: None };
|
||||
|
||||
assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
|
||||
assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -207,8 +207,6 @@ pub enum NodeGraphMessage {
|
||||
SelectedNodesSet {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
SendClickTargets,
|
||||
EndSendClickTargets,
|
||||
UnloadWires,
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
@@ -448,8 +446,6 @@ impl NodeGraphMessage {
|
||||
| Self::SelectedNodesAdd { .. }
|
||||
| Self::SelectedNodesRemove { .. }
|
||||
| Self::SelectedNodesSet { .. }
|
||||
| Self::SendClickTargets
|
||||
| Self::EndSendClickTargets
|
||||
| Self::UnloadWires
|
||||
| Self::SendWires
|
||||
| Self::UpdateVisibleNodes
|
||||
|
||||
@@ -24,14 +24,12 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use crate::messages::viewport::Position;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graphene_std::math::math_ext::QuadExt;
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||
use graphene_std::*;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
use renderer::Quad;
|
||||
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct NodeGraphMessageContext<'a> {
|
||||
@@ -2025,10 +2023,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
selected_nodes.set_selected_nodes(nodes);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
|
||||
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
|
||||
}),
|
||||
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
|
||||
NodeGraphMessage::UnloadWires => {
|
||||
self.frontend_wires.clear();
|
||||
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
||||
@@ -2543,13 +2537,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
HashSet::new()
|
||||
};
|
||||
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
||||
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
|
||||
for node_id in all_nodes {
|
||||
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
|
||||
log::error!("Could not get transient metadata for node {node_id}");
|
||||
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
|
||||
log::error!("Could not get the body of node {node_id}");
|
||||
continue;
|
||||
};
|
||||
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
|
||||
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
|
||||
if body.overlaps(selection_min, selection_max) {
|
||||
if alt {
|
||||
nodes.remove(&node_id);
|
||||
} else {
|
||||
@@ -3211,11 +3205,6 @@ impl NodeGraphMessageHandler {
|
||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
||||
|
||||
// Only development builds draw the click targets, so users don't come across the overlay by accident
|
||||
if cfg!(debug_assertions) {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
|
||||
}
|
||||
|
||||
if self.has_selection {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant;
|
||||
Copy,
|
||||
|
||||
@@ -20,6 +20,7 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::RadialBlurMethod;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{
|
||||
@@ -40,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, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -238,7 +239,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>,
|
||||
@@ -250,50 +251,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.
|
||||
@@ -347,12 +304,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();
|
||||
}
|
||||
@@ -395,7 +349,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| {
|
||||
@@ -439,10 +393,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, &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)),
|
||||
@@ -503,9 +454,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().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(),
|
||||
@@ -944,7 +898,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, 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(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -959,7 +913,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))))
|
||||
@@ -970,7 +924,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()))))
|
||||
@@ -985,7 +939,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))))
|
||||
@@ -996,7 +950,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()))))
|
||||
@@ -2838,10 +2792,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);
|
||||
}
|
||||
}
|
||||
@@ -3304,20 +3258,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;
|
||||
}
|
||||
|
||||
@@ -3333,21 +3307,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)
|
||||
@@ -3807,6 +3772,29 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||
}
|
||||
|
||||
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::filters::sharpen::*;
|
||||
|
||||
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
|
||||
let edges_only = get_document_node(node_id, context)
|
||||
.ok()
|
||||
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
|
||||
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
|
||||
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
|
||||
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
|
||||
|
||||
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
|
||||
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
|
||||
|
||||
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
|
||||
|
||||
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
|
||||
}
|
||||
|
||||
pub struct ParameterWidgetsInfo<'a> {
|
||||
document_id: DocumentId,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
|
||||
@@ -212,23 +212,6 @@ pub struct NodeEvaluationError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendClickTargets {
|
||||
#[serde(rename = "nodeClickTargets")]
|
||||
pub node_click_targets: Vec<String>,
|
||||
#[serde(rename = "layerClickTargets")]
|
||||
pub layer_click_targets: Vec<String>,
|
||||
#[serde(rename = "connectorClickTargets")]
|
||||
pub connector_click_targets: Vec<String>,
|
||||
#[serde(rename = "iconClickTargets")]
|
||||
pub icon_click_targets: Vec<String>,
|
||||
#[serde(rename = "allNodesBoundingBox")]
|
||||
pub all_nodes_bounding_box: String,
|
||||
#[serde(rename = "importExportNames")]
|
||||
pub import_export_names: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Direction {
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
|
||||
pub struct OverlaysMessageContext<'a> {
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub graph_open: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -25,7 +26,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
|
||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||
|
||||
if visibility_settings.all() {
|
||||
if visibility_settings.all() && !context.graph_open {
|
||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 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};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use glam::DVec2;
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -20,20 +20,32 @@ const DEMOS: [&str; 8] = [
|
||||
const REPETITIONS: u32 = 200;
|
||||
|
||||
#[test]
|
||||
fn wire_anchors_match_the_ports_of_every_demo_node() {
|
||||
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() {
|
||||
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
|
||||
// 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 input = InputConnector::node_at_index(*node_id, index);
|
||||
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {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 output = OutputConnector::node(*node_id, index);
|
||||
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +72,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for node_id in &node_ids {
|
||||
std::hint::black_box(interface.node_click_targets(node_id, &[]));
|
||||
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
|
||||
}
|
||||
}
|
||||
let all_click_targets = start.elapsed() / REPETITIONS;
|
||||
|
||||
@@ -35,7 +35,6 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
|
||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_absolute_position(*position);
|
||||
}
|
||||
interface.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,14 +171,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
||||
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
|
||||
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
|
||||
panic!("the root network is laid out")
|
||||
};
|
||||
let fresh = graph_layout::Layout::new(&graph);
|
||||
for (other, position) in kept {
|
||||
assert_eq!(
|
||||
Some(position),
|
||||
indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ mod layout;
|
||||
mod layout_pass;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod node_parts;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
@@ -36,6 +37,7 @@ mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use layout_pass::NetworkLayout;
|
||||
pub use node_parts::{Part, PartTarget};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
@@ -52,11 +54,12 @@ use crate::consts::{
|
||||
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::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
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;
|
||||
@@ -71,7 +74,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;
|
||||
|
||||
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
|
||||
EditorDelta::NodeMetadata { network, node_id, change } => {
|
||||
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
||||
match change {
|
||||
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||
|
||||
@@ -88,34 +88,15 @@ impl NodeNetworkInterface {
|
||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||
}
|
||||
|
||||
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
|
||||
self.load_import_export_ports(network_path);
|
||||
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_ports");
|
||||
return None;
|
||||
};
|
||||
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
|
||||
log::error!("Could not load import export ports in import_export_ports");
|
||||
return None;
|
||||
};
|
||||
Some(ports)
|
||||
}
|
||||
|
||||
/// Reads the import/export ports through &self, loading them first if needed.
|
||||
/// 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> {
|
||||
self.network_metadata(network_path)?
|
||||
.transient_metadata
|
||||
.import_export_ports
|
||||
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
|
||||
}
|
||||
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
|
||||
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
|
||||
cache.unload();
|
||||
}
|
||||
|
||||
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in load_import_export_ports");
|
||||
return;
|
||||
};
|
||||
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
|
||||
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
|
||||
}
|
||||
|
||||
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
||||
@@ -126,78 +107,13 @@ impl NodeNetworkInterface {
|
||||
transient.import_export_ports.unload();
|
||||
}
|
||||
|
||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
|
||||
return None;
|
||||
};
|
||||
|
||||
let bounding_box = network_metadata
|
||||
.transient_metadata
|
||||
.all_nodes_bounding_box
|
||||
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
|
||||
if bounding_box.is_none() {
|
||||
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
|
||||
}
|
||||
bounding_box
|
||||
}
|
||||
|
||||
/// The combined bounds of every node in the network, in node graph space.
|
||||
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
|
||||
Some(
|
||||
nodes
|
||||
.iter()
|
||||
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
|
||||
.reduce(Quad::combine_bounds)
|
||||
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
|
||||
return;
|
||||
};
|
||||
transient.all_nodes_bounding_box.unload();
|
||||
transient.import_export_clearance.unload();
|
||||
self.unload_import_export_ports(network_path);
|
||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_layout(network_path, NetworkLayout::bounds)
|
||||
}
|
||||
|
||||
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_clearance");
|
||||
return None;
|
||||
};
|
||||
|
||||
network_metadata
|
||||
.transient_metadata
|
||||
.import_export_clearance
|
||||
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
|
||||
}
|
||||
|
||||
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
|
||||
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
let mut clearance = ImportExportClearance::default();
|
||||
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
||||
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
let center = (top_left.x + bottom_right.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
|
||||
}
|
||||
}
|
||||
|
||||
Some(clearance)
|
||||
self.with_layout(network_path, NetworkLayout::clearance)
|
||||
}
|
||||
|
||||
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
||||
@@ -364,6 +280,10 @@ 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");
|
||||
return None;
|
||||
@@ -376,7 +296,7 @@ impl NodeNetworkInterface {
|
||||
node_metadata
|
||||
.transient_metadata
|
||||
.layer_width
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
|
||||
}
|
||||
|
||||
/// Unloads layer width if the node is a layer.
|
||||
@@ -475,7 +395,7 @@ impl NodeNetworkInterface {
|
||||
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);
|
||||
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();
|
||||
@@ -523,7 +443,7 @@ impl NodeNetworkInterface {
|
||||
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);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
@@ -549,17 +469,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// The node's body, ports, and handles, built where it is drawn now.
|
||||
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
self.compute_node_click_targets(node_id, network_path)
|
||||
}
|
||||
|
||||
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
|
||||
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
|
||||
}
|
||||
|
||||
/// 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]> {
|
||||
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||
.flatten()
|
||||
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
|
||||
Some([body.min, body.max])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+72
-3
@@ -2,7 +2,7 @@ use super::{
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
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};
|
||||
@@ -330,7 +330,6 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
|
||||
}
|
||||
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
||||
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
||||
network_interface.invalidate_positions(&[]);
|
||||
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
||||
|
||||
@@ -2614,7 +2613,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;
|
||||
@@ -4228,3 +4227,73 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping a group");
|
||||
}
|
||||
|
||||
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
|
||||
let interface = &editor.active_document().network_interface;
|
||||
let parent = layer.parent(interface.document_metadata())?;
|
||||
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
for x in [0., 50., 100.] {
|
||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||
}
|
||||
|
||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the artboard should be a layer");
|
||||
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
let group = artboard
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the group should be the top layer of the artboard");
|
||||
for insert_index in [0, 2] {
|
||||
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
|
||||
|
||||
for layer in group.children(editor.active_document().metadata()).chain([group]) {
|
||||
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
|
||||
}
|
||||
}
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
for x in [0., 50., 100., 150.] {
|
||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||
}
|
||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the artboard should be a layer");
|
||||
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
|
||||
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
|
||||
for keep_upstream in [false, true] {
|
||||
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
|
||||
let before = interface.positions(layers.iter().copied(), &[]);
|
||||
interface.drag_selected_nodes(offset, keep_upstream, &[]);
|
||||
let dragging = interface.positions(layers.iter().copied(), &[]);
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
|
||||
|
||||
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -62,11 +62,21 @@ pub enum NodeMetadataChange {
|
||||
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
||||
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
||||
NodeType(NodeTypePersistentMetadata),
|
||||
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
|
||||
Position(NodeTypePersistentMetadata),
|
||||
DisplayName(String),
|
||||
Locked(bool),
|
||||
Pinned(bool),
|
||||
}
|
||||
|
||||
impl NodeMetadataChange {
|
||||
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
|
||||
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
|
||||
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
|
||||
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
||||
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -319,6 +329,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
||||
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
||||
]
|
||||
}
|
||||
NodeMetadataChange::Position(node_type) => vec![node_attribute(
|
||||
node_attr::ui::POSITION,
|
||||
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
|
||||
)],
|
||||
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
||||
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
||||
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
||||
|
||||
+28
-1
@@ -3,6 +3,7 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use super::{InputConnector, NodeTemplate};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use document_graph_storage::attr::node as node_attr;
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -184,7 +185,7 @@ async fn per_field_metadata_edits_match_the_diff() {
|
||||
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
||||
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
||||
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
||||
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
|
||||
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network: None,
|
||||
node_id: node,
|
||||
@@ -283,6 +284,32 @@ async fn unchanged_writes_emit_nothing() {
|
||||
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_layer_writes_only_its_position() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 40., 40.).await;
|
||||
let layer = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the rectangle should be a layer")
|
||||
.to_node();
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
|
||||
|
||||
let emitted = committed_deltas(&mut editor);
|
||||
let written: Vec<String> = construct(&editor, &emitted, &working)
|
||||
.into_iter()
|
||||
.filter_map(|op| match op {
|
||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(written, [node_attr::ui::POSITION]);
|
||||
}
|
||||
|
||||
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
||||
/// without the caller saying anything about it.
|
||||
#[tokio::test]
|
||||
|
||||
+3
-190
@@ -46,193 +46,6 @@ impl NodeNetworkInterface {
|
||||
(!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.)))
|
||||
}
|
||||
|
||||
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
|
||||
let Some(node_position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get node position in compute_node_ports for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let document_node = self.document_node(node_id, network_path)?;
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
let mut ports = Ports::new();
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
|
||||
} else if !self.is_layer(node_id, network_path) {
|
||||
let mut input_row_count = 0;
|
||||
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
||||
if input.is_exposed() {
|
||||
ports.insert_node_input(input_index, input_row_count, node_top_left);
|
||||
}
|
||||
if input_index == 0 || input.is_exposed() {
|
||||
input_row_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
|
||||
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
|
||||
ports.insert_node_output(output_index, node_top_left);
|
||||
}
|
||||
} else {
|
||||
ports.insert_layer_input(0, node_top_left);
|
||||
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
|
||||
ports.insert_layer_input(1, node_top_left);
|
||||
}
|
||||
ports.insert_layer_output(node_top_left);
|
||||
}
|
||||
|
||||
Some(ports)
|
||||
}
|
||||
|
||||
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
|
||||
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
let Some(node_position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let node_metadata = self.node_metadata(node_id, network_path)?;
|
||||
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
|
||||
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
|
||||
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
const DOT_HALF_WIDTH: f64 = 15.;
|
||||
const DOT_HALF_HEIGHT: f64 = 8.;
|
||||
|
||||
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
|
||||
let path = rounded_rectangle_path(
|
||||
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
[DOT_HALF_HEIGHT; 4],
|
||||
);
|
||||
|
||||
return Some(DocumentNodeClickTargets {
|
||||
node_click_target: ClickTarget::new_with_path(path, 0.),
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
});
|
||||
}
|
||||
|
||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
|
||||
let width = 5 * GRID_SIZE;
|
||||
// Offset down by half a grid so the click target sits below the top connector strip.
|
||||
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
|
||||
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
||||
|
||||
let radius = 3.;
|
||||
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
}
|
||||
} else {
|
||||
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
|
||||
log::error!("Could not get layer width in compute_node_click_targets");
|
||||
0
|
||||
});
|
||||
let width = layer_width_cells * GRID_SIZE;
|
||||
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
|
||||
let locked = self.is_locked(node_id, network_path);
|
||||
|
||||
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
|
||||
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
|
||||
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
||||
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
||||
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
||||
let lock_click_target = if locked {
|
||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
[0.; 4],
|
||||
);
|
||||
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
|
||||
// so the rest of the layer still drills into the subgraph on double-click
|
||||
|
||||
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
||||
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
||||
/// `.thumbnail` (70px) + its 1px side margins (= 72)
|
||||
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
|
||||
/// `.details` margin-left
|
||||
const DETAILS_LEFT_MARGIN: f64 = 8.;
|
||||
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
|
||||
/// Distance from layer's right edge to visibility's left edge (= 12)
|
||||
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
|
||||
let display_name = self.display_name(node_id, network_path);
|
||||
let name_click_target = if display_name.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
|
||||
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
|
||||
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
|
||||
let name_width = text_width(&display_name, FONT_SIZE);
|
||||
let name_right = (name_left + name_width).min(name_right_max);
|
||||
if name_right > name_left {
|
||||
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
||||
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
||||
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
||||
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// The layer click target spans the layer and its chain background
|
||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||
|
||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
||||
const CORNER_RADIUS: f64 = 10.;
|
||||
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
|
||||
visibility_click_target,
|
||||
lock_click_target,
|
||||
grip_click_target,
|
||||
name_click_target,
|
||||
})),
|
||||
}
|
||||
};
|
||||
|
||||
Some(document_node_click_targets)
|
||||
}
|
||||
|
||||
/// 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])> {
|
||||
@@ -339,9 +152,9 @@ impl NodeNetworkInterface {
|
||||
Some((1..row_count).find(|&row| first_row_center + import_export_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. Cached
|
||||
/// 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 {
|
||||
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.;
|
||||
@@ -356,7 +169,7 @@ impl NodeNetworkInterface {
|
||||
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;
|
||||
((layer_width_pixels / 24.).ceil() as u32).max(8)
|
||||
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
||||
}
|
||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
||||
|
||||
+59
-116
@@ -24,81 +24,6 @@ impl NodeNetworkInterface {
|
||||
all_selected_nodes
|
||||
}
|
||||
|
||||
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
|
||||
let mut all_node_click_targets = Vec::new();
|
||||
let mut connector_click_targets = Vec::new();
|
||||
let mut icon_click_targets = Vec::new();
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
|
||||
return FrontendClickTargets::default();
|
||||
};
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
self.with_import_export_ports(network_path, |import_export_click_targets| {
|
||||
for port in import_export_click_targets.click_targets() {
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
nodes.into_iter().for_each(|node_id| {
|
||||
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
|
||||
let mut node_path = String::new();
|
||||
|
||||
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
|
||||
node_path.push_str(path.to_svg().as_str())
|
||||
}
|
||||
all_node_click_targets.push((node_id, node_path));
|
||||
for port in node_click_targets.port_click_targets.click_targets() {
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
||||
// Visibility button (eye icon)
|
||||
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Lock button (padlock icon), only when the layer is locked
|
||||
if let Some(lock_click_target) = &layer_metadata.lock_click_target
|
||||
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
|
||||
{
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Drag grip (dotted symbol)
|
||||
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut layer_click_targets = Vec::new();
|
||||
let mut node_click_targets = Vec::new();
|
||||
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
|
||||
if self.is_layer(&node_id, network_path) {
|
||||
layer_click_targets.push(path);
|
||||
} else {
|
||||
node_click_targets.push(path);
|
||||
}
|
||||
});
|
||||
|
||||
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
|
||||
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
|
||||
|
||||
let import_export_names = self
|
||||
.import_export_name_bounds(network_path)
|
||||
.into_iter()
|
||||
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
|
||||
.collect();
|
||||
FrontendClickTargets {
|
||||
node_click_targets,
|
||||
layer_click_targets,
|
||||
connector_click_targets,
|
||||
icon_click_targets,
|
||||
all_nodes_bounding_box,
|
||||
import_export_names,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
||||
self.document_metadata.document_to_viewport = transform;
|
||||
}
|
||||
@@ -123,6 +48,24 @@ impl NodeNetworkInterface {
|
||||
Some(&mut navigation.node_graph_ptz)
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
let part = match target.part {
|
||||
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
|
||||
part => part,
|
||||
};
|
||||
find(part, target)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
||||
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
@@ -133,16 +76,13 @@ 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 clicked_nodes = self
|
||||
.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
||||
}) == Some(true)
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
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))))
|
||||
.collect::<Vec<_>>()
|
||||
})?;
|
||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||
let drawing_layer = |node_id: &NodeId| {
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
@@ -165,25 +105,18 @@ 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);
|
||||
|
||||
self.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
|
||||
match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
let wanted = match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => Part::Visibility,
|
||||
LayerClickTargetTypes::Lock => Part::Lock,
|
||||
LayerClickTargetTypes::Grip => Part::Grip,
|
||||
LayerClickTargetTypes::Name => Part::Name,
|
||||
};
|
||||
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -269,13 +202,11 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|port| InputConnector::node_at_index(*node_id, port))
|
||||
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,
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
.or_else(|| {
|
||||
@@ -302,13 +233,11 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
||||
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,
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
.or_else(|| {
|
||||
@@ -426,3 +355,17 @@ impl NodeNetworkInterface {
|
||||
(layer_widths, chain_widths, has_left_input_wire)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
@@ -6,10 +6,6 @@
|
||||
use super::*;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
|
||||
/// Unloads the network's import and export ports.
|
||||
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_import_export_ports(network_path);
|
||||
@@ -17,6 +13,5 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
self.try_unload_layer_width(node_id, network_path);
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
||||
@@ -145,7 +144,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a layer to a stack position
|
||||
@@ -159,8 +157,6 @@ impl NodeNetworkInterface {
|
||||
} else if node.set_stack_position(y_offset) {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a node to a stack position without changing its y offset
|
||||
@@ -371,7 +367,6 @@ impl NodeNetworkInterface {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||
if node.shift_absolute_position(position - current_position) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+158
-36
@@ -1,7 +1,9 @@
|
||||
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
||||
use super::*;
|
||||
use glam::UVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
const REACH_MARGIN: f64 = 16.;
|
||||
|
||||
@@ -9,13 +11,53 @@ const REACH_MARGIN: f64 = 16.;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkLayout {
|
||||
revision: u64,
|
||||
generation: u64,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
graph: Graph,
|
||||
shapes: Vec<NodeShape>,
|
||||
layout: Layout,
|
||||
bounds: [DVec2; 2],
|
||||
clearance: ImportExportClearance,
|
||||
}
|
||||
|
||||
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
|
||||
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
impl NetworkLayout {
|
||||
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
|
||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||
let mut network_layout = Self {
|
||||
revision,
|
||||
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
|
||||
node_ids,
|
||||
indices,
|
||||
graph,
|
||||
shapes,
|
||||
layout,
|
||||
bounds: [DVec2::ZERO; 2],
|
||||
clearance: ImportExportClearance::default(),
|
||||
};
|
||||
network_layout.measure_bounds_and_clearance();
|
||||
network_layout
|
||||
}
|
||||
|
||||
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
|
||||
let Self {
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
graph,
|
||||
layout,
|
||||
..
|
||||
} = self;
|
||||
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
||||
Some(self.node(node_id)?.position)
|
||||
}
|
||||
@@ -53,6 +95,33 @@ impl NetworkLayout {
|
||||
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
|
||||
}
|
||||
|
||||
/// What the imports and exports keep their distance from horizontally.
|
||||
pub(crate) fn clearance(&self) -> ImportExportClearance {
|
||||
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())
|
||||
}
|
||||
|
||||
/// 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)?);
|
||||
let mut found = None;
|
||||
placed.parts(|target| {
|
||||
if found.is_none() {
|
||||
found = find(&target);
|
||||
}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
||||
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
||||
let Some(index) = self.indices.get(node_id) else { return false };
|
||||
@@ -62,6 +131,38 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
|
||||
fn measure_bounds_and_clearance(&mut self) {
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
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();
|
||||
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 {
|
||||
let center = (body.min.x + body.max.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
|
||||
}
|
||||
}
|
||||
|
||||
self.bounds = bounds.unwrap_or_default();
|
||||
self.clearance = clearance;
|
||||
}
|
||||
|
||||
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
||||
Some(self.layout.node(*self.indices.get(node_id)?))
|
||||
}
|
||||
@@ -86,12 +187,14 @@ struct DragOrigin {
|
||||
keep_upstream: bool,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
shapes: Vec<NodeShape>,
|
||||
start: Graph,
|
||||
drag: Drag,
|
||||
}
|
||||
|
||||
impl DragOrigin {
|
||||
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
||||
Self {
|
||||
revision,
|
||||
@@ -99,6 +202,7 @@ impl DragOrigin {
|
||||
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
start,
|
||||
}
|
||||
}
|
||||
@@ -154,7 +258,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
||||
@@ -178,9 +281,14 @@ impl NodeNetworkInterface {
|
||||
.filter(|((before, after), _)| before.placement != after.placement)
|
||||
.map(|((_, after), node_id)| (*node_id, after.placement))
|
||||
.collect();
|
||||
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: std::mem::take(&mut origin.node_ids),
|
||||
indices: std::mem::take(&mut origin.indices),
|
||||
shapes: std::mem::take(&mut origin.shapes),
|
||||
};
|
||||
(moved_placements, laid_out, moved)
|
||||
});
|
||||
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
|
||||
let Some((moved_placements, laid_out, graph)) = finished else { return };
|
||||
|
||||
let mut stored_all = true;
|
||||
for (node_id, placement) in moved_placements {
|
||||
@@ -189,13 +297,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
||||
let layout = Layout::new(&graph);
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout {
|
||||
revision: store::revision(),
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
});
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,16 +310,15 @@ impl NodeNetworkInterface {
|
||||
let transient = self.network_transient_mut(network_path)?;
|
||||
let drag = transient.drag.take()?;
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
Some(drag)
|
||||
}
|
||||
|
||||
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
||||
let mut origin = drag.origin.borrow_mut();
|
||||
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
||||
let (node_ids, indices, start) = self.layout_graph(network_path)?;
|
||||
let (laid_out, start) = self.layout_graph(network_path)?;
|
||||
let start_layout = Layout::new(&start);
|
||||
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
}
|
||||
origin.as_mut().map(read)
|
||||
}
|
||||
@@ -227,8 +328,8 @@ impl NodeNetworkInterface {
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
||||
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
||||
|
||||
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
|
||||
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
|
||||
let (laid_out, graph, layout) = cached.into_parts();
|
||||
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
|
||||
}
|
||||
|
||||
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
||||
@@ -246,40 +347,38 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
if node.set_node_type(node_type) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
||||
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
||||
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
||||
layout.snap_chains(&graph);
|
||||
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: origin.node_ids.clone(),
|
||||
indices: origin.indices.clone(),
|
||||
shapes: origin.shapes.clone(),
|
||||
};
|
||||
(laid_out, graph, layout)
|
||||
})?,
|
||||
None => {
|
||||
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
|
||||
let (laid_out, graph) = self.layout_graph(network_path)?;
|
||||
let layout = Layout::new(&graph);
|
||||
(node_ids, indices, graph, layout)
|
||||
(laid_out, graph, layout)
|
||||
}
|
||||
};
|
||||
|
||||
Some(NetworkLayout {
|
||||
revision,
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
})
|
||||
Some(NetworkLayout::new(revision, laid_out, graph, layout))
|
||||
}
|
||||
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
|
||||
let network = self.nested_network(network_path)?;
|
||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
||||
|
||||
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
|
||||
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
|
||||
let wires = node_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -297,10 +396,10 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some((node_ids, indices, Graph { nodes, wires }))
|
||||
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
|
||||
}
|
||||
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
|
||||
let metadata = self.node_metadata(node_id, network_path)?;
|
||||
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||
@@ -314,17 +413,40 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
||||
let (layer_width, name_width) = if is_layer {
|
||||
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
|
||||
} else {
|
||||
(0, 0.)
|
||||
};
|
||||
let (kind, size) = match (is_layer, is_redirect_dot) {
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
|
||||
(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))),
|
||||
};
|
||||
Some(Node {
|
||||
|
||||
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
||||
let node = Node {
|
||||
placement,
|
||||
kind,
|
||||
size: size.as_ivec2(),
|
||||
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
|
||||
chainable: !is_redirect_dot && !primary_output_hidden,
|
||||
held: false,
|
||||
})
|
||||
};
|
||||
let shape = NodeShape {
|
||||
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
|
||||
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),
|
||||
};
|
||||
Some((node, shape))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
shapes: Vec<NodeShape>,
|
||||
}
|
||||
+6
-17
@@ -94,11 +94,9 @@ impl NodeNetworkInterface {
|
||||
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
||||
}
|
||||
|
||||
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
||||
// Update the outward wires for all nodes in the encapsulating network
|
||||
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
||||
encapsulating_transient.outward_wires.unload();
|
||||
encapsulating_transient.all_nodes_bounding_box.unload();
|
||||
encapsulating_transient.import_export_clearance.unload();
|
||||
}
|
||||
|
||||
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
||||
@@ -141,7 +139,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Update the metadata for the encapsulating node
|
||||
self.unload_outward_wires(encapsulating_network_path);
|
||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
||||
}
|
||||
if affects_document_structure {
|
||||
@@ -179,7 +176,6 @@ impl NodeNetworkInterface {
|
||||
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
||||
// Update the metadata for the encapsulating node
|
||||
self.unload_outward_wires(encapsulating_network_path);
|
||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
||||
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
||||
}
|
||||
@@ -572,8 +568,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Lightweight version of `set_input` for bulk import operations.
|
||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
|
||||
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
|
||||
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
||||
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
||||
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
||||
@@ -673,8 +668,6 @@ impl NodeNetworkInterface {
|
||||
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
||||
// Exposing or hiding a value input changes the node's port count
|
||||
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
// A nested network draws its interior ports from the encapsulating node's inputs
|
||||
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
||||
let nested_path = [network_path, &[*node_id]].concat();
|
||||
@@ -904,7 +897,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.unload_outward_wires(network_path);
|
||||
}
|
||||
|
||||
@@ -927,7 +919,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
previous_entry
|
||||
}
|
||||
@@ -1092,7 +1083,6 @@ impl NodeNetworkInterface {
|
||||
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
||||
}
|
||||
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||
return;
|
||||
@@ -1126,10 +1116,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
let reconnected_offset = reconnect_to_input
|
||||
.as_ref()
|
||||
.and_then(NodeInput::as_node)
|
||||
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
|
||||
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
|
||||
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
|
||||
Some((reconnected, offset))
|
||||
});
|
||||
|
||||
let mut exports_fed_by_import = Vec::new();
|
||||
|
||||
@@ -1365,7 +1355,6 @@ impl NodeNetworkInterface {
|
||||
transient.layer_width.unload();
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.invalidate_import_export(network_path);
|
||||
self.load_structure();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! 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,7 +1,9 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -827,26 +829,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 graph text describes for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
let 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 field = graphene_std::graph_text::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.
|
||||
|
||||
@@ -328,7 +328,10 @@ fn field_deltas(
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
deltas.push(metadata(NodeMetadataChange::placement(
|
||||
¤t_metadata.node_type_metadata,
|
||||
target_metadata.node_type_metadata.clone(),
|
||||
)));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
|
||||
+7
-6
@@ -229,13 +229,14 @@ impl NodeMut<'_> {
|
||||
|
||||
/// Whether the node is displayed as a layer or a node, together with its position.
|
||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||
let changed = self.metadata.node_type_metadata != node_type;
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||
self.deltas.metadata(change);
|
||||
if self.metadata.node_type_metadata == node_type {
|
||||
return false;
|
||||
}
|
||||
changed
|
||||
|
||||
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
self.deltas.metadata(change);
|
||||
true
|
||||
}
|
||||
|
||||
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
||||
|
||||
@@ -3,12 +3,7 @@ use graphene_std::ParameterRef;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
|
||||
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
||||
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
if radii.iter().all(|radius| *radius == 0.) {
|
||||
@@ -19,16 +14,6 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
|
||||
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Ellipse inscribed in the box spanning the two opposite corners.
|
||||
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
|
||||
|
||||
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
|
||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ChainNodeCopy {
|
||||
@@ -292,13 +277,6 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||
}
|
||||
|
||||
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
|
||||
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
|
||||
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
|
||||
[center - HALF_SIZE, center + HALF_SIZE]
|
||||
}
|
||||
|
||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||
const CORNER_RADIUS: f64 = 4.;
|
||||
|
||||
@@ -332,13 +310,6 @@ impl Ports {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
|
||||
self.input_ports
|
||||
.iter()
|
||||
.map(|(_, click_target)| click_target)
|
||||
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
|
||||
}
|
||||
|
||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||
self.input_ports.iter()
|
||||
}
|
||||
@@ -348,51 +319,15 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
||||
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
|
||||
self.input_anchors.push((input_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||
self.input_ports.push((input_index, click_target));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
||||
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
|
||||
self.output_anchors.push((output_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||
self.output_ports.push((output_index, click_target));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
|
||||
self.insert_input_port_at_center(input_index, center);
|
||||
}
|
||||
|
||||
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
|
||||
self.insert_output_port_at_center(output_index, center);
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
|
||||
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
|
||||
if input_index == 0 {
|
||||
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
|
||||
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
|
||||
} else {
|
||||
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
|
||||
// The center of the click target is 8 px above the layer, over its thumbnail
|
||||
let center = node_top_left + DVec2::new(2. * 24., -8.);
|
||||
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(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))
|
||||
}
|
||||
@@ -401,37 +336,12 @@ impl Ports {
|
||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
|
||||
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
|
||||
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
|
||||
const GUTTER_OFFSET: f64 = 10.;
|
||||
const GUTTER_RADIUS: f64 = 5.;
|
||||
|
||||
let gutter = |x_offset: f64| {
|
||||
let gutter_center = center + DVec2::new(x_offset, 0.);
|
||||
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
|
||||
};
|
||||
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
|
||||
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
|
||||
self.input_anchors.push((0, center));
|
||||
self.output_anchors.push((0, center));
|
||||
}
|
||||
|
||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.input_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
}
|
||||
|
||||
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.output_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -747,16 +657,12 @@ impl<T> TransientCache<T> {
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct NodeNetworkTransientMetadata {
|
||||
pub selected_nodes: SelectedNodes,
|
||||
/// Cache for the bounding box around all nodes in node graph space.
|
||||
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
|
||||
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
|
||||
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
|
||||
/// Cache for all outward wire connections
|
||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||
pub(crate) layout: TransientCache<NetworkLayout>,
|
||||
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
||||
/// All export connector click targets
|
||||
pub(crate) import_export_ports: TransientCache<Ports>,
|
||||
/// 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>,
|
||||
@@ -867,11 +773,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),
|
||||
}
|
||||
|
||||
@@ -908,6 +854,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);
|
||||
}
|
||||
@@ -1099,40 +1079,8 @@ impl From<LegacyNodePosition> for NodePosition {
|
||||
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct DocumentNodeTransientMetadata {
|
||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
|
||||
pub(crate) layer_width: TransientCache<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DocumentNodeClickTargets {
|
||||
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
|
||||
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
|
||||
pub node_click_target: ClickTarget,
|
||||
/// Stores all port click targets in node graph space.
|
||||
pub port_click_targets: Ports,
|
||||
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
|
||||
pub node_type_metadata: NodeTypeClickTargets,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NodeTypeClickTargets {
|
||||
Layer(Box<LayerClickTargets>),
|
||||
Node, // No transient click targets are stored exclusively for nodes
|
||||
}
|
||||
|
||||
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LayerClickTargets {
|
||||
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
|
||||
pub visibility_click_target: ClickTarget,
|
||||
/// Cache for the lock icon button, only present when the layer is locked.
|
||||
pub lock_click_target: Option<ClickTarget>,
|
||||
/// Cache for the grip icon, which is next to the visibility button.
|
||||
pub grip_click_target: ClickTarget,
|
||||
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
|
||||
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
|
||||
/// `None` for layers whose display name is empty.
|
||||
pub name_click_target: Option<ClickTarget>,
|
||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
|
||||
pub(crate) layer_width: TransientCache<(u32, f64)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -125,23 +125,27 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
|
||||
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
||||
}
|
||||
|
||||
/// The center line that cleaves a thick layer-stack wire. 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) -> BezPath {
|
||||
/// 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) {
|
||||
return BezPath::new();
|
||||
}
|
||||
|
||||
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let output_trim = 1.5;
|
||||
let input_trim = 1.;
|
||||
let start = output_position + DVec2::new(0., output_trim * sign);
|
||||
let end = input_position - DVec2::new(0., input_trim * sign);
|
||||
let wire = build_vector_wire(output_position, input_position, true, true, graph_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();
|
||||
};
|
||||
|
||||
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let mut center_line = BezPath::new();
|
||||
center_line.move_to(dvec2_to_point(start));
|
||||
center_line.line_to(dvec2_to_point(end));
|
||||
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
|
||||
center_line.line_to(start);
|
||||
for element in wire.elements().iter().skip(1) {
|
||||
center_line.push(*element);
|
||||
}
|
||||
center_line.line_to(end + Vec2::new(0., 2. * sign));
|
||||
center_line
|
||||
}
|
||||
|
||||
@@ -580,7 +584,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::{Affine, Vec2};
|
||||
use kurbo::{Affine, ParamCurveNearest};
|
||||
|
||||
#[test]
|
||||
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
|
||||
@@ -603,4 +607,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -2856,8 +2856,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::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);
|
||||
|
||||
@@ -5143,11 +5143,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, &[]);
|
||||
@@ -5164,7 +5160,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)
|
||||
);
|
||||
}
|
||||
@@ -5181,11 +5177,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, &[]);
|
||||
|
||||
@@ -5195,7 +5187,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.)));
|
||||
}
|
||||
|
||||
@@ -5277,15 +5269,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);
|
||||
@@ -5299,9 +5284,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))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -41,6 +41,15 @@ pub struct ExecutionResponse {
|
||||
dropped_thumbnails: Vec<NodeId>,
|
||||
/// The latest result of each observation.
|
||||
observations: HashMap<ObservationKey, InspectResult>,
|
||||
/// The canvas the frame was presented to
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info: Option<ViewportCanvasInfo>,
|
||||
}
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
struct ViewportCanvasInfo {
|
||||
id: u64,
|
||||
resolution: DVec2,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
@@ -192,18 +201,6 @@ impl NodeGraphExecutor {
|
||||
self.canvas_images_sent.clear();
|
||||
}
|
||||
|
||||
/// Allows the test runner to see if any more executions have been queued.
|
||||
#[cfg(test)]
|
||||
pub fn current_execution_id(&self) -> u64 {
|
||||
self.current_execution_id
|
||||
}
|
||||
|
||||
/// Allows the test runner to access last executions evaluation errors.
|
||||
#[cfg(test)]
|
||||
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
||||
self.evaluation_errors.take()
|
||||
}
|
||||
|
||||
/// Execute the network by flattening it and creating a borrow stack.
|
||||
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
||||
let execution_id = self.current_execution_id;
|
||||
@@ -253,29 +250,6 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the thumbnails in view");
|
||||
}
|
||||
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
// We should always invalidate the cache.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
}
|
||||
|
||||
/// Update the cached network if necessary.
|
||||
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
|
||||
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
|
||||
@@ -527,6 +501,8 @@ impl NodeGraphExecutor {
|
||||
responses: existing_responses,
|
||||
dropped_thumbnails,
|
||||
mut observations,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info,
|
||||
} = *execution_response;
|
||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||
|
||||
@@ -569,6 +545,29 @@ impl NodeGraphExecutor {
|
||||
continue;
|
||||
}
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let mut result = result;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
if let Some(canvas) = viewport_canvas_info {
|
||||
let placeholder = format!(
|
||||
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
|
||||
canvas.resolution.x, canvas.resolution.y, canvas.id,
|
||||
);
|
||||
match result.render_output() {
|
||||
Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => {
|
||||
let end = svg.rfind("</svg>").unwrap_or(svg.len());
|
||||
svg.insert_str(end, &placeholder);
|
||||
}
|
||||
_ => {
|
||||
let svg = format!("<svg>{placeholder}</svg>");
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
@@ -1036,11 +1035,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
|
||||
let svg = format!("<svg>{}</svg>", viewport_canvas_placeholder(canvas_id, resolution));
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
RenderOutputType::Texture { .. } => {}
|
||||
RenderOutputType::Buffer { width, height, .. } => {
|
||||
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
|
||||
@@ -1205,15 +1199,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
None
|
||||
}
|
||||
|
||||
/// The SVG element the frontend replaces with the viewport canvas, covering the viewport at its logical `resolution`.
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn viewport_canvas_placeholder(canvas_id: u64, resolution: DVec2) -> String {
|
||||
format!(
|
||||
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
|
||||
resolution.x, resolution.y, canvas_id,
|
||||
)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -1268,6 +1253,40 @@ mod test {
|
||||
use graphene_std::list::Item;
|
||||
use test_prelude::LayerNodeIdentifier;
|
||||
|
||||
impl NodeGraphExecutor {
|
||||
/// Allows the test runner to see if any more executions have been queued.
|
||||
pub fn current_execution_id(&self) -> u64 {
|
||||
self.current_execution_id
|
||||
}
|
||||
|
||||
/// Allows the test runner to access last executions evaluation errors.
|
||||
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
||||
self.evaluation_errors.take()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
|
||||
#[derive(Default)]
|
||||
pub struct Instrumented {
|
||||
|
||||
@@ -20,7 +20,7 @@ use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
use std::sync::Arc;
|
||||
@@ -94,7 +94,7 @@ enum ViewportArtwork {
|
||||
}
|
||||
|
||||
/// Messages passed from the editor thread to the node runtime thread.
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug)]
|
||||
pub enum GraphRuntimeRequest {
|
||||
GraphUpdate(GraphUpdate),
|
||||
ExecutionRequest(ExecutionRequest),
|
||||
@@ -114,7 +114,7 @@ pub enum GraphRuntimeRequest {
|
||||
RenderOverlays(OverlayContext),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug)]
|
||||
pub struct GraphUpdate {
|
||||
pub(super) network: NodeNetwork,
|
||||
pub(super) resources: ResourceRegistry,
|
||||
@@ -302,7 +302,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
if let Some(viewport) = viewport {
|
||||
texture = self.run_viewport(viewport).await;
|
||||
self.run_viewport(viewport).await;
|
||||
}
|
||||
|
||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||
@@ -315,63 +315,27 @@ impl NodeRuntime {
|
||||
texture
|
||||
}
|
||||
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let mut result = self.evaluate(request)?;
|
||||
let Some(mut result) = self.evaluate(request) else { return };
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let resolution = request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale;
|
||||
|
||||
let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
self.viewport_artwork = Some(ViewportArtwork::Texture(texture.clone()));
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
let frame = self.composite_viewport_frame();
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
{
|
||||
*data = RenderOutputType::CanvasFrame {
|
||||
canvas_id: self.wasm_canvas_cache.id(),
|
||||
resolution,
|
||||
};
|
||||
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
||||
let content = match data {
|
||||
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
|
||||
RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
|
||||
_ => None,
|
||||
};
|
||||
if content.is_some() {
|
||||
self.viewport_artwork = content;
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
}
|
||||
}
|
||||
|
||||
frame
|
||||
} else if request.render_config.export_format == ExportFormat::Raster
|
||||
&& let Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { .. },
|
||||
metadata,
|
||||
}) = result.render_output()
|
||||
{
|
||||
// The viewport was rendered as SVG in place of the requested raster, so the frontend draws it beneath the overlays
|
||||
self.viewport_artwork = Some(ViewportArtwork::Svg);
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
let frame = self.composite_viewport_frame();
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
if let Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) = result.render_output()
|
||||
{
|
||||
let end = svg.rfind("</svg>").unwrap_or(svg.len());
|
||||
svg.insert_str(end, &viewport_canvas_placeholder(self.wasm_canvas_cache.id(), resolution));
|
||||
}
|
||||
|
||||
frame
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
texture
|
||||
self.respond(request, result, observations).await;
|
||||
}
|
||||
|
||||
/// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web.
|
||||
@@ -431,7 +395,7 @@ impl NodeRuntime {
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(request, result, observations).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
@@ -465,7 +429,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
@@ -475,7 +439,7 @@ impl NodeRuntime {
|
||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
||||
}
|
||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
|
||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||
Err(payload) => {
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
@@ -483,6 +447,8 @@ impl NodeRuntime {
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info: None,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
return None;
|
||||
@@ -491,18 +457,37 @@ impl NodeRuntime {
|
||||
Some(result)
|
||||
}
|
||||
|
||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let mut result = result;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let viewport_canvas_info = (!request.render_config.for_export
|
||||
&& match result.render_output() {
|
||||
Some(RenderOutput { data, .. }) => match data {
|
||||
RenderOutputType::Texture(_) => true,
|
||||
RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster,
|
||||
RenderOutputType::Buffer { .. } => false,
|
||||
},
|
||||
None => false,
|
||||
})
|
||||
.then(|| ViewportCanvasInfo {
|
||||
id: self.wasm_canvas_cache.id(),
|
||||
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
|
||||
});
|
||||
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
execution_id: request.execution_id,
|
||||
result,
|
||||
responses,
|
||||
dropped_thumbnails,
|
||||
observations,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
@@ -522,7 +507,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
@@ -586,7 +571,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
impl ExecutionResult {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -398,8 +398,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;
|
||||
@@ -430,20 +429,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(),
|
||||
|
||||
@@ -520,14 +520,18 @@ fn init_test_logger() {
|
||||
});
|
||||
}
|
||||
|
||||
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
||||
/// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
||||
/// Panics if no adapter is found, since tests render on the GPU like the app does.
|
||||
fn gpu_application_io() -> PlatformApplicationIo {
|
||||
pub fn gpu_executor() -> <PlatformApplicationIo as ApplicationIo>::Executor {
|
||||
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
|
||||
let executor = GPU_EXECUTOR.clone().expect(
|
||||
GPU_EXECUTOR.clone().expect(
|
||||
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
|
||||
);
|
||||
PlatformApplicationIo::new_with_executor(executor)
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
|
||||
fn gpu_application_io() -> PlatformApplicationIo {
|
||||
PlatformApplicationIo::new_with_executor(gpu_executor())
|
||||
}
|
||||
|
||||
/// Runs `operation`, returning its result along with the errors it logged.
|
||||
|
||||
@@ -538,30 +538,6 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Click target debug visualizations -->
|
||||
{#if $nodeGraph.clickTargets}
|
||||
<div class="click-targets" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||
<svg>
|
||||
{#each $nodeGraph.clickTargets.nodeClickTargets as pathString}
|
||||
<path class="node" d={pathString} />
|
||||
{/each}
|
||||
{#each $nodeGraph.clickTargets.layerClickTargets as pathString}
|
||||
<path class="layer" d={pathString} />
|
||||
{/each}
|
||||
{#each $nodeGraph.clickTargets.connectorClickTargets as pathString}
|
||||
<path class="connector" d={pathString} />
|
||||
{/each}
|
||||
{#each $nodeGraph.clickTargets.iconClickTargets as pathString}
|
||||
<path class="visibility" d={pathString} />
|
||||
{/each}
|
||||
<path class="all-nodes-bounding-box" d={$nodeGraph.clickTargets.allNodesBoundingBox} />
|
||||
{#each $nodeGraph.clickTargets.importExportNames as pathString}
|
||||
<path class="import-export-name" d={pathString} />
|
||||
{/each}
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Thick vertical layer connection wires -->
|
||||
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||
<svg>
|
||||
@@ -1311,46 +1287,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.click-targets {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
|
||||
svg {
|
||||
overflow: visible;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
stroke-width: 1;
|
||||
fill: none;
|
||||
|
||||
.layer {
|
||||
stroke: yellow;
|
||||
}
|
||||
|
||||
.node {
|
||||
stroke: blue;
|
||||
}
|
||||
|
||||
.connector {
|
||||
stroke: green;
|
||||
}
|
||||
|
||||
.visibility {
|
||||
stroke: red;
|
||||
}
|
||||
|
||||
.all-nodes-bounding-box {
|
||||
stroke: purple;
|
||||
}
|
||||
|
||||
.import-export-name {
|
||||
stroke: orange;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.wires {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
|
||||
@@ -3,7 +3,7 @@ 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, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
||||
|
||||
@@ -13,7 +13,6 @@ export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId
|
||||
|
||||
type NodeGraphStoreState = {
|
||||
box: BoxSelection | undefined;
|
||||
clickTargets: FrontendClickTargets | undefined;
|
||||
contextMenuInformation: ContextMenuInformation | undefined;
|
||||
errors: NodeGraphErrorDiagnostic[];
|
||||
layerWidths: Map<bigint, number>;
|
||||
@@ -36,7 +35,6 @@ type NodeGraphStoreState = {
|
||||
};
|
||||
const initialState: NodeGraphStoreState = {
|
||||
box: undefined,
|
||||
clickTargets: undefined,
|
||||
contextMenuInformation: undefined,
|
||||
errors: [],
|
||||
layerWidths: new Map(),
|
||||
@@ -136,13 +134,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
|
||||
update((state) => {
|
||||
state.clickTargets = data.clickTargets;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
|
||||
update((state) => {
|
||||
state.contextMenuInformation = data.contextMenuInformation;
|
||||
@@ -330,7 +321,6 @@ export function destroyNodeGraphStore() {
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::mover::Mover;
|
||||
use crate::graph::LAYER_BOTTOM_GAP;
|
||||
use crate::per_node::PerNode;
|
||||
use crate::{NodeIndex, Placement};
|
||||
use glam::IVec2;
|
||||
use std::mem;
|
||||
|
||||
pub(super) struct Snapshot {
|
||||
placements: PerNode<Placement>,
|
||||
@@ -16,38 +16,85 @@ impl Mover {
|
||||
Snapshot { placements, positions }
|
||||
}
|
||||
|
||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) {
|
||||
let followers = self.followers(before, moved);
|
||||
let mut restored = PerNode::filled(&self.graph, false);
|
||||
followers
|
||||
.indices()
|
||||
.filter(|node| followers[*node])
|
||||
.for_each(|node| self.restore_follower(node, &followers, &before.positions, &mut restored));
|
||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) {
|
||||
let followers = self.followers(before, kept);
|
||||
let mut pushed = PerNode::filled(&self.graph, None);
|
||||
for node in followers.indices().filter(|node| followers[*node]) {
|
||||
self.restore_follower(node, &followers, &before.positions, &mut pushed);
|
||||
}
|
||||
}
|
||||
|
||||
fn followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) -> PerNode<bool> {
|
||||
fn followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) -> PerNode<bool> {
|
||||
let (graph, layout) = self.graph_and_layout();
|
||||
PerNode::from_fn(graph, |node| {
|
||||
let placement = graph[node].placement;
|
||||
let unchanged = placement == before.placements[node];
|
||||
let was_relative = matches!(before.placements[node], Placement::Relative(_));
|
||||
let is_relative = matches!(placement, Placement::Relative(_));
|
||||
!moved.contains(&node) && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
||||
kept[node] && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
||||
})
|
||||
}
|
||||
|
||||
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, restored: &mut PerNode<bool>) {
|
||||
if mem::replace(&mut restored[node], true) {
|
||||
return;
|
||||
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, pushed: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||
if let Some(push) = pushed[node] {
|
||||
return push;
|
||||
}
|
||||
pushed[node] = Some(IVec2::ZERO);
|
||||
|
||||
let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect();
|
||||
for reader in following_readers {
|
||||
self.restore_follower(reader, followers, positions_before, restored);
|
||||
let pushed_by_readers = following_readers
|
||||
.into_iter()
|
||||
.map(|reader| self.restore_follower(reader, followers, positions_before, pushed))
|
||||
.fold(IVec2::ZERO, IVec2::max);
|
||||
|
||||
let shift = positions_before[node] + pushed_by_readers - self.position(node);
|
||||
let shifted = self.graph[node].placement.shifted(shift);
|
||||
let clear = self.clear_of_the_layer_above(node, shifted);
|
||||
self.set_placement(node, clear);
|
||||
|
||||
let push = pushed_by_readers + clear.stored_offset() - shifted.stored_offset();
|
||||
pushed[node] = Some(push);
|
||||
push
|
||||
}
|
||||
|
||||
pub(super) fn carry_along(&mut self, before: &Snapshot, carried: &PerNode<bool>) {
|
||||
let mut shifts = PerNode::filled(&self.graph, None);
|
||||
for node in carried.indices().filter(|node| carried[*node]) {
|
||||
self.carry(node, carried, &before.positions, &mut shifts);
|
||||
}
|
||||
}
|
||||
|
||||
fn carry(&mut self, node: NodeIndex, carried: &PerNode<bool>, positions_before: &PerNode<IVec2>, shifts: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||
if let Some(shift) = shifts[node] {
|
||||
return shift;
|
||||
}
|
||||
shifts[node] = Some(IVec2::ZERO);
|
||||
|
||||
let readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).collect();
|
||||
let mut shift = IVec2::ZERO;
|
||||
for reader in readers {
|
||||
shift = if carried[reader] {
|
||||
self.carry(reader, carried, positions_before, shifts)
|
||||
} else {
|
||||
self.position(reader) - positions_before[reader]
|
||||
};
|
||||
if shift != IVec2::ZERO {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let shift = positions_before[node] - self.position(node);
|
||||
let shifted = self.graph[node].placement.shifted(shift);
|
||||
self.set_placement(node, shifted);
|
||||
shifts[node] = Some(shift);
|
||||
shift
|
||||
}
|
||||
|
||||
fn clear_of_the_layer_above(&self, node: NodeIndex, placement: Placement) -> Placement {
|
||||
let Placement::Relative(offset) = placement else { return placement };
|
||||
let layer_above = self.readers.of(&self.graph, node).find(|wire| self.graph.feeds_stack(wire)).map(|wire| wire.target);
|
||||
let Some(layer_above) = layer_above.filter(|_| offset.x == 0) else { return placement };
|
||||
|
||||
let lowest_free_row = self.graph[layer_above].size.y + LAYER_BOTTOM_GAP;
|
||||
Placement::Relative(IVec2::new(0, offset.y.max(lowest_free_row)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use crate::connections::WiresByNode;
|
||||
use crate::per_node::PerNode;
|
||||
use crate::{Graph, NodeIndex, Placement, Wire};
|
||||
use glam::IVec2;
|
||||
use std::mem;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct UpstreamOfDragged {
|
||||
moving_up_or_down: Upstream,
|
||||
moving_sideways: Upstream,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Upstream {
|
||||
pub(super) kept: PerNode<bool>,
|
||||
pub(super) carried: PerNode<bool>,
|
||||
}
|
||||
|
||||
impl UpstreamOfDragged {
|
||||
pub(super) fn new(graph: &Graph, dragged: &[NodeIndex]) -> Self {
|
||||
let inputs = WiresByNode::inputs(graph);
|
||||
let everything = upstream_through(graph, &inputs, dragged, |_| true);
|
||||
let into_a_node = |wire: &Wire| !graph[wire.target].is_layer();
|
||||
let split = |kept: PerNode<bool>| {
|
||||
let carried = PerNode::from_fn(graph, |node| everything[node] && !kept[node] && matches!(graph[node].placement, Placement::Absolute(_)));
|
||||
Upstream { kept, carried }
|
||||
};
|
||||
Self {
|
||||
moving_up_or_down: split(upstream_through(graph, &inputs, dragged, |wire| into_a_node(wire) || graph.feeds_stack(wire))),
|
||||
moving_sideways: split(upstream_through(graph, &inputs, dragged, into_a_node)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn moving_by(&self, shift: IVec2) -> &Upstream {
|
||||
if shift.x == 0 { &self.moving_up_or_down } else { &self.moving_sideways }
|
||||
}
|
||||
}
|
||||
|
||||
fn upstream_through(graph: &Graph, inputs: &WiresByNode, dragged: &[NodeIndex], followed: impl Fn(&Wire) -> bool) -> PerNode<bool> {
|
||||
let mut upstream = PerNode::filled(graph, false);
|
||||
for node in dragged {
|
||||
upstream[*node] = true;
|
||||
}
|
||||
dragged
|
||||
.iter()
|
||||
.flat_map(|node| inputs.of(graph, *node))
|
||||
.filter(|wire| followed(wire))
|
||||
.for_each(|wire| mark_upstream(graph, inputs, wire.source, &mut upstream));
|
||||
for node in dragged {
|
||||
upstream[*node] = false;
|
||||
}
|
||||
upstream
|
||||
}
|
||||
|
||||
fn mark_upstream(graph: &Graph, inputs: &WiresByNode, node: NodeIndex, upstream: &mut PerNode<bool>) {
|
||||
if mem::replace(&mut upstream[node], true) {
|
||||
return;
|
||||
}
|
||||
inputs.of(graph, node).for_each(|wire| mark_upstream(graph, inputs, wire.source, upstream));
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
mod followers;
|
||||
mod kept;
|
||||
mod mover;
|
||||
mod shift;
|
||||
mod stack;
|
||||
|
||||
use crate::{Graph, Layout, NodeIndex, Placement};
|
||||
use glam::IVec2;
|
||||
use kept::UpstreamOfDragged;
|
||||
use mover::Mover;
|
||||
|
||||
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
|
||||
@@ -12,7 +14,7 @@ use mover::Mover;
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
dragged: Vec<NodeIndex>,
|
||||
keep_upstream: bool,
|
||||
upstream: Option<UpstreamOfDragged>,
|
||||
rows_up: Vec<Graph>,
|
||||
held_in_place: Vec<HeldInPlace>,
|
||||
}
|
||||
@@ -26,8 +28,11 @@ struct HeldInPlace {
|
||||
|
||||
impl Drag {
|
||||
/// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn.
|
||||
/// Dragged layers still carry their content and chain, and carry the stacks below them when moved sideways.
|
||||
/// Nodes starting a tree of their own upstream of what moves follow the nodes reading them.
|
||||
#[must_use]
|
||||
pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self {
|
||||
let upstream = keep_upstream.then(|| UpstreamOfDragged::new(&start, &dragged));
|
||||
let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect();
|
||||
let mut mover = Mover::new(start, Some(start_layout));
|
||||
mover.hold(&dragged);
|
||||
@@ -45,7 +50,7 @@ impl Drag {
|
||||
.collect();
|
||||
Self {
|
||||
dragged,
|
||||
keep_upstream,
|
||||
upstream,
|
||||
rows_up: vec![held],
|
||||
held_in_place,
|
||||
}
|
||||
@@ -74,7 +79,7 @@ impl Drag {
|
||||
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
|
||||
.into_iter()
|
||||
.filter(|shift| *shift != IVec2::ZERO)
|
||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.keep_upstream));
|
||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.upstream.as_ref().map(|upstream| upstream.moving_by(shift))));
|
||||
mover.into_graph_and_layout()
|
||||
}
|
||||
|
||||
@@ -89,7 +94,7 @@ impl Drag {
|
||||
fn one_row_further_up(&self) -> Graph {
|
||||
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
|
||||
let mut mover = Mover::new(highest_so_far, None);
|
||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.keep_upstream);
|
||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.upstream.as_ref().map(|upstream| upstream.moving_by(IVec2::NEG_Y)));
|
||||
mover.into_graph()
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,27 @@
|
||||
use super::kept::Upstream;
|
||||
use super::mover::Mover;
|
||||
use crate::NodeIndex;
|
||||
use glam::IVec2;
|
||||
|
||||
impl Mover {
|
||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, keep_upstream: bool) {
|
||||
let before = keep_upstream.then(|| self.snapshot());
|
||||
let shifted = self.shift_nodes(dragged, shift);
|
||||
if let Some(before) = before {
|
||||
let moved: Vec<NodeIndex> = dragged.iter().chain(&shifted).copied().collect();
|
||||
self.restore_followers(&before, &moved);
|
||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, upstream: Option<&Upstream>) {
|
||||
let before = upstream.map(|upstream| (self.snapshot(), upstream));
|
||||
self.shift_nodes(dragged, shift);
|
||||
if let Some((before, upstream)) = before {
|
||||
self.restore_followers(&before, &upstream.kept);
|
||||
self.carry_along(&before, &upstream.carried);
|
||||
}
|
||||
}
|
||||
|
||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) -> Vec<NodeIndex> {
|
||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) {
|
||||
let mut shifted = Vec::new();
|
||||
for node in self.moving_on_their_own(nodes) {
|
||||
self.shift_node(node, shift, &mut shifted);
|
||||
}
|
||||
shifted
|
||||
}
|
||||
|
||||
fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) {
|
||||
let moving = self.node_moving_for(node, shift);
|
||||
let Some(moving) = self.node_moving_for(node, shift) else { return };
|
||||
if shifted.contains(&moving) {
|
||||
return;
|
||||
}
|
||||
@@ -34,12 +34,12 @@ impl Mover {
|
||||
self.place_at(moving, position + shift);
|
||||
}
|
||||
|
||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> NodeIndex {
|
||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> Option<NodeIndex> {
|
||||
let (stack, layout) = self.stack_and_layout();
|
||||
match shift {
|
||||
IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node),
|
||||
IVec2 { x: 0, .. } => node,
|
||||
_ => stack.top(node),
|
||||
IVec2 { x: 0, .. } => Some(node),
|
||||
_ => Some(stack.top(node)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,18 @@ impl Stack<'_> {
|
||||
self.climb(node, |layer| self.layer_above(layer))
|
||||
}
|
||||
|
||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> NodeIndex {
|
||||
self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)))
|
||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> Option<NodeIndex> {
|
||||
let top_of_closed_up_run = self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)));
|
||||
(!self.closed_up_under_its_parent(layout, top_of_closed_up_run)).then_some(top_of_closed_up_run)
|
||||
}
|
||||
|
||||
fn closed_up_under_its_parent(&self, layout: &Layout, layer: NodeIndex) -> bool {
|
||||
let parent = self
|
||||
.readers
|
||||
.of(self.graph, layer)
|
||||
.find(|wire| wire.is_primary() && self.graph[wire.target].is_layer() && !self.graph.feeds_stack(wire))
|
||||
.map(|wire| wire.target);
|
||||
self.graph[layer].is_layer() && parent.is_some_and(|parent| self.closed_up(layout, layer, parent))
|
||||
}
|
||||
|
||||
fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod common;
|
||||
|
||||
use common::{at, layer, stacked, wire};
|
||||
use common::{CHAINED, at, layer, node, stacked, wire};
|
||||
use glam::IVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Placement};
|
||||
|
||||
@@ -73,3 +73,148 @@ fn a_layer_pushed_up_with_its_upstream_kept_carries_the_layer_above_from_the_fir
|
||||
assert_eq!(layout.node(at(2)).position, before.node(at(2)).position + IVec2::new(0, -2));
|
||||
assert_eq!(layout.node(at(1)).position, before.node(at(1)).position + IVec2::new(0, -2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_dragged_up_with_its_upstream_kept_carries_its_chain_and_leaves_its_stack() {
|
||||
let start = Graph {
|
||||
nodes: vec![
|
||||
layer(Placement::Absolute(IVec2::new(30, 10))),
|
||||
node(CHAINED),
|
||||
node(Placement::Relative(IVec2::new(-8, 0))),
|
||||
layer(stacked(0)),
|
||||
],
|
||||
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 0, 0)],
|
||||
};
|
||||
let before = Layout::new(&start);
|
||||
let offset = IVec2::new(0, -4);
|
||||
|
||||
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(0)], true).moved(offset);
|
||||
|
||||
for carried in [0, 1, 2] {
|
||||
assert_eq!(layout.node(at(carried)).position, before.node(at(carried)).position + offset);
|
||||
}
|
||||
assert_eq!(layout.node(at(3)).position, before.node(at(3)).position);
|
||||
}
|
||||
|
||||
fn stack_of_layers_with_chains() -> Graph {
|
||||
let layers = [layer(Placement::Absolute(IVec2::new(30, 10))), layer(stacked(0)), layer(stacked(0))];
|
||||
let chains = [node(CHAINED), node(CHAINED), node(CHAINED)];
|
||||
let stack_wires = [wire(1, 0, 0), wire(2, 1, 0)];
|
||||
let chain_wires = [wire(3, 0, 1), wire(4, 1, 1), wire(5, 2, 1)];
|
||||
Graph {
|
||||
nodes: layers.into_iter().chain(chains).collect(),
|
||||
wires: stack_wires.into_iter().chain(chain_wires).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn moved_by_dragging(graph: &Graph, dragged: &[u32], offset: IVec2) -> Vec<u32> {
|
||||
let before = Layout::new(graph);
|
||||
let (_, layout) = Drag::new(graph.clone(), Layout::new(graph), dragged.iter().copied().map(at).collect(), true).moved(offset);
|
||||
let node_count = u32::try_from(graph.nodes.len()).unwrap();
|
||||
(0..node_count).filter(|index| layout.node(at(*index)).position != before.node(at(*index)).position).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_in_the_middle_of_a_stack_dragged_sideways_with_its_upstream_kept_moves_its_whole_stack() {
|
||||
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1], IVec2::new(10, 0)), vec![0, 1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_node_dragged_with_its_upstream_kept_moves_alone() {
|
||||
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[4], IVec2::new(0, 10)), vec![4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_pushed_up_with_its_upstream_kept_carries_the_closed_up_layers_above_with_their_chains() {
|
||||
let graph = stack_of_layers_with_chains();
|
||||
let mut stack_with_one_more_below = graph.clone();
|
||||
stack_with_one_more_below.nodes.push(layer(stacked(0)));
|
||||
stack_with_one_more_below.wires.push(wire(6, 2, 0));
|
||||
|
||||
assert_eq!(moved_by_dragging(&stack_with_one_more_below, &[2], IVec2::new(0, -1)), vec![0, 1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_of_one_stack_dragged_down_together_with_their_upstream_kept_carry_their_chains() {
|
||||
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1, 2], IVec2::new(0, 4)), vec![1, 2, 4, 5]);
|
||||
}
|
||||
|
||||
fn artboard_holding_a_stack_of_layers_with_chains() -> Graph {
|
||||
let artboard = layer(Placement::Absolute(IVec2::new(30, 10)));
|
||||
let layers = [layer(Placement::Relative(IVec2::new(-8, 3))), layer(stacked(0)), layer(stacked(0)), layer(stacked(0))];
|
||||
let chains = (0..4).flat_map(|_| [node(CHAINED), node(CHAINED), node(CHAINED)]);
|
||||
let stack_wires = [wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 0), wire(4, 3, 0)];
|
||||
let chain_wires = (0..4).flat_map(|layer| {
|
||||
let first = 5 + layer * 3;
|
||||
[wire(first, layer + 1, 1), wire(first + 1, first, 0), wire(first + 2, first + 1, 0)]
|
||||
});
|
||||
Graph {
|
||||
nodes: [artboard].into_iter().chain(layers).chain(chains).collect(),
|
||||
wires: stack_wires.into_iter().chain(chain_wires).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releasing_a_drag_draws_every_node_where_the_drag_drew_it() {
|
||||
let stack = artboard_holding_a_stack_of_layers_with_chains();
|
||||
let reading_a_tree = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
|
||||
let drags = [
|
||||
(&stack, vec![1, 2], IVec2::new(5, 0), true),
|
||||
(&stack, vec![1, 2], IVec2::new(5, 0), false),
|
||||
(&stack, vec![2], IVec2::new(5, 0), false),
|
||||
(&stack, vec![3], IVec2::new(0, -2), true),
|
||||
(&stack, vec![3], IVec2::new(0, 3), true),
|
||||
(&stack, vec![3], IVec2::new(0, -2), false),
|
||||
(&stack, vec![3], IVec2::new(0, 3), false),
|
||||
(&reading_a_tree, vec![2], IVec2::new(0, 3), true),
|
||||
(&reading_a_tree, vec![2], IVec2::new(5, 0), true),
|
||||
];
|
||||
for (start, dragged, offset, keep_upstream) in drags {
|
||||
let mut drag = Drag::new(start.clone(), Layout::new(start), dragged.iter().copied().map(at).collect(), keep_upstream);
|
||||
let (_, dragging) = drag.moved(offset);
|
||||
let released = Layout::new(&drag.released(offset));
|
||||
|
||||
let node_count = u32::try_from(start.nodes.len()).unwrap();
|
||||
let drawn = |layout: &Layout| (0..node_count).map(|index| layout.node(at(index)).position).collect::<Vec<_>>();
|
||||
assert_eq!(drawn(&released), drawn(&dragging), "dragging {dragged:?} by {offset} keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_closed_up_under_the_layer_holding_them_cannot_be_pushed_up_into_it() {
|
||||
let start = artboard_holding_a_stack_of_layers_with_chains();
|
||||
for keep_upstream in [false, true] {
|
||||
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(3)], keep_upstream).moved(IVec2::new(0, -2));
|
||||
assert_eq!(layout.node(at(1)).position, Layout::new(&start).node(at(1)).position, "keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
|
||||
fn artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own() -> Graph {
|
||||
Graph {
|
||||
nodes: vec![
|
||||
layer(Placement::Absolute(IVec2::new(30, 10))),
|
||||
layer(Placement::Relative(IVec2::new(-8, 3))),
|
||||
layer(stacked(0)),
|
||||
node(CHAINED),
|
||||
node(Placement::Absolute(IVec2::new(0, 30))),
|
||||
node(CHAINED),
|
||||
],
|
||||
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 1), wire(4, 3, 0), wire(5, 4, 0)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_dragged_with_its_upstream_kept_carries_the_trees_its_chain_reads() {
|
||||
let graph = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
|
||||
|
||||
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(0, 3)), vec![2, 3, 4, 5]);
|
||||
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(5, 0)), vec![1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trees_a_blocked_layer_reads_stay_with_it() {
|
||||
assert_eq!(
|
||||
moved_by_dragging(&artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own(), &[2], IVec2::new(0, -2)),
|
||||
Vec::<u32>::new()
|
||||
);
|
||||
}
|
||||
+2
-35
@@ -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 its graph text (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,40 +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 is written in graph text, a Rust-like syntax parsed at runtime by the `graph-text` crate. Built-in graphs are registered with the `core_types::graph!` macro, which only records the text and where it's written. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
graph! {
|
||||
#![syntax(1)]
|
||||
use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
|
||||
|
||||
/// Loads an image from a given URL.
|
||||
#[category("Data: I/O"), icon("NodeLoadImage")]
|
||||
fn load_image@1(
|
||||
_,
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url,
|
||||
) -> (
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url) >> bytes_to_image()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The text starts with its syntax version, `#![syntax(1)]`. The `use` section names each node by its identifier's module path and function name, at the declaration version it was written for, and `as` renames one. A graph's own version follows its name, like `load_image@1`. The graph's attributes are `category`, `icon`, `name`, and `layer`, and its name (or the title derived from its function name) is its catalog identifier, which documents store.
|
||||
|
||||
The function's parameters are the subgraph's imports, written without types, and `_` is a primary import that takes nothing. An import inherits its type, default, description, and widget settings from the inner parameter of its own name that it feeds, or else from the first one, and its attributes override those: `name`, `expose`, `default`, `widget`, `unit`, `hard`, `soft`, `range`, `step`, `display_decimal_places`, `multiline`, `progression`, `labels`, `integer`, and `blank_assist`. The exports are named in parentheses after `->`.
|
||||
|
||||
In the body, `let` binds a node, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. A value has the type it's written with, so `1` is an integer and `1.` a number, and `#[exposed]` before an argument exposes its value. State methods after a call, each written once, set the node's display name (`.named("…")`) and flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`). Nodes are placed left of the node they feed, so positions are only written to adjust that, with `.offset(x, y)` or `.at(x, y)` in grid units. A graph's output name after a call or binding, like `.captures`, wires from that output instead of the primary one. The body ends with one value per export.
|
||||
|
||||
The `every_graph_resolves` test in `subgraphs.rs` reports any graph whose text doesn't resolve, with the place it's written. Every input a call leaves out keeps the default from the node's own definition.
|
||||
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`
|
||||
|
||||
|
||||
@@ -542,9 +542,12 @@ tagged_value! {
|
||||
GlowTechnique(graphic_types::GlowTechnique),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
MaskMode(graphic_types::MaskMode),
|
||||
MinimumMaximumMode(graphic_types::MinimumMaximumMode),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
BevelTechnique(graphic_types::BevelTechnique),
|
||||
NoiseDistribution(graphic_types::NoiseDistribution),
|
||||
RadialBlurMethod(graphic_types::RadialBlurMethod),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -974,8 +977,6 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
|
||||
impl CacheHash for RenderOutputType {
|
||||
@@ -992,11 +993,6 @@ impl CacheHash for RenderOutputType {
|
||||
svg.cache_hash(state);
|
||||
image_data.cache_hash(state);
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.cache_hash(state);
|
||||
resolution.cache_hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
[package]
|
||||
name = "graph-ui"
|
||||
description = "The node graph UI of Graphite, drawn by Graphene"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
dyn-any = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graph-ui-icons = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
graphene-hash = { 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 }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
interpreted-executor = { workspace = true }
|
||||
preprocessor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
futures = { workspace = true }
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "graph-ui-icons"
|
||||
description = "The icons of the node graph UI of Graphite, as SVG sources"
|
||||
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
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// 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)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_icons_are_found_by_the_names_the_frontend_gives_them() {
|
||||
let icons_ts = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../frontend/src/icons.ts")).unwrap();
|
||||
let imported = icons_ts.lines().filter_map(|line| line.strip_prefix("import ")?.split_once(" from \"/../branding/assets/"));
|
||||
let names = imported
|
||||
.filter(|(_, path)| path.starts_with("16x16-nodes/") || path.starts_with("16x16-ui-general/"))
|
||||
.map(|(name, _)| name);
|
||||
let missing: Vec<_> = names.filter(|name| svg(name).is_none()).collect();
|
||||
assert!(SOURCES.is_empty() || missing.is_empty(), "{missing:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
use crate::metrics::{CONNECTOR_SIZE, GRID_SIZE, INPUT_CONNECTOR_LEFT, NODE_WIDTH, OUTPUT_CONNECTOR_RIGHT};
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Card {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub name: String,
|
||||
pub icon: String,
|
||||
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,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub enum Selection {
|
||||
None,
|
||||
Inactive,
|
||||
Active,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Connector {
|
||||
pub name: String,
|
||||
pub data_type: DataType,
|
||||
pub connected: bool,
|
||||
pub highlight: Highlight,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub enum Highlight {
|
||||
#[default]
|
||||
None,
|
||||
Hovered,
|
||||
WireSource,
|
||||
WireTarget,
|
||||
}
|
||||
|
||||
#[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
|
||||
}
|
||||
}
|
||||
|
||||
impl Card {
|
||||
pub fn rows(&self) -> usize {
|
||||
1 + self.secondary_inputs.len().max(self.secondary_outputs.len())
|
||||
}
|
||||
|
||||
pub fn body(&self) -> [DVec2; 2] {
|
||||
let top_left = (self.cell.as_dvec2() + DVec2::new(0., 0.5)) * GRID_SIZE + self.glide;
|
||||
[top_left, top_left + DVec2::new(NODE_WIDTH, self.rows() as f64 * GRID_SIZE)]
|
||||
}
|
||||
|
||||
pub fn inputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
|
||||
self.connectors(&self.primary_input, &self.secondary_inputs, INPUT_CONNECTOR_LEFT)
|
||||
}
|
||||
|
||||
pub fn outputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
|
||||
self.connectors(&self.primary_output, &self.secondary_outputs, NODE_WIDTH + OUTPUT_CONNECTOR_RIGHT - CONNECTOR_SIZE)
|
||||
}
|
||||
|
||||
fn connectors<'a>(&self, primary: &'a Option<Connector>, secondary: &'a [Connector], left: f64) -> impl Iterator<Item = (DVec2, &'a Connector)> {
|
||||
let [top_left, _] = self.body();
|
||||
let rows = primary
|
||||
.iter()
|
||||
.map(|connector| (0, connector))
|
||||
.chain(secondary.iter().enumerate().map(|(index, connector)| (index + 1, connector)));
|
||||
rows.map(move |(row, connector)| (top_left + DVec2::new(left, row as f64 * GRID_SIZE + (GRID_SIZE - CONNECTOR_SIZE) / 2.), connector))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{card, connector};
|
||||
|
||||
#[test]
|
||||
fn a_node_body_is_five_cells_wide_and_starts_half_a_cell_below_its_cell() {
|
||||
let mut card = Card {
|
||||
cell: IVec2::new(2, -1),
|
||||
primary_output: Some(connector("Shape")),
|
||||
..card(0)
|
||||
};
|
||||
assert_eq!(card.body(), [DVec2::new(48., -12.), DVec2::new(168., 12.)]);
|
||||
|
||||
card.secondary_inputs = vec![connector("Width"), connector("Height")];
|
||||
card.secondary_outputs = vec![connector("Area")];
|
||||
assert_eq!(card.body(), [DVec2::new(48., -12.), DVec2::new(168., 60.)], "a row for each secondary input");
|
||||
|
||||
let top_left = |(top_left, _): (DVec2, &Connector)| top_left;
|
||||
assert_eq!(card.inputs().map(top_left).collect::<Vec<_>>(), [DVec2::new(45., 20.), DVec2::new(45., 44.)], "no primary input");
|
||||
assert_eq!(card.outputs().map(top_left).collect::<Vec<_>>(), [DVec2::new(165., -4.), DVec2::new(165., 20.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gliding_card_is_drawn_its_glide_away() {
|
||||
let glide = DVec2::new(3., -4.);
|
||||
let gliding = Card { glide, ..card(0) };
|
||||
assert_eq!(gliding.body(), card(0).body().map(|corner| corner + glide));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
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)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vello_gpu::kurbo::Shape;
|
||||
|
||||
#[test]
|
||||
fn dashes_start_at_the_start_of_each_contour_and_are_cut_at_its_end() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0., 0.));
|
||||
path.line_to((12., 0.));
|
||||
path.move_to((0., 10.));
|
||||
path.line_to((4., 10.));
|
||||
let starts: Vec<Point> = dashed(&path, [3., 2.])
|
||||
.elements()
|
||||
.iter()
|
||||
.filter_map(|element| if let PathEl::MoveTo(point) = element { Some(*point) } else { None })
|
||||
.collect();
|
||||
assert_eq!(starts, [(0., 0.), (5., 0.), (10., 0.), (0., 10.)].map(Point::from));
|
||||
let ends: Vec<Point> = dashed(&path, [3., 2.])
|
||||
.elements()
|
||||
.iter()
|
||||
.filter_map(|element| if let PathEl::LineTo(point) = element { Some(*point) } else { None })
|
||||
.collect();
|
||||
assert_eq!(ends, [(3., 0.), (8., 0.), (12., 0.), (3., 10.)].map(Point::from));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_is_measured_along_chords_that_stray_from_it_by_at_most_half_a_pixel() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0., 0.));
|
||||
path.curve_to((0., 100.), (100., 100.), (100., 0.));
|
||||
let measured = measure(&contours(&path)[0]);
|
||||
let measured_length = measured.last().unwrap().distance;
|
||||
let length = vello_gpu::kurbo::ParamCurveArclen::arclen(&CubicBez::new((0., 0.), (0., 100.), (100., 100.), (100., 0.)), 1e-9);
|
||||
assert!(measured_length < length && length - measured_length < 1., "{measured_length} {length}");
|
||||
assert!(measured.windows(2).all(|pair| pair[0].t < pair[1].t), "the chords follow the curve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dashes_of_a_border_follow_its_outer_edge_with_flattened_corners_and_the_gap_nearest_two_pixels() {
|
||||
let starts = |path: &BezPath| {
|
||||
path.elements()
|
||||
.iter()
|
||||
.filter_map(|element| if let PathEl::MoveTo(point) = element { Some(*point) } else { None })
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let layer = starts(&border(DVec2::ZERO, DVec2::new(912., 48.), 8., &[], true));
|
||||
let on_top = layer.iter().filter(|point| point.y == 0.5).map(|point| point.x);
|
||||
assert!(
|
||||
on_top.clone().all(|x| ((x - 8.) / 5. - ((x - 8.) / 5.).round()).abs() < 1e-9),
|
||||
"the dashes along the top of a layer are five pixels apart"
|
||||
);
|
||||
assert_eq!(on_top.count(), 180);
|
||||
assert_eq!(layer.len(), 381);
|
||||
|
||||
assert_eq!(
|
||||
starts(&border(DVec2::ZERO, DVec2::new(120., 72.), 2., &[], true)).len(),
|
||||
76,
|
||||
"a node card, its corners measured as chords"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_border_is_left_out_inside_its_gaps_corners_included() {
|
||||
let [min, max] = [DVec2::ZERO, DVec2::new(100., 48.)];
|
||||
let starts = |path: &BezPath| path.elements().iter().filter(|element| matches!(element, PathEl::MoveTo(_))).count();
|
||||
assert_eq!(starts(&border(min, max, 8., &[], false)), 1);
|
||||
|
||||
let left = [DVec2::new(-8., -2.), DVec2::new(30., 50.)];
|
||||
let right = [DVec2::new(88., 12.), DVec2::new(112., 36.)];
|
||||
let cut = border(min, max, 8., &[left, right], false);
|
||||
assert_eq!(starts(&cut), 2, "the right gap splits what the left gap leaves");
|
||||
let bounds = cut.bounding_box();
|
||||
assert!((bounds.x0 - 30.).abs() < 1e-9 && bounds.x1 == 99.5, "{bounds:?}");
|
||||
let on_the_right = cut.elements().iter().filter_map(|element| element.end_point()).filter(|point| point.x == 99.5);
|
||||
assert!(
|
||||
on_the_right.clone().all(|point| !(12.001..=35.999).contains(&point.y)),
|
||||
"the right gap leaves out the middle of the right side"
|
||||
);
|
||||
assert!(on_the_right.clone().any(|point| (point.y - 12.).abs() < 1e-9) && on_the_right.clone().any(|point| (point.y - 36.).abs() < 1e-9));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use crate::card::{DataType, Highlight};
|
||||
use crate::metrics::GRID_SIZE;
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Dot {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub data_type: DataType,
|
||||
pub wired: bool,
|
||||
pub selected: bool,
|
||||
pub previewed: bool,
|
||||
pub highlight: Highlight,
|
||||
pub output_highlight: Highlight,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
impl Keyed for Dot {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Dot {
|
||||
pub fn center(&self) -> DVec2 {
|
||||
(self.cell.as_dvec2() + DVec2::Y) * GRID_SIZE + self.glide
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::dot;
|
||||
|
||||
#[test]
|
||||
fn a_dot_sits_on_the_left_edge_of_its_cell_a_cell_down() {
|
||||
let dot = Dot { cell: IVec2::new(2, -1), ..dot(0) };
|
||||
assert_eq!(dot.center(), DVec2::new(48., 0.));
|
||||
let gliding = Dot { glide: DVec2::new(3., -4.), ..dot };
|
||||
assert_eq!(gliding.center(), DVec2::new(51., -4.), "a gliding dot is drawn its glide away");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE, GRID_SIZE, LAYER_LEFT_MARGIN};
|
||||
use crate::replicated_map::Keyed;
|
||||
use crate::text;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct ErrorBadge {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub on_layer: bool,
|
||||
pub text: String,
|
||||
pub hovered: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
impl Keyed for ErrorBadge {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorBadge {
|
||||
fn anchor(&self) -> DVec2 {
|
||||
let offset = if self.on_layer { DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.) } else { DVec2::ZERO };
|
||||
self.cell.as_dvec2() * GRID_SIZE + offset + self.glide
|
||||
}
|
||||
|
||||
pub fn text_size(&self) -> DVec2 {
|
||||
text::paragraph_size(&self.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)
|
||||
}
|
||||
|
||||
pub fn body(&self, text_size: DVec2) -> [DVec2; 2] {
|
||||
let bottom_left = self.anchor();
|
||||
let size = text_size + 2. * ERROR_PADDING;
|
||||
[bottom_left - DVec2::Y * size.y, bottom_left + DVec2::X * size.x]
|
||||
}
|
||||
|
||||
pub fn text_top_left(&self, text_size: DVec2) -> DVec2 {
|
||||
let [top_left, _] = self.body(text_size);
|
||||
top_left + ERROR_PADDING
|
||||
}
|
||||
|
||||
pub fn tail(&self) -> [DVec2; 3] {
|
||||
let top_left = self.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(&self, point: DVec2, text_size: DVec2) -> bool {
|
||||
let [tail, ..] = self.tail();
|
||||
let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all();
|
||||
within(self.body(text_size)) || within([tail, tail + ERROR_TAIL_SIZE])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::badge;
|
||||
|
||||
#[test]
|
||||
fn a_badge_stands_half_a_cell_above_its_card_or_above_the_thumbnail_of_its_layer() {
|
||||
let badge = ErrorBadge {
|
||||
cell: IVec2::new(13, 22),
|
||||
..badge(0, "")
|
||||
};
|
||||
assert_eq!(badge.anchor(), DVec2::new(312., 528.));
|
||||
let on_layer = ErrorBadge { on_layer: true, ..badge };
|
||||
assert_eq!(on_layer.anchor(), DVec2::new(324., 516.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_badge_grows_up_and_right_from_its_anchor_with_its_tail_below() {
|
||||
let badge = ErrorBadge {
|
||||
cell: IVec2::new(2, 1),
|
||||
..badge(0, "")
|
||||
};
|
||||
let text_size = DVec2::new(100., 36.);
|
||||
assert_eq!(badge.body(text_size), [DVec2::new(48., -28.), DVec2::new(164., 24.)]);
|
||||
assert_eq!(badge.text_top_left(text_size), DVec2::new(56., -20.), "the text is padded");
|
||||
assert_eq!(badge.tail(), [DVec2::new(54., 24.), DVec2::new(66., 24.), DVec2::new(60., 32.)]);
|
||||
let glide = DVec2::new(3., -4.);
|
||||
let gliding = ErrorBadge { glide, ..badge.clone() };
|
||||
assert_eq!(gliding.body(text_size), badge.body(text_size).map(|corner| corner + glide), "a gliding badge is drawn its glide away");
|
||||
assert_eq!(gliding.tail(), badge.tail().map(|corner| corner + glide), "its tail glides with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_badge_covers_its_box_and_the_box_around_its_tail() {
|
||||
let badge = ErrorBadge {
|
||||
cell: IVec2::new(2, 1),
|
||||
..badge(0, "Error")
|
||||
};
|
||||
let text_size = badge.text_size();
|
||||
let covers = |point| badge.covers(point, text_size);
|
||||
let [min, max] = badge.body(text_size);
|
||||
assert!(covers(min) && covers(max - 1.) && covers((min + max) / 2.), "the box");
|
||||
assert!(covers(DVec2::new(55., 31.)), "beside the tip of the tail, inside the box around it");
|
||||
assert!(!covers(DVec2::new(52., 30.)), "left of the tail");
|
||||
assert!(!covers(max + 1.), "beyond the box");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// 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 })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::list::ATTR_APPEARANCE;
|
||||
use graphic_types::{Appearance, Cover, Graphic};
|
||||
|
||||
const CURRENT: SRGBA8 = SRGBA8::new_opaque(0x12, 0x34, 0x56);
|
||||
|
||||
fn icon(shapes: &str) -> Option<Icon> {
|
||||
convert(&format!(r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">{shapes}</svg>"#), CURRENT)
|
||||
}
|
||||
|
||||
fn hex(color: Option<SRGBA8>) -> Option<String> {
|
||||
color.map(|color| format!("{:02x}{:02x}{:02x}", color.red, color.green, color.blue))
|
||||
}
|
||||
|
||||
fn fills(icon: &Icon) -> Vec<Option<String>> {
|
||||
let fill = |index| match icon.shapes.attribute::<Appearance>(ATTR_APPEARANCE, index)?.first_paint_of(Cover::Fill)? {
|
||||
Graphic::Color(color) => hex(Some(SRGBA8::from(*color.element()))),
|
||||
_ => None,
|
||||
};
|
||||
(0..icon.shapes.len()).map(fill).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_class_names_its_color() {
|
||||
assert_eq!(hex(class_color("color-8-uppergray")).as_deref(), Some("888888"));
|
||||
assert_eq!(hex(class_color("color-number-dim")).as_deref(), Some("886b60"));
|
||||
assert_eq!(hex(class_color("color-mix-gradient-gradient-dim-85")).as_deref(), Some("7651a7"));
|
||||
assert_eq!(hex(class_color("color-mix-raster-dim-7-middlegray-50")).as_deref(), Some("89795d"));
|
||||
assert_eq!(class_color("color-sepia"), None);
|
||||
assert_eq!(class_color("color-mix-general-sepia-50"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_is_its_shapes_in_document_order_filled_with_their_class_colors_or_the_current_color() {
|
||||
let icon = icon(r#"<path class="color-number" d="M2,2L14,2L14,14Z" /><circle cx="8" cy="8" r="2" />"#).unwrap();
|
||||
assert_eq!(fills(&icon), [Some("c9a699".to_string()), hex(Some(CURRENT))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_overflows_when_a_shape_reaches_past_its_box() {
|
||||
assert!(!icon(r#"<rect x="2" y="2" width="12" height="12" />"#).unwrap().overflows);
|
||||
assert!(icon(r#"<path d="M14,2L17,2L17,5L14,5Z" />"#).unwrap().overflows);
|
||||
assert!(
|
||||
icon(r#"<rect transform="translate(4)" x="2" y="2" width="12" height="12" />"#).unwrap().overflows,
|
||||
"moved out by its transform"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_with_an_unknown_color_class_is_left_out() {
|
||||
assert!(icon(r#"<path class="color-sepia" d="M2,2L14,2Z" />"#).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use crate::card::{Connector, Selection};
|
||||
use crate::metrics::{
|
||||
CONNECTOR_SIZE, GRID_SIZE, INPUT_CONNECTOR_LEFT, LAYER_BUTTON_SIZE, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_HEIGHT, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET,
|
||||
LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, STACK_CONNECTOR_SIZE,
|
||||
};
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Layer {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub name: String,
|
||||
pub renaming: bool,
|
||||
pub width: u32,
|
||||
pub chain_width: u32,
|
||||
pub has_left_input_wire: bool,
|
||||
pub primary_input: Option<Connector>,
|
||||
pub primary_output: Option<Connector>,
|
||||
pub secondary_input: Option<Connector>,
|
||||
pub primary_input_connected_to_layer: bool,
|
||||
pub primary_output_connected_to_layer: bool,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
pub read_only: bool,
|
||||
pub selection: Selection,
|
||||
pub previewed: bool,
|
||||
pub hovered_button: Option<LayerButton>,
|
||||
pub hovered_button_clicked: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub enum LayerButton {
|
||||
Visibility,
|
||||
Lock,
|
||||
Grip,
|
||||
}
|
||||
|
||||
impl Keyed for Layer {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
fn top_left(&self) -> DVec2 {
|
||||
self.cell.as_dvec2() * GRID_SIZE + self.glide
|
||||
}
|
||||
|
||||
pub fn body(&self) -> [DVec2; 2] {
|
||||
let top_left = self.top_left();
|
||||
let left = if self.chain_width > 0 { -(self.chain_width as f64) * GRID_SIZE } else { LAYER_LEFT_MARGIN };
|
||||
[top_left + DVec2::X * left, top_left + DVec2::new(self.width as f64 * GRID_SIZE, LAYER_HEIGHT)]
|
||||
}
|
||||
|
||||
pub fn left_input_wire(&self) -> Option<DVec2> {
|
||||
let [min, _] = self.body();
|
||||
(self.has_left_input_wire && self.chain_width > 0).then(|| DVec2::new(min.x, min.y + LAYER_HEIGHT / 2.))
|
||||
}
|
||||
|
||||
pub fn thumbnail_block(&self) -> [DVec2; 2] {
|
||||
let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN;
|
||||
[left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, LAYER_HEIGHT)]
|
||||
}
|
||||
|
||||
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.top_left() + DVec2::new(INPUT_CONNECTOR_LEFT, (LAYER_HEIGHT - CONNECTOR_SIZE) / 2.)
|
||||
}
|
||||
|
||||
pub fn name_box(&self) -> [DVec2; 2] {
|
||||
let top_left = self.top_left() + DVec2::new(LAYER_NAME_LEFT, (LAYER_HEIGHT - GRID_SIZE) / 2.);
|
||||
[top_left, top_left + DVec2::new(self.name_width(), GRID_SIZE)]
|
||||
}
|
||||
|
||||
pub fn name_width(&self) -> f64 {
|
||||
self.width as f64 * GRID_SIZE - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN
|
||||
}
|
||||
|
||||
pub fn visibility(&self) -> [DVec2; 2] {
|
||||
let [_, max] = self.body();
|
||||
let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.top_left().y + (LAYER_HEIGHT - LAYER_BUTTON_SIZE) / 2.);
|
||||
[top_left, top_left + LAYER_BUTTON_SIZE]
|
||||
}
|
||||
|
||||
pub 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]
|
||||
}
|
||||
|
||||
pub fn lock(&self) -> Option<[DVec2; 2]> {
|
||||
let [min, max] = self.visibility();
|
||||
self.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::layer;
|
||||
|
||||
#[test]
|
||||
fn a_layer_spans_its_width_from_half_a_cell_into_its_cell() {
|
||||
let layer = Layer {
|
||||
cell: IVec2::new(2, -1),
|
||||
has_left_input_wire: true,
|
||||
..layer(0)
|
||||
};
|
||||
assert_eq!(layer.body(), [DVec2::new(60., -24.), DVec2::new(240., 24.)]);
|
||||
assert_eq!(layer.thumbnail_block(), [DVec2::new(60., -24.), DVec2::new(132., 24.)]);
|
||||
assert_eq!(layer.thumbnail(), [DVec2::new(61., -24.), DVec2::new(131., 24.)], "a pixel in from each side of its block");
|
||||
assert_eq!(
|
||||
layer.thumbnail_image(),
|
||||
[DVec2::new(63., -22.), DVec2::new(129., 22.)],
|
||||
"two pixels in from the thumbnail, at its aspect ratio"
|
||||
);
|
||||
assert_eq!(
|
||||
layer.name_box(),
|
||||
[DVec2::new(140., -12.), DVec2::new(232., 12.)],
|
||||
"the name follows the thumbnail and ends a margin short of the right edge"
|
||||
);
|
||||
assert_eq!(layer.stack_output(), DVec2::new(92., -36.), "the stack connectors are centred above and below the thumbnail");
|
||||
assert_eq!(layer.stack_input(), DVec2::new(92., 24.));
|
||||
assert_eq!(layer.secondary_input_connector(), DVec2::new(45., -4.), "the input on the left side sits where a node's would");
|
||||
assert_eq!(
|
||||
layer.visibility(),
|
||||
[DVec2::new(228., -12.), DVec2::new(252., 12.)],
|
||||
"the visibility button is centred on the right edge"
|
||||
);
|
||||
assert_eq!(layer.left_input_wire(), None, "no chain for a wire to enter");
|
||||
let gliding = Layer {
|
||||
glide: DVec2::new(3., -4.),
|
||||
..layer.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
gliding.visibility(),
|
||||
layer.visibility().map(|corner| corner + DVec2::new(3., -4.)),
|
||||
"a gliding layer is drawn its glide away"
|
||||
);
|
||||
assert_eq!(layer.lock(), None, "an unlocked layer has no lock button");
|
||||
let locked = Layer { locked: true, ..layer.clone() };
|
||||
assert_eq!(locked.lock(), Some([DVec2::new(204., -12.), DVec2::new(228., 12.)]), "the lock button is left of the visibility button");
|
||||
assert_eq!(layer.grip(), [DVec2::new(220., -12.), DVec2::new(228., 12.)], "the grip is left of the visibility button");
|
||||
assert_eq!(locked.grip(), [DVec2::new(196., -12.), DVec2::new(204., 12.)], "the grip is left of the lock button");
|
||||
|
||||
let chained = Layer { chain_width: 8, ..layer };
|
||||
assert_eq!(chained.body(), [DVec2::new(-144., -24.), DVec2::new(240., 24.)], "the chain reaches left of the cell");
|
||||
assert_eq!(chained.thumbnail_block()[0], DVec2::new(60., -24.), "the thumbnail stays where it is");
|
||||
assert_eq!(chained.left_input_wire(), Some(DVec2::new(-144., 0.)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphic_types::Graphic;
|
||||
use network_connector::NetworkConnectorKind;
|
||||
use scene::GraphUiScene;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use wire::WireInProgress;
|
||||
|
||||
pub mod card;
|
||||
mod dashes;
|
||||
pub mod dot;
|
||||
pub mod error_badge;
|
||||
pub mod icons;
|
||||
pub mod layer;
|
||||
mod look;
|
||||
pub mod metrics;
|
||||
pub mod network_connector;
|
||||
pub mod nodes;
|
||||
pub mod render;
|
||||
pub mod replicated_map;
|
||||
pub mod scene;
|
||||
#[cfg(test)]
|
||||
mod test_utils;
|
||||
mod text;
|
||||
pub mod wire;
|
||||
|
||||
#[derive(CacheHash)]
|
||||
pub struct GraphUi {
|
||||
pub scene: GraphUiScene,
|
||||
pub config: GraphUiConfig,
|
||||
pub thumbnails: Arc<BTreeMap<NodeId, Graphic>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, CacheHash)]
|
||||
pub struct GraphUiConfig {
|
||||
pub view: DAffine2,
|
||||
pub fade_artwork: f64,
|
||||
pub wire_in_progress: Option<WireInProgress>,
|
||||
pub reorder_bar: Option<(NetworkConnectorKind, DVec2)>,
|
||||
pub box_selection: Option<[DVec2; 2]>,
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use crate::card::{Connector, DataType, 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) -> List<Vector> {
|
||||
drawn_connector(outline, top_left, connector.data_type, connector.connected, connector.highlight)
|
||||
}
|
||||
|
||||
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List<Vector> {
|
||||
let [bright, dim] = data_type_colors(data_type);
|
||||
match highlight {
|
||||
Highlight::None => List::new_from_item(outlined(outline, top_left, if connected { bright } else { dim })),
|
||||
Highlight::WireSource => List::new_from_item(outlined(outline, top_left, bright)),
|
||||
Highlight::Hovered | Highlight::WireTarget => {
|
||||
let grown = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(HOVERED_CONNECTOR_SCALE, outline.bounding_box().center()) * outline.clone();
|
||||
let grown = Vector::item_from_bezpath(&grown);
|
||||
let ring = Stroke {
|
||||
join: StrokeJoin::Round,
|
||||
..Stroke::new(HOVERED_CONNECTOR_RING * HOVERED_CONNECTOR_SCALE)
|
||||
};
|
||||
List::from_iter([painted(grown.clone(), Coverage::new_stroke(&ring), dim.into()), painted(grown, Coverage::new_fill(), bright.into())])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use glam::DVec2;
|
||||
|
||||
pub const GRID_SIZE: f64 = 24.;
|
||||
pub const GRID_COLLAPSE_SPACING: f64 = 10.;
|
||||
pub const TEXT_SIZE: f64 = 14.;
|
||||
pub const BORDER_WIDTH: f64 = 1.;
|
||||
pub const BORDER_DASHES: [f64; 2] = [3., 2.];
|
||||
pub const ICON_SIZE: f64 = 16.;
|
||||
|
||||
pub const NODE_WIDTH: f64 = 5. * GRID_SIZE;
|
||||
pub const NODE_RADIUS: f64 = 2.;
|
||||
pub const NODE_ICON_LEFT: f64 = 8.;
|
||||
pub const NODE_NAME_LEFT: f64 = 32.;
|
||||
pub const NODE_NAME_MAX_WIDTH: f64 = 84.;
|
||||
pub const NODE_ROW_PADDING: f64 = 8.;
|
||||
|
||||
pub const CONNECTOR_SIZE: f64 = 8.;
|
||||
pub const INPUT_CONNECTOR_LEFT: f64 = -3.;
|
||||
pub const OUTPUT_CONNECTOR_RIGHT: f64 = 5.;
|
||||
pub const CONNECTOR_GAP: f64 = 16.;
|
||||
pub const HOVERED_CONNECTOR_SCALE: f64 = 1.3;
|
||||
pub const HOVERED_CONNECTOR_RING: f64 = 4.;
|
||||
pub const STACK_CONNECTOR_SIZE: DVec2 = DVec2::new(CONNECTOR_SIZE, 12.);
|
||||
|
||||
pub const IMPORT_EXPORT_CONNECTOR: DVec2 = DVec2::new(INPUT_CONNECTOR_LEFT, -CONNECTOR_SIZE / 2.);
|
||||
pub const IMPORT_NAME_INSET: f64 = 8.;
|
||||
pub const EXPORT_NAME_INSET: f64 = 9.;
|
||||
pub const IMPORT_EXPORT_NAME_RAISE: f64 = 1.;
|
||||
pub const IMPORT_EXPORT_SEPARATOR_OVERHANG: f64 = 4.;
|
||||
pub const REORDER_BAR_SIZE: DVec2 = DVec2::new(50., 2.);
|
||||
|
||||
pub const ERROR_PADDING: f64 = 8.;
|
||||
pub const ERROR_LINE_HEIGHT: f64 = 18.;
|
||||
pub const ERROR_MAX_WIDTH: f64 = 600.;
|
||||
pub const ERROR_RADIUS: f64 = 4.;
|
||||
pub const ERROR_TAIL_LEFT: f64 = 6.;
|
||||
pub const ERROR_TAIL_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
|
||||
pub const WIRE_WIDTH: f64 = 2.;
|
||||
pub const LIST_WIRE_WIDTH: f64 = 4.;
|
||||
pub const WIRE_DASHES: [f64; 2] = [3., 2.];
|
||||
pub const THICK_WIRE_WIDTH: f64 = 8.;
|
||||
|
||||
pub const DOT_RADIUS: f64 = 5.;
|
||||
pub const DOT_SELECTED_RING: f64 = 2.;
|
||||
pub const DOT_PREVIEWED_RING_OFFSET: f64 = 2.;
|
||||
pub const DOT_HOVERED_RING: f64 = 2.;
|
||||
pub const DOT_OUTPUT_ARROW: DVec2 = DVec2::new(6., -4.);
|
||||
|
||||
pub const LAYER_HEIGHT: f64 = 2. * GRID_SIZE;
|
||||
pub const LAYER_RADIUS: f64 = 8.;
|
||||
pub const LAYER_LEFT_MARGIN: f64 = GRID_SIZE / 2.;
|
||||
pub const LAYER_THUMBNAIL_WIDTH: f64 = 3. * GRID_SIZE;
|
||||
pub const LAYER_THUMBNAIL_MARGIN: f64 = 1.;
|
||||
pub const LAYER_THUMBNAIL_RADIUS: f64 = 2.;
|
||||
pub const LAYER_THUMBNAIL_IMAGE_INSET: f64 = 2.;
|
||||
pub const CHECKER_CELL: f64 = 8.;
|
||||
pub const LAYER_DETAILS_MARGIN: f64 = 8.;
|
||||
pub const LAYER_NAME_LEFT: f64 = LAYER_LEFT_MARGIN + LAYER_THUMBNAIL_WIDTH + LAYER_DETAILS_MARGIN;
|
||||
pub const LAYER_BUTTON_SIZE: f64 = GRID_SIZE;
|
||||
pub const LAYER_BUTTON_RADIUS: f64 = 2.;
|
||||
pub const LAYER_GRIP_WIDTH: f64 = 8.;
|
||||
pub const LAYER_GRIP_DOTS: DVec2 = DVec2::new(2.5, 9.5);
|
||||
pub const LAYER_GRIP_DOT_COUNT: [u32; 2] = [2, 3];
|
||||
pub const LAYER_GRIP_DOT_SPACING: f64 = 3.;
|
||||
pub const LAYER_GRIP_DOT_RADIUS: f64 = 0.5;
|
||||
pub const LAYER_THUMBNAIL_GAP: DVec2 = DVec2::new(8., 2.);
|
||||
@@ -0,0 +1,117 @@
|
||||
use crate::card::{Connector, Highlight};
|
||||
use crate::metrics::{BORDER_WIDTH, EXPORT_NAME_INSET, GRID_SIZE, IMPORT_EXPORT_CONNECTOR, IMPORT_EXPORT_NAME_RAISE, IMPORT_EXPORT_SEPARATOR_OVERHANG, IMPORT_NAME_INSET, REORDER_BAR_SIZE};
|
||||
use crate::replicated_map::Keyed;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||
pub enum NetworkConnectorKind {
|
||||
Import,
|
||||
Export,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct NetworkConnector {
|
||||
pub kind: NetworkConnectorKind,
|
||||
pub index: usize,
|
||||
pub position: IVec2,
|
||||
pub connector: Option<Connector>,
|
||||
pub add_highlight: Highlight,
|
||||
pub editable: bool,
|
||||
pub renaming: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
impl Keyed for NetworkConnector {
|
||||
type Key = (NetworkConnectorKind, usize);
|
||||
|
||||
fn key(&self) -> (NetworkConnectorKind, usize) {
|
||||
(self.kind, self.index)
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkConnector {
|
||||
pub fn anchor(&self) -> DVec2 {
|
||||
self.position.as_dvec2() + self.glide
|
||||
}
|
||||
|
||||
pub fn connector_top_left(&self) -> DVec2 {
|
||||
self.anchor() + IMPORT_EXPORT_CONNECTOR
|
||||
}
|
||||
|
||||
pub fn name_box(&self, width: f64) -> [DVec2; 2] {
|
||||
let anchor = self.anchor();
|
||||
let left = match self.kind {
|
||||
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - width,
|
||||
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
|
||||
};
|
||||
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2. - IMPORT_EXPORT_NAME_RAISE);
|
||||
[top_left, top_left + DVec2::new(width, GRID_SIZE)]
|
||||
}
|
||||
|
||||
pub fn separator(&self, name_width: f64) -> [DVec2; 2] {
|
||||
let [name_min, name_max] = self.name_box(name_width);
|
||||
let toward_the_line = if self.index == 0 { GRID_SIZE } else { -GRID_SIZE };
|
||||
let top = self.anchor().y + toward_the_line - BORDER_WIDTH;
|
||||
[
|
||||
DVec2::new(name_min.x - IMPORT_EXPORT_SEPARATOR_OVERHANG, top),
|
||||
DVec2::new(name_max.x + IMPORT_EXPORT_SEPARATOR_OVERHANG, top + BORDER_WIDTH),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reorder_bar(kind: NetworkConnectorKind, anchor: DVec2) -> [DVec2; 2] {
|
||||
let left = match kind {
|
||||
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - REORDER_BAR_SIZE.x,
|
||||
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
|
||||
};
|
||||
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.);
|
||||
[top_left, top_left + REORDER_BAR_SIZE]
|
||||
}
|
||||
|
||||
pub fn import_export_row_offset(index: usize) -> f64 {
|
||||
let rows = if index == 0 { 0 } else { index + 1 };
|
||||
rows as f64 * GRID_SIZE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::network_connector;
|
||||
|
||||
#[test]
|
||||
fn the_name_of_an_import_ends_left_of_its_connector_and_the_name_of_an_export_starts_right_of_it() {
|
||||
let primary = NetworkConnector {
|
||||
position: IVec2::new(48, -24),
|
||||
..network_connector(NetworkConnectorKind::Import, 0)
|
||||
};
|
||||
let secondary = NetworkConnector {
|
||||
position: IVec2::new(48, 24),
|
||||
..network_connector(NetworkConnectorKind::Import, 1)
|
||||
};
|
||||
assert_eq!(secondary.connector_top_left(), DVec2::new(45., 20.), "the connector box beside the anchor");
|
||||
let gliding = NetworkConnector {
|
||||
glide: DVec2::new(3., -4.),
|
||||
..secondary.clone()
|
||||
};
|
||||
assert_eq!(gliding.anchor(), DVec2::new(51., 20.), "a gliding import is drawn its glide away");
|
||||
assert_eq!(primary.name_box(30.), [DVec2::new(10., -37.), DVec2::new(40., -13.)], "an import's name ends left of its connector");
|
||||
let export = NetworkConnector {
|
||||
kind: NetworkConnectorKind::Export,
|
||||
..primary.clone()
|
||||
};
|
||||
assert_eq!(export.name_box(30.), [DVec2::new(57., -37.), DVec2::new(87., -13.)], "an export's name starts right of its connector");
|
||||
assert_eq!(primary.separator(30.), [DVec2::new(6., -1.), DVec2::new(44., 0.)], "the line under the primary name");
|
||||
assert_eq!(secondary.separator(20.), [DVec2::new(16., -1.), DVec2::new(44., 0.)], "the line over the next name, the same line");
|
||||
assert_eq!(
|
||||
reorder_bar(NetworkConnectorKind::Import, secondary.anchor()),
|
||||
[DVec2::new(-10., 12.), DVec2::new(40., 14.)],
|
||||
"the bar where an import would be dropped, above its row"
|
||||
);
|
||||
assert_eq!(
|
||||
reorder_bar(NetworkConnectorKind::Export, primary.anchor()),
|
||||
[DVec2::new(57., -36.), DVec2::new(107., -34.)],
|
||||
"the bar where an export would be dropped"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
use crate::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use crate::dashes::{border, dashed};
|
||||
use crate::dot::Dot;
|
||||
use crate::error_badge::ErrorBadge;
|
||||
use crate::layer::{Layer, LayerButton};
|
||||
use crate::look::{
|
||||
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, outlined, painted, rounded_rect, text,
|
||||
};
|
||||
use crate::metrics::{
|
||||
BORDER_WIDTH, 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, NODE_ICON_LEFT, NODE_NAME_LEFT, NODE_NAME_MAX_WIDTH, NODE_RADIUS, NODE_ROW_PADDING, NODE_WIDTH, THICK_WIRE_WIDTH,
|
||||
WIRE_DASHES, WIRE_WIDTH,
|
||||
};
|
||||
use crate::network_connector::{NetworkConnector, reorder_bar};
|
||||
use crate::render::{graph_ui, render_config};
|
||||
use crate::replicated_map::{Keyed, ReplicatedMap};
|
||||
use crate::text::{Labels, Paragraphs};
|
||||
use crate::wire::{Wire, WireKey};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, Item, List};
|
||||
use core_types::transform::ApplyTransform;
|
||||
use core_types::{Color, Ctx, ExtractVarArgs};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::convert::Infallible;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
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;
|
||||
|
||||
fn rows<T: Keyed + 'static>(ctx: &impl ExtractVarArgs, index: usize) -> &ReplicatedMap<T> {
|
||||
ctx.vararg(index).ok().and_then(|rows| rows.downcast_ref()).expect("A scene band is given the rows it draws")
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_grid(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let render_config = render_config(&ctx);
|
||||
let viewport_size = render_config.viewport.resolution.as_dvec2() / render_config.scale;
|
||||
grid_dots(graph_ui(&ctx).config.view, viewport_size, render_config.scale)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
type Cache<Row, Texts = ()> = Arc<Mutex<RowCache<Row, Texts>>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RowCache<Row: Keyed, Texts> {
|
||||
drawn: BTreeMap<Row::Key, (Row, List<Vector>)>,
|
||||
labels: Texts,
|
||||
}
|
||||
|
||||
impl<Row: Keyed, Texts: Default> Default for RowCache<Row, Texts> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
drawn: BTreeMap::new(),
|
||||
labels: Texts::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_changed_rows<'a, Row: Keyed + Placed + PartialEq + 'a, Texts, Error>(
|
||||
rows: impl IntoIterator<Item = &'a Row>,
|
||||
cache: &mut RowCache<Row, Texts>,
|
||||
draw: impl Fn(&Row, &mut Texts) -> Result<List<Vector>, Error>,
|
||||
) -> Result<List<Vector>, Error> {
|
||||
let mut kept = BTreeMap::new();
|
||||
let mut graphic = List::new();
|
||||
for row in rows {
|
||||
let entry = match cache.drawn.remove(&row.key()).map(|(drawn, drawing)| (drawn.placed_at(row.place()), drawing)) {
|
||||
Some(entry) if entry.0 == *row => entry,
|
||||
_ => {
|
||||
let at_origin = row.clone().placed_at(Default::default());
|
||||
let drawing = draw(&at_origin, &mut cache.labels)?;
|
||||
(at_origin, drawing)
|
||||
}
|
||||
};
|
||||
let mut placed = entry.1.clone();
|
||||
let offset = row.offset();
|
||||
if offset != DVec2::ZERO {
|
||||
placed.left_apply_transform(&DAffine2::from_translation(offset));
|
||||
}
|
||||
graphic.extend(placed);
|
||||
kept.insert(row.key(), entry);
|
||||
}
|
||||
cache.drawn = kept;
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_rows<'a, Row: Keyed + Placed + PartialEq + 'a>(rows: impl IntoIterator<Item = &'a Row>, cache: &Cache<Row>, draw: impl Fn(&Row) -> List<Vector>) -> List<Vector> {
|
||||
let Ok(graphic) = draw_changed_rows(rows, &mut cache.lock().unwrap_or_else(PoisonError::into_inner), |row, _| Ok::<_, Infallible>(draw(row)));
|
||||
graphic
|
||||
}
|
||||
|
||||
trait Placed: Clone {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn placed_at(self, _place: (IVec2, DVec2)) -> Self {
|
||||
self
|
||||
}
|
||||
|
||||
fn offset(&self) -> DVec2 {
|
||||
let (cell, glide) = self.place();
|
||||
cell.as_dvec2() * GRID_SIZE + glide
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for Wire {}
|
||||
|
||||
impl Placed for Card {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for Layer {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for Dot {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for ErrorBadge {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for NetworkConnector {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.position, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (position, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { position, glide, ..self }
|
||||
}
|
||||
|
||||
fn offset(&self) -> DVec2 {
|
||||
self.position.as_dvec2() + self.glide
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_layers(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Layer, Labels>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let layers = rows::<Layer>(&ctx, 0);
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(layers, &mut cache, draw_layer)?;
|
||||
|
||||
let shown: HashSet<&str> = layers.iter().map(|layer| layer.name.as_str()).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_layer(layer: &Layer, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||
let mut graphic = List::new();
|
||||
let [min, max] = layer.body();
|
||||
let fill = match (layer.selection, layer.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.renaming {
|
||||
let [name, _] = layer.name_box();
|
||||
let text_color = if layer.visible { TEXT } else { HIDDEN_TEXT };
|
||||
graphic.extend(text(&labels.label(&layer.name, layer.name_width())?.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.primary_output {
|
||||
graphic.extend(connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output));
|
||||
if output.connected && layer.primary_output_connected_to_layer {
|
||||
graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1]));
|
||||
}
|
||||
}
|
||||
match &layer.primary_input {
|
||||
Some(input) => {
|
||||
graphic.extend(connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input));
|
||||
if input.connected && layer.primary_input_connected_to_layer {
|
||||
graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1]));
|
||||
}
|
||||
}
|
||||
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.previewed));
|
||||
let border_color = if layer.previewed { PREVIEWED_BORDER } else { BORDER };
|
||||
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_thumbnails(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let graph_ui = graph_ui(&ctx);
|
||||
let thumbnails = graph_ui.thumbnails.iter().filter_map(|(key, thumbnail)| Some((graph_ui.scene.layers().get(key)?, thumbnail)));
|
||||
thumbnails
|
||||
.map(|(layer, thumbnail)| {
|
||||
let [min, max] = layer.thumbnail_image();
|
||||
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
|
||||
image.left_apply_transform(&DAffine2::from_scale_angle_translation(max - min, 0., min));
|
||||
stamp_coverage(&mut image, Coverage::new_fill(), thumbnail.clone(), CoverPlacement::Above);
|
||||
image
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_raised(ctx: impl Ctx + ExtractVarArgs, #[data] layers: Cache<Layer>, #[data] cards: Cache<Card>) -> List<Vector> {
|
||||
let mut graphic = draw_rows(rows::<Layer>(&ctx, 0), layers, draw_raised_parts_of_layer);
|
||||
graphic.extend(draw_rows(rows::<Card>(&ctx, 1), cards, draw_connectors_of_card));
|
||||
graphic
|
||||
}
|
||||
|
||||
fn draw_raised_parts_of_layer(layer: &Layer) -> List<Vector> {
|
||||
let mut graphic = List::new();
|
||||
if let Some(input) = &layer.secondary_input {
|
||||
graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input));
|
||||
}
|
||||
let hovered = |button| layer.hovered_button == Some(button);
|
||||
let grip_color = match (hovered(LayerButton::Grip), layer.selection != Selection::None) {
|
||||
(true, _) => Some(Color::WHITE),
|
||||
(false, true) => Some(TEXT.into()),
|
||||
(false, false) => None,
|
||||
};
|
||||
if let Some(grip_color) = grip_color {
|
||||
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));
|
||||
}
|
||||
graphic.push(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color));
|
||||
}
|
||||
|
||||
let mut button = |[min, max]: [DVec2; 2], which: LayerButton, [resting, hover]: [&str; 2]| {
|
||||
let hovered = hovered(which) && !layer.read_only;
|
||||
if hovered {
|
||||
graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into()));
|
||||
}
|
||||
let name = if hovered && !layer.hovered_button_clicked { hover } else { resting };
|
||||
graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.read_only { DISABLED_ICON } else { TEXT }));
|
||||
};
|
||||
if let Some(lock) = layer.lock() {
|
||||
button(lock, LayerButton::Lock, ["PadlockLocked", "PadlockUnlocked"]);
|
||||
}
|
||||
let eye = if layer.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] };
|
||||
button(layer.visibility(), LayerButton::Visibility, eye);
|
||||
graphic
|
||||
}
|
||||
|
||||
fn draw_connectors_of_card(card: &Card) -> List<Vector> {
|
||||
card.inputs()
|
||||
.chain(card.outputs())
|
||||
.flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_thick_wires(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Wire>) -> List<Vector> {
|
||||
draw_rows(rows::<Wire>(&ctx, 0).iter().filter(|wire| wire.thick), cache, draw_wire)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_wires(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Wire>) -> List<Vector> {
|
||||
draw_rows(rows::<Wire>(&ctx, 0).iter().filter(|wire| !wire.thick), cache, draw_wire)
|
||||
}
|
||||
|
||||
fn draw_wire(wire: &Wire) -> 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(&wire.path);
|
||||
if wire.thick {
|
||||
List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(&wire.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))
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_wire_in_progress(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let Some(wire) = graph_ui(&ctx).config.wire_in_progress else { return List::new() };
|
||||
let [_, dim] = data_type_colors(wire.data_type);
|
||||
let path = flattened(&BezPath::from_vec(wire.path.to_vec()));
|
||||
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(category(""), memoize)]
|
||||
fn draw_cards(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Card, Labels>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let cards = rows::<Card>(&ctx, 0);
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(cards, &mut cache, draw_card)?;
|
||||
|
||||
let shown: HashSet<&str> = cards.iter().flat_map(texts).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_card(card: &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.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) };
|
||||
let body = rounded_rect(min, max, [NODE_RADIUS; 4]);
|
||||
graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY)));
|
||||
|
||||
let (header_tint, rows_tint) = match card.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 { NODE_RADIUS } else { 0. };
|
||||
let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [NODE_RADIUS, NODE_RADIUS, header_bottom, header_bottom]);
|
||||
graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint)));
|
||||
if card.selection != Selection::None && card.rows() > 1 {
|
||||
let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., NODE_RADIUS, NODE_RADIUS]);
|
||||
graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint)));
|
||||
}
|
||||
graphic.extend(icon(&card.icon, min + DVec2::new(NODE_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color));
|
||||
let name = labels.label(&card.name, NODE_NAME_MAX_WIDTH)?;
|
||||
graphic.extend(text(&name.outline, min + DVec2::new(NODE_NAME_LEFT, 0.), text_color));
|
||||
|
||||
for row in 1..card.rows() {
|
||||
let (input, output) = (card.secondary_inputs.get(row - 1), card.secondary_outputs.get(row - 1));
|
||||
let Some(connector) = input.or(output) else { continue };
|
||||
let name = labels.label(&connector.name, NODE_WIDTH - 2. * NODE_ROW_PADDING)?;
|
||||
let left = if input.is_some() { NODE_ROW_PADDING } else { NODE_WIDTH - NODE_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.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, NODE_RADIUS, &gaps, card.previewed));
|
||||
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn texts(card: &Card) -> impl Iterator<Item = &str> {
|
||||
let connectors = card.secondary_inputs.iter().chain(&card.secondary_outputs);
|
||||
std::iter::once(card.name.as_str()).chain(connectors.map(|connector| connector.name.as_str()))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_dots(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Dot>) -> List<Vector> {
|
||||
draw_rows(rows::<Dot>(&ctx, 0), cache, draw_dot)
|
||||
}
|
||||
|
||||
fn draw_dot(dot: &Dot) -> List<Vector> {
|
||||
let [wired, unwired] = data_type_colors(dot.data_type);
|
||||
let center = dot.center();
|
||||
let grown = matches!(dot.highlight, Highlight::Hovered | Highlight::WireTarget);
|
||||
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 = dot.output_highlight != Highlight::None;
|
||||
let fill = if dot.wired && !output_shown { wired } else { unwired };
|
||||
let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into()));
|
||||
|
||||
if grown {
|
||||
let offset = if dot.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 dot.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 dot.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 {
|
||||
graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.data_type, true, dot.output_highlight));
|
||||
}
|
||||
graphic
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_errors(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<ErrorBadge, Paragraphs>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let badges = rows::<ErrorBadge>(&ctx, 0);
|
||||
let errors = badges.iter();
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(errors.clone().filter(|error| !error.hovered).chain(errors.filter(|error| error.hovered)), &mut cache, draw_error)?;
|
||||
|
||||
let shown: HashSet<&str> = badges.iter().map(|error| error.text.as_str()).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_error(error: &ErrorBadge, paragraphs: &mut Paragraphs) -> Result<List<Vector>, TextToVectorError> {
|
||||
let paragraph = paragraphs.paragraph(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?;
|
||||
let [min, max] = error.body(paragraph.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.tail();
|
||||
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()));
|
||||
|
||||
badge.extend(text(¶graph.outline, error.text_top_left(paragraph.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 !error.hovered {
|
||||
grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY);
|
||||
}
|
||||
Ok(List::new_from_item(grouped))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_network_connectors(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<NetworkConnector, Labels>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let network_connectors = rows::<NetworkConnector>(&ctx, 0);
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(network_connectors, &mut cache, draw_network_connector)?;
|
||||
|
||||
let connectors = network_connectors.iter().filter_map(|row| row.connector.as_ref());
|
||||
let shown: HashSet<&str> = connectors.map(|connector| connector.name.as_str()).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||
let Some(entry) = &row.connector else {
|
||||
return Ok(drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, row.add_highlight));
|
||||
};
|
||||
let mut graphic = connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry);
|
||||
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.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)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_reorder_bar(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let Some((kind, anchor)) = graph_ui(&ctx).config.reorder_bar else { return List::new() };
|
||||
let [min, max] = reorder_bar(kind, anchor);
|
||||
List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_box_selection(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let Some([start, end]) = graph_ui(&ctx).config.box_selection 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());
|
||||
List::from_iter([fill, border])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::network_connector::NetworkConnectorKind;
|
||||
use crate::render::rows_context;
|
||||
use crate::scene::GraphUiScene;
|
||||
use crate::test_utils::{badge, card, connector, dot, layer, network_connector, wire};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::uuid::NodeId;
|
||||
use vello_gpu::kurbo::PathEl;
|
||||
|
||||
fn bounds(graphic: &List<Vector>) -> RenderBoundingBox {
|
||||
graphic.bounding_box(DAffine2::IDENTITY, false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_card_that_only_moved_to_another_cell_keeps_its_vectors_and_is_drawn_at_that_cell() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_cards(rows_context(scene.cards()), &cache).unwrap();
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.put(Card {
|
||||
name: "Path".to_string(),
|
||||
cell: IVec2::new(2, 1),
|
||||
..card(0)
|
||||
});
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let drawn = cache.lock().unwrap().drawn[&NodeId(0)].1.elements_witness();
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.cards.update(&NodeId(0), |card| card.cell = IVec2::new(-3, 5));
|
||||
let (scene, _) = edit.finish();
|
||||
let moved = draw(scene.clone());
|
||||
assert!(drawn.matches(&cache.lock().unwrap().drawn[&NodeId(0)].1), "a moved card keeps its vectors");
|
||||
let in_place = draw_card(scene.cards().get(&NodeId(0)).unwrap(), &mut Labels::default()).unwrap();
|
||||
assert_eq!(bounds(&moved), bounds(&in_place), "a moved card is drawn at its new cell");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gliding_layer_keeps_its_vectors_and_is_drawn_its_glide_away() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_layers(rows_context(scene.layers()), &cache).unwrap();
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.layers.put(Layer {
|
||||
name: "Path".to_string(),
|
||||
cell: IVec2::new(2, 1),
|
||||
..layer(0)
|
||||
});
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let drawn = cache.lock().unwrap().drawn[&NodeId(0)].1.elements_witness();
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.layers.update(&NodeId(0), |layer| layer.glide = DVec2::new(-7.25, 3.5));
|
||||
let (scene, _) = edit.finish();
|
||||
let gliding = draw(scene.clone());
|
||||
assert!(drawn.matches(&cache.lock().unwrap().drawn[&NodeId(0)].1), "a gliding layer keeps its vectors");
|
||||
let in_place = draw_layer(scene.layers().get(&NodeId(0)).unwrap(), &mut Labels::default()).unwrap();
|
||||
assert_eq!(bounds(&gliding), bounds(&in_place), "a gliding layer is drawn its glide away");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_whose_look_changed_is_drawn_again_while_a_dot_that_only_moved_keeps_its_vectors() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_dots(rows_context(scene.dots()), &cache);
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.dots.replace_all([dot(0), dot(1)]);
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let witness = |key| cache.lock().unwrap().drawn[&NodeId(key)].1.elements_witness();
|
||||
let [moved, changed] = [witness(0), witness(1)];
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.dots.update(&NodeId(0), |dot| dot.cell = IVec2::new(4, -2));
|
||||
edit.dots.update(&NodeId(1), |dot| {
|
||||
dot.cell = IVec2::new(4, 2);
|
||||
dot.selected = true;
|
||||
});
|
||||
let (scene, _) = edit.finish();
|
||||
let drawn = draw(scene.clone());
|
||||
let cache = cache.lock().unwrap();
|
||||
assert!(moved.matches(&cache.drawn[&NodeId(0)].1), "a dot that only moved keeps its vectors");
|
||||
assert!(!changed.matches(&cache.drawn[&NodeId(1)].1), "a dot whose look changed is drawn again");
|
||||
let in_place: List<Vector> = scene.dots().iter().flat_map(draw_dot).collect();
|
||||
assert_eq!(bounds(&drawn), bounds(&in_place), "both dots are drawn at their new cells");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_cards_that_changed_are_drawn_again() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_cards(rows_context(scene.cards()), &cache).unwrap();
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all([card(0), card(1), card(2)]);
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let witness = |key| cache.lock().unwrap().drawn[&NodeId(key)].1.elements_witness();
|
||||
let [unchanged, changed] = [witness(0), witness(1)];
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.cards.update(&NodeId(1), |card| card.selection = Selection::Active);
|
||||
edit.cards.remove(&NodeId(2));
|
||||
draw(edit.finish().0);
|
||||
let cache = cache.lock().unwrap();
|
||||
assert!(unchanged.matches(&cache.drawn[&NodeId(0)].1), "an unchanged card keeps its vectors");
|
||||
assert!(!changed.matches(&cache.drawn[&NodeId(1)].1), "a changed card is drawn again");
|
||||
assert!(!cache.drawn.contains_key(&NodeId(2)), "a removed card is forgotten");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_a_text_is_forgotten_once_no_card_shows_it() {
|
||||
let named = |key, name: &str| Card { name: name.to_string(), ..card(key) };
|
||||
let cache = Default::default();
|
||||
let draw = |cards: Vec<Card>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all(cards);
|
||||
draw_cards(rows_context(edit.finish().0.cards()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![named(0, "Path"), named(1, "Fill")]);
|
||||
let label = |text| cache.lock().unwrap().labels.label(text, NODE_NAME_MAX_WIDTH).unwrap().outline.elements_witness();
|
||||
let [path, fill] = [label("Path"), label("Fill")];
|
||||
|
||||
draw(vec![named(0, "Path")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(
|
||||
path.matches(&cache.labels.label("Path", NODE_NAME_MAX_WIDTH).unwrap().outline),
|
||||
"the label of a text still shown is kept"
|
||||
);
|
||||
assert!(
|
||||
!fill.matches(&cache.labels.label("Fill", NODE_NAME_MAX_WIDTH).unwrap().outline),
|
||||
"the label of a text no card shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_a_text_is_forgotten_once_no_layer_shows_it() {
|
||||
let named = |key, name: &str| Layer { name: name.to_string(), ..layer(key) };
|
||||
let cache = Default::default();
|
||||
let draw = |layers: Vec<Layer>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.layers.replace_all(layers);
|
||||
draw_layers(rows_context(edit.finish().0.layers()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![named(0, "Path"), named(1, "Fill")]);
|
||||
let max_width = layer(0).name_width();
|
||||
let label = |text| cache.lock().unwrap().labels.label(text, max_width).unwrap().outline.elements_witness();
|
||||
let [path, fill] = [label("Path"), label("Fill")];
|
||||
|
||||
draw(vec![named(0, "Path")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(path.matches(&cache.labels.label("Path", max_width).unwrap().outline), "the label of a text still shown is kept");
|
||||
assert!(
|
||||
!fill.matches(&cache.labels.label("Fill", max_width).unwrap().outline),
|
||||
"the label of a text no layer shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_a_text_is_forgotten_once_no_import_or_export_shows_it() {
|
||||
let named = |kind, name: &str| NetworkConnector {
|
||||
connector: Some(connector(name)),
|
||||
..network_connector(kind, 0)
|
||||
};
|
||||
let cache = Default::default();
|
||||
let draw = |rows: Vec<NetworkConnector>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.network_connectors.replace_all(rows);
|
||||
draw_network_connectors(rows_context(edit.finish().0.network_connectors()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![named(NetworkConnectorKind::Import, "Path"), named(NetworkConnectorKind::Export, "Fill")]);
|
||||
let label = |text| cache.lock().unwrap().labels.label(text, f64::INFINITY).unwrap().outline.elements_witness();
|
||||
let [path, fill] = [label("Path"), label("Fill")];
|
||||
|
||||
draw(vec![named(NetworkConnectorKind::Import, "Path")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(path.matches(&cache.labels.label("Path", f64::INFINITY).unwrap().outline), "the label of a text still shown is kept");
|
||||
assert!(
|
||||
!fill.matches(&cache.labels.label("Fill", f64::INFINITY).unwrap().outline),
|
||||
"the label of a text no import or export shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_paragraph_of_an_error_is_forgotten_once_no_badge_shows_it() {
|
||||
let cache = Default::default();
|
||||
let draw = |badges: Vec<ErrorBadge>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.errors.replace_all(badges);
|
||||
draw_errors(rows_context(edit.finish().0.errors()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![badge(0, "Failed"), badge(1, "Missing input")]);
|
||||
let paragraph = |text| cache.lock().unwrap().labels.paragraph(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline.elements_witness();
|
||||
let [failed, missing] = [paragraph("Failed"), paragraph("Missing input")];
|
||||
|
||||
draw(vec![badge(0, "Failed")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(
|
||||
failed.matches(&cache.labels.paragraph("Failed", ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline),
|
||||
"the paragraph of a text still shown is kept"
|
||||
);
|
||||
assert!(
|
||||
!missing.matches(&cache.labels.paragraph("Missing input", ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline),
|
||||
"the paragraph of a text no badge shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_groups_of_a_grid_dot_light_each_pixel_of_its_disc_once() {
|
||||
for (radius, groups, pixels) in [(1, 1, 4), (2, 2, 12), (3, 2, 32), (4, 3, 52)] {
|
||||
let disc: Vec<[u32; 2]> = (0..2 * radius)
|
||||
.flat_map(|row| (0..2 * radius).map(move |column| [column, row]))
|
||||
.filter(|&[column, row]| (column as f64 + 0.5 - radius as f64).hypot(row as f64 + 0.5 - radius as f64) < radius as f64)
|
||||
.collect();
|
||||
let columns = disc_columns(radius);
|
||||
let mut lit: Vec<[u32; 2]> = columns
|
||||
.iter()
|
||||
.flat_map(|(&[top, bottom], runs)| (top..bottom).flat_map(move |row| runs.iter().flat_map(move |&[left, right]| (left..right).map(move |column| [column, row]))))
|
||||
.collect();
|
||||
lit.sort_by_key(|&[column, row]| [row, column]);
|
||||
assert_eq!((columns.len(), disc.len()), (groups, pixels), "the groups and pixels of the disc at radius {radius}");
|
||||
assert_eq!(lit, disc, "every pixel of the disc at radius {radius} is lit by exactly one group");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_wires_that_changed_are_drawn_again() {
|
||||
let key = |node| WireKey::Input { node: NodeId(node), index: 0 };
|
||||
let at = |node, y: f64| Wire {
|
||||
path: BezPath::from_vec(vec![PathEl::MoveTo((0., y).into()), PathEl::LineTo((48., y).into())]),
|
||||
..wire(key(node))
|
||||
};
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_wires(rows_context(scene.wires()), &cache);
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.wires.replace_all([at(0, 0.), at(1, 24.)]);
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let witness = |node| cache.lock().unwrap().drawn[&key(node)].1.elements_witness();
|
||||
let [unchanged, changed] = [witness(0), witness(1)];
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.wires.put(at(1, 48.));
|
||||
draw(edit.finish().0);
|
||||
let cache = cache.lock().unwrap();
|
||||
assert!(unchanged.matches(&cache.drawn[&key(0)].1), "the other wire keeps its vectors");
|
||||
assert!(!changed.matches(&cache.drawn[&key(1)].1), "the changed wire is drawn again");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use crate::look::{BACKDROP, painted, rounded_rect};
|
||||
use crate::replicated_map::{Keyed, ReplicatedMap};
|
||||
use crate::{GraphUi, nodes};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractVarArgs, Interrupt, NodeError, OwnedContextImpl, ProtoNodeIdentifier};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use graphene_application_io::RenderConfig;
|
||||
use graphic_types::{Coverage, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderParams};
|
||||
use std::error::Error;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
const BANDS: [ProtoNodeIdentifier; 13] = [
|
||||
nodes::draw_grid::IDENTIFIER,
|
||||
nodes::draw_thick_wires::IDENTIFIER,
|
||||
nodes::draw_layers::IDENTIFIER,
|
||||
nodes::draw_thumbnails::IDENTIFIER,
|
||||
nodes::draw_wires::IDENTIFIER,
|
||||
nodes::draw_wire_in_progress::IDENTIFIER,
|
||||
nodes::draw_cards::IDENTIFIER,
|
||||
nodes::draw_dots::IDENTIFIER,
|
||||
nodes::draw_raised::IDENTIFIER,
|
||||
nodes::draw_errors::IDENTIFIER,
|
||||
nodes::draw_network_connectors::IDENTIFIER,
|
||||
nodes::draw_reorder_bar::IDENTIFIER,
|
||||
nodes::draw_box_selection::IDENTIFIER,
|
||||
];
|
||||
|
||||
pub fn network() -> NodeNetwork {
|
||||
let node = |identifier, inputs| DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
let mut network = NodeNetwork::default();
|
||||
let root = NodeId(BANDS.len() as u64);
|
||||
let mut inputs = Vec::new();
|
||||
for (band, identifier) in (0..).map(NodeId).zip(BANDS) {
|
||||
network.nodes.insert(band, node(identifier, Vec::new()));
|
||||
inputs.push(NodeInput::node(band, 0));
|
||||
}
|
||||
inputs.push(NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER));
|
||||
network.nodes.insert(root, node(render_graph_ui::IDENTIFIER, inputs));
|
||||
network.exports.push(NodeInput::node(root, 0));
|
||||
network
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_graph_ui(
|
||||
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs,
|
||||
grid: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
thick_wires: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
layers: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
thumbnails: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
wires: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
wire_in_progress: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
cards: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
dots: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
raised: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
errors: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
imports_exports: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
reorder_bar: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
box_selection: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
#[scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node<Context<'static>, Output = Item<WgpuExecutor>>,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
let render_config = *render_config(&ctx);
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
let graph_ui = graph_ui(&context);
|
||||
|
||||
let viewport_size = render_config.viewport.resolution.as_dvec2() / render_config.scale;
|
||||
let opacity = graph_ui.config.fade_artwork as f32;
|
||||
let backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity));
|
||||
let mut drawn = vec![(List::new_from_item(backdrop), DAffine2::IDENTITY)];
|
||||
let scene = &graph_ui.scene;
|
||||
let wire_rows = rows_context(scene.wires());
|
||||
let raised_rows = OwnedContextImpl::default()
|
||||
.with_varargs([Box::new(scene.layers().clone()), Box::new(scene.cards().clone())])
|
||||
.into_context();
|
||||
let bands = [
|
||||
(grid.eval(&context)?, DAffine2::IDENTITY),
|
||||
(thick_wires.eval(&wire_rows)?, graph_ui.config.view),
|
||||
(layers.eval(&rows_context(scene.layers()))?, graph_ui.config.view),
|
||||
(thumbnails.eval(&context)?, graph_ui.config.view),
|
||||
(wires.eval(&wire_rows)?, graph_ui.config.view),
|
||||
(wire_in_progress.eval(&context)?, graph_ui.config.view),
|
||||
(cards.eval(&rows_context(scene.cards()))?, graph_ui.config.view),
|
||||
(dots.eval(&rows_context(scene.dots()))?, graph_ui.config.view),
|
||||
(raised.eval(&raised_rows)?, graph_ui.config.view),
|
||||
(errors.eval(&rows_context(scene.errors()))?, graph_ui.config.view),
|
||||
(imports_exports.eval(&rows_context(scene.network_connectors()))?, graph_ui.config.view),
|
||||
(reorder_bar.eval(&context)?, graph_ui.config.view),
|
||||
(box_selection.eval(&context)?, DAffine2::IDENTITY),
|
||||
];
|
||||
drawn.extend(bands);
|
||||
|
||||
let executor = executor.eval(&Context::default())?.into_element();
|
||||
let data = raster_frame(&executor, &drawn, &render_config).map_err(NodeError::new)?;
|
||||
Ok(Item::new_from_element(RenderOutput { data, metadata: Default::default() }))
|
||||
}
|
||||
|
||||
fn raster_frame(executor: &WgpuExecutor, drawn: &[(List<Vector>, DAffine2)], render_config: &RenderConfig) -> Result<RenderOutputType, Box<dyn Error + Send + Sync>> {
|
||||
let viewport = DAffine2::from_scale(DVec2::splat(render_config.scale));
|
||||
let mut draw = |scene: &mut VelloSceneBuilder| {
|
||||
for (band, transform) in drawn {
|
||||
band.render_to_vello(scene, viewport * *transform, &RenderParams::default());
|
||||
}
|
||||
};
|
||||
let texture = executor.render_vello(render_config.viewport.resolution, DAffine2::IDENTITY, &mut draw)?;
|
||||
Ok(RenderOutputType::Texture(texture))
|
||||
}
|
||||
|
||||
pub fn context(render_config: RenderConfig, graph_ui: GraphUi) -> OwnedContextImpl {
|
||||
OwnedContextImpl::default().with_varargs([Box::new(render_config), Box::new(graph_ui)])
|
||||
}
|
||||
|
||||
pub fn rows_context<T: Keyed + CacheHash + Send + Sync + 'static>(rows: &ReplicatedMap<T>) -> Context<'static> {
|
||||
OwnedContextImpl::default().with_vararg(Box::new(rows.clone())).into_context()
|
||||
}
|
||||
|
||||
pub(crate) fn render_config(ctx: &impl ExtractVarArgs) -> &RenderConfig {
|
||||
ctx.vararg(0).ok().and_then(|config| config.downcast_ref()).expect("The render config is the first vararg")
|
||||
}
|
||||
|
||||
pub(crate) fn graph_ui(ctx: &impl ExtractVarArgs) -> &GraphUi {
|
||||
ctx.vararg(1).ok().and_then(|graph_ui| graph_ui.downcast_ref()).expect("The graph UI is the second vararg")
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
pub trait Keyed: Clone {
|
||||
type Key: Ord + Clone + Debug;
|
||||
|
||||
fn key(&self) -> Self::Key;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ReplicatedMap<T: Keyed> {
|
||||
items: Arc<Vec<T>>,
|
||||
hash: Arc<OnceLock<u64>>,
|
||||
}
|
||||
|
||||
impl<T: Keyed> Default for ReplicatedMap<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
items: Arc::default(),
|
||||
hash: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed + PartialEq> PartialEq for ReplicatedMap<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.items == other.items
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed + CacheHash> CacheHash for ReplicatedMap<T> {
|
||||
fn cache_hash<H: Hasher>(&self, state: &mut H) {
|
||||
let hash = self.hash.get_or_init(|| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
self.items.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
});
|
||||
state.write_u64(*hash);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed> ReplicatedMap<T> {
|
||||
pub fn get(&self, key: &T::Key) -> Option<&T> {
|
||||
self.position(key).ok().map(|index| &self.items[index])
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> std::slice::Iter<'_, T> {
|
||||
self.items.iter()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
|
||||
pub fn edit(self) -> ReplicatedMapEdit<T> {
|
||||
ReplicatedMapEdit { map: self, deltas: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, deltas: impl IntoIterator<Item = ReplicatedMapDelta<T>>) {
|
||||
for delta in deltas {
|
||||
match delta {
|
||||
ReplicatedMapDelta::Put(item) => self.put(item),
|
||||
ReplicatedMapDelta::Remove(key) => {
|
||||
let removed = self.remove(&key);
|
||||
debug_assert!(removed, "a delta removes an item that its map never held");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn position(&self, key: &T::Key) -> Result<usize, usize> {
|
||||
self.items.binary_search_by(|item| item.key().cmp(key))
|
||||
}
|
||||
|
||||
fn items_mut(&mut self) -> &mut Vec<T> {
|
||||
self.hash = Arc::default();
|
||||
Arc::make_mut(&mut self.items)
|
||||
}
|
||||
|
||||
fn put(&mut self, item: T) {
|
||||
match self.position(&item.key()) {
|
||||
Ok(index) => self.items_mut()[index] = item,
|
||||
Err(index) => self.items_mut().insert(index, item),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, key: &T::Key) -> bool {
|
||||
let position = self.position(key);
|
||||
if let Ok(index) = position {
|
||||
self.items_mut().remove(index);
|
||||
}
|
||||
position.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Keyed> IntoIterator for &'a ReplicatedMap<T> {
|
||||
type Item = &'a T;
|
||||
type IntoIter = std::slice::Iter<'a, T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ReplicatedMapDelta<T: Keyed> {
|
||||
Put(T),
|
||||
Remove(T::Key),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ReplicatedMapEdit<T: Keyed> {
|
||||
map: ReplicatedMap<T>,
|
||||
deltas: Vec<ReplicatedMapDelta<T>>,
|
||||
}
|
||||
|
||||
impl<T: Keyed> Deref for ReplicatedMapEdit<T> {
|
||||
type Target = ReplicatedMap<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed> ReplicatedMapEdit<T> {
|
||||
pub fn put(&mut self, item: T)
|
||||
where
|
||||
T: PartialEq,
|
||||
{
|
||||
if self.map.get(&item.key()) == Some(&item) {
|
||||
return;
|
||||
}
|
||||
self.map.put(item.clone());
|
||||
self.deltas.push(ReplicatedMapDelta::Put(item));
|
||||
}
|
||||
|
||||
pub fn update(&mut self, key: &T::Key, change: impl FnOnce(&mut T)) -> bool {
|
||||
let Ok(index) = self.map.position(key) else { return false };
|
||||
let item = &mut self.map.items_mut()[index];
|
||||
change(item);
|
||||
debug_assert!(item.key() == *key, "an update must not change the key of its item");
|
||||
self.deltas.push(ReplicatedMapDelta::Put(item.clone()));
|
||||
true
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, key: &T::Key) -> bool {
|
||||
let removed = self.map.remove(key);
|
||||
if removed {
|
||||
self.deltas.push(ReplicatedMapDelta::Remove(key.clone()));
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
pub fn replace_all(&mut self, items: impl IntoIterator<Item = T>)
|
||||
where
|
||||
T: PartialEq,
|
||||
{
|
||||
let mut items: Vec<T> = items.into_iter().collect();
|
||||
items.sort_by_key(T::key);
|
||||
debug_assert!(items.windows(2).all(|pair| pair[0].key() != pair[1].key()), "two items of a map share a key");
|
||||
|
||||
let removed = self.map.iter().rev().map(T::key).filter(|key| items.binary_search_by(|item| item.key().cmp(key)).is_err());
|
||||
self.deltas.extend(removed.map(ReplicatedMapDelta::Remove));
|
||||
let put = items.iter().filter(|item| self.map.get(&item.key()) != Some(item));
|
||||
self.deltas.extend(put.cloned().map(ReplicatedMapDelta::Put));
|
||||
|
||||
*self.map.items_mut() = items;
|
||||
}
|
||||
|
||||
pub fn finish(self) -> (ReplicatedMap<T>, Vec<ReplicatedMapDelta<T>>) {
|
||||
(self.map, self.deltas)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
struct Item {
|
||||
key: u8,
|
||||
value: u8,
|
||||
}
|
||||
|
||||
impl Keyed for Item {
|
||||
type Key = u8;
|
||||
|
||||
fn key(&self) -> u8 {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
fn item(key: u8, value: u8) -> Item {
|
||||
Item { key, value }
|
||||
}
|
||||
|
||||
fn map(items: &[Item]) -> ReplicatedMap<Item> {
|
||||
let mut edit = ReplicatedMap::default().edit();
|
||||
edit.replace_all(items.iter().copied());
|
||||
edit.finish().0
|
||||
}
|
||||
|
||||
fn small_maps() -> Vec<Vec<Item>> {
|
||||
let choices = [None, Some(0), Some(1)];
|
||||
let mut maps = Vec::new();
|
||||
for a in choices {
|
||||
for b in choices {
|
||||
for c in choices {
|
||||
maps.push([a, b, c].into_iter().zip(0..).filter_map(|(value, key)| Some(item(key, value?))).collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
maps
|
||||
}
|
||||
|
||||
fn hash(map: &ReplicatedMap<Item>) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
map.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_that_applies_the_deltas_of_an_edit_holds_the_same_items() {
|
||||
for old in small_maps() {
|
||||
for new in small_maps() {
|
||||
let mut copy = map(&old);
|
||||
|
||||
let mut edit = map(&old).edit();
|
||||
edit.replace_all(new.iter().copied());
|
||||
let (replaced, deltas) = edit.finish();
|
||||
assert_eq!(replaced, map(&new));
|
||||
assert_eq!(deltas.is_empty(), old == new, "{old:?} to {new:?}");
|
||||
copy.apply(deltas);
|
||||
assert_eq!(copy, replaced, "{old:?} to {new:?}");
|
||||
|
||||
let mut copy = map(&old);
|
||||
let mut edit = map(&old).edit();
|
||||
for item in &old {
|
||||
assert!(edit.remove(&item.key));
|
||||
}
|
||||
for item in new.iter().rev() {
|
||||
edit.put(*item);
|
||||
}
|
||||
let (rebuilt, deltas) = edit.finish();
|
||||
assert_eq!(rebuilt, map(&new));
|
||||
copy.apply(deltas);
|
||||
assert_eq!(copy, rebuilt, "{old:?} to {new:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_are_held_in_key_order_and_found_by_key() {
|
||||
let mut edit = ReplicatedMap::default().edit();
|
||||
edit.put(item(2, 0));
|
||||
edit.put(item(0, 0));
|
||||
edit.put(item(1, 0));
|
||||
edit.put(item(0, 1));
|
||||
assert_eq!(edit.get(&0), Some(&item(0, 1)), "an edit reads what it has done so far");
|
||||
let (map, _) = edit.finish();
|
||||
|
||||
assert_eq!(map.iter().copied().collect::<Vec<_>>(), [item(0, 1), item(1, 0), item(2, 0)]);
|
||||
assert_eq!(map.get(&1), Some(&item(1, 0)));
|
||||
assert_eq!(map.get(&3), None);
|
||||
assert_eq!(map.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_put_of_the_item_already_held_records_no_delta() {
|
||||
let mut edit = map(&[item(0, 0)]).edit();
|
||||
edit.put(item(0, 0));
|
||||
assert!(edit.finish().1.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_changes_the_item_in_the_copy_too() {
|
||||
let mut copy = map(&[item(0, 0), item(1, 0)]);
|
||||
|
||||
let mut edit = copy.clone().edit();
|
||||
assert!(edit.update(&1, |item| item.value = 1));
|
||||
assert!(!edit.update(&2, |item| item.value = 1));
|
||||
assert!(!edit.remove(&2));
|
||||
let (updated, deltas) = edit.finish();
|
||||
|
||||
assert_eq!(updated, map(&[item(0, 0), item(1, 1)]));
|
||||
copy.apply(deltas);
|
||||
assert_eq!(copy, updated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_leaves_other_holders_of_the_set_as_they_were() {
|
||||
let held = map(&[item(0, 0)]);
|
||||
|
||||
let mut edit = held.clone().edit();
|
||||
edit.put(item(1, 0));
|
||||
edit.remove(&0);
|
||||
|
||||
assert_eq!(held, map(&[item(0, 0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hash_follows_the_items() {
|
||||
let a = map(&[item(0, 0), item(1, 0)]);
|
||||
let held = a.clone();
|
||||
assert!(a.hash.get().is_none(), "nothing asked for the hash yet");
|
||||
assert_eq!(hash(&a), hash(&map(&[item(1, 0), item(0, 0)])));
|
||||
assert!(a.hash.get().is_some());
|
||||
assert!(held.hash.get().is_some(), "a clone made before shares the hash");
|
||||
|
||||
let mut edit = a.clone().edit();
|
||||
edit.update(&1, |item| item.value = 1);
|
||||
let (b, deltas) = edit.finish();
|
||||
assert!(b.hash.get().is_none(), "a change empties the hash");
|
||||
assert_ne!(hash(&a), hash(&b));
|
||||
|
||||
let mut copy = a.clone();
|
||||
copy.apply(deltas);
|
||||
assert!(copy.hash.get().is_none());
|
||||
assert_eq!(hash(©), hash(&b));
|
||||
|
||||
let mut edit = b.edit();
|
||||
edit.update(&1, |item| item.value = 0);
|
||||
assert_eq!(hash(&edit.finish().0), hash(&a), "the same items again hash the same");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use crate::card::Card;
|
||||
use crate::dot::Dot;
|
||||
use crate::error_badge::ErrorBadge;
|
||||
use crate::layer::Layer;
|
||||
use crate::network_connector::NetworkConnector;
|
||||
use crate::replicated_map::{ReplicatedMap, ReplicatedMapDelta, ReplicatedMapEdit};
|
||||
use crate::wire::Wire;
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct GraphUiScene {
|
||||
cards: ReplicatedMap<Card>,
|
||||
layers: ReplicatedMap<Layer>,
|
||||
dots: ReplicatedMap<Dot>,
|
||||
wires: ReplicatedMap<Wire>,
|
||||
network_connectors: ReplicatedMap<NetworkConnector>,
|
||||
errors: ReplicatedMap<ErrorBadge>,
|
||||
}
|
||||
|
||||
impl GraphUiScene {
|
||||
pub fn cards(&self) -> &ReplicatedMap<Card> {
|
||||
&self.cards
|
||||
}
|
||||
|
||||
pub fn layers(&self) -> &ReplicatedMap<Layer> {
|
||||
&self.layers
|
||||
}
|
||||
|
||||
pub fn dots(&self) -> &ReplicatedMap<Dot> {
|
||||
&self.dots
|
||||
}
|
||||
|
||||
pub fn wires(&self) -> &ReplicatedMap<Wire> {
|
||||
&self.wires
|
||||
}
|
||||
|
||||
pub fn network_connectors(&self) -> &ReplicatedMap<NetworkConnector> {
|
||||
&self.network_connectors
|
||||
}
|
||||
|
||||
pub fn errors(&self) -> &ReplicatedMap<ErrorBadge> {
|
||||
&self.errors
|
||||
}
|
||||
|
||||
pub fn edit(self) -> GraphUiSceneEdit {
|
||||
GraphUiSceneEdit {
|
||||
cards: self.cards.edit(),
|
||||
layers: self.layers.edit(),
|
||||
dots: self.dots.edit(),
|
||||
wires: self.wires.edit(),
|
||||
network_connectors: self.network_connectors.edit(),
|
||||
errors: self.errors.edit(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, delta: GraphUiSceneDelta) {
|
||||
self.cards.apply(delta.cards);
|
||||
self.layers.apply(delta.layers);
|
||||
self.dots.apply(delta.dots);
|
||||
self.wires.apply(delta.wires);
|
||||
self.network_connectors.apply(delta.network_connectors);
|
||||
self.errors.apply(delta.errors);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphUiSceneEdit {
|
||||
pub cards: ReplicatedMapEdit<Card>,
|
||||
pub layers: ReplicatedMapEdit<Layer>,
|
||||
pub dots: ReplicatedMapEdit<Dot>,
|
||||
pub wires: ReplicatedMapEdit<Wire>,
|
||||
pub network_connectors: ReplicatedMapEdit<NetworkConnector>,
|
||||
pub errors: ReplicatedMapEdit<ErrorBadge>,
|
||||
}
|
||||
|
||||
impl GraphUiSceneEdit {
|
||||
pub fn finish(self) -> (GraphUiScene, GraphUiSceneDelta) {
|
||||
let (cards, card_deltas) = self.cards.finish();
|
||||
let (layers, layer_deltas) = self.layers.finish();
|
||||
let (dots, dot_deltas) = self.dots.finish();
|
||||
let (wires, wire_deltas) = self.wires.finish();
|
||||
let (network_connectors, network_connector_deltas) = self.network_connectors.finish();
|
||||
let (errors, error_deltas) = self.errors.finish();
|
||||
(
|
||||
GraphUiScene {
|
||||
cards,
|
||||
layers,
|
||||
dots,
|
||||
wires,
|
||||
network_connectors,
|
||||
errors,
|
||||
},
|
||||
GraphUiSceneDelta {
|
||||
cards: card_deltas,
|
||||
layers: layer_deltas,
|
||||
dots: dot_deltas,
|
||||
wires: wire_deltas,
|
||||
network_connectors: network_connector_deltas,
|
||||
errors: error_deltas,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GraphUiSceneDelta {
|
||||
cards: Vec<ReplicatedMapDelta<Card>>,
|
||||
layers: Vec<ReplicatedMapDelta<Layer>>,
|
||||
dots: Vec<ReplicatedMapDelta<Dot>>,
|
||||
wires: Vec<ReplicatedMapDelta<Wire>>,
|
||||
network_connectors: Vec<ReplicatedMapDelta<NetworkConnector>>,
|
||||
errors: Vec<ReplicatedMapDelta<ErrorBadge>>,
|
||||
}
|
||||
|
||||
impl GraphUiSceneDelta {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.cards.is_empty() && self.layers.is_empty() && self.dots.is_empty() && self.wires.is_empty() && self.network_connectors.is_empty() && self.errors.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::network_connector::NetworkConnectorKind;
|
||||
use crate::test_utils::{badge, card, connector, dot, layer, network_connector, wire};
|
||||
use crate::wire::WireKey;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::IVec2;
|
||||
|
||||
#[test]
|
||||
fn a_copy_that_applies_the_delta_of_an_edit_equals_the_edited_scene() {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all([card(0), card(1)]);
|
||||
let (scene, _) = edit.finish();
|
||||
let mut copy = scene.clone();
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.cards.put(card(2));
|
||||
edit.cards.update(&NodeId(0), |card| card.cell = IVec2::ONE);
|
||||
edit.cards.remove(&NodeId(1));
|
||||
edit.layers.put(layer(4));
|
||||
edit.dots.put(dot(3));
|
||||
edit.wires.put(wire(WireKey::Input { node: NodeId(2), index: 0 }));
|
||||
edit.network_connectors.put(network_connector(NetworkConnectorKind::Import, 0));
|
||||
edit.network_connectors.put(NetworkConnector {
|
||||
connector: Some(connector("Canvas")),
|
||||
..network_connector(NetworkConnectorKind::Export, 0)
|
||||
});
|
||||
edit.errors.put(badge(2, "An error"));
|
||||
let (edited, delta) = edit.finish();
|
||||
|
||||
assert!(!delta.is_empty());
|
||||
copy.apply(delta);
|
||||
assert_eq!(copy, edited);
|
||||
|
||||
let mut edit = copy.edit();
|
||||
edit.errors.remove(&NodeId(2));
|
||||
assert!(!edit.finish().1.is_empty(), "a change to one map is a delta");
|
||||
|
||||
assert!(edited.edit().finish().1.is_empty(), "an edit that changes nothing has no deltas");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
use crate::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use crate::dot::Dot;
|
||||
use crate::error_badge::ErrorBadge;
|
||||
use crate::layer::Layer;
|
||||
use crate::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||
use crate::wire::{Wire, WireKey};
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use vello_gpu::kurbo::BezPath;
|
||||
|
||||
pub(crate) fn card(key: u64) -> Card {
|
||||
Card {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
name: String::new(),
|
||||
icon: String::new(),
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_inputs: Vec::new(),
|
||||
secondary_outputs: Vec::new(),
|
||||
selection: Selection::None,
|
||||
visible: true,
|
||||
previewed: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn layer(key: u64) -> Layer {
|
||||
Layer {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
name: String::new(),
|
||||
renaming: false,
|
||||
width: 8,
|
||||
chain_width: 0,
|
||||
has_left_input_wire: false,
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_input: None,
|
||||
primary_input_connected_to_layer: false,
|
||||
primary_output_connected_to_layer: false,
|
||||
visible: true,
|
||||
locked: false,
|
||||
read_only: false,
|
||||
selection: Selection::None,
|
||||
previewed: false,
|
||||
hovered_button: None,
|
||||
hovered_button_clicked: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dot(key: u64) -> Dot {
|
||||
Dot {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
data_type: DataType::General,
|
||||
wired: false,
|
||||
selected: false,
|
||||
previewed: false,
|
||||
highlight: Highlight::None,
|
||||
output_highlight: Highlight::None,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn wire(key: WireKey) -> Wire {
|
||||
Wire {
|
||||
key,
|
||||
path: BezPath::new(),
|
||||
data_type: DataType::General,
|
||||
thick: false,
|
||||
center_line: BezPath::new(),
|
||||
list: false,
|
||||
insertion_target: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn network_connector(kind: NetworkConnectorKind, index: usize) -> NetworkConnector {
|
||||
NetworkConnector {
|
||||
kind,
|
||||
index,
|
||||
position: IVec2::ZERO,
|
||||
connector: None,
|
||||
add_highlight: Highlight::None,
|
||||
editable: false,
|
||||
renaming: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn badge(key: u64, text: &str) -> ErrorBadge {
|
||||
ErrorBadge {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
on_layer: false,
|
||||
text: text.to_string(),
|
||||
hovered: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn connector(name: &str) -> Connector {
|
||||
Connector {
|
||||
name: name.to_string(),
|
||||
data_type: DataType::General,
|
||||
connected: false,
|
||||
highlight: Highlight::None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use crate::metrics::{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)?, width(&text));
|
||||
Ok(label.insert(Label { outline, width }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, mut shown: impl FnMut(&str) -> bool) {
|
||||
self.0.retain(|(text, _), _| shown(text));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Paragraph {
|
||||
pub outline: List<Vector>,
|
||||
pub size: DVec2,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Paragraphs(HashMap<(String, u64, u64), Paragraph>);
|
||||
|
||||
impl Paragraphs {
|
||||
pub fn paragraph(&mut self, text: &str, line_height: f64, max_width: f64) -> Result<&Paragraph, TextToVectorError> {
|
||||
match self.0.entry((text.to_string(), line_height.to_bits(), max_width.to_bits())) {
|
||||
Entry::Occupied(paragraph) => Ok(paragraph.into_mut()),
|
||||
Entry::Vacant(paragraph) => {
|
||||
let (outline, size) = (paragraph_outline(text, line_height, max_width)?, paragraph_size(text, line_height, max_width));
|
||||
Ok(paragraph.insert(Paragraph { outline, size }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, mut shown: impl FnMut(&str) -> bool) {
|
||||
self.0.retain(|(text, ..), _| shown(text));
|
||||
}
|
||||
}
|
||||
|
||||
fn width(text: &str) -> f64 {
|
||||
text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x
|
||||
}
|
||||
|
||||
fn ellipsized(text: &str, max_width: f64) -> String {
|
||||
if 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| 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)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::look::{TEXT, text};
|
||||
use core_types::list::ATTR_PATHS;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn text_too_wide_is_cut_where_one_more_character_would_not_fit() {
|
||||
let name = "A Node With a Very Long Name";
|
||||
assert_eq!(ellipsized(name, 1000.), name);
|
||||
|
||||
let cut = ellipsized(name, 84.);
|
||||
let kept = cut.trim_end_matches('…');
|
||||
assert!(kept.len() < name.len() && width(&cut) <= 84., "{cut}");
|
||||
assert!(width(&format!("{}…", &name[..kept.len() + 1])) > 84., "{cut}");
|
||||
|
||||
assert_eq!(ellipsized(name, 0.), "…");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_keeps_its_line_breaks_and_wraps_where_it_would_get_too_wide() {
|
||||
let line = "These input types are incompatible:";
|
||||
let one_line = paragraph_size(line, 18., 600.);
|
||||
assert_eq!(one_line, DVec2::new(width(line), 18.), "as wide as its text, a line high");
|
||||
assert_eq!(
|
||||
paragraph_size(&format!("{line}\n\nNext"), 18., 600.),
|
||||
DVec2::new(width(line), 54.),
|
||||
"an empty line between the paragraphs"
|
||||
);
|
||||
|
||||
let long = [line; 20].join(" ");
|
||||
let wrapped = paragraph_size(&long, 18., 600.);
|
||||
assert_eq!(wrapped.x, 600., "as wide as it may be once it wraps");
|
||||
assert!(wrapped.y >= 18. * (width(&long) / 600.).ceil(), "{wrapped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_is_laid_out_once_until_its_text_is_no_longer_shown() {
|
||||
let mut labels = Labels::default();
|
||||
let path = labels.label("Path", 84.).unwrap().outline.elements_witness();
|
||||
labels.label("Fill", 84.).unwrap();
|
||||
assert!(path.matches(&labels.label("Path", 84.).unwrap().outline), "the second label of a text is the first");
|
||||
assert!(!path.matches(&labels.label("Path", 104.).unwrap().outline), "a label of another width is its own");
|
||||
|
||||
labels.retain(|text| text == "Fill");
|
||||
assert!(!path.matches(&labels.label("Path", 84.).unwrap().outline), "a forgotten label is laid out again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_contours_of_a_label_are_extracted_once_for_every_place_it_is_drawn() {
|
||||
let outline = Labels::default().label("Path", 84.).unwrap().outline.clone();
|
||||
let contours = |top_left| {
|
||||
let drawn = text(&outline, top_left, TEXT);
|
||||
let cache = drawn.attribute::<GeometryCache>(ATTR_GEOMETRY_CACHE, 0).cloned().unwrap_or_default();
|
||||
cache.contours(drawn.element(0).unwrap(), drawn.attribute(ATTR_PATHS, 0).unwrap())
|
||||
};
|
||||
assert!(Arc::ptr_eq(&contours(DVec2::ZERO), &contours(DVec2::ONE)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use crate::card::DataType;
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use graphene_hash::CacheHash;
|
||||
use vello_gpu::kurbo::{BezPath, PathEl};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Wire {
|
||||
pub key: WireKey,
|
||||
pub path: BezPath,
|
||||
pub data_type: DataType,
|
||||
pub thick: bool,
|
||||
pub center_line: BezPath,
|
||||
pub list: bool,
|
||||
pub insertion_target: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||
pub enum WireKey {
|
||||
Input { node: NodeId, index: usize },
|
||||
Export(usize),
|
||||
Preview,
|
||||
}
|
||||
|
||||
impl Keyed for Wire {
|
||||
type Key = WireKey;
|
||||
|
||||
fn key(&self) -> WireKey {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub struct WireInProgress {
|
||||
pub path: [PathEl; 4],
|
||||
pub data_type: DataType,
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
mod render;
|
||||
mod timing;
|
||||
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::Item;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, ProtoNodeIdentifier};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::item;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_ui::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use graph_ui::error_badge::ErrorBadge;
|
||||
use graph_ui::layer::Layer;
|
||||
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||
use graph_ui::wire::{Wire, WireKey};
|
||||
use graph_ui::{GraphUi, GraphUiConfig};
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::raster_types::Raster;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use rendering::to_peniko::ToPenikoColor;
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use std::sync::Arc;
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Rect};
|
||||
use vello_gpu::peniko::Fill;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
const ARTWORK: SRGBA8 = SRGBA8::new_opaque(0x30, 0x60, 0x90);
|
||||
|
||||
fn gpu() -> WgpuExecutor {
|
||||
futures::executor::block_on(WgpuExecutor::new()).expect("rendering needs a GPU adapter, such as lavapipe through `VK_ADD_DRIVER_FILES`")
|
||||
}
|
||||
|
||||
fn node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
inputs,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn nested(network: NodeNetwork) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(network),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn network(gpu: &WgpuExecutor, nodes: impl IntoIterator<Item = DocumentNode>) -> NodeNetwork {
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
|
||||
});
|
||||
let editor_api = node(graphene_std::ops::passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)]);
|
||||
let nodes: Vec<DocumentNode> = [editor_api].into_iter().chain(nodes).collect();
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(nodes.len() as u64 - 1), 0)],
|
||||
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
||||
scope_injections: [("editor-api".to_string(), (NodeId(0), item!(Arc<PlatformEditorApi>)))].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn compiled(mut network: NodeNetwork) -> ProtoNetwork {
|
||||
preprocessor::Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
|
||||
graph_craft::util::compile(network)
|
||||
}
|
||||
|
||||
fn executor(network: NodeNetwork) -> (DynamicExecutor, OutputHandle) {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(compiled(network)).unwrap();
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
fn config(view: DAffine2, fade_artwork: f64) -> GraphUiConfig {
|
||||
GraphUiConfig {
|
||||
view,
|
||||
fade_artwork,
|
||||
wire_in_progress: None,
|
||||
reorder_bar: None,
|
||||
box_selection: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn context(render_config: RenderConfig, graph_ui: GraphUi) -> Context<'static> {
|
||||
graph_ui::render::context(render_config, graph_ui).into_context()
|
||||
}
|
||||
|
||||
fn thumbnail(gpu: &WgpuExecutor, painted: Rect, color: SRGBA8) -> Graphic {
|
||||
let mut paint = |scene: &mut VelloSceneBuilder| scene.fill(Fill::NonZero, Affine::IDENTITY, color.to_peniko_color(), None, &painted);
|
||||
let texture = gpu.render_vello(UVec2::new(72, 48), DAffine2::IDENTITY, &mut paint).unwrap();
|
||||
Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture)))
|
||||
}
|
||||
|
||||
fn card(key: u64, (x, y): (i32, i32), name: &str) -> Card {
|
||||
Card {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::new(x, y),
|
||||
name: name.to_string(),
|
||||
icon: "NodeCustomNode".to_string(),
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_inputs: Vec::new(),
|
||||
secondary_outputs: Vec::new(),
|
||||
selection: Selection::None,
|
||||
visible: true,
|
||||
previewed: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn layer(key: u64, (x, y): (i32, i32), name: &str) -> Layer {
|
||||
Layer {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::new(x, y),
|
||||
name: name.to_string(),
|
||||
renaming: false,
|
||||
width: 8,
|
||||
chain_width: 0,
|
||||
has_left_input_wire: false,
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_input: None,
|
||||
primary_input_connected_to_layer: false,
|
||||
primary_output_connected_to_layer: false,
|
||||
visible: true,
|
||||
locked: false,
|
||||
read_only: false,
|
||||
selection: Selection::None,
|
||||
previewed: false,
|
||||
hovered_button: None,
|
||||
hovered_button_clicked: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn wire(key: WireKey, path: BezPath, data_type: DataType) -> Wire {
|
||||
Wire {
|
||||
key,
|
||||
path,
|
||||
data_type,
|
||||
thick: false,
|
||||
center_line: BezPath::new(),
|
||||
list: false,
|
||||
insertion_target: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn network_connector(kind: NetworkConnectorKind, index: usize, (x, y): (i32, i32), connector: Option<Connector>) -> NetworkConnector {
|
||||
NetworkConnector {
|
||||
kind,
|
||||
index,
|
||||
position: IVec2::new(x, y),
|
||||
connector,
|
||||
add_highlight: Highlight::None,
|
||||
editable: false,
|
||||
renaming: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn badge(key: u64, (x, y): (i32, i32), text: &str) -> ErrorBadge {
|
||||
ErrorBadge {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::new(x, y),
|
||||
on_layer: false,
|
||||
text: text.to_string(),
|
||||
hovered: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn connector(name: &str, data_type: DataType) -> Connector {
|
||||
Connector {
|
||||
name: name.to_string(),
|
||||
data_type,
|
||||
connected: false,
|
||||
highlight: Highlight::None,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,490 @@
|
||||
use super::{ARTWORK, badge, config, connector, context, executor, gpu, layer, nested, network, network_connector, node, thumbnail, wire};
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, OwnedContextImpl, Poll};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_ui::GraphUi;
|
||||
use graph_ui::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use graph_ui::error_badge::ErrorBadge;
|
||||
use graph_ui::layer::Layer;
|
||||
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||
use graph_ui::render::rows_context;
|
||||
use graph_ui::replicated_map::ReplicatedMap;
|
||||
use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit};
|
||||
use graph_ui::wire::{Wire, WireKey};
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderParams};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Rect};
|
||||
|
||||
const CARDS: usize = 300;
|
||||
const LAYERS: usize = 60;
|
||||
const ERRORS: usize = 10;
|
||||
const GLIDING: usize = 5;
|
||||
const COLUMNS: usize = 20;
|
||||
const SAMPLES: usize = 21;
|
||||
const RESOLUTION: UVec2 = UVec2::new(1920, 1080);
|
||||
const NAMES: [&str; 10] = [
|
||||
"Transform",
|
||||
"Fill",
|
||||
"Stroke",
|
||||
"Boolean Operation",
|
||||
"Copy to Points",
|
||||
"Sample Polyline",
|
||||
"Morph",
|
||||
"Blend Shapes",
|
||||
"Image Color Palette",
|
||||
"Rectangle",
|
||||
];
|
||||
const ICONS: [&str; 10] = [
|
||||
"NodeTransform",
|
||||
"NodeFill",
|
||||
"NodeStroke",
|
||||
"NodeBooleanOperation",
|
||||
"NodeRepeatOnPoints",
|
||||
"NodeSamplePolyline",
|
||||
"NodeMorph",
|
||||
"NodeBlend",
|
||||
"NodeImageColorPalette",
|
||||
"NodeRectangle",
|
||||
];
|
||||
const ERROR: &str = "These input types are incompatible:\n• Input 2:\n…found: Color\n…expected: Number\n\nThis is not a supported arrangement of types for the node.";
|
||||
const ROWS: [(&str, DataType); 8] = [
|
||||
("Translation", DataType::General),
|
||||
("Rotation", DataType::Number),
|
||||
("Scale", DataType::General),
|
||||
("Color", DataType::Color),
|
||||
("Width", DataType::Number),
|
||||
("Opacity", DataType::Number),
|
||||
("Gradient", DataType::Gradient),
|
||||
("Separation Disk Diameter", DataType::Number),
|
||||
];
|
||||
|
||||
fn selection(index: usize) -> Selection {
|
||||
if index.is_multiple_of(7) { Selection::Active } else { Selection::None }
|
||||
}
|
||||
|
||||
fn connector_from((name, data_type): (&str, DataType), connected: bool) -> Connector {
|
||||
Connector {
|
||||
connected,
|
||||
..connector(name, data_type)
|
||||
}
|
||||
}
|
||||
|
||||
fn card(index: usize) -> Card {
|
||||
Card {
|
||||
icon: ICONS[index % ICONS.len()].to_string(),
|
||||
primary_input: Some(connector_from(("Content", DataType::Vector), true)),
|
||||
primary_output: Some(connector_from(("Out", DataType::Vector), !index.is_multiple_of(4))),
|
||||
secondary_inputs: (0..2 + index % 3)
|
||||
.map(|row| connector_from(ROWS[(index + row) % ROWS.len()], (index + row).is_multiple_of(3)))
|
||||
.collect(),
|
||||
secondary_outputs: if index.is_multiple_of(5) {
|
||||
vec![connector_from(("Area", DataType::Number), false)]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
selection: selection(index),
|
||||
visible: !index.is_multiple_of(11),
|
||||
previewed: index == 0,
|
||||
..super::card(index as u64, ((index % COLUMNS) as i32 * 7, (index / COLUMNS) as i32 * 6), NAMES[index % NAMES.len()])
|
||||
}
|
||||
}
|
||||
|
||||
fn nth_layer(index: usize) -> Layer {
|
||||
Layer {
|
||||
width: 8 + (index % 3) as u32,
|
||||
chain_width: if index.is_multiple_of(2) { 8 } else { 0 },
|
||||
has_left_input_wire: index.is_multiple_of(4),
|
||||
primary_input: Some(connector_from(("", DataType::Graphic), !index.is_multiple_of(10))),
|
||||
primary_output: Some(connector_from(("", DataType::Graphic), true)),
|
||||
secondary_input: Some(connector_from(("", DataType::Vector), index.is_multiple_of(2))),
|
||||
primary_input_connected_to_layer: !index.is_multiple_of(10),
|
||||
primary_output_connected_to_layer: !index.is_multiple_of(10),
|
||||
visible: !index.is_multiple_of(11),
|
||||
locked: index.is_multiple_of(13),
|
||||
selection: selection(index),
|
||||
previewed: index == 1,
|
||||
..layer((CARDS + index) as u64, ((index % 10) as i32 * 14 + 3, (index / 10) as i32 * 6 + 3), NAMES[index % NAMES.len()])
|
||||
}
|
||||
}
|
||||
|
||||
fn unnamed(mut card: Card) -> Card {
|
||||
card.name.clear();
|
||||
let connectors = card
|
||||
.primary_input
|
||||
.iter_mut()
|
||||
.chain(&mut card.primary_output)
|
||||
.chain(&mut card.secondary_inputs)
|
||||
.chain(&mut card.secondary_outputs);
|
||||
connectors.for_each(|connector| connector.name.clear());
|
||||
card
|
||||
}
|
||||
|
||||
fn scene(cards: impl IntoIterator<Item = Card>) -> GraphUiScene {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all(cards);
|
||||
edit.finish().0
|
||||
}
|
||||
|
||||
fn rewire(edit: &mut GraphUiSceneEdit) {
|
||||
let wires = wires(&edit.cards);
|
||||
edit.wires.replace_all(wires);
|
||||
}
|
||||
|
||||
fn wires(cards: &ReplicatedMap<Card>) -> Vec<Wire> {
|
||||
cards.iter().zip(cards.iter().skip(1)).map(|(from, to)| wire_between(from, to)).collect()
|
||||
}
|
||||
|
||||
fn wire_between(from: &Card, to: &Card) -> Wire {
|
||||
let center = |(top_left, _): (DVec2, &Connector)| top_left + 4.;
|
||||
let [start, end] = [from.outputs().next(), to.inputs().next()].map(|connector| connector.map(center).expect("every card has a primary input and output"));
|
||||
let point = |point: DVec2| (point.x, point.y);
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(point(start));
|
||||
path.line_to(point(start + DVec2::X * 12.));
|
||||
path.curve_to(point(start + DVec2::X * 48.), point(end - DVec2::X * 48.), point(end - DVec2::X * 12.));
|
||||
path.line_to(point(end));
|
||||
Wire {
|
||||
list: to.key.0.is_multiple_of(4),
|
||||
..wire(WireKey::Input { node: to.key, index: 0 }, path, DataType::Vector)
|
||||
}
|
||||
}
|
||||
|
||||
fn network_connectors(cells_down: i32) -> Vec<NetworkConnector> {
|
||||
let column = |kind, x| {
|
||||
let place = move |row: usize| (x, (cells_down + row as i32) * 24);
|
||||
let named = ROWS[..4].iter().enumerate().map(move |(index, &row)| NetworkConnector {
|
||||
editable: true,
|
||||
..network_connector(kind, index, place(if index == 0 { 0 } else { index + 1 }), Some(connector_from(row, true)))
|
||||
});
|
||||
named.chain([network_connector(kind, 4, place(6), None)])
|
||||
};
|
||||
column(NetworkConnectorKind::Import, -96).chain(column(NetworkConnectorKind::Export, COLUMNS as i32 * 7 * 24)).collect()
|
||||
}
|
||||
|
||||
fn error(index: usize) -> ErrorBadge {
|
||||
let card = card(index * 31 % CARDS);
|
||||
badge(card.key.0, card.cell.into(), ERROR)
|
||||
}
|
||||
|
||||
fn full_scene() -> GraphUiScene {
|
||||
let mut edit = scene((0..CARDS).map(card)).edit();
|
||||
edit.layers.replace_all((0..LAYERS).map(nth_layer));
|
||||
edit.network_connectors.replace_all(network_connectors(0));
|
||||
edit.errors.replace_all((0..ERRORS).map(error));
|
||||
rewire(&mut edit);
|
||||
edit.finish().0
|
||||
}
|
||||
|
||||
fn moved(card: &Card, offset: IVec2) -> Card {
|
||||
Card {
|
||||
cell: card.cell + offset,
|
||||
..card.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn reselected(card: &Card) -> Card {
|
||||
let selection = match card.selection {
|
||||
Selection::None => Selection::Inactive,
|
||||
Selection::Inactive => Selection::Active,
|
||||
Selection::Active => Selection::None,
|
||||
};
|
||||
Card { selection, ..card.clone() }
|
||||
}
|
||||
|
||||
fn median(mut times: Vec<Duration>) -> Duration {
|
||||
times.sort();
|
||||
times[times.len() / 2]
|
||||
}
|
||||
|
||||
fn ms(time: Duration) -> f64 {
|
||||
time.as_secs_f64() * 1000.
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "prints timings"]
|
||||
fn time_a_pan_a_card_change_and_a_rebuild_of_300_cards() {
|
||||
let gpu = gpu();
|
||||
let (render_graph_ui, graph_ui_output) = executor(network(&gpu, [nested(graph_ui::render::network())]));
|
||||
let (draw_cards, cards_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_cards::IDENTIFIER, vec![])]));
|
||||
let (draw_wires, wires_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_wires::IDENTIFIER, vec![])]));
|
||||
let (draw_grid, grid_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_grid::IDENTIFIER, vec![])]));
|
||||
let (draw_thumbnails, thumbnails_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_thumbnails::IDENTIFIER, vec![])]));
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint {
|
||||
resolution: RESOLUTION,
|
||||
..Default::default()
|
||||
},
|
||||
scale: 1.,
|
||||
export_format: ExportFormat::Raster,
|
||||
..Default::default()
|
||||
};
|
||||
let view = |sample: usize| DAffine2::from_scale_angle_translation(DVec2::splat(0.5), 0., DVec2::new(100. + sample as f64, 0.));
|
||||
let mut editor_scene = full_scene();
|
||||
let mut runtime_scene = editor_scene.clone();
|
||||
let thumbnails: Arc<BTreeMap<NodeId, Graphic>> = Arc::new(editor_scene.layers().iter().map(|layer| (layer.key, thumbnail(&gpu, Rect::new(12., 0., 60., 48.), ARTWORK))).collect());
|
||||
let mut render = |change: &mut dyn FnMut(&mut GraphUiSceneEdit), view: DAffine2| {
|
||||
let mut edit = std::mem::take(&mut editor_scene).edit();
|
||||
change(&mut edit);
|
||||
let (scene, delta) = edit.finish();
|
||||
editor_scene = scene;
|
||||
|
||||
let start = Instant::now();
|
||||
runtime_scene.apply(delta);
|
||||
let graph_ui = GraphUi {
|
||||
scene: runtime_scene.clone(),
|
||||
config: config(view, 0.5),
|
||||
thumbnails: thumbnails.clone(),
|
||||
};
|
||||
let context = context(render_config, graph_ui);
|
||||
let output = render_graph_ui.tree().eval_tagged_value(graph_ui_output.node(), &context).unwrap();
|
||||
let time = start.elapsed();
|
||||
|
||||
let Poll::Final(TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
})) = output
|
||||
else {
|
||||
panic!("{output:?}")
|
||||
};
|
||||
gpu.read_texture_pixels(&texture).unwrap();
|
||||
time
|
||||
};
|
||||
|
||||
render(&mut |_| {}, view(0));
|
||||
let pan = median((1..=SAMPLES).map(|sample| render(&mut |_| {}, view(sample))).collect());
|
||||
let interface_pan = median(
|
||||
(1..=SAMPLES)
|
||||
.map(|sample| render(&mut |edit| edit.network_connectors.replace_all(network_connectors(sample as i32 % 2)), view(sample)))
|
||||
.collect(),
|
||||
);
|
||||
let card_change = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let key = NodeId((sample * 37 % CARDS) as u64);
|
||||
render(
|
||||
&mut |edit| {
|
||||
edit.cards.update(&key, |card| *card = reselected(&moved(card, IVec2::Y)));
|
||||
rewire(edit);
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let highlight = |card: &mut Card, highlight| card.primary_output.as_mut().expect("every card has a primary output").highlight = highlight;
|
||||
let mut hovered = None;
|
||||
let hover_move = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let key = NodeId((sample * 37 % CARDS) as u64);
|
||||
let left = hovered.replace(key);
|
||||
render(
|
||||
&mut |edit| {
|
||||
if let Some(left) = left {
|
||||
edit.cards.update(&left, |card| highlight(card, Highlight::None));
|
||||
}
|
||||
edit.cards.update(&key, |card| highlight(card, Highlight::Hovered));
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let glide_frame = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let glide = DVec2::new(-24. * 0.6_f64.powi(sample as i32 % 8 + 1), 0.);
|
||||
render(
|
||||
&mut |edit| {
|
||||
for index in 0..GLIDING {
|
||||
edit.cards.update(&NodeId((index * 61 % CARDS) as u64), |card| card.glide = glide);
|
||||
}
|
||||
rewire(edit);
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let mut every_card = |changed: fn(&Card, IVec2) -> Card| {
|
||||
median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let offset = if sample % 2 == 0 { IVec2::X } else { -IVec2::X };
|
||||
render(
|
||||
&mut |edit| {
|
||||
let cards: Vec<Card> = edit.cards.iter().map(|card| changed(card, offset)).collect();
|
||||
edit.cards.replace_all(cards);
|
||||
rewire(edit);
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
let rebuild = every_card(|card, offset| reselected(&moved(card, offset)));
|
||||
let every_card_moved = every_card(moved);
|
||||
|
||||
let draw = |card_at: fn(usize) -> Card| {
|
||||
let cards: Vec<Card> = (0..CARDS).map(card_at).collect();
|
||||
let scenes = [scene(cards.clone()), scene(cards.iter().map(reselected))];
|
||||
let times = (0..SAMPLES).map(|sample| {
|
||||
let context = rows_context(scenes[sample % 2].cards());
|
||||
let start = Instant::now();
|
||||
draw_cards.tree().eval::<Context, List<Vector>>(cards_output.node(), &context).expect("the cards are drawn");
|
||||
start.elapsed()
|
||||
});
|
||||
median(times.collect())
|
||||
};
|
||||
let drawn = draw(card);
|
||||
let drawn_unnamed = draw(|index| unnamed(card(index)));
|
||||
let text = drawn.saturating_sub(drawn_unnamed);
|
||||
|
||||
let wired = |cards: Vec<Card>| {
|
||||
let mut edit = scene(cards).edit();
|
||||
rewire(&mut edit);
|
||||
edit.finish().0
|
||||
};
|
||||
let cards: Vec<Card> = (0..CARDS).map(card).collect();
|
||||
let scenes = [wired(cards.clone()), wired(cards.iter().map(|card| moved(card, IVec2::X)).collect())];
|
||||
let wires_drawn = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let context = rows_context(scenes[sample % 2].wires());
|
||||
let start = Instant::now();
|
||||
draw_wires.tree().eval::<Context, List<Vector>>(wires_output.node(), &context).expect("the wires are drawn");
|
||||
start.elapsed()
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
|
||||
let grid = |zoom: f64, scale: f64| {
|
||||
let resolution = (RESOLUTION.as_dvec2() * scale).as_uvec2();
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint { resolution, ..render_config.viewport },
|
||||
scale,
|
||||
..render_config
|
||||
};
|
||||
let times = (1..=SAMPLES).map(|sample| {
|
||||
let graph_ui = GraphUi {
|
||||
scene: GraphUiScene::default(),
|
||||
config: config(DAffine2::from_scale_angle_translation(DVec2::splat(zoom), 0., DVec2::new(100. + sample as f64, 0.)), 0.5),
|
||||
thumbnails: Default::default(),
|
||||
};
|
||||
let context = context(render_config, graph_ui);
|
||||
let mut scene = VelloSceneBuilder::new(resolution.x as u16, resolution.y as u16, Affine::IDENTITY, resolution.x);
|
||||
let start = Instant::now();
|
||||
let dots = draw_grid.tree().eval::<Context, List<Vector>>(grid_output.node(), &context).expect("the grid is drawn");
|
||||
let drawn = start.elapsed();
|
||||
dots.render_to_vello(&mut scene, DAffine2::from_scale(DVec2::splat(scale)), &RenderParams::default());
|
||||
(drawn, start.elapsed() - drawn)
|
||||
});
|
||||
let (drawn, encoded): (Vec<Duration>, Vec<Duration>) = times.unzip();
|
||||
(median(drawn), median(encoded))
|
||||
};
|
||||
let grids = [1., 2.].map(|scale| (scale, grid(0.5, scale), grid(1., scale)));
|
||||
|
||||
let times = (1..=SAMPLES).map(|sample| {
|
||||
let graph_ui = GraphUi {
|
||||
scene: editor_scene.clone(),
|
||||
config: config(view(sample), 0.5),
|
||||
thumbnails: thumbnails.clone(),
|
||||
};
|
||||
let context = context(render_config, graph_ui);
|
||||
let mut scene = VelloSceneBuilder::new(RESOLUTION.x as u16, RESOLUTION.y as u16, Affine::IDENTITY, RESOLUTION.x);
|
||||
let start = Instant::now();
|
||||
let drawn = draw_thumbnails
|
||||
.tree()
|
||||
.eval::<Context, List<Vector>>(thumbnails_output.node(), &context)
|
||||
.expect("the thumbnails are drawn");
|
||||
let elapsed = start.elapsed();
|
||||
drawn.render_to_vello(&mut scene, view(sample), &RenderParams::default());
|
||||
(elapsed, start.elapsed() - elapsed)
|
||||
});
|
||||
let (thumbnails_drawn, thumbnails_encoded): (Vec<Duration>, Vec<Duration>) = times.unzip();
|
||||
|
||||
let scene = full_scene();
|
||||
let raised_rows = OwnedContextImpl::default()
|
||||
.with_varargs([Box::new(scene.layers().clone()), Box::new(scene.cards().clone())])
|
||||
.into_context();
|
||||
let scene_bands = [
|
||||
("cards", graph_ui::nodes::draw_cards::IDENTIFIER, rows_context(scene.cards())),
|
||||
("raised", graph_ui::nodes::draw_raised::IDENTIFIER, raised_rows),
|
||||
("layers", graph_ui::nodes::draw_layers::IDENTIFIER, rows_context(scene.layers())),
|
||||
("wires", graph_ui::nodes::draw_wires::IDENTIFIER, rows_context(scene.wires())),
|
||||
("errors", graph_ui::nodes::draw_errors::IDENTIFIER, rows_context(scene.errors())),
|
||||
("imports/exports", graph_ui::nodes::draw_network_connectors::IDENTIFIER, rows_context(scene.network_connectors())),
|
||||
]
|
||||
.map(|(name, band, rows)| {
|
||||
let (band, output) = executor(network(&gpu, [node(band, Vec::new())]));
|
||||
(name, band.tree().eval::<Context, List<Vector>>(output.node(), &rows).expect("the band is drawn"))
|
||||
});
|
||||
let encoded = |band: &List<Vector>, zoom: f64, left: f64| {
|
||||
let times = (1..=SAMPLES).map(|sample| {
|
||||
let view = DAffine2::from_scale_angle_translation(DVec2::splat(zoom), 0., DVec2::new(left + sample as f64, 0.));
|
||||
let mut scene = VelloSceneBuilder::new(RESOLUTION.x as u16, RESOLUTION.y as u16, Affine::IDENTITY, RESOLUTION.x);
|
||||
let start = Instant::now();
|
||||
band.render_to_vello(&mut scene, view, &RenderParams::default());
|
||||
start.elapsed()
|
||||
});
|
||||
median(times.collect())
|
||||
};
|
||||
let band_encodes = [0.5, 1.].map(|zoom| {
|
||||
let bands = scene_bands.iter().map(|(name, band)| (*name, band.len(), encoded(band, zoom, 100.), encoded(band, zoom, -100_000.)));
|
||||
(zoom, bands.collect::<Vec<_>>())
|
||||
});
|
||||
|
||||
let profile = if cfg!(debug_assertions) { "dev" } else { "release" };
|
||||
println!(
|
||||
"{CARDS} cards, each wired to the next, {LAYERS} layers, four imports and four exports and {ERRORS} error badges at {}x{}, {profile} profile, CPU time without the GPU wait, median of {SAMPLES}",
|
||||
RESOLUTION.x, RESOLUTION.y
|
||||
);
|
||||
println!("pan step (view change only): {:.3} ms", ms(pan));
|
||||
println!("pan step that moves the imports and exports a cell: {:.3} ms", ms(interface_pan));
|
||||
println!("one-card change (one card moved and reselected, so drawn again, and its two wires): {:.3} ms", ms(card_change));
|
||||
println!("hover moving from one card to another: {:.3} ms", ms(hover_move));
|
||||
println!("glide frame of {GLIDING} cards and their wires: {:.3} ms", ms(glide_frame));
|
||||
println!("full rebuild (every card and wire changed): {:.3} ms", ms(rebuild));
|
||||
println!("every card only moved a cell (placed again, not drawn again), every wire changed: {:.3} ms", ms(every_card_moved));
|
||||
println!("draw_cards alone, every card drawn again: {:.3} ms, with every name empty: {:.3} ms", ms(drawn), ms(drawn_unnamed));
|
||||
println!("draw_wires alone, every wire drawn again: {:.3} ms", ms(wires_drawn));
|
||||
println!(
|
||||
"text (width, ellipsized, outline), the difference: {:.3} ms, {:.0}% of draw_cards, {:.0}% of a one-card change",
|
||||
ms(text),
|
||||
100. * text.as_secs_f64() / drawn.as_secs_f64(),
|
||||
100. * text.as_secs_f64() / card_change.as_secs_f64()
|
||||
);
|
||||
for (scale, (drawn, encoded), (drawn_at_1, encoded_at_1)) in grids {
|
||||
println!(
|
||||
"grid alone at zoom 0.5 and device scale {scale}: draw_grid {:.3} ms + Vello encode {:.3} ms (at zoom 1: {:.3} ms + {:.3} ms)",
|
||||
ms(drawn),
|
||||
ms(encoded),
|
||||
ms(drawn_at_1),
|
||||
ms(encoded_at_1)
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"thumbnails alone, one on each of the {LAYERS} layers: draw_thumbnails {:.3} ms + Vello encode {:.3} ms",
|
||||
ms(median(thumbnails_drawn)),
|
||||
ms(median(thumbnails_encoded))
|
||||
);
|
||||
for (zoom, bands) in band_encodes {
|
||||
println!("Vello encode alone of each scene band at zoom {zoom}, on screen and with every item panned off screen (the bookkeeping before the cull):");
|
||||
for (name, items, on_screen, off_screen) in &bands {
|
||||
println!(" {name} ({items} items): {:.3} ms on screen, {:.3} ms off screen", ms(*on_screen), ms(*off_screen));
|
||||
}
|
||||
let on_screen: Duration = bands.iter().map(|(_, _, on_screen, _)| *on_screen).sum();
|
||||
let off_screen: Duration = bands.iter().map(|(_, _, _, off_screen)| *off_screen).sum();
|
||||
println!(" all six: {:.3} ms on screen, {:.3} ms off screen", ms(on_screen), ms(off_screen));
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
@@ -95,7 +95,7 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
||||
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
||||
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
write_layer_paths(&mut network, layers);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
let preprocessed = match gdd {
|
||||
|
||||
@@ -5,7 +5,7 @@ use graph_craft::util::{DEMO_ART, compile};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
|
||||
@@ -13,7 +13,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
||||
.unwrap()
|
||||
.network;
|
||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
|
||||
@@ -21,7 +21,7 @@ use graphene_std::{Color, Context};
|
||||
use gungraun::prelude::*;
|
||||
use gungraun::{Callgrind, EntryPoint};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use std::hint::black_box;
|
||||
use std::sync::Arc;
|
||||
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
|
||||
@@ -70,7 +70,7 @@ impl Session {
|
||||
|
||||
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
|
||||
fn update(&mut self, document: NodeNetwork) {
|
||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
|
||||
@@ -5,6 +5,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_std::RadialBlurMethod;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
@@ -28,7 +29,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -292,9 +293,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
GlowTechnique,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
NoiseDistribution,
|
||||
RadialBlurMethod,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
|
||||
@@ -9,7 +9,7 @@ use graphene_std::RuntimeHandle;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
pub fn wrap_network_with_render_node_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
let definitions = std::mem::take(&mut network.definitions);
|
||||
|
||||
let inner_network = DocumentNode {
|
||||
@@ -114,10 +114,28 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(0), inner_network), (NodeId(1), render_node)].into_iter().collect(),
|
||||
definitions,
|
||||
generated: true,
|
||||
..Default::default()
|
||||
};
|
||||
wrap_network_in_scope(network, editor_api, runtime)
|
||||
}
|
||||
|
||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
let definitions = std::mem::take(&mut network.definitions);
|
||||
|
||||
let inner_network = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(network),
|
||||
inputs: vec![],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// wrap the inner network in a scope
|
||||
let nodes = vec![
|
||||
inner_network,
|
||||
render_node,
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)],
|
||||
@@ -130,12 +148,12 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
},
|
||||
];
|
||||
let scope_injections = vec![
|
||||
("editor-api".to_string(), (NodeId(2), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))),
|
||||
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
|
||||
];
|
||||
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(0), 0)],
|
||||
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
||||
scope_injections: scope_injections.into_iter().collect(),
|
||||
definitions,
|
||||
|
||||
@@ -805,6 +805,11 @@ impl OwnedContextImpl {
|
||||
self.varargs = Some(Arc::new([value]));
|
||||
self
|
||||
}
|
||||
pub fn with_varargs<const N: usize>(mut self, values: [Box<dyn AnyHash + Send + Sync>; N]) -> Self {
|
||||
assert!(self.varargs.is_none_or(|value| value.is_empty()));
|
||||
self.varargs = Some(Arc::new(values));
|
||||
self
|
||||
}
|
||||
pub fn with_generations(mut self, generations: Generations) -> Self {
|
||||
self.generations = (!generations.is_empty()).then_some(generations);
|
||||
self
|
||||
|
||||
@@ -281,11 +281,11 @@ impl<'a, N> LazyInput<'a, N> {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn eval<Input>(&self, input: Input) -> Result<N::Output, Interrupt>
|
||||
pub fn eval<Input>(&self, input: &Input) -> Result<N::Output, Interrupt>
|
||||
where
|
||||
N: Node<Input>,
|
||||
{
|
||||
self.status.record(self.index, self.node.eval(&input))
|
||||
self.status.record(self.index, self.node.eval(input))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,6 @@ pub struct NodeFlags {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FieldMetadata {
|
||||
pub name: &'static str,
|
||||
/// The parameter's name in the node function, which graph text uses to set it.
|
||||
pub identifier: &'static str,
|
||||
pub description: &'static str,
|
||||
/// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub internal: bool,
|
||||
@@ -62,12 +60,6 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -230,146 +222,6 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// The graph text of every `graph!` invocation, in registration order.
|
||||
pub static GRAPH_SOURCES: LazyLock<Mutex<Vec<GraphSource>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// The text of one `graph!` invocation and where it's written, for error messages.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphSource {
|
||||
/// The module the graph is defined in, which qualifies its name in `use` paths.
|
||||
pub module_path: &'static str,
|
||||
pub file: &'static str,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub text: &'static str,
|
||||
}
|
||||
|
||||
/// Registers graph text as a built-in subgraph node, which the editor turns into a catalog definition.
|
||||
///
|
||||
/// Each invocation registers itself under a symbol named after its crate, line, and column, so two invocations at the
|
||||
/// same line and column in different files of one crate fail to link.
|
||||
#[macro_export]
|
||||
macro_rules! graph {
|
||||
($($source:tt)*) => {
|
||||
const _: () = {
|
||||
use $crate as gcore;
|
||||
use gcore::ctor::ctor;
|
||||
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
|
||||
#[unsafe(export_name = concat!("__node_registry_graph_", env!("CARGO_CRATE_NAME"), "_", line!(), "_", column!()))]
|
||||
extern "C" fn register_graph() {
|
||||
gcore::registry::GRAPH_SOURCES.lock().unwrap().push(gcore::registry::GraphSource {
|
||||
module_path: module_path!(),
|
||||
file: file!(),
|
||||
line: line!(),
|
||||
column: column!(),
|
||||
text: stringify!($($source)*),
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/// A node defined as a subgraph in graph text, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
/// The module path and function name that `use` paths in graph text name the graph by.
|
||||
pub path: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `fn name@N`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[layer]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
/// The export's name in graph text, which chooses it as an output.
|
||||
pub identifier: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined in graph text.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The position in grid units.
|
||||
pub position: (i32, i32),
|
||||
pub layer: bool,
|
||||
pub display_name: Option<&'static str>,
|
||||
pub hidden: bool,
|
||||
pub locked: bool,
|
||||
pub pinned: bool,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another subgraph node, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined in graph text.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in graph text, whose type is set by how it's written.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
[package]
|
||||
name = "graph-text"
|
||||
description = "Parses the graph text format, which defines subgraph nodes in a Rust-like syntax"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
syn = { workspace = true }
|
||||
proc-macro2 = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -1,106 +0,0 @@
|
||||
//! The default placement of a graph's nodes, relative to the nodes they feed.
|
||||
|
||||
/// How far apart, in grid units, a node is placed from the node it feeds.
|
||||
const COLUMN_WIDTH: i32 = 7;
|
||||
|
||||
/// A node's wires and its written placement, as the layout reads them.
|
||||
pub struct LayoutNode {
|
||||
/// The node feeding the primary input.
|
||||
pub primary: Option<usize>,
|
||||
/// The nodes feeding the other inputs, in the order they're written.
|
||||
pub secondaries: Vec<usize>,
|
||||
/// The absolute position from `.at(x, y)`, which replaces the default one.
|
||||
pub at: Option<(i32, i32)>,
|
||||
/// The nudge from `.offset(x, y)`, added to the default position.
|
||||
pub offset: (i32, i32),
|
||||
}
|
||||
|
||||
/// Places each node in the column left of the first node it feeds. A node feeding a primary input shares that node's row,
|
||||
/// and one feeding another input goes in a new row below everything placed so far. Each export's node starts a new row.
|
||||
pub fn layout(nodes: &[LayoutNode], roots: &[usize]) -> Vec<(i32, i32)> {
|
||||
let mut placement = Placement {
|
||||
nodes,
|
||||
positions: vec![None; nodes.len()],
|
||||
bottom: None,
|
||||
};
|
||||
|
||||
for &root in roots {
|
||||
let row = placement.next_row();
|
||||
placement.place(root, 0, row);
|
||||
}
|
||||
for node in 0..nodes.len() {
|
||||
let row = placement.next_row();
|
||||
placement.place(node, 0, row);
|
||||
}
|
||||
|
||||
placement.positions.into_iter().map(Option::unwrap_or_default).collect()
|
||||
}
|
||||
|
||||
struct Placement<'a> {
|
||||
nodes: &'a [LayoutNode],
|
||||
positions: Vec<Option<(i32, i32)>>,
|
||||
/// The lowest row used so far.
|
||||
bottom: Option<i32>,
|
||||
}
|
||||
|
||||
impl Placement<'_> {
|
||||
fn next_row(&self) -> i32 {
|
||||
self.bottom.map_or(0, |bottom| bottom + 1)
|
||||
}
|
||||
|
||||
fn place(&mut self, node: usize, x: i32, y: i32) {
|
||||
if self.positions[node].is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let LayoutNode { primary, secondaries, at, offset } = &self.nodes[node];
|
||||
let (x, y) = at.unwrap_or((x + offset.0, y + offset.1));
|
||||
self.positions[node] = Some((x, y));
|
||||
self.bottom = Some(self.bottom.map_or(y, |bottom| bottom.max(y)));
|
||||
|
||||
if let Some(primary) = primary {
|
||||
self.place(*primary, x - COLUMN_WIDTH, y);
|
||||
}
|
||||
for &secondary in secondaries {
|
||||
let row = self.next_row();
|
||||
self.place(secondary, x - COLUMN_WIDTH, row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn node(primary: Option<usize>, secondaries: Vec<usize>) -> LayoutNode {
|
||||
LayoutNode {
|
||||
primary,
|
||||
secondaries,
|
||||
at: None,
|
||||
offset: (0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chains_run_left_and_side_inputs_go_below() {
|
||||
// Merge: `base >> as_graphic() >> extend(new = content >> into_group())`
|
||||
let nodes = [node(None, vec![]), node(None, vec![]), node(Some(0), vec![1])];
|
||||
assert_eq!(layout(&nodes, &[2]), [(-7, 0), (-7, 1), (0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_placement_moves_a_node_and_its_upstream() {
|
||||
let mut offset = node(None, vec![]);
|
||||
offset.offset = (0, 2);
|
||||
let mut at = node(Some(0), vec![]);
|
||||
at.at = Some((10, -4));
|
||||
|
||||
assert_eq!(layout(&[offset, at], &[1]), [(3, -2), (10, -4)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_export_and_unexported_node_starts_a_new_row() {
|
||||
let nodes = [node(None, vec![]), node(None, vec![]), node(None, vec![])];
|
||||
assert_eq!(layout(&nodes, &[0, 1]), [(0, 0), (0, 1), (0, 2)]);
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
//! Graph text, which defines a subgraph node in a Rust-like syntax that is parsed at runtime.
|
||||
//!
|
||||
//! Built-in graphs are written in `core_types::graph!` invocations, which register their text at startup.
|
||||
|
||||
mod layout;
|
||||
mod resolve;
|
||||
mod syntax;
|
||||
|
||||
use core_types::ProtoNodeIdentifier;
|
||||
use core_types::registry::{GRAPH_SOURCES, GraphMetadata, GraphSource, NODE_METADATA, NodeMetadata};
|
||||
use resolve::{Context, ResolveError};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::sync::LazyLock;
|
||||
pub use syntax::SYNTAX_VERSION;
|
||||
|
||||
/// Every registered graph that resolves, in registration order. Resolved on first access, which must happen after
|
||||
/// startup registration of the nodes and graphs completes. Each graph that fails is left out and its error logged.
|
||||
pub static GRAPHS: LazyLock<Vec<GraphMetadata>> = LazyLock::new(|| {
|
||||
let sources = GRAPH_SOURCES.lock().map(|sources| sources.clone()).unwrap_or_default();
|
||||
let Ok(proto_nodes) = NODE_METADATA.lock() else {
|
||||
log::error!("The node metadata is poisoned, so no graph resolves");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let (graphs, errors) = resolve_sources(&sources, &proto_nodes);
|
||||
for error in errors {
|
||||
log::error!("{error}");
|
||||
}
|
||||
graphs
|
||||
});
|
||||
|
||||
/// The position of a registered graph's import, by the graph's identifier and the import's name.
|
||||
pub fn import_index(graph: &str, import: &str) -> Option<usize> {
|
||||
GRAPHS.iter().find(|metadata| metadata.identifier == graph)?.imports.iter().position(|field| field.identifier == import)
|
||||
}
|
||||
|
||||
/// An error in graph text, with the place it's written.
|
||||
#[derive(Debug)]
|
||||
pub struct GraphTextError {
|
||||
pub message: String,
|
||||
pub file: &'static str,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
/// The graph text from the error onward, which locates it within the text.
|
||||
pub excerpt: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for GraphTextError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "{}:{}:{}: {} (at `{}`)", self.file, self.line, self.column, self.message, self.excerpt)
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphTextError {
|
||||
fn new(source: &GraphSource, error: syn::Error) -> Vec<Self> {
|
||||
error
|
||||
.into_iter()
|
||||
.map(|error| {
|
||||
let start = error.span().start();
|
||||
let excerpt = source
|
||||
.text
|
||||
.lines()
|
||||
.nth(start.line.saturating_sub(1))
|
||||
.map(|line| line.chars().skip(start.column).take(40).collect::<String>())
|
||||
.unwrap_or_default();
|
||||
|
||||
Self {
|
||||
message: error.to_string(),
|
||||
file: source.file,
|
||||
line: source.line,
|
||||
column: source.column,
|
||||
excerpt: excerpt.trim().to_string(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses and resolves graph sources. A graph using another one resolves once that one has, whatever the order.
|
||||
pub fn resolve_sources(sources: &[GraphSource], proto_nodes: &HashMap<ProtoNodeIdentifier, NodeMetadata>) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
let mut pending = Vec::new();
|
||||
for source in sources {
|
||||
match syn::parse_str::<syntax::Source>(source.text) {
|
||||
Ok(parsed) => pending.push((source, parsed, None)),
|
||||
Err(error) => errors.extend(GraphTextError::new(source, error)),
|
||||
}
|
||||
}
|
||||
|
||||
let mut graphs = Vec::new();
|
||||
loop {
|
||||
let pending_count = pending.len();
|
||||
|
||||
let mut still_pending = Vec::new();
|
||||
for (source, parsed, _) in pending {
|
||||
let context = Context { proto_nodes, graphs: &graphs };
|
||||
match resolve::resolve(&parsed, source.module_path, &context) {
|
||||
Ok(graph) => graphs.push(graph),
|
||||
Err(ResolveError::Invalid(error)) => errors.extend(GraphTextError::new(source, error)),
|
||||
Err(ResolveError::Unresolved(error)) => still_pending.push((source, parsed, Some(error))),
|
||||
}
|
||||
}
|
||||
pending = still_pending;
|
||||
|
||||
if pending.is_empty() || pending.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (source, _, error) in pending {
|
||||
if let Some(error) = error {
|
||||
errors.extend(GraphTextError::new(source, error));
|
||||
}
|
||||
}
|
||||
|
||||
(graphs, errors)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,749 +0,0 @@
|
||||
//! Resolves parsed graph text against the registered nodes and graphs, producing the graph's `GraphMetadata`.
|
||||
|
||||
use crate::layout::{LayoutNode, layout};
|
||||
use crate::syntax::{Attribute, Expression, GraphItem, Import, Source, StateKind, Use, ValueKind, doc_comment};
|
||||
use convert_case::{Case, Casing};
|
||||
use core_types::registry::{
|
||||
FieldMetadata, GraphExportMetadata, GraphInputSource, GraphMetadata, GraphNodeImplementation, GraphNodeMetadata, GraphValue, NodeMetadata, RegistryValueSource, RegistryWidgetOverride,
|
||||
};
|
||||
use core_types::{ProtoNodeIdentifier, Type, concrete, generic};
|
||||
use proc_macro2::Span;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use syn::ext::IdentExt;
|
||||
use syn::parse::{ParseStream, Parser};
|
||||
use syn::{Error, Ident, LitBool, LitInt, LitStr, Token};
|
||||
|
||||
/// The registered nodes and the graphs resolved so far, which graph text can use.
|
||||
pub struct Context<'a> {
|
||||
pub proto_nodes: &'a HashMap<ProtoNodeIdentifier, NodeMetadata>,
|
||||
pub graphs: &'a [GraphMetadata],
|
||||
}
|
||||
|
||||
pub enum ResolveError {
|
||||
/// A used name matches nothing yet, which may be a graph that resolves later.
|
||||
Unresolved(Error),
|
||||
Invalid(Error),
|
||||
}
|
||||
|
||||
impl From<Error> for ResolveError {
|
||||
fn from(error: Error) -> Self {
|
||||
Self::Invalid(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a used name refers to.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Target<'a> {
|
||||
ProtoNode(&'a ProtoNodeIdentifier, &'a NodeMetadata),
|
||||
Graph(&'a GraphMetadata),
|
||||
}
|
||||
|
||||
impl<'a> Target<'a> {
|
||||
fn parameters(&self) -> &'a [FieldMetadata] {
|
||||
match self {
|
||||
Self::ProtoNode(_, metadata) => &metadata.fields,
|
||||
Self::Graph(graph) => &graph.imports,
|
||||
}
|
||||
}
|
||||
|
||||
fn implementation(&self) -> GraphNodeImplementation {
|
||||
match self {
|
||||
Self::ProtoNode(identifier, _) => GraphNodeImplementation::ProtoNode((*identifier).clone()),
|
||||
Self::Graph(graph) => GraphNodeImplementation::Graph(graph.identifier),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input or export while the body is read.
|
||||
#[derive(Clone)]
|
||||
enum Feed {
|
||||
/// A node's output, chosen by name, or else its primary output.
|
||||
Node {
|
||||
node: usize,
|
||||
output: Option<usize>,
|
||||
},
|
||||
Import(usize),
|
||||
Value {
|
||||
value: GraphValue,
|
||||
exposed: Option<bool>,
|
||||
},
|
||||
Scope(String),
|
||||
NodePath,
|
||||
SourceId,
|
||||
}
|
||||
|
||||
struct Node<'a> {
|
||||
target: Target<'a>,
|
||||
name: Ident,
|
||||
inputs: Vec<(usize, Feed)>,
|
||||
states: Vec<StateKind>,
|
||||
}
|
||||
|
||||
struct Resolver<'a> {
|
||||
context: &'a Context<'a>,
|
||||
graph_path: String,
|
||||
uses: HashMap<String, &'a Use>,
|
||||
used: HashSet<String>,
|
||||
imports: &'a [Import],
|
||||
bindings: HashMap<String, Feed>,
|
||||
nodes: Vec<Node<'a>>,
|
||||
/// The parameters of the inner inputs each import feeds, in the order they're written.
|
||||
import_consumers: Vec<Vec<FieldMetadata>>,
|
||||
}
|
||||
|
||||
/// Resolves a parsed graph text, given the module path its graph is defined in.
|
||||
pub fn resolve(source: &Source, module_path: &str, context: &Context) -> Result<GraphMetadata, ResolveError> {
|
||||
let graph = &source.graph;
|
||||
let graph_path = format!("{module_path}::{}", graph.name);
|
||||
|
||||
let mut uses = HashMap::new();
|
||||
for entry in &source.uses {
|
||||
let local_name = entry.local_name();
|
||||
if uses.insert(local_name.to_string(), entry).is_some() {
|
||||
return Err(Error::new(local_name.span(), format!("`{local_name}` is used twice. Rename one with `as`")).into());
|
||||
}
|
||||
}
|
||||
|
||||
let mut resolver = Resolver {
|
||||
context,
|
||||
graph_path,
|
||||
uses,
|
||||
used: HashSet::new(),
|
||||
imports: &graph.imports,
|
||||
bindings: HashMap::new(),
|
||||
nodes: Vec::new(),
|
||||
import_consumers: vec![Vec::new(); graph.imports.len()],
|
||||
};
|
||||
|
||||
for binding in &graph.bindings {
|
||||
let name = binding.name.to_string();
|
||||
if resolver.bindings.contains_key(&name) || resolver.import_index(&binding.name).is_some() {
|
||||
return Err(Error::new(binding.name.span(), format!("`{name}` is already the name of a binding or import")).into());
|
||||
}
|
||||
let feed = resolver.read(&binding.value)?;
|
||||
resolver.bindings.insert(name, feed);
|
||||
}
|
||||
|
||||
let export_feeds = resolver.read_exports(&graph.result, graph.exports.len())?;
|
||||
|
||||
if let Some(unused) = source.uses.iter().find(|entry| !resolver.used.contains(&entry.local_name().to_string())) {
|
||||
return Err(Error::new(unused.local_name().span(), format!("`{}` is used but never called", unused.local_name())).into());
|
||||
}
|
||||
|
||||
resolver.build(graph, module_path, export_feeds)
|
||||
}
|
||||
|
||||
impl<'a> Resolver<'a> {
|
||||
fn import_index(&self, name: &Ident) -> Option<usize> {
|
||||
self.imports.iter().position(|import| import.name.as_ref() == Some(name))
|
||||
}
|
||||
|
||||
fn read(&mut self, expression: &'a Expression) -> Result<Feed, ResolveError> {
|
||||
match expression {
|
||||
Expression::Name(name) => {
|
||||
if let Some(feed) = self.bindings.get(&name.to_string()) {
|
||||
return Ok(feed.clone());
|
||||
}
|
||||
if let Some(index) = self.import_index(name) {
|
||||
return Ok(Feed::Import(index));
|
||||
}
|
||||
Err(Error::new(name.span(), format!("`{name}` isn't a binding or import. Call a node with parentheses, like `{name}()`")).into())
|
||||
}
|
||||
Expression::Value(value) => Ok(Feed::Value {
|
||||
value: match &value.kind {
|
||||
ValueKind::Integer(integer) => GraphValue::Integer(*integer),
|
||||
ValueKind::Number(number) => GraphValue::Number(*number),
|
||||
ValueKind::Bool(boolean) => GraphValue::Bool(*boolean),
|
||||
ValueKind::String(string) => GraphValue::String(string.clone()),
|
||||
ValueKind::Vec2(x, y) => GraphValue::vec2(*x, *y),
|
||||
},
|
||||
exposed: None,
|
||||
}),
|
||||
Expression::Call(call) => self.read_call(call),
|
||||
Expression::Feed { upstream, downstream, span } => {
|
||||
let upstream_feed = self.read(upstream)?;
|
||||
let Feed::Node { node, output } = self.read(downstream)? else {
|
||||
return Err(Error::new(downstream.span(), "The right side of `>>` is a node, like `fill()`, or a binding naming one").into());
|
||||
};
|
||||
|
||||
if let Feed::Node { node: upstream_node, .. } = upstream_feed
|
||||
&& self.is_fed_by(upstream_node, node)
|
||||
{
|
||||
return Err(Error::new(*span, "This wire makes a loop, since the node on the right already feeds the left side").into());
|
||||
}
|
||||
|
||||
let entry = &self.nodes[node];
|
||||
if entry.target.parameters().is_empty() {
|
||||
return Err(Error::new(entry.name.span(), format!("`{}` has no parameters, so `>>` has no input to feed", entry.name)).into());
|
||||
}
|
||||
if entry.inputs.iter().any(|(index, _)| *index == 0) {
|
||||
let primary = &entry.target.parameters()[0];
|
||||
let message = format!("The primary input of `{}`, `{}`, is already fed, so `>>` can't feed it too", entry.name, primary.identifier);
|
||||
return Err(Error::new(*span, message).into());
|
||||
}
|
||||
|
||||
self.connect(node, 0, upstream_feed);
|
||||
Ok(Feed::Node { node, output })
|
||||
}
|
||||
Expression::Output { node, output } => {
|
||||
let Feed::Node { node, output: None } = self.read(node)? else {
|
||||
return Err(Error::new(output.span(), "Only a node has outputs to choose from, and only one can be chosen").into());
|
||||
};
|
||||
let Target::Graph(graph) = self.nodes[node].target else {
|
||||
return Err(Error::new(output.span(), "Only a graph's outputs can be chosen by name").into());
|
||||
};
|
||||
let name = output.unraw().to_string();
|
||||
let Some(index) = graph.exports.iter().position(|export| export.identifier == name) else {
|
||||
return Err(Error::new(output.span(), format!("`{}` has no output named `{name}`", self.nodes[node].name)).into());
|
||||
};
|
||||
Ok(Feed::Node { node, output: Some(index) })
|
||||
}
|
||||
Expression::Tuple { span, .. } => Err(Error::new(*span, "A tuple only gives a graph's exports, as its final expression").into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_exports(&mut self, result: &'a Expression, export_count: usize) -> Result<Vec<Feed>, ResolveError> {
|
||||
let values: Vec<&Expression> = match result {
|
||||
Expression::Tuple { elements, .. } => elements.iter().collect(),
|
||||
single => vec![single],
|
||||
};
|
||||
if values.len() != export_count {
|
||||
return Err(Error::new(result.span(), format!("The graph names {export_count} exports, but ends with {} values", values.len())).into());
|
||||
}
|
||||
|
||||
values
|
||||
.into_iter()
|
||||
.map(|value| match self.read(value)? {
|
||||
Feed::Import(_) | Feed::Scope(_) => Err(Error::new(value.span(), "An export can't come straight from an import or scope yet, so pass it through a node first").into()),
|
||||
feed => Ok(feed),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `node` is `source` or feeds it through any chain of wires.
|
||||
fn is_fed_by(&self, node: usize, source: usize) -> bool {
|
||||
let mut visited = vec![false; self.nodes.len()];
|
||||
let mut stack = vec![node];
|
||||
|
||||
while let Some(current) = stack.pop() {
|
||||
if current == source {
|
||||
return true;
|
||||
}
|
||||
if std::mem::replace(&mut visited[current], true) {
|
||||
continue;
|
||||
}
|
||||
stack.extend(self.nodes[current].inputs.iter().filter_map(|(_, feed)| match feed {
|
||||
Feed::Node { node, .. } => Some(*node),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn connect(&mut self, node: usize, input: usize, feed: Feed) {
|
||||
if let Feed::Import(import) = feed {
|
||||
let parameter = self.nodes[node].target.parameters()[input].clone();
|
||||
self.import_consumers[import].push(parameter);
|
||||
}
|
||||
self.nodes[node].inputs.push((input, feed));
|
||||
}
|
||||
|
||||
fn read_call(&mut self, call: &'a crate::syntax::Call) -> Result<Feed, ResolveError> {
|
||||
let name = call.name.to_string();
|
||||
if let Some(feed) = self.read_value_helper(call)? {
|
||||
return Ok(feed);
|
||||
}
|
||||
|
||||
let target = self.target(&call.name)?;
|
||||
self.used.insert(name);
|
||||
|
||||
let mut inputs = Vec::new();
|
||||
for argument in &call.arguments {
|
||||
let parameter = match (&argument.parameter, &argument.value) {
|
||||
(Some(parameter), _) => parameter,
|
||||
(None, Expression::Name(shorthand)) => shorthand,
|
||||
(None, value) => return Err(Error::new(value.span(), "Name each argument, like `weight = 6`, or write a bare name for the shorthand").into()),
|
||||
};
|
||||
|
||||
let Some(index) = target.parameters().iter().position(|field| parameter == field.identifier) else {
|
||||
return Err(Error::new(parameter.span(), format!("`{}` has no parameter named `{parameter}`", call.name)).into());
|
||||
};
|
||||
if inputs.iter().any(|(existing, _)| *existing == index) {
|
||||
return Err(Error::new(parameter.span(), format!("`{parameter}` is already set in this call")).into());
|
||||
}
|
||||
|
||||
let mut feed = self.read(&argument.value)?;
|
||||
for attribute in &argument.attributes {
|
||||
if attribute.name != "exposed" {
|
||||
return Err(Error::new(attribute.name.span(), format!("Unknown argument attribute `#[{}]`", attribute.name)).into());
|
||||
}
|
||||
attribute.flag()?;
|
||||
let Feed::Value { exposed, .. } = &mut feed else {
|
||||
return Err(Error::new(attribute.name.span(), "Only a value can be exposed").into());
|
||||
};
|
||||
*exposed = Some(true);
|
||||
}
|
||||
|
||||
inputs.push((index, feed));
|
||||
}
|
||||
|
||||
self.nodes.push(Node {
|
||||
target,
|
||||
name: call.name.clone(),
|
||||
inputs: Vec::new(),
|
||||
states: call.states.iter().map(|state| state.kind.clone()).collect(),
|
||||
});
|
||||
let node = self.nodes.len() - 1;
|
||||
for (index, feed) in inputs {
|
||||
self.connect(node, index, feed);
|
||||
}
|
||||
|
||||
Ok(Feed::Node { node, output: None })
|
||||
}
|
||||
|
||||
/// Reads a call to `rgb`, `rgba`, `scope`, or `reflect`, which build values and input sources rather than nodes.
|
||||
fn read_value_helper(&self, call: &crate::syntax::Call) -> Result<Option<Feed>, ResolveError> {
|
||||
let name = call.name.to_string();
|
||||
if !matches!(name.as_str(), "rgb" | "rgba" | "scope" | "reflect") {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let [argument] = call.arguments.as_slice() else {
|
||||
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes one argument")).into());
|
||||
};
|
||||
if let Some(state) = call.states.first() {
|
||||
return Err(Error::new(state.span, format!("`{name}(...)` is a value, so it has no node state")).into());
|
||||
}
|
||||
if argument.parameter.is_some() || !argument.attributes.is_empty() {
|
||||
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes a plain argument")).into());
|
||||
}
|
||||
|
||||
let value = &argument.value;
|
||||
let feed = match (name.as_str(), value) {
|
||||
("rgb", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFF_FFFF).contains(hex) => Feed::Value {
|
||||
value: GraphValue::rgb(*hex as u32),
|
||||
exposed: None,
|
||||
},
|
||||
("rgb", _) => return Err(Error::new(value.span(), "`rgb(...)` takes six hex digits, like `rgb(0xE85D75)`. Use `rgba(...)` to give an alpha too").into()),
|
||||
("rgba", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFFFF_FFFF).contains(hex) => Feed::Value {
|
||||
value: GraphValue::rgba(*hex as u32),
|
||||
exposed: None,
|
||||
},
|
||||
("rgba", _) => return Err(Error::new(value.span(), "`rgba(...)` takes eight hex digits, like `rgba(0xE85D75FF)`").into()),
|
||||
("scope", Expression::Value(crate::syntax::Value { kind: ValueKind::String(key), .. })) => Feed::Scope(key.clone()),
|
||||
("scope", _) => return Err(Error::new(value.span(), "`scope(...)` takes the scope's key as a string").into()),
|
||||
(_, Expression::Name(reflected)) if reflected == "NodePath" => Feed::NodePath,
|
||||
(_, Expression::Name(reflected)) if reflected == "SourceId" => Feed::SourceId,
|
||||
_ => return Err(Error::new(value.span(), "Reflect `NodePath` or `SourceId`").into()),
|
||||
};
|
||||
Ok(Some(feed))
|
||||
}
|
||||
|
||||
/// The node or graph a called name refers to, through the `use` section.
|
||||
fn target(&self, name: &Ident) -> Result<Target<'a>, ResolveError> {
|
||||
let Some(entry) = self.uses.get(&name.to_string()) else {
|
||||
return Err(Error::new(name.span(), format!("`{name}` isn't used. Add it to the `use` section, like `use path::{name}@1;`")).into());
|
||||
};
|
||||
let module_path = entry.module_path();
|
||||
|
||||
let proto_identifier = ProtoNodeIdentifier::with_owned_string(format!("{module_path}::{}Node", entry.name.to_string().to_case(Case::Pascal)));
|
||||
if let Some((identifier, metadata)) = self.context.proto_nodes.get_key_value(&proto_identifier) {
|
||||
check_version(entry, metadata.version)?;
|
||||
return Ok(Target::ProtoNode(identifier, metadata));
|
||||
}
|
||||
|
||||
let graph_path = format!("{module_path}::{}", entry.name);
|
||||
if graph_path == self.graph_path {
|
||||
return Err(Error::new(name.span(), "A graph can't contain itself").into());
|
||||
}
|
||||
if let Some(graph) = self.context.graphs.iter().find(|graph| graph.path == graph_path) {
|
||||
check_version(entry, graph.version)?;
|
||||
return Ok(Target::Graph(graph));
|
||||
}
|
||||
|
||||
Err(ResolveError::Unresolved(Error::new(entry.name.span(), format!("No node or graph is named `{graph_path}`"))))
|
||||
}
|
||||
|
||||
fn build(self, graph: &GraphItem, module_path: &str, export_feeds: Vec<Feed>) -> Result<GraphMetadata, ResolveError> {
|
||||
let attributes = GraphAttributes::read(&graph.attributes)?;
|
||||
|
||||
let imports = graph
|
||||
.imports
|
||||
.iter()
|
||||
.zip(&self.import_consumers)
|
||||
.enumerate()
|
||||
.map(|(index, (import, consumers))| import_metadata(index, import, consumers))
|
||||
.collect::<syn::Result<Vec<_>>>()?;
|
||||
let import_types: Vec<Type> = imports.iter().map(import_wire_type).collect();
|
||||
|
||||
let source = |feed: &Feed| match feed {
|
||||
Feed::Node { node, output } => GraphInputSource::Node {
|
||||
node: *node,
|
||||
output: output.unwrap_or(0),
|
||||
},
|
||||
Feed::Import(index) => GraphInputSource::Import {
|
||||
index: *index,
|
||||
ty: import_types[*index].clone(),
|
||||
},
|
||||
Feed::Value { value, exposed } => GraphInputSource::Value {
|
||||
value: value.clone(),
|
||||
exposed: *exposed,
|
||||
},
|
||||
Feed::Scope(key) => GraphInputSource::Scope(leak(key.clone())),
|
||||
Feed::NodePath => GraphInputSource::NodePath,
|
||||
Feed::SourceId => GraphInputSource::SourceId,
|
||||
};
|
||||
|
||||
let layout_nodes: Vec<LayoutNode> = self
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let upstream = |input: &(usize, Feed)| match input.1 {
|
||||
Feed::Node { node, .. } => Some(node),
|
||||
_ => None,
|
||||
};
|
||||
LayoutNode {
|
||||
primary: node.inputs.iter().filter(|input| input.0 == 0).find_map(upstream),
|
||||
secondaries: node.inputs.iter().filter(|input| input.0 != 0).filter_map(upstream).collect(),
|
||||
at: node.states.iter().find_map(|state| match state {
|
||||
StateKind::At(x, y) => Some((*x, *y)),
|
||||
_ => None,
|
||||
}),
|
||||
offset: node
|
||||
.states
|
||||
.iter()
|
||||
.find_map(|state| match state {
|
||||
StateKind::Offset(x, y) => Some((*x, *y)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let roots: Vec<usize> = export_feeds
|
||||
.iter()
|
||||
.filter_map(|feed| match feed {
|
||||
Feed::Node { node, .. } => Some(*node),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let positions = layout(&layout_nodes, &roots);
|
||||
|
||||
let nodes = self
|
||||
.nodes
|
||||
.iter()
|
||||
.zip(positions)
|
||||
.map(|(node, position)| GraphNodeMetadata {
|
||||
implementation: node.target.implementation(),
|
||||
inputs: node.inputs.iter().map(|(index, feed)| (*index, source(feed))).collect(),
|
||||
position,
|
||||
layer: node.states.contains(&StateKind::Layer),
|
||||
display_name: node.states.iter().find_map(|state| match state {
|
||||
StateKind::Named(name) => Some(leak(name.clone())),
|
||||
_ => None,
|
||||
}),
|
||||
hidden: node.states.contains(&StateKind::Hidden),
|
||||
locked: node.states.contains(&StateKind::Locked),
|
||||
pinned: node.states.contains(&StateKind::Pinned),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exports = graph
|
||||
.exports
|
||||
.iter()
|
||||
.zip(&export_feeds)
|
||||
.map(|(export, feed)| {
|
||||
let mut name = None;
|
||||
for attribute in &export.attributes {
|
||||
match attribute.name.to_string().as_str() {
|
||||
"doc" => {}
|
||||
"name" => set_once(&mut name, attribute, attribute.string()?)?,
|
||||
other => return Err(Error::new(attribute.name.span(), format!("Unknown export attribute `#[{other}]`"))),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(GraphExportMetadata {
|
||||
name: leak(name.unwrap_or_else(|| derived_display_name(&export.name))),
|
||||
identifier: leak(export.name.unraw().to_string()),
|
||||
description: leak(doc_comment(&export.attributes)),
|
||||
source: source(feed),
|
||||
})
|
||||
})
|
||||
.collect::<syn::Result<Vec<_>>>()?;
|
||||
|
||||
let identifier = attributes.display_name.unwrap_or_else(|| graph.name.unraw().to_string().to_case(Case::Pascal).to_case(Case::Title));
|
||||
|
||||
Ok(GraphMetadata {
|
||||
identifier: leak(identifier),
|
||||
path: leak(format!("{module_path}::{}", graph.name)),
|
||||
category: leak(attributes.category),
|
||||
icon: attributes.icon.map(leak),
|
||||
description: leak(doc_comment(&graph.attributes)),
|
||||
version: graph.version,
|
||||
layer: attributes.layer,
|
||||
imports,
|
||||
exports,
|
||||
nodes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn check_version(entry: &Use, version: u32) -> syn::Result<()> {
|
||||
if entry.version == version {
|
||||
return Ok(());
|
||||
}
|
||||
Err(Error::new(entry.name.span(), format!("`{}` is at version {version}, not {}", entry.name, entry.version)))
|
||||
}
|
||||
|
||||
/// Strings in the registry's metadata live for the whole program, which holds for graphs resolved once at startup.
|
||||
fn leak(string: String) -> &'static str {
|
||||
Box::leak(string.into_boxed_str())
|
||||
}
|
||||
|
||||
/// The display name an identifier derives, in Title Case.
|
||||
fn derived_display_name(ident: &Ident) -> String {
|
||||
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
|
||||
}
|
||||
|
||||
fn set_once<T>(slot: &mut Option<T>, attribute: &Attribute, value: T) -> syn::Result<()> {
|
||||
if slot.is_some() {
|
||||
return Err(Error::new(attribute.name.span(), format!("Multiple `{}` attributes are not allowed", attribute.name)));
|
||||
}
|
||||
*slot = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct GraphAttributes {
|
||||
category: String,
|
||||
icon: Option<String>,
|
||||
display_name: Option<String>,
|
||||
layer: bool,
|
||||
}
|
||||
|
||||
impl GraphAttributes {
|
||||
fn read(attributes: &[Attribute]) -> syn::Result<Self> {
|
||||
let (mut category, mut icon, mut display_name, mut layer) = (None, None, None, None);
|
||||
|
||||
for attribute in attributes {
|
||||
match attribute.name.to_string().as_str() {
|
||||
"doc" => {}
|
||||
"category" => set_once(&mut category, attribute, attribute.string()?)?,
|
||||
"icon" => set_once(&mut icon, attribute, attribute.string()?)?,
|
||||
"name" => set_once(&mut display_name, attribute, attribute.string()?)?,
|
||||
"layer" => {
|
||||
attribute.flag()?;
|
||||
set_once(&mut layer, attribute, true)?;
|
||||
}
|
||||
other => {
|
||||
return Err(Error::new(
|
||||
attribute.name.span(),
|
||||
format!("Unknown graph attribute `#[{other}]`. Expected `category(\"…\")`, `icon(\"…\")`, `name(\"…\")`, or `layer`"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(category) = category else {
|
||||
return Err(Error::new(Span::call_site(), "A graph needs a category, like `#[category(\"Vector: Deform\")]`"));
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
category,
|
||||
icon,
|
||||
display_name,
|
||||
layer: layer.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter description with nothing set, which an import starts from when it feeds no input.
|
||||
pub(crate) fn blank_field() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "",
|
||||
identifier: "",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: false,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: None,
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// An import's parameter description, inherited from an inner input it feeds and overridden by its own attributes.
|
||||
/// That input is the one whose parameter has the import's name, or else the first one fed.
|
||||
fn import_metadata(index: usize, import: &Import, consumers: &[FieldMetadata]) -> syn::Result<FieldMetadata> {
|
||||
let Some(name) = &import.name else {
|
||||
if let Some(attribute) = import.attributes.first() {
|
||||
return Err(Error::new(attribute.name.span(), "An unused primary import takes no attributes"));
|
||||
}
|
||||
return Ok(FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..blank_field()
|
||||
});
|
||||
};
|
||||
|
||||
let identifier = name.unraw().to_string();
|
||||
let inherited = consumers.iter().find(|consumer| consumer.identifier == identifier).or(consumers.first());
|
||||
let mut field = FieldMetadata {
|
||||
identifier: leak(identifier.clone()),
|
||||
exposed: false,
|
||||
internal: index > 0 && identifier.starts_with('_'),
|
||||
constant: false,
|
||||
..inherited.cloned().unwrap_or_else(blank_field)
|
||||
};
|
||||
|
||||
let mut display_name = None;
|
||||
let mut seen = HashSet::new();
|
||||
for attribute in &import.attributes {
|
||||
let attribute_name = attribute.name.to_string();
|
||||
if attribute_name != "doc" && !seen.insert(attribute_name.clone()) {
|
||||
return Err(Error::new(attribute.name.span(), format!("Multiple `{attribute_name}` attributes are not allowed")));
|
||||
}
|
||||
apply_import_attribute(&mut field, &mut display_name, attribute)?;
|
||||
}
|
||||
|
||||
field.name = leak(display_name.unwrap_or_else(|| derived_display_name(name)));
|
||||
let description = doc_comment(&import.attributes);
|
||||
if !description.is_empty() {
|
||||
field.description = leak(description);
|
||||
}
|
||||
|
||||
Ok(field)
|
||||
}
|
||||
|
||||
fn apply_import_attribute(field: &mut FieldMetadata, display_name: &mut Option<String>, attribute: &Attribute) -> syn::Result<()> {
|
||||
let arguments = || attribute.list();
|
||||
|
||||
match attribute.name.to_string().as_str() {
|
||||
"doc" => {}
|
||||
"name" => *display_name = Some(attribute.string()?),
|
||||
"expose" => {
|
||||
attribute.flag()?;
|
||||
field.exposed = true;
|
||||
}
|
||||
"default" => {
|
||||
let tokens = arguments()?;
|
||||
field.default_type = default_type(&tokens, field.default_type.take());
|
||||
field.value_source = RegistryValueSource::Default(leak(tokens.to_string()));
|
||||
field.default_colors = None;
|
||||
}
|
||||
"widget" => {
|
||||
field.widget_override = (|input: ParseStream| {
|
||||
let kind: Ident = input.parse()?;
|
||||
let text = || -> syn::Result<&'static str> {
|
||||
input.parse::<Token![=]>()?;
|
||||
Ok(leak(input.parse::<LitStr>()?.value()))
|
||||
};
|
||||
match kind.to_string().as_str() {
|
||||
"Hidden" => Ok(RegistryWidgetOverride::Hidden),
|
||||
"String" => Ok(RegistryWidgetOverride::String(text()?)),
|
||||
"Custom" => Ok(RegistryWidgetOverride::Custom(text()?)),
|
||||
_ => Err(Error::new(kind.span(), "A widget is `Hidden`, `String = \"…\"`, or `Custom = \"…\"`")),
|
||||
}
|
||||
})
|
||||
.parse2(arguments()?)?;
|
||||
}
|
||||
"unit" => field.unit = Some(leak(attribute.string()?)),
|
||||
"hard" => (field.number_hard_min, field.number_hard_max) = parse_bounds.parse2(arguments()?)?,
|
||||
"soft" => (field.number_soft_min, field.number_soft_max) = parse_bounds.parse2(arguments()?)?,
|
||||
"range" => {
|
||||
attribute.flag()?;
|
||||
field.number_mode_range = true;
|
||||
}
|
||||
"step" => field.number_step = Some(parse_number.parse2(arguments()?)?),
|
||||
"display_decimal_places" => field.number_display_decimal_places = Some(syn::parse2::<LitInt>(arguments()?)?.base10_parse()?),
|
||||
"multiline" => {
|
||||
attribute.flag()?;
|
||||
field.multiline = true;
|
||||
}
|
||||
"progression" => {
|
||||
attribute.flag()?;
|
||||
field.progression = true;
|
||||
}
|
||||
"integer" => {
|
||||
attribute.flag()?;
|
||||
field.integer = true;
|
||||
}
|
||||
"labels" => {
|
||||
field.labels = Some(
|
||||
(|input: ParseStream| {
|
||||
let x: LitStr = input.parse()?;
|
||||
input.parse::<Token![,]>()?;
|
||||
let y: LitStr = input.parse()?;
|
||||
Ok((leak(x.value()), leak(y.value())))
|
||||
})
|
||||
.parse2(arguments()?)?,
|
||||
);
|
||||
}
|
||||
"blank_assist" => field.blank_assist = syn::parse2::<LitBool>(arguments()?)?.value,
|
||||
other => return Err(Error::new(attribute.name.span(), format!("Unknown import attribute `#[{other}]`"))),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The type a `#[default(...)]` is parsed as: a literal's own type, or else the bare element of the inherited type.
|
||||
fn default_type(tokens: &proc_macro2::TokenStream, inherited: Option<Type>) -> Option<Type> {
|
||||
if let Ok(literal) = syn::parse2::<crate::syntax::Value>(tokens.clone()) {
|
||||
return Some(match literal.kind {
|
||||
ValueKind::Integer(_) => concrete!(i64),
|
||||
ValueKind::Number(_) => concrete!(f64),
|
||||
ValueKind::Bool(_) => concrete!(bool),
|
||||
ValueKind::String(_) => concrete!(String),
|
||||
ValueKind::Vec2(..) => concrete!(glam::DVec2),
|
||||
});
|
||||
}
|
||||
|
||||
match inherited {
|
||||
Some(Type::Item(element)) => Some(*element),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The type an import's wire records, ranked as an `Item` when its default is a bare element.
|
||||
fn import_wire_type(field: &FieldMetadata) -> Type {
|
||||
match &field.default_type {
|
||||
Some(ty @ (Type::Item(_) | Type::List(_) | Type::Fn(..) | Type::Generic(_))) => ty.clone(),
|
||||
Some(unit) if *unit == concrete!(()) => unit.clone(),
|
||||
Some(element) => Type::Item(Box::new(element.clone())),
|
||||
None => generic!(T),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_number(input: ParseStream) -> syn::Result<f64> {
|
||||
let negative = input.peek(Token![-]);
|
||||
if negative {
|
||||
input.parse::<Token![-]>()?;
|
||||
}
|
||||
let magnitude: f64 = match input.parse::<syn::Lit>()? {
|
||||
syn::Lit::Int(integer) => integer.base10_parse()?,
|
||||
syn::Lit::Float(float) => float.base10_parse()?,
|
||||
other => return Err(Error::new(other.span(), "Expected a number")),
|
||||
};
|
||||
Ok(if negative { -magnitude } else { magnitude })
|
||||
}
|
||||
|
||||
/// Reads `a..b`, where either end may be left out.
|
||||
fn parse_bounds(input: ParseStream) -> syn::Result<(Option<f64>, Option<f64>)> {
|
||||
let start = if input.peek(Token![..]) { None } else { Some(parse_number(input)?) };
|
||||
input.parse::<Token![..]>()?;
|
||||
let end = if input.is_empty() { None } else { Some(parse_number(input)?) };
|
||||
Ok((start, end))
|
||||
}
|
||||
@@ -1,780 +0,0 @@
|
||||
//! The grammar of graph text, parsed with syn from the tokens of a `graph!` invocation or a clipboard string.
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use syn::ext::IdentExt;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Error, Ident, Lit, LitInt, LitStr, Token, braced, bracketed, parenthesized};
|
||||
|
||||
/// The syntax version this parser reads, from the `#![syntax(N)]` header.
|
||||
pub const SYNTAX_VERSION: u32 = 1;
|
||||
|
||||
/// A whole graph text: its header, its `use` section, and the graph it defines.
|
||||
pub struct Source {
|
||||
pub uses: Vec<Use>,
|
||||
pub graph: GraphItem,
|
||||
}
|
||||
|
||||
/// One node or graph named by the `use` section, like `math_nodes::add@1`.
|
||||
pub struct Use {
|
||||
pub module: Vec<Ident>,
|
||||
pub name: Ident,
|
||||
pub version: u32,
|
||||
pub alias: Option<Ident>,
|
||||
}
|
||||
|
||||
impl Use {
|
||||
/// The name the body calls it by.
|
||||
pub fn local_name(&self) -> &Ident {
|
||||
self.alias.as_ref().unwrap_or(&self.name)
|
||||
}
|
||||
|
||||
pub fn module_path(&self) -> String {
|
||||
self.module.iter().map(Ident::to_string).collect::<Vec<_>>().join("::")
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute item like `category("Graphic")`, `layer`, or `doc = "…"`. One `#[...]` can hold several, separated by commas.
|
||||
pub struct Attribute {
|
||||
pub name: Ident,
|
||||
pub arguments: AttributeArguments,
|
||||
}
|
||||
|
||||
pub enum AttributeArguments {
|
||||
None,
|
||||
List(TokenStream),
|
||||
Value(Lit),
|
||||
}
|
||||
|
||||
impl Attribute {
|
||||
/// The parenthesized arguments, or an error naming the attribute if it has none.
|
||||
pub fn list(&self) -> syn::Result<TokenStream> {
|
||||
match &self.arguments {
|
||||
AttributeArguments::List(tokens) => Ok(tokens.clone()),
|
||||
_ => Err(Error::new(self.name.span(), format!("`{}` takes arguments in parentheses", self.name))),
|
||||
}
|
||||
}
|
||||
|
||||
/// An error unless the attribute is written without arguments.
|
||||
pub fn flag(&self) -> syn::Result<()> {
|
||||
match &self.arguments {
|
||||
AttributeArguments::None => Ok(()),
|
||||
_ => Err(Error::new(self.name.span(), format!("`{}` takes no arguments", self.name))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn string(&self) -> syn::Result<String> {
|
||||
syn::parse2::<LitStr>(self.list()?).map(|literal| literal.value())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphItem {
|
||||
pub attributes: Vec<Attribute>,
|
||||
pub name: Ident,
|
||||
pub version: u32,
|
||||
pub imports: Vec<Import>,
|
||||
pub exports: Vec<Export>,
|
||||
pub bindings: Vec<Binding>,
|
||||
/// The final expression, which gives one value per export.
|
||||
pub result: Expression,
|
||||
}
|
||||
|
||||
pub struct Import {
|
||||
pub attributes: Vec<Attribute>,
|
||||
/// The import's name, or `None` for an unused primary import written `_`.
|
||||
pub name: Option<Ident>,
|
||||
}
|
||||
|
||||
pub struct Export {
|
||||
pub attributes: Vec<Attribute>,
|
||||
pub name: Ident,
|
||||
}
|
||||
|
||||
pub struct Binding {
|
||||
pub name: Ident,
|
||||
pub value: Expression,
|
||||
}
|
||||
|
||||
pub enum Expression {
|
||||
Name(Ident),
|
||||
Value(Value),
|
||||
Call(Call),
|
||||
/// `upstream >> downstream`, which feeds the upstream into the downstream node's primary input.
|
||||
Feed {
|
||||
upstream: Box<Expression>,
|
||||
downstream: Box<Expression>,
|
||||
span: Span,
|
||||
},
|
||||
/// A node's output chosen by name, like `.captures`.
|
||||
Output {
|
||||
node: Box<Expression>,
|
||||
output: Ident,
|
||||
},
|
||||
Tuple {
|
||||
elements: Vec<Expression>,
|
||||
span: Span,
|
||||
},
|
||||
}
|
||||
|
||||
impl Expression {
|
||||
pub fn span(&self) -> Span {
|
||||
match self {
|
||||
Self::Name(name) => name.span(),
|
||||
Self::Value(value) => value.span,
|
||||
Self::Call(call) => call.name.span(),
|
||||
Self::Feed { span, .. } | Self::Tuple { span, .. } => *span,
|
||||
Self::Output { output, .. } => output.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Value {
|
||||
pub kind: ValueKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
pub enum ValueKind {
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(f64, f64),
|
||||
}
|
||||
|
||||
pub struct Call {
|
||||
pub name: Ident,
|
||||
pub arguments: Vec<Argument>,
|
||||
pub states: Vec<State>,
|
||||
}
|
||||
|
||||
pub struct Argument {
|
||||
pub attributes: Vec<Attribute>,
|
||||
/// The parameter set by `parameter = value`, or `None` for a positional argument, which for a node is the shorthand `name`.
|
||||
pub parameter: Option<Ident>,
|
||||
pub value: Expression,
|
||||
}
|
||||
|
||||
/// A node state method after a call, like `.offset(0, 2)`.
|
||||
pub struct State {
|
||||
pub kind: StateKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub enum StateKind {
|
||||
At(i32, i32),
|
||||
Offset(i32, i32),
|
||||
Named(String),
|
||||
Hidden,
|
||||
Locked,
|
||||
Pinned,
|
||||
Layer,
|
||||
}
|
||||
|
||||
impl Parse for Source {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
parse_header(input)?;
|
||||
|
||||
let mut uses = Vec::new();
|
||||
while input.peek(Token![use]) {
|
||||
uses.extend(parse_use(input)?);
|
||||
}
|
||||
|
||||
let graph = input.parse()?;
|
||||
if !input.is_empty() {
|
||||
return Err(input.error("Graph text defines one graph"));
|
||||
}
|
||||
|
||||
Ok(Self { uses, graph })
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `#![syntax(N)]`, which every graph text starts with.
|
||||
fn parse_header(input: ParseStream) -> syn::Result<()> {
|
||||
if !(input.peek(Token![#]) && input.peek2(Token![!])) {
|
||||
return Err(input.error(format!("Graph text starts with its syntax version, like `#![syntax({SYNTAX_VERSION})]`")));
|
||||
}
|
||||
input.parse::<Token![#]>()?;
|
||||
input.parse::<Token![!]>()?;
|
||||
|
||||
let content;
|
||||
bracketed!(content in input);
|
||||
let name: Ident = content.parse()?;
|
||||
if name != "syntax" {
|
||||
return Err(Error::new(name.span(), "The header is `#![syntax(N)]`"));
|
||||
}
|
||||
|
||||
let arguments;
|
||||
parenthesized!(arguments in content);
|
||||
let literal: LitInt = arguments.parse()?;
|
||||
let version: u32 = literal.base10_parse()?;
|
||||
if version != SYNTAX_VERSION {
|
||||
return Err(Error::new(literal.span(), format!("Syntax version {version} isn't supported, only {SYNTAX_VERSION} is")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads `use path::name@N;` or `use path::{a@N, b@N as c};`.
|
||||
fn parse_use(input: ParseStream) -> syn::Result<Vec<Use>> {
|
||||
let use_token: Token![use] = input.parse()?;
|
||||
|
||||
let mut module = Vec::new();
|
||||
let entries = loop {
|
||||
if input.peek(syn::token::Brace) {
|
||||
let content;
|
||||
braced!(content in input);
|
||||
break Punctuated::<UseEntry, Token![,]>::parse_terminated(&content)?.into_iter().collect::<Vec<_>>();
|
||||
}
|
||||
|
||||
let segment: Ident = input.parse()?;
|
||||
if input.peek(Token![::]) {
|
||||
input.parse::<Token![::]>()?;
|
||||
module.push(segment);
|
||||
} else {
|
||||
break vec![UseEntry::parse_after_name(segment, input)?];
|
||||
}
|
||||
};
|
||||
input.parse::<Token![;]>()?;
|
||||
|
||||
if module.is_empty() {
|
||||
return Err(Error::new(use_token.span, "Name a node by its full path, like `use math_nodes::add@1;`"));
|
||||
}
|
||||
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.map(|entry| Use {
|
||||
module: module.clone(),
|
||||
name: entry.name,
|
||||
version: entry.version,
|
||||
alias: entry.alias,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
struct UseEntry {
|
||||
name: Ident,
|
||||
version: u32,
|
||||
alias: Option<Ident>,
|
||||
}
|
||||
|
||||
impl UseEntry {
|
||||
fn parse_after_name(name: Ident, input: ParseStream) -> syn::Result<Self> {
|
||||
let version = parse_version(input)?;
|
||||
let alias = if input.peek(Token![as]) {
|
||||
input.parse::<Token![as]>()?;
|
||||
Some(input.parse()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self { name, version, alias })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for UseEntry {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let name = input.parse()?;
|
||||
Self::parse_after_name(name, input)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `@N`, the version a node or graph is declared or used at.
|
||||
fn parse_version(input: ParseStream) -> syn::Result<u32> {
|
||||
if !input.peek(Token![@]) {
|
||||
return Err(input.error("Give the version, like `@1`"));
|
||||
}
|
||||
input.parse::<Token![@]>()?;
|
||||
|
||||
let literal: LitInt = input.parse()?;
|
||||
if !literal.suffix().is_empty() {
|
||||
return Err(Error::new(literal.span(), "Write the version without a type suffix"));
|
||||
}
|
||||
let version: u32 = literal.base10_parse()?;
|
||||
if version == 0 {
|
||||
return Err(Error::new(literal.span(), "Versions start at 1"));
|
||||
}
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
/// Reads any number of `#[...]` groups, each holding comma-separated attribute items.
|
||||
fn parse_attributes(input: ParseStream) -> syn::Result<Vec<Attribute>> {
|
||||
let mut attributes = Vec::new();
|
||||
|
||||
while input.peek(Token![#]) && !input.peek2(Token![!]) {
|
||||
input.parse::<Token![#]>()?;
|
||||
let content;
|
||||
bracketed!(content in input);
|
||||
|
||||
while !content.is_empty() {
|
||||
let name = content.call(Ident::parse_any)?;
|
||||
let arguments = if content.peek(syn::token::Paren) {
|
||||
let arguments;
|
||||
parenthesized!(arguments in content);
|
||||
AttributeArguments::List(arguments.parse()?)
|
||||
} else if content.peek(Token![=]) {
|
||||
content.parse::<Token![=]>()?;
|
||||
AttributeArguments::Value(content.parse()?)
|
||||
} else {
|
||||
AttributeArguments::None
|
||||
};
|
||||
attributes.push(Attribute { name, arguments });
|
||||
|
||||
if content.is_empty() {
|
||||
break;
|
||||
}
|
||||
content.parse::<Token![,]>()?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(attributes)
|
||||
}
|
||||
|
||||
/// The `///` lines among the attributes, each trimmed and joined by line breaks.
|
||||
pub fn doc_comment(attributes: &[Attribute]) -> String {
|
||||
attributes
|
||||
.iter()
|
||||
.filter(|attribute| attribute.name == "doc")
|
||||
.filter_map(|attribute| match &attribute.arguments {
|
||||
AttributeArguments::Value(Lit::Str(text)) => Some(text.value().trim().to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
impl Parse for GraphItem {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
input.parse::<Token![fn]>()?;
|
||||
let name: Ident = input.parse()?;
|
||||
let version = parse_version(input)?;
|
||||
|
||||
let parameters;
|
||||
parenthesized!(parameters in input);
|
||||
let imports = Punctuated::<Import, Token![,]>::parse_terminated(¶meters)?.into_iter().collect();
|
||||
|
||||
input.parse::<Token![->]>()?;
|
||||
let exports: Vec<Export> = if input.peek(syn::token::Paren) {
|
||||
let content;
|
||||
parenthesized!(content in input);
|
||||
Punctuated::<Export, Token![,]>::parse_terminated(&content)?.into_iter().collect()
|
||||
} else {
|
||||
vec![input.parse()?]
|
||||
};
|
||||
if exports.is_empty() {
|
||||
return Err(Error::new(name.span(), "Name at least one export, like `-> (out)`"));
|
||||
}
|
||||
|
||||
let body;
|
||||
braced!(body in input);
|
||||
let mut bindings = Vec::new();
|
||||
while body.peek(Token![let]) {
|
||||
bindings.push(body.parse()?);
|
||||
}
|
||||
|
||||
if body.is_empty() {
|
||||
return Err(Error::new(name.span(), "A graph ends its body with one value per export"));
|
||||
}
|
||||
let result = parse_expression(&body)?;
|
||||
if body.peek(Token![;]) {
|
||||
return Err(body.error("The graph ends with its exports, written without a semicolon"));
|
||||
}
|
||||
if !body.is_empty() {
|
||||
return Err(body.error("Each statement in a graph is a `let` binding, followed by the exports it ends with"));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
attributes,
|
||||
name,
|
||||
version,
|
||||
imports,
|
||||
exports,
|
||||
bindings,
|
||||
result,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Import {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
let name = if input.peek(Token![_]) {
|
||||
input.parse::<Token![_]>()?;
|
||||
None
|
||||
} else {
|
||||
Some(input.parse()?)
|
||||
};
|
||||
if input.peek(Token![:]) {
|
||||
return Err(input.error("Imports take no type, since it's inferred from the inputs they feed"));
|
||||
}
|
||||
|
||||
Ok(Self { attributes, name })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Export {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
let name = input.call(Ident::parse_any)?;
|
||||
Ok(Self { attributes, name })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Binding {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
input.parse::<Token![let]>()?;
|
||||
let name = input.parse()?;
|
||||
input.parse::<Token![=]>()?;
|
||||
let value = parse_expression(input)?;
|
||||
input.parse::<Token![;]>()?;
|
||||
Ok(Self { name, value })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Expression {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
parse_expression(input)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a chain of `>>`, which binds loosest and groups from the left.
|
||||
fn parse_expression(input: ParseStream) -> syn::Result<Expression> {
|
||||
let mut expression = parse_postfix(input)?;
|
||||
|
||||
while input.peek(Token![>>]) {
|
||||
let token: Token![>>] = input.parse()?;
|
||||
let downstream = parse_postfix(input)?;
|
||||
expression = Expression::Feed {
|
||||
upstream: Box::new(expression),
|
||||
downstream: Box::new(downstream),
|
||||
span: token.span(),
|
||||
};
|
||||
}
|
||||
|
||||
Ok(expression)
|
||||
}
|
||||
|
||||
/// Reads a primary expression followed by node state methods and output choices.
|
||||
fn parse_postfix(input: ParseStream) -> syn::Result<Expression> {
|
||||
let mut expression = parse_primary(input)?;
|
||||
|
||||
while input.peek(Token![.]) && !input.peek(Token![..]) {
|
||||
input.parse::<Token![.]>()?;
|
||||
let name = input.call(Ident::parse_any)?;
|
||||
|
||||
if !input.peek(syn::token::Paren) {
|
||||
if matches!(expression, Expression::Output { .. }) {
|
||||
return Err(Error::new(name.span(), "An output is already chosen here"));
|
||||
}
|
||||
expression = Expression::Output {
|
||||
node: Box::new(expression),
|
||||
output: name,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
let arguments;
|
||||
parenthesized!(arguments in input);
|
||||
let call = match &mut expression {
|
||||
Expression::Call(call) => call,
|
||||
Expression::Output { .. } => {
|
||||
return Err(Error::new(name.span(), "Node state goes before the output it chooses, like `regex_find().at(0, 0).captures`"));
|
||||
}
|
||||
_ => return Err(Error::new(name.span(), "Node state goes directly after the call it modifies, not on a binding")),
|
||||
};
|
||||
|
||||
let state = parse_state(&name, &arguments)?;
|
||||
if call.states.iter().any(|existing| std::mem::discriminant(&existing.kind) == std::mem::discriminant(&state.kind)) {
|
||||
return Err(Error::new(name.span(), format!("`.{name}()` is already set on this node")));
|
||||
}
|
||||
call.states.push(state);
|
||||
}
|
||||
|
||||
Ok(expression)
|
||||
}
|
||||
|
||||
fn parse_state(name: &Ident, arguments: ParseStream) -> syn::Result<State> {
|
||||
let method = name.to_string();
|
||||
let no_arguments = || match arguments.is_empty() {
|
||||
true => Ok(()),
|
||||
false => Err(arguments.error(format!("`.{method}()` takes no arguments"))),
|
||||
};
|
||||
let coordinates = || -> syn::Result<(i32, i32)> {
|
||||
let x = parse_grid_coordinate(arguments)?;
|
||||
arguments.parse::<Token![,]>()?;
|
||||
let y = parse_grid_coordinate(arguments)?;
|
||||
if !arguments.is_empty() {
|
||||
return Err(arguments.error("Give two coordinates in grid units"));
|
||||
}
|
||||
Ok((x, y))
|
||||
};
|
||||
|
||||
let kind = match method.as_str() {
|
||||
"at" => {
|
||||
let (x, y) = coordinates()?;
|
||||
StateKind::At(x, y)
|
||||
}
|
||||
"offset" => {
|
||||
let (x, y) = coordinates()?;
|
||||
StateKind::Offset(x, y)
|
||||
}
|
||||
"named" => {
|
||||
let display_name: LitStr = arguments.parse()?;
|
||||
StateKind::Named(display_name.value())
|
||||
}
|
||||
"hidden" => no_arguments().map(|_| StateKind::Hidden)?,
|
||||
"locked" => no_arguments().map(|_| StateKind::Locked)?,
|
||||
"pinned" => no_arguments().map(|_| StateKind::Pinned)?,
|
||||
"layer" => no_arguments().map(|_| StateKind::Layer)?,
|
||||
_ => {
|
||||
return Err(Error::new(
|
||||
name.span(),
|
||||
format!("Unknown node state `.{method}()`. Parameters go inside the call's parentheses, like `node({method} = ...)`"),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(State { kind, span: name.span() })
|
||||
}
|
||||
|
||||
fn parse_grid_coordinate(input: ParseStream) -> syn::Result<i32> {
|
||||
let negative = input.peek(Token![-]);
|
||||
if negative {
|
||||
input.parse::<Token![-]>()?;
|
||||
}
|
||||
|
||||
let literal: LitInt = input.parse().map_err(|error| Error::new(error.span(), "Positions are integers in grid units"))?;
|
||||
if !literal.suffix().is_empty() {
|
||||
return Err(Error::new(literal.span(), "Write the position without a type suffix"));
|
||||
}
|
||||
let magnitude: i32 = literal.base10_parse()?;
|
||||
Ok(if negative { -magnitude } else { magnitude })
|
||||
}
|
||||
|
||||
fn parse_primary(input: ParseStream) -> syn::Result<Expression> {
|
||||
let span = input.span();
|
||||
|
||||
if input.peek(syn::token::Paren) {
|
||||
let content;
|
||||
parenthesized!(content in input);
|
||||
let elements = Punctuated::<Expression, Token![,]>::parse_terminated(&content)?;
|
||||
if elements.is_empty() {
|
||||
return Err(Error::new(span, "Empty parentheses aren't part of the graph syntax"));
|
||||
}
|
||||
if elements.len() == 1 && !elements.trailing_punct() {
|
||||
return Ok(elements.into_iter().next().expect("there is one element"));
|
||||
}
|
||||
return Ok(Expression::Tuple {
|
||||
elements: elements.into_iter().collect(),
|
||||
span,
|
||||
});
|
||||
}
|
||||
|
||||
if input.peek(syn::token::Bracket) {
|
||||
let content;
|
||||
bracketed!(content in input);
|
||||
let numbers = Punctuated::<Value, Token![,]>::parse_terminated(&content)?;
|
||||
let components: Vec<f64> = numbers
|
||||
.iter()
|
||||
.filter_map(|number| match number.kind {
|
||||
ValueKind::Number(number) => Some(number),
|
||||
ValueKind::Integer(integer) => Some(integer as f64),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let [x, y] = components.as_slice() else {
|
||||
return Err(Error::new(span, "A value array is a two-number Vec2, like `[1., 2.]`"));
|
||||
};
|
||||
return Ok(Expression::Value(Value { kind: ValueKind::Vec2(*x, *y), span }));
|
||||
}
|
||||
|
||||
if input.peek(Lit) || input.peek(Token![-]) {
|
||||
return input.parse().map(Expression::Value);
|
||||
}
|
||||
|
||||
if input.peek(Ident) {
|
||||
let name: Ident = input.parse()?;
|
||||
if !input.peek(syn::token::Paren) {
|
||||
return Ok(Expression::Name(name));
|
||||
}
|
||||
|
||||
let content;
|
||||
parenthesized!(content in input);
|
||||
let arguments = Punctuated::<Argument, Token![,]>::parse_terminated(&content)?.into_iter().collect();
|
||||
return Ok(Expression::Call(Call { name, arguments, states: Vec::new() }));
|
||||
}
|
||||
|
||||
Err(input.error("This isn't part of the graph syntax"))
|
||||
}
|
||||
|
||||
impl Parse for Value {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let span = input.span();
|
||||
let negative = input.peek(Token![-]);
|
||||
if negative {
|
||||
input.parse::<Token![-]>()?;
|
||||
}
|
||||
|
||||
let literal: Lit = input.parse()?;
|
||||
let kind = match &literal {
|
||||
Lit::Int(integer) => {
|
||||
if !integer.suffix().is_empty() {
|
||||
return Err(Error::new(integer.span(), "Write the integer without a type suffix. Its type is `i64`"));
|
||||
}
|
||||
let value: i64 = integer.base10_parse()?;
|
||||
ValueKind::Integer(if negative { -value } else { value })
|
||||
}
|
||||
Lit::Float(float) => {
|
||||
if !float.suffix().is_empty() {
|
||||
return Err(Error::new(float.span(), "Write the number without a type suffix. Its type is `f64`"));
|
||||
}
|
||||
let value: f64 = float.base10_parse()?;
|
||||
ValueKind::Number(if negative { -value } else { value })
|
||||
}
|
||||
Lit::Bool(boolean) if !negative => ValueKind::Bool(boolean.value),
|
||||
Lit::Str(string) if !negative => ValueKind::String(string.value()),
|
||||
_ if negative => return Err(Error::new(literal.span(), "Only a number can be negated")),
|
||||
_ => return Err(Error::new(literal.span(), "Unsupported literal")),
|
||||
};
|
||||
|
||||
Ok(Self { kind, span })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Argument {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
|
||||
let parameter = if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) {
|
||||
let parameter = input.parse()?;
|
||||
input.parse::<Token![=]>()?;
|
||||
Some(parameter)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let value = parse_expression(input)?;
|
||||
|
||||
Ok(Self { attributes, parameter, value })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(text: &str) -> syn::Result<Source> {
|
||||
syn::parse_str(text)
|
||||
}
|
||||
|
||||
fn error_message(text: &str) -> String {
|
||||
match parse(text) {
|
||||
Ok(_) => panic!("the graph text should be rejected"),
|
||||
Err(error) => error.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_header_uses_and_graph() {
|
||||
let source = parse(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use graphic_nodes::graphic::{as_graphic@1, extend@2 as append};
|
||||
use graphic_nodes::graphic::into_group@1;
|
||||
|
||||
/// Merges content.
|
||||
#[category("Graphic"), layer]
|
||||
fn merge@3(base, #[expose] content) -> (out) {
|
||||
let grouped = content >> into_group();
|
||||
base >> as_graphic() >> append(new = grouped)
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.expect("the graph text should parse");
|
||||
|
||||
let uses: Vec<String> = source.uses.iter().map(|entry| format!("{}::{}@{}", entry.module_path(), entry.local_name(), entry.version)).collect();
|
||||
assert_eq!(
|
||||
uses,
|
||||
["graphic_nodes::graphic::as_graphic@1", "graphic_nodes::graphic::append@2", "graphic_nodes::graphic::into_group@1"]
|
||||
);
|
||||
|
||||
let graph = &source.graph;
|
||||
assert_eq!(graph.name, "merge");
|
||||
assert_eq!(graph.version, 3);
|
||||
assert_eq!(doc_comment(&graph.attributes), "Merges content.");
|
||||
assert_eq!(graph.imports.len(), 2);
|
||||
assert_eq!(graph.bindings.len(), 1);
|
||||
assert!(matches!(graph.result, Expression::Feed { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_state_values_and_outputs() {
|
||||
let source = parse(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use a::b::{f@1, g@1};
|
||||
fn state@1(_, x) -> (match, other) {
|
||||
let node = f(#[exposed] flag = false, offset = -2.5, size = [1, -2.], count = 3, label = "text", x).named("N").offset(0, -2).hidden();
|
||||
(node.match, node >> g())
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.expect("the graph text should parse");
|
||||
|
||||
let graph = &source.graph;
|
||||
assert!(graph.imports[0].name.is_none());
|
||||
assert_eq!(graph.exports[0].name, "match");
|
||||
|
||||
let Expression::Call(call) = &graph.bindings[0].value else {
|
||||
panic!("the binding should be a call")
|
||||
};
|
||||
let kinds: Vec<StateKind> = call.states.iter().map(|state| state.kind.clone()).collect();
|
||||
assert!(kinds == [StateKind::Named("N".into()), StateKind::Offset(0, -2), StateKind::Hidden]);
|
||||
assert!(matches!(call.arguments[1].value, Expression::Value(Value { kind: ValueKind::Number(-2.5), .. })));
|
||||
assert!(matches!(call.arguments[2].value, Expression::Value(Value { kind: ValueKind::Vec2(1., -2.), .. })));
|
||||
assert!(matches!(call.arguments[3].value, Expression::Value(Value { kind: ValueKind::Integer(3), .. })));
|
||||
assert!(call.arguments[5].parameter.is_none());
|
||||
|
||||
let Expression::Tuple { elements, .. } = &graph.result else {
|
||||
panic!("the result should be a tuple")
|
||||
};
|
||||
assert!(matches!(&elements[0], Expression::Output { output, .. } if output == "match"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_text_without_a_supported_header() {
|
||||
assert!(error_message("fn a@1() -> (out) { b() }").contains("starts with its syntax version"));
|
||||
assert!(error_message("#![syntax(2)] fn a@1() -> (out) { b() }").contains("isn't supported"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unversioned_and_unqualified_names() {
|
||||
assert!(error_message("#![syntax(1)] use a::b; fn a@1() -> (out) { b() }").contains("Give the version"));
|
||||
assert!(error_message("#![syntax(1)] use b@1; fn a@1() -> (out) { b() }").contains("full path"));
|
||||
assert!(error_message("#![syntax(1)] fn a() -> (out) { b() }").contains("Give the version"));
|
||||
assert!(error_message("#![syntax(1)] fn a@0() -> (out) { b() }").contains("start at 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_typed_imports_and_suffixed_literals() {
|
||||
assert!(error_message("#![syntax(1)] fn a@1(x: Item<f64>) -> (out) { b(x) }").contains("take no type"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1_u32) }").contains("without a type suffix"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1.5_f32) }").contains("without a type suffix"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_misplaced_state() {
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { let n = b(); n.hidden() }").contains("not on a binding"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().out.hidden() }").contains("before the output"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().hidden().hidden() }").contains("already set"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().weight(2) }").contains("Unknown node state"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().at(1.5, 2) }").contains("integers in grid units"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_semicolon_after_the_exports() {
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(); }").contains("without a semicolon"));
|
||||
}
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
use super::*;
|
||||
use crate::resolve::blank_field;
|
||||
use core_types::registry::{FieldMetadata, GraphInputSource, GraphNodeImplementation, GraphValue, NodeFlags, RegistryValueSource};
|
||||
use core_types::{Type, concrete};
|
||||
|
||||
fn parameter(identifier: &'static str, default_type: Type) -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: identifier,
|
||||
identifier,
|
||||
description: "From the node.",
|
||||
default_type: Some(default_type),
|
||||
..blank_field()
|
||||
}
|
||||
}
|
||||
|
||||
fn proto_node(fields: Vec<FieldMetadata>) -> NodeMetadata {
|
||||
NodeMetadata {
|
||||
display_name: "",
|
||||
category: "",
|
||||
icon: None,
|
||||
fields,
|
||||
description: "",
|
||||
inspector: None,
|
||||
context_features: Vec::new(),
|
||||
flags: NodeFlags::default(),
|
||||
version: 1,
|
||||
output_fields: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `test_nodes::Group(content)`, `test_nodes::Extend(base, new)`, and `test_nodes::Scale(value, factor, label)`.
|
||||
fn proto_nodes() -> HashMap<ProtoNodeIdentifier, NodeMetadata> {
|
||||
let list = || Type::List(Box::new(concrete!(f64)));
|
||||
let number = || Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
let mut factor = parameter("factor", number());
|
||||
factor.unit = Some(" px");
|
||||
factor.value_source = RegistryValueSource::Default("2.");
|
||||
|
||||
HashMap::from([
|
||||
(ProtoNodeIdentifier::new("test_nodes::GroupNode"), proto_node(vec![parameter("content", list())])),
|
||||
(
|
||||
ProtoNodeIdentifier::new("test_nodes::ExtendNode"),
|
||||
proto_node(vec![parameter("base", list()), parameter("new", list())]),
|
||||
),
|
||||
(
|
||||
ProtoNodeIdentifier::new("test_nodes::ScaleNode"),
|
||||
proto_node(vec![parameter("value", number()), factor, parameter("label", Type::Item(Box::new(concrete!(String))))]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn source(text: &'static str) -> GraphSource {
|
||||
GraphSource {
|
||||
module_path: "test_graphs",
|
||||
file: "test_graphs.rs",
|
||||
line: 1,
|
||||
column: 1,
|
||||
text,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_texts(texts: &[&'static str]) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
|
||||
let sources: Vec<GraphSource> = texts.iter().map(|text| source(text)).collect();
|
||||
resolve_sources(&sources, &proto_nodes())
|
||||
}
|
||||
|
||||
fn resolve_one(text: &'static str) -> GraphMetadata {
|
||||
let (mut graphs, errors) = resolve_texts(&[text]);
|
||||
assert!(errors.is_empty(), "the graph should resolve: {}", errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n"));
|
||||
graphs.remove(0)
|
||||
}
|
||||
|
||||
fn error_message(text: &'static str) -> String {
|
||||
let (graphs, errors) = resolve_texts(&[text]);
|
||||
assert!(graphs.is_empty(), "the graph should be rejected");
|
||||
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
const MERGE: &str = r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::{extend@1, group@1};
|
||||
|
||||
/// Merges content.
|
||||
#[category("Test"), layer]
|
||||
fn merge@1(
|
||||
/// The stack below.
|
||||
base,
|
||||
#[expose]
|
||||
content,
|
||||
) -> (out) {
|
||||
base >> extend(new = content >> group())
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn resolves_nodes_wires_and_layout() {
|
||||
let graph = resolve_one(MERGE);
|
||||
|
||||
assert_eq!(graph.identifier, "Merge");
|
||||
assert_eq!(graph.path, "test_graphs::merge");
|
||||
assert_eq!(graph.description, "Merges content.");
|
||||
assert!(graph.layer);
|
||||
|
||||
let implementations: Vec<_> = graph.nodes.iter().map(|node| node.implementation.clone()).collect();
|
||||
assert_eq!(
|
||||
implementations,
|
||||
[
|
||||
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::GroupNode")),
|
||||
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::ExtendNode")),
|
||||
]
|
||||
);
|
||||
assert!(matches!(
|
||||
graph.nodes[1].inputs.as_slice(),
|
||||
[(1, GraphInputSource::Node { node: 0, output: 0 }), (0, GraphInputSource::Import { index: 0, .. })]
|
||||
));
|
||||
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 1, output: 0 }));
|
||||
|
||||
let positions: Vec<_> = graph.nodes.iter().map(|node| node.position).collect();
|
||||
assert_eq!(positions, [(-7, 1), (0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_inherit_from_the_input_they_feed_unless_overridden() {
|
||||
let graph = resolve_one(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::scale@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn scaled@1(value, factor, #[unit("%")] #[default(10)] other) -> (out) {
|
||||
let first = value >> scale(factor);
|
||||
first >> scale(factor = other)
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
let [value, factor, other] = graph.imports.as_slice() else {
|
||||
panic!("the graph should have three imports")
|
||||
};
|
||||
assert_eq!(value.name, "Value");
|
||||
assert_eq!(factor.unit, Some(" px"));
|
||||
assert_eq!(factor.description, "From the node.");
|
||||
assert!(matches!(factor.value_source, RegistryValueSource::Default("2.")));
|
||||
|
||||
assert_eq!(other.unit, Some("%"));
|
||||
assert!(matches!(other.value_source, RegistryValueSource::Default("10")));
|
||||
assert_eq!(other.default_type, Some(concrete!(i64)));
|
||||
assert!(matches!(&graph.nodes[1].inputs[0].1, GraphInputSource::Import { index: 2, ty } if *ty == Type::Item(Box::new(concrete!(i64)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_inherits_from_the_parameter_of_its_own_name_first() {
|
||||
let graph = resolve_one(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::scale@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn scaled@1(value, label) -> (out) {
|
||||
let first = value >> scale(factor = 1., label = value);
|
||||
first >> scale(label)
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
assert_eq!(graph.imports[0].default_type, Some(Type::Item(Box::new(concrete!(f64)))));
|
||||
assert_eq!(graph.imports[1].default_type, Some(Type::Item(Box::new(concrete!(String)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_keep_the_type_they_are_written_with() {
|
||||
let graph = resolve_one(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::scale@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn values@1(value) -> (out) {
|
||||
value >> scale(factor = 2, #[exposed] label = "text")
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
let inputs = &graph.nodes[0].inputs;
|
||||
assert!(matches!(
|
||||
&inputs[0].1,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Integer(2),
|
||||
exposed: None
|
||||
}
|
||||
));
|
||||
assert!(matches!(&inputs[1].1, GraphInputSource::Value { value: GraphValue::String(text), exposed: Some(true) } if text == "text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_after_a_graph_it_uses_and_chooses_its_outputs_by_name() {
|
||||
let outer = r#"
|
||||
#![syntax(1)]
|
||||
use test_graphs::pair@1;
|
||||
use test_nodes::group@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn outer@1(content) -> (out) {
|
||||
content >> pair().second >> group()
|
||||
}
|
||||
"#;
|
||||
let pair = r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn pair@1(content) -> (first, second) {
|
||||
let grouped = content >> group();
|
||||
(grouped, grouped >> group())
|
||||
}
|
||||
"#;
|
||||
|
||||
let (graphs, errors) = resolve_texts(&[outer, pair]);
|
||||
assert!(errors.is_empty(), "both graphs should resolve");
|
||||
|
||||
let outer = graphs.iter().find(|graph| graph.identifier == "Outer").expect("the outer graph should resolve");
|
||||
assert_eq!(outer.nodes[0].implementation, GraphNodeImplementation::Graph("Pair"));
|
||||
assert!(matches!(outer.nodes[1].inputs[0].1, GraphInputSource::Node { node: 0, output: 1 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_names_that_dont_resolve() {
|
||||
let unknown_parameter = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group(weight = 2) }
|
||||
"#,
|
||||
);
|
||||
assert!(unknown_parameter.contains("`group` has no parameter named `weight`"), "{unknown_parameter}");
|
||||
|
||||
let unknown_node = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::missing@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> missing() }
|
||||
"#,
|
||||
);
|
||||
assert!(unknown_node.contains("No node or graph is named `test_nodes::missing`"), "{unknown_node}");
|
||||
|
||||
let not_used = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group() }
|
||||
"#,
|
||||
);
|
||||
assert!(not_used.contains("`group` isn't used"), "{not_used}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_versions_and_unused_entries() {
|
||||
let wrong_version = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@2;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group() }
|
||||
"#,
|
||||
);
|
||||
assert!(wrong_version.contains("is at version 1, not 2"), "{wrong_version}");
|
||||
|
||||
let unused = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::{extend@1, group@1};
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group() }
|
||||
"#,
|
||||
);
|
||||
assert!(unused.contains("`extend` is used but never called"), "{unused}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wiring_mistakes() {
|
||||
let primary_twice = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group(content) }
|
||||
"#,
|
||||
);
|
||||
assert!(primary_twice.contains("is already fed"), "{primary_twice}");
|
||||
|
||||
let looped = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) {
|
||||
let node = group();
|
||||
node >> node
|
||||
}
|
||||
"#,
|
||||
);
|
||||
assert!(looped.contains("makes a loop"), "{looped}");
|
||||
|
||||
let export_from_import = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content }
|
||||
"#,
|
||||
);
|
||||
assert!(export_from_import.contains("straight from an import"), "{export_from_import}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_name_where_the_graph_is_written() {
|
||||
let (_, errors) = resolve_texts(&["#![syntax(1)] #[category(\"Test\")] fn bad@1(content) -> (out) { content >> missing() }"]);
|
||||
let error = errors.first().expect("the graph should be rejected");
|
||||
|
||||
assert_eq!((error.file, error.line, error.column), ("test_graphs.rs", 1, 1));
|
||||
assert!(error.excerpt.starts_with("missing()"), "{}", error.excerpt);
|
||||
}
|
||||
@@ -232,6 +232,17 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: CacheHash, V: CacheHash> CacheHash for std::collections::BTreeMap<K, V> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(&self.len(), state);
|
||||
for (key, value) in self {
|
||||
key.cache_hash(state);
|
||||
value.cache_hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
|
||||
@@ -82,6 +82,7 @@ pub enum Adjustment {
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -107,6 +108,7 @@ impl Adjustment {
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +125,7 @@ impl Adjustment {
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
| Self::Solarize
|
||||
)
|
||||
}
|
||||
|
||||
@@ -134,7 +137,7 @@ impl Adjustment {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::MakeOpaque | Self::Invert | Self::Solarize => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::adjustment::Adjustment;
|
||||
use crate::effects::{BevelStyle, EffectCapture, EffectOperation, Effects, GlowFill, OutlineFill, outline_extents};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Which side of the content a piece of an effect draws on, and how.
|
||||
@@ -99,9 +100,7 @@ impl EffectLayers {
|
||||
let has_beneath = |pieces: &[(EffectPiece, BlendMode)]| pieces.iter().any(|(piece, _)| piece.place == PiecePlace::Beneath);
|
||||
|
||||
// Flattened shadows and glows that no later pixel filter merges into the content would draw over the layered ones, so then everything is flattened
|
||||
let last_pixel_filter = (operations[..flattened].iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||
.map_or(0, |index| index + 1);
|
||||
let last_pixel_filter = merged_into_content(&operations[..flattened]);
|
||||
let unmerged = pieces_from(last_pixel_filter, flattened);
|
||||
let mut pieces = pieces_from(flattened, operations.len());
|
||||
if has_beneath(&unmerged) && has_beneath(&pieces) {
|
||||
@@ -277,18 +276,39 @@ fn is_straight_along_backdrop(blend_mode: BlendMode) -> bool {
|
||||
matches!(blend_mode, BlendMode::Normal | BlendMode::Multiply | BlendMode::Screen | BlendMode::Exclusion | BlendMode::HardLight)
|
||||
}
|
||||
|
||||
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, or a feather does.
|
||||
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, a feather, or another filter does.
|
||||
/// A solid paint overlay decodes into the color overlay adjustment, but it paints within the content like any other paint overlay.
|
||||
pub fn is_pixel_filter(operation: &EffectOperation) -> bool {
|
||||
match operation {
|
||||
// TODO: Make a mask between other effects fade each layer drawn before it too, as the trailing masks do, rather than flattening those layers.
|
||||
// TODO: Likewise for a trailing feather, faded by the footprint of every layer drawn together (not the content's alone, which would erase shadows past it).
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
||||
EffectOperation::Blur { .. } | EffectOperation::MotionBlur { .. } | EffectOperation::RadialBlur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
||||
operation if crate::filters::is_filter(operation) => true,
|
||||
EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of the `operations`, from the first, run through the last pixel filter among them, which merges the pieces before it into the content's image.
|
||||
fn merged_into_content(operations: &[EffectOperation]) -> usize {
|
||||
(operations.iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||
.map_or(0, |index| index + 1)
|
||||
}
|
||||
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it.
|
||||
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
|
||||
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let trailing_masks = trailing_masks(&operations);
|
||||
let merged = merged_into_content(&operations[..trailing_masks.start]);
|
||||
if merged == trailing_masks.start {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
|
||||
Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
}
|
||||
|
||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
@@ -359,7 +379,20 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } | EffectOperation::Adjustment(_) => Vec::new(),
|
||||
EffectOperation::Blur { .. }
|
||||
| EffectOperation::MotionBlur { .. }
|
||||
| EffectOperation::RadialBlur { .. }
|
||||
| EffectOperation::Mask { .. }
|
||||
| EffectOperation::Feather { .. }
|
||||
| EffectOperation::ConvolutionKernel { .. }
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
}
|
||||
@@ -564,6 +597,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rows_that_change_nothing_neither_flatten_nor_split_the_others() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -605,6 +639,7 @@ mod tests {
|
||||
#[test]
|
||||
fn trailing_masks_fade_each_layer_in_its_own_blend_mode() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -642,6 +677,7 @@ mod tests {
|
||||
#[test]
|
||||
fn effects_before_a_blur_or_a_mode_css_lacks_are_flattened() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -668,6 +704,29 @@ mod tests {
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_images_keep_the_filters_and_what_they_merge_but_not_the_pieces_around_them() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let shadow = || drop_shadow(RED, BlendMode::Multiply);
|
||||
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// A shadow is cast from the content, unless a later filter merges it into the content's image
|
||||
assert!(kinds(vec![shadow()]).is_empty());
|
||||
assert_eq!(kinds(vec![blur.clone(), shadow()]), [EffectKind::Blur]);
|
||||
let merged = Effects::from_operations([shadow(), blur.clone()]);
|
||||
assert!(matches!(content_image_effects(&merged), Cow::Borrowed(_)));
|
||||
|
||||
// Trailing masks fade the content's image as they fade each layer
|
||||
assert_eq!(kinds(vec![shadow(), mask()]), [EffectKind::Mask]);
|
||||
let filtered = vec![mask(), inner_shadow(RED, BlendMode::Screen), blur, shadow(), mask()];
|
||||
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::filters::{Convolution, NoiseDistribution};
|
||||
use crate::masks::{MaskMode, mask_feather_sigma};
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
use crate::resampling::RadialBlurMethod;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
@@ -25,7 +27,7 @@ use vector_types::{Gradient, GradientSettings};
|
||||
/// The image operation an [`Effect`] carries out.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
|
||||
pub enum EffectKind {
|
||||
/// Softens the content by blurring it.
|
||||
/// Softens the content by blurring it, evenly or more where its radius mask is brighter.
|
||||
#[default]
|
||||
Blur,
|
||||
/// Casts the content's silhouette as a soft shadow beneath it.
|
||||
@@ -48,6 +50,26 @@ pub enum EffectKind {
|
||||
Mask,
|
||||
/// Fades the content out toward its edges, reaching nothing at them.
|
||||
Feather,
|
||||
/// Sums each pixel's neighbors weighted by a kernel of numbers.
|
||||
ConvolutionKernel,
|
||||
/// Grays the content, showing its edges in relief as if lit from one side.
|
||||
Emboss,
|
||||
/// Outlines the content's edges in dark over white.
|
||||
FindEdges,
|
||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||
MinimumMaximum,
|
||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||
Sharpen,
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
HighPass,
|
||||
/// Scatters random offsets across the colors, fixed in place on the content.
|
||||
AddNoise,
|
||||
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
|
||||
Dissolve,
|
||||
/// Smears the content along a line, as if it moved while being captured.
|
||||
MotionBlur,
|
||||
/// Smears the content around a center or toward it.
|
||||
RadialBlur,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
@@ -68,6 +90,7 @@ pub enum EffectKind {
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -84,6 +107,16 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Mask => "Mask",
|
||||
Self::Feather => "Feather",
|
||||
Self::ConvolutionKernel => "Convolution Kernel",
|
||||
Self::Emboss => "Emboss",
|
||||
Self::FindEdges => "Find Edges",
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::AddNoise => "Add Noise",
|
||||
Self::Dissolve => "Dissolve",
|
||||
Self::MotionBlur => "Motion Blur",
|
||||
Self::RadialBlur => "Radial Blur",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
@@ -103,6 +136,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -133,6 +167,19 @@ pub enum GlowSource {
|
||||
Center,
|
||||
}
|
||||
|
||||
/// Which extreme of the colors around each pixel a Minimum/Maximum spreads.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum MinimumMaximumMode {
|
||||
/// Spreads the darkest colors, growing the content's coverage by the radius.
|
||||
#[default]
|
||||
Minimum,
|
||||
/// Spreads the lightest colors, shrinking the content's coverage by the radius.
|
||||
Maximum,
|
||||
}
|
||||
|
||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EffectCapture {
|
||||
@@ -287,37 +334,9 @@ pub fn texture_gray([red, green, blue, _]: [f32; 4]) -> f32 {
|
||||
0.299 * red + 0.587 * green + 0.114 * blue
|
||||
}
|
||||
|
||||
/// Whether a paint is a gradient or image without its own placement, which stretches across the content it paints.
|
||||
pub fn is_unplaced_paint(paint: &Graphic) -> bool {
|
||||
match paint {
|
||||
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// An effect's drawn paint with its unit square fitted to `content_bounds`, the extent it fills in the space it's drawn in, if it's a gradient or image without its own placement.
|
||||
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
|
||||
if !is_unplaced_paint(paint) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
|
||||
let mut paint = paint.clone();
|
||||
match &mut paint {
|
||||
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
_ => {}
|
||||
}
|
||||
Some(paint)
|
||||
}
|
||||
|
||||
/// The `graphic` expressed in the own space of content placed by `placement`, for an effect with a drawn graphic that follows the content (see [`EffectOperation::drawn_paint_follows_content`]).
|
||||
/// A gradient or image without its own placement stays as it is, since it stretches across the content wherever that lies.
|
||||
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
||||
if is_unplaced_paint(&graphic) || placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||
return graphic;
|
||||
}
|
||||
Graphic::Graphic(Box::new(Item::new_from_element(graphic).with_attribute(ATTR_TRANSFORM, placement.inverse())))
|
||||
@@ -403,6 +422,7 @@ impl Effects {
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in the effect space of a run of them.
|
||||
/// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.painted_reach()).sum()
|
||||
}
|
||||
@@ -412,6 +432,11 @@ impl Effects {
|
||||
self.operations().map(|operation| operation.working_reach()).sum()
|
||||
}
|
||||
|
||||
/// How far past the content a render of the effects must reach to draw them right (see [`EffectOperation::required_reach`]), in the effect space of a run of them.
|
||||
pub fn required_reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.required_reach()).sum()
|
||||
}
|
||||
|
||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||
@@ -438,31 +463,38 @@ impl Effects {
|
||||
runs
|
||||
}
|
||||
|
||||
/// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry, and the graphics that follow the content with them.
|
||||
/// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry, and the graphics and radial blur centers that follow the content with them.
|
||||
pub fn rebase_stamped_transforms(&mut self, baked: DAffine2) {
|
||||
if let Some(transforms) = self.0.iter_attribute_values_mut::<DAffine2>(ATTR_TRANSFORM) {
|
||||
transforms.for_each(|transform| *transform = rebased_stamped_transform(*transform, baked));
|
||||
}
|
||||
|
||||
// A mask's graphic lies in the content's own space, which `baked` now places within the geometry
|
||||
// A graphic following the content (see `EffectOperation::drawn_paint_follows_content`) lies in its own space, which `baked` now places within the geometry
|
||||
if baked == DAffine2::IDENTITY || !baked.matrix2.determinant().is_normal() {
|
||||
return;
|
||||
}
|
||||
for effect in self.0.iter_element_values_mut() {
|
||||
if effect.kind() == EffectKind::Mask
|
||||
&& let Some(mask) = effect.0.attribute_mut::<Graphic>("mask")
|
||||
&& !is_unplaced_paint(mask)
|
||||
{
|
||||
*mask = Graphic::Graphic(Box::new(Item::new_from_element(std::mem::take(mask)).with_attribute(ATTR_TRANSFORM, baked)));
|
||||
let key = match effect.kind() {
|
||||
EffectKind::Mask => "mask",
|
||||
EffectKind::Blur => "radius_mask",
|
||||
EffectKind::PaintOverlay | EffectKind::Outline => "paint",
|
||||
EffectKind::BevelAndEmboss => "texture",
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(graphic) = effect.0.attribute_mut::<Graphic>(key) {
|
||||
*graphic = Graphic::Graphic(Box::new(Item::new_from_element(std::mem::take(graphic)).with_attribute(ATTR_TRANSFORM, baked)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask and feather rows alone, with the transforms they were stamped at, or `None` without any. They shape what clips to the content as they shape the content itself, unlike the other effects.
|
||||
pub fn shaping_only(&self) -> Option<Effects> {
|
||||
let shapes = |index: &usize| self.0.element(*index).is_some_and(|effect| matches!(effect.kind(), EffectKind::Mask | EffectKind::Feather));
|
||||
let shaping: List<Effect> = (0..self.len()).filter(shapes).filter_map(|index| self.0.clone_item(index)).collect();
|
||||
(!shaping.is_empty()).then_some(Effects(shaping))
|
||||
// A radial blur's center is a position measured from the effect space's origin, which moves by the translation `baked` took from the content
|
||||
for index in 0..self.0.len() {
|
||||
let stamped_transform = self.0.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
|
||||
if let Some(effect) = self.0.element_mut(index)
|
||||
&& matches!(effect.kind(), EffectKind::RadialBlur)
|
||||
{
|
||||
*effect.0.attribute_mut_or_insert_default::<DVec2>("center") += stamped_transform.matrix2 * baked.translation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The effects of a run of rows, borrowed when the run is every row.
|
||||
@@ -473,6 +505,12 @@ impl Effects {
|
||||
}
|
||||
}
|
||||
|
||||
/// The effects with operations that `keep` accepts, in order, each still stamped where it was.
|
||||
pub fn keeping(&self, keep: impl Fn(&EffectOperation) -> bool) -> Self {
|
||||
let kept = self.effects().enumerate().filter(|(_, effect)| keep(&effect.operation())).map(|(index, _)| index);
|
||||
Effects(kept.filter_map(|index| self.0.clone_item(index)).collect())
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint along each axis of the space `content_transform` places the content in.
|
||||
pub fn reach_along_axes(&self, content_transform: DAffine2) -> DVec2 {
|
||||
self.reach_along_axes_by(content_transform, EffectOperation::painted_reach)
|
||||
@@ -494,7 +532,7 @@ impl Effects {
|
||||
|
||||
/// How far past the content the effects reading around each pixel (see [`EffectOperation::reads_pixels_around`]) together read, along the axis of the space `content_transform` places the content in that they read furthest along.
|
||||
pub fn read_reach(&self, content_transform: DAffine2) -> f64 {
|
||||
let reach = |operation: &EffectOperation| if operation.reads_pixels_around() { operation.painted_reach() } else { 0. };
|
||||
let reach = |operation: &EffectOperation| if operation.reads_pixels_around() { operation.working_reach() } else { 0. };
|
||||
self.reach_along_axes_by(content_transform, reach).max_element()
|
||||
}
|
||||
|
||||
@@ -726,8 +764,13 @@ pub fn rebased_stamped_transform(stamped_transform: DAffine2, baked: DAffine2) -
|
||||
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in its [`effect_space`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EffectOperation {
|
||||
/// Blurs the content after what lies beneath it joins it, evenly or as its radius mask varies the radius: by the interpolation between Gaussians [`crate::masks::masked_radius_blur_interpolation`] defines,
|
||||
/// or as a box blur, by a box at each pixel as wide as its fraction of the radius.
|
||||
Blur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
/// Lies in the content's own space, so it moves with the content, with its luminance setting each point's fraction of the radius.
|
||||
/// One that draws nothing, the default, blurs the whole content by the radius.
|
||||
radius_mask: Graphic,
|
||||
/// The standard deviation of the Gaussian, or the half width of the box, where the radius mask is white.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
@@ -797,7 +840,7 @@ pub enum EffectOperation {
|
||||
contour: TransferCurve,
|
||||
},
|
||||
Outline {
|
||||
/// A solid color with the outline's opacity, a gradient, or any graphic, fitted when unplaced to the content and the outline's margin.
|
||||
/// A solid color with the outline's opacity, a gradient, or any graphic, placed in the space the content's item is.
|
||||
paint: Graphic,
|
||||
/// How the outline mixes with what lies beneath it, or with the content for the part inside its edge.
|
||||
blend_mode: BlendMode,
|
||||
@@ -846,7 +889,7 @@ pub enum EffectOperation {
|
||||
},
|
||||
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
|
||||
PaintOverlay {
|
||||
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
|
||||
/// Placed in the space the content's item is.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
@@ -868,6 +911,76 @@ pub enum EffectOperation {
|
||||
/// How far in from the edges the fade reaches full strength.
|
||||
distance: f64,
|
||||
},
|
||||
ConvolutionKernel {
|
||||
/// The weights row by row, centered on each pixel as [`Convolution::custom`] places them.
|
||||
kernel: List<f64>,
|
||||
/// How many weights each row of the kernel holds.
|
||||
columns: u32,
|
||||
/// What the weighted sum is divided by.
|
||||
scale: f64,
|
||||
/// On a scale of 0 to 255.
|
||||
offset: f64,
|
||||
/// Whether the content's coverage is weighed by the kernel too, rather than kept.
|
||||
apply_to_alpha: bool,
|
||||
},
|
||||
Emboss {
|
||||
/// The direction the light comes from, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How far apart the two samples are, the difference between them showing as relief.
|
||||
height: f64,
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
},
|
||||
FindEdges,
|
||||
MinimumMaximum {
|
||||
/// How many pixels the square neighborhood reaches out from its center.
|
||||
radius: f64,
|
||||
mode: MinimumMaximumMode,
|
||||
},
|
||||
Sharpen {
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
/// The standard deviation of the Gaussian blur the content is compared against, which Edges Only ignores.
|
||||
radius: f64,
|
||||
/// On a scale of 0 to 255.
|
||||
threshold: f64,
|
||||
/// Whether the content is compared against its four nearest neighbors only along edges, as [`crate::filters::edge_gain`] ramps it, rather than against the blur.
|
||||
edges_only: bool,
|
||||
},
|
||||
HighPass {
|
||||
radius: f64,
|
||||
},
|
||||
AddNoise {
|
||||
/// Percent of full brightness.
|
||||
amount: f64,
|
||||
distribution: NoiseDistribution,
|
||||
/// Whether each pixel's colors all take the same offset, so only their brightness changes.
|
||||
monochromatic: bool,
|
||||
seed: i64,
|
||||
},
|
||||
Dissolve {
|
||||
/// Percent of the content that shows where it's fully opaque.
|
||||
opacity: f64,
|
||||
seed: i64,
|
||||
},
|
||||
MotionBlur {
|
||||
/// The direction of the line, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How long the line each point is smeared along is.
|
||||
distance: f64,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
RadialBlur {
|
||||
/// Whether the content spins around the center or zooms toward it.
|
||||
method: RadialBlurMethod,
|
||||
/// How far the blur smears, by the degrees of a spin or twice the percentage of the distance to the center of a zoom, up to 360.
|
||||
amount: f64,
|
||||
/// The point the blur spins around or zooms toward, measured from the effect space's origin (the content's).
|
||||
center: DVec2,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
@@ -877,6 +990,21 @@ impl EffectOperation {
|
||||
Effect(Item::new_from_element(kind)).operation()
|
||||
}
|
||||
|
||||
/// A convolution kernel of the weights `text` writes (see [`crate::filters::parse_kernel`]), its sums divided by `scale` and raised by `offset` levels out of 255, weighing the coverage too if `apply_to_alpha`.
|
||||
/// Without a `scale`, it divides by the [`crate::filters::automatic_scale`].
|
||||
pub fn convolution_kernel(text: &str, scale: Option<f64>, offset: f64, apply_to_alpha: bool) -> Self {
|
||||
let (weights, columns) = crate::filters::parse_kernel(text);
|
||||
let scale = scale.unwrap_or_else(|| crate::filters::automatic_scale(&weights, columns));
|
||||
|
||||
Self::ConvolutionKernel {
|
||||
kernel: List::new_from_elements(weights),
|
||||
columns: columns as u32,
|
||||
scale,
|
||||
offset,
|
||||
apply_to_alpha,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Blur { .. } => EffectKind::Blur,
|
||||
@@ -890,10 +1018,43 @@ impl EffectOperation {
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Mask { .. } => EffectKind::Mask,
|
||||
Self::Feather { .. } => EffectKind::Feather,
|
||||
Self::ConvolutionKernel { .. } => EffectKind::ConvolutionKernel,
|
||||
Self::Emboss { .. } => EffectKind::Emboss,
|
||||
Self::FindEdges => EffectKind::FindEdges,
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::AddNoise { .. } => EffectKind::AddNoise,
|
||||
Self::Dissolve { .. } => EffectKind::Dissolve,
|
||||
Self::MotionBlur { .. } => EffectKind::MotionBlur,
|
||||
Self::RadialBlur { .. } => EffectKind::RadialBlur,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The weighted sum of shifted copies of the content that a filter carries out, for the filters that are one.
|
||||
pub fn convolution(&self) -> Option<Convolution> {
|
||||
match self {
|
||||
// An empty kernel, like the identity, leaves the content as it is
|
||||
Self::ConvolutionKernel {
|
||||
kernel,
|
||||
columns,
|
||||
scale,
|
||||
offset,
|
||||
apply_to_alpha,
|
||||
} => {
|
||||
let weights: Vec<f64> = kernel.iter_element_values().copied().collect();
|
||||
let convolution = Convolution {
|
||||
weighs_coverage: *apply_to_alpha,
|
||||
..Convolution::custom(&weights, *columns as usize, *scale, *offset)
|
||||
};
|
||||
(!weights.is_empty() && !convolution.is_identity()).then_some(convolution)
|
||||
}
|
||||
Self::Emboss { angle, height, amount } => Some(Convolution::emboss(*angle, *height, *amount)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity.
|
||||
pub fn changes_nothing(&self) -> bool {
|
||||
match self {
|
||||
@@ -910,17 +1071,30 @@ impl EffectOperation {
|
||||
..
|
||||
} => (highlight_color.a() <= 0. && shadow_color.a() <= 0.) || (*size <= 0. && gloss_contour.is_identity()),
|
||||
Self::PaintOverlay { opacity, .. } => *opacity <= 0.,
|
||||
Self::MotionBlur { distance, .. } => *distance <= 0.,
|
||||
Self::RadialBlur { amount, .. } => *amount <= 0.,
|
||||
Self::Adjustment(Adjustment::ColorOverlay { color, opacity, .. }) => color.a() <= 0. || *opacity <= 0.,
|
||||
Self::Mask { density, .. } => *density <= 0.,
|
||||
Self::Feather { distance } => *distance <= 0.,
|
||||
Self::Adjustment(_) => false,
|
||||
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
|
||||
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::AddNoise { amount, .. } => *amount <= 0.,
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is a blur varying its radius by a radius mask that draws something, rather than blurring the whole content evenly.
|
||||
pub fn varies_blur_radius(&self) -> bool {
|
||||
matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing())
|
||||
}
|
||||
|
||||
/// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur, rather than casting from the content's shape or changing each pixel alone.
|
||||
pub fn reads_pixels_around(&self) -> bool {
|
||||
match self {
|
||||
Self::Blur { .. } => true,
|
||||
Self::Blur { .. } | Self::MotionBlur { .. } | Self::RadialBlur { .. } => true,
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
@@ -930,17 +1104,27 @@ impl EffectOperation {
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::Feather { .. } => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::Adjustment(_) => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, or a feather.
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||
pub fn painted_reach(&self) -> f64 {
|
||||
if self.changes_nothing() || matches!(self, Self::Mask { .. } | Self::Feather { .. }) {
|
||||
0.
|
||||
} else {
|
||||
self.reach()
|
||||
}
|
||||
let keeps_coverage = matches!(
|
||||
self,
|
||||
Self::Mask { .. }
|
||||
| Self::Feather { .. }
|
||||
| Self::ConvolutionKernel { apply_to_alpha: false, .. }
|
||||
| Self::Emboss { .. }
|
||||
| Self::FindEdges
|
||||
| Self::MinimumMaximum {
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
..
|
||||
}
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
);
|
||||
if self.changes_nothing() || keeps_coverage { 0. } else { self.reach() }
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints or reads from, which the region it's worked out over covers, and nowhere for an operation that changes nothing.
|
||||
@@ -948,10 +1132,16 @@ impl EffectOperation {
|
||||
if self.changes_nothing() { 0. } else { self.reach() }
|
||||
}
|
||||
|
||||
/// How far past the content a render must reach for this operation to come out right: as far as it paints, or for one reading around each pixel, as far as it reads.
|
||||
pub fn required_reach(&self) -> f64 {
|
||||
if self.reads_pixels_around() { self.working_reach() } else { self.painted_reach() }
|
||||
}
|
||||
|
||||
/// How far past the content this operation can paint, or reads from, in its effect space.
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// A Gaussian is negligible past three standard deviations
|
||||
// A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations
|
||||
Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
// An inner shadow paints within the content but reads this far out to find the edges it casts from.
|
||||
// Shadows and glows end within their size, past which a precise glow fades over one more unit.
|
||||
@@ -965,11 +1155,22 @@ impl EffectOperation {
|
||||
Self::Mask { feather, .. } => 3. * mask_feather_sigma(*feather),
|
||||
// A feather paints nothing past the content, but finds edges up to this far past it, which a render cut short there would miss
|
||||
Self::Feather { distance } => distance.max(0.) + 1.,
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } => self.convolution().map_or(0., |convolution| convolution.read_reach()),
|
||||
// The Sobel taps' diagonal, then a faint pixel's nearest visible color within the square of a pixel around that, plus two pixels for rounding and copies between pixels
|
||||
Self::Sharpen { edges_only: true, .. } => 2. * std::f64::consts::SQRT_2 + 2.,
|
||||
Self::Sharpen { radius, .. } | Self::HighPass { radius } => 3. * radius.max(0.) + 1.,
|
||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||
Self::MotionBlur { distance, .. } => distance.max(0.) / 2. + 3.,
|
||||
// It reaches farther from content lying farther from its center, which `Effects::reach_around` measures
|
||||
Self::RadialBlur { .. } => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// The graphic this operation paints with that renderers draw over the content's pixels on their own: a paint overlay's paint, an outline's drawn paint, a bevel's texture, or a mask's graphic.
|
||||
/// The graphic this operation paints with that renderers draw over the content's pixels on their own: a paint overlay's paint, an outline's drawn paint, a bevel's texture, a mask's graphic, or a blur's radius mask.
|
||||
/// An operation that changes nothing draws none, since renderers skip it.
|
||||
pub fn drawn_paint(&self) -> Option<&Graphic> {
|
||||
if self.changes_nothing() {
|
||||
@@ -984,31 +1185,18 @@ impl EffectOperation {
|
||||
},
|
||||
Self::BevelAndEmboss { texture, .. } => (!matches!(texture, Graphic::None(_) | Graphic::NoneList(_))).then_some(texture),
|
||||
Self::Mask { mask, .. } => Some(mask),
|
||||
Self::Blur { radius_mask, .. } => self.varies_blur_radius().then_some(radius_mask),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the graphic this operation draws with is placed in the content's own space, so it moves with the content, rather than in the space the content's item is placed in.
|
||||
/// The nodes stamping such operations express the graphic relative to the content's placement at that time with [`linked_to_content`].
|
||||
/// A paint lies there as given, like a fill's, while a mask's graphic is expressed relative to the content's placement at the time with [`linked_to_content`].
|
||||
pub fn drawn_paint_follows_content(&self) -> bool {
|
||||
matches!(self, Self::Mask { .. })
|
||||
}
|
||||
|
||||
/// The bounds a drawn paint without its own placement is fitted to, given the content's bounds and the length a document pixel spans along each of their axes.
|
||||
/// For PSD interop, an outline's paint fits the content grown by the whole pixels the outline reaches outside it, at least one.
|
||||
pub fn drawn_paint_bounds(&self, content_bounds: [DVec2; 2], pixel_spans: DVec2) -> [DVec2; 2] {
|
||||
match self {
|
||||
Self::Outline { weight, align, .. } => {
|
||||
// Interpolated between the whole weights PSD stores
|
||||
let margin_at = |weight: f64| outline_extents(weight, *align).0.ceil().max(1.);
|
||||
let weight = weight.max(0.);
|
||||
let below = weight.floor();
|
||||
let margin = margin_at(below) + (margin_at(below + 1.) - margin_at(below)) * (weight - below);
|
||||
|
||||
[content_bounds[0] - margin * pixel_spans, content_bounds[1] + margin * pixel_spans]
|
||||
}
|
||||
_ => content_bounds,
|
||||
}
|
||||
matches!(
|
||||
self,
|
||||
Self::Mask { .. } | Self::Blur { .. } | Self::PaintOverlay { .. } | Self::Outline { .. } | Self::BevelAndEmboss { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// This operation with each length that isn't finite (like one computed by dividing by zero) made zero, since no renderer can carry it out.
|
||||
@@ -1043,7 +1231,14 @@ impl EffectOperation {
|
||||
} => [depth, size, soften, angle, altitude, slope_range, texture_depth].into_iter().for_each(finite),
|
||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||
Self::Feather { distance } => finite(distance),
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => {}
|
||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||
Self::AddNoise { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
|
||||
Self::RadialBlur { amount, center, .. } => [amount, &mut center.x, &mut center.y].into_iter().for_each(finite),
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
@@ -1052,6 +1247,7 @@ impl EffectOperation {
|
||||
fn placeholder(kind: EffectKind) -> Self {
|
||||
match kind {
|
||||
EffectKind::Blur => Self::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -1144,6 +1340,44 @@ impl EffectOperation {
|
||||
invert: false,
|
||||
},
|
||||
EffectKind::Feather => Self::Feather { distance: 0. },
|
||||
EffectKind::ConvolutionKernel => Self::ConvolutionKernel {
|
||||
kernel: List::new(),
|
||||
columns: 0,
|
||||
scale: 0.,
|
||||
offset: 0.,
|
||||
apply_to_alpha: false,
|
||||
},
|
||||
EffectKind::Emboss => Self::Emboss { angle: 0., height: 0., amount: 0. },
|
||||
EffectKind::FindEdges => Self::FindEdges,
|
||||
EffectKind::MinimumMaximum => Self::MinimumMaximum {
|
||||
radius: 0.,
|
||||
mode: MinimumMaximumMode::default(),
|
||||
},
|
||||
EffectKind::Sharpen => Self::Sharpen {
|
||||
amount: 0.,
|
||||
radius: 0.,
|
||||
threshold: 0.,
|
||||
edges_only: false,
|
||||
},
|
||||
EffectKind::HighPass => Self::HighPass { radius: 0. },
|
||||
EffectKind::AddNoise => Self::AddNoise {
|
||||
amount: 0.,
|
||||
distribution: NoiseDistribution::default(),
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
},
|
||||
EffectKind::Dissolve => Self::Dissolve { opacity: 0., seed: 0 },
|
||||
EffectKind::MotionBlur => Self::MotionBlur {
|
||||
angle: 0.,
|
||||
distance: 0.,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::RadialBlur => Self::RadialBlur {
|
||||
method: RadialBlurMethod::default(),
|
||||
amount: 0.,
|
||||
center: DVec2::ZERO,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
|
||||
@@ -1179,6 +1413,7 @@ impl EffectOperation {
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1189,8 +1424,9 @@ impl EffectOperation {
|
||||
let glow_color = Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf));
|
||||
|
||||
match self {
|
||||
Self::Blur { radius, box_blur, gamma } => {
|
||||
Self::Blur { radius_mask, radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 0.);
|
||||
visitor.parameter("radius_mask", radius_mask, Graphic::default());
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
@@ -1350,6 +1586,68 @@ impl EffectOperation {
|
||||
visitor.parameter("invert", invert, false);
|
||||
}
|
||||
Self::Feather { distance } => visitor.parameter("distance", distance, 10.),
|
||||
Self::ConvolutionKernel {
|
||||
kernel,
|
||||
columns,
|
||||
scale,
|
||||
offset,
|
||||
apply_to_alpha,
|
||||
} => {
|
||||
visitor.parameter("kernel", kernel, List::new_from_elements(vec![0., 0., 0., 0., 1., 0., 0., 0., 0.]));
|
||||
visitor.parameter("columns", columns, 3);
|
||||
visitor.parameter("scale", scale, 1.);
|
||||
visitor.parameter("offset", offset, 0.);
|
||||
visitor.parameter("apply_to_alpha", apply_to_alpha, false);
|
||||
}
|
||||
// For PSD interop, the defaults are those of the filters' dialogs
|
||||
Self::Emboss { angle, height, amount } => {
|
||||
visitor.parameter("angle", angle, 135.);
|
||||
visitor.parameter("height", height, 3.);
|
||||
visitor.parameter("amount", amount, 100.);
|
||||
}
|
||||
Self::FindEdges => {}
|
||||
Self::MinimumMaximum { radius, mode } => {
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||
}
|
||||
Self::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
threshold,
|
||||
edges_only,
|
||||
} => {
|
||||
visitor.parameter("amount", amount, 50.);
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("threshold", threshold, 0.);
|
||||
visitor.parameter("edges_only", edges_only, false);
|
||||
}
|
||||
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
|
||||
Self::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => {
|
||||
visitor.parameter("amount", amount, 12.5);
|
||||
visitor.parameter("distribution", distribution, NoiseDistribution::default());
|
||||
visitor.parameter("monochromatic", monochromatic, false);
|
||||
visitor.parameter("seed", seed, 0);
|
||||
}
|
||||
Self::Dissolve { opacity, seed } => {
|
||||
visitor.parameter("opacity", opacity, 50.);
|
||||
visitor.parameter("seed", seed, 0);
|
||||
}
|
||||
Self::MotionBlur { angle, distance, gamma } => {
|
||||
visitor.parameter("angle", angle, 0.);
|
||||
visitor.parameter("distance", distance, 10.);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::RadialBlur { method, amount, center, gamma } => {
|
||||
visitor.parameter("method", method, RadialBlurMethod::default());
|
||||
visitor.parameter("amount", amount, 10.);
|
||||
visitor.parameter("center", center, DVec2::ZERO);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
@@ -1364,6 +1662,7 @@ mod tests {
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 6.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
@@ -1462,11 +1761,66 @@ mod tests {
|
||||
invert: true,
|
||||
},
|
||||
EffectOperation::Feather { distance: 4.5 },
|
||||
EffectOperation::Blur {
|
||||
radius_mask: Graphic::from(Color::WHITE),
|
||||
radius: 7.5,
|
||||
box_blur: true,
|
||||
gamma: true,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
EffectOperation::convolution_kernel("-1 0 1\n-2 0 2\n-1 0 1", Some(4.), 128., false),
|
||||
EffectOperation::convolution_kernel("0 -1 0\n-1 8 -1\n0 -1 0", None, 0., true),
|
||||
EffectOperation::Emboss {
|
||||
angle: -30.,
|
||||
height: 4.5,
|
||||
amount: 250.,
|
||||
},
|
||||
EffectOperation::FindEdges,
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius: 2.5,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
},
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius: 7.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||
EffectOperation::Sharpen {
|
||||
amount: 180.,
|
||||
radius: 2.5,
|
||||
threshold: 4.,
|
||||
edges_only: false,
|
||||
},
|
||||
EffectOperation::HighPass { radius: 3.5 },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 1.,
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Gaussian,
|
||||
monochromatic: true,
|
||||
seed: 7,
|
||||
},
|
||||
EffectOperation::Dissolve { opacity: 25., seed: 3 },
|
||||
EffectOperation::MotionBlur {
|
||||
angle: -30.,
|
||||
distance: 25.5,
|
||||
gamma: true,
|
||||
},
|
||||
EffectOperation::RadialBlur {
|
||||
method: RadialBlurMethod::Zoom,
|
||||
amount: 40.,
|
||||
center: DVec2::new(10., -25.),
|
||||
gamma: false,
|
||||
},
|
||||
EffectOperation::default_for(EffectKind::RadialBlur),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
@@ -1494,6 +1848,36 @@ mod tests {
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blur_row_without_a_radius_mask_decodes_as_an_even_blur() {
|
||||
let blur = |radius_mask: Graphic| EffectOperation::Blur {
|
||||
radius_mask,
|
||||
radius: 5.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// An empty radius mask is elided from the row, which reads back as empty
|
||||
let row = Effect::new(&blur(Graphic::default()));
|
||||
assert!(row.0.attribute::<Graphic>("radius_mask").is_none());
|
||||
assert_eq!(row.operation(), blur(Graphic::default()));
|
||||
|
||||
// So the row decodes the same as one carrying an empty radius mask, or one that draws nothing, all blurring evenly with nothing drawn
|
||||
let mut carrying_empty = row.clone();
|
||||
carrying_empty.0.set_attribute("radius_mask", Graphic::default());
|
||||
let mut carrying_nothing = row.clone();
|
||||
carrying_nothing.0.set_attribute("radius_mask", Graphic::GraphicList(List::new()));
|
||||
for row in [row, carrying_empty, carrying_nothing] {
|
||||
let operation = row.operation();
|
||||
assert!(!operation.varies_blur_radius() && operation.drawn_paint().is_none(), "{operation:?}");
|
||||
}
|
||||
|
||||
// A radius mask drawing something varies the blur and draws as its paint
|
||||
let masked = blur(Graphic::from(Color::WHITE));
|
||||
assert!(Effect::new(&masked).0.attribute::<Graphic>("radius_mask").is_some());
|
||||
assert!(masked.varies_blur_radius() && masked.drawn_paint() == Some(&Graphic::from(Color::WHITE)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_that_arent_finite_decode_as_zero() {
|
||||
let row = Effect::new(&EffectOperation::DropShadow {
|
||||
@@ -1542,41 +1926,6 @@ mod tests {
|
||||
assert_eq!(precise_falloff(0., 16., 16.), 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_paints_fit_the_whole_pixels_the_outline_reaches_outside() {
|
||||
let margin = |weight, align| {
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Graphic::from(Gradient::default()),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight,
|
||||
align,
|
||||
contour_gradient: false,
|
||||
};
|
||||
outline.drawn_paint_bounds([DVec2::ZERO, DVec2::splat(10.)], DVec2::ONE)[1].x - 10.
|
||||
};
|
||||
|
||||
assert_eq!(margin(8., StrokeAlign::Outside), 8.);
|
||||
// A centered outline of odd weight reaches into one more pixel, and one inside still fits a pixel past the content
|
||||
assert_eq!(margin(7., StrokeAlign::Center), 4.);
|
||||
assert_eq!(margin(40., StrokeAlign::Center), 20.);
|
||||
assert_eq!(margin(8., StrokeAlign::Inside), 1.);
|
||||
// Between whole weights, the margin is interpolated
|
||||
assert_eq!(margin(6.5, StrokeAlign::Center), 3.5);
|
||||
|
||||
// In a space a document pixel spans unevenly, the margin is measured along each axis
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Graphic::from(Gradient::default()),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight: 4.,
|
||||
align: StrokeAlign::Outside,
|
||||
contour_gradient: false,
|
||||
};
|
||||
assert_eq!(
|
||||
outline.drawn_paint_bounds([DVec2::ZERO, DVec2::splat(10.)], DVec2::new(2., 0.5)),
|
||||
[DVec2::new(-8., -2.), DVec2::new(18., 12.)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_contours_continue_straight_past_their_ends() {
|
||||
// Inner and outer bevels map the range down from the top and up from the foot, while an emboss maps its whole slope
|
||||
@@ -1633,6 +1982,7 @@ mod tests {
|
||||
#[test]
|
||||
fn runs_join_effects_stamped_rounding_apart_and_those_changing_nothing() {
|
||||
let blur = |radius: f64| EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -1680,6 +2030,7 @@ mod tests {
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
@@ -1750,6 +2101,56 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([mask]);
|
||||
assert_eq!((effects.reach(), effects.working_reach()), (0., 3. * mask_feather_sigma(4.)));
|
||||
// Unlike a convolution, which a render must read past the view for, the feather leaves edges past the view to what fits
|
||||
assert_eq!(effects.required_reach(), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_convolution_paints_nothing_past_the_content_but_reads_past_it() {
|
||||
let sharpen = EffectOperation::convolution_kernel("0 -1 0\n-1 5 -1\n0 -1 0", Some(1.), 0., false);
|
||||
assert_eq!(sharpen.painted_reach(), 0.);
|
||||
|
||||
// Weighing the coverage too, a kernel can spread it past the content
|
||||
let spread = EffectOperation::convolution_kernel("1 1 1", None, 0., true);
|
||||
assert_eq!(spread.painted_reach(), spread.reach());
|
||||
|
||||
// Its farthest copy a pixel away, a faint pixel's nearest visible color within the square around that, turned any way, and two pixels for rounding and copies between pixels
|
||||
let reach = 1. + std::f64::consts::SQRT_2 + 2.;
|
||||
assert_eq!((sharpen.working_reach(), sharpen.required_reach()), (reach, reach));
|
||||
|
||||
// The stylize and sharpen filters keep or shrink the coverage too, while a Minimum grows it
|
||||
let keeping = [
|
||||
EffectOperation::Emboss {
|
||||
angle: 135.,
|
||||
height: 3.,
|
||||
amount: 100.,
|
||||
},
|
||||
EffectOperation::FindEdges,
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 3.,
|
||||
threshold: 0.,
|
||||
edges_only: false,
|
||||
},
|
||||
EffectOperation::HighPass { radius: 3. },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 1.,
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
];
|
||||
assert!(keeping.iter().all(|operation| operation.painted_reach() == 0. && operation.working_reach() > 0.));
|
||||
let minimum = EffectOperation::MinimumMaximum {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
};
|
||||
assert_eq!(minimum.painted_reach(), 4.);
|
||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1778,14 +2179,56 @@ mod tests {
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.5, DVec2::new(200., 100.));
|
||||
let drawn_at = DAffine2::from_translation(DVec2::new(5., 7.));
|
||||
let mask = Graphic::Graphic(Box::new(Item::new_from_element(Graphic::default()).with_attribute(ATTR_TRANSFORM, drawn_at)));
|
||||
let mut effects = masked_by(linked_to_content(mask, placement));
|
||||
let mut effects = masked_by(linked_to_content(mask.clone(), placement));
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
assert!(nested_placement(&mask_of(&effects)).abs_diff_eq(drawn_at, 1e-9));
|
||||
|
||||
// A gradient without its own placement stretches across the content wherever it lies, so it's left as it is
|
||||
let unplaced = Graphic::Gradient(Item::new_from_element(Gradient::default()));
|
||||
let mut effects = masked_by(unplaced.clone());
|
||||
// A blur's radius mask follows the content the same way
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: linked_to_content(mask, placement),
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let mut effects = Effects::from_operations([blur]);
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
assert_eq!(mask_of(&effects), unplaced);
|
||||
let Some(EffectOperation::Blur { radius_mask, .. }) = effects.operations().next() else {
|
||||
panic!("the row should stay a blur")
|
||||
};
|
||||
assert!(nested_placement(&radius_mask).abs_diff_eq(drawn_at, 1e-9));
|
||||
|
||||
// A gradient without a transform lies at the identity in the content's own space, so it follows the content like any other graphic
|
||||
let gradient = Graphic::Gradient(Item::new_from_element(Gradient::default()));
|
||||
let mut effects = masked_by(gradient);
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
assert!(nested_placement(&mask_of(&effects)).abs_diff_eq(placement, 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_the_content_placement_into_its_geometry_keeps_radial_blur_centers_in_place() {
|
||||
// Stamped on stretched and turned content, which `placement` then moves before going into the content's geometry
|
||||
let stamped = DAffine2::from_scale_angle_translation(DVec2::new(1.5, 0.5), 0.1, DVec2::ZERO);
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(2., 3.), 0.5, DVec2::new(200., 100.));
|
||||
|
||||
for method in [RadialBlurMethod::Spin, RadialBlurMethod::Zoom] {
|
||||
let mut effects = Effects::from_operations([EffectOperation::RadialBlur {
|
||||
method,
|
||||
amount: 10.,
|
||||
center: DVec2::new(5., 7.),
|
||||
gamma: false,
|
||||
}]);
|
||||
effects.0.set_attribute(ATTR_TRANSFORM, 0, stamped);
|
||||
let pivot = |effects: &Effects, content_transform: DAffine2| {
|
||||
let Some(EffectOperation::RadialBlur { center, .. }) = effects.operations().next() else {
|
||||
panic!("the row should stay a radial blur")
|
||||
};
|
||||
effect_space(content_transform, effects.0.attribute_cloned_or_default(ATTR_TRANSFORM, 0)).transform_point2(center)
|
||||
};
|
||||
|
||||
let before = pivot(&effects, placement);
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
let after = pivot(&effects, DAffine2::IDENTITY);
|
||||
assert!(after.abs_diff_eq(before, 1e-9), "{method:?}: {before} moved to {after}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user