mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90d953f199 | ||
|
|
adba81a906 | ||
|
|
c9cec90437 | ||
|
|
a47695090d | ||
|
|
47845ec5a6 | ||
|
|
f88896a887 | ||
|
|
0eab6aa93c | ||
|
|
581bb05f5d | ||
|
|
048c458789 | ||
|
|
d241cdcb2e | ||
|
|
a770448bc9 | ||
|
|
2090e9979a |
No files matched your search
+14
-17
@@ -1,30 +1,27 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
|
||||
};
|
||||
version = "149.7827.0";
|
||||
upstream = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
|
||||
selectSystem =
|
||||
attrs:
|
||||
attrs.${pkgs.stdenv.hostPlatform.system}
|
||||
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
|
||||
|
||||
src = pkgs.fetchurl {
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
src = selectSystem {
|
||||
x86_64-linux = pkgs.fetchurl {
|
||||
url = "https://github.com/timon-schelling/graphite-cef/releases/download/v${version}/graphite_cef_x86-64_linux.tar.xz";
|
||||
hash = "sha256-CtvS/+NUh5ilnunt4AsWaZfWPiCsdEtz6+TLADT1Gqk=";
|
||||
};
|
||||
aarch64-linux = pkgs.fetchurl {
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${upstream}_linuxarm64_minimal.tar.bz2";
|
||||
hash = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
};
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
inherit src;
|
||||
pkgs.cef-binary.overrideAttrs (_: {
|
||||
inherit src version;
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
@@ -38,7 +35,7 @@ pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf finalAttrs.src.url;
|
||||
name = "cef_binary_${upstream}";
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
|
||||
Generated
+22
-2
@@ -1141,6 +1141,15 @@ version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
|
||||
|
||||
[[package]]
|
||||
name = "delaunator"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e1ee323c1275374f7e612d3724d12707079fb6a2117349fe144def656f5a880"
|
||||
dependencies = [
|
||||
"robust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.4.0"
|
||||
@@ -2008,7 +2017,6 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"gungraun",
|
||||
"interpreted-executor",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mmap-io",
|
||||
@@ -2182,6 +2190,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"vector-types",
|
||||
@@ -2394,6 +2403,7 @@ dependencies = [
|
||||
"graphite-proc-macros",
|
||||
"js-sys",
|
||||
"log",
|
||||
"node-macro",
|
||||
"serde",
|
||||
"serde-wasm-bindgen",
|
||||
"serde_bytes",
|
||||
@@ -2937,7 +2947,6 @@ dependencies = [
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"gungraun",
|
||||
"log",
|
||||
"once_cell",
|
||||
@@ -4882,11 +4891,15 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"tokio",
|
||||
"vector-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -4991,6 +5004,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "robust"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
|
||||
|
||||
[[package]]
|
||||
name = "ron"
|
||||
version = "0.12.0"
|
||||
@@ -6574,6 +6593,7 @@ name = "vector-nodes"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"delaunator",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam",
|
||||
|
||||
@@ -209,6 +209,7 @@ syn = { version = "2.0", default-features = false, features = [
|
||||
"proc-macro",
|
||||
] }
|
||||
lyon_geom = "1.0"
|
||||
delaunator = "1.0"
|
||||
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.2050787Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"viLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"impleLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":"","sources":[]}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"ValueLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[2,{"inputs":Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementatiLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implemeLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"List":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodesLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
|
||||
@@ -97,11 +97,6 @@ impl App {
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
||||
|
||||
let completion_render_sender = start_render_sender.clone();
|
||||
DesktopWrapper::set_completion_notifier(move || {
|
||||
let _ = completion_render_sender.try_send(());
|
||||
});
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
wgpu_context,
|
||||
|
||||
@@ -228,7 +228,7 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture.into());
|
||||
|
||||
@@ -52,10 +52,6 @@ impl DesktopWrapper {
|
||||
executor.execute()
|
||||
}
|
||||
|
||||
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
|
||||
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
|
||||
}
|
||||
|
||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||
match result {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod node {
|
||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||
pub const CONTEXT_FEATURES: &str = "context_features";
|
||||
pub const VISIBLE: &str = "visible";
|
||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::Context;
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -389,6 +390,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
attributes
|
||||
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
|
||||
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
|
||||
attributes
|
||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||
|
||||
@@ -14,9 +14,7 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
|
||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
let compiler = Compiler {};
|
||||
compiler
|
||||
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
|
||||
.map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -248,6 +246,11 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies {
|
||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
@@ -257,6 +260,7 @@ fn test_metadata_preservation() {
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||
call_argument: concrete!(String),
|
||||
context_features,
|
||||
visible: false, // Non-default value
|
||||
skip_deduplication: true, // Non-default value
|
||||
..Default::default()
|
||||
@@ -290,12 +294,8 @@ fn test_metadata_preservation() {
|
||||
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
||||
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
||||
|
||||
// Verify context_features is not stored
|
||||
assert_eq!(
|
||||
conv_node_0.context_features,
|
||||
ContextDependencies::default(),
|
||||
"context_features should resolve at compile, not round-trip"
|
||||
);
|
||||
// Verify context_features is preserved
|
||||
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
|
||||
|
||||
// Verify visible is preserved
|
||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||
|
||||
@@ -310,8 +310,8 @@ fn convert_node(
|
||||
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_features: Default::default(),
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -252,9 +252,20 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let mut vectors = Vec::new();
|
||||
let mut resources = Vec::new();
|
||||
for item in items {
|
||||
// Pasted templates skip document migration, so stored types normalize here
|
||||
match item {
|
||||
ClipboardItem::Layer(entry) => layers.push(entry),
|
||||
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
|
||||
ClipboardItem::Layer(mut entry) => {
|
||||
for (_, template) in &mut entry.nodes {
|
||||
template.document_node.normalize_stored_types();
|
||||
}
|
||||
layers.push(entry);
|
||||
}
|
||||
ClipboardItem::Nodes(mut nodes) => {
|
||||
for (_, template) in &mut nodes {
|
||||
template.document_node.normalize_stored_types();
|
||||
}
|
||||
node_groups.push(nodes);
|
||||
}
|
||||
ClipboardItem::Vector(vector) => vectors.push(vector),
|
||||
ClipboardItem::Resource(resource) => resources.push(resource),
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::parse_css_color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, Gradient, GradientUI};
|
||||
|
||||
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
|
||||
const MIN_MIDPOINT: f64 = 0.01;
|
||||
@@ -28,7 +28,7 @@ pub struct ColorPickerMessageHandler {
|
||||
old_is_none: bool,
|
||||
|
||||
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
|
||||
gradient: Option<GradientStops>,
|
||||
gradient: Option<Gradient>,
|
||||
active_marker_index: Option<u32>,
|
||||
active_marker_is_midpoint: bool,
|
||||
|
||||
@@ -430,7 +430,7 @@ impl ColorPickerMessageHandler {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
|
||||
let mut row_widgets = vec![
|
||||
SpectrumInput::new(GradientStopsUI::from(gradient))
|
||||
SpectrumInput::new(GradientUI::from(gradient))
|
||||
.markers(markers)
|
||||
.active_marker_index(self.active_marker_index)
|
||||
.active_marker_is_midpoint(self.active_marker_is_midpoint)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
@@ -292,11 +291,7 @@ impl LayoutMessageHandler {
|
||||
responses.add(callback_message);
|
||||
}
|
||||
WidgetValueAction::Update => {
|
||||
let Value::String(ref node_type) = value else {
|
||||
error!("NodeCatalog update was not of type: String, found {value:?}");
|
||||
return;
|
||||
};
|
||||
let callback_message = (node_type_input.on_update.callback)(&DefinitionIdentifier::from_serialized(node_type));
|
||||
let callback_message = (node_type_input.on_update.callback)(&value.into());
|
||||
responses.add(callback_message);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@ use derivative::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientUI};
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -531,7 +531,7 @@ pub struct SpectrumInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
pub track: GradientStopsUI,
|
||||
pub track: GradientUI,
|
||||
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackCSS")]
|
||||
#[widget_builder(skip)]
|
||||
|
||||
@@ -6,14 +6,26 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{Item, List, NodeIdPath};
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use graphene_std::text::TextAlign;
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{DashPattern, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
|
||||
use graphene_std::{Artboard, Color, Context, Graphic};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -166,8 +178,8 @@ macro_rules! generate_layout_downcast {
|
||||
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
|
||||
if false { None }
|
||||
$(
|
||||
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
|
||||
Some(element.layout_with_breadcrumb($data))
|
||||
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() {
|
||||
Some(io.output.layout_with_breadcrumb($data))
|
||||
}
|
||||
)*
|
||||
else { None }
|
||||
@@ -175,15 +187,10 @@ macro_rules! generate_layout_downcast {
|
||||
}
|
||||
// TODO: We simply try all these types sequentially. Find a better strategy.
|
||||
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
||||
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
||||
// `Item<NodeIdPath>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
||||
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
|
||||
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
|
||||
}
|
||||
// The path's plain value form, produced by `path_of_subgraph` on leveled wires.
|
||||
if let Some(path) = introspected_data.downcast_ref::<Vec<NodeId>>() {
|
||||
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&list, data));
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<NodeIdPath>>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&io.output.element().0, data));
|
||||
}
|
||||
generate_layout_downcast!(introspected_data, data, [
|
||||
List<Artboard>,
|
||||
@@ -192,27 +199,106 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<Gradient>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<u8>,
|
||||
List<f32>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<i32>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientType>,
|
||||
List<GradientSpreadMethod>,
|
||||
GradientStops,
|
||||
f64,
|
||||
u32,
|
||||
u64,
|
||||
bool,
|
||||
String,
|
||||
Option<f64>,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
List<DashPattern>,
|
||||
List<BoxCorners>,
|
||||
List<StrokeJoin>,
|
||||
List<StrokeAlign>,
|
||||
List<StrokeCap>,
|
||||
List<PaintOrder>,
|
||||
List<MergeByDistanceAlgorithm>,
|
||||
List<ExtrudeJoiningAlgorithm>,
|
||||
List<PointSpacingType>,
|
||||
List<StringCapitalization>,
|
||||
List<LuminanceCalculation>,
|
||||
List<RedGreenBlue>,
|
||||
List<RedGreenBlueAlpha>,
|
||||
List<RelativeAbsolute>,
|
||||
List<SelectiveColorChoice>,
|
||||
List<XY>,
|
||||
List<ScaleType>,
|
||||
List<ReferencePoint>,
|
||||
List<CentroidType>,
|
||||
List<BooleanOperation>,
|
||||
List<NoiseType>,
|
||||
List<FractalType>,
|
||||
List<CellularDistanceFunction>,
|
||||
List<CellularReturnType>,
|
||||
List<DomainWarpType>,
|
||||
List<RealTimeMode>,
|
||||
List<GridType>,
|
||||
List<ArcType>,
|
||||
List<SpiralType>,
|
||||
List<TextAlign>,
|
||||
List<QRCodeErrorCorrectionLevel>,
|
||||
List<InterpolationDistribution>,
|
||||
List<RowsOrColumns>,
|
||||
Item<Artboard>,
|
||||
Item<Graphic>,
|
||||
Item<Vector>,
|
||||
Item<Raster<CPU>>,
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<f32>,
|
||||
Item<u32>,
|
||||
Item<u64>,
|
||||
Item<i32>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientType>,
|
||||
Item<GradientSpreadMethod>,
|
||||
Item<DashPattern>,
|
||||
Item<BoxCorners>,
|
||||
Item<StrokeJoin>,
|
||||
Item<StrokeAlign>,
|
||||
Item<StrokeCap>,
|
||||
Item<PaintOrder>,
|
||||
Item<MergeByDistanceAlgorithm>,
|
||||
Item<ExtrudeJoiningAlgorithm>,
|
||||
Item<PointSpacingType>,
|
||||
Item<StringCapitalization>,
|
||||
Item<LuminanceCalculation>,
|
||||
Item<RedGreenBlue>,
|
||||
Item<RedGreenBlueAlpha>,
|
||||
Item<RelativeAbsolute>,
|
||||
Item<SelectiveColorChoice>,
|
||||
Item<XY>,
|
||||
Item<ScaleType>,
|
||||
Item<ReferencePoint>,
|
||||
Item<CentroidType>,
|
||||
Item<BooleanOperation>,
|
||||
Item<NoiseType>,
|
||||
Item<FractalType>,
|
||||
Item<CellularDistanceFunction>,
|
||||
Item<CellularReturnType>,
|
||||
Item<DomainWarpType>,
|
||||
Item<RealTimeMode>,
|
||||
Item<GridType>,
|
||||
Item<ArcType>,
|
||||
Item<SpiralType>,
|
||||
Item<TextAlign>,
|
||||
Item<QRCodeErrorCorrectionLevel>,
|
||||
Item<InterpolationDistribution>,
|
||||
Item<RowsOrColumns>,
|
||||
])
|
||||
}
|
||||
|
||||
@@ -250,6 +336,57 @@ trait TableItemLayout {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TableItemLayout> TableItemLayout for Item<T> {
|
||||
fn type_name() -> &'static str {
|
||||
T::type_name()
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.element().identifier()
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
if let Some(step) = data.desired_path.get(data.current_depth).cloned() {
|
||||
match step {
|
||||
PathStep::Element(_) => {
|
||||
data.current_depth += 1;
|
||||
let result = self.element().layout_with_breadcrumb(data);
|
||||
data.current_depth -= 1;
|
||||
return result;
|
||||
}
|
||||
PathStep::Attribute { key, .. } => {
|
||||
if let Some(any) = self.attributes().get_any(&key) {
|
||||
data.current_depth += 1;
|
||||
if let Some(result) = drilldown_attribute_layout(any, data) {
|
||||
data.current_depth -= 1;
|
||||
return result;
|
||||
}
|
||||
data.current_depth -= 1;
|
||||
warn!("Drilldown unsupported for attribute {key:?}");
|
||||
}
|
||||
data.desired_path.truncate(data.current_depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
|
||||
|
||||
// A single element, so no leading ID column, unlike the `List` table
|
||||
let mut values = vec![self.element().value_widget(PathStep::Element(0), data)];
|
||||
for key in &attribute_keys {
|
||||
let target = PathStep::Attribute { row: 0, key: key.clone() };
|
||||
let widget = self.attributes().get_any(key).and_then(|any| dispatch_value_widget(any, target, data)).unwrap_or_else(|| {
|
||||
let text = self.attributes().display_value(key, display_value_override).unwrap_or_else(|| "-".to_string());
|
||||
TextLabel::new(text).narrow(true).widget_instance()
|
||||
});
|
||||
values.push(widget);
|
||||
}
|
||||
|
||||
let mut column_names = vec!["element"];
|
||||
column_names.extend(attribute_keys.iter().map(|s| s.as_str()));
|
||||
|
||||
vec![LayoutGroup::table(vec![column_headings(&column_names), values], false)]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TableItemLayout> TableItemLayout for List<T> {
|
||||
fn type_name() -> &'static str {
|
||||
"List"
|
||||
@@ -312,7 +449,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Artboard<'_> {
|
||||
impl TableItemLayout for Artboard {
|
||||
fn type_name() -> &'static str {
|
||||
"Artboard"
|
||||
}
|
||||
@@ -328,12 +465,53 @@ impl TableItemLayout for Artboard<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Graphic<'_> {
|
||||
impl TableItemLayout for DashPattern {
|
||||
fn type_name() -> &'static str {
|
||||
"DashPattern"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"DashPattern".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
|
||||
fn value_widget(&self, target: PathStep, data: &LayoutData) -> WidgetInstance {
|
||||
self.0.value_widget(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for BoxCorners {
|
||||
fn type_name() -> &'static str {
|
||||
"BoxCorners"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"BoxCorners".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
|
||||
fn value_widget(&self, target: PathStep, data: &LayoutData) -> WidgetInstance {
|
||||
self.0.value_widget(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Graphic {
|
||||
fn type_name() -> &'static str {
|
||||
"Graphic"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
match self {
|
||||
Self::None => "None".to_string(),
|
||||
Self::Graphic(list) => list.identifier(),
|
||||
Self::Vector(list) => list.identifier(),
|
||||
Self::RasterCPU(list) => list.identifier(),
|
||||
@@ -341,7 +519,6 @@ impl TableItemLayout for Graphic<'_> {
|
||||
Self::Color(list) => list.identifier(),
|
||||
Self::Gradient(list) => list.identifier(),
|
||||
Self::Text(list) => list.identifier(),
|
||||
Self::Group(_) => "Group".to_string(),
|
||||
}
|
||||
}
|
||||
// Don't put a breadcrumb for Graphic
|
||||
@@ -350,6 +527,7 @@ impl TableItemLayout for Graphic<'_> {
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
match self {
|
||||
Self::None => label("None"),
|
||||
Self::Graphic(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Vector(list) => list.layout_with_breadcrumb(data),
|
||||
Self::RasterCPU(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -357,7 +535,6 @@ impl TableItemLayout for Graphic<'_> {
|
||||
Self::Color(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Gradient(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Text(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Group(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -518,7 +695,7 @@ impl TableItemLayout for Raster<GPU> {
|
||||
format!("Raster ({} x {})", self.data().width(), self.data().height())
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let widgets = vec![TextLabel::new("Raster is a texture on the GPU and cannot currently be displayed here").widget_instance()];
|
||||
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
|
||||
vec![LayoutGroup::row(widgets)]
|
||||
}
|
||||
}
|
||||
@@ -543,7 +720,7 @@ impl TableItemLayout for Color {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for GradientStops {
|
||||
impl TableItemLayout for Gradient {
|
||||
fn type_name() -> &'static str {
|
||||
"Gradient"
|
||||
}
|
||||
@@ -591,6 +768,21 @@ impl TableItemLayout for u8 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u32)"
|
||||
@@ -606,6 +798,37 @@ impl TableItemLayout for u32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
// TODO: Make this robust for large i64 values that don't fit in f64 (beyond roughly 2^53), as with u64.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u64)"
|
||||
@@ -732,45 +955,73 @@ impl TableItemLayout for Affine2 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for BlendMode {
|
||||
fn type_name() -> &'static str {
|
||||
"BlendMode"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
// Choice enums all display as their variant's label, shown inline as a plain text widget
|
||||
macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
($($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl TableItemLayout for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
stringify!($ty)
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
PaintOrder,
|
||||
MergeByDistanceAlgorithm,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
XY,
|
||||
ScaleType,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
NoiseType,
|
||||
FractalType,
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
ArcType,
|
||||
SpiralType,
|
||||
TextAlign,
|
||||
QRCodeErrorCorrectionLevel,
|
||||
InterpolationDistribution,
|
||||
RowsOrColumns,
|
||||
);
|
||||
|
||||
impl TableItemLayout for GradientType {
|
||||
// ReferencePoint is not a choice enum with display labels, so its variant name serves as the label
|
||||
impl TableItemLayout for ReferencePoint {
|
||||
fn type_name() -> &'static str {
|
||||
"GradientType"
|
||||
"ReferencePoint"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
format!("{self:?}")
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for GradientSpreadMethod {
|
||||
fn type_name() -> &'static str {
|
||||
"GradientSpreadMethod"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
TextLabel::new(self.identifier()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
@@ -911,12 +1162,10 @@ macro_rules! known_item_types {
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<Gradient>,
|
||||
List<String>,
|
||||
List<NodeId>,
|
||||
List<f64>,
|
||||
List<u8>,
|
||||
GradientStops,
|
||||
Gradient,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
@@ -925,9 +1174,12 @@ macro_rules! known_item_types {
|
||||
Vec2,
|
||||
Option<f64>,
|
||||
f64,
|
||||
f32,
|
||||
u8,
|
||||
u32,
|
||||
u64,
|
||||
i32,
|
||||
i64,
|
||||
bool,
|
||||
String,
|
||||
Vector,
|
||||
@@ -935,6 +1187,42 @@ macro_rules! known_item_types {
|
||||
Raster<GPU>,
|
||||
Graphic,
|
||||
Artboard,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
PaintOrder,
|
||||
MergeByDistanceAlgorithm,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
XY,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
NoiseType,
|
||||
FractalType,
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
ArcType,
|
||||
SpiralType,
|
||||
TextAlign,
|
||||
QRCodeErrorCorrectionLevel,
|
||||
InterpolationDistribution,
|
||||
RowsOrColumns,
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -955,6 +1243,10 @@ fn display_value_override(any: &dyn Any) -> Option<String> {
|
||||
/// element-column rendering and attribute-column rendering. Returns `None` for unrecognized
|
||||
/// types so the caller can fall back to a debug-formatted [`TextLabel`].
|
||||
fn dispatch_value_widget(any: &dyn Any, target: PathStep, data: &LayoutData) -> Option<WidgetInstance> {
|
||||
// `NodeIdPath` (e.g. the `editor:layer_path` attribute) drills into its inner path list, matching `drilldown_attribute_layout`.
|
||||
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
|
||||
return Some(path.0.value_widget(target, data));
|
||||
}
|
||||
macro_rules! check {
|
||||
( $($ty:ty),* $(,)? ) => {
|
||||
$(
|
||||
@@ -1011,15 +1303,10 @@ fn table_node_id_path_layout_with_breadcrumb(path: &List<NodeId>, data: &mut Lay
|
||||
/// Mirrors [`dispatch_value_widget`] but routes to [`TableItemLayout::layout_with_breadcrumb`].
|
||||
/// Returns `None` for unrecognized types.
|
||||
fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
||||
// `List<NodeId>` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
|
||||
// resolves against the prefix made up of preceding items. Handled before the generic `List<T>` blanket impl.
|
||||
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(path, data));
|
||||
}
|
||||
// The path's plain value form, the layer-path marker's owned shape.
|
||||
if let Some(path) = any.downcast_ref::<Vec<NodeId>>() {
|
||||
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&list, data));
|
||||
// `NodeIdPath` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
|
||||
// resolves against the prefix made up of preceding items. Handled before the generic blanket impl.
|
||||
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
|
||||
}
|
||||
macro_rules! check {
|
||||
( $($ty:ty),* $(,)? ) => {
|
||||
|
||||
@@ -248,11 +248,11 @@ pub enum DocumentMessage {
|
||||
// `UpdateFillAttributes` and `UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
||||
#[serde(skip)]
|
||||
UpdateFillAttributes {
|
||||
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
fill_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
},
|
||||
#[serde(skip)]
|
||||
UpdateStrokeAttributes {
|
||||
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
stroke_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
|
||||
@@ -34,9 +34,9 @@ use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graph_craft::list;
|
||||
use graphene_std::graphic::is_paint_present;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
@@ -125,7 +125,7 @@ pub struct DocumentMessageHandler {
|
||||
/// network path, the node itself, and its original relative gradient. The deferred migration removes each entry as its bake lands.
|
||||
/// Transient migration state, but persisted in the saved document so unfinished bakes retry on the next open instead of losing placement.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
|
||||
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
|
||||
// =============================================
|
||||
// Fields omitted from the saved document format
|
||||
@@ -2748,7 +2748,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// For each selected layer, splits its fill and stroke into two stacked layers connected
|
||||
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
|
||||
/// to a shared `Solidify Stroke` node via two `Item at Index` nodes (indices 0 and 1).
|
||||
/// Layers with only a stroke get just a `Solidify Stroke` added.
|
||||
/// Layers with only a fill, or neither, are left untouched.
|
||||
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
|
||||
@@ -2758,7 +2758,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
|
||||
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
|
||||
let item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Item at Index node should exist");
|
||||
|
||||
let mut resulting_layers: Vec<NodeId> = Vec::new();
|
||||
|
||||
@@ -2791,7 +2791,7 @@ impl DocumentMessageHandler {
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
|
||||
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
@@ -2813,7 +2813,7 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
@@ -3789,7 +3789,7 @@ impl DocumentMessageHandler {
|
||||
/// Create a network interface with a single export
|
||||
fn default_document_network_interface() -> NodeNetworkInterface {
|
||||
let mut network_interface = NodeNetworkInterface::default();
|
||||
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
|
||||
network_interface.add_export(TaggedValue::TypeDefault(list!(graphene_std::Artboard)), -1, "", &[]);
|
||||
network_interface
|
||||
}
|
||||
|
||||
@@ -4007,7 +4007,7 @@ mod document_message_handler_tests {
|
||||
#[test]
|
||||
fn pending_gradient_bakes_round_trip_through_serialization() {
|
||||
let document = DocumentMessageHandler {
|
||||
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::Gradient::default())],
|
||||
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::LegacyGradient::default())],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -4318,4 +4318,35 @@ mod document_message_handler_tests {
|
||||
Dist: {distance} (should be < 1)"
|
||||
);
|
||||
}
|
||||
|
||||
// Grouping choreography transiently disconnects the stack wire, and the stored default for that connector
|
||||
// must stay an empty list rather than any value which materializes as a one-element phantom in the stack
|
||||
#[tokio::test]
|
||||
async fn grouping_adds_no_phantom_element_to_the_stack() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
|
||||
let instrumented = editor.eval_graph().await.unwrap();
|
||||
|
||||
let base_lengths: Vec<usize> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::BaseInput<graphene_std::Graphic>>(&editor.runtime)
|
||||
.map(|base| base.len())
|
||||
.collect();
|
||||
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
|
||||
|
||||
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput<graphene_std::Graphic>>(&editor.runtime).collect();
|
||||
let phantom_count = news
|
||||
.iter()
|
||||
.flat_map(|new| new.iter_element_values())
|
||||
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None))
|
||||
.count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -22,7 +22,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
FillGradientSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient: GradientStops,
|
||||
gradient: Gradient,
|
||||
gradient_type: GradientType,
|
||||
spread_method: GradientSpreadMethod,
|
||||
transform: DAffine2,
|
||||
@@ -33,7 +33,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
GradientStopsSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
stops: GradientStops,
|
||||
stops: Gradient,
|
||||
},
|
||||
GradientTransformSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
|
||||
+13
-21
@@ -8,12 +8,11 @@ use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::list::List;
|
||||
use graph_craft::list;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::{Gradient, GradientSpreadMethod, GradientStop, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
@@ -180,7 +179,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
}
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::type_default(list!(Artboard), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
} else {
|
||||
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
|
||||
@@ -188,7 +187,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::type_default(list!(Artboard), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
}
|
||||
}
|
||||
@@ -508,8 +507,8 @@ const GRAPHITE_NAMESPACE: &str = "https://graphite.art";
|
||||
/// Pre-parses the raw SVG XML to extract gradient stops that have `graphite:midpoint` attributes.
|
||||
/// Graphite exports gradients with midpoint curve data by writing interpolated approximation stops
|
||||
/// alongside the real stops. Real stops are tagged with `graphite:midpoint` attributes.
|
||||
/// Returns a map from gradient element `id` to `GradientStops` containing only the real stops.
|
||||
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, GradientStops> {
|
||||
/// Returns a map from gradient element `id` to `Gradient` containing only the real stops.
|
||||
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, Gradient> {
|
||||
let mut result = HashMap::new();
|
||||
|
||||
// Quick check: if the SVG doesn't reference `graphite:midpoint` at all, skip parsing
|
||||
@@ -555,7 +554,7 @@ fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, GradientStops>
|
||||
}
|
||||
|
||||
if has_any_midpoint && !real_stops.is_empty() {
|
||||
result.insert(gradient_id, GradientStops::new(real_stops));
|
||||
result.insert(gradient_id, Gradient::new(real_stops));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,14 +578,7 @@ fn parse_hex_stop_color(hex: &str, opacity: f32) -> Option<Color> {
|
||||
/// interact with any existing layers in the parent stack. All descendant layers use a lightweight
|
||||
/// O(n) import path that skips collision detection and instead calculates positions directly from
|
||||
/// the known tree structure.
|
||||
fn import_usvg_node(
|
||||
modify_inputs: &mut ModifyInputsContext,
|
||||
node: &usvg::Node,
|
||||
id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
graphite_gradient_stops: &HashMap<String, GradientStops>,
|
||||
) {
|
||||
fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, id: NodeId, parent: LayerNodeIdentifier, insert_index: usize, graphite_gradient_stops: &HashMap<String, Gradient>) {
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
|
||||
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
@@ -649,7 +641,7 @@ fn import_usvg_node_inner(
|
||||
id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
graphite_gradient_stops: &HashMap<String, GradientStops>,
|
||||
graphite_gradient_stops: &HashMap<String, Gradient>,
|
||||
group_extents_map: &mut HashMap<LayerNodeIdentifier, Vec<u32>>,
|
||||
) -> u32 {
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
@@ -692,7 +684,7 @@ fn import_usvg_node_inner(
|
||||
}
|
||||
|
||||
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
|
||||
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, Gradient>) {
|
||||
let subpaths = convert_usvg_path(path);
|
||||
|
||||
// Skip creating a Transform node entirely when the SVG-native transform is identity.
|
||||
@@ -807,7 +799,7 @@ fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMet
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, Gradient>) {
|
||||
match &fill.paint() {
|
||||
usvg::Paint::Color(color) => modify_inputs.fill_color_set(Some(usvg_color(*color, fill.opacity().get()))),
|
||||
usvg::Paint::LinearGradient(linear) => {
|
||||
@@ -827,7 +819,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
midpoint: 0.5,
|
||||
color: usvg_color(stop.color(), stop.opacity().get()),
|
||||
});
|
||||
GradientStops::new(stops)
|
||||
Gradient::new(stops)
|
||||
}
|
||||
};
|
||||
let spread_method = convert_spread_method(linear.spread_method());
|
||||
@@ -851,7 +843,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
midpoint: 0.5,
|
||||
color: usvg_color(stop.color(), stop.opacity().get()),
|
||||
});
|
||||
GradientStops::new(stops)
|
||||
Gradient::new(stops)
|
||||
}
|
||||
};
|
||||
let spread_method = convert_spread_method(radial.spread_method());
|
||||
|
||||
@@ -8,7 +8,7 @@ use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
@@ -16,7 +16,7 @@ use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -134,11 +134,11 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
/// Creates an artboard as the primary export for the document network.
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::type_default(list!(Artboard), true)),
|
||||
Some(NodeInput::type_default(list!(Graphic), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Some(background)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(background), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||
]);
|
||||
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
|
||||
@@ -149,7 +149,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
|
||||
.expect("Boolean node does not exist")
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::type_default(list!(Graphic), true)),
|
||||
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
|
||||
]);
|
||||
|
||||
@@ -161,7 +161,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
|
||||
let blend = resolve_network_node_type("Blend")
|
||||
.expect("Blend node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
|
||||
let blend_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
@@ -173,7 +173,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
|
||||
.expect("Morph node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
@@ -300,7 +300,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier) {
|
||||
let color_value = resolve_proto_node_type(graphene_std::math_nodes::color_value::IDENTIFIER)
|
||||
.expect("Color Value node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(Some(color)), false))]);
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(color), false))]);
|
||||
|
||||
let color_value_id = NodeId::new();
|
||||
self.network_interface.insert_node(color_value_id, color_value, &[]);
|
||||
@@ -433,17 +433,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
return None;
|
||||
};
|
||||
|
||||
// If inserting a 'Path' node, insert a 'Flatten Path' node if the type is `Graphic`.
|
||||
// If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`.
|
||||
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
|
||||
if node_definition.identifier == "Path" {
|
||||
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
|
||||
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
|
||||
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
|
||||
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
|
||||
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
|
||||
log::error!("Combine Paths does not exist in ModifyInputsContext::existing_node_id");
|
||||
return None;
|
||||
};
|
||||
let node_id = NodeId::new();
|
||||
self.network_interface.insert_node(node_id, flatten_path_definition.default_node_template(), &[]);
|
||||
self.network_interface.insert_node(node_id, combine_paths_definition.default_node_template(), &[]);
|
||||
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
|
||||
}
|
||||
}
|
||||
@@ -457,14 +457,18 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX);
|
||||
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
|
||||
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
|
||||
|
||||
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
|
||||
// The backup remembers the last solid color, so the red-slash "none" choice leaves it untouched
|
||||
if let Some(color) = color {
|
||||
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
}
|
||||
let fill_value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(fill_value, false), false);
|
||||
}
|
||||
|
||||
pub fn fill_gradient_set(&mut self, gradient: GradientStops, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
|
||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
|
||||
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
@@ -474,7 +478,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
|
||||
// Skip the rerender on all but the last input so the whole update triggers a single graph run
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX),
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX),
|
||||
NodeInput::value(TaggedValue::Gradient(gradient), false),
|
||||
true,
|
||||
);
|
||||
@@ -488,9 +492,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX))
|
||||
.is_some_and(|input| input.as_value().is_some());
|
||||
if transform_is_value {
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
|
||||
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
|
||||
NodeInput::value(TaggedValue::DAffine2(transform), false),
|
||||
true,
|
||||
);
|
||||
}
|
||||
@@ -563,7 +572,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
|
||||
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
|
||||
pub fn gradient_stops_set(&mut self, stops: Gradient) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let gradient_value_id = match get_upstream_gradient_value_node_id(output_layer, self.network_interface) {
|
||||
@@ -715,8 +724,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
|
||||
@@ -729,8 +738,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths.into()), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
}
|
||||
|
||||
@@ -14,15 +14,15 @@ use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, descriptor};
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
#[allow(unused_imports)]
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::*;
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
pub struct NodePropertiesContext<'a> {
|
||||
@@ -88,8 +88,12 @@ impl DefinitionIdentifier {
|
||||
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Value> for DefinitionIdentifier {
|
||||
fn from(value: Value) -> Self {
|
||||
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
|
||||
|
||||
pub fn from_serialized(s: &str) -> Self {
|
||||
match s.split_once(':') {
|
||||
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
|
||||
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
|
||||
@@ -159,8 +163,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Collection of the content into the layer's group; the wrap keeps
|
||||
// the content level's element type for the legacy boundary.
|
||||
// Secondary (left) input type coercion
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::wrap_graphic::IDENTIFIER),
|
||||
@@ -175,8 +178,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// The monitor node is used to display a thumbnail in the UI
|
||||
@@ -199,7 +206,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Graphic>), true), NodeInput::type_default(descriptor!(List<Graphic>), true)],
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -233,7 +240,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 3: stamp_layer_path
|
||||
// 3: write_attribute
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
||||
@@ -284,11 +291,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(6), 0),
|
||||
NodeInput::import(concrete!(TaggedValue), 2),
|
||||
NodeInput::import(concrete!(TaggedValue), 3),
|
||||
NodeInput::import(concrete!(TaggedValue), 4),
|
||||
NodeInput::import(concrete!(TaggedValue), 5),
|
||||
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),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -301,13 +308,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// The monitor node is used to display a thumbnail in the UI.
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
skip_deduplication: true,
|
||||
@@ -315,33 +326,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(List<Artboard>))), 0),
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Content coercion into a graphic level, evaluated within the artboard's footprint
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::import(concrete!(TaggedValue), 2)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::translate_footprint::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Lifts the artboard element onto a one-lane level so it concatenates with the base stack
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
NodeInput::value(TaggedValue::U32(1), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -350,11 +340,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Artboard>), true),
|
||||
NodeInput::type_default(descriptor!(List<Graphic>), true),
|
||||
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(Some(Color::WHITE)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
..Default::default()
|
||||
@@ -409,7 +399,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 2: stamp_layer_path
|
||||
// 2: write_attribute
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
||||
@@ -433,30 +423,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 5: to_graphic
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-35, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 6: translate_footprint
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-28, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 7: repeat (the one-lane lift)
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-10, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -486,9 +452,9 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count Elements (number of subpaths)
|
||||
// 1: List Length (number of subpaths)
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(vector::count_elements::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(vector::list_length::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -501,7 +467,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 3: Floor (integer count per subpath)
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 1)],
|
||||
inputs: vec![NodeInput::import(item!(f64), 1)],
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
@@ -577,8 +543,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(generic!(T), 4),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -608,11 +574,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Vector>), true),
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(descriptor!(List<Vector>), false),
|
||||
NodeInput::type_default(list!(Vector), false),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -637,7 +603,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count Elements
|
||||
// 1: List Length
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
@@ -840,9 +806,9 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Flatten Path
|
||||
// 6: Combine Paths
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(vector::flatten_path::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -859,7 +825,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Vector>), true)],
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -917,7 +883,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Flatten Path
|
||||
// 6: Combine Paths
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
@@ -957,12 +923,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::import(concrete!(String), 1),
|
||||
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
|
||||
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1037,13 +998,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::import(concrete!(Footprint), 1),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
|
||||
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
],
|
||||
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1055,7 +1010,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Vector>), true),
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(
|
||||
TaggedValue::Footprint(Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::new(1000., 1000.), 0., DVec2::new(0., 0.)),
|
||||
@@ -1125,7 +1080,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1134,7 +1089,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1143,7 +1098,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1152,7 +1107,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1166,7 +1121,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
|
||||
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -1227,13 +1182,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
|
||||
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
|
||||
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
..Default::default()
|
||||
@@ -1284,89 +1239,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
description: Cow::Borrowed(
|
||||
"Decomposes the X and Y components of a vec2.\n\
|
||||
\n\
|
||||
The inverse of this node is \"Vec2 Value\", which can have either or both its X and Y parameters exposed as graph inputs.",
|
||||
The inverse of this node is **Combine Vec2**, which composes a vec2 from its X and Y components.",
|
||||
),
|
||||
properties: None,
|
||||
},
|
||||
#[cfg(feature = "gpu")]
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Upload Texture",
|
||||
category: "Debug",
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(List<Raster<CPU>>), 0), NodeInput::scope(platform_application_io::wgpu_executor::IDENTIFIER)],
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::memoize::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
output_names: vec!["Texture".to_string()],
|
||||
network_metadata: Some(NodeNetworkMetadata {
|
||||
persistent_metadata: NodeNetworkPersistentMetadata {
|
||||
node_metadata: [
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Extract",
|
||||
category: "",
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Extract,
|
||||
inputs: vec![NodeInput::type_default(descriptor!(DocumentNode), true)],
|
||||
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -1394,25 +1277,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(String), 0),
|
||||
NodeInput::import(concrete!(String), 1),
|
||||
NodeInput::import(concrete!(f64), 2),
|
||||
NodeInput::import(concrete!(bool), 3),
|
||||
NodeInput::import(concrete!(bool), 4),
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(f64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: extract_element 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)
|
||||
// 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)
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::extract_element::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: omit_element at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
// 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
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::omit_element::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
@@ -1494,7 +1377,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: vec![
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(List<Vector>), 0)],
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
skip_deduplication: true,
|
||||
@@ -1518,7 +1401,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Vector>), true),
|
||||
NodeInput::type_default(item!(Vector), true),
|
||||
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
|
||||
],
|
||||
..Default::default()
|
||||
@@ -2251,3 +2134,33 @@ impl DocumentNodeDefinition {
|
||||
self.node_template_input_override(self.node_template.document_node.inputs.clone().into_iter().map(Some))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::resolve_network_node_type;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// Guards the embedded Map body chain (Read Vector -> Extract Transform -> Decompose Translation -> As Vector) against registry drift
|
||||
#[tokio::test]
|
||||
async fn origins_to_polyline_resolves_and_evaluates() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = NodeId::new();
|
||||
let node_template = resolve_network_node_type("Origins to Polyline")
|
||||
.expect("the Origins to Polyline definition should exist")
|
||||
.default_node_template();
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(node_template),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
|
||||
}
|
||||
}
|
||||
+6
-5
@@ -29,7 +29,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
|
||||
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
let node_registry = NODE_REGISTRY.lock().unwrap();
|
||||
let empty_implementations: Vec<RegistryEntry> = Vec::new();
|
||||
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
let context_type = concrete!(Context);
|
||||
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
|
||||
@@ -42,17 +42,18 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
fields,
|
||||
description,
|
||||
properties,
|
||||
context_features,
|
||||
..
|
||||
} = metadata;
|
||||
|
||||
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
|
||||
|
||||
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
|
||||
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
|
||||
implementations.iter().map(|entry| &entry.io.call_argument).collect()
|
||||
implementations.iter().map(|(_, io)| &io.call_argument).collect()
|
||||
} else if let Some(impls) = extended_node_registry.get(id) {
|
||||
impls.iter().map(|entry| &entry.io.call_argument).collect()
|
||||
impls.keys().map(|io| &io.call_argument).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -77,7 +78,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
|
||||
visible: true,
|
||||
skip_deduplication: false,
|
||||
context_features: ContextDependencies::default(),
|
||||
context_features: ContextDependencies::from(context_features.as_slice()),
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
|
||||
@@ -1179,6 +1179,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
data_type: self.wire_in_progress_type,
|
||||
thick: false,
|
||||
dashed: false,
|
||||
is_list: false,
|
||||
center_path_string: String::new(),
|
||||
};
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: Some(wire_path) });
|
||||
}
|
||||
@@ -1431,7 +1433,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
return None;
|
||||
}
|
||||
|
||||
let (wire, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
|
||||
let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
|
||||
|
||||
let node_bbox = kurbo::Rect::new(node_bbox[0].x, node_bbox[0].y, node_bbox[1].x, node_bbox[1].y).to_path(DEFAULT_ACCURACY);
|
||||
let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None);
|
||||
@@ -1726,7 +1728,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
continue;
|
||||
};
|
||||
|
||||
if node_bbox[1].x >= document_bbox[0].x && node_bbox[0].x <= document_bbox[1].x && node_bbox[1].y >= document_bbox[0].y && node_bbox[0].y <= document_bbox[1].y {
|
||||
// Expand the cull box by a grid cell so a node stays rendered until its connectors, which reach beyond its bounding box, also leave the viewport
|
||||
let cull_margin = 24.;
|
||||
if node_bbox[1].x + cull_margin >= document_bbox[0].x
|
||||
&& node_bbox[0].x - cull_margin <= document_bbox[1].x
|
||||
&& node_bbox[1].y + cull_margin >= document_bbox[0].y
|
||||
&& node_bbox[0].y - cull_margin <= document_bbox[1].y
|
||||
{
|
||||
nodes.push(*node_id);
|
||||
}
|
||||
for error in &network_interface.resolved_types.node_graph_errors {
|
||||
@@ -1769,7 +1777,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
|
||||
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
|
||||
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
|
||||
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::INDEX;
|
||||
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::<graphene_std::list::List<Graphic>>::INDEX;
|
||||
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
|
||||
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
|
||||
.into_iter()
|
||||
@@ -2167,7 +2175,37 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::UpdateTypes { resolved_types, node_graph_errors } => {
|
||||
// Hidden passthrough nodes let a wire borrow its color and rank from an upstream node, so any type change can restyle wires whose own node is unchanged.
|
||||
// Compare each displayed wire's style (color, rank) across the update and unload only those that changed, so value-only recompiles keep their built wire paths.
|
||||
let types_changed = !resolved_types.add.is_empty() || !resolved_types.remove.is_empty();
|
||||
let wire_style = |network_interface: &mut NodeNetworkInterface, input: &InputConnector| {
|
||||
network_interface.upstream_output_connector(input, breadcrumb_network_path).map(|output| {
|
||||
let output_type = network_interface.output_type(&output, breadcrumb_network_path);
|
||||
(output_type.displayed_type(), output_type.is_list())
|
||||
})
|
||||
};
|
||||
let styles_before = types_changed.then(|| {
|
||||
network_interface
|
||||
.node_graph_input_connectors(breadcrumb_network_path)
|
||||
.into_iter()
|
||||
.map(|input| {
|
||||
let style = wire_style(network_interface, &input);
|
||||
(input, style)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
network_interface.resolved_types.update(resolved_types, node_graph_errors);
|
||||
|
||||
if let Some(styles_before) = styles_before {
|
||||
for (input, style_before) in styles_before {
|
||||
if wire_style(network_interface, &input) != style_before {
|
||||
network_interface.unload_wire(&input, breadcrumb_network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::UpdateActionButtons => {
|
||||
if selection_network_path == breadcrumb_network_path {
|
||||
|
||||
@@ -16,9 +16,10 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::{Type, concrete};
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::brush::brush_stroke::BrushTrace;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::list::List;
|
||||
@@ -31,9 +32,11 @@ use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
DashPattern, FillChoiceUI, Gradient, GradientSpreadMethod, GradientType, GradientUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
|
||||
@@ -212,6 +215,24 @@ pub(crate) fn property_from_type(
|
||||
|
||||
let default_info = ParameterWidgetsInfo::new(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| {
|
||||
let is_exposed = default_info.is_exposed();
|
||||
|
||||
let mut widgets = start_widgets(default_info);
|
||||
if !is_exposed {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("-")
|
||||
.tooltip_label(type_label)
|
||||
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
|
||||
vec![LayoutGroup::from(widgets)]
|
||||
};
|
||||
|
||||
let mut extra_widgets = vec![];
|
||||
let widgets = match ty {
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -233,100 +254,87 @@ pub(crate) fn property_from_type(
|
||||
// For all other types, use TypeId-based matching
|
||||
_ => {
|
||||
use std::any::TypeId;
|
||||
|
||||
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
|
||||
fn id_is<T: 'static>(id: TypeId) -> bool {
|
||||
id == TypeId::of::<T>()
|
||||
}
|
||||
|
||||
match concrete_type.id {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
|
||||
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some(x) if x == TypeId::of::<bool>() => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if x == TypeId::of::<String>() => text_widget(default_info).into(),
|
||||
Some(x) if x == TypeId::of::<DVec2>() => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
Some(x) if x == TypeId::of::<DAffine2>() => transform_widget(default_info, &mut extra_widgets),
|
||||
// ==========
|
||||
// LIST TYPES
|
||||
// ==========
|
||||
Some(x) if x == TypeId::of::<List<f64>>() => array_of_number_widget(default_info, TextInput::default()).into(),
|
||||
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||
Some(x) if x == TypeId::of::<List<GradientStops>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if x == TypeId::of::<List<BrushStroke>>() => brush_strokes_widget(default_info).into(),
|
||||
// Leveled wires type by their element; each element keeps its list form's widget.
|
||||
Some(x) if x == TypeId::of::<Color>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||
Some(x) if x == TypeId::of::<GradientStops>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if x == TypeId::of::<BrushStroke>() => brush_strokes_widget(default_info).into(),
|
||||
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
|
||||
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<BrushTrace>(x) => brush_strokes_widget(default_info).into(),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
Some(x) if x == TypeId::of::<Font>() => font_widget(default_info),
|
||||
Some(x) if x == TypeId::of::<Footprint>() => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if x == TypeId::of::<Box<VectorModification>>() => vector_modification_widget(default_info).into(),
|
||||
Some(x) if x == TypeId::of::<Image<Color>>() => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
// ===============================
|
||||
// MANUALLY IMPLEMENTED ENUM TYPES
|
||||
// ===============================
|
||||
Some(x) if x == TypeId::of::<ReferencePoint>() => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if x == TypeId::of::<BlendMode>() => blend_mode_widget(default_info),
|
||||
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
|
||||
// =========================
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if x == TypeId::of::<GradientType>() => enum_choice::<GradientType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<GradientSpreadMethod>() => enum_choice::<GradientSpreadMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RealTimeMode>() => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RedGreenBlue>() => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RedGreenBlueAlpha>() => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<XY>() => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StringCapitalization>() => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<NoiseType>() => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<FractalType>() => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<CellularDistanceFunction>() => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<CellularReturnType>() => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<DomainWarpType>() => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<RelativeAbsolute>() => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<GridType>() => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StrokeCap>() => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StrokeJoin>() => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StrokeAlign>() => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<PaintOrder>() => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<ArcType>() => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RowsOrColumns>() => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<TextAlign>() => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<MergeByDistanceAlgorithm>() => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<ExtrudeJoiningAlgorithm>() => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<PointSpacingType>() => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<BooleanOperation>() => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<CentroidType>() => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<LuminanceCalculation>() => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<QRCodeErrorCorrectionLevel>() => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<ScaleType>() => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<InterpolationDistribution>() => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientType>(x) => enum_choice::<GradientType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpreadMethod>(x) => enum_choice::<GradientSpreadMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PaintOrder>(x) => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<LuminanceCalculation>(x) => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
// =====
|
||||
// OTHER
|
||||
// =====
|
||||
_ => {
|
||||
let is_exposed = default_info.is_exposed();
|
||||
|
||||
let mut widgets = start_widgets(default_info);
|
||||
|
||||
if !is_exposed {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("-")
|
||||
.tooltip_label(concrete_type.to_string())
|
||||
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
return Err(vec![widgets.into()]);
|
||||
}
|
||||
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
|
||||
Type::List(element) => match element.as_ref() {
|
||||
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
|
||||
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
|
||||
},
|
||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -858,6 +866,32 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
|
||||
widgets
|
||||
}
|
||||
|
||||
pub fn dash_pattern_widget(parameter_widgets_info: ParameterWidgetsInfo, text_input: TextInput) -> Vec<WidgetInstance> {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
|
||||
let mut widgets = start_widgets(parameter_widgets_info);
|
||||
|
||||
let Some(document_node) = document_node else { return Vec::new() };
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(TaggedValue::DashPattern(pattern)) = &input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
text_input
|
||||
.value(pattern.0.iter_element_values().map(|length| length.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(
|
||||
move |input: &TextInput| Some(TaggedValue::DashPattern(DashPattern::from(input.value.as_str()))),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.widget_instance(),
|
||||
])
|
||||
}
|
||||
widgets
|
||||
}
|
||||
|
||||
pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetInstance>, Option<Vec<WidgetInstance>>) {
|
||||
pub fn assign_font_message(node_id: NodeId, font: Font) -> Message {
|
||||
let resource_id = ResourceId::new();
|
||||
@@ -1170,30 +1204,37 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
// Add the color input
|
||||
match &**tagged_value {
|
||||
TaggedValue::Color(color) => widgets.push(
|
||||
color_button
|
||||
.value(FillChoiceUI::from(&match color {
|
||||
Some(color) => FillChoice::Solid(*color),
|
||||
None => FillChoice::None,
|
||||
}))
|
||||
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid().map(Color::from)), node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
),
|
||||
TaggedValue::Gradient(stops) => widgets.push(
|
||||
color_button
|
||||
.value(FillChoiceUI::from(&FillChoice::Gradient(stops.clone())))
|
||||
.on_update(update_value(
|
||||
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().map(GradientStops::from).unwrap_or_default()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
),
|
||||
x => warn!("Color {x:?}"),
|
||||
}
|
||||
let widget_value = match &**tagged_value {
|
||||
TaggedValue::Color(color) => FillChoiceUI::Solid(SRGBA8::from(*color)),
|
||||
TaggedValue::Gradient(stops) => FillChoiceUI::Gradient(GradientUI::from(stops)),
|
||||
value if value.is_no_paint() => FillChoiceUI::None,
|
||||
x => {
|
||||
warn!("Color {x:?}");
|
||||
return LayoutGroup::row(widgets);
|
||||
}
|
||||
};
|
||||
|
||||
// A paint input (`allow_none`) stores the pick as a plain color, gradient, or no-paint type default,
|
||||
// while a plain color or gradient input always keeps its own value type
|
||||
let on_update: fn(&ColorInput) -> TaggedValue = if color_button.allow_none {
|
||||
|input| match &input.value {
|
||||
FillChoiceUI::None => TaggedValue::no_paint(),
|
||||
FillChoiceUI::Solid(srgba) => TaggedValue::Color(Color::from(*srgba)),
|
||||
FillChoiceUI::Gradient(gradient_ui) => TaggedValue::Gradient(Gradient::from(gradient_ui)),
|
||||
}
|
||||
} else if matches!(&**tagged_value, TaggedValue::Gradient(_)) {
|
||||
|input| TaggedValue::Gradient(input.value.as_gradient().map(Gradient::from).unwrap_or_default())
|
||||
} else {
|
||||
|input| TaggedValue::Color(input.value.as_solid().map(Color::from).unwrap_or(Color::TRANSPARENT))
|
||||
};
|
||||
|
||||
widgets.push(
|
||||
color_button
|
||||
.value(widget_value)
|
||||
.on_update(update_value(on_update, node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
|
||||
LayoutGroup::row(widgets)
|
||||
}
|
||||
@@ -1262,8 +1303,8 @@ pub fn query_assign_colors_randomize(node_id: NodeId, context: &NodePropertiesCo
|
||||
}
|
||||
|
||||
/// 2-stop black-to-white gradient track for spectrum sliders that map a value to a grayscale axis.
|
||||
fn bw_track() -> GradientStops {
|
||||
GradientStops {
|
||||
fn bw_track() -> Gradient {
|
||||
Gradient {
|
||||
position: vec![0., 1.],
|
||||
midpoint: vec![0.5, 0.5],
|
||||
color: vec![Color::BLACK, Color::WHITE],
|
||||
@@ -1271,8 +1312,8 @@ fn bw_track() -> GradientStops {
|
||||
}
|
||||
|
||||
/// 3-stop black-to-color-to-white gradient track for spectrum sliders that map a value to a hue's full luminance range.
|
||||
fn color_track(color: Color) -> GradientStops {
|
||||
GradientStops {
|
||||
fn color_track(color: Color) -> Gradient {
|
||||
Gradient {
|
||||
position: vec![0., 0.5, 1.],
|
||||
midpoint: vec![0.5; 3],
|
||||
color: vec![Color::BLACK, color, Color::WHITE],
|
||||
@@ -1307,7 +1348,7 @@ pub(crate) fn brightness_contrast_properties(node_id: NodeId, context: &mut Node
|
||||
|
||||
let contrast_min = if use_classic_value { -100. } else { -50. };
|
||||
let zero_position = -contrast_min / (100. - contrast_min);
|
||||
let contrast_track = GradientStops {
|
||||
let contrast_track = Gradient {
|
||||
position: vec![0., zero_position, 1.],
|
||||
midpoint: vec![0.5; 3],
|
||||
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), Color::BLACK, Color::from_rgbf32_unchecked(0.5, 0.5, 0.5)],
|
||||
@@ -1404,7 +1445,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
|
||||
|
||||
// Build the shared spectrum widget (placed on the first non-exposed row)
|
||||
let spectrum_widget = (!spectrum_markers.is_empty()).then(|| {
|
||||
SpectrumInput::new(GradientStopsUI::from(&bw_track()))
|
||||
SpectrumInput::new(GradientUI::from(&bw_track()))
|
||||
.markers(spectrum_markers)
|
||||
.show_midpoints(false)
|
||||
.allow_insert(false)
|
||||
@@ -1497,13 +1538,13 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
let saturated_current_hue = Color::from_hsva(marker_hue, 1., 1., 1.);
|
||||
|
||||
// Hue: cyclic rainbow
|
||||
let hue_track = GradientStops {
|
||||
let hue_track = Gradient {
|
||||
position: vec![0., 1. / 6., 2. / 6., 3. / 6., 4. / 6., 5. / 6., 1.],
|
||||
midpoint: vec![0.5; 7],
|
||||
color: vec![Color::RED, Color::YELLOW, Color::GREEN, Color::CYAN, Color::BLUE, Color::MAGENTA, Color::RED],
|
||||
};
|
||||
// Saturation: gray to the fully saturated current hue
|
||||
let saturation_track = GradientStops {
|
||||
let saturation_track = Gradient {
|
||||
position: vec![0., 1.],
|
||||
midpoint: vec![0.5, 0.5],
|
||||
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), saturated_current_hue],
|
||||
@@ -1553,7 +1594,7 @@ fn spectrum_slider_row(
|
||||
node_id: NodeId,
|
||||
context: &mut NodePropertiesContext,
|
||||
input_index: usize,
|
||||
track: GradientStops,
|
||||
track: Gradient,
|
||||
handle_color: Color,
|
||||
value_min: f64,
|
||||
value_max: f64,
|
||||
@@ -1578,7 +1619,7 @@ fn spectrum_slider_row(
|
||||
|
||||
let position_to_value = move |position: f64| value_min + position * value_range;
|
||||
row.push(
|
||||
SpectrumInput::new(GradientStopsUI::from(&track))
|
||||
SpectrumInput::new(GradientUI::from(&track))
|
||||
.markers(vec![SpectrumMarker::new(position, 0.5, handle_color)])
|
||||
.show_midpoints(false)
|
||||
.allow_insert(false)
|
||||
@@ -1638,7 +1679,7 @@ pub(crate) fn threshold_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
pub(crate) fn vibrance_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::vibrance::*;
|
||||
|
||||
let track = GradientStops {
|
||||
let track = Gradient {
|
||||
position: vec![0., 1.],
|
||||
midpoint: vec![0.5, 0.5],
|
||||
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), Color::RED],
|
||||
@@ -2195,16 +2236,11 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
let uniform_val = match input.as_non_exposed_value() {
|
||||
Some(TaggedValue::F64(x)) => *x,
|
||||
Some(TaggedValue::F64Array(values)) => values.first().copied().unwrap_or(0.),
|
||||
_ => 0.,
|
||||
};
|
||||
let individual_val = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::F64(x)) => vec![x; 4],
|
||||
Some(TaggedValue::F64Array(values)) => values.clone(),
|
||||
_ => vec![0.; 4],
|
||||
let corner_values = match input.as_non_exposed_value() {
|
||||
Some(TaggedValue::BoxCorners(corners)) => corners.to_corner_values(),
|
||||
_ => [0.; 4],
|
||||
};
|
||||
let uniform_val = corner_values[0];
|
||||
|
||||
// Uniform/individual radio input widget
|
||||
let uniform = RadioEntryData::new("Uniform")
|
||||
@@ -2220,13 +2256,12 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::F64(uniform_val),
|
||||
value: TaggedValue::BoxCorners(BoxCorners::from(uniform_val)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value);
|
||||
let individual_val_for_switch = individual_val.clone();
|
||||
let individual = RadioEntryData::new("Individual")
|
||||
.label("Individual")
|
||||
.on_update(move |_| Message::Batched {
|
||||
@@ -2240,7 +2275,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
||||
value: TaggedValue::BoxCorners(BoxCorners::from(corner_values.to_vec())),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2251,24 +2286,23 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
|
||||
// Radius value input widget
|
||||
let input_widget = if is_individual {
|
||||
let from_string = |string: &str| {
|
||||
string
|
||||
.split(&[',', ' '])
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(str::parse::<f64>)
|
||||
.collect::<Result<Vec<f64>, _>>()
|
||||
.ok()
|
||||
.map(|values| TaggedValue::F64Array(values.into_iter().take(4).collect()))
|
||||
};
|
||||
TextInput::default()
|
||||
.value(individual_val.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::INDEX))
|
||||
.value(corner_values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(
|
||||
move |x: &TextInput| Some(TaggedValue::BoxCorners(BoxCorners::from(x.value.as_str()))),
|
||||
node_id,
|
||||
CornerRadiusInput::INDEX,
|
||||
))
|
||||
.widget_instance()
|
||||
} else {
|
||||
NumberInput::default()
|
||||
.value(Some(uniform_val))
|
||||
.unit(" px")
|
||||
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::INDEX))
|
||||
.on_update(update_value(
|
||||
move |x: &NumberInput| TaggedValue::BoxCorners(BoxCorners::from(x.value.unwrap())),
|
||||
node_id,
|
||||
CornerRadiusInput::INDEX,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance()
|
||||
};
|
||||
@@ -2337,10 +2371,14 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
let mut unit_suffix = None;
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(proto_node_identifier)
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
number_options = NumberOptions {
|
||||
@@ -2353,17 +2391,19 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
display_decimal_places = field.number_display_decimal_places;
|
||||
unit_suffix = field.unit;
|
||||
step = field.number_step;
|
||||
if let Some(ref default) = field.default_type {
|
||||
break 'early_return default.clone();
|
||||
}
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
let Some(implementations) = &interpreted_executor::node_registry::NODE_REGISTRY.get(proto_node_identifier) else {
|
||||
if let Some(default) = default_type {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
let Some(implementations) = &interpreted_executor::node_registry::NODE_REGISTRY.get(&proto_node_identifier) else {
|
||||
log::error!("Could not get implementation for protonode {proto_node_identifier:?}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
|
||||
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>();
|
||||
input_types.sort_by_key(|ty| ty.type_name());
|
||||
let input_type = input_types.first().cloned();
|
||||
|
||||
@@ -2446,7 +2486,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
enum ResolvedFill {
|
||||
Solid(Option<Color>),
|
||||
Gradient {
|
||||
gradient: GradientStops,
|
||||
gradient: Gradient,
|
||||
gradient_type: GradientType,
|
||||
spread_method: GradientSpreadMethod,
|
||||
transform: DAffine2,
|
||||
@@ -2456,13 +2496,10 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
Other,
|
||||
}
|
||||
|
||||
let connector = InputConnector::node(node_id, FillInput::INDEX);
|
||||
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
|
||||
|
||||
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
|
||||
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::INDEX, false, context));
|
||||
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, context));
|
||||
|
||||
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::INDEX).is_some_and(|input| input.is_exposed())) {
|
||||
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::<List<Graphic>>::INDEX).is_some_and(|input| input.is_exposed())) {
|
||||
return vec![LayoutGroup::row(widgets_first_row)];
|
||||
}
|
||||
|
||||
@@ -2470,51 +2507,42 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
// bounding-box default transform needs the layer, and it falls back to a unit box when there isn't one.
|
||||
let layer = root_layer_for_chain_node(node_id, context);
|
||||
|
||||
let fill = match input_type.compiled_nested_type() {
|
||||
Some(ty) if ty == &concrete!(List<Color>) => {
|
||||
if let Ok(document_node) = get_document_node(node_id, context) {
|
||||
let color = match document_node.inputs[FillInput::INDEX].as_value() {
|
||||
Some(&TaggedValue::Color(c)) => c,
|
||||
_ => None,
|
||||
};
|
||||
ResolvedFill::Solid(color)
|
||||
} else {
|
||||
ResolvedFill::Other
|
||||
}
|
||||
}
|
||||
Some(ty) if ty == &concrete!(List<GradientStops>) => {
|
||||
// Read this node's own inputs rather than the layer's nearest Fill, which may be a different node when Fills are chained
|
||||
if let Ok(document_node) = get_document_node(node_id, context)
|
||||
&& let Some(gradient) = graph_modification_utils::read_fill_node_gradient(document_node, || {
|
||||
let fill = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
|
||||
Some(TaggedValue::Color(color)) => ResolvedFill::Solid(Some(*color)),
|
||||
Some(value) if value.is_no_paint() => ResolvedFill::Solid(None),
|
||||
Some(TaggedValue::Gradient(_)) => {
|
||||
match graph_modification_utils::read_fill_node_gradient(document_node, || {
|
||||
layer.map_or([DVec2::ZERO, DVec2::ONE], |layer| context.network_interface.document_metadata().nonzero_bounding_box(layer))
|
||||
}) {
|
||||
ResolvedFill::Gradient {
|
||||
gradient: gradient.stops,
|
||||
gradient_type: gradient.gradient_type,
|
||||
spread_method: gradient.spread_method,
|
||||
transform: gradient.transform,
|
||||
transform_is_value: gradient.transform_is_value,
|
||||
Some(gradient) => ResolvedFill::Gradient {
|
||||
gradient: gradient.stops,
|
||||
gradient_type: gradient.gradient_type,
|
||||
spread_method: gradient.spread_method,
|
||||
transform: gradient.transform,
|
||||
transform_is_value: gradient.transform_is_value,
|
||||
},
|
||||
None => ResolvedFill::Other,
|
||||
}
|
||||
} else {
|
||||
ResolvedFill::Other
|
||||
}
|
||||
}
|
||||
_ => ResolvedFill::Other,
|
||||
_ => ResolvedFill::Other,
|
||||
},
|
||||
Err(_) => ResolvedFill::Other,
|
||||
};
|
||||
|
||||
let (backup_color, backup_gradient) = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let backup_color = match document_node.inputs[BackupColorInput::INDEX].as_value() {
|
||||
Some(&TaggedValue::Color(color)) => color,
|
||||
Some(&TaggedValue::Color(color)) => Some(color),
|
||||
_ => None,
|
||||
};
|
||||
let backup_stops = match document_node.inputs[BackupGradientInput::INDEX].as_value() {
|
||||
Some(TaggedValue::Gradient(stops)) => stops.clone(),
|
||||
_ => GradientStops::default(),
|
||||
_ => Gradient::default(),
|
||||
};
|
||||
(backup_color, backup_stops)
|
||||
}
|
||||
Err(_) => (None, GradientStops::default()),
|
||||
Err(_) => (None, Gradient::default()),
|
||||
};
|
||||
|
||||
match &fill {
|
||||
@@ -2524,7 +2552,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
let reverse_button = IconButton::new("Reverse", 24)
|
||||
.tooltip_label("Reverse Stops")
|
||||
.tooltip_description("Reverse the gradient color stops.")
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::INDEX))
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::<List<Graphic>>::INDEX))
|
||||
.widget_instance();
|
||||
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets_first_row.push(reverse_button);
|
||||
@@ -2540,32 +2568,37 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
FillChoiceUI::None
|
||||
}
|
||||
}
|
||||
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientStopsUI::from(stops)),
|
||||
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientUI::from(stops)),
|
||||
ResolvedFill::Other => FillChoiceUI::None,
|
||||
};
|
||||
|
||||
let solid_set_messages = move |color: Option<Color>| Message::Batched {
|
||||
messages: Box::new([
|
||||
let solid_set_messages = move |color: Option<Color>| {
|
||||
let mut messages = vec![
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
||||
value: color.map_or_else(TaggedValue::no_paint, TaggedValue::Color),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: BackupColorInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
];
|
||||
if let Some(color) = color {
|
||||
messages.push(
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: BackupColorInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
Message::Batched { messages: messages.into() }
|
||||
};
|
||||
|
||||
let gradient_set_messages = move |gradient: GradientStops| Message::Batched {
|
||||
let gradient_set_messages = move |gradient: Gradient| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::INDEX,
|
||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
||||
value: TaggedValue::Gradient(gradient.clone()),
|
||||
}
|
||||
.into(),
|
||||
@@ -2589,7 +2622,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
solid_set_messages(color)
|
||||
}
|
||||
FillChoiceUI::Gradient(gradient_stops_ui) => {
|
||||
let gradient = GradientStops::from(gradient_stops_ui);
|
||||
let gradient = Gradient::from(gradient_stops_ui);
|
||||
gradient_set_messages(gradient)
|
||||
}
|
||||
})
|
||||
@@ -2606,11 +2639,15 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
let entries = vec![
|
||||
RadioEntryData::new("solid")
|
||||
.label("Solid")
|
||||
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::INDEX))
|
||||
.on_update(update_value(
|
||||
move |_| backup_color.map_or_else(TaggedValue::no_paint, TaggedValue::Color),
|
||||
node_id,
|
||||
FillInput::<List<Graphic>>::INDEX,
|
||||
))
|
||||
.on_commit(commit_value),
|
||||
RadioEntryData::new("gradient")
|
||||
.label("Gradient")
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::INDEX))
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::<List<Graphic>>::INDEX))
|
||||
.on_commit(commit_value),
|
||||
];
|
||||
|
||||
@@ -2672,7 +2709,22 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
} else {
|
||||
"Swap the start and end points of the gradient line."
|
||||
})
|
||||
.on_update(update_value(move |_| TaggedValue::OptionalDAffine2(Some(new_transform)), node_id, TransformInput::INDEX))
|
||||
.on_update(move |_| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: HasTransformInput::INDEX,
|
||||
value: TaggedValue::Bool(true),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: TransformInput::INDEX,
|
||||
value: TaggedValue::DAffine2(new_transform),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.widget_instance();
|
||||
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
spread_methods_row.push(reverse_direction_button);
|
||||
@@ -2716,14 +2768,14 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
_ => &StrokeJoin::Miter,
|
||||
};
|
||||
|
||||
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::INDEX].as_value() {
|
||||
Some(TaggedValue::F64Array(values)) => values.is_empty(),
|
||||
let has_dash_lengths = match &document_node.inputs[DashPatternInput::INDEX].as_value() {
|
||||
Some(TaggedValue::DashPattern(pattern)) => pattern.0.is_empty(),
|
||||
_ => true,
|
||||
};
|
||||
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
|
||||
|
||||
let color = color_widget(
|
||||
ParameterWidgetsInfo::new(node_id, PaintInput::INDEX, true, context),
|
||||
ParameterWidgetsInfo::new(node_id, PaintInput::<List<Graphic>>::INDEX, true, context),
|
||||
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
||||
);
|
||||
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput::INDEX, true, context), NumberInput::default().unit(" px").min(0.));
|
||||
@@ -2743,7 +2795,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput::INDEX, true, context))
|
||||
.property_row();
|
||||
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
||||
let dash_lengths = array_of_number_widget(ParameterWidgetsInfo::new(node_id, DashLengthsInput::INDEX, true, context), TextInput::default().centered(true));
|
||||
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput::INDEX, true, context), TextInput::default().centered(true));
|
||||
let number_input = disabled_number_input;
|
||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput::INDEX, true, context), number_input);
|
||||
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::Type;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use graphene_std::{Type, simplify_identifier_name};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -24,20 +19,22 @@ pub enum FrontendGraphDataType {
|
||||
|
||||
impl FrontendGraphDataType {
|
||||
pub fn from_type(input: &Type) -> Self {
|
||||
match TaggedValue::from_type_or_none(input) {
|
||||
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
|
||||
TaggedValue::Color(_) => Self::Color,
|
||||
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
|
||||
TaggedValue::String(_) => Self::Typography,
|
||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => Self::Graphic,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => Self::Artboard,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => Self::Raster,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => Self::Vector,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => Self::Typography,
|
||||
_ => Self::General,
|
||||
},
|
||||
// Color a wire by its element type, peeling a rank-0 `Item` or rank-1 `List` wrapper (and a whole-list `Bundle` cell) so all ranks share the element's color
|
||||
let nested_type = input.nested_type();
|
||||
let element = match nested_type.bundle_element_name() {
|
||||
Some(bundle_element) => simplify_identifier_name(bundle_element),
|
||||
None => nested_type.list_element().unwrap_or(nested_type).identifier_name(),
|
||||
};
|
||||
|
||||
match element.as_str() {
|
||||
"Vector" => Self::Vector,
|
||||
"Graphic" => Self::Graphic,
|
||||
"Artboard" => Self::Artboard,
|
||||
"Color" => Self::Color,
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -708,3 +708,103 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
// Autosaving the undone state still round-trips cleanly (no drift panic).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
|
||||
/// The document's single Fill node, as `(network_path, node_id)`.
|
||||
fn find_fill_node(document: &DocumentMessageHandler) -> (Vec<graph_craft::document::NodeId>, graph_craft::document::NodeId) {
|
||||
node_paths(&document.network_interface)
|
||||
.into_iter()
|
||||
.find(|(network_path, node_id)| {
|
||||
let Some(network) = document.network_interface.nested_network(network_path) else { return false };
|
||||
network.nodes[node_id].implementation == graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
})
|
||||
.expect("the document should contain a Fill node")
|
||||
}
|
||||
|
||||
/// The stored paint value of the document's single Fill node.
|
||||
fn fill_paint_value(document: &DocumentMessageHandler) -> graph_craft::document::value::TaggedValue {
|
||||
use graphene_std::NodeInputDecleration as _;
|
||||
|
||||
let (network_path, node_id) = find_fill_node(document);
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let input = network.nodes[&node_id]
|
||||
.inputs
|
||||
.get(graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX)
|
||||
.expect("Fill should have a paint input");
|
||||
input.as_value().expect("the paint input should hold a value").clone()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn none_fill_survives_document_reopen() {
|
||||
use graphene_std::NodeInputDecleration as _;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
|
||||
// Pick the red-slash "none" paint, stored the same way as the Fill widget's None choice
|
||||
let (_, fill_node_id) = find_fill_node(editor.active_document());
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: fill_node_id,
|
||||
input_index: graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX,
|
||||
value: graph_craft::document::value::TaggedValue::no_paint(),
|
||||
})
|
||||
.await;
|
||||
assert!(fill_paint_value(editor.active_document()).is_no_paint(), "the None pick should store as no_paint");
|
||||
|
||||
// Reopen through the editor's real open path, which runs the document migrations
|
||||
let serialized = editor.active_document().serialize_document();
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenDocumentFile {
|
||||
document_name: None,
|
||||
document_path: None,
|
||||
document_serialized_content: serialized,
|
||||
})
|
||||
.await;
|
||||
|
||||
let reopened_paint = fill_paint_value(editor.active_document());
|
||||
assert!(reopened_paint.is_no_paint(), "a none fill should survive reopening, but the stored paint became {reopened_paint:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration as _;
|
||||
|
||||
// A minimal master-era document: a 4-input Fill (content, fill: wired, backup color, backup gradient) fed by another node
|
||||
const LEGACY_DOCUMENT: &str = r#"{"network_interface":{"network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[1,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"OptionalColor":null},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::ops::SampleGradientNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]},"network_metadata":{"persistent_metadata":{"node_metadata":[[1,{"persistent_metadata":{"reference":"Fill","display_name":"","input_properties":[{"input_data":{"input_name":"Vector Data"},"widget_override":null},{"input_data":{"input_name":"Fill"},"widget_override":null},{"input_data":{"input_name":"Backup Color"},"widget_override":null},{"input_data":{"input_name":"Backup Gradient"},"widget_override":null}],"output_names":["Future<Instances<VectorData>>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[0,0]}}},"network_metadata":null}}],[2,{"persistent_metadata":{"reference":"Sample Gradient","display_name":"","input_properties":[{"input_data":{"input_name":"Primary"},"widget_override":null},{"input_data":{"input_name":"Gradient"},"widget_override":null},{"input_data":{"input_name":"Position"},"widget_override":null}],"output_names":["Future<Color>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[-20,0]}}},"network_metadata":null}}]],"previewing":"No","navigation_metadata":{"node_graph_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"node_graph_to_viewport":[1.0,0.0,0.0,1.0,0.0,0.0],"node_graph_top_right":[0.0,0.0]},"selection_undo_history":[],"selection_redo_history":[]}}},"collapsed":[],"name":"legacy_fill.graphite","commit_hash":"0000000000000000000000000000000000000000","document_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"document_mode":"DesignMode","view_mode":"Normal","overlays_visibility_settings":{"all":true,"artboard_name":true,"compass_rose":true,"quick_measurement":true,"transform_measurement":true,"transform_cage":true,"hover_outline":true,"selection_outline":true,"pivot":true,"path":true,"anchors":true,"handles":true},"rulers_visible":true,"snapping_state":{"snapping_enabled":true,"grid_snapping":false,"artboards":true,"tolerance":8.0,"bounding_box":{"center_point":true,"corner_point":true,"edge_midpoint":true,"align_with_edges":true,"distribute_evenly":true},"path":{"anchor_point":true,"line_midpoint":true,"along_path":true,"normal_to_path":true,"tangent_to_path":true,"path_intersection_point":true,"align_with_anchor_point":true,"perpendicular_from_endpoint":true},"grid":{"origin":[0.0,0.0],"grid_type":{"Rectangular":{"spacing":[1.0,1.0]}},"grid_color":{"red":0.6,"green":0.6,"blue":0.6,"alpha":1.0},"dot_display":false}},"graph_view_overlay_open":false,"graph_fade_artwork_percentage":80.0}"#;
|
||||
|
||||
// Deserializing alone must succeed, so a failure below is attributable to the migrations
|
||||
DocumentMessageHandler::deserialize_document(LEGACY_DOCUMENT).expect("the legacy document should deserialize");
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenDocumentFile {
|
||||
document_name: None,
|
||||
document_path: None,
|
||||
document_serialized_content: LEGACY_DOCUMENT.to_string(),
|
||||
})
|
||||
.await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let (network_path, node_id) = find_fill_node(document);
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let inputs = &network.nodes[&node_id].inputs;
|
||||
|
||||
assert_eq!(inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
|
||||
let paint = &inputs[graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX];
|
||||
assert!(
|
||||
matches!(paint, graph_craft::document::NodeInput::Node { .. }),
|
||||
"the wired legacy fill should keep its connection, but became {paint:?}"
|
||||
);
|
||||
let has_transform = inputs[graphene_std::vector::fill::HasTransformInput::INDEX].as_value();
|
||||
assert!(
|
||||
matches!(has_transform, Some(TaggedValue::Bool(_))),
|
||||
"the has-transform input should hold a bool, but became {has_transform:?}"
|
||||
);
|
||||
let transform = inputs[graphene_std::vector::fill::TransformInput::INDEX].as_value();
|
||||
assert!(
|
||||
matches!(transform, Some(TaggedValue::DAffine2(_))),
|
||||
"the transform input should hold a matrix, but became {transform:?}"
|
||||
);
|
||||
}
|
||||
@@ -20,29 +20,6 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Dev tool for the flip: runs each demo through the full open-time migration and writes the
|
||||
/// re-saved form into the directory named by `DEMO_OUT`, so the CLI can render migrated copies
|
||||
/// while the checked-in originals stay pristine until the flip's re-save.
|
||||
#[test]
|
||||
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
||||
fn migrate_demo_artwork_into_demo_out() {
|
||||
use crate::messages::portfolio::document_migration::{document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades};
|
||||
let out_dir = std::env::var("DEMO_OUT").expect("set DEMO_OUT to the output directory");
|
||||
for entry in std::fs::read_dir("../demo-artwork").unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().and_then(|extension| extension.to_str()) != Some("graphite") {
|
||||
continue;
|
||||
}
|
||||
let content = std::fs::read_to_string(&path).unwrap();
|
||||
let content = document_migration_string_preprocessing(content);
|
||||
let reset = document_migration_reset_node_definition(&content);
|
||||
let mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
|
||||
document_migration_upgrades(&mut document, reset);
|
||||
let out = format!("{out_dir}/{}", path.file_name().unwrap().to_string_lossy());
|
||||
std::fs::write(out, document.serialize_document()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
|
||||
/// iterate every node addressable from the metadata side.
|
||||
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
||||
|
||||
@@ -43,10 +43,10 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
||||
/// information that lives on the list.
|
||||
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
||||
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
|
||||
/// stroke paint information that lives on the list.
|
||||
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
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;
|
||||
@@ -24,6 +24,7 @@ use graph_craft::Type;
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graphene_std::ContextDependencies;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
@@ -2498,14 +2499,20 @@ 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 path_string = vector_wire.to_svg();
|
||||
let data_type = self.input_type(&input, network_path).displayed_type();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let input_type = self.input_type(&input, network_path);
|
||||
let data_type = input_type.displayed_type();
|
||||
let is_list = input_type.is_list();
|
||||
let wire_path_update = Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed: false,
|
||||
is_list,
|
||||
center_path_string,
|
||||
});
|
||||
|
||||
Some(WirePathUpdate {
|
||||
@@ -2515,15 +2522,15 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the vector subpath and a boolean of whether the wire should be thick.
|
||||
pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> {
|
||||
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
|
||||
pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
|
||||
let Some(input_position) = self.get_input_center(input, network_path) else {
|
||||
log::error!("Could not get dom rect for wire end: {input:?}");
|
||||
return None;
|
||||
};
|
||||
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector
|
||||
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
|
||||
return Some((BezPath::new(), false));
|
||||
return Some((BezPath::new(), BezPath::new(), false));
|
||||
};
|
||||
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
|
||||
log::error!("Could not get output port for wire start: {:?}", upstream_output);
|
||||
@@ -2532,21 +2539,29 @@ impl NodeNetworkInterface {
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
Some((build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style), thick))
|
||||
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);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
pub fn wire_path_from_input(&mut self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, network_path: &[NodeId]) -> Option<WirePath> {
|
||||
let (vector_wire, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
|
||||
let (vector_wire, center_line, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
|
||||
let path_string = vector_wire.to_svg();
|
||||
let data_type = self
|
||||
let center_path_string = center_line.to_svg();
|
||||
let (data_type, is_list) = self
|
||||
.upstream_output_connector(input, network_path)
|
||||
.map(|output| self.output_type(&output, network_path).displayed_type())
|
||||
.unwrap_or(FrontendGraphDataType::General);
|
||||
.map(|output| {
|
||||
let output_type = self.output_type(&output, network_path);
|
||||
(output_type.displayed_type(), output_type.is_list())
|
||||
})
|
||||
.unwrap_or((FrontendGraphDataType::General, false));
|
||||
Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed,
|
||||
is_list,
|
||||
center_path_string,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3440,12 +3455,12 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_FILL` snapshot.
|
||||
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
|
||||
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
||||
self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_STROKE` snapshot.
|
||||
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
|
||||
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
||||
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
|
||||
}
|
||||
}
|
||||
@@ -4089,6 +4104,18 @@ impl NodeNetworkInterface {
|
||||
node.call_argument = call_argument;
|
||||
}
|
||||
|
||||
pub fn set_context_features(&mut self, node_id: &NodeId, network_path: &[NodeId], context_features: ContextDependencies) {
|
||||
let Some(network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network in set_context_features");
|
||||
return;
|
||||
};
|
||||
let Some(node) = network.nodes.get_mut(node_id) else {
|
||||
log::error!("Could not get node in set_context_features");
|
||||
return;
|
||||
};
|
||||
node.context_features = context_features;
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -6092,6 +6119,19 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Chain is empty: wire the node as the first (and only) entry in the chain
|
||||
if matches!(current_input, NodeInput::Value { .. }) {
|
||||
// A node whose exposed primary defaults to no value inherits the layer's content value, so the chain keeps producing the layer's content type
|
||||
let node_primary = InputConnector::node(*node_id, 0);
|
||||
let default_is_valueless = self
|
||||
.input_from_connector(&node_primary, network_path)
|
||||
.is_some_and(|input| matches!(input, NodeInput::Value { tagged_value, exposed: true } if matches!(**tagged_value, TaggedValue::None)));
|
||||
if default_is_valueless {
|
||||
if import {
|
||||
self.set_input_for_import(&node_primary, current_input.clone(), network_path);
|
||||
} else {
|
||||
self.set_input(&node_primary, current_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Wire: [parent] -> [new node]
|
||||
if import {
|
||||
self.set_input_for_import(&parent_input, NodeInput::node(*node_id, 0), network_path);
|
||||
|
||||
+43
-29
@@ -4,11 +4,7 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::{Type, concrete};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
|
||||
@@ -56,28 +52,28 @@ impl TypeSource {
|
||||
return FrontendGraphDataType::Invalid;
|
||||
};
|
||||
match self.compiled_nested_type() {
|
||||
Some(nested_type) => match TaggedValue::from_type_or_none(nested_type) {
|
||||
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => {
|
||||
FrontendGraphDataType::Number
|
||||
}
|
||||
TaggedValue::Color(_) => FrontendGraphDataType::Color,
|
||||
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
|
||||
TaggedValue::String(_) => FrontendGraphDataType::Typography,
|
||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => FrontendGraphDataType::Graphic,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => FrontendGraphDataType::Artboard,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => FrontendGraphDataType::Raster,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => FrontendGraphDataType::Vector,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => FrontendGraphDataType::Typography,
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
Some(nested_type) => FrontendGraphDataType::from_type(nested_type),
|
||||
None => FrontendGraphDataType::General,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the compiled type is a rank-1 `List<T>`, as opposed to a rank-0 `Item<T>` or a bare value.
|
||||
/// A bundled cell carrying a whole list displays as the list it carries.
|
||||
pub fn is_list(&self) -> bool {
|
||||
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some())
|
||||
}
|
||||
|
||||
/// The element type's identifier name with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic.
|
||||
pub fn compiled_element_name(&self) -> Option<String> {
|
||||
let nested_type = self.compiled_nested_type()?;
|
||||
// A rank-0 `Item` or rank-1 `List` peels to its element; a bare value reports itself
|
||||
let element = match nested_type {
|
||||
Type::Item(element) | Type::List(element) => element.as_ref(),
|
||||
other => other,
|
||||
};
|
||||
Some(element.identifier_name())
|
||||
}
|
||||
|
||||
pub fn compiled_nested_type(&self) -> Option<&Type> {
|
||||
match self {
|
||||
TypeSource::Compiled(compiled_type) => Some(compiled_type.nested_type()),
|
||||
@@ -206,6 +202,19 @@ impl NodeNetworkInterface {
|
||||
concrete!(())
|
||||
}
|
||||
};
|
||||
|
||||
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0),
|
||||
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0
|
||||
if let Some(element) = guaranteed_type.nested_type().list_element()
|
||||
&& let Some(item_type) = self
|
||||
.potential_valid_input_types(input_connector, network_path)
|
||||
.into_iter()
|
||||
.find(|ty| matches!(ty.nested_type(), Type::Item(item_element) if item_element.as_ref() == element))
|
||||
&& let Some(item_default) = TaggedValue::from_type(&item_type)
|
||||
{
|
||||
return item_default;
|
||||
}
|
||||
|
||||
TaggedValue::from_type_or_none(&guaranteed_type)
|
||||
}
|
||||
|
||||
@@ -253,9 +262,8 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let node_io = &entry.io;
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
// Check if this NodeIOTypes implementation is valid for the other inputs
|
||||
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
|
||||
@@ -294,9 +302,8 @@ impl NodeNetworkInterface {
|
||||
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
|
||||
|
||||
implementations
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let node_io = &entry.io;
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
|
||||
return None;
|
||||
}
|
||||
@@ -325,7 +332,7 @@ impl NodeNetworkInterface {
|
||||
log::error!("Protonode {render_node:?} not found in registry");
|
||||
return Vec::new();
|
||||
};
|
||||
implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
|
||||
implementations.keys().map(|types| types.inputs[1].clone()).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,12 +342,19 @@ impl NodeNetworkInterface {
|
||||
pub fn output_type(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
|
||||
match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => {
|
||||
// A hidden node is replaced by a passthrough during flattening, so its output carries its primary input's type
|
||||
if *output_index == 0 && !self.is_visible(node_id, network_path) {
|
||||
return self.input_type(&InputConnector::node(*node_id, 0), network_path);
|
||||
}
|
||||
|
||||
// First try iterating upstream to the first protonode and try get its compiled type
|
||||
let Some(implementation) = self.implementation(node_id, network_path) else {
|
||||
return TypeSource::Error("Could not get implementation");
|
||||
};
|
||||
match implementation {
|
||||
DocumentNodeImplementation::Network(_) => self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat()),
|
||||
// The compiler removes passthrough nodes so they resolve no type of their own, but their output carries their primary input's type
|
||||
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => self.input_type(&InputConnector::node(*node_id, 0), network_path),
|
||||
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
|
||||
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
|
||||
None => TypeSource::Unknown,
|
||||
|
||||
@@ -12,6 +12,12 @@ pub struct WirePath {
|
||||
pub data_type: FrontendGraphDataType,
|
||||
pub thick: bool,
|
||||
pub dashed: bool,
|
||||
// A rank-1 `List<T>` wire renders as a doubled-up pair of parallel lines to distinguish it from a rank-0 `Item<T>` wire
|
||||
#[serde(rename = "isList")]
|
||||
pub is_list: bool,
|
||||
// A thick wire's center line reaches past the wire into the cleaved connector slots, so it needs its own longer path; empty otherwise
|
||||
#[serde(rename = "centerPathString")]
|
||||
pub center_path_string: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -57,6 +63,19 @@ impl GraphWireStyle {
|
||||
|
||||
pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
|
||||
let grid_spacing = 24.;
|
||||
|
||||
// A thick layer-stack wire (vertical at both ends) is skipped across a single straight grid cell where its connectors
|
||||
// already meet, and otherwise trimmed 3px inward at each end since it overshoots the connectors.
|
||||
let (output_position, input_position) = if vertical_out && vertical_in {
|
||||
if thick_wire_spans_single_cell(output_position, input_position) {
|
||||
return BezPath::new();
|
||||
}
|
||||
let trim = 3. * (input_position.y - output_position.y).signum();
|
||||
(output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim))
|
||||
} else {
|
||||
(output_position, input_position)
|
||||
};
|
||||
|
||||
match graph_wire_style {
|
||||
GraphWireStyle::Direct => {
|
||||
let horizontal_gap = (output_position.x - input_position.x).abs();
|
||||
@@ -101,6 +120,31 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
|
||||
}
|
||||
}
|
||||
|
||||
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
|
||||
let grid_spacing = 24.;
|
||||
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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 mut center_line = BezPath::new();
|
||||
center_line.move_to(dvec2_to_point(start));
|
||||
center_line.line_to(dvec2_to_point(end));
|
||||
center_line
|
||||
}
|
||||
|
||||
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
|
||||
let grid_spacing = 24;
|
||||
let line_width = 2;
|
||||
|
||||
@@ -7,15 +7,18 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Inp
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
use graph_craft::{Type, item};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::misc::BoxCorners;
|
||||
use graphene_std::vector::style::{DashPattern, PaintOrder, StrokeAlign};
|
||||
use std::collections::HashMap;
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -32,6 +35,9 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
|
||||
("\"OptionalF64\":", "\"F64\":"),
|
||||
("\"path_bool_nodes::BooleanOperation\"", "\"vector_types::vector::misc::BooleanOperation\""),
|
||||
("\"core_types::table::Table<", "\"core_types::list::List<"),
|
||||
// The `GradientStops` type was renamed to `Gradient`; stale stored output names are cleared so the display falls back to the live type name
|
||||
("\"output_names\":[\"GradientStops\"]", "\"output_names\":[\"\"]"),
|
||||
("vector_types::gradient::GradientStops", "vector_types::gradient::Gradient"),
|
||||
];
|
||||
|
||||
pub struct NodeReplacement<'a> {
|
||||
@@ -87,10 +93,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::animation::animation_time::IDENTIFIER,
|
||||
aliases: &["graphene_core::animation::AnimationTimeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::clone::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::CloneNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::extract_xy::extract_xy::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::ExtractXyNode"],
|
||||
@@ -106,6 +108,14 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::transform_nodes::FreezeRealTimeNode",
|
||||
"graphene_core::vector::SubpathSegmentLengthsNode",
|
||||
"core_types::vector::SubpathSegmentLengthsNode",
|
||||
// The deleted debug Option trio degrades to a passthrough of its single input
|
||||
"graphene_core::ops::SizeOfNode",
|
||||
"graphene_core::debug::SizeOfNode",
|
||||
"graphene_core::ops::SomeNode",
|
||||
"graphene_core::debug::SomeNode",
|
||||
"graphene_core::ops::UnwrapNode",
|
||||
"graphene_core::debug::UnwrapNode",
|
||||
"graphene_core::debug::UnwrapOptionNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -120,18 +130,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::animation::real_time::IDENTIFIER,
|
||||
aliases: &["graphene_core::animation::RealTimeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::size_of::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::SizeOfNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::some::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::SomeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::unwrap_option::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::UnwrapNode", "graphene_core::debug::UnwrapNode"],
|
||||
},
|
||||
// ================================
|
||||
// graphic
|
||||
// ================================
|
||||
@@ -161,13 +159,19 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::index_elements::IDENTIFIER,
|
||||
node: graphene_std::graphic::item_at_index::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::graphic_element::IndexNode",
|
||||
"graphene_core::graphic::IndexNode",
|
||||
"graphene_core::graphic::IndexElementsNode",
|
||||
"graphic_nodes::graphic::IndexElementsNode",
|
||||
"graphic_nodes::graphic::ExtractElementNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::remove_at_index::IDENTIFIER,
|
||||
aliases: &["graphic_nodes::graphic::OmitElementNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::legacy_layer_extend::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -290,8 +294,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::length::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::LengthNode", "graphene_core::ops::LenghtNode"],
|
||||
node: graphene_std::math_nodes::magnitude::IDENTIFIER,
|
||||
aliases: &["math_nodes::LengthNode", "graphene_math_nodes::LengthNode", "graphene_core::ops::LenghtNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::less_than::IDENTIFIER,
|
||||
@@ -416,6 +420,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::as_u_64::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::ToU64Node", "graphene_core::ops::ToU64Node", "math_nodes::ToU64Node"],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Combine Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Combine Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -735,8 +741,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
// vector
|
||||
// ================================
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::apply_transform::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::ApplyTransformNode", "graphene_core::vector::vector_modification::ApplyTransformNode"],
|
||||
node: graphene_std::vector::bake_transform::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::vector::ApplyTransformNode",
|
||||
"graphene_core::vector::vector_modification::ApplyTransformNode",
|
||||
"vector_nodes::vector_modification_nodes::ApplyTransformNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::area::IDENTIFIER,
|
||||
@@ -771,7 +781,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::ClosePathNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::count_elements::IDENTIFIER,
|
||||
node: graphene_std::vector::list_length::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::CountElementsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -795,7 +805,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::vector_nodes::FillNode", "graphene_core::vector::FillNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::flatten_path::IDENTIFIER,
|
||||
node: graphene_std::vector::combine_paths::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::vector::vector_nodes::FlattenPathNode",
|
||||
"graphene_core::vector::FlattenVectorElementsNode",
|
||||
@@ -1024,12 +1034,6 @@ fn replace_optional_f64_null(input: &str) -> String {
|
||||
result
|
||||
}
|
||||
|
||||
/// Serialized proto identifiers of the pre-flip Merge and Artboard layer internals.
|
||||
/// A document containing any of them predates the leveled-records flip and rebuilds its
|
||||
/// layer definitions through the same reset mechanism as the `SourceNodeIdNode` entry in
|
||||
/// `document_migration_reset_node_definition`.
|
||||
pub const FLIP_RESET_NODE_MARKERS: &[&str] = &["graphic_nodes::graphic::WriteAttributeNode"];
|
||||
|
||||
pub fn document_migration_reset_node_definition(document_serialized_content: &str) -> bool {
|
||||
// Upgrade a document being opened to use fresh copies of all nodes
|
||||
if document_serialized_content.contains("node_output_index") {
|
||||
@@ -1051,12 +1055,6 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
|
||||
return true;
|
||||
}
|
||||
|
||||
// The leveled-records flip replaced the layer internals; documents from before it rebuild
|
||||
// their layer definitions.
|
||||
if FLIP_RESET_NODE_MARKERS.iter().any(|marker| document_serialized_content.contains(marker)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1133,6 +1131,7 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
|
||||
|
||||
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
|
||||
document.network_interface.migrate_path_modify_node();
|
||||
document.network_interface.document_network_mut().normalize_stored_types();
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
|
||||
@@ -1297,9 +1296,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> "Text to Vector" pair, which reuses the same
|
||||
// proto identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current
|
||||
// 12-input node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and move it onto `text_to_vector`.
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
|
||||
// identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input
|
||||
// node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and splice the matching converter after it.
|
||||
let old_text_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
@@ -1333,7 +1332,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, new_index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
let separate_glyphs = old_inputs.get(12).cloned();
|
||||
// A `true` toggle at index 12 chose per-glyph geometry, which is now the dedicated "Text to Vector Glyphs" node
|
||||
let separate_glyphs = matches!(old_inputs.get(12).and_then(|input| input.as_value()), Some(TaggedValue::Bool(true)));
|
||||
|
||||
// Collect the inputs reading the old text node's output before any rewiring so the new node can be spliced onto those wires.
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
@@ -1345,44 +1345,62 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
|
||||
let text_was_in_chain = text_nodes_in_chain.contains(node_id);
|
||||
|
||||
// Insert the `text_to_vector` node that converts the `text` `String[]` output back into vector geometry.
|
||||
let Some(text_to_vector_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER)) else {
|
||||
// Insert the converter that turns the `text` `String[]` output back into vector geometry: "Text to Vector Glyphs" for the per-glyph case, otherwise "Text to Vector".
|
||||
let converter_identifier = if separate_glyphs {
|
||||
graphene_std::text::text_to_vector_glyphs::IDENTIFIER
|
||||
} else {
|
||||
graphene_std::text::text_to_vector::IDENTIFIER
|
||||
};
|
||||
let Some(converter_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(converter_identifier)) else {
|
||||
continue;
|
||||
};
|
||||
let text_to_vector_id = NodeId::new();
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(text_to_vector_id, text_to_vector_definition.default_node_template(), network_path);
|
||||
let converter_id = NodeId::new();
|
||||
document.network_interface.insert_node(converter_id, converter_definition.default_node_template(), network_path);
|
||||
|
||||
// Splice `text_to_vector` onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for
|
||||
// dropping a node on a wire), then carry the old `separate_glyphs` value onto its second input.
|
||||
// Splice the converter onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for dropping a node on a wire).
|
||||
if let Some((first_consumer, remaining_consumers)) = downstream_consumers.split_first() {
|
||||
document.network_interface.insert_node_between(&text_to_vector_id, first_consumer, 0, network_path);
|
||||
document.network_interface.insert_node_between(&converter_id, first_consumer, 0, network_path);
|
||||
for consumer in remaining_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(text_to_vector_id, 0), network_path);
|
||||
document.network_interface.set_input(consumer, NodeInput::node(converter_id, 0), network_path);
|
||||
}
|
||||
} else {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(text_to_vector_id, 0), NodeInput::node(*node_id, 0), network_path);
|
||||
}
|
||||
if let Some(separate_glyphs) = separate_glyphs {
|
||||
document.network_interface.set_input(&InputConnector::node(text_to_vector_id, 1), separate_glyphs, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(converter_id, 0), NodeInput::node(*node_id, 0), network_path);
|
||||
}
|
||||
|
||||
// If `text` was in a layer chain, re-chain `text_to_vector` and its upstream so both lay out by distance from the layer (the splice
|
||||
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place `text_to_vector` beside it instead of
|
||||
// If `text` was in a layer chain, re-chain the converter and its upstream so both lay out by distance from the layer (the splice
|
||||
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place the converter beside it instead of
|
||||
// leaving it at the origin.
|
||||
if text_was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&text_to_vector_id, network_path);
|
||||
document.network_interface.force_set_upstream_to_chain(&converter_id, network_path);
|
||||
} else if let Some(text_position) = document.network_interface.position(node_id, network_path) {
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&text_to_vector_id, text_position + IVec2::new(7, 0), network_path);
|
||||
document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let pattern = match &*tagged_value.clone().into_inner() {
|
||||
TaggedValue::F64Array(lengths) => DashPattern::from(lengths.clone()),
|
||||
TaggedValue::F64(length) => DashPattern::from(*length),
|
||||
TaggedValue::String(text) => DashPattern::from(text.as_str()),
|
||||
_ => return None,
|
||||
};
|
||||
Some(NodeInput::value(TaggedValue::DashPattern(pattern), *exposed))
|
||||
}
|
||||
|
||||
/// Converts a legacy rectangle corner radius input (a single `f64` or a `List<f64>` of up to four values) to the `BoxCorners` value type.
|
||||
fn migrate_corner_radius_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let corners = match &*tagged_value.clone().into_inner() {
|
||||
TaggedValue::F64Array(values) => BoxCorners::from(values.clone()),
|
||||
TaggedValue::F64(value) => BoxCorners::from(*value),
|
||||
_ => return None,
|
||||
};
|
||||
Some(NodeInput::value(TaggedValue::BoxCorners(corners), *exposed))
|
||||
}
|
||||
|
||||
fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) -> Option<()> {
|
||||
// Must run before the reset block below: a node referencing a removed catalog entry would otherwise abort
|
||||
// `migrate_node` via the `?` on `resolve_document_node_type`, preventing subsequent migration blocks from running.
|
||||
@@ -1391,34 +1409,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
|
||||
let node_definition = resolve_document_node_type(&reference)?;
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
|
||||
// The leveled-records flip moved the Copy to Points content wire ahead of the points wire.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::copy_to_points::IDENTIFIER) {
|
||||
let mut node_template = node_definition.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[0].clone(), network_path);
|
||||
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The leveled-records flip moved the Repeat on Points content wire ahead of the points wire.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::repeat::repeat_on_points::IDENTIFIER) {
|
||||
let mut node_template = node_definition.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[0].clone(), network_path);
|
||||
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The leveled-records flip gave Mandelbrot a unit primary input.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||
let mut node_template = node_definition.default_node_template();
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally
|
||||
@@ -1612,8 +1602,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 5;
|
||||
}
|
||||
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the
|
||||
// value-model 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _transform).
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
||||
// 8-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _has_transform, _transform).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
@@ -1622,21 +1612,21 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// Content: no change
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
// Fill: a literal Fill value is decomposed, and a wired input (`List<GradientStops> / List<Color>`) is kept as-is
|
||||
// Fill: a literal Fill value is decomposed, and a wired input (`List<Gradient> / List<Color>`) is kept as-is
|
||||
match old_inputs[1].as_value() {
|
||||
Some(TaggedValue::LegacyFill(old_fill)) => {
|
||||
let exposed = old_inputs[1].is_exposed();
|
||||
let fill_value = match old_fill {
|
||||
graphic_types::migrations::legacy::Fill::None => TaggedValue::Color(None),
|
||||
graphic_types::migrations::legacy::Fill::Solid(color) => TaggedValue::Color(Some(*color)),
|
||||
graphic_types::migrations::legacy::Fill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
|
||||
graphic_types::migrations::legacy::LegacyFill::None => TaggedValue::no_paint(),
|
||||
graphic_types::migrations::legacy::LegacyFill::Solid(color) => TaggedValue::Color(*color),
|
||||
graphic_types::migrations::legacy::LegacyFill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(fill_value, exposed), network_path);
|
||||
|
||||
// Gradient metadata (4, 5, 6): applies only to a literal gradient, solids/none keep the template defaults
|
||||
if let graphic_types::migrations::legacy::Fill::Gradient(gradient) = old_fill {
|
||||
// Gradient metadata (4, 5, 6, 7): applies only to a literal gradient, solids/none keep the template defaults
|
||||
if let graphic_types::migrations::legacy::LegacyFill::Gradient(gradient) = old_fill {
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 4),
|
||||
NodeInput::value(TaggedValue::GradientType(gradient.gradient_type), false),
|
||||
@@ -1648,20 +1638,23 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
network_path,
|
||||
);
|
||||
|
||||
let transform = if gradient.absolute {
|
||||
Some(gradient.transform * gradient.to_transform())
|
||||
if gradient.absolute {
|
||||
let transform = gradient.transform * gradient.to_transform();
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
} else {
|
||||
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint target's bounds
|
||||
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint
|
||||
// target's bounds, so the template's unbaked `_has_transform = false` stands until the bake lands
|
||||
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, gradient.clone()));
|
||||
None
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wired/exposed fill keeps the connection.
|
||||
// The generic paint connector accepts the existing `List<Color>`/`List<GradientStops>` paint sources directly.
|
||||
// The generic paint connector accepts the existing `List<Color>`/`List<Gradient>` paint sources directly.
|
||||
_ => {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
@@ -1680,7 +1673,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
if matches!(
|
||||
old_inputs[1].as_value(),
|
||||
Some(TaggedValue::LegacyFill(
|
||||
graphic_types::migrations::legacy::Fill::None | graphic_types::migrations::legacy::Fill::Solid(_)
|
||||
graphic_types::migrations::legacy::LegacyFill::None | graphic_types::migrations::legacy::LegacyFill::Solid(_)
|
||||
))
|
||||
) {
|
||||
document
|
||||
@@ -1692,19 +1685,54 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
network_path,
|
||||
);
|
||||
|
||||
let transform = if g.absolute {
|
||||
Some(g.transform * g.to_transform())
|
||||
if g.absolute {
|
||||
let transform = g.transform * g.to_transform();
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
} else {
|
||||
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, g.clone()));
|
||||
None
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = 7;
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.iter().enumerate().take(6) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
|
||||
match old_inputs.get(6).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::LegacyOptionalDAffine2(value)) => {
|
||||
let has_transform = value.is_some();
|
||||
let transform = value.unwrap_or(glam::DAffine2::IDENTITY);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(has_transform), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
}
|
||||
// A wired (or otherwise non-value) transform keeps its connection and is treated as present
|
||||
_ => {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
let transform_input = old_inputs.get(6).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::DAffine2(glam::DAffine2::IDENTITY), false));
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), transform_input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
|
||||
@@ -1723,10 +1751,111 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[6].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 6), old_inputs[7].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), paint_order_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[3].clone(), network_path);
|
||||
let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone());
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), dash_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 9), old_inputs[4].clone(), network_path);
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
// A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color,
|
||||
// since only paint connectors keep the no-paint choice
|
||||
{
|
||||
let migrate_color_input = |input: &NodeInput, fallback: Color| -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
if !tagged_value.is_no_paint() {
|
||||
return None;
|
||||
}
|
||||
Some(NodeInput::value(TaggedValue::Color(fallback), *exposed))
|
||||
};
|
||||
|
||||
let conversions: &[(ProtoNodeIdentifier, usize, Color)] = &[
|
||||
(graphene_std::vector::fill::IDENTIFIER, graphene_std::vector::fill::BackupColorInput::INDEX, Color::BLACK),
|
||||
(
|
||||
graphene_std::artboard::create_artboard::IDENTIFIER,
|
||||
graphene_std::artboard::create_artboard::BackgroundInput::INDEX,
|
||||
Color::WHITE,
|
||||
),
|
||||
(
|
||||
graphene_std::math_nodes::color_value::IDENTIFIER,
|
||||
graphene_std::math_nodes::color_value::ColorInput::INDEX,
|
||||
Color::TRANSPARENT,
|
||||
),
|
||||
(
|
||||
graphene_std::raster_nodes::adjustments::black_and_white::IDENTIFIER,
|
||||
graphene_std::raster_nodes::adjustments::black_and_white::TintInput::INDEX,
|
||||
Color::BLACK,
|
||||
),
|
||||
(
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput::INDEX,
|
||||
Color::BLACK,
|
||||
),
|
||||
(
|
||||
graphene_std::raster_nodes::std_nodes::empty_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::empty_image::ColorInput::INDEX,
|
||||
Color::WHITE,
|
||||
),
|
||||
];
|
||||
for &(ref identifier, index, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(identifier.clone()) {
|
||||
continue;
|
||||
}
|
||||
let Some(input) = node.inputs.get(index) else { continue };
|
||||
if let Some(migrated) = migrate_color_input(input, fallback) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), migrated, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The stroke dash sequence became the `DashPattern` value type; convert any already-shaped stroke that still stores a legacy dash input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER)
|
||||
&& let Some(dash_input) = node.inputs.get(graphene_std::vector::stroke::DashPatternInput::INDEX)
|
||||
&& let Some(migrated) = migrate_dash_input(dash_input)
|
||||
{
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, graphene_std::vector::stroke::DashPatternInput::INDEX), migrated, network_path);
|
||||
}
|
||||
|
||||
// The rectangle's corner radius became the `BoxCorners` value type and its hidden individual-radii toggle moved after the
|
||||
// user-visible inputs. A legacy rectangle stores that toggle (a plain `bool`) at index 3, where the new shape stores the corner
|
||||
// radius, so a `bool` value there identifies the old input order: [width, height, individual, corner_radius, clamped].
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
|
||||
&& let Some(toggle_input) = node.inputs.get(3)
|
||||
&& matches!(toggle_input.as_value(), Some(TaggedValue::Bool(_)))
|
||||
{
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
let corner_radius = migrate_corner_radius_input(&old_inputs[4]).unwrap_or_else(|| old_inputs[4].clone());
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 3), corner_radius, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[5].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
|
||||
// The Text to Vector node's runtime `separate_glyphs` toggle became the dedicated "Text to Vector Glyphs" node, leaving Text to Vector as a plain
|
||||
// string-to-compound-path converter. A 2-input Text to Vector is the old toggled shape: a `true` toggle routes to Text to Vector Glyphs, otherwise
|
||||
// the node stays Text to Vector; either way the toggle input is dropped and the string wire is preserved.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER) && inputs_count == 2 {
|
||||
let separate_glyphs = matches!(node.inputs.get(1).and_then(|input| input.as_value()), Some(TaggedValue::Bool(true)));
|
||||
let target = if separate_glyphs {
|
||||
graphene_std::text::text_to_vector_glyphs::IDENTIFIER
|
||||
} else {
|
||||
graphene_std::text::text_to_vector::IDENTIFIER
|
||||
};
|
||||
|
||||
let mut node_template = resolve_proto_node_type(target)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
if let Some(string_input) = node.inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), string_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 8 {
|
||||
let mut template: NodeTemplate = legacy_text_node_template()?;
|
||||
@@ -1894,6 +2023,20 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
}
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Combine Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let combine_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::combine_vec_2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&combine_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the Mirror node to add the `keep_original` boolean input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::graphic::mirror::IDENTIFIER) && inputs_count == 3 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2026,6 +2169,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// A brush node saved before `Item<Raster<CPU>>` had a default stored its unconnected background as the invalid `()`,
|
||||
// which fails type resolution against the raster primary; adopt the definition's empty-raster default instead.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER) && matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::None)) {
|
||||
let default_background = resolve_document_node_type(&reference)?.node_template.document_node.inputs.first()?.clone();
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), default_background, network_path);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::RemoveHandlesNode")) {
|
||||
let mut node_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::auto_tangents::IDENTIFIER))?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
@@ -2242,7 +2392,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// Migrate from the v2 "Morph" node (2 inputs: content, progression) to the v3 "Morph" node (5 inputs: content, progression, reverse, distribution, path).
|
||||
// The old progression used integer part for pair selection (range 0..N-1 where N is the number of content objects).
|
||||
// The new progression uses fractional 0..1 for euclidean traversal through all objects.
|
||||
// We insert Count Elements → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
|
||||
// We insert List Length → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
|
||||
// For the common 2-object case (N=2), this divides by 1 which is a no-op, preserving identical behavior.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::morph::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2257,14 +2407,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
return None;
|
||||
};
|
||||
|
||||
// Create Count Elements node: counts content `List` items → N
|
||||
let Some(count_elements_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::count_elements::IDENTIFIER)) else {
|
||||
log::error!("Could not get count_elements node from definition when upgrading morph");
|
||||
// Create List Length node: counts content `List` items → N
|
||||
let Some(list_length_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::list_length::IDENTIFIER)) else {
|
||||
log::error!("Could not get list_length node from definition when upgrading morph");
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
return None;
|
||||
};
|
||||
let count_elements_template = count_elements_def.default_node_template();
|
||||
let count_elements_id = NodeId::new();
|
||||
let list_length_template = list_length_def.default_node_template();
|
||||
let list_length_id = NodeId::new();
|
||||
|
||||
// Create Subtract node: N → N-1
|
||||
let Some(subtract_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER)) else {
|
||||
@@ -2286,10 +2436,10 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let divide_id = NodeId::new();
|
||||
|
||||
// Insert and position nodes
|
||||
document.network_interface.insert_node(count_elements_id, count_elements_template, network_path);
|
||||
document.network_interface.insert_node(list_length_id, list_length_template, network_path);
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&count_elements_id, morph_position + IVec2::new(-21, 2), network_path);
|
||||
.shift_absolute_node_position(&list_length_id, morph_position + IVec2::new(-21, 2), network_path);
|
||||
|
||||
document.network_interface.insert_node(subtract_id, subtract_template, network_path);
|
||||
document.network_interface.shift_absolute_node_position(&subtract_id, morph_position + IVec2::new(-14, 2), network_path);
|
||||
@@ -2297,13 +2447,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.insert_node(divide_id, divide_template, network_path);
|
||||
document.network_interface.shift_absolute_node_position(÷_id, morph_position + IVec2::new(-7, 1), network_path);
|
||||
|
||||
// Wire: content source → Count Elements input 0
|
||||
document.network_interface.set_input(&InputConnector::node(count_elements_id, 0), old_inputs[0].clone(), network_path);
|
||||
// Wire: content source → List Length input 0
|
||||
document.network_interface.set_input(&InputConnector::node(list_length_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
// Wire: Count Elements output → Subtract input 0 (minuend)
|
||||
// Wire: List Length output → Subtract input 0 (minuend)
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(count_elements_id, 0), network_path);
|
||||
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(list_length_id, 0), network_path);
|
||||
|
||||
// Wire: old progression → Divide input 0 (numerator)
|
||||
document.network_interface.set_input(&InputConnector::node(divide_id, 0), old_inputs[1].clone(), network_path);
|
||||
@@ -2441,6 +2591,15 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// Add context features to nodes that don't have them (fine-grained context caching migration)
|
||||
if node.context_features == graphene_std::ContextDependencies::default()
|
||||
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
|
||||
&& let Some(node_definition) = resolve_document_node_type(&reference)
|
||||
{
|
||||
let context_features = node_definition.node_template.document_node.context_features;
|
||||
document.network_interface.set_context_features(node_id, network_path, context_features);
|
||||
}
|
||||
|
||||
// Add the "Scale Type" parameter to the "Decompose Scale" node
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2475,11 +2634,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let modification = modification.clone();
|
||||
let was_exposed = *exposed;
|
||||
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 0),
|
||||
NodeInput::type_default(descriptor!(graphene_std::list::List<graphene_std::vector::Vector>), true),
|
||||
network_path,
|
||||
);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 0), NodeInput::type_default(item!(graphene_std::vector::Vector), true), network_path);
|
||||
|
||||
if !was_exposed {
|
||||
document
|
||||
@@ -2511,6 +2668,34 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
|
||||
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
|
||||
if let Some(definition) = resolve_document_node_type(&reference) {
|
||||
let definition_inputs = definition.node_template.document_node.inputs.clone();
|
||||
for (index, definition_input) in definition_inputs.iter().enumerate() {
|
||||
if !matches!(definition_input, NodeInput::Value { .. }) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let stale_list_default = document
|
||||
.network_interface
|
||||
.input_from_connector(&InputConnector::node(*node_id, index), network_path)
|
||||
.is_some_and(|stored_input| match stored_input {
|
||||
NodeInput::Value { tagged_value, .. } => match &**tagged_value {
|
||||
TaggedValue::TypeDefault(stored_type) if matches!(stored_type, Type::List(_)) && !tagged_value.is_no_paint() => {
|
||||
!matches!(definition_input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, TaggedValue::TypeDefault(definition_type) if definition_type == stored_type))
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
});
|
||||
|
||||
if stale_list_default {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), definition_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// PUT ALL MIGRATIONS ABOVE THIS LINE
|
||||
// ==================================
|
||||
@@ -2596,6 +2781,31 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
}
|
||||
}
|
||||
|
||||
// The removed Attach Attribute node degrades to a passthrough of its
|
||||
// content: its eager whole-list source input cannot be mechanically rewired as Write Attribute's lazy per-item value producer.
|
||||
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
|
||||
&& identifier.as_str().ends_with("::AttachAttributeNode")
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
if let Some(content) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Upload Texture node's old wrapper-network form maps onto its proto node form, which draws the executor from scope
|
||||
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
|
||||
&& name == "Upload Texture"
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
if let Some(content) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
@@ -2603,11 +2813,11 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// The removed-definition blocks above abort silently via `?` if their swap target ever leaves the catalog
|
||||
#[test]
|
||||
fn the_flip_reset_markers_keep_the_historical_merge_internals_spelling() {
|
||||
// The node itself is removed; the marker matches its spelling in
|
||||
// documents saved before the flip, which must stay stable.
|
||||
assert_eq!(FLIP_RESET_NODE_MARKERS, &["graphic_nodes::graphic::WriteAttributeNode"]);
|
||||
fn removed_definition_swap_targets_resolve() {
|
||||
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
|
||||
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,18 +4,19 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, GradientSpreadMethod, GradientType, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::{Color, Graphic};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
|
||||
@@ -100,21 +101,21 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
|
||||
delete_children: false,
|
||||
});
|
||||
|
||||
// Add a Flatten Path node after the merge
|
||||
let flatten_node_id = NodeId::new();
|
||||
let flatten_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::flatten_path::IDENTIFIER)
|
||||
.expect("Failed to create flatten node")
|
||||
// Add a Combine Paths node after the merge
|
||||
let combine_paths_node_id = NodeId::new();
|
||||
let combine_paths_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::combine_paths::IDENTIFIER)
|
||||
.expect("Failed to create combine paths node")
|
||||
.default_node_template();
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id: flatten_node_id,
|
||||
node_template: Box::new(flatten_node),
|
||||
node_id: combine_paths_node_id,
|
||||
node_template: Box::new(combine_paths_node),
|
||||
});
|
||||
responses.add(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: flatten_node_id,
|
||||
node_id: combine_paths_node_id,
|
||||
parent: first_layer,
|
||||
});
|
||||
|
||||
// Add a path node after the flatten node
|
||||
// Add a path node after the combine paths node
|
||||
let path_node_id = NodeId::new();
|
||||
let path_node = document_node_definitions::resolve_network_node_type("Path")
|
||||
.expect("Failed to create path node")
|
||||
@@ -274,14 +275,14 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
|
||||
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
|
||||
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
|
||||
}
|
||||
|
||||
/// Determine the input connector where the gradient chain enters the layer.
|
||||
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
|
||||
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
|
||||
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX)
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)
|
||||
} else {
|
||||
InputConnector::node(layer.to_node(), 1)
|
||||
}
|
||||
@@ -302,21 +303,21 @@ pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_i
|
||||
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)? else {
|
||||
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)? else {
|
||||
return None;
|
||||
};
|
||||
Some(*node_id)
|
||||
}
|
||||
|
||||
/// Get the gradient stops of a layer, if any.
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||
// Try to find the gradient stops value that is created by a Fill node first
|
||||
if let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
|
||||
return network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.get(&fill_node_id)
|
||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::INDEX))
|
||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX))
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
|
||||
}
|
||||
@@ -328,7 +329,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(stops.clone())
|
||||
}
|
||||
|
||||
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<GradientStops>`
|
||||
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<Gradient>`
|
||||
/// layer this is the layer's incoming footprint transform; for a Fill-owned gradient value it composes the layer's viewport
|
||||
/// transform with the [0,1]² → bounding-box mapping.
|
||||
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
|
||||
@@ -362,10 +363,10 @@ pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
|
||||
/// Get the current fill of a layer from the closest "Fill" node.
|
||||
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? else {
|
||||
let TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
color
|
||||
Some(*color)
|
||||
}
|
||||
|
||||
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
|
||||
@@ -569,8 +570,8 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashPatternInput::INDEX) {
|
||||
Some(TaggedValue::DashPattern(value)) => value.0.iter_element_values().copied().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
|
||||
@@ -625,7 +626,7 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
|
||||
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
|
||||
pub struct FillNodeGradient {
|
||||
pub stops: GradientStops,
|
||||
pub stops: Gradient,
|
||||
pub gradient_type: GradientType,
|
||||
pub spread_method: GradientSpreadMethod,
|
||||
pub transform: DAffine2,
|
||||
@@ -637,7 +638,7 @@ pub struct FillNodeGradient {
|
||||
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? else {
|
||||
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
|
||||
@@ -648,9 +649,11 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
let has_transform = matches!(fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
|
||||
let transform = match transform_input {
|
||||
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
|
||||
let transform = match (has_transform, transform_input) {
|
||||
(true, Some(&TaggedValue::DAffine2(value))) => value,
|
||||
(false, _) => initial_gradient_transform_for_bounding_box(bounding_box()),
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -664,9 +667,13 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
}
|
||||
/// Returns the stroke color from a layer's upstream Stroke node.
|
||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||
let color_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
||||
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
||||
match tagged {
|
||||
TaggedValue::Color(color) => Some(Some(*color)),
|
||||
value if value.is_no_paint() => Some(None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregated fill state across all selected non-artboard layers.
|
||||
@@ -686,7 +693,7 @@ pub struct SelectedStrokeState {
|
||||
}
|
||||
|
||||
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is the no-paint choice.
|
||||
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
@@ -698,9 +705,10 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
|
||||
let fill_choice = (|| {
|
||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
|
||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? {
|
||||
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
|
||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
||||
TaggedValue::Color(color) => Some(FillChoice::Solid(*color)),
|
||||
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
|
||||
value if value.is_no_paint() => Some(FillChoice::None),
|
||||
_ => None,
|
||||
}
|
||||
})()
|
||||
@@ -798,10 +806,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
|
||||
Some(TaggedValue::OptionalDAffine2(value)) => {
|
||||
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
|
||||
}
|
||||
let has_transform = matches!(read(graphene_std::vector::fill::HasTransformInput::INDEX), Some(TaggedValue::Bool(true)));
|
||||
let transform = match (has_transform, read(graphene_std::vector::fill::TransformInput::INDEX)) {
|
||||
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
||||
(false, _) => initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)),
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -824,8 +832,8 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(weight);
|
||||
@@ -976,8 +984,6 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
||||
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
|
||||
|
||||
// A leveled wire is typed by its element; depth rides the layout.
|
||||
let compiled = layer_input_type.compiled_nested_type();
|
||||
compiled == Some(&concrete!(Raster<CPU>)) || compiled == Some(&concrete!(Raster<GPU>))
|
||||
matches!(layer_input_type.compiled_element_name().as_deref(), Some("Raster<CPU>" | "Raster<GPU>"))
|
||||
}
|
||||
}
|
||||
@@ -421,7 +421,7 @@ impl ShapeState {
|
||||
(point.as_handle().is_some() && self.ignore_handles) || (point.as_anchor().is_some() && self.ignore_anchors)
|
||||
}
|
||||
|
||||
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a «Flatten Path» node.
|
||||
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a Combine Paths node.
|
||||
fn add_dummy_modification_to_trigger_graph_reorganization(layer: LayerNodeIdentifier, start_point: PointId, _end_point: PointId, responses: &mut VecDeque<Message>) {
|
||||
// Apply a zero-delta to one of the points to trigger reorganization
|
||||
let dummy_modification = VectorModificationType::ApplyPointDelta {
|
||||
|
||||
@@ -75,8 +75,8 @@ mod test_ellipse {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
|
||||
Some(ResolvedEllipse {
|
||||
radius_x: instrumented.grab_protonode_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_protonode_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
transform: document.metadata().transform_to_document(layer),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -214,7 +214,7 @@ pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, docu
|
||||
|
||||
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_lengths = Some(lengths.clone());
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::INDEX, TaggedValue::F64Array(lengths), responses);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashPatternInput::INDEX, TaggedValue::DashPattern(lengths.into()), responses);
|
||||
}
|
||||
|
||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
|
||||
@@ -11,9 +11,7 @@ use crate::messages::tool::common_functionality::transformation_cage::SelectedEd
|
||||
use crate::messages::tool::tool_messages::path_tool::PathOverlayMode;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::subpath::{Bezier, BezierHandles};
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
|
||||
@@ -568,11 +566,11 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
|
||||
}
|
||||
for _ in selected_layers {}
|
||||
|
||||
// Must be a layer of type List<Vector>
|
||||
// Must be a vector layer, at either rank
|
||||
let node_id = NodeGraphLayer::new(first_layer, network_interface).horizontal_layer_flow().nth(1)?;
|
||||
|
||||
let output_type = network_interface.output_type(&OutputConnector::node(node_id, 0), &[]);
|
||||
if output_type.compiled_nested_type() != Some(&concrete!(List<Vector>)) {
|
||||
if output_type.compiled_element_name().as_deref() != Some("Vector") {
|
||||
return None;
|
||||
}
|
||||
|
||||
|
||||
@@ -574,22 +574,12 @@ mod test_artboard {
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::list::List;
|
||||
|
||||
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
||||
/// occurrence yields one list rather than one element.
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
let mut artboards = List::new();
|
||||
for list in instrumented.grab_all_input_level::<graphene_std::graphic::extend::NewInput<Artboard>, Artboard>(&editor.runtime) {
|
||||
for index in 0..list.len() {
|
||||
if let Some(item) = list.clone_item(index) {
|
||||
artboards.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
artboards
|
||||
instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput<Artboard>>(&editor.runtime).flatten().collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
|
||||
@@ -205,21 +205,19 @@ impl Fsm for FillToolFsmState {
|
||||
#[cfg(test)]
|
||||
mod test_fill {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
/// Paint inputs are single-typed now, so the monitored wire carries the
|
||||
/// colors themselves and the `Graphic` conversion sits downstream of it.
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
||||
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
|
||||
instrumented
|
||||
.grab_all_input_level::<fill::FillInput, Color>(&editor.runtime)
|
||||
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
|
||||
.collect()
|
||||
instrumented.grab_all_input_as::<fill::FillInput<List<Graphic>>, Item<Color>>(&editor.runtime).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -249,7 +247,8 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::GREEN));
|
||||
let color = fills.first().unwrap().element();
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -261,6 +260,7 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::YELLOW));
|
||||
let color = fills.first().unwrap().element();
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ use glam::DMat2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStop, GradientStops, GradientStopsUI, GradientType, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, Gradient, GradientSpreadMethod, GradientStop, GradientType, GradientUI, build_transform_with_y_preservation};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
pub struct GradientTool {
|
||||
@@ -53,7 +53,7 @@ pub enum GradientToolMessage {
|
||||
CommitTransactionForColorStop,
|
||||
CloseStopColorPicker,
|
||||
UpdateStopColor { color: Color },
|
||||
UpdateStops { stops: GradientStopsUI },
|
||||
UpdateStops { stops: GradientUI },
|
||||
UpdateOptions { options: GradientOptionsUpdate },
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
}
|
||||
}
|
||||
ToolMessage::Gradient(GradientToolMessage::UpdateStops { stops }) => {
|
||||
apply_stops_update(&mut self.data, context, responses, GradientStops::from(&stops));
|
||||
apply_stops_update(&mut self.data, context, responses, Gradient::from(&stops));
|
||||
}
|
||||
ToolMessage::Gradient(GradientToolMessage::CloseStopColorPicker) => {
|
||||
if self.data.color_picker_transaction_open {
|
||||
@@ -264,7 +264,7 @@ impl LayoutHolder for GradientTool {
|
||||
.or_else(|| self.data.default_gradient_stops.clone())
|
||||
.map(FillChoice::Gradient)
|
||||
.unwrap_or_else(|| {
|
||||
FillChoice::Gradient(GradientStops::new([
|
||||
FillChoice::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -389,7 +389,7 @@ enum GradientSource {
|
||||
}
|
||||
|
||||
/// Get the gradient with appearance information from Fill node values, or the chain connected to Fill node / layer.
|
||||
fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(GradientStops, GradientAppearance, GradientSource)> {
|
||||
fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(Gradient, GradientAppearance, GradientSource)> {
|
||||
if let Some(stops) = get_gradient_stops(layer, network_interface) {
|
||||
// A Fill node holding a direct gradient value decodes through the shared reader
|
||||
if let Some(fill_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
|
||||
@@ -521,15 +521,15 @@ struct SelectedGradient {
|
||||
dragging: GradientDragTarget,
|
||||
/// Transform from the geometry's local gradient space to viewport space.
|
||||
gradient_space_transform: DAffine2,
|
||||
gradient: GradientStops,
|
||||
gradient: Gradient,
|
||||
appearance: GradientAppearance,
|
||||
initial_gradient: GradientStops,
|
||||
initial_gradient: Gradient,
|
||||
/// Transform from unit [0, 1] line to the geometry's local gradient space, the snapshot from `GradientAppearance.transform`.
|
||||
initial_gradient_transform: DAffine2,
|
||||
is_gradient_chain: bool,
|
||||
}
|
||||
|
||||
fn calculate_insertion(start: DVec2, end: DVec2, stops: &GradientStops, mouse: DVec2) -> Option<f64> {
|
||||
fn calculate_insertion(start: DVec2, end: DVec2, stops: &Gradient, mouse: DVec2) -> Option<f64> {
|
||||
let distance = (end - start).angle_to(mouse - start).sin() * (mouse - start).length();
|
||||
let projection = ((end - start).angle_to(mouse - start)).cos() * start.distance(mouse) / start.distance(end);
|
||||
|
||||
@@ -568,7 +568,7 @@ fn calculate_insertion(start: DVec2, end: DVec2, stops: &GradientStops, mouse: D
|
||||
}
|
||||
|
||||
impl SelectedGradient {
|
||||
pub fn new(gradient: GradientStops, appearance: GradientAppearance, source: GradientSource, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
|
||||
pub fn new(gradient: Gradient, appearance: GradientAppearance, source: GradientSource, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
|
||||
let gradient_space_transform = gradient_space_transform(layer, document);
|
||||
Self {
|
||||
layer: Some(layer),
|
||||
@@ -820,7 +820,7 @@ impl SelectedGradient {
|
||||
}
|
||||
|
||||
/// Send the four per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &GradientStops, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
responses.add(GraphOperationMessage::GradientStopsSet { layer, stops: gradient.clone() });
|
||||
responses.add(GraphOperationMessage::GradientTransformSet {
|
||||
layer,
|
||||
@@ -868,11 +868,11 @@ struct GradientToolData {
|
||||
has_selected_gradient: bool,
|
||||
/// Cached stops of the currently selected layer's gradient, mirrored into the control-bar widget.
|
||||
/// Independent of any in-progress drag (which uses `selected_gradient`) so it stays current after selection changes too.
|
||||
current_gradient_stops: Option<GradientStops>,
|
||||
current_gradient_stops: Option<Gradient>,
|
||||
/// User-customized default gradient stop colors: used when nothing that has a gradient is selected.
|
||||
/// `None` means to follow the working colors.
|
||||
/// Cleared on tool deactivation so each fresh activation starts from the working colors again.
|
||||
default_gradient_stops: Option<GradientStops>,
|
||||
default_gradient_stops: Option<Gradient>,
|
||||
/// Cached viewport-space orientation (true = predominantly rightward) of the selected gradient line.
|
||||
/// Used to refresh the control bar's "Reverse Direction" icon only when the line's apparent direction flips.
|
||||
gradient_orientation_rightward: bool,
|
||||
@@ -1496,7 +1496,7 @@ impl Fsm for GradientToolFsmState {
|
||||
// Generate a new gradient running primary → secondary so the default working colors
|
||||
// (primary = black, secondary = white) produce the expected black-to-white gradient
|
||||
None => (
|
||||
GradientStops::new([
|
||||
Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -1738,7 +1738,7 @@ impl Fsm for GradientToolFsmState {
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_stop_at_point(gradient: &mut GradientStops, point: DVec2, unit_to_viewport: DAffine2) -> Option<usize> {
|
||||
fn insert_stop_at_point(gradient: &mut Gradient, point: DVec2, unit_to_viewport: DAffine2) -> Option<usize> {
|
||||
let (start, end) = gradient_handle_positions(unit_to_viewport);
|
||||
let t = ((end - start).angle_to(point - start)).cos() * start.distance(point) / start.distance(end);
|
||||
(0. ..=1.).contains(&t).then(|| gradient.insert_stop(t))
|
||||
@@ -1831,8 +1831,8 @@ fn apply_gradient_update(
|
||||
data: &mut GradientToolData,
|
||||
context: &mut ToolActionMessageContext,
|
||||
responses: &mut VecDeque<Message>,
|
||||
condition: impl Fn((&GradientStops, &GradientAppearance)) -> bool,
|
||||
update: impl Fn((&mut GradientStops, &mut GradientAppearance)),
|
||||
condition: impl Fn((&Gradient, &GradientAppearance)) -> bool,
|
||||
update: impl Fn((&mut Gradient, &mut GradientAppearance)),
|
||||
) {
|
||||
let selected_layers: Vec<_> = context
|
||||
.document
|
||||
@@ -1888,7 +1888,7 @@ fn apply_gradient_update(
|
||||
/// Set new gradient stops on every selected layer's gradient. Unlike `apply_gradient_update`, this doesn't open its own
|
||||
/// transaction so it can be called repeatedly during a color picker drag and have all the changes coalesced into a
|
||||
/// single undo entry by the surrounding 'on_commit' callback.
|
||||
fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessageContext, responses: &mut VecDeque<Message>, new_gradient: GradientStops) {
|
||||
fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessageContext, responses: &mut VecDeque<Message>, new_gradient: Gradient) {
|
||||
let selected_layers: Vec<_> = context
|
||||
.document
|
||||
.network_interface
|
||||
@@ -1933,7 +1933,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
}
|
||||
|
||||
/// Find the first selected visible layer that has a gradient and return both the layer ID and its resolved gradient.
|
||||
fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<LayerNodeIdentifier>, Option<(GradientStops, GradientAppearance)>) {
|
||||
fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<LayerNodeIdentifier>, Option<(Gradient, GradientAppearance)>) {
|
||||
for layer in document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface) {
|
||||
if let Some((gradient, appearance, _source)) = resolve_gradient(layer, &document.network_interface) {
|
||||
return (Some(layer), Some((gradient, appearance)));
|
||||
@@ -1942,7 +1942,7 @@ fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<Laye
|
||||
(None, None)
|
||||
}
|
||||
|
||||
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<(GradientStops, GradientAppearance, GradientSource)> {
|
||||
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<(Gradient, GradientAppearance, GradientSource)> {
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
@@ -2012,21 +2012,22 @@ mod test_gradient {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
||||
use graphene_std::vector::{Gradient, GradientStop, fill};
|
||||
use graphene_std::{Graphic, NodeInputDecleration};
|
||||
|
||||
use super::gradient_space_transform;
|
||||
|
||||
struct ResolvedGradient {
|
||||
stops: GradientStops,
|
||||
stops: Gradient,
|
||||
spread_method: GradientSpreadMethod,
|
||||
transform: DAffine2,
|
||||
}
|
||||
|
||||
impl ResolvedGradient {
|
||||
fn new(stops: GradientStops, appearance: super::GradientAppearance) -> Self {
|
||||
fn new(stops: Gradient, appearance: super::GradientAppearance) -> Self {
|
||||
Self {
|
||||
stops,
|
||||
spread_method: appearance.spread_method,
|
||||
@@ -2057,7 +2058,7 @@ mod test_gradient {
|
||||
let fill_node_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface)?;
|
||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
|
||||
let stops = match fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? {
|
||||
let stops = match fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
||||
TaggedValue::Gradient(stops) => stops.clone(),
|
||||
_ => return None,
|
||||
};
|
||||
@@ -2067,8 +2068,9 @@ mod test_gradient {
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
|
||||
let has_transform = matches!(fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let local_transform = match fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::OptionalDAffine2(Some(value))) => value,
|
||||
Some(&TaggedValue::DAffine2(value)) if has_transform => value,
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -2146,7 +2148,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_node_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: TaggedValue::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2175,7 +2177,7 @@ mod test_gradient {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(gradient_node_id, 0),
|
||||
input_connector: InputConnector::node(fill_node_id, fill::FillInput::INDEX),
|
||||
input_connector: InputConnector::node(fill_node_id, fill::FillInput::<List<Graphic>>::INDEX),
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2183,7 +2185,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_node_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: TaggedValue::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2654,7 +2656,7 @@ mod test_gradient {
|
||||
// Create original transform for the control geometry and apply it
|
||||
let initial_start = DVec2::new(10., 50.);
|
||||
let initial_end = DVec2::new(200., 50.);
|
||||
let stops = GradientStops::new([
|
||||
let stops = Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2725,7 +2727,7 @@ mod test_gradient {
|
||||
let layer = create_gradient_list_layer(&mut editor).await;
|
||||
|
||||
// Set up a 3-stop gradient with distinct colors
|
||||
let original_stops = GradientStops::new([
|
||||
let original_stops = Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2826,7 +2828,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_value_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: TaggedValue::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
|
||||
@@ -10,11 +10,12 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, graphic_types};
|
||||
use graphene_std::{ATTR_TRANSFORM, Graphic, NodeInputDecleration};
|
||||
use graphene_std::{ATTR_TRANSFORM, Context, Graphic, NodeInputDecleration};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -25,7 +26,7 @@ pub use runtime_io::NodeRuntimeIO;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -58,9 +59,6 @@ pub struct NodeGraphExecutor {
|
||||
runtime_io: NodeRuntimeIO,
|
||||
current_execution_id: u64,
|
||||
futures: VecDeque<(u64, ExecutionContext)>,
|
||||
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
|
||||
/// (sent after an async source completion) finds its context again.
|
||||
last_execution_context: Option<(u64, ExecutionContext)>,
|
||||
node_graph_hash: u64,
|
||||
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
||||
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
|
||||
@@ -84,7 +82,7 @@ struct ExecutionContext {
|
||||
/// Set when this execution is a gradient-migration measurement run, carrying the "Fill" node (addressed by its enclosing
|
||||
/// network path) and its original relative gradient. The evaluated geometry is read back from the inspect result to size the
|
||||
/// gradient; such runs never touch the visible artwork. Carrying the entry keeps a stale re-dispatched response paired with the fill it measured.
|
||||
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
|
||||
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
@@ -94,7 +92,7 @@ struct ExecutionContext {
|
||||
#[derive(Debug, Clone)]
|
||||
struct GradientMigration {
|
||||
document_id: DocumentId,
|
||||
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
|
||||
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
resolution: UVec2,
|
||||
scale: f64,
|
||||
}
|
||||
@@ -110,7 +108,6 @@ impl NodeGraphExecutor {
|
||||
let node_executor = Self {
|
||||
futures: Default::default(),
|
||||
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
|
||||
last_execution_context: None,
|
||||
node_graph_hash: 0,
|
||||
current_execution_id: 0,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
@@ -378,22 +375,10 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
||||
let (_, execution_context) = self.futures.pop_front().expect("front was just matched");
|
||||
self.last_execution_context = Some((execution_id, execution_context.clone()));
|
||||
execution_context
|
||||
} else {
|
||||
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
|
||||
match &self.last_execution_context {
|
||||
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
|
||||
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
|
||||
continue;
|
||||
}
|
||||
execution_context.clone()
|
||||
}
|
||||
_ => panic!("InvalidGenerationId"),
|
||||
}
|
||||
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else {
|
||||
panic!("InvalidGenerationId")
|
||||
};
|
||||
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
|
||||
@@ -465,7 +450,6 @@ impl NodeGraphExecutor {
|
||||
resolved_types: incomplete_delta,
|
||||
node_graph_errors,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
return Err(format!("Node graph evaluation failed:\n{e}"));
|
||||
}
|
||||
@@ -476,7 +460,6 @@ impl NodeGraphExecutor {
|
||||
resolved_types: type_delta,
|
||||
node_graph_errors,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphUpdate::EyedropperPreview(raster) => {
|
||||
let (data, width, height) = raster.to_flat_u8();
|
||||
@@ -507,7 +490,7 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
// Snapshot the queue but leave `pending_gradient_bbox_bake` populated, so subsequent render requests keep deferring here (and hit the guard above); each entry is removed from the document as its bake lands.
|
||||
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
|
||||
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
|
||||
let Some((first_network_path, first_fill, first_gradient)) = remaining.front().cloned() else {
|
||||
return false;
|
||||
};
|
||||
@@ -534,7 +517,7 @@ impl NodeGraphExecutor {
|
||||
document_id: DocumentId,
|
||||
network_path: Vec<NodeId>,
|
||||
fill_node_id: NodeId,
|
||||
gradient: graphic_types::migrations::legacy::Gradient,
|
||||
gradient: graphic_types::migrations::legacy::LegacyGradient,
|
||||
resolution: UVec2,
|
||||
scale: f64,
|
||||
responses: &mut VecDeque<Message>,
|
||||
@@ -603,7 +586,7 @@ impl NodeGraphExecutor {
|
||||
&mut self,
|
||||
document: &mut DocumentMessageHandler,
|
||||
document_id: DocumentId,
|
||||
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient),
|
||||
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient),
|
||||
inspect_result: Option<InspectResult>,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
@@ -625,10 +608,14 @@ impl NodeGraphExecutor {
|
||||
if fill_transform_unbaked(document, &network_path, fill_node_id) {
|
||||
let absolute_gradient = gradient.to_absolute(bounding_box, item_transform);
|
||||
let gradient_transform = absolute_gradient.transform * absolute_gradient.to_transform();
|
||||
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
|
||||
let has_transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX);
|
||||
let transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&input, NodeInput::value(TaggedValue::OptionalDAffine2(Some(gradient_transform)), false), &network_path);
|
||||
.set_input(&has_transform_input, NodeInput::value(TaggedValue::Bool(true), false), &network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&transform_input, NodeInput::value(TaggedValue::DAffine2(gradient_transform), false), &network_path);
|
||||
}
|
||||
|
||||
// The transform is settled, so its entry no longer needs to persist for a retry on the next open
|
||||
@@ -832,16 +819,16 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether the fill node's transform input is still the unset `OptionalDAffine2(None)` placeholder that the migration leaves
|
||||
/// behind, meaning its gradient placement has not yet been baked (or set by the user), so a measured bake may safely be written.
|
||||
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
|
||||
/// (or set by the user), so a measured bake may safely be written.
|
||||
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
|
||||
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Some(node) = network.nodes.get(&fill_node_id) else { return false };
|
||||
matches!(
|
||||
node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::OptionalDAffine2(None))
|
||||
node.inputs.get(graphene_std::vector::fill::HasTransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::Bool(false))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -899,9 +886,18 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Extract a monitor node's captured output element.
|
||||
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
|
||||
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
|
||||
data.downcast_ref::<T>().cloned()
|
||||
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() {
|
||||
return Some(io.output.clone());
|
||||
}
|
||||
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
|
||||
return Some(io.output.clone());
|
||||
}
|
||||
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
|
||||
return Some(io.output.clone());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
@@ -917,9 +913,20 @@ mod test {
|
||||
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graphene_std::Context;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::memo::IORecord;
|
||||
use test_prelude::LayerNodeIdentifier;
|
||||
|
||||
/// A ranked input whose `Item<E>` Result carries an element `E`, recovered by `grab_ranked_input`.
|
||||
pub trait RankedResult {
|
||||
type Element: Send + Sync + Clone + 'static;
|
||||
}
|
||||
impl<E: Send + Sync + Clone + 'static> RankedResult for Item<E> {
|
||||
type Element = E;
|
||||
}
|
||||
|
||||
/// Stores all of the monitor nodes that have been attached to a graph
|
||||
#[derive(Default)]
|
||||
pub struct Instrumented {
|
||||
@@ -942,11 +949,17 @@ mod test {
|
||||
let mut monitor_node_ids = Vec::with_capacity(node.inputs.len());
|
||||
for input in &mut node.inputs {
|
||||
let node_id = NodeId::new();
|
||||
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
|
||||
monitor_nodes.push((old_input, node_id));
|
||||
path.push(node_id);
|
||||
monitor_node_ids.push(path.clone());
|
||||
path.pop();
|
||||
|
||||
// A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent
|
||||
if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
|
||||
monitor_nodes.push((old_input, node_id));
|
||||
}
|
||||
if let DocumentNodeImplementation::ProtoNode(identifier) = &mut node.implementation {
|
||||
path.push(*id);
|
||||
@@ -978,11 +991,23 @@ mod test {
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
{
|
||||
let element = dynamic.downcast_ref::<Input::Result>().cloned();
|
||||
if element.is_none() {
|
||||
Self::downcast_record::<Input::Result>(dynamic).or_else(|| {
|
||||
warn!("cannot downcast type for introspection");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
|
||||
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
|
||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Grab all of the values of the input every time it occurs in the graph.
|
||||
@@ -999,18 +1024,16 @@ mod test {
|
||||
.filter_map(Instrumented::downcast::<Input>) // Some might not resolve (e.g. generics that don't work properly)
|
||||
}
|
||||
|
||||
/// Grab all of the values of a LEVELED input, which introspects as its
|
||||
/// whole legacy list rather than as one element. `T` is the introspected
|
||||
/// element type, which differs from the declared one where a conversion
|
||||
/// sits downstream of the monitor.
|
||||
pub fn grab_all_input_level<'a, Input: NodeInputDecleration + 'a, T: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = List<T>> + 'a {
|
||||
/// Like [`Self::grab_all_input`], but downcasting the recorded values to `Output` instead of the marker's `Result`.
|
||||
/// Useful when a stored value's wire form (e.g. `Item<Color>`) differs from the declared row types the marker's generic accepts.
|
||||
pub fn grab_all_input_as<'a, Input: NodeInputDecleration + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
|
||||
self.protonodes_by_name
|
||||
.get(&Input::identifier())
|
||||
.map_or([].as_slice(), |x| x.as_slice())
|
||||
.iter()
|
||||
.filter_map(|inputs| inputs.get(Input::INDEX))
|
||||
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
|
||||
.filter_map(|dynamic| dynamic.downcast_ref::<List<T>>().cloned())
|
||||
.filter_map(Instrumented::downcast_record::<Output>)
|
||||
}
|
||||
|
||||
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||
@@ -1024,6 +1047,17 @@ mod test {
|
||||
Self::downcast::<Input>(dynamic)
|
||||
}
|
||||
|
||||
/// Grabs a ranked (`Item<E>`) input's recorded value as its bare element `E`.
|
||||
/// A stored value materializes as an `Item<E>` wire, so the monitor records the whole cell and this unwraps its element.
|
||||
pub fn grab_ranked_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<<Input::Result as RankedResult>::Element>
|
||||
where
|
||||
Input::Result: RankedResult,
|
||||
{
|
||||
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
|
||||
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
|
||||
Self::downcast_record::<Item<<Input::Result as RankedResult>::Element>>(dynamic).map(|item| item.into_element())
|
||||
}
|
||||
|
||||
pub fn grab_input_from_layer<Input: NodeInputDecleration>(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
|
||||
@@ -3,24 +3,25 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::core_types::gpoll::GPoll;
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::ops::Convert;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||
use graphene_std::transform::RenderQuality;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use graphene_std::{Artboard, Context, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use spin::Mutex;
|
||||
use std::sync::Arc;
|
||||
@@ -39,9 +40,6 @@ pub struct NodeRuntime {
|
||||
editor_preferences: EditorPreferences,
|
||||
old_graph: Option<NodeNetwork>,
|
||||
update_thumbnails: bool,
|
||||
graph_runtime: Arc<DynGraphRuntime>,
|
||||
/// The last plain render request, replayed when an async source completion marks the graph dirty.
|
||||
last_render: Option<ExecutionRequest>,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
@@ -121,86 +119,20 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl TokioSpawner {
|
||||
pub fn new() -> Self {
|
||||
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Default for TokioSpawner {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||
let _guard = runtime.enter();
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
runtime.spawn(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
|
||||
/// [`NodeRuntime`] from one, so shut down in the background instead.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Drop for TokioSpawner {
|
||||
fn drop(&mut self) {
|
||||
if let Some(runtime) = self.0.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub struct WasmSpawner;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl Spawner for WasmSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeRuntime {
|
||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
||||
#[cfg(target_family = "wasm")]
|
||||
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.set_runtime(Arc::clone(&graph_runtime));
|
||||
|
||||
Self {
|
||||
executor,
|
||||
executor: DynamicExecutor::default(),
|
||||
receiver,
|
||||
sender: InternalNodeGraphUpdateSender(sender.clone()),
|
||||
editor_preferences: EditorPreferences::default(),
|
||||
old_graph: None,
|
||||
resources: ResourceRegistry::default(),
|
||||
update_thumbnails: true,
|
||||
graph_runtime: Arc::clone(&graph_runtime),
|
||||
last_render: None,
|
||||
|
||||
editor_api: PlatformEditorApi {
|
||||
editor_preferences: Box::new(EditorPreferences::default()),
|
||||
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
|
||||
runtime: RuntimeHandle(graph_runtime),
|
||||
|
||||
#[cfg(not(test))]
|
||||
application_io: None,
|
||||
@@ -225,11 +157,6 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.executor.take_dirty()
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Option<Texture> {
|
||||
let mut preferences = None;
|
||||
let mut graph = None;
|
||||
@@ -246,9 +173,6 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let for_export = execution_request.render_config.for_export;
|
||||
if !for_export {
|
||||
self.last_render = Some(execution_request.clone());
|
||||
}
|
||||
|
||||
execution = Some(request);
|
||||
|
||||
@@ -269,10 +193,6 @@ impl NodeRuntime {
|
||||
eyedropper.render_config.pointer = execution.render_config.pointer;
|
||||
}
|
||||
|
||||
if self.executor.take_dirty() && execution.is_none() {
|
||||
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
|
||||
}
|
||||
|
||||
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
|
||||
|
||||
for request in requests {
|
||||
@@ -283,12 +203,11 @@ impl NodeRuntime {
|
||||
application_io: self.editor_api.application_io.clone(),
|
||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||
editor_preferences: Box::new(preferences),
|
||||
runtime: self.editor_api.runtime.clone(),
|
||||
}
|
||||
.into();
|
||||
if let Some(graph) = self.old_graph.clone() {
|
||||
// We ignore this result as compilation errors should have been reported in an earlier iteration
|
||||
let _ = self.update_network(graph);
|
||||
let _ = self.update_network(graph).await;
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
@@ -303,7 +222,7 @@ impl NodeRuntime {
|
||||
self.resources = resources;
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
let result = self.update_network(network);
|
||||
let result = self.update_network(network).await;
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
|
||||
self.update_thumbnails = true;
|
||||
@@ -318,7 +237,7 @@ impl NodeRuntime {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
|
||||
let result = self.execute_network(render_config);
|
||||
let result = self.execute_network(render_config).await;
|
||||
let mut responses = VecDeque::new();
|
||||
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
|
||||
if !render_config.for_eyedropper {
|
||||
@@ -339,10 +258,10 @@ impl NodeRuntime {
|
||||
.application_io
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.gpu_executor_arc()
|
||||
.gpu_executor()
|
||||
.expect("GPU executor should be available when we receive a texture");
|
||||
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
|
||||
|
||||
let (data, width, height) = raster_cpu.to_flat_u8();
|
||||
|
||||
@@ -363,10 +282,10 @@ impl NodeRuntime {
|
||||
.application_io
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.gpu_executor_arc()
|
||||
.gpu_executor()
|
||||
.expect("GPU executor should be available when we receive a texture");
|
||||
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
|
||||
|
||||
self.sender.send_eyedropper_preview(raster_cpu);
|
||||
continue;
|
||||
@@ -426,7 +345,7 @@ impl NodeRuntime {
|
||||
None
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
|
||||
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
@@ -437,7 +356,7 @@ impl NodeRuntime {
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
let c = Compiler {};
|
||||
let proto_network = match c.compile_single(scoped_network, &interpreted_executor::node_registry::NODE_REGISTRY) {
|
||||
let proto_network = match c.compile_single(scoped_network) {
|
||||
Ok(network) => network,
|
||||
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
|
||||
};
|
||||
@@ -449,24 +368,20 @@ impl NodeRuntime {
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
self.executor.update(proto_network).await.map_err(|(types, e)| {
|
||||
self.node_graph_errors.clone_from(&e);
|
||||
(types, format!("{e:?}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
|
||||
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
|
||||
match (&self.executor).execute(render_config).map_err(|e| e.to_string())? {
|
||||
GPoll::Final(value) | GPoll::Partial(value) => Ok(value),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
Ok(value)
|
||||
}
|
||||
GPoll::Pending => Err("Node graph evaluation is pending".to_string()),
|
||||
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}")),
|
||||
match self.executor.input_type() {
|
||||
Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()),
|
||||
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
|
||||
Some(t) => Err(format!("Invalid input type {t:?}")),
|
||||
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,63 +406,66 @@ impl NodeRuntime {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Read the monitored run directly, inside the introspection window
|
||||
let thumbnail_renders = &mut self.thumbnail_renders;
|
||||
let vector_modify = &mut self.vector_modify;
|
||||
let result = self.executor.introspect_with(monitor_node_path, |layout, batch, _arena| {
|
||||
use graphene_std::core_types::record::{Group, GroupItem, RunView};
|
||||
let type_id = layout.element.type_id;
|
||||
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||
if type_id == std::any::TypeId::of::<Graphic>() {
|
||||
if update_thumbnails {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
|
||||
let group = Graphic::Group(Group { row: None, content: item });
|
||||
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &group, bounds, responses)
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
|
||||
// clips content to those rectangles so anything outside isn't visible
|
||||
else if type_id == std::any::TypeId::of::<Artboard>() {
|
||||
if update_thumbnails {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<Artboard>::new(&item)?;
|
||||
let bounds = artboard_clip_bounds(&run);
|
||||
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
// Vector run: vector modifications
|
||||
else if type_id == std::any::TypeId::of::<Vector>() {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<Vector>::new(&item)?;
|
||||
use graphene_std::core_types::lane::LaneSource;
|
||||
vector_modify.insert(parent_network_node_id, run.element(0).cloned().unwrap_or_default());
|
||||
Some(())
|
||||
}
|
||||
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
||||
else if type_id == std::any::TypeId::of::<String>() {
|
||||
if update_thumbnails {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<String>::new(&item)?;
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
|
||||
}
|
||||
Some(())
|
||||
} else {
|
||||
log::warn!("Failed to read monitor node output {parent_network_node_id:?}");
|
||||
Some(())
|
||||
}
|
||||
});
|
||||
if result.is_err() {
|
||||
// Extract the monitor node's stored `Graphic` data
|
||||
let Ok(introspected_data) = self.executor.introspect(monitor_node_path) else {
|
||||
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
||||
#[cfg(debug_assertions)]
|
||||
warn!("Failed to introspect monitor node {}", result.unwrap_err());
|
||||
warn!("Failed to introspect monitor node {}", self.executor.introspect(monitor_node_path).unwrap_err());
|
||||
continue;
|
||||
};
|
||||
|
||||
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
|
||||
// clips content to those rectangles so anything outside isn't visible
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Artboard>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = artboard_clip_bounds(&io.output);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Vector list: vector modifications
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Vector>>>() {
|
||||
// Insert the vector modify
|
||||
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
|
||||
}
|
||||
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Rank-0 wires record single items; each arm mirrors its list counterpart through a singleton raise
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Graphic>>>() {
|
||||
if update_thumbnails {
|
||||
let singleton = List::new_from_item(io.output.clone());
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&singleton, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
|
||||
}
|
||||
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Artboard>>>() {
|
||||
if update_thumbnails {
|
||||
let singleton = List::new_from_item(io.output.clone());
|
||||
let bounds = artboard_clip_bounds(&singleton);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
|
||||
}
|
||||
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Vector>>>() {
|
||||
self.vector_modify.insert(parent_network_node_id, io.output.element().clone());
|
||||
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<String>>>() {
|
||||
if update_thumbnails {
|
||||
let singleton = List::new_from_item(io.output.clone());
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&singleton, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Other
|
||||
else {
|
||||
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -615,12 +533,11 @@ impl NodeRuntime {
|
||||
|
||||
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
|
||||
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
|
||||
fn artboard_clip_bounds<'a, S: graphene_std::core_types::lane::LaneSource<Element = Artboard<'a>>>(artboards: &S) -> RenderBoundingBox {
|
||||
use graphene_std::core_types::attribute::{Dimensions, Location};
|
||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
||||
let mut combined: Option<[DVec2; 2]> = None;
|
||||
for index in 0..artboards.lane_count() {
|
||||
let location: DVec2 = artboards.attr::<Location>(index);
|
||||
let dimensions: DVec2 = artboards.attr::<Dimensions>(index);
|
||||
for index in 0..artboards.len() {
|
||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||
let bounds = [location, location + dimensions];
|
||||
combined = Some(match combined {
|
||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||
@@ -649,6 +566,14 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
[center - half, center + half]
|
||||
}
|
||||
|
||||
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let runtime = NODE_RUNTIME.lock();
|
||||
if let Some(ref mut runtime) = runtime.as_ref() {
|
||||
return runtime.executor.introspect(path);
|
||||
}
|
||||
Err(IntrospectError::RuntimeNotReady)
|
||||
}
|
||||
|
||||
pub async fn run_node_graph() -> (bool, Option<Texture>) {
|
||||
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
|
||||
if let Some(ref mut runtime) = runtime.as_mut() {
|
||||
@@ -668,20 +593,12 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
|
||||
let node_runtime = NODE_RUNTIME.lock();
|
||||
if let Some(node_runtime) = &*node_runtime {
|
||||
node_runtime.graph_runtime.set_notifier(notifier);
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeRuntime {
|
||||
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
|
||||
self.editor_api = PlatformEditorApi {
|
||||
application_io: Some(application_io.into()),
|
||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||
editor_preferences: Box::new(self.editor_preferences.clone()),
|
||||
runtime: self.editor_api.runtime.clone(),
|
||||
}
|
||||
.into();
|
||||
}
|
||||
|
||||
@@ -53,27 +53,6 @@ impl EditorTestUtils {
|
||||
}
|
||||
runtime.run().await;
|
||||
|
||||
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
|
||||
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
|
||||
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
|
||||
// dispatched, or the editor's type map desyncs permanently.
|
||||
while runtime.take_dirty() {
|
||||
let mut superseded_messages = VecDeque::new();
|
||||
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
|
||||
for message in superseded_messages {
|
||||
editor.handle_message(message);
|
||||
}
|
||||
|
||||
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
runtime.run().await;
|
||||
}
|
||||
|
||||
let mut messages = VecDeque::new();
|
||||
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
|
||||
return Err(format!("Graph should render\n\n{e}"));
|
||||
|
||||
@@ -320,7 +320,7 @@
|
||||
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||
<svg>
|
||||
{#each $nodeGraphWires.values() as map}
|
||||
{#each map.values() as { pathString, dataType, thick, dashed }}
|
||||
{#each map.values() as { pathString, centerPathString, dataType, thick, dashed }}
|
||||
{#if thick}
|
||||
<path
|
||||
d={pathString}
|
||||
@@ -329,6 +329,8 @@
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
|
||||
<path d={centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
|
||||
{/if}
|
||||
{/each}
|
||||
{/each}
|
||||
@@ -561,7 +563,10 @@
|
||||
{#if node.primaryOutput.connectedTo.length > 0}
|
||||
<path d="M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z" fill="var(--data-color)" />
|
||||
{#if node.primaryOutputConnectedToLayer}
|
||||
<path d="M0,-3.5h8v8l-2.521,-1.681a2.666,2.666,0,0,0,-2.959,0l-2.52,1.681z" fill="var(--data-color-dim)" />
|
||||
<path
|
||||
d="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 ZM5,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"
|
||||
fill="var(--data-color-dim)"
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
<path d="M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z" fill="var(--data-color-dim)" />
|
||||
@@ -583,7 +588,10 @@
|
||||
{#if node.primaryInput?.connectedTo !== "Connected to nothing."}
|
||||
<path d="M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z" fill="var(--data-color)" />
|
||||
{#if node.primaryInputConnectedToLayer}
|
||||
<path d="M0,10.95l2.52,-1.69c0.89,-0.6,2.06,-0.6,2.96,0l2.52,1.69v5.05h-8v-5.05z" fill="var(--data-color-dim)" />
|
||||
<path
|
||||
d="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 ZM5,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"
|
||||
fill="var(--data-color-dim)"
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
<path d="M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z" fill="var(--data-color-dim)" />
|
||||
@@ -679,15 +687,27 @@
|
||||
<div class="wires">
|
||||
<svg>
|
||||
{#each $nodeGraphWires.values() as map}
|
||||
{#each map.values() as { pathString, dataType, thick, dashed }}
|
||||
{#each map.values() as { pathString, dataType, thick, dashed, isList }}
|
||||
{#if !thick}
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="2px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
{#if isList}
|
||||
<!-- A rank-1 List wire reads as two parallel lines: a triple-width data line split down the middle by a 1x background-colored overlay -->
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="4px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
<path d={pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={`3,${dashed ? 2 : 0}`} />
|
||||
{:else}
|
||||
<path
|
||||
d={pathString}
|
||||
style:--data-line-width="2px"
|
||||
style:--data-color={`var(--color-data-${dataType.toLowerCase()})`}
|
||||
style:--data-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
|
||||
style:--data-dasharray={`3,${dashed ? 2 : 0}`}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
{/each}
|
||||
{/each}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { createEventDispatcher } from "svelte";
|
||||
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import { contrastingOutlineFactor, fillChoiceUIColor, fillChoiceUIGradientStops } from "/src/utility-functions/colors";
|
||||
import { contrastingOutlineFactor, fillChoiceUIColor, fillChoiceUIGradient } from "/src/utility-functions/colors";
|
||||
import type { FillChoiceUI, MenuDirection, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const dispatch = createEventDispatcher<{ value: FillChoiceUI; startHistoryTransaction: undefined }>();
|
||||
@@ -29,10 +29,10 @@
|
||||
|
||||
$: outlineFactor = contrastingOutlineFactor(value, "--color-3-darkgray", 0.01);
|
||||
$: outlined = outlineFactor > 0.0001;
|
||||
$: gradientStops = fillChoiceUIGradientStops(value);
|
||||
$: gradient = fillChoiceUIGradient(value);
|
||||
$: solidColor = fillChoiceUIColor(value);
|
||||
$: none = value === "None";
|
||||
$: transparency = gradientStops ? gradientStops.color.some((color) => color.alpha < 255) : solidColor ? solidColor.alpha < 255 : false;
|
||||
$: transparency = gradient ? gradient.color.some((color) => color.alpha < 255) : solidColor ? solidColor.alpha < 255 : false;
|
||||
</script>
|
||||
|
||||
<LayoutCol
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { FillChoiceUI, GradientStopsUI, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { FillChoiceUI, GradientUI, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// Channels can have any range (0-1, 0-255, 0-100, 0-360) in the context they are being used in, these are just containers for the numbers
|
||||
export type HSV = { h: number; s: number; v: number };
|
||||
@@ -167,12 +167,12 @@ export function contrastingOutlineFactor(value: FillChoiceUI, proximityColor: st
|
||||
return (1 - Math.min(distance / proximityRange, 1)) * (1 - sRgba8ToHSV(color).s);
|
||||
};
|
||||
|
||||
const gradientStops = fillChoiceUIGradientStops(value);
|
||||
if (gradientStops) {
|
||||
if (gradientStops.color.length === 0) return 0;
|
||||
const gradient = fillChoiceUIGradient(value);
|
||||
if (gradient) {
|
||||
if (gradient.color.length === 0) return 0;
|
||||
|
||||
const first = contrast(gradientStops.color[0]);
|
||||
const last = contrast(gradientStops.color[gradientStops.color.length - 1]);
|
||||
const first = contrast(gradient.color[0]);
|
||||
const last = contrast(gradient.color[gradient.color.length - 1]);
|
||||
|
||||
return Math.min(first, last);
|
||||
}
|
||||
@@ -182,7 +182,7 @@ export function contrastingOutlineFactor(value: FillChoiceUI, proximityColor: st
|
||||
|
||||
// GRADIENT UTILITY FUNCTIONS
|
||||
|
||||
export function isGradientStopsUI(value: unknown): value is GradientStopsUI {
|
||||
export function isGradientUI(value: unknown): value is GradientUI {
|
||||
return typeof value === "object" && value !== null && "position" in value && "midpoint" in value && "color" in value;
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ export function fillChoiceUIColor(value: FillChoiceUI): SRGBA8 | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function fillChoiceUIGradientStops(value: FillChoiceUI): GradientStopsUI | undefined {
|
||||
export function fillChoiceUIGradient(value: FillChoiceUI): GradientUI | undefined {
|
||||
if (typeof value === "object" && "Gradient" in value) return value.Gradient;
|
||||
return undefined;
|
||||
}
|
||||
@@ -201,6 +201,6 @@ export function fillChoiceUIGradientStops(value: FillChoiceUI): GradientStopsUI
|
||||
export function parseFillChoiceUI(value: unknown): FillChoiceUI {
|
||||
if (value === "None" || value === undefined || value === null) return "None";
|
||||
if (typeof value === "object" && value !== null && "Solid" in value && isSRgba8(value.Solid)) return { Solid: value.Solid };
|
||||
if (typeof value === "object" && value !== null && "Gradient" in value && isGradientStopsUI(value.Gradient)) return { Gradient: value.Gradient };
|
||||
if (typeof value === "object" && value !== null && "Gradient" in value && isGradientUI(value.Gradient)) return { Gradient: value.Gradient };
|
||||
return "None";
|
||||
}
|
||||
@@ -13,10 +13,10 @@ license = "Apache-2.0"
|
||||
[features]
|
||||
default = ["gpu", "shader-nodes", "web"]
|
||||
web = ["editor", "editor?/wasm"]
|
||||
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:wgpu"]
|
||||
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:node-macro", "dep:wgpu"]
|
||||
gpu = ["editor?/gpu"]
|
||||
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
|
||||
native = []
|
||||
native = ["node-macro?/disable-registration"]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
@@ -39,6 +39,7 @@ wgpu = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tsify = { workspace = true }
|
||||
node-macro = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_bytes = { workspace = true }
|
||||
|
||||
@@ -17,7 +17,6 @@ mod editor_commands {
|
||||
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
||||
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||
use editor::messages::portfolio::utility_types::PanelGroupId;
|
||||
@@ -516,11 +515,11 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Creates a new document node in the node graph
|
||||
fn create_node(node_type: String, x: i32, y: i32) -> Message {
|
||||
fn create_node(node_type: Any, x: i32, y: i32) -> Message {
|
||||
let id = NodeId::new();
|
||||
NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(id),
|
||||
node_type: DefinitionIdentifier::from_serialized(&node_type),
|
||||
node_type: node_type.cast(),
|
||||
xy: Some((x / 24, y / 24)),
|
||||
add_transaction: true,
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ extern crate proc_macro;
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Span;
|
||||
use quote::quote;
|
||||
use syn::{DeriveInput, GenericParam, Lifetime, TypeParamBound, parse_macro_input};
|
||||
use syn::{DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound, parse_macro_input};
|
||||
|
||||
/// Derives an implementation for the [`DynAny`] trait.
|
||||
///
|
||||
@@ -40,45 +40,37 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream {
|
||||
let struct_name = &ast.ident;
|
||||
let generics = &ast.generics;
|
||||
|
||||
let static_params = generic_arguments(generics, "'static");
|
||||
let dyn_params = generic_arguments(generics, "'dyn_any");
|
||||
let static_params = replace_lifetimes(generics, "'static");
|
||||
let dyn_params = replace_lifetimes(generics, "'dyn_any");
|
||||
|
||||
let impl_params = generics.params.iter().map(|param| match param {
|
||||
GenericParam::Type(t) => {
|
||||
let mut t = t.clone();
|
||||
t.bounds.push(TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())));
|
||||
quote! {#t}
|
||||
}
|
||||
param => quote! {#param},
|
||||
});
|
||||
let old_params = &generics.params.iter().collect::<Vec<_>>();
|
||||
quote! {
|
||||
unsafe impl<'dyn_any, #(#impl_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
|
||||
unsafe impl<'dyn_any, #(#old_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
|
||||
type Static = #struct_name <#(#static_params,)*>;
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// The struct's generic parameters as argument tokens: bare idents for type
|
||||
/// and const parameters (bounds are illegal in argument position), the
|
||||
/// replacement for lifetimes.
|
||||
fn generic_arguments(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
|
||||
fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
|
||||
generics
|
||||
.params
|
||||
.iter()
|
||||
.map(|param| match param {
|
||||
GenericParam::Lifetime(_) => {
|
||||
let lifetime = Lifetime::new(replacement, Span::call_site());
|
||||
quote! {#lifetime}
|
||||
}
|
||||
GenericParam::Type(t) => {
|
||||
let ident = &t.ident;
|
||||
quote! {#ident}
|
||||
}
|
||||
GenericParam::Const(c) => {
|
||||
let ident = &c.ident;
|
||||
quote! {#ident}
|
||||
}
|
||||
.map(|param| {
|
||||
let param = match param {
|
||||
GenericParam::Lifetime(_) => GenericParam::Lifetime(LifetimeParam::new(Lifetime::new(replacement, Span::call_site()))),
|
||||
GenericParam::Type(t) => {
|
||||
let mut t = t.clone();
|
||||
t.bounds.iter_mut().for_each(|bond| {
|
||||
if let TypeParamBound::Lifetime(t) = bond {
|
||||
*t = Lifetime::new(replacement, Span::call_site())
|
||||
}
|
||||
});
|
||||
GenericParam::Type(t.clone())
|
||||
}
|
||||
c => c.clone(),
|
||||
};
|
||||
quote! {#param}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
@@ -74,7 +74,6 @@ mmap-io = { workspace = true }
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
interpreted-executor = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
criterion = { workspace = true }
|
||||
gungraun = { workspace = true }
|
||||
|
||||
@@ -6,13 +6,10 @@ use graph_craft::util::DEMO_ART;
|
||||
fn compile_to_proto(c: &mut Criterion) {
|
||||
use graph_craft::util::{compile, load_from_name};
|
||||
let mut c = c.benchmark_group("Compile Network cold");
|
||||
let registry = &interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
|
||||
for name in DEMO_ART {
|
||||
let network = load_from_name(name);
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(|| network.clone(), |network| compile(black_box(network), registry), criterion::BatchSize::SmallInput)
|
||||
});
|
||||
c.bench_function(name, |b| b.iter_batched(|| network.clone(), |network| compile(black_box(network)), criterion::BatchSize::SmallInput));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use gungraun::prelude::*;
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
|
||||
pub fn compile_to_proto(_input: NodeNetwork) {
|
||||
std::hint::black_box(compile(_input, &interpreted_executor::node_registry::NODE_REGISTRY));
|
||||
std::hint::black_box(compile(_input));
|
||||
}
|
||||
|
||||
library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto);
|
||||
|
||||
@@ -9,7 +9,7 @@ pub use graphene_application_io::ApplicationIo;
|
||||
#[derive(Default)]
|
||||
pub struct PlatformApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: Option<std::sync::Arc<WgpuExecutor>>,
|
||||
gpu_executor: Option<WgpuExecutor>,
|
||||
resources: Option<Box<dyn resource::LoadResource>>,
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ impl PlatformApplicationIo {
|
||||
|
||||
Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor.map(std::sync::Arc::new),
|
||||
gpu_executor: executor,
|
||||
resources: None,
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl PlatformApplicationIo {
|
||||
set_wgpu_available(wgpu_available);
|
||||
|
||||
Self {
|
||||
gpu_executor: executor.map(std::sync::Arc::new),
|
||||
gpu_executor: executor,
|
||||
resources: None,
|
||||
}
|
||||
}
|
||||
@@ -57,12 +57,7 @@ impl ApplicationIo for PlatformApplicationIo {
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
self.gpu_executor.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor_arc(&self) -> Option<std::sync::Arc<Self::Executor>> {
|
||||
self.gpu_executor.clone()
|
||||
self.gpu_executor.as_ref()
|
||||
}
|
||||
|
||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
||||
|
||||
@@ -8,6 +8,7 @@ pub use core_types::uuid::generate_uuid;
|
||||
use core_types::{Context, ContextDependencies, Cow, MemoHash, ProtoNodeIdentifier, Type};
|
||||
use dyn_any::DynAny;
|
||||
use glam::IVec2;
|
||||
use log::Metadata;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
@@ -57,8 +58,7 @@ pub struct DocumentNode {
|
||||
#[serde(default)]
|
||||
pub skip_deduplication: bool,
|
||||
/// List of Extract and Inject annotations for the Context.
|
||||
/// Resolved from the registry at compile time; only code-built wrapper nodes carry a declaration here.
|
||||
#[serde(skip)]
|
||||
#[serde(default)]
|
||||
pub context_features: ContextDependencies,
|
||||
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
||||
#[serde(skip)]
|
||||
@@ -121,6 +121,18 @@ impl OriginalLocation {
|
||||
}
|
||||
}
|
||||
impl DocumentNode {
|
||||
/// Normalizes this node's stored types (call argument, `Import` input types, `TypeDefault` value payloads, and any nested network) to their structural form.
|
||||
/// Applied once at ingestion (document migration and clipboard paste) so no name-encoded ranked type enters a live document.
|
||||
pub fn normalize_stored_types(&mut self) {
|
||||
self.call_argument = self.call_argument.clone().normalize_rank();
|
||||
for input in &mut self.inputs {
|
||||
normalize_input_stored_type(input);
|
||||
}
|
||||
if let Some(network) = self.implementation.get_network_mut() {
|
||||
network.normalize_stored_types();
|
||||
}
|
||||
}
|
||||
|
||||
/// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`].
|
||||
pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize, source: impl Iterator<Item = Source>, skip: usize) {
|
||||
let (index, _) = self
|
||||
@@ -167,8 +179,6 @@ impl DocumentNode {
|
||||
original_location: self.original_location,
|
||||
skip_deduplication: self.skip_deduplication,
|
||||
context_features: self.context_features,
|
||||
lane_invariant_inputs: 0,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,14 +227,12 @@ impl InlineRust {
|
||||
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DocumentNodeMetadata {
|
||||
DocumentNodePath,
|
||||
SourceId,
|
||||
}
|
||||
|
||||
impl DocumentNodeMetadata {
|
||||
pub fn ty(&self) -> Type {
|
||||
match self {
|
||||
DocumentNodeMetadata::DocumentNodePath => concrete!(Vec<NodeId>),
|
||||
DocumentNodeMetadata::SourceId => concrete!(u64),
|
||||
DocumentNodeMetadata::DocumentNodePath => item!(core_types::list::NodeIdPath),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,10 +247,10 @@ impl NodeInput {
|
||||
Self::Value { tagged_value, exposed }
|
||||
}
|
||||
|
||||
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(td)`, recording only the
|
||||
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(ty)`, recording only the
|
||||
/// type so the runtime materializes its default rather than baking a placeholder value into the saved document.
|
||||
pub fn type_default(td: core_types::TypeDescriptor, exposed: bool) -> Self {
|
||||
Self::value(TaggedValue::TypeDefault(td), exposed)
|
||||
pub fn type_default(ty: Type, exposed: bool) -> Self {
|
||||
Self::value(TaggedValue::TypeDefault(ty.normalize_rank()), exposed)
|
||||
}
|
||||
|
||||
pub const fn import(import_type: Type, import_index: usize) -> Self {
|
||||
@@ -274,10 +282,11 @@ impl NodeInput {
|
||||
match self {
|
||||
NodeInput::Node { .. } => unreachable!("ty() called on NodeInput::Node"),
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
// Stored import types are normalized to their structural form once at document migration
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
|
||||
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
|
||||
NodeInput::Reflection(metadata) => metadata.ty(),
|
||||
NodeInput::Reflection(_) => concrete!(Metadata),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,7 +736,33 @@ impl ScopeChain<'_> {
|
||||
}
|
||||
|
||||
/// Functions for compiling the network
|
||||
/// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload.
|
||||
fn normalize_input_stored_type(input: &mut NodeInput) {
|
||||
match input {
|
||||
NodeInput::Import { import_type, .. } => *import_type = import_type.clone().normalize_rank(),
|
||||
NodeInput::Value { tagged_value, .. } => {
|
||||
if let TaggedValue::TypeDefault(ty) = &**tagged_value {
|
||||
let normalized = ty.clone().normalize_rank();
|
||||
if normalized != *ty {
|
||||
*tagged_value = TaggedValue::TypeDefault(normalized).into();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeNetwork {
|
||||
/// Normalizes every stored type in the network (exports and each node's types) to the structural form, recursively.
|
||||
pub fn normalize_stored_types(&mut self) {
|
||||
for export in &mut self.exports {
|
||||
normalize_input_stored_type(export);
|
||||
}
|
||||
for node in self.nodes.values_mut() {
|
||||
node.normalize_stored_types();
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace all references in the graph of a node ID with a new node ID defined by the function `f`.
|
||||
pub fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId + Copy) {
|
||||
self.exports.iter_mut().for_each(|output| {
|
||||
@@ -883,7 +918,7 @@ impl NodeNetwork {
|
||||
|
||||
// Replace value inputs with dedicated value nodes
|
||||
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
|
||||
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id, Some(&mut node.context_features));
|
||||
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id);
|
||||
}
|
||||
|
||||
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
|
||||
@@ -902,7 +937,6 @@ impl NodeNetwork {
|
||||
gen_id,
|
||||
map_ids,
|
||||
id,
|
||||
None,
|
||||
);
|
||||
|
||||
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
|
||||
@@ -983,12 +1017,6 @@ impl NodeNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
fn source_id_for_path(path: &[NodeId]) -> u64 {
|
||||
let mut hasher = graphene_hash::FxHasher64::new();
|
||||
path.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn replace_value_inputs_with_nodes(
|
||||
inputs: &mut [NodeInput],
|
||||
@@ -997,7 +1025,6 @@ impl NodeNetwork {
|
||||
gen_id: impl Fn() -> NodeId + Copy,
|
||||
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
|
||||
id: NodeId,
|
||||
mut context_features: Option<&mut ContextDependencies>,
|
||||
) {
|
||||
// Replace value exports and imports with value nodes, added inside the nested network
|
||||
for export in inputs {
|
||||
@@ -1007,14 +1034,7 @@ impl NodeNetwork {
|
||||
let (tagged_value, exposed) = match previous_export {
|
||||
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
|
||||
NodeInput::Reflection(reflect) => match reflect {
|
||||
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
|
||||
DocumentNodeMetadata::SourceId => {
|
||||
let source_id = Self::source_id_for_path(path);
|
||||
if let Some(context_features) = context_features.as_deref_mut() {
|
||||
context_features.add_sources(&[source_id]);
|
||||
}
|
||||
(TaggedValue::U64(source_id).into(), false)
|
||||
}
|
||||
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false),
|
||||
},
|
||||
previous_export => {
|
||||
*export = previous_export;
|
||||
@@ -1165,7 +1185,6 @@ impl NodeNetwork {
|
||||
inputs: Vec::new(),
|
||||
output: node_id,
|
||||
nodes,
|
||||
..Default::default()
|
||||
}]
|
||||
.into_iter();
|
||||
}
|
||||
@@ -1182,7 +1201,6 @@ impl NodeNetwork {
|
||||
// inputs: self.imports.clone(),
|
||||
output: node_id,
|
||||
nodes: nodes.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
@@ -1229,9 +1247,7 @@ fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> R
|
||||
Old(Option<Type>),
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
Ok(match CallArg::deserialize(deserializer)? {
|
||||
CallArg::New(Type::Concrete(descriptor)) if descriptor.name.ends_with("OwnedContextImpl>>") => concrete!(Context),
|
||||
CallArg::New(ty) => ty,
|
||||
CallArg::Old(ty) => ty.unwrap_or_default(),
|
||||
})
|
||||
@@ -1447,7 +1463,6 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = flat_network();
|
||||
let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>();
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
use super::DocumentNode;
|
||||
use crate::application_io::PlatformEditorApi;
|
||||
use crate::application_io::resource::Resource;
|
||||
use crate::proto::Any as DAny;
|
||||
use brush_nodes::brush_stroke::BrushStroke;
|
||||
use crate::proto::{Any as DAny, FutureAny};
|
||||
use brush_nodes::brush_stroke::{BrushStroke, BrushTrace};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::context::Context;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::value::{leveled_record_value_edge, record_value_edge};
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||
use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor};
|
||||
use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graphene_application_io::resource::ResourceHash;
|
||||
use graphene_application_io::resource::ResourceId;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::vector_types::vector::style::GradientStops;
|
||||
use graphic_types::vector_types::vector::misc::BoxCorners;
|
||||
use graphic_types::vector_types::vector::style::DashPattern;
|
||||
use graphic_types::vector_types::vector::style::Gradient;
|
||||
use graphic_types::vector_types::vector::{self, ReferencePoint};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::RenderMetadata;
|
||||
use std::fmt::Display;
|
||||
use std::hash::Hash;
|
||||
use std::marker::PhantomData;
|
||||
use std::str::FromStr;
|
||||
pub use std::sync::Arc;
|
||||
use text_nodes::Font;
|
||||
@@ -31,15 +30,38 @@ use vector::VectorModification;
|
||||
|
||||
pub struct TaggedValueTypeError;
|
||||
|
||||
/// List of types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant.
|
||||
/// Item-cell element types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant, stored as the concrete `Item<T>` wire type.
|
||||
/// Consumed by [`TaggedValue::from_type`] (which creates `TypeDefault` values) and [`TaggedValue::to_dynany`]/[`TaggedValue::to_any`] (which unwrap them into real default values).
|
||||
macro_rules! for_each_type_default {
|
||||
macro_rules! for_each_item_type_default {
|
||||
($action:ident) => {
|
||||
$action!(Vector);
|
||||
$action!(f64);
|
||||
$action!(Raster<CPU>);
|
||||
$action!(Graphic);
|
||||
$action!(Color);
|
||||
$action!(Gradient);
|
||||
$action!(Artboard);
|
||||
$action!(String);
|
||||
};
|
||||
}
|
||||
|
||||
/// List element types routed through [`TaggedValue::TypeDefault`], stored as the structural [`Type::List`] form.
|
||||
/// `List<f64>` is absent because it stores as `TaggedValue::F64Array`.
|
||||
macro_rules! for_each_list_type_default {
|
||||
($action:ident) => {
|
||||
$action!(Graphic);
|
||||
$action!(Artboard);
|
||||
$action!(Raster<CPU>);
|
||||
$action!(Vector);
|
||||
$action!(String);
|
||||
$action!(Color);
|
||||
$action!(Gradient);
|
||||
};
|
||||
}
|
||||
|
||||
/// Unranked types routed through [`TaggedValue::TypeDefault`], stored as their concrete type.
|
||||
macro_rules! for_each_bare_type_default {
|
||||
($action:ident) => {
|
||||
$action!(List<Graphic>);
|
||||
$action!(List<Artboard>);
|
||||
$action!(List<Raster<CPU>>);
|
||||
$action!(List<Vector>);
|
||||
$action!(List<String>);
|
||||
$action!(DocumentNode);
|
||||
$action!(Resource);
|
||||
};
|
||||
@@ -57,22 +79,24 @@ macro_rules! tagged_value {
|
||||
// ===============
|
||||
None,
|
||||
/// Stores a type, from which its `Default::default()` value can be obtained, rather than storing an actual type's value.
|
||||
/// Example: `TaggedValue::TypeDefault(descriptor!(String))` stores the type `String` but no specific string value.
|
||||
TypeDefault(TypeDescriptor),
|
||||
/// Example: `TaggedValue::TypeDefault(concrete!(String))` stores the type `String` but no specific string value.
|
||||
/// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.)
|
||||
TypeDefault(Type),
|
||||
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_f64_array")] // TODO: Eventually remove this migration document upgrade code
|
||||
#[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
|
||||
F64Array(Vec<f64>),
|
||||
/// Stored compactly as an `Option<Color>`, materializes as `List<Color>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_optional_color")] // TODO: Eventually remove this migration document upgrade code
|
||||
/// A plain, always-present color. Aliases recover legacy on-disk shapes; a legacy `null` payload (the old "no color")
|
||||
/// is routed to [`TaggedValue::no_paint`] by `deserialize_tagged_value_with_legacy_migration`.
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_color")] // TODO: Eventually remove this migration document upgrade code
|
||||
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
|
||||
Color(Option<Color>),
|
||||
/// Stored compactly as a `GradientStops`, materializes as a single-row `List<GradientStops>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
Color(Color),
|
||||
/// Stored compactly as a `Gradient`, materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
|
||||
/// (Old documents that stored a full `Gradient` struct under this same `"Gradient"` tag are routed to `LegacyGradient` by `deserialize_tagged_value_with_legacy_migration`.)
|
||||
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient_stops")] // TODO: Eventually remove this migration document upgrade code
|
||||
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient")] // TODO: Eventually remove this migration document upgrade code
|
||||
#[serde(alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
|
||||
Gradient(GradientStops),
|
||||
/// Stored compactly as a `Vec<BrushStroke>`, materializes as `List<BrushStroke>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
Gradient(Gradient),
|
||||
/// Stored compactly as a `Vec<BrushStroke>`, materializes as the single-value `Item<BrushTrace>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "brush_nodes::migrations::migrate_to_brush_strokes")] // TODO: Eventually remove this migration document upgrade code
|
||||
#[serde(alias = "BrushStrokeTable")]
|
||||
BrushStrokes(Vec<BrushStroke>),
|
||||
@@ -85,15 +109,15 @@ macro_rules! tagged_value {
|
||||
// =======================
|
||||
#[serde(skip)]
|
||||
RenderOutput(RenderOutput),
|
||||
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes a `List<NodeId>` at runtime via `to_dynany`/`to_any` during graph flattening.
|
||||
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes an `Item<NodeIdPath>` at runtime via `to_dynany`/`to_any` during graph flattening, matching the ranked connectors it feeds.
|
||||
#[serde(skip)]
|
||||
NodeIdPath(Vec<NodeId>),
|
||||
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(descriptor!(DocumentNode))`.
|
||||
NodeIdPath(NodeIdPath),
|
||||
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`.
|
||||
#[serde(skip)]
|
||||
DocumentNode(DocumentNode),
|
||||
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
|
||||
#[serde(skip)]
|
||||
ContextModification(ContextModification),
|
||||
ContextFeatures(ContextFeatures),
|
||||
#[serde(skip)]
|
||||
EditorApi(Arc<PlatformEditorApi>),
|
||||
/// Only used by the `resource` node, should never be serialized
|
||||
@@ -121,9 +145,9 @@ macro_rules! tagged_value {
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::NodeIdPath(path) => path.hash(state),
|
||||
Self::NodeIdPath(path) => path.cache_hash(state),
|
||||
Self::DocumentNode(node) => node.cache_hash(state),
|
||||
Self::ContextModification(modification) => modification.cache_hash(state),
|
||||
Self::ContextFeatures(features) => features.cache_hash(state),
|
||||
Self::RenderOutput(x) => x.cache_hash(state),
|
||||
Self::EditorApi(x) => x.cache_hash(state),
|
||||
Self::ResourceHash(x) => x.cache_hash(state),
|
||||
@@ -141,43 +165,58 @@ macro_rules! tagged_value {
|
||||
Self::None => Box::new(()),
|
||||
Self::TypeDefault(td) => {
|
||||
// Construct the actual default for types without a `TaggedValue` variant directly.
|
||||
// Recursion through `from_type_or_none` below is safe only because `for_each_type_default!`
|
||||
// exhaustively handles every type that `from_type` would route back to `TypeDefault`.
|
||||
let name = td.name.as_ref();
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Box::new(<$type_default>::default()); }
|
||||
};
|
||||
// Recursion through `from_type_or_none` below is safe only because the type-default lists
|
||||
// exhaustively cover every type that `from_type` would route back to `TypeDefault`.
|
||||
match &td {
|
||||
Type::List(element) => {
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Box::new(List::<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_list_type_default!(check);
|
||||
}
|
||||
Type::Item(element) => {
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Box::new(Item::<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_item_type_default!(check);
|
||||
}
|
||||
Type::Concrete(descriptor) => {
|
||||
let name = descriptor.name.as_ref();
|
||||
macro_rules! check_bare {
|
||||
($type_default:ty) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_bare_type_default!(check_bare);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_dynany()
|
||||
Self::from_type_or_none(&td).to_dynany()
|
||||
}
|
||||
Self::F64Array(values) => {
|
||||
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Box::new(list)
|
||||
}
|
||||
Self::Color(color) => {
|
||||
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Box::new(list)
|
||||
}
|
||||
Self::Gradient(stops) => Box::new(List::<GradientStops>::new_from_element(stops)),
|
||||
Self::BrushStrokes(strokes) => {
|
||||
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Box::new(list)
|
||||
}
|
||||
Self::Color(color) => Box::new(Item::new_from_element(color)),
|
||||
Self::Gradient(stops) => Box::new(Item::new_from_element(stops)),
|
||||
Self::BrushStrokes(strokes) => Box::new(core_types::list::Item::new_from_element(BrushTrace::from(strokes))),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => Box::new(x), )*
|
||||
$( Self::$identifier(x) => Box::new(Item::new_from_element(x)), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Box::new(x),
|
||||
Self::NodeIdPath(path) => Box::new(path),
|
||||
Self::RenderOutput(x) => Box::new(Item::new_from_element(x)),
|
||||
Self::NodeIdPath(path) => Box::new(Item::new_from_element(path)),
|
||||
Self::DocumentNode(node) => Box::new(node),
|
||||
Self::ContextModification(modification) => Box::new(modification),
|
||||
Self::ContextFeatures(features) => Box::new(Item::new_from_element(features)),
|
||||
Self::EditorApi(x) => Box::new(x),
|
||||
Self::ResourceHash(x) => Box::new(x),
|
||||
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,199 +229,88 @@ macro_rules! tagged_value {
|
||||
Self::None => Arc::new(()),
|
||||
Self::TypeDefault(td) => {
|
||||
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
|
||||
let name = td.name.as_ref();
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Arc::new(<$type_default>::default()); }
|
||||
};
|
||||
match &td {
|
||||
Type::List(element) => {
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Arc::new(List::<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_list_type_default!(check);
|
||||
}
|
||||
Type::Item(element) => {
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Arc::new(Item::<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_item_type_default!(check);
|
||||
}
|
||||
Type::Concrete(descriptor) => {
|
||||
let name = descriptor.name.as_ref();
|
||||
macro_rules! check_bare {
|
||||
($type_default:ty) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_bare_type_default!(check_bare);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_any()
|
||||
Self::from_type_or_none(&td).to_any()
|
||||
}
|
||||
Self::F64Array(values) => {
|
||||
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Arc::new(list)
|
||||
}
|
||||
Self::Color(color) => {
|
||||
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Arc::new(list)
|
||||
}
|
||||
Self::Gradient(stops) => Arc::new(List::<GradientStops>::new_from_element(stops)),
|
||||
Self::BrushStrokes(strokes) => {
|
||||
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Arc::new(list)
|
||||
}
|
||||
Self::Color(color) => Arc::new(Item::new_from_element(color)),
|
||||
Self::Gradient(stops) => Arc::new(Item::new_from_element(stops)),
|
||||
Self::BrushStrokes(strokes) => Arc::new(core_types::list::Item::new_from_element(BrushTrace::from(strokes))),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => Arc::new(x), )*
|
||||
$( Self::$identifier(x) => Arc::new(Item::new_from_element(x)), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Arc::new(x),
|
||||
Self::NodeIdPath(path) => Arc::new(path),
|
||||
Self::RenderOutput(x) => Arc::new(Item::new_from_element(x)),
|
||||
Self::NodeIdPath(path) => Arc::new(Item::new_from_element(path)),
|
||||
Self::DocumentNode(node) => Arc::new(node),
|
||||
Self::ContextModification(modification) => Arc::new(modification),
|
||||
Self::ContextFeatures(features) => Arc::new(Item::new_from_element(features)),
|
||||
Self::EditorApi(x) => Arc::new(x),
|
||||
Self::ResourceHash(x) => Arc::new(x),
|
||||
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a core_types::Type::Concrete(TypeDescriptor { .. }) with the type of the value inside the tagged value
|
||||
/// Creates the wire [`Type`] of the value inside the tagged value, with ranked types in their structural form.
|
||||
pub fn ty(&self) -> Type {
|
||||
match self {
|
||||
let ty = match self {
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => concrete!(()),
|
||||
// The list-typed defaults type by their element: depth is not a
|
||||
// `Type` axis, it rides the layout proven at wiring.
|
||||
Self::TypeDefault(td) => {
|
||||
let name = td.name.as_ref();
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return concrete!(Graphic); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return concrete!(Artboard); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) { return concrete!(Raster<CPU>); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return concrete!(Vector); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<String>>()) { return concrete!(String); }
|
||||
Type::Concrete(td.clone())
|
||||
}
|
||||
Self::F64Array(_) => concrete!(f64),
|
||||
Self::Color(_) => concrete!(Color),
|
||||
Self::Gradient(_) => concrete!(GradientStops),
|
||||
Self::BrushStrokes(_) => concrete!(BrushStroke),
|
||||
Self::TypeDefault(td) => td.clone(),
|
||||
Self::F64Array(_) => list!(f64),
|
||||
Self::Color(_) => item!(Color),
|
||||
Self::Gradient(_) => item!(Gradient),
|
||||
Self::BrushStrokes(_) => item!(BrushTrace),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(_) => concrete!($ty), )*
|
||||
$( Self::$identifier(_) => item!($ty), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(_) => concrete!(RenderOutput),
|
||||
Self::NodeIdPath(_) => concrete!(Vec<NodeId>),
|
||||
Self::RenderOutput(_) => item!(RenderOutput),
|
||||
Self::NodeIdPath(_) => item!(NodeIdPath),
|
||||
Self::DocumentNode(_) => concrete!(DocumentNode),
|
||||
Self::ContextModification(_) => concrete!(ContextModification),
|
||||
Self::EditorApi(_) => concrete!(Arc<PlatformEditorApi>),
|
||||
Self::ResourceHash(_) => concrete!(ResourceHash),
|
||||
}
|
||||
}
|
||||
Self::ContextFeatures(_) => item!(ContextFeatures),
|
||||
Self::EditorApi(_) => item!(&PlatformEditorApi),
|
||||
Self::ResourceHash(_) => item!(ResourceHash),
|
||||
};
|
||||
|
||||
/// The record layout of this value's edge: leveled for the list-carrying
|
||||
/// variants, element-only at rank 0 otherwise. `None` for a
|
||||
/// [`Self::TypeDefault`] whose named type is outside `for_each_type_default!`.
|
||||
pub fn value_layout(&self) -> Option<core_types::record::Layout> {
|
||||
fn leveled<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>() -> Option<core_types::record::Layout>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
Some(core_types::record::Layout::default().with_writes(1, core_types::record::element_write_hashed::<T>(), &[]))
|
||||
}
|
||||
fn scalar<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Option<core_types::record::Layout>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
Some(core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[]))
|
||||
}
|
||||
match self {
|
||||
Self::None => scalar::<()>(),
|
||||
Self::TypeDefault(td) => {
|
||||
let name = td.name.as_ref();
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return leveled::<Graphic>(); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return leveled::<Artboard>(); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) { return leveled::<Raster<CPU>>(); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return leveled::<Vector>(); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<String>>()) { return leveled::<String>(); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return scalar::<DocumentNode>(); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return scalar::<Resource>(); }
|
||||
None
|
||||
}
|
||||
Self::F64Array(_) => leveled::<f64>(),
|
||||
Self::Color(_) => leveled::<Color>(),
|
||||
Self::Gradient(_) => leveled::<GradientStops>(),
|
||||
Self::BrushStrokes(_) => leveled::<BrushStroke>(),
|
||||
$( Self::$identifier(_) => scalar::<$ty>(), )*
|
||||
Self::RenderOutput(_) => scalar::<RenderOutput>(),
|
||||
Self::NodeIdPath(_) => scalar::<Vec<NodeId>>(),
|
||||
Self::DocumentNode(_) => scalar::<DocumentNode>(),
|
||||
Self::ContextModification(_) => scalar::<ContextModification>(),
|
||||
Self::EditorApi(_) => scalar::<Arc<PlatformEditorApi>>(),
|
||||
Self::ResourceHash(_) => scalar::<ResourceHash>(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value edge typed by [`Self::ty`].
|
||||
pub fn to_edge(self) -> Result<EdgeHandle, String> {
|
||||
match self {
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => Ok(record_value_edge(())),
|
||||
Self::TypeDefault(td) => {
|
||||
let name = td.name.as_ref();
|
||||
// The list-typed defaults serve an empty level; the rest construct
|
||||
// their default directly, mirroring `to_dynany`'s recursion guard.
|
||||
macro_rules! check_level {
|
||||
($list:ty, $element:ty) => {
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$list>()) {
|
||||
return Ok(leveled_record_value_edge(Vec::<$element>::new()));
|
||||
}
|
||||
};
|
||||
}
|
||||
check_level!(List<Graphic>, Graphic);
|
||||
check_level!(List<Artboard>, Artboard);
|
||||
check_level!(List<Raster<CPU>>, Raster<CPU>);
|
||||
// One default lane rather than an empty level: an unwired path input
|
||||
// starts from a blank vector, as the legacy path modify synthesized itself.
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_edge(vec![Vector::default()])); }
|
||||
check_level!(List<String>, String);
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_edge(DocumentNode::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_edge(Resource::default())); }
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||
}
|
||||
Self::F64Array(values) => Ok(leveled_record_value_edge(values)),
|
||||
Self::Color(color) => Ok(leveled_record_value_edge(color.into_iter().collect::<Vec<_>>())),
|
||||
Self::Gradient(stops) => Ok(leveled_record_value_edge(vec![stops])),
|
||||
Self::BrushStrokes(strokes) => Ok(leveled_record_value_edge(strokes)),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Ok(record_value_edge(x)),
|
||||
Self::NodeIdPath(path) => Ok(record_value_edge(path)),
|
||||
Self::DocumentNode(node) => Ok(record_value_edge(node)),
|
||||
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
|
||||
Self::EditorApi(x) => Ok(record_value_edge(x)),
|
||||
Self::ResourceHash(x) => Ok(record_value_edge(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a typed edge and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||
pub fn from_edge<'f>(handle: EdgeHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||
let ty = handle.ty().clone();
|
||||
// =======================
|
||||
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||
// =======================
|
||||
if ty == core_types::registry::record_edge_type::<()>() {
|
||||
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||
}
|
||||
$(
|
||||
if ty == core_types::registry::record_edge_type::<$ty>() {
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames)
|
||||
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||
}
|
||||
)*
|
||||
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames)
|
||||
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
|
||||
}
|
||||
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
|
||||
// Defensively converges any remaining name-encoded ranked type (e.g. an opaque macro capture) to the structural form
|
||||
ty.normalize_rank()
|
||||
}
|
||||
|
||||
/// Attempts to downcast the dynamic type to a tagged value
|
||||
@@ -399,10 +327,11 @@ macro_rules! tagged_value {
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*downcast(input).unwrap())), )*
|
||||
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(downcast::<Item<$ty>>(input).unwrap().into_element())), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(*downcast(input).unwrap())),
|
||||
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(downcast::<Item<RenderOutput>>(input).unwrap().into_element())),
|
||||
|
||||
_ => Err(format!("Cannot convert {:?} to TaggedValue", DynAny::type_name(input.as_ref()))),
|
||||
}
|
||||
@@ -421,52 +350,64 @@ macro_rules! tagged_value {
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(<$ty as Clone>::clone(input.downcast_ref().unwrap()))), )*
|
||||
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(Item::<$ty>::clone(input.downcast_ref().unwrap()).into_element())), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(RenderOutput::clone(input.downcast_ref().unwrap()))),
|
||||
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(Item::<RenderOutput>::clone(input.downcast_ref().unwrap()).into_element())),
|
||||
_ => Err(format!("Cannot convert {:?} to TaggedValue", std::any::type_name_of_val(input))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a TaggedValue from the type, where that value is its type's `Default::default()`.
|
||||
/// Dispatches by the type's name (the field that round-trips through serde) so it works for both
|
||||
/// freshly constructed types and types deserialized from disk where the runtime `TypeId` is unavailable.
|
||||
/// Dispatches by name for concrete types and structurally by element for ranked types, where the name
|
||||
/// field is what round-trips through serde so it works even for types deserialized from disk.
|
||||
pub fn from_type(input: &Type) -> Option<Self> {
|
||||
match input {
|
||||
Type::Generic(_) => None,
|
||||
Type::Record(inner) => Self::from_type(inner),
|
||||
Type::Concrete(concrete_type) => {
|
||||
let name = concrete_type.name.as_ref();
|
||||
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
|
||||
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<()>()) { return Some(TaggedValue::None) }
|
||||
// List-wrapped types need a single-item default with the element's default, not an empty list
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Color>>()) { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<GradientStops>>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
$( if name == core_types::normalize_type_name(std::any::type_name::<$ty>()) { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<f64>>()) { return Some(TaggedValue::F64Array(Vec::new())) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<BrushStroke>>()) { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||
// Leveled wires type by their element; each element name maps to the
|
||||
// same tagged default as its legacy list form.
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Color>()) { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<GradientStops>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<BrushStroke>()) { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Graphic>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Artboard>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Raster<CPU>>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Vector>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))) }
|
||||
// Types whose `TaggedValue` variant has been removed. They route through `TypeDefault` instead, with `to_dynany`/`to_any` constructing the actual default at execution time.
|
||||
macro_rules! check {
|
||||
if name == std::any::type_name::<()>() { return Some(TaggedValue::None) }
|
||||
if name == std::any::type_name::<Color>() { return Some(TaggedValue::Color(Color::default())) }
|
||||
if name == std::any::type_name::<Gradient>() { return Some(TaggedValue::Gradient(Gradient::default())) }
|
||||
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||
if name == std::any::type_name::<BrushTrace>() { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||
// Unranked types without a variant route through `TypeDefault`, with `to_dynany`/`to_any` constructing the actual default at execution time
|
||||
macro_rules! check_bare {
|
||||
($type_default:ty) => {
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
|
||||
if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
for_each_bare_type_default!(check_bare);
|
||||
None
|
||||
}
|
||||
Type::Fn(_, output) => TaggedValue::from_type(output),
|
||||
Type::Future(output) => TaggedValue::from_type(output),
|
||||
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
||||
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
};
|
||||
}
|
||||
for_each_item_type_default!(check);
|
||||
None
|
||||
}),
|
||||
// Structural lists match by element; `List<f64>` stays the dedicated `F64Array` variant
|
||||
Type::List(element) => {
|
||||
if **element == concrete!(f64) {
|
||||
return Some(TaggedValue::F64Array(Vec::new()));
|
||||
}
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
};
|
||||
}
|
||||
for_each_list_type_default!(check);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,7 +421,7 @@ macro_rules! tagged_value {
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => "()".to_string(),
|
||||
Self::TypeDefault(td) => format!("TypeDefault({})", td.name),
|
||||
Self::TypeDefault(td) => format!("TypeDefault({td})"),
|
||||
Self::F64Array(values) => format!("F64Array({values:?})"),
|
||||
Self::Color(color) => format!("Color({color:?})"),
|
||||
Self::Gradient(stops) => format!("Gradient({stops:?})"),
|
||||
@@ -495,7 +436,7 @@ macro_rules! tagged_value {
|
||||
Self::RenderOutput(_) => "RenderOutput".to_string(),
|
||||
Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"),
|
||||
Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
|
||||
Self::ContextModification(modification) => format!("ContextModification({modification:?})"),
|
||||
Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"),
|
||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
||||
}
|
||||
@@ -538,19 +479,19 @@ tagged_value! {
|
||||
DVec2(DVec2),
|
||||
#[serde(alias = "Affine2")]
|
||||
DAffine2(DAffine2),
|
||||
OptionalDAffine2(Option<DAffine2>),
|
||||
#[serde(alias = "FillGradient")]
|
||||
LegacyGradient(graphic_types::migrations::legacy::Gradient),
|
||||
Font(Font),
|
||||
Footprint(Footprint),
|
||||
VectorModification(Box<VectorModification>),
|
||||
ImageData(Image<Color>),
|
||||
Resource(graphene_application_io::resource::ResourceId),
|
||||
Resource(ResourceId),
|
||||
// Legacy
|
||||
#[serde(alias = "OptionalDAffine2")]
|
||||
LegacyOptionalDAffine2(Option<DAffine2>),
|
||||
#[serde(alias = "FillGradient")]
|
||||
LegacyGradient(graphic_types::migrations::legacy::LegacyGradient),
|
||||
// ==========
|
||||
// ENUM TYPES
|
||||
// ==========
|
||||
#[serde(alias = "Fill")]
|
||||
LegacyFill(graphic_types::migrations::legacy::Fill),
|
||||
BlendMode(core_types::blending::BlendMode),
|
||||
LuminanceCalculation(raster_nodes::adjustments::LuminanceCalculation),
|
||||
QRCodeErrorCorrectionLevel(vector_nodes::generator_nodes::QRCodeErrorCorrectionLevel),
|
||||
@@ -580,6 +521,8 @@ tagged_value! {
|
||||
StrokeJoin(vector::style::StrokeJoin),
|
||||
StrokeAlign(vector::style::StrokeAlign),
|
||||
PaintOrder(vector::style::PaintOrder),
|
||||
DashPattern(vector::style::DashPattern),
|
||||
BoxCorners(vector::misc::BoxCorners),
|
||||
GradientType(vector::style::GradientType),
|
||||
GradientSpreadMethod(vector::style::GradientSpreadMethod),
|
||||
ReferencePoint(vector::ReferencePoint),
|
||||
@@ -587,6 +530,9 @@ tagged_value! {
|
||||
BooleanOperation(vector::misc::BooleanOperation),
|
||||
TextAlign(text_nodes::TextAlign),
|
||||
ScaleType(core_types::transform::ScaleType),
|
||||
// Legacy
|
||||
#[serde(alias = "Fill")]
|
||||
LegacyFill(graphic_types::migrations::legacy::LegacyFill),
|
||||
}
|
||||
|
||||
impl TaggedValue {
|
||||
@@ -648,11 +594,11 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_gradient(input: &str) -> Option<GradientStops> {
|
||||
fn to_gradient(input: &str) -> Option<Gradient> {
|
||||
// String syntax: (e.g. "000000ff, ff0000ff")
|
||||
let stops = input.split(',').filter_map(|s| to_color(s.trim())).collect::<Vec<_>>();
|
||||
if stops.len() == 1 {
|
||||
Some(GradientStops::new(vec![
|
||||
Some(Gradient::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -666,7 +612,7 @@ impl TaggedValue {
|
||||
]))
|
||||
} else if stops.len() >= 2 {
|
||||
let step = 1. / (stops.len() - 1) as f64;
|
||||
Some(GradientStops::new(stops.into_iter().enumerate().map(|(i, color)| GradientStop {
|
||||
Some(Gradient::new(stops.into_iter().enumerate().map(|(i, color)| GradientStop {
|
||||
position: i as f64 * step,
|
||||
midpoint: 0.5,
|
||||
color,
|
||||
@@ -705,8 +651,6 @@ impl TaggedValue {
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
// A leveled wire's default is its element's default, as in `from_type`.
|
||||
Type::Record(inner) => TaggedValue::from_primitive_string(string, inner),
|
||||
Type::Concrete(concrete_type) => {
|
||||
let ty = concrete_type.id?;
|
||||
use std::any::TypeId;
|
||||
@@ -721,19 +665,21 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<u32>() => FromStr::from_str(string).map(TaggedValue::U32).ok()?,
|
||||
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
|
||||
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
|
||||
// `Color` (not in a `List`) is still currently needed by `BlackAndWhiteNode` and `ColorOverlayNode` GPU `shader_node(PerPixelAdjust)` variants
|
||||
() if ty == TypeId::of::<Color>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
|
||||
() if ty == TypeId::of::<List<Color>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
|
||||
// The Fill and Stroke nodes' paint connectors default to `List<Graphic>`, their first registered implementation row
|
||||
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
|
||||
() if ty == TypeId::of::<List<GradientStops>>() => to_gradient(string).map(TaggedValue::Gradient)?,
|
||||
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
|
||||
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(TaggedValue::Gradient)?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(DashPattern::from(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(BoxCorners::from(string)),
|
||||
_ => return None,
|
||||
};
|
||||
Some(ty)
|
||||
}
|
||||
Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output),
|
||||
Type::Future(fut) => TaggedValue::from_primitive_string(string, fut),
|
||||
Type::Item(element) => TaggedValue::from_primitive_string(string, element),
|
||||
Type::List(element) => TaggedValue::from_primitive_string(string, element),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -743,6 +689,16 @@ impl TaggedValue {
|
||||
_ => panic!("Passed value is not of type u32"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored form of a paint input's red-slash "no paint" choice: the `List<Graphic>` type default, materializing as an empty paint list.
|
||||
pub fn no_paint() -> Self {
|
||||
TaggedValue::TypeDefault(list!(Graphic))
|
||||
}
|
||||
|
||||
/// Whether this is the `List<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire).
|
||||
pub fn is_no_paint(&self) -> bool {
|
||||
matches!(self, TaggedValue::TypeDefault(td) if *td == list!(Graphic))
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom deserializer hooked onto `NodeInput::Value::tagged_value` that intercepts removed-variant tags before delegating to `TaggedValue`'s standard derive.
|
||||
@@ -750,14 +706,16 @@ impl TaggedValue {
|
||||
/// Routes legacy variant names into modern variants, in typed Rust. Each legacy name is also matched against the historical `#[serde(alias = "...")]` spellings the deleted variant accepted, so old-shape inner payloads are caught:
|
||||
///
|
||||
/// - `BrushCache` → `TaggedValue::None` (purely runtime cache; no payload to preserve)
|
||||
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(descriptor!(List<Graphic>))`
|
||||
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(descriptor!(List<Artboard>))`
|
||||
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(list!(Graphic))`
|
||||
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(list!(Artboard))`
|
||||
/// - `Raster` (or alias `ImageFrame`/`RasterData`/`Image`):
|
||||
/// - non-empty (the legacy `image` proto's input 1, where the inner `Raster<CPU>` serializes as the embedded `Image<Color>`) → `TaggedValue::ImageData(<inner Image<Color>>)`
|
||||
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))`
|
||||
/// - empty → `TaggedValue::TypeDefault(list!(Raster<CPU>))`
|
||||
/// - `Vector` (or alias `VectorData`):
|
||||
/// - non-empty → `TaggedValue::VectorModification(<built from first element>)` (the document_migration's Path pass disambiguates this between SVG-import legacy and a discardable modern baked value via the input's `exposed` flag)
|
||||
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Vector>))`
|
||||
/// - empty → `TaggedValue::TypeDefault(list!(Vector))`
|
||||
/// - `FillChoice` → `TaggedValue::Color` (solid), `TaggedValue::Gradient` (gradient), or `TaggedValue::no_paint()` (none)
|
||||
/// - `TypeDefault` with the old bare-`TypeDescriptor` payload → the same variant wrapping a `Type` (name-encoded `List` normalized to structural)
|
||||
///
|
||||
/// All other tags (including ones with the modern shape) fall through to the standard derived `Deserialize` for `TaggedValue`.
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
@@ -772,8 +730,8 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
|
||||
{
|
||||
match tag.as_str() {
|
||||
"BrushCache" => return Ok(MemoHash::new(TaggedValue::None)),
|
||||
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Graphic>)))),
|
||||
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Artboard>)))),
|
||||
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Graphic)))),
|
||||
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Artboard)))),
|
||||
"Raster" | "ImageFrame" | "RasterData" | "Image" => {
|
||||
let first_element = content
|
||||
.as_object()
|
||||
@@ -784,7 +742,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
|
||||
let image: Image<Color> = serde_json::from_value(image_value.clone()).map_err(serde::de::Error::custom)?;
|
||||
return Ok(MemoHash::new(TaggedValue::ImageData(image)));
|
||||
}
|
||||
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))));
|
||||
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Raster<CPU>))));
|
||||
}
|
||||
"Vector" | "VectorData" => {
|
||||
let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?;
|
||||
@@ -792,12 +750,42 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
return Ok(MemoHash::new(TaggedValue::VectorModification(modification)));
|
||||
}
|
||||
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Vector>))));
|
||||
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Vector))));
|
||||
}
|
||||
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<GradientStops>`.
|
||||
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `GradientStops` has none of those (it has `position`/`midpoint`/`color`).
|
||||
// The `TypeDefault` payload used to be a bare `TypeDescriptor`; it now carries a `Type`
|
||||
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("name")) => {
|
||||
let descriptor: TypeDescriptor = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
|
||||
return Ok(MemoHash::new(TaggedValue::TypeDefault(Type::Concrete(descriptor).normalize_rank())));
|
||||
}
|
||||
// The `Color` tag used to carry `Option<Color>`, where a `null` payload (or an empty legacy color table) was the red-slash "no paint" choice
|
||||
"Color" | "ColorTable" | "OptionalColor" | "ColorNotInTable"
|
||||
if content.is_null()
|
||||
|| content
|
||||
.as_object()
|
||||
.and_then(|c| c.get("element").or_else(|| c.get("instance")).or_else(|| c.get("instances")))
|
||||
.and_then(|e| e.as_array())
|
||||
.is_some_and(|colors| colors.is_empty()) =>
|
||||
{
|
||||
return Ok(MemoHash::new(TaggedValue::no_paint()));
|
||||
}
|
||||
// The removed `FillChoice` variant decomposes into the plain paint values
|
||||
"FillChoice" => {
|
||||
if let Some(payload) = content.as_object() {
|
||||
if let Some(solid) = payload.get("Solid") {
|
||||
let color: Color = serde_json::from_value(solid.clone()).map_err(serde::de::Error::custom)?;
|
||||
return Ok(MemoHash::new(TaggedValue::Color(color)));
|
||||
}
|
||||
if let Some(gradient) = payload.get("Gradient") {
|
||||
let gradient: Gradient = serde_json::from_value(gradient.clone()).map_err(serde::de::Error::custom)?;
|
||||
return Ok(MemoHash::new(TaggedValue::Gradient(gradient)));
|
||||
}
|
||||
}
|
||||
return Ok(MemoHash::new(TaggedValue::no_paint()));
|
||||
}
|
||||
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<Gradient>`.
|
||||
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `Gradient` has none of those (it has `position`/`midpoint`/`color`).
|
||||
"Gradient" if content.as_object().is_some_and(|c| c.contains_key("start") && c.contains_key("end")) => {
|
||||
let gradient: graphic_types::migrations::legacy::Gradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
|
||||
let gradient: graphic_types::migrations::legacy::LegacyGradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
|
||||
return Ok(MemoHash::new(TaggedValue::LegacyGradient(gradient)));
|
||||
}
|
||||
_ => {}
|
||||
@@ -822,6 +810,39 @@ impl Display for TaggedValue {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UpcastNode {
|
||||
value: MemoHash<TaggedValue>,
|
||||
}
|
||||
impl<'input> Node<'input, DAny<'input>> for UpcastNode {
|
||||
type Output = FutureAny<'input>;
|
||||
|
||||
fn eval(&'input self, _: DAny<'input>) -> Self::Output {
|
||||
let memo_clone = MemoHash::clone(&self.value);
|
||||
Box::pin(async move { memo_clone.into_inner().as_ref().clone().to_dynany() })
|
||||
}
|
||||
}
|
||||
impl UpcastNode {
|
||||
pub fn new(value: MemoHash<TaggedValue>) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct UpcastAsRefNode<T: AsRef<U> + Sync + Send, U: Sync + Send>(pub T, PhantomData<U>);
|
||||
|
||||
impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<'i, DAny<'i>> for UpcastAsRefNode<T, U> {
|
||||
type Output = FutureAny<'i>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
|
||||
Box::pin(async move { Box::new(Item::new_from_element(self.0.as_ref())) as DAny<'i> })
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<U> + Sync + Send, U: Sync + Send> UpcastAsRefNode<T, U> {
|
||||
pub const fn new(value: T) -> UpcastAsRefNode<T, U> {
|
||||
UpcastAsRefNode(value, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RenderOutput {
|
||||
pub data: RenderOutputType,
|
||||
@@ -883,93 +904,85 @@ impl CacheHash for RenderOutput {
|
||||
#[cfg(test)]
|
||||
mod typedefault_dispatch {
|
||||
use super::*;
|
||||
use core_types::descriptor;
|
||||
use core_types::{concrete, item, list};
|
||||
|
||||
/// Round-trips every type listed in [`for_each_type_default`] through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the descriptor.
|
||||
/// Round-trips every type in the type-default lists through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the stored type.
|
||||
///
|
||||
/// This guards against the only way to break the recursion invariant in the unwrap functions: someone hand-rolling a `TypeDefault`-yielding case in `from_type` (or the macro's expansion in one of the unwrap sites silently failing to match a name). If it fails, the message points at the specific type and the structural reason.
|
||||
#[test]
|
||||
fn typedefault_dispatch_terminates() {
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {{
|
||||
let descriptor = descriptor!($type_default);
|
||||
($type_default:ty, $stored:expr) => {{
|
||||
let ty: Type = $stored;
|
||||
let expected_type_id = std::any::TypeId::of::<$type_default>();
|
||||
let dyn_value = TaggedValue::TypeDefault(descriptor.clone()).to_dynany();
|
||||
let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany();
|
||||
assert_eq!(
|
||||
DynAny::type_id(&*dyn_value),
|
||||
expected_type_id,
|
||||
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — `for_each_type_default!` lists this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
|
||||
core_types::normalize_type_name(std::any::type_name::<$type_default>()),
|
||||
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — the type-default lists cover this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
|
||||
std::any::type_name::<$type_default>(),
|
||||
);
|
||||
|
||||
let arc_value = TaggedValue::TypeDefault(descriptor).to_any();
|
||||
let arc_value = TaggedValue::TypeDefault(ty).to_any();
|
||||
assert_eq!(
|
||||
(*arc_value).type_id(),
|
||||
expected_type_id,
|
||||
"`to_any(TypeDefault({0}))` did not produce a `{0}` — same recursion hazard as above for the `to_any` path.",
|
||||
core_types::normalize_type_name(std::any::type_name::<$type_default>()),
|
||||
std::any::type_name::<$type_default>(),
|
||||
);
|
||||
}};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
macro_rules! check_item {
|
||||
($element:ty) => {
|
||||
check!(Item<$element>, item!($element));
|
||||
};
|
||||
}
|
||||
macro_rules! check_list {
|
||||
($element:ty) => {
|
||||
check!(List<$element>, list!($element));
|
||||
};
|
||||
}
|
||||
macro_rules! check_bare {
|
||||
($type_default:ty) => {
|
||||
check!($type_default, concrete!($type_default));
|
||||
};
|
||||
}
|
||||
for_each_item_type_default!(check_item);
|
||||
for_each_list_type_default!(check_list);
|
||||
for_each_bare_type_default!(check_bare);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod leveled_edges {
|
||||
mod paint_default_parsing {
|
||||
use super::*;
|
||||
use core_types::descriptor;
|
||||
use core_types::registry::record_edge_type;
|
||||
use core_types::{item, list};
|
||||
|
||||
/// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse through the
|
||||
/// element recursion into a `Color` for a fresh Fill node's paint to resolve.
|
||||
#[test]
|
||||
fn list_variants_produce_leveled_edges_typed_by_element() {
|
||||
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<f64>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::Color(Some(Color::default())).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<Color>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<Graphic>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
fn paint_wire_parses_color_default_through_its_element() {
|
||||
let black = Some(TaggedValue::Color(Color::BLACK));
|
||||
assert_eq!(
|
||||
TaggedValue::from_primitive_string("Color::BLACK", &list!(Graphic)),
|
||||
black,
|
||||
"a `List<Graphic>` paint wire should resolve its color default"
|
||||
);
|
||||
assert_eq!(
|
||||
TaggedValue::from_primitive_string("Color::BLACK", &item!(Graphic)),
|
||||
black,
|
||||
"an `Item<Graphic>` paint wire should resolve its color default"
|
||||
);
|
||||
}
|
||||
|
||||
/// Table-era documents stored the red-slash "no paint" fill as an empty color table, which must keep
|
||||
/// deserializing to [`TaggedValue::no_paint`] rather than collapsing to a transparent color.
|
||||
#[test]
|
||||
fn scalar_variants_keep_their_rank_zero_edges() {
|
||||
let edge = TaggedValue::Bool(true).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<bool>());
|
||||
assert_eq!(edge.layout().depth, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_value_layout_matches_the_edge_layout() {
|
||||
for value in [
|
||||
TaggedValue::F64Array(vec![1.]),
|
||||
TaggedValue::Bool(true),
|
||||
TaggedValue::TypeDefault(descriptor!(List<Vector>)),
|
||||
TaggedValue::Gradient(Default::default()),
|
||||
] {
|
||||
let layout = value.value_layout().unwrap();
|
||||
let edge = value.to_edge().unwrap();
|
||||
assert_eq!(&layout, edge.layout());
|
||||
fn empty_legacy_color_table_deserializes_to_no_paint() {
|
||||
for payload in [r#"{"ColorTable": {"instances": []}}"#, r#"{"ColorTable": {"element": []}}"#, r#"{"Color": null}"#] {
|
||||
let mut deserializer = serde_json::Deserializer::from_str(payload);
|
||||
let value = deserialize_tagged_value_with_legacy_migration(&mut deserializer).expect("The legacy payload should deserialize");
|
||||
assert!(value.is_no_paint(), "The legacy payload `{payload}` should migrate to the no-paint choice");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod record_defaults {
|
||||
use super::*;
|
||||
use core_types::registry::record_edge_type;
|
||||
|
||||
// The registry can present a record row first (wasm registration order),
|
||||
// so primitive defaults must parse through the record wrapping.
|
||||
#[test]
|
||||
fn primitive_defaults_parse_through_record_wires() {
|
||||
let leveled = core_types::registry::record_type::<f64>();
|
||||
assert_eq!(TaggedValue::from_primitive_string("2.", &leveled), Some(TaggedValue::F64(2.)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("5", &record_edge_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("true", &record_edge_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::proto::{ProtoNetwork, Registry};
|
||||
use crate::proto::{LocalFuture, ProtoNetwork};
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Compiler {}
|
||||
|
||||
impl Compiler {
|
||||
pub fn compile<'r>(&self, mut network: NodeNetwork, registry: &'r Registry) -> impl Iterator<Item = Result<ProtoNetwork, String>> + 'r {
|
||||
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
|
||||
network.resolve_scope_inputs();
|
||||
network.generate_node_paths(&[]);
|
||||
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||
@@ -19,15 +19,13 @@ impl Compiler {
|
||||
|
||||
proto_networks.map(move |mut proto_network| {
|
||||
proto_network.insert_context_nullification_nodes()?;
|
||||
let _ = proto_network.resolve_types(registry);
|
||||
proto_network.compute_layouts();
|
||||
proto_network.generate_stable_node_ids();
|
||||
Ok(proto_network)
|
||||
})
|
||||
}
|
||||
pub fn compile_single(&self, network: NodeNetwork, registry: &Registry) -> Result<ProtoNetwork, String> {
|
||||
pub fn compile_single(&self, network: NodeNetwork) -> Result<ProtoNetwork, String> {
|
||||
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
let Some(proto_network) = self.compile(network, registry).next() else {
|
||||
let Some(proto_network) = self.compile(network).next() else {
|
||||
return Err("Failed to convert graph into proto graph".to_string());
|
||||
};
|
||||
proto_network
|
||||
@@ -35,5 +33,5 @@ impl Compiler {
|
||||
}
|
||||
|
||||
pub trait Executor<I, O> {
|
||||
fn execute(&self, input: I) -> Result<O, Box<dyn Error>>;
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<O, Box<dyn Error>>>;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ extern crate log;
|
||||
#[macro_use]
|
||||
extern crate core_types;
|
||||
|
||||
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic};
|
||||
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic, item, list};
|
||||
|
||||
pub mod application_io;
|
||||
pub mod document;
|
||||
|
||||
+263
-516
@@ -19,9 +19,6 @@ pub struct ProtoNetwork {
|
||||
pub output: NodeId,
|
||||
/// A list of nodes stored in a Vec to allow for sorting.
|
||||
pub nodes: Vec<(NodeId, ProtoNode)>,
|
||||
/// Peak record-stack bytes for an evaluation, folded from the resolved layouts by [`compute_layouts`](ProtoNetwork::compute_layouts).
|
||||
#[serde(default)]
|
||||
pub stack_need: usize,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for ProtoNetwork {
|
||||
@@ -127,20 +124,6 @@ impl ConstructionArgs {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct Resolved {
|
||||
pub io: Option<NodeIOTypes>,
|
||||
pub layout_meta: Option<core_types::record::LayoutMeta>,
|
||||
pub layout: Option<core_types::record::RecordLayout>,
|
||||
}
|
||||
|
||||
impl PartialEq for Resolved {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Eq for Resolved {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
/// A proto node is an intermediate step between the `DocumentNode` and the boxed struct that actually runs the node (found in the [`BorrowTree`]).
|
||||
/// At different stages in the compilation process, this struct will be transformed into a reduced (more restricted) form acting as a subset of its original form, but that restricted form is still valid in the earlier stage in the compilation process before it was transformed.
|
||||
@@ -151,12 +134,6 @@ pub struct ProtoNode {
|
||||
pub original_location: OriginalLocation,
|
||||
pub skip_deduplication: bool,
|
||||
pub(crate) context_features: ContextDependencies,
|
||||
/// Bit `i` marks input `i` as invariant under the innermost index. Inputs at
|
||||
/// position 32 and above never set a bit, so they read as varying.
|
||||
#[serde(skip)]
|
||||
pub(crate) lane_invariant_inputs: u32,
|
||||
#[serde(skip)]
|
||||
pub(crate) resolved: Resolved,
|
||||
}
|
||||
|
||||
impl Default for ProtoNode {
|
||||
@@ -168,8 +145,6 @@ impl Default for ProtoNode {
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
context_features: Default::default(),
|
||||
lane_invariant_inputs: 0,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,8 +185,6 @@ impl ProtoNode {
|
||||
},
|
||||
skip_deduplication: false,
|
||||
context_features: Default::default(),
|
||||
lane_invariant_inputs: 0,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,10 +202,6 @@ impl ProtoNode {
|
||||
_ => panic!("tried to unwrap nodes from non node construction args \n node: {self:#?}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolved_layout(&self) -> Option<&core_types::record::RecordLayout> {
|
||||
self.resolved.layout.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
@@ -258,7 +227,6 @@ impl ProtoNetwork {
|
||||
inputs: vec![node_id],
|
||||
output: node_id,
|
||||
nodes: vec![(node_id, proto_node.clone())],
|
||||
..Default::default()
|
||||
};
|
||||
(proto_network, node_id, proto_node)
|
||||
}
|
||||
@@ -290,11 +258,6 @@ impl ProtoNetwork {
|
||||
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
|
||||
self.nodes[index].0 = sni;
|
||||
}
|
||||
|
||||
// Equal nodes hash to one id; the copies must go, or a pass that
|
||||
// rewrites one of them (like adapter splicing) leaves the others stale.
|
||||
let mut seen = HashSet::new();
|
||||
self.nodes.retain(|(id, _)| seen.insert(*id));
|
||||
}
|
||||
|
||||
// TODO: Remove
|
||||
@@ -331,115 +294,6 @@ impl ProtoNetwork {
|
||||
(inwards_edges, id_map)
|
||||
}
|
||||
|
||||
pub fn source_ids(&self) -> Vec<SourceId> {
|
||||
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
|
||||
}
|
||||
|
||||
pub fn resolve_types(&mut self, registry: &Registry) -> Result<(), String> {
|
||||
self.reorder_ids()?;
|
||||
for index in 0..self.nodes.len() {
|
||||
let resolved = {
|
||||
let node = &self.nodes[index].1;
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(value) => Resolved {
|
||||
io: Some(NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(value.ty())), vec![])),
|
||||
..Default::default()
|
||||
},
|
||||
_ => {
|
||||
let inputs: Vec<Type> = match &node.construction_args {
|
||||
ConstructionArgs::Nodes(nodes) => nodes
|
||||
.iter()
|
||||
.map(|input| {
|
||||
self.nodes[input.0 as usize]
|
||||
.1
|
||||
.resolved
|
||||
.io
|
||||
.as_ref()
|
||||
.map(|io| io.ty())
|
||||
.ok_or_else(|| format!("input {input:?} of {} is not yet typed", node.identifier.as_str()))
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
ConstructionArgs::Inline(inline) => vec![inline.ty.clone()],
|
||||
ConstructionArgs::Value(_) => unreachable!(),
|
||||
};
|
||||
let impls = registry.get(&node.identifier).ok_or_else(|| format!("no implementations for {}", node.identifier.as_str()))?;
|
||||
let (io, entry) = resolve_entry(node, &inputs, impls).map_err(|errors| format!("{errors:?}"))?;
|
||||
Resolved {
|
||||
io: Some(io),
|
||||
layout_meta: entry.layout_meta.clone(),
|
||||
layout: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
self.nodes[index].1.resolved = resolved;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn compute_layouts(&mut self) {
|
||||
for index in 0..self.nodes.len() {
|
||||
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
|
||||
let layout = {
|
||||
let node = &self.nodes[index].1;
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(value) => value.value_layout().map(|layout| core_types::record::RecordLayout {
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
lane_invariant,
|
||||
layout,
|
||||
}),
|
||||
ConstructionArgs::Nodes(inputs) => node.resolved.layout_meta.as_ref().and_then(|meta| {
|
||||
let input_layouts: Vec<Option<&core_types::record::Layout>> = inputs
|
||||
.iter()
|
||||
.map(|input| self.nodes[input.0 as usize].1.resolved.layout.as_ref().map(|resolved| &resolved.layout))
|
||||
.collect();
|
||||
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| core_types::record::RecordLayout {
|
||||
lane_invariant,
|
||||
..meta.resolve(&input_layouts)
|
||||
})
|
||||
}),
|
||||
ConstructionArgs::Inline(_) => None,
|
||||
}
|
||||
};
|
||||
// Set GRAPHENE_LAYOUT_DEBUG to dump each node's resolved record depth.
|
||||
if let Some(resolved) = &layout
|
||||
&& std::env::var("GRAPHENE_LAYOUT_DEBUG").is_ok()
|
||||
{
|
||||
eprintln!("layout {} depth {}", self.nodes[index].1.identifier, resolved.layout.depth);
|
||||
}
|
||||
self.nodes[index].1.resolved.layout = layout;
|
||||
}
|
||||
self.stack_need = self.fold_stack_peak();
|
||||
}
|
||||
|
||||
/// Peak record-stack bytes for evaluating [`output`](Self::output)'s cone. A node holds its
|
||||
/// inputs' frames until it returns, so its need is its own frame plus every input's frame plus
|
||||
/// the deepest input's peak. Memoized over shared cones. Runs while node IDs are still indices.
|
||||
fn fold_stack_peak(&self) -> usize {
|
||||
fn peak(index: usize, network: &ProtoNetwork, memo: &mut [Option<usize>]) -> usize {
|
||||
if let Some(cached) = memo[index] {
|
||||
return cached;
|
||||
}
|
||||
let frame = |i: usize| network.nodes[i].1.resolved.layout.as_ref().map_or(0, |resolved| resolved.frame_bytes);
|
||||
let mut held = 0;
|
||||
let mut deepest = 0;
|
||||
if let ConstructionArgs::Nodes(inputs) = &network.nodes[index].1.construction_args {
|
||||
for input in inputs {
|
||||
let child = input.0 as usize;
|
||||
let child_frame = frame(child);
|
||||
held += child_frame;
|
||||
deepest = deepest.max(peak(child, network, memo).saturating_sub(child_frame));
|
||||
}
|
||||
}
|
||||
let need = frame(index) + held + deepest;
|
||||
memo[index] = Some(need);
|
||||
need
|
||||
}
|
||||
let mut memo = vec![None; self.nodes.len()];
|
||||
peak(self.output.0 as usize, self, &mut memo)
|
||||
}
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||
@@ -454,7 +308,7 @@ impl ProtoNetwork {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId {
|
||||
let (_, node) = &self.nodes[node_id.0 as usize];
|
||||
let mut path = node.original_location.path.clone();
|
||||
|
||||
@@ -470,7 +324,7 @@ impl ProtoNetwork {
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Nodes(vec![node_id]),
|
||||
call_argument: concrete!(Context),
|
||||
identifier: graphene_core::memo::frame_memo::IDENTIFIER,
|
||||
identifier: graphene_core::memo::memoize::IDENTIFIER,
|
||||
original_location: OriginalLocation {
|
||||
path: path.clone(),
|
||||
..Default::default()
|
||||
@@ -484,7 +338,7 @@ impl ProtoNetwork {
|
||||
self.nodes.push((
|
||||
nullification_value_node_id,
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextModification(context_deps))),
|
||||
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))),
|
||||
call_argument: concrete!(Context),
|
||||
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
|
||||
original_location: OriginalLocation {
|
||||
@@ -511,87 +365,36 @@ impl ProtoNetwork {
|
||||
nullification_node_id
|
||||
}
|
||||
|
||||
/// The node's declared dependencies and per-input pushed levels, both read
|
||||
/// from the registry since they follow the node's signature. A node with no
|
||||
/// registry entry declares nothing and pushes nothing.
|
||||
fn registry_dependencies(&self, node_index: usize) -> (ContextDependencies, Vec<u8>) {
|
||||
let identifier = &self.nodes[node_index].1.identifier;
|
||||
let metadata = core_types::registry::NODE_METADATA.lock().unwrap();
|
||||
match metadata.get(identifier) {
|
||||
Some(entry) => (
|
||||
ContextDependencies::from(entry.context_features.as_slice()),
|
||||
entry.fields.iter().map(|field| field.pushed_levels).collect(),
|
||||
),
|
||||
None => (ContextDependencies::default(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option<NodeId>) {
|
||||
let mut branch_dependencies = Vec::new();
|
||||
let mut combined_deps = ContextModification::default();
|
||||
let mut combined_deps = ContextFeatures::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let (registry_deps, pushed_levels) = self.registry_dependencies(node_index);
|
||||
let (extract, inject, own_deps) = {
|
||||
let carried = &self.nodes[node_index].1.context_features;
|
||||
// A code-built wrapper node declares dependencies its signature cannot
|
||||
// express; everything else resolves from the registry. Sources are
|
||||
// input wiring, not declarations, so they merge either way.
|
||||
let mut dependencies = match carried.extract.is_empty() && carried.inject.is_empty() {
|
||||
false => carried.clone(),
|
||||
true => registry_deps,
|
||||
};
|
||||
dependencies.add_sources(carried.sources());
|
||||
let index_levels = match dependencies.extract.contains(core_types::context::ContextFeatures::INDEX) {
|
||||
// A hand-declared `INDEX` names no level and addresses the innermost.
|
||||
true if dependencies.index_levels.is_empty() => core_types::context::IndexLevels::innermost(),
|
||||
true => dependencies.index_levels,
|
||||
false => core_types::context::IndexLevels::empty(),
|
||||
};
|
||||
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources()).with_index_levels(index_levels);
|
||||
(dependencies.extract, dependencies.inject, own_deps)
|
||||
};
|
||||
let context_features = self.nodes[node_index].1.context_features;
|
||||
|
||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
||||
ConstructionArgs::Value(value) => {
|
||||
let mut deps = own_deps;
|
||||
// A leveled value serves its lanes by the innermost index.
|
||||
if value.value_layout().is_some_and(|layout| layout.depth > 0) {
|
||||
deps |= core_types::context::ContextFeatures::INDEX;
|
||||
deps.index_levels |= core_types::context::IndexLevels::innermost();
|
||||
}
|
||||
return (deps, Some(id));
|
||||
}
|
||||
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
ConstructionArgs::Inline(_) => return (own_deps, Some(id)),
|
||||
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
|
||||
};
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
let mut lane_invariant_inputs = 0u32;
|
||||
for (input, &node) in inputs.iter().enumerate() {
|
||||
for &node in &inputs {
|
||||
let branch = self.find_context_dependencies(node);
|
||||
|
||||
let reads_innermost = branch.0.features.contains(core_types::context::ContextFeatures::INDEX) && branch.0.index_levels.contains_level(0);
|
||||
if !reads_innermost && input < 32 {
|
||||
lane_invariant_inputs |= 1 << input;
|
||||
}
|
||||
|
||||
let mut lifted = branch.0.clone();
|
||||
lifted.index_levels = lifted.index_levels.lifted(0, pushed_levels.get(input).copied().unwrap_or(0));
|
||||
combined_deps |= &lifted;
|
||||
branch_dependencies.push(branch);
|
||||
combined_deps |= branch.0;
|
||||
}
|
||||
self.nodes[node_index].1.lane_invariant_inputs = lane_invariant_inputs;
|
||||
let mut new_deps = combined_deps.clone();
|
||||
let mut new_deps = combined_deps;
|
||||
|
||||
// Remove requirements which this node provides
|
||||
new_deps &= !inject;
|
||||
new_deps &= !context_features.inject;
|
||||
// Add requirements we have
|
||||
new_deps |= own_deps;
|
||||
new_deps |= context_features.extract;
|
||||
|
||||
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
|
||||
let we_introduce_new_deps = !combined_deps.contains(&new_deps);
|
||||
let we_introduce_new_deps = !combined_deps.contains(new_deps);
|
||||
|
||||
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
|
||||
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
|
||||
@@ -604,21 +407,18 @@ impl ProtoNetwork {
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
|
||||
// Which dependencies do we supply (and don't need ourselves)?
|
||||
// TODO: a shrinking index-level mask does not count as supplying a
|
||||
// dependency, so a fold that consumes its subtree's only level inserts
|
||||
// no boundary here.
|
||||
let net_injections = inject.difference(extract);
|
||||
let net_injections = context_features.inject.difference(context_features.extract);
|
||||
|
||||
// Which dependencies still need to be met after this node?
|
||||
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
|
||||
let remaining_deps_from_children = combined_deps.difference(net_injections);
|
||||
|
||||
// Do we satisfy any existing dependencies?
|
||||
let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
|
||||
let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty();
|
||||
|
||||
let mut new_id = None;
|
||||
if we_supply_existing_deps {
|
||||
// Our set of context dependencies has shrunk so we can add a cache node after the current node
|
||||
new_id = Some(self.insert_context_nullification_node(id, new_deps.clone()));
|
||||
new_id = Some(self.insert_context_nullification_node(id, new_deps));
|
||||
}
|
||||
|
||||
(new_deps, new_id)
|
||||
@@ -745,7 +545,6 @@ pub enum GraphErrorType {
|
||||
},
|
||||
NoImplementations,
|
||||
NoConstructor,
|
||||
ConstructionFailed(String),
|
||||
/// The `inputs` represents a formatted list of input indices corresponding to their types.
|
||||
/// Each element in `error_inputs` represents a valid `NodeIOTypes` implementation.
|
||||
/// The inner Vec stores the inputs which need to be changed and what type each needs to be changed to.
|
||||
@@ -766,7 +565,6 @@ impl Debug for GraphErrorType {
|
||||
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
|
||||
GraphErrorType::NoImplementations => write!(f, "No implementations found"),
|
||||
GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
|
||||
GraphErrorType::ConstructionFailed(error) => write!(f, "Construction failed: {error}"),
|
||||
GraphErrorType::InvalidImplementations { inputs, error_inputs } => {
|
||||
let format_error = |(index, (found, expected)): &(usize, (Type, Type))| {
|
||||
let index = index + 1;
|
||||
@@ -830,34 +628,53 @@ impl Debug for GraphError {
|
||||
}
|
||||
pub type GraphErrors = Vec<GraphError>;
|
||||
|
||||
pub type Registry = HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>;
|
||||
|
||||
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
|
||||
#[derive(Default, Clone, dyn_any::DynAny)]
|
||||
pub struct TypingContext {
|
||||
lookup: Cow<'static, Registry>,
|
||||
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>>,
|
||||
inferred: HashMap<NodeId, NodeIOTypes>,
|
||||
constructor: HashMap<NodeId, NodeConstructor>,
|
||||
promotions: HashMap<NodeId, Vec<(usize, Promotion)>>,
|
||||
}
|
||||
|
||||
/// A rank adapter which type resolution marks for insertion between a wire and a connector whose ranks differ,
|
||||
/// carrying the element type the adapter is registered under.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Promotion {
|
||||
/// Raises an `Item<X>` wire onto a `List<X>` connector as a one-element list.
|
||||
ItemToList(Type),
|
||||
/// Bundles a whole `List<X>` wire into one opaque `Item<Bundle<X>>` cell.
|
||||
Bundle(Type),
|
||||
/// Unbundles an `Item<Bundle<X>>` wire back into the whole `List<X>`.
|
||||
Unbundle(Type),
|
||||
}
|
||||
|
||||
impl Promotion {
|
||||
/// The registry identifier of the adapter node monomorphized for this promotion's element type.
|
||||
pub fn adapter_identifier(&self) -> ProtoNodeIdentifier {
|
||||
let (adapter_name, element) = match self {
|
||||
Self::ItemToList(element) => ("graphene_core::ops::ItemToListNode", element),
|
||||
Self::Bundle(element) => ("graphene_core::ops::BundleNode", element),
|
||||
Self::Unbundle(element) => ("graphene_core::ops::UnbundleNode", element),
|
||||
};
|
||||
ProtoNodeIdentifier::with_owned_string(format!("{adapter_name}<{}>", element.identifier_name()))
|
||||
}
|
||||
}
|
||||
|
||||
impl TypingContext {
|
||||
/// Creates a new `TypingContext` with the given lookup table.
|
||||
pub fn new(lookup: &'static Registry) -> Self {
|
||||
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>) -> Self {
|
||||
Self {
|
||||
lookup: Cow::Borrowed(lookup),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.lookup
|
||||
}
|
||||
|
||||
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
|
||||
/// and store them in the `inferred` field. The proto network has to be topologically sorted
|
||||
/// and contain fully resolved stable node ids.
|
||||
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
|
||||
for (id, node) in &network.nodes {
|
||||
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
|
||||
for (id, node) in network.nodes.iter() {
|
||||
self.infer(*id, node)?;
|
||||
}
|
||||
|
||||
@@ -866,9 +683,20 @@ impl TypingContext {
|
||||
|
||||
pub fn remove_inference(&mut self, node_id: NodeId) -> Option<NodeIOTypes> {
|
||||
self.constructor.remove(&node_id);
|
||||
self.promotions.remove(&node_id);
|
||||
self.inferred.remove(&node_id)
|
||||
}
|
||||
|
||||
/// Returns the input positions of a node which type resolution marked for rank promotion, with each position's adapter.
|
||||
pub fn promotions(&self, node_id: NodeId) -> Option<&Vec<(usize, Promotion)>> {
|
||||
self.promotions.get(&node_id)
|
||||
}
|
||||
|
||||
/// Looks up the sole constructor registered under an adapter identifier, such as an Item -> List promotion adapter.
|
||||
pub fn adapter_constructor(&self, identifier: &ProtoNodeIdentifier) -> Option<NodeConstructor> {
|
||||
self.lookup.get(identifier).and_then(|implementations| implementations.values().next().copied())
|
||||
}
|
||||
|
||||
/// Returns the node constructor for a given node id.
|
||||
pub fn constructor(&self, node_id: NodeId) -> Option<NodeConstructor> {
|
||||
self.constructor.get(&node_id).copied()
|
||||
@@ -887,10 +715,10 @@ impl TypingContext {
|
||||
}
|
||||
|
||||
let inputs = match node.construction_args {
|
||||
// A value node is a native record source, so it types as a record
|
||||
// of its value.
|
||||
// If the node has a value input we can infer the return type from it
|
||||
ConstructionArgs::Value(ref v) => {
|
||||
let types = NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(v.ty())), vec![]);
|
||||
// TODO: This should return a reference to the value
|
||||
let types = NodeIOTypes::new(concrete!(Context), Type::Future(Box::new(v.ty())), vec![]);
|
||||
self.inferred.insert(node_id, types.clone());
|
||||
return Ok(types);
|
||||
}
|
||||
@@ -908,147 +736,217 @@ impl TypingContext {
|
||||
};
|
||||
|
||||
// Get the node input type from the proto node declaration
|
||||
let call_argument = &node.call_argument;
|
||||
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
|
||||
let (node_io, entry) = resolve_entry(node, &inputs, impls)?;
|
||||
if std::env::var("GRAPHENE_TYPE_DEBUG").is_ok() {
|
||||
eprintln!("type {} {} -> {}", node_id, node.identifier, node_io.ty());
|
||||
|
||||
if let Some(index) = inputs.iter().position(|p| {
|
||||
matches!(p,
|
||||
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
|
||||
}) {
|
||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
|
||||
}
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, entry.constructor);
|
||||
Ok(node_io)
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the single registry entry matching the node's resolved input types,
|
||||
/// substituting generics. Stateless and stable-id-free.
|
||||
fn resolve_entry<'a>(node: &ProtoNode, inputs: &[Type], impls: &'a [RegistryEntry]) -> Result<(NodeIOTypes, &'a RegistryEntry), GraphErrors> {
|
||||
let call_argument = &node.call_argument;
|
||||
let candidates: Vec<(NodeIOTypes, &RegistryEntry)> = impls.iter().map(|entry| (entry.io.clone(), entry)).collect();
|
||||
|
||||
if let Some(index) = inputs.iter().position(|p| {
|
||||
matches!(p,
|
||||
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
|
||||
}) {
|
||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs: inputs.to_vec() })]);
|
||||
}
|
||||
|
||||
// List of all implementations that match the input types
|
||||
let valid_output_types = candidates
|
||||
.iter()
|
||||
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Attempt to substitute generic types with concrete types and save the list of results
|
||||
let substitution_results = valid_output_types
|
||||
.iter()
|
||||
.map(|(node_io, entry)| {
|
||||
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
||||
.iter()
|
||||
.map(|generic| check_generic(node_io, call_argument, inputs, generic).map(|x| (generic.to_string(), x)))
|
||||
.collect();
|
||||
|
||||
generics_lookup.map(|generics_lookup| {
|
||||
let mut new_node_io = node_io.clone();
|
||||
replace_generics(&mut new_node_io, &generics_lookup);
|
||||
(new_node_io, *entry)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Collect all substitutions that are valid
|
||||
let valid_impls = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
|
||||
|
||||
match valid_impls.as_slice() {
|
||||
[] => {
|
||||
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
||||
let mut best_errors = usize::MAX;
|
||||
let mut error_inputs = Vec::new();
|
||||
for (node_io, _) in &candidates {
|
||||
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
||||
let current_errors = [call_argument]
|
||||
.into_iter()
|
||||
.chain(inputs)
|
||||
.cloned()
|
||||
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
|
||||
.enumerate()
|
||||
.filter(|(_, (p1, p2))| !valid_type(p1, p2))
|
||||
.map(|(index, expected)| (index - 1 + convert_node_index_offset, expected))
|
||||
.collect::<Vec<_>>();
|
||||
if current_errors.len() < best_errors {
|
||||
best_errors = current_errors.len();
|
||||
error_inputs.clear();
|
||||
}
|
||||
if current_errors.len() <= best_errors {
|
||||
error_inputs.push(current_errors);
|
||||
}
|
||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
match (from, to) {
|
||||
// Direct comparison of two concrete types.
|
||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||
// Check inner type for futures
|
||||
(Type::Future(type1), Type::Future(type2)) => valid_type(type1, type2),
|
||||
// Direct comparison of two function types.
|
||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// Ranked wrappers of the same rank are compared element-wise
|
||||
(Type::Item(element1), Type::Item(element2)) => valid_type(element1, element2),
|
||||
(Type::List(element1), Type::List(element2)) => valid_type(element1, element2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
// TODO: Add proper generic counting which is not based on the name
|
||||
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
||||
// Reject unknown type relationships.
|
||||
_ => false,
|
||||
}
|
||||
let inputs = [call_argument]
|
||||
.into_iter()
|
||||
.chain(inputs)
|
||||
.enumerate()
|
||||
.filter_map(|(i, t)| {
|
||||
if i == 0 {
|
||||
None
|
||||
} else {
|
||||
let number = i + convert_node_index_offset;
|
||||
Some(format!("• Input {number}: {t}"))
|
||||
}
|
||||
}
|
||||
|
||||
// List of all implementations that match the input types
|
||||
let valid_output_types = impls
|
||||
.keys()
|
||||
.filter(|node_io| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Attempt to substitute generic types with concrete types and save the list of results
|
||||
let substitution_results = valid_output_types
|
||||
.iter()
|
||||
.map(|node_io| {
|
||||
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
||||
.iter()
|
||||
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
|
||||
.collect();
|
||||
|
||||
generics_lookup.map(|generics_lookup| {
|
||||
let orig_node_io = (*node_io).clone();
|
||||
let mut new_node_io = orig_node_io.clone();
|
||||
replace_generics(&mut new_node_io, &generics_lookup);
|
||||
(new_node_io, orig_node_io)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
||||
}
|
||||
[(node_io, entry)] => Ok((node_io.clone(), *entry)),
|
||||
// If two types are available and one of them accepts () an input, always choose that one
|
||||
[first, second] => {
|
||||
if first.0.call_argument != second.0.call_argument {
|
||||
for (node_io, entry) in [first, second] {
|
||||
if node_io.call_argument != concrete!(()) {
|
||||
continue;
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Collect all substitutions that are valid
|
||||
let valid_impls = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
|
||||
|
||||
match valid_impls.as_slice() {
|
||||
[] => {
|
||||
// Retry allowing a wire whose rank differs from its connector, satisfied at construction time by an inserted promotion adapter.
|
||||
// Every rank relation is matched structurally; only the `Bundle` layer inside an `Item` cell remains name-encoded.
|
||||
fn promotable_adapter(from: &Type, to: &Type) -> Option<Promotion> {
|
||||
fn concrete_name(ty: &Type) -> Option<&str> {
|
||||
match ty {
|
||||
Type::Concrete(descriptor) => Some(&descriptor.name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let (Type::Fn(from_input, from_output), Type::Fn(to_input, to_output)) = (from, to) else {
|
||||
return None;
|
||||
};
|
||||
if !valid_type(from_input, to_input) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let from_value = from_output.nested_type();
|
||||
let to_value = to_output.nested_type();
|
||||
|
||||
match (from_value, to_value) {
|
||||
// An `Item<X>` wire may feed a `List<X>` connector via a singleton raise
|
||||
(Type::Item(from_element), Type::List(element)) if valid_type(from_element, element) => Some(Promotion::ItemToList((**element).clone())),
|
||||
|
||||
// A `List<X>` wire may feed an `Item<Bundle<X>>` connector by bundling the whole list into one opaque cell
|
||||
(Type::List(element), Type::Item(_)) if to_value.bundle_element_name().is_some_and(|name| Some(name) == concrete_name(element)) => Some(Promotion::Bundle((**element).clone())),
|
||||
|
||||
// An `Item<Bundle<X>>` wire may feed a `List<X>` connector by unbundling it back into the whole list
|
||||
(Type::Item(_), Type::List(element)) if from_value.bundle_element_name().is_some_and(|name| Some(name) == concrete_name(element)) => {
|
||||
Some(Promotion::Unbundle((**element).clone()))
|
||||
}
|
||||
|
||||
_ => None,
|
||||
}
|
||||
return Ok((node_io.clone(), *entry));
|
||||
}
|
||||
|
||||
let mut promotable_matches = impls
|
||||
.keys()
|
||||
.filter(|node_io| collect_generics(node_io).is_empty() && valid_type(&node_io.call_argument, call_argument) && inputs.len() == node_io.inputs.len())
|
||||
.filter_map(|node_io| {
|
||||
let mut required_promotions = Vec::new();
|
||||
for (index, (provided, expected)) in inputs.iter().zip(node_io.inputs.iter()).enumerate() {
|
||||
if valid_type(provided, expected) {
|
||||
continue;
|
||||
}
|
||||
required_promotions.push((index, promotable_adapter(provided, expected)?));
|
||||
}
|
||||
Some((node_io, required_promotions))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Prefer the variant needing the fewest promotions, so an Item wire resolves the all-Item variant instead of raising every ranked connector to reach the mapped variant; a tie stays ambiguous.
|
||||
promotable_matches.sort_by_key(|(_, required_promotions)| required_promotions.len());
|
||||
let minimum_promotions = promotable_matches.first().map(|(_, required_promotions)| required_promotions.len());
|
||||
let tied_at_minimum = promotable_matches
|
||||
.iter()
|
||||
.take_while(|(_, required_promotions)| Some(required_promotions.len()) == minimum_promotions)
|
||||
.count();
|
||||
|
||||
if tied_at_minimum == 1 {
|
||||
let (node_io, required_promotions) = promotable_matches.remove(0);
|
||||
let node_io = node_io.clone();
|
||||
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, impls[&node_io]);
|
||||
self.promotions.insert(node_id, required_promotions);
|
||||
return Ok(node_io);
|
||||
}
|
||||
|
||||
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
||||
let mut best_errors = usize::MAX;
|
||||
let mut error_inputs = Vec::new();
|
||||
for node_io in impls.keys() {
|
||||
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
||||
let current_errors = [call_argument]
|
||||
.into_iter()
|
||||
.chain(&inputs)
|
||||
.cloned()
|
||||
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
|
||||
.enumerate()
|
||||
.filter(|(_, (p1, p2))| !valid_type(p1, p2))
|
||||
.map(|(index, expected)| (index - 1 + convert_node_index_offset, expected))
|
||||
.collect::<Vec<_>>();
|
||||
if current_errors.len() < best_errors {
|
||||
best_errors = current_errors.len();
|
||||
error_inputs.clear();
|
||||
}
|
||||
if current_errors.len() <= best_errors {
|
||||
error_inputs.push(current_errors);
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument]
|
||||
.into_iter()
|
||||
.chain(&inputs)
|
||||
.enumerate()
|
||||
.filter_map(|(i, t)| {
|
||||
if i == 0 {
|
||||
None
|
||||
} else {
|
||||
let number = i + convert_node_index_offset;
|
||||
Some(format!("• Input {number}: {t}"))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
||||
}
|
||||
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
[(node_io, org_nio)] => {
|
||||
let node_io = node_io.clone();
|
||||
|
||||
_ => {
|
||||
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
}
|
||||
}
|
||||
// Save the inferred type
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, impls[org_nio]);
|
||||
Ok(node_io)
|
||||
}
|
||||
// If two types are available and one of them accepts () an input, always choose that one
|
||||
[first, second] => {
|
||||
if first.0.call_argument != second.0.call_argument {
|
||||
for (node_io, orig_nio) in [first, second] {
|
||||
if node_io.call_argument != concrete!(()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
match (from, to) {
|
||||
// Direct comparison of two concrete types.
|
||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||
// Direct comparison of two function types.
|
||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// A lend edge is substitutable exactly when the lent values are.
|
||||
// A record edge is substitutable exactly when the elements are.
|
||||
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
// TODO: Add proper generic counting which is not based on the name
|
||||
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
||||
// Reject unknown type relationships.
|
||||
_ => false,
|
||||
// Save the inferred type
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, impls[orig_nio]);
|
||||
return Ok(node_io.clone());
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().cloned().collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
|
||||
_ => {
|
||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().cloned().collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1070,17 +968,10 @@ fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
|
||||
|
||||
/// Checks if a generic type can be substituted with a concrete type and returns the concrete type
|
||||
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
|
||||
fn record_element(ty: Option<&Type>) -> Option<&Type> {
|
||||
match ty {
|
||||
Some(Type::Record(inner)) => Some(inner.as_ref()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let inputs = [(Some(&types.call_argument), Some(input))]
|
||||
.into_iter()
|
||||
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
|
||||
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())))
|
||||
.chain(types.inputs.iter().map(|x| record_element(x.fn_output())).zip(parameters.iter().map(|x| record_element(x.fn_output()))));
|
||||
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())));
|
||||
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
|
||||
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
|
||||
let out_ty = outputs
|
||||
@@ -1110,34 +1001,6 @@ mod test {
|
||||
use super::*;
|
||||
use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
|
||||
#[test]
|
||||
fn stack_peak_folds_a_diamond_chain() {
|
||||
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs; every frame is one byte.
|
||||
let node = |index: u64| {
|
||||
let args = if index == 0 {
|
||||
ConstructionArgs::Value(value::TaggedValue::U32(0).into())
|
||||
} else {
|
||||
ConstructionArgs::Nodes(vec![NodeId(index - 1), NodeId(index - 1)])
|
||||
};
|
||||
ProtoNode {
|
||||
construction_args: args,
|
||||
resolved: Resolved {
|
||||
layout: Some(core_types::record::RecordLayout { frame_bytes: 1, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let mut network = ProtoNetwork {
|
||||
output: NodeId(3),
|
||||
nodes: (0..4).map(|index| (NodeId(index), node(index))).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(network.fold_stack_peak(), 7);
|
||||
network.output = NodeId(0);
|
||||
assert_eq!(network.fold_stack_peak(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn topological_sort() {
|
||||
let construction_network = test_network();
|
||||
@@ -1200,81 +1063,6 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retain_filter_placement_on_source_free_branch() {
|
||||
let mut network = source_branch_network(vec![1], vec![]);
|
||||
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||
|
||||
let filters = nullification_filters(&network);
|
||||
assert_eq!(filters.len(), 1, "only the source-free branch gets a filter");
|
||||
let (filter_id, wrapped, retained) = &filters[0];
|
||||
assert_eq!(wrapped, "source_b");
|
||||
assert!(retained.is_empty(), "the source-free branch retains no sources");
|
||||
|
||||
let (source_a_id, _) = find_node(&network, "source_a");
|
||||
let (_, join) = find_node(&network, "join");
|
||||
let ConstructionArgs::Nodes(join_args) = &join.construction_args else {
|
||||
panic!("join args must be nodes")
|
||||
};
|
||||
assert_eq!(join_args, &vec![source_a_id, *filter_id], "the source branch stays direct, the filter replaces the source-free branch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diverging_source_sets_filter_each_branch() {
|
||||
let mut network = source_branch_network(vec![1], vec![2]);
|
||||
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||
|
||||
let mut filters = nullification_filters(&network);
|
||||
filters.sort_by(|(_, a, _), (_, b, _)| a.cmp(b));
|
||||
let summary: Vec<_> = filters.iter().map(|(_, wrapped, retained)| (wrapped.as_str(), retained.as_slice())).collect();
|
||||
assert_eq!(
|
||||
summary,
|
||||
vec![("source_a", &[1u64][..]), ("source_b", &[2u64][..])],
|
||||
"each diverging branch is filtered down to its own source set"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_source_sets_insert_no_filter() {
|
||||
let mut network = source_branch_network(vec![1], vec![1]);
|
||||
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||
|
||||
assert!(nullification_filters(&network).is_empty(), "equal branch source sets need no filter");
|
||||
}
|
||||
|
||||
fn find_node<'a>(network: &'a ProtoNetwork, name: &str) -> (NodeId, &'a ProtoNode) {
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.identifier.as_str() == name)
|
||||
.map(|(id, node)| (*id, node))
|
||||
.unwrap_or_else(|| panic!("node {name} not found"))
|
||||
}
|
||||
|
||||
fn nullification_filters(network: &ProtoNetwork) -> Vec<(NodeId, String, Vec<SourceId>)> {
|
||||
let node = |id: NodeId| &network.nodes[id.0 as usize].1;
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, candidate)| candidate.identifier.as_str() == graphene_core::context_modification::context_modification::IDENTIFIER.as_str())
|
||||
.map(|(id, candidate)| {
|
||||
let ConstructionArgs::Nodes(args) = &candidate.construction_args else {
|
||||
panic!("filter args must be nodes")
|
||||
};
|
||||
let ConstructionArgs::Nodes(memoized) = &node(args[0]).construction_args else {
|
||||
panic!("filter memoize args must be nodes")
|
||||
};
|
||||
let ConstructionArgs::Value(value) = &node(args[1]).construction_args else {
|
||||
panic!("filter payload must be a value")
|
||||
};
|
||||
let value::TaggedValue::ContextModification(modification) = &**value else {
|
||||
panic!("filter payload must be a context modification")
|
||||
};
|
||||
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn test_network() -> ProtoNetwork {
|
||||
ProtoNetwork {
|
||||
inputs: vec![NodeId(10)],
|
||||
@@ -1328,46 +1116,6 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn source_branch_network(branch_a_sources: Vec<SourceId>, branch_b_sources: Vec<SourceId>) -> ProtoNetwork {
|
||||
let branch = |name: &str, sources: Vec<SourceId>| ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
|
||||
context_features: ContextDependencies::from_sources(&sources),
|
||||
..Default::default()
|
||||
};
|
||||
ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: [
|
||||
(
|
||||
NodeId(0),
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("value"),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(2).into()),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(NodeId(1), branch("source_a", branch_a_sources)),
|
||||
(NodeId(2), branch("source_b", branch_b_sources)),
|
||||
(
|
||||
NodeId(3),
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("join"),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1397,7 +1145,6 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::graphene_compiler::Compiler;
|
||||
use crate::proto::{ProtoNetwork, Registry};
|
||||
use crate::proto::ProtoNetwork;
|
||||
|
||||
pub fn load_network(document_string: &str) -> NodeNetwork {
|
||||
let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document");
|
||||
@@ -8,9 +8,9 @@ pub fn load_network(document_string: &str) -> NodeNetwork {
|
||||
serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document")
|
||||
}
|
||||
|
||||
pub fn compile(network: NodeNetwork, registry: &Registry) -> ProtoNetwork {
|
||||
pub fn compile(network: NodeNetwork) -> ProtoNetwork {
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network, registry).unwrap()
|
||||
compiler.compile_single(network).unwrap()
|
||||
}
|
||||
|
||||
pub fn load_from_name(name: &str) -> NodeNetwork {
|
||||
|
||||
@@ -1,40 +1,15 @@
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::core_types::gpoll::GPoll;
|
||||
use graphene_std::core_types::ops::ConvertAsync;
|
||||
use graphene_std::core_types::ops::Convert;
|
||||
use graphene_std::core_types::transform::Footprint;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use std::error::Error;
|
||||
use std::io::Cursor;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::Duration;
|
||||
|
||||
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
loop {
|
||||
while completion.try_recv().is_ok() {}
|
||||
match executor.execute(render_config)? {
|
||||
GPoll::Final(value) => return Ok(value),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
return Ok(value);
|
||||
}
|
||||
GPoll::Partial(_) | GPoll::Pending => {
|
||||
completion
|
||||
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
|
||||
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
|
||||
}
|
||||
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FileType {
|
||||
Svg,
|
||||
@@ -53,16 +28,14 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn export_document(
|
||||
pub async fn export_document(
|
||||
executor: &DynamicExecutor,
|
||||
wgpu_executor: wgpu_executor::WgpuExecutorHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
file_type: FileType,
|
||||
scale: f64,
|
||||
(width, height): (Option<u32>, Option<u32>),
|
||||
transparent: bool,
|
||||
completion: &Receiver<()>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Determine export format based on file type
|
||||
let export_format = match file_type {
|
||||
@@ -84,7 +57,7 @@ pub fn export_document(
|
||||
}
|
||||
|
||||
// Execute the graph
|
||||
let result = execute_until_final(executor, render_config, completion)?;
|
||||
let result = executor.execute(render_config.into_context()).await?;
|
||||
|
||||
// Handle the result based on output type
|
||||
match result {
|
||||
@@ -97,7 +70,7 @@ pub fn export_document(
|
||||
RenderOutputType::Texture(texture) => {
|
||||
// Convert GPU texture to CPU buffer
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
|
||||
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await;
|
||||
let (data, width, height) = cpu_raster.to_flat_u8();
|
||||
|
||||
// Encode and write raster image
|
||||
@@ -176,14 +149,13 @@ impl AnimationParams {
|
||||
}
|
||||
|
||||
/// Export an animated GIF by rendering multiple frames at different animation times
|
||||
pub fn export_gif(
|
||||
pub async fn export_gif(
|
||||
executor: &DynamicExecutor,
|
||||
wgpu_executor: wgpu_executor::WgpuExecutorHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
scale: f64,
|
||||
(width, height): (Option<u32>, Option<u32>),
|
||||
animation: AnimationParams,
|
||||
completion: &Receiver<()>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
use image::codecs::gif::{GifEncoder, Repeat};
|
||||
use image::{Frame, RgbaImage};
|
||||
@@ -223,14 +195,14 @@ pub fn export_gif(
|
||||
}
|
||||
|
||||
// Execute the graph for this frame
|
||||
let result = execute_until_final(executor, render_config, completion)?;
|
||||
let result = executor.execute(render_config.into_context()).await?;
|
||||
|
||||
// Extract RGBA data from result
|
||||
let (data, img_width, img_height) = match result {
|
||||
TaggedValue::RenderOutput(output) => match output.data {
|
||||
RenderOutputType::Texture(texture) => {
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
|
||||
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await;
|
||||
cpu_raster.to_flat_u8()
|
||||
}
|
||||
RenderOutputType::Buffer { data, width, height } => (data, width, height),
|
||||
|
||||
@@ -7,13 +7,13 @@ use document_format::{GddV1, GddV1Layout};
|
||||
use fern::colors::{Color, ColoredLevelConfig};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::application_io::EditorPreferences;
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::error::Error;
|
||||
@@ -28,35 +28,6 @@ impl NodeGraphUpdateSender for UpdateLogger {
|
||||
}
|
||||
}
|
||||
|
||||
struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||
|
||||
impl TokioSpawner {
|
||||
fn new() -> Result<Self, std::io::Error> {
|
||||
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||
let _guard = runtime.enter();
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
runtime.spawn(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
|
||||
impl Drop for TokioSpawner {
|
||||
fn drop(&mut self) {
|
||||
if let Some(runtime) = self.0.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[clap(name = "graphene-cli", version)]
|
||||
pub struct App {
|
||||
@@ -130,7 +101,8 @@ struct GlobalOpts {
|
||||
verbose: u8,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app = App::parse();
|
||||
|
||||
let log_level = app.global_opts.verbose;
|
||||
@@ -158,7 +130,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let gdd = if is_gdd {
|
||||
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
let gdd = block_on(document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)).map_err(|error| format!("Failed to open document: {error}"))?;
|
||||
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)
|
||||
.await
|
||||
.map_err(|error| format!("Failed to open document: {error}"))?;
|
||||
Some(gdd)
|
||||
} else {
|
||||
None
|
||||
@@ -166,7 +140,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
if let Command::ExtractLegacyDoc { ref document } = app.command {
|
||||
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
|
||||
let Some(legacy_doc) = block_on(gdd.read_legacy_document()) else {
|
||||
let Some(legacy_doc) = gdd.read_legacy_document().await else {
|
||||
return Err("gdd file did not contain a legacy .graphite document".into());
|
||||
};
|
||||
let mut new_path = document.clone();
|
||||
@@ -179,7 +153,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
|
||||
let node_network = match &gdd {
|
||||
Some(gdd) => {
|
||||
let declarations = block_on(gdd.declarations(gdd));
|
||||
let declarations = gdd.declarations(gdd).await;
|
||||
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
node_network
|
||||
}
|
||||
@@ -190,7 +164,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
};
|
||||
|
||||
log::info!("Creating GPU context");
|
||||
let mut application_io = block_on(PlatformApplicationIo::new());
|
||||
let mut application_io = PlatformApplicationIo::new().await;
|
||||
if let Some(gdd) = &gdd {
|
||||
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
||||
}
|
||||
@@ -202,22 +176,16 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let application_io_for_api = application_io_arc.clone();
|
||||
|
||||
// Get reference to wgpu executor and clone device handle
|
||||
let wgpu_executor_ref = wgpu_executor::WgpuExecutorHandle(application_io_arc.gpu_executor_arc().unwrap());
|
||||
let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap();
|
||||
let device = wgpu_executor_ref.context().device.clone();
|
||||
|
||||
let preferences = EditorPreferences {
|
||||
max_render_region_size: EditorPreferences::default().max_render_region_size,
|
||||
};
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
|
||||
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
|
||||
graph_runtime.set_notifier(Arc::new(move || {
|
||||
let _ = completion_sender.send(());
|
||||
}));
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(application_io_for_api),
|
||||
node_graph_message_sender: Box::new(UpdateLogger {}),
|
||||
editor_preferences: Box::new(preferences),
|
||||
runtime: RuntimeHandle(graph_runtime.clone()),
|
||||
});
|
||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
|
||||
|
||||
@@ -250,7 +218,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let file_type = export::detect_file_type(&output)?;
|
||||
|
||||
// Create executor
|
||||
let executor = create_executor(proto_graph, graph_runtime)?;
|
||||
let executor = create_executor(proto_graph)?;
|
||||
|
||||
if fps <= 0. {
|
||||
return Err("Fps number must be positive".into());
|
||||
@@ -259,9 +227,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Perform export based on file type
|
||||
if file_type == export::FileType::Gif {
|
||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
|
||||
export::export_gif(&executor, wgpu_executor_ref, output, scale, (width, height), animation).await?;
|
||||
} else {
|
||||
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
|
||||
export::export_document(&executor, wgpu_executor_ref, output, file_type, scale, (width, height), transparent).await?;
|
||||
}
|
||||
}
|
||||
_ => unreachable!("All other commands should be handled before this match statement is run"),
|
||||
@@ -314,11 +282,10 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
|
||||
}
|
||||
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network, &interpreted_executor::node_registry::NODE_REGISTRY).map_err(|x| x.into())
|
||||
compiler.compile_single(network).map_err(|x| x.into())
|
||||
}
|
||||
|
||||
fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
let mut executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
||||
executor.set_runtime(runtime);
|
||||
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
let executor = block_on(DynamicExecutor::new(proto_network)).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
||||
Ok(executor)
|
||||
}
|
||||
@@ -15,7 +15,6 @@ wasm = ["graphene-std/wasm"]
|
||||
graphene-std = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graphene-core = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
dyn-any = { workspace = true }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use criterion::BenchmarkGroup;
|
||||
use criterion::measurement::Measurement;
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
@@ -12,13 +13,11 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let mut network = wrap_network_in_scope(network, editor_api);
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
|
||||
let proto_network = compile(network);
|
||||
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
// Some benches in this module's include set drive the demos themselves.
|
||||
#[allow(dead_code)]
|
||||
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
|
||||
where
|
||||
F: Fn(&str, &mut BenchmarkGroup<M>),
|
||||
|
||||
@@ -2,15 +2,17 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
|
||||
fn subsequent_evaluations(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("Subsequent Evaluations");
|
||||
let context = RenderConfig::default();
|
||||
let context = RenderConfig::default().into_context();
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
let (executor, _) = setup_network(name);
|
||||
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
|
||||
let context = context.clone();
|
||||
g.bench_function(name, |b| {
|
||||
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap())
|
||||
});
|
||||
});
|
||||
group.finish();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
mod benchmark_util;
|
||||
|
||||
use benchmark_util::setup_network;
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -11,17 +10,17 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
let (executor, _) = setup_network(name);
|
||||
|
||||
// Warm up the cache by running once
|
||||
let context = RenderConfig::default();
|
||||
let _ = Executor::execute(&&executor, context);
|
||||
let context = RenderConfig::default().into_context();
|
||||
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
|
||||
|
||||
executor
|
||||
}
|
||||
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = RenderConfig::default();
|
||||
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
let context = RenderConfig::default().into_context();
|
||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -8,12 +8,15 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
|
||||
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
let proto_network = compile(network);
|
||||
let empty = ProtoNetwork::default();
|
||||
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
|| (executor.clone(), proto_network.clone()),
|
||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
@@ -28,12 +31,12 @@ fn update_executor_demo(c: &mut Criterion) {
|
||||
|
||||
fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
let proto_network = compile(network);
|
||||
|
||||
let executor = DynamicExecutor::new(proto_network).unwrap();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap();
|
||||
let footprint = Footprint::default();
|
||||
|
||||
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
|
||||
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint))));
|
||||
}
|
||||
fn run_once_demo(c: &mut Criterion) {
|
||||
let mut g = c.benchmark_group("Run Once no render");
|
||||
|
||||
@@ -2,20 +2,18 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
|
||||
fn run_once(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("Run Once");
|
||||
let context = RenderConfig::default();
|
||||
let context = RenderConfig::default().into_context();
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
let (_, network) = setup_network(name);
|
||||
let context = context.clone();
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched_ref(
|
||||
|| DynamicExecutor::new(network.clone()).unwrap(),
|
||||
|executor| Executor::execute(&&*executor, std::hint::black_box(context)).unwrap(),
|
||||
criterion::BatchSize::LargeInput,
|
||||
b.iter_batched(
|
||||
|| setup_network(name),
|
||||
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap(),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
mod benchmark_util;
|
||||
|
||||
use benchmark_util::setup_network;
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -13,13 +12,13 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
|
||||
}
|
||||
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> (DynamicExecutor, core_types::gpoll::GPoll<graph_craft::document::value::TaggedValue>) {
|
||||
let context = application_io::RenderConfig::default();
|
||||
let result = black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = application_io::RenderConfig::default().into_context();
|
||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
||||
|
||||
// Return the executor and result so their teardown happens outside the measured section
|
||||
(executor, result)
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
}
|
||||
|
||||
library_benchmark_group!(name = run_once_group; benchmarks = run_once);
|
||||
|
||||
@@ -9,14 +9,14 @@ fn update_executor(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("Update Executor");
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched_ref(
|
||||
b.iter_batched(
|
||||
|| {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
(executor, proto_network)
|
||||
},
|
||||
|(executor, network)| executor.update(std::hint::black_box(std::mem::take(network))),
|
||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::hint::black_box;
|
||||
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
||||
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
||||
let (mut executor, network) = setup;
|
||||
let _ = black_box(executor.update(black_box(network)));
|
||||
let _ = black_box(futures::executor::block_on(executor.update(black_box(network))));
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -1,46 +1,17 @@
|
||||
use crate::node_registry;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||
use dyn_any::StaticType;
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graph_craft::proto::{ConstructionArgs, GraphError, ProtoNetwork, ProtoNode, TypingContext};
|
||||
use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const ARENA_CAPACITY: usize = 1 << 27;
|
||||
|
||||
const PERSISTENT_CAPACITY: usize = 1 << 26;
|
||||
|
||||
/// The heap the persistent region's parked payloads may own before a flush.
|
||||
/// Occupancy cannot stand in for it: a park costs one pointer in the region
|
||||
/// and owns its content outside it, so the two diverge by orders of magnitude.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
const PERSISTENT_HEAP_BUDGET: usize = 1 << 29;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
const PERSISTENT_HEAP_BUDGET: usize = 1 << 28;
|
||||
|
||||
/// The share of a budget that triggers a flush at the next boundary, chosen so
|
||||
/// the region is emptied before a promote is refused mid-evaluation.
|
||||
fn over_budget(used: usize, budget: usize) -> bool {
|
||||
used >= budget / 8 * 7
|
||||
}
|
||||
|
||||
fn new_arena(capacity: usize) -> Arena {
|
||||
Arena::new(capacity).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
Arena::parked()
|
||||
})
|
||||
}
|
||||
use std::sync::Arc;
|
||||
|
||||
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
|
||||
#[derive(Clone)]
|
||||
pub struct DynamicExecutor {
|
||||
output: NodeId,
|
||||
/// Stores all of the dynamic node structs.
|
||||
@@ -49,19 +20,6 @@ pub struct DynamicExecutor {
|
||||
typing_context: TypingContext,
|
||||
// This allows us to keep the nodes around for one more frame which is used for introspection
|
||||
orphaned_nodes: HashSet<NodeId>,
|
||||
arena: Mutex<Arena>,
|
||||
/// The region memo levels are promoted into: reset only between
|
||||
/// evaluations, and only once a promote has been refused.
|
||||
persistent: Mutex<Arena>,
|
||||
/// The record frame space, grow-only across evaluations and lent to the
|
||||
/// root by `&mut`.
|
||||
frames: Mutex<core_types::record::FrameArena>,
|
||||
runtime: Arc<DynGraphRuntime>,
|
||||
live_sources: Vec<core_types::SourceId>,
|
||||
}
|
||||
|
||||
fn noop_runtime() -> Arc<DynGraphRuntime> {
|
||||
Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>))
|
||||
}
|
||||
|
||||
impl Default for DynamicExecutor {
|
||||
@@ -71,11 +29,6 @@ impl Default for DynamicExecutor {
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
|
||||
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
|
||||
frames: Mutex::new(core_types::record::FrameArena::new()),
|
||||
runtime: noop_runtime(),
|
||||
live_sources: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,42 +48,25 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
}
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
pub async fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&mut proto_network)?;
|
||||
typing_context.update(&proto_network)?;
|
||||
let output = proto_network.output;
|
||||
let sources = proto_network.source_ids();
|
||||
let tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||
let runtime = noop_runtime();
|
||||
runtime.retain_sources(&sources);
|
||||
let tree = BorrowTree::new(proto_network, &typing_context).await?;
|
||||
|
||||
Ok(Self {
|
||||
tree,
|
||||
output,
|
||||
typing_context,
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
|
||||
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
|
||||
frames: Mutex::new(core_types::record::FrameArena::new()),
|
||||
runtime,
|
||||
live_sources: sources,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_runtime(&mut self, runtime: Arc<DynGraphRuntime>) {
|
||||
runtime.retain_sources(&self.live_sources);
|
||||
self.runtime = runtime;
|
||||
}
|
||||
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.runtime.take_dirty()
|
||||
}
|
||||
|
||||
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
|
||||
#[cfg_attr(debug_assertions, inline(never))]
|
||||
pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
pub async fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.output = proto_network.output;
|
||||
self.typing_context.update(&mut proto_network).map_err(|e| {
|
||||
self.typing_context.update(&proto_network).map_err(|e| {
|
||||
// If there is an error then get types that have been resolved before the error
|
||||
let add = proto_network
|
||||
.nodes
|
||||
@@ -151,10 +87,11 @@ impl DynamicExecutor {
|
||||
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
||||
})?;
|
||||
|
||||
let sources = proto_network.source_ids();
|
||||
let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
self.runtime.retain_sources(&sources);
|
||||
self.live_sources = sources;
|
||||
let (add, orphaned) = self
|
||||
.tree
|
||||
.update(proto_network, &self.typing_context)
|
||||
.await
|
||||
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
||||
for node_id in old_to_remove {
|
||||
@@ -170,73 +107,9 @@ impl DynamicExecutor {
|
||||
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node. A monitor serializes
|
||||
/// its stored context snapshot, and this entry recreates the monitored
|
||||
/// value from it as the legacy value the editor's downcasts expect: a
|
||||
/// rank-0 wire yields its element and a leveled wire its legacy list.
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let result = self.tree.introspect(node_path)?;
|
||||
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
|
||||
return self
|
||||
.introspect_with(node_path, |layout, batch, arena| graphic_types::boundary::batch_to_legacy(layout, batch, arena))
|
||||
.map(Arc::from);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Re-evaluates the monitored edge at `node_path` with its stored context
|
||||
/// snapshot and hands the resulting resident batch to `read`, inside the
|
||||
/// introspection window. The monitor stores only the context; the value is
|
||||
/// recreated against current source data, so a read right after an
|
||||
/// execution serves out of the warm memo entries.
|
||||
pub fn introspect_with<R>(&self, node_path: &[NodeId], read: impl FnOnce(&core_types::record::Layout, core_types::node::RecordBatch<'_>, &Arena) -> Option<R>) -> Result<R, IntrospectError> {
|
||||
let serialized = self.tree.introspect(node_path)?;
|
||||
let Some(snapshot) = serialized.downcast_ref::<core_types::context::CtxSnapshot>() else {
|
||||
return Err(IntrospectError::NoData);
|
||||
};
|
||||
let edge = self
|
||||
.tree
|
||||
.get_by_path(node_path)
|
||||
.and_then(EdgeHandle::record_edge)
|
||||
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
buffer.reserve(self.tree.stack_need());
|
||||
let frames = buffer.frames();
|
||||
let generations = self.runtime.snapshot();
|
||||
let scope = EvalScope::new(snapshot.try_real_time(), snapshot.try_animation_time(), snapshot.try_pointer_position(), &generations, &arena).with_persistent(&persistent);
|
||||
let Some(ctx) = snapshot.rehydrate(&scope) else {
|
||||
return Err(IntrospectError::NoData);
|
||||
};
|
||||
let layout = core_types::node::Node::<ContextImpl>::layout(&edge);
|
||||
// The batch borrows the frames the read closure is handed, so the read
|
||||
// cannot outlive the scope that owns them.
|
||||
let frames = frames.scope();
|
||||
let result = if layout.depth > 0 {
|
||||
match core_types::record::materialize_level(&edge, &ctx, &arena, &frames) {
|
||||
core_types::record::LevelStatus::Batch(batch, _) => read(layout, batch, &arena),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
match core_types::record::serve_edge(&edge, &ctx, &frames) {
|
||||
GPoll::Final(value) | GPoll::Partial(value) => {
|
||||
let rec = layout.rec(&value);
|
||||
// SAFETY: the serve produced one live record of the edge's layout.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
|
||||
read(layout, batch, &arena)
|
||||
}
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, _) = *boxed;
|
||||
let rec = layout.rec(&value);
|
||||
// SAFETY: as for the final arm.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
|
||||
read(layout, batch, &arena)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
result.ok_or(IntrospectError::NoData)
|
||||
self.tree.introspect(node_path)
|
||||
}
|
||||
|
||||
pub fn input_type(&self) -> Option<Type> {
|
||||
@@ -262,75 +135,27 @@ impl DynamicExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> Executor<I, GPoll<TaggedValue>> for &DynamicExecutor
|
||||
impl<I> Executor<I, TaggedValue> for &DynamicExecutor
|
||||
where
|
||||
I: VarArg + Send + Sync + std::panic::RefUnwindSafe,
|
||||
I: StaticType + 'static + Send + Sync,
|
||||
{
|
||||
fn execute(&self, input: I) -> Result<GPoll<TaggedValue>, Box<dyn Error>> {
|
||||
let Some(handle) = self.tree.get(self.output) else {
|
||||
return Err("Output node not found in executor".into());
|
||||
};
|
||||
let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
// The region is flushed whole between evaluations and the memos
|
||||
// re-promote: on a refusal, which leaves no room for the next promote,
|
||||
// and ahead of one where either the region itself or the heap its
|
||||
// parked payloads own is close to full.
|
||||
if persistent.exhausted() || over_budget(persistent.occupancy(), persistent.capacity()) || over_budget(persistent.retained_heap(), PERSISTENT_HEAP_BUDGET) {
|
||||
persistent.reset();
|
||||
}
|
||||
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
buffer.reserve(self.tree.stack_need());
|
||||
let result = eval_root(&mut arena, &persistent, &mut buffer, &self.runtime, &input, |ctx, frames| {
|
||||
match TaggedValue::from_edge(handle.duplicate(), ctx, frames) {
|
||||
Ok(poll) => poll.map(Ok),
|
||||
Err(error) => GPoll::Final(Err(error)),
|
||||
}
|
||||
});
|
||||
match result {
|
||||
GPoll::Final(value) => Ok(GPoll::Final(value?)),
|
||||
GPoll::Partial(value) => Ok(GPoll::Partial(value?)),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
Ok(GPoll::Fallback(Box::new((value?, error))))
|
||||
}
|
||||
GPoll::Pending => Ok(GPoll::Pending),
|
||||
GPoll::Error(error) => Ok(GPoll::Error(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One evaluation over the arena and the frame buffer, which the caller sized
|
||||
/// to the graph's frame need: both are the evaluation's lifetime, so a record
|
||||
/// served anywhere in the cone lives exactly as long as the arena it may
|
||||
/// reference. The persistent region is borrowed shared for the same span, so
|
||||
/// no flush can land while a value promoted into it is readable.
|
||||
pub fn eval_root<S, T>(
|
||||
arena: &mut Arena,
|
||||
persistent: &Arena,
|
||||
buffer: &mut core_types::record::FrameArena,
|
||||
runtime: &GraphRuntime<S>,
|
||||
call_argument: DynSlot,
|
||||
eval: impl for<'e> FnOnce(&ContextImpl<'e>, &core_types::record::Frames<'e>) -> GPoll<T>,
|
||||
) -> GPoll<T> {
|
||||
arena.reset();
|
||||
let generations = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &generations, arena).with_persistent(persistent);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let link = VarArgLink {
|
||||
args: VarArgSlots::Single(call_argument),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&link);
|
||||
let frames = buffer.frames();
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx, &frames))) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
arena.reset();
|
||||
GPoll::panicked()
|
||||
}
|
||||
}
|
||||
}
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> {
|
||||
Box::pin(async move {
|
||||
use futures::FutureExt;
|
||||
|
||||
let result = self.tree.eval_tagged_value(self.output, input);
|
||||
let wrapped_result = std::panic::AssertUnwindSafe(result).catch_unwind().await;
|
||||
|
||||
match wrapped_result {
|
||||
Ok(result) => result.map_err(|e| e.into()),
|
||||
Err(e) => {
|
||||
Box::leak(e);
|
||||
Err("Node graph execution panicked".into())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
pub struct InputMapping {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -363,76 +188,85 @@ impl std::fmt::Display for IntrospectError {
|
||||
///
|
||||
/// # Fields
|
||||
///
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`EdgeHandle`] and [`Path`].
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`] and [`Path`].
|
||||
/// This stores the actual node instances and their associated paths.
|
||||
///
|
||||
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
||||
/// This maps document paths to node IDs and their associated type information.
|
||||
///
|
||||
/// A store of the dynamically typed nodes and also the source map.
|
||||
#[derive(Default)]
|
||||
#[derive(Default, Clone)]
|
||||
pub struct BorrowTree {
|
||||
/// A hashmap of node IDs and dynamically typed nodes.
|
||||
nodes: HashMap<NodeId, (EdgeHandle, Path)>,
|
||||
nodes: HashMap<NodeId, (SharedNodeContainer, Path)>,
|
||||
/// A hashmap from the document path to the proto node ID.
|
||||
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
||||
/// The record-stack reserve, folded from the graph at construction.
|
||||
stack_need: usize,
|
||||
}
|
||||
|
||||
impl BorrowTree {
|
||||
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||
pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||
let mut nodes = BorrowTree::default();
|
||||
let stack_need = proto_network.stack_need;
|
||||
for (id, node) in proto_network.nodes {
|
||||
nodes.push_node(id, node, typing_context)?
|
||||
nodes.push_node(id, node, typing_context).await?
|
||||
}
|
||||
nodes.stack_need = stack_need;
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
/// Pushes new nodes into the tree and return orphaned nodes
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||
let stack_need = proto_network.stack_need;
|
||||
pub async fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
|
||||
let mut new_nodes: Vec<_> = Vec::new();
|
||||
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
||||
for (id, node) in proto_network.nodes {
|
||||
if !self.nodes.contains_key(&id) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
self.push_node(id, node, typing_context)?;
|
||||
self.push_node(id, node, typing_context).await?;
|
||||
} else if self.update_source_map(id, typing_context, &node) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
}
|
||||
old_nodes.remove(&id);
|
||||
}
|
||||
self.stack_need = stack_need;
|
||||
Ok((new_nodes, old_nodes))
|
||||
}
|
||||
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<EdgeHandle> {
|
||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> {
|
||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect()
|
||||
}
|
||||
|
||||
fn store_node(&mut self, node: EdgeHandle, id: NodeId, path: Path) {
|
||||
fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path) {
|
||||
self.nodes.insert(id, (node, path));
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured io record for a monitor node. The node path must match the document node path.
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||
node.serialize().ok_or(IntrospectError::NoData)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: NodeId) -> Option<EdgeHandle> {
|
||||
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> {
|
||||
self.nodes.get(&id).map(|(node, _)| node.clone())
|
||||
}
|
||||
|
||||
/// The edge handle for the node at a document path.
|
||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<EdgeHandle> {
|
||||
let (id, _) = self.source_map.get(node_path)?;
|
||||
self.get(*id)
|
||||
/// Evaluate the output node of the [`BorrowTree`].
|
||||
pub async fn eval<'i, I, O>(&'i self, id: NodeId, input: I) -> Option<O>
|
||||
where
|
||||
I: StaticType + 'i + Send + Sync,
|
||||
O: StaticType + 'i,
|
||||
{
|
||||
let (node, _path) = self.nodes.get(&id).cloned()?;
|
||||
let output = node.eval(Box::new(input));
|
||||
dyn_any::downcast::<O>(output.await).ok().map(|o| *o)
|
||||
}
|
||||
/// Evaluate the output node of the [`BorrowTree`] and cast it to a tagged value.
|
||||
/// This ensures that no borrowed data can escape the node graph.
|
||||
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
|
||||
where
|
||||
I: StaticType + 'static + Send + Sync,
|
||||
{
|
||||
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
|
||||
let output = node.eval(Box::new(input));
|
||||
TaggedValue::try_from_any(output.await)
|
||||
}
|
||||
|
||||
/// Removes a node from the [`BorrowTree`] and returns its associated path.
|
||||
@@ -459,10 +293,10 @@ impl BorrowTree {
|
||||
/// use interpreted_executor::node_registry;
|
||||
///
|
||||
///
|
||||
/// fn example() -> Result<(), GraphErrors> {
|
||||
/// async fn example() -> Result<(), GraphErrors> {
|
||||
/// let (proto_network, node_id, proto_node) = ProtoNetwork::example();
|
||||
/// let typing_context = TypingContext::default();
|
||||
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||
/// let typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context).await?;
|
||||
///
|
||||
/// // Assert that the node exists in the BorrowTree
|
||||
/// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal");
|
||||
@@ -559,26 +393,42 @@ impl BorrowTree {
|
||||
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
||||
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
||||
/// - Returns an error if no constructor is found for the given node ID.
|
||||
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||
async fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||
self.update_source_map(id, typing_context, &proto_node);
|
||||
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
||||
|
||||
match &proto_node.construction_args {
|
||||
ConstructionArgs::Value(value) => {
|
||||
let node = (**value)
|
||||
.clone()
|
||||
.to_edge()
|
||||
.map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(error))])?;
|
||||
let node = if let TaggedValue::EditorApi(api) = &**value {
|
||||
let editor_api = UpcastAsRefNode::new(api.clone());
|
||||
let node = Box::new(editor_api) as TypeErasedBox<'_>;
|
||||
NodeContainer::new(node)
|
||||
} else {
|
||||
let upcasted = UpcastNode::new(value.to_owned());
|
||||
let node = Box::new(upcasted) as TypeErasedBox<'_>;
|
||||
NodeContainer::new(node)
|
||||
};
|
||||
self.store_node(node, id, path.into());
|
||||
}
|
||||
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
|
||||
ConstructionArgs::Nodes(ids) => {
|
||||
let construction_nodes = self.node_deps(ids);
|
||||
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
||||
let mut node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
|
||||
if let Some(layout) = proto_node.resolved_layout() {
|
||||
node.set_layout(layout.clone());
|
||||
let ids = ids.to_vec();
|
||||
let mut construction_nodes = self.node_deps(&ids);
|
||||
|
||||
// Wrap arguments the typing pass marked for rank promotion with their adapter node
|
||||
if let Some(promotions) = typing_context.promotions(id) {
|
||||
for (argument_index, promotion) in promotions {
|
||||
let adapter_constructor = typing_context
|
||||
.adapter_constructor(&promotion.adapter_identifier())
|
||||
.ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
||||
let adapter = adapter_constructor(vec![construction_nodes[*argument_index].clone()]).await;
|
||||
construction_nodes[*argument_index] = NodeContainer::new(adapter);
|
||||
}
|
||||
}
|
||||
|
||||
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
||||
let node = constructor(construction_nodes).await;
|
||||
let node = NodeContainer::new(node);
|
||||
self.store_node(node, id, path.into());
|
||||
}
|
||||
};
|
||||
@@ -589,309 +439,7 @@ impl BorrowTree {
|
||||
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
||||
&self.source_map
|
||||
}
|
||||
|
||||
/// The record-stack reserve of an evaluation, folded from the resolved layouts by the layout pass.
|
||||
pub fn stack_need(&self) -> usize {
|
||||
self.stack_need
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::arena::ArenaCell;
|
||||
use core_types::context::{ExtractFootprint, ExtractVarArgs};
|
||||
use core_types::runtime::{SourceFuture, Spawner};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
struct InertSpawner;
|
||||
|
||||
impl Spawner for InertSpawner {
|
||||
fn spawn(&self, _task: SourceFuture) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flush_trigger_fires_on_occupancy_and_on_retained_heap() {
|
||||
assert!(!over_budget(0, 1 << 10));
|
||||
assert!(!over_budget(1 << 10 >> 1, 1 << 10), "half full stays");
|
||||
assert!(over_budget(1 << 10 >> 3 << 3, 1 << 10), "a full region flushes");
|
||||
assert!(over_budget((1 << 10) / 8 * 7, 1 << 10), "seven eighths is the trigger");
|
||||
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
assert!(!over_budget(arena.retained_heap(), PERSISTENT_HEAP_BUDGET), "an empty region is under every budget");
|
||||
let owned = vec![0u8; 4096];
|
||||
let length = owned.len();
|
||||
arena.alloc_sized(owned, length).unwrap();
|
||||
assert_eq!(arena.retained_heap(), length);
|
||||
assert!(over_budget(arena.retained_heap(), 4096), "the heap hint alone can trigger a flush");
|
||||
assert!(
|
||||
!over_budget(arena.occupancy(), arena.capacity()),
|
||||
"occupancy stays low while the retained heap is large, which is why the trigger reads both"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let persistent = Arena::new(64).unwrap();
|
||||
let mut buffer = core_types::record::FrameArena::new();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let argument = 21.5f64;
|
||||
let result = eval_root(&mut arena, &persistent, &mut buffer, &runtime, &argument, |ctx, _frames| {
|
||||
assert!(ctx.try_footprint().is_none(), "the bare root carries no axes");
|
||||
GPoll::Final(ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.))
|
||||
});
|
||||
assert_eq!(result, GPoll::Final(21.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_root_resets_the_arena_at_eval_start() {
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let persistent = Arena::new(64).unwrap();
|
||||
let mut buffer = core_types::record::FrameArena::new();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let cell = ArenaCell::new();
|
||||
eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
|
||||
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
|
||||
cell.store(weak);
|
||||
GPoll::Final(())
|
||||
});
|
||||
assert!(cell.load(&arena).is_some(), "the introspection window spans until the next eval");
|
||||
eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
|
||||
assert!(cell.load(ctx.scope().arena()).is_none(), "the reset at eval start reclaims the previous frame");
|
||||
GPoll::Final(())
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let persistent = Arena::new(64).unwrap();
|
||||
let mut buffer = core_types::record::FrameArena::new();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let cell = ArenaCell::new();
|
||||
let result: GPoll<()> = eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
|
||||
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
|
||||
cell.store(weak);
|
||||
panic!("mid-eval");
|
||||
});
|
||||
assert_eq!(result, GPoll::panicked());
|
||||
assert!(cell.load(&arena).is_none(), "reset-on-panic leaves no stale records");
|
||||
assert_eq!(eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |_, _| GPoll::Final(7u32)), GPoll::Final(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_node_sync() {
|
||||
let mut tree = BorrowTree::default();
|
||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
|
||||
let context = TypingContext::default();
|
||||
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
|
||||
let handle = tree.get(NodeId(0)).unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let GPoll::Final(value) = core_types::record::serve_edge(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
|
||||
}
|
||||
|
||||
fn build_executor(mut network: ProtoNetwork) -> DynamicExecutor {
|
||||
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
|
||||
network.compute_layouts();
|
||||
DynamicExecutor::new(network).unwrap()
|
||||
}
|
||||
|
||||
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
|
||||
let mut node = ProtoNode::default();
|
||||
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
|
||||
node.call_argument = core_types::concrete!(core_types::context::Context);
|
||||
node.construction_args = ConstructionArgs::Nodes(args);
|
||||
node
|
||||
}
|
||||
|
||||
fn string_value(value: &str) -> ProtoNode {
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![7.]).into()), vec![])),
|
||||
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
let arena = Arena::new(1 << 20).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let handle = executor.tree().get(NodeId(1)).unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
|
||||
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||
let GPoll::Final(value) = core_types::record::serve_edge(&edge, &ctx, &frames) else {
|
||||
panic!("the flipped clone must evaluate over record wires, got a non-final poll");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }, 7.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_palette_folds_its_record_wire_to_a_color_level() {
|
||||
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
|
||||
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
|
||||
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let edge = executor.tree().get(NodeId(2)).unwrap().downcast_record::<graphene_std::raster::color::Color>().unwrap();
|
||||
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||
let result = core_types::record::serve_edge(&edge, &ctx, &frames);
|
||||
// The empty raster level folds to an empty palette: past-end at lane 0.
|
||||
assert!(
|
||||
matches!(&result, GPoll::Error(error) if error.kind == core_types::gpoll::ErrorKind::PastEnd),
|
||||
"the empty palette level must serve the past-end signal at lane 0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_edge_is_a_record_wire_end_to_end() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(0),
|
||||
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![]))],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
let value = executor.tree().get(NodeId(0)).unwrap();
|
||||
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
|
||||
assert_eq!(value.layout().depth, 0);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_monitor_row_forwards_and_introspects_through_the_executor() {
|
||||
let mut monitor = proto_node("graphene_core::memo::MonitorNode", vec![NodeId(0)]);
|
||||
monitor.original_location.path = Some(vec![NodeId(9)]);
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])), (NodeId(1), monitor)],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
let element = executor.introspect(&[NodeId(9)]).unwrap();
|
||||
let element = element.downcast_ref::<f64>().expect("a record capture materializes to its element");
|
||||
assert_eq!(*element, 7.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_memoize_row_wires_generically_and_replays_over_record_wires() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(String::from("cached")).into()), vec![])),
|
||||
(NodeId(1), proto_node("graphene_core::memo::MemoizeNode", vec![NodeId(0)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
|
||||
assert_eq!(
|
||||
(&executor).execute(()).unwrap(),
|
||||
GPoll::Final(TaggedValue::String(String::from("cached"))),
|
||||
"the second execution replays the deep copy against a reset arena"
|
||||
);
|
||||
}
|
||||
|
||||
fn modification_value() -> ProtoNode {
|
||||
let modification = core_types::ContextModification::from_sources(core_types::context::ContextFeatures::all(), &[]);
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(modification).into()), vec![])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_modification_row_wires_over_a_value_wire() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||
(NodeId(1), modification_value()),
|
||||
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_context_modifications_forward_the_layout() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(4),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||
(NodeId(1), modification_value()),
|
||||
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
|
||||
(NodeId(3), modification_value()),
|
||||
(NodeId(4), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(2), NodeId(3)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_frame_memos_replay_over_record_wires() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), string_value("memoized")),
|
||||
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
|
||||
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
|
||||
assert_eq!(
|
||||
(&executor).execute(()).unwrap(),
|
||||
GPoll::Final(TaggedValue::String("memoized".to_string())),
|
||||
"the frame memo must replay across evaluations"
|
||||
);
|
||||
}
|
||||
}
|
||||
mod test;
|
||||
@@ -0,0 +1,668 @@
|
||||
use super::*;
|
||||
use core_types::Context;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{item, list};
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::vector::Vector;
|
||||
|
||||
#[test]
|
||||
fn push_node_sync() {
|
||||
let mut tree = BorrowTree::default();
|
||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
|
||||
let context = TypingContext::default();
|
||||
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
|
||||
futures::executor::block_on(future).unwrap();
|
||||
let _node = tree.get(NodeId(0)).unwrap();
|
||||
let result: Option<Item<u32>> = futures::executor::block_on(tree.eval(NodeId(0), ()));
|
||||
assert_eq!(result.map(|item| *item.element()), Some(2_u32));
|
||||
}
|
||||
|
||||
/// Builds a two-node network feeding the given value into Bounding Box, whose primary input registers both `Item<Vector>` and `List<Vector>` wire variants.
|
||||
fn bounding_box_network(content: TaggedValue) -> ProtoNetwork {
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
|
||||
|
||||
let mut bounding_box_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
bounding_box_node.identifier = ProtoNodeIdentifier::new("core_types::vector::BoundingBoxNode");
|
||||
|
||||
ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), bounding_box_node)],
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_bounding_box_network(content: TaggedValue) -> BorrowTree {
|
||||
let network = bounding_box_network(content);
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("The network should resolve against exactly one registered wire variant");
|
||||
futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The resolved variant's constructor should instantiate")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_wire_variant_resolves_and_executes() {
|
||||
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(item!(Vector)));
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
|
||||
assert!(result.is_some(), "The Item wire variant should downcast and execute end-to-end");
|
||||
|
||||
let wrong_type: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert!(wrong_type.is_none(), "An Item wire should not downcast as a List");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_wire_promotes_to_list_connector() {
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]);
|
||||
|
||||
// Box Corners takes a `List<f64>` primary, so feeding it an `Item<f64>` wire exercises the singleton raise
|
||||
let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER;
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An Item wire should resolve a List connector via promotion");
|
||||
assert!(typing_context.promotions(NodeId(1)).is_some(), "The typing pass should record the promotion");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapter should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<graphene_std::vector::misc::BoxCorners>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert!(result.is_some(), "The promoted wire should execute end-to-end");
|
||||
}
|
||||
|
||||
// The layer content path: a rank-0 content wire enters Wrap Graphic's `List` connector by singleton raise, and the
|
||||
// wrapped `Item<Graphic>` raises again at Extend's `List` connector, so layers accept rank-0 chains without new machinery
|
||||
#[test]
|
||||
fn rank_0_content_promotes_through_the_layer_coercion_path() {
|
||||
let content_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(Vector)).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut wrap_graphic_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
wrap_graphic_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::WrapGraphicNode");
|
||||
|
||||
let base_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2), NodeId(1)]), vec![NodeId(3)]);
|
||||
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: vec![(NodeId(0), content_node), (NodeId(1), wrap_graphic_node), (NodeId(2), base_node), (NodeId(3), extend_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("A rank-0 content wire should resolve the layer coercion path via promotion");
|
||||
assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 content should be raised at Wrap Graphic's List connector");
|
||||
assert!(typing_context.promotions(NodeId(3)).is_some(), "The wrapped Item<Graphic> should be raised at Extend's List connector");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapters should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
|
||||
let stack = result.expect("The layer coercion path should execute end-to-end");
|
||||
assert_eq!(stack.len(), 1, "The rank-0 content should contribute exactly one graphic to the stack");
|
||||
}
|
||||
|
||||
/// Builds a network feeding the given content plus an f64 distance value into Offset Points, whose distance input is ranked `Item<f64>`.
|
||||
fn offset_points_network(content: TaggedValue) -> ProtoNetwork {
|
||||
let content_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
|
||||
let distance_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(10.).into()), vec![NodeId(1)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
|
||||
let mut offset_points_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
|
||||
offset_points_node.identifier = ProtoNodeIdentifier::new("core_types::vector::OffsetPointsNode");
|
||||
|
||||
ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: vec![(NodeId(0), content_node), (NodeId(1), distance_node), (NodeId(2), input_adapter_node), (NodeId(3), offset_points_node)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_rank_connectors_resolve_via_promotion() {
|
||||
let network = offset_points_network(TaggedValue::TypeDefault(list!(Vector)));
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context
|
||||
.update(&network)
|
||||
.expect("A List primary with an Item parameter should resolve the mapped variant via promotion");
|
||||
assert!(typing_context.promotions(NodeId(3)).is_some(), "The Item distance should be marked for promotion");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Construction should wrap the promoted argument");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
|
||||
assert!(result.is_some(), "The zipped mapped variant should execute end-to-end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_item_connectors_resolve_without_promotion() {
|
||||
let network = offset_points_network(TaggedValue::TypeDefault(item!(Vector)));
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("All-Item connectors should resolve the rank-0 variant exactly");
|
||||
assert!(typing_context.promotions(NodeId(3)).is_none(), "No promotion should be needed at rank 0");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The rank-0 variant should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
|
||||
assert!(result.is_some(), "The rank-0 variant should execute and stay rank 0");
|
||||
}
|
||||
|
||||
/// Builds a Transform network: content (node 0) plus four parameter values, each promoted onto Item wires as the preprocessor would.
|
||||
fn transform_network(content: TaggedValue, rotation: TaggedValue) -> ProtoNetwork {
|
||||
let mut nodes = vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]))];
|
||||
|
||||
let parameters = [
|
||||
(TaggedValue::DVec2(glam::DVec2::new(5., 0.)), "DVec2"),
|
||||
(rotation, "f64"),
|
||||
(TaggedValue::DVec2(glam::DVec2::ONE), "DVec2"),
|
||||
(TaggedValue::DVec2(glam::DVec2::ZERO), "DVec2"),
|
||||
];
|
||||
let mut transform_inputs = vec![NodeId(0)];
|
||||
let mut next_id = 1;
|
||||
for (value, element) in parameters {
|
||||
let value_id = NodeId(next_id);
|
||||
let input_adapter_id = NodeId(next_id + 1);
|
||||
next_id += 2;
|
||||
|
||||
nodes.push((value_id, ProtoNode::value(ConstructionArgs::Value(value.into()), vec![value_id])));
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![value_id]), vec![input_adapter_id]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{element}>"));
|
||||
nodes.push((input_adapter_id, input_adapter_node));
|
||||
transform_inputs.push(input_adapter_id);
|
||||
}
|
||||
|
||||
let output = NodeId(next_id);
|
||||
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes(transform_inputs), vec![output]);
|
||||
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
|
||||
nodes.push((output, transform_node));
|
||||
|
||||
ProtoNetwork { inputs: vec![], output, nodes }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_composes_onto_item_wire() {
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64(0.));
|
||||
let output = network.output;
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("Transform should resolve its rank-0 variant");
|
||||
assert!(typing_context.promotions(output).is_none(), "All-Item connectors should need no promotion");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Transform's rank-0 variant should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(output, context));
|
||||
let item = result.expect("A rank-0 chain through Transform should stay rank 0");
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
|
||||
assert_eq!(transform.translation, DVec2::new(5., 0.), "The translation should compose onto the item's transform attribute");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_broadcasts_item_content_across_a_framed_parameter() {
|
||||
use glam::DAffine2;
|
||||
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64Array(vec![0., 90.]));
|
||||
let output = network.output;
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context
|
||||
.update(&network)
|
||||
.expect("A framed rotation should resolve the mapped variant via promotion of the other connectors");
|
||||
assert!(typing_context.promotions(output).is_some(), "The Item-typed connectors should be raised into the frame");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped variant should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(output, context));
|
||||
let list = result.expect("The broadcast should produce a List");
|
||||
assert_eq!(list.len(), 2, "One output item per frame slot");
|
||||
|
||||
let first: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 0);
|
||||
let second: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 1);
|
||||
assert!((first.matrix2.col(0).y - 0.).abs() < 1e-10, "Slot 0 should be unrotated");
|
||||
assert!((second.matrix2.col(0).y - 1.).abs() < 1e-10, "Slot 1 should be rotated 90 degrees");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_frames_over_a_list_parameter() {
|
||||
// A `()` generator (Circle) fed a `List<f64>` radius should frame into one circle per slot
|
||||
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
|
||||
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
|
||||
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
|
||||
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
|
||||
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: vec![(NodeId(0), primary), (NodeId(1), radii), (NodeId(2), radius_adapter), (NodeId(3), circle_node)],
|
||||
};
|
||||
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("A List<f64> radius should resolve Circle's mapped generator variant");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped generator variant should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
|
||||
let list = result.expect("The generator frame should produce a List<Vector>");
|
||||
assert_eq!(list.len(), 3, "One circle per radius slot");
|
||||
}
|
||||
|
||||
/// Builds the compiler's cache chain (child, then Memoize, then Context Modification) around a value, as `insert_context_nullification_node` does.
|
||||
fn nullification_chain_network(value: TaggedValue) -> ProtoNetwork {
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(0)]);
|
||||
|
||||
let mut memoize_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
memoize_node.identifier = graphene_core::memo::memoize::IDENTIFIER;
|
||||
|
||||
let features_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextFeatures(Default::default()).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut nullification_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
|
||||
nullification_node.identifier = graphene_core::context_modification::context_modification::IDENTIFIER;
|
||||
|
||||
ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), memoize_node), (NodeId(2), features_node), (NodeId(3), nullification_node)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nullification_chain_resolves_for_ranked_enum_wires() {
|
||||
use graphene_std::vector::style::StrokeAlign;
|
||||
|
||||
// The Item form, as a wrapped input adapter's output presents to the chain
|
||||
let network = nullification_chain_network(TaggedValue::TypeDefault(item!(StrokeAlign)));
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An Item<StrokeAlign> wire should resolve through the compiler's cache chain");
|
||||
|
||||
// The List form, as a whole-list enum wire presents to the chain
|
||||
let network = nullification_chain_network(TaggedValue::TypeDefault(list!(StrokeAlign)));
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("A List<StrokeAlign> wire should resolve through the compiler's cache chain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_wires_materialize_as_items_at_resolution() {
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
let values = [
|
||||
TaggedValue::DAffine2(DAffine2::IDENTITY),
|
||||
TaggedValue::DVec2(DVec2::new(7., 0.)),
|
||||
TaggedValue::F64(0.),
|
||||
TaggedValue::DVec2(DVec2::ONE),
|
||||
TaggedValue::DVec2(DVec2::ZERO),
|
||||
];
|
||||
let mut nodes: Vec<_> = values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| (NodeId(index as u64), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(index as u64)])))
|
||||
.collect();
|
||||
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes((0..5).map(NodeId).collect()), vec![NodeId(5)]);
|
||||
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
|
||||
nodes.push((NodeId(5), transform_node));
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(5),
|
||||
nodes,
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("Value wires should materialize as Items and resolve the all-Item variant");
|
||||
assert!(typing_context.promotions(NodeId(5)).is_none(), "Already-Item value wires should need no promotion");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The all-Item variant should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<DAffine2>> = futures::executor::block_on(tree.eval(NodeId(5), context));
|
||||
let item = result.expect("A value matrix should flow through Transform as an Item");
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
|
||||
assert_eq!(transform.translation, DVec2::new(7., 0.), "The translation should compose onto the gained transform attribute");
|
||||
}
|
||||
|
||||
// A position's Item wire converts through the vector input adapter into a single-anchor path, which the ItemToList promotion can then raise at a List connector
|
||||
#[test]
|
||||
fn position_value_converts_through_the_vector_input_adapter() {
|
||||
let position_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::DVec2(glam::DVec2::new(3., 4.)).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Vector>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), position_node), (NodeId(1), input_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An Item<DVec2> wire should resolve the adapter's element conversion row");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The conversion constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert!(result.is_some(), "The position should arrive as an Item<Vector> single-anchor path");
|
||||
}
|
||||
|
||||
// A scalar wire feeding a `DVec2` connector splats into both axes through the input adapter's `Convert` row
|
||||
#[test]
|
||||
fn number_value_splats_through_the_vec2_input_adapter() {
|
||||
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(-60.).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<DVec2>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), number_node), (NodeId(1), input_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An f64 wire should resolve the adapter's splat conversion row");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The splat constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<glam::DVec2>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert_eq!(result.map(|item| *item.element()), Some(glam::DVec2::splat(-60.)), "The scalar should splat into both axes");
|
||||
}
|
||||
|
||||
// A scalar wire feeding a `String` connector formats as text through the input adapter's `Convert` row
|
||||
#[test]
|
||||
fn number_value_formats_through_the_string_input_adapter() {
|
||||
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(42.).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), number_node), (NodeId(1), input_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An f64 wire should resolve the adapter's formatting conversion row");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The formatting constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<String>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert_eq!(result.map(|item| item.element().clone()), Some("42".to_string()), "The number should format as its text representation");
|
||||
}
|
||||
|
||||
// A `List` wire feeding a `ListDyn` connector erases its element type through the input adapter's `Into` row
|
||||
#[test]
|
||||
fn list_wire_erases_through_the_list_dyn_input_adapter() {
|
||||
use core_types::list::ListDyn;
|
||||
|
||||
let list_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<ListDyn>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), list_node), (NodeId(1), input_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("A List<f64> wire should resolve the ListDyn erasure row");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The erasure constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<ListDyn> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
let erased = result.expect("The erased list should arrive as a ListDyn");
|
||||
assert_eq!(erased.len(), 3, "The erased list should keep its row count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_wire_passes_through_the_input_adapter_as_item() {
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An f64 value's Item wire should resolve the adapter's passthrough row");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<f64>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert_eq!(result.map(|item| *item.element()), Some(3.), "The value should arrive as an Item");
|
||||
}
|
||||
|
||||
// Path Modify's ranked modification parameter: a `Box<VectorModification>` value rides the `Item` wire through its input adapter,
|
||||
// exercising the nested-generic identifier round-trip between the registered `stringify!` name and the preprocessor's simplified name
|
||||
#[test]
|
||||
fn modification_value_rides_the_item_wire_through_its_input_adapter() {
|
||||
use graphene_std::vector::VectorModification;
|
||||
|
||||
let modification = TaggedValue::VectorModification(Default::default());
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(modification.into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Box<VectorModification>>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("A modification value's Item wire should resolve the adapter's passthrough row");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<Box<VectorModification>>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert!(result.is_some(), "The modification should arrive as an Item");
|
||||
}
|
||||
|
||||
// The Write Attribute value input: a value's Item wire boxes its element into a type-erased attribute value through the input adapter
|
||||
#[test]
|
||||
fn item_wire_boxes_into_the_attribute_value_connector() {
|
||||
use graphene_std::list::AttributeValueDyn;
|
||||
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
|
||||
let mut attribute_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
attribute_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<AttributeValueDyn>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), attribute_adapter_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("An Item<f64> wire should resolve the attribute value boxing row");
|
||||
assert!(typing_context.promotions(NodeId(1)).is_none(), "The already-Item value wire should need no promotion");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The boxing constructor should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<Item<AttributeValueDyn>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
let boxed = result.expect("The boxed attribute value should arrive as an Item");
|
||||
assert_eq!(
|
||||
boxed.element().0.as_any().downcast_ref::<f64>(),
|
||||
Some(&3.),
|
||||
"The stored value should be the bare element, not the whole Item"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_wire_variant_resolves_and_executes() {
|
||||
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(list!(Vector)));
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
|
||||
assert!(result.is_some(), "The mapped List wire variant should downcast and execute end-to-end");
|
||||
|
||||
let wrong_type: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
|
||||
assert!(wrong_type.is_none(), "A List wire should not downcast as an Item");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expander_flattens_under_the_frame() {
|
||||
// A string value's Item wire feeds String Split's expander primary; its parameters ride Item wires through their input adapters
|
||||
let string_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("a,b".into()).into()), vec![NodeId(0)]);
|
||||
|
||||
let delimiter_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(",".into()).into()), vec![NodeId(1)]);
|
||||
let mut delimiter_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
delimiter_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
|
||||
|
||||
let escaping_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(false).into()), vec![NodeId(3)]);
|
||||
let mut escaping_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
|
||||
escaping_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<bool>");
|
||||
|
||||
let output = NodeId(5);
|
||||
let mut string_split_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2), NodeId(4)]), vec![output]);
|
||||
string_split_node.identifier = graphene_std::text_nodes::string_split::IDENTIFIER;
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output,
|
||||
nodes: vec![
|
||||
(NodeId(0), string_node),
|
||||
(NodeId(1), delimiter_node),
|
||||
(NodeId(2), delimiter_input_adapter_node),
|
||||
(NodeId(3), escaping_node),
|
||||
(NodeId(4), escaping_input_adapter_node),
|
||||
(output, string_split_node),
|
||||
],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context
|
||||
.update(&network)
|
||||
.expect("All-Item connectors should resolve the expander's direct `Item -> List` variant");
|
||||
assert!(typing_context.promotions(output).is_none(), "No promotion should be needed when every connector is already an Item");
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The expander variant should instantiate");
|
||||
|
||||
let context: Context = None;
|
||||
let result: Option<List<String>> = futures::executor::block_on(tree.eval(output, context));
|
||||
let list = result.expect("An Item-wired expander should produce a List");
|
||||
assert_eq!(list.len(), 2, "Splitting \"a,b\" on the comma should expand into two rows");
|
||||
let substrings: Vec<_> = list.iter_element_values().map(|s| s.as_str()).collect();
|
||||
assert_eq!(substrings, ["a", "b"], "The rows should hold the split substrings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_list_switches_as_one_bundle() {
|
||||
// One bool selecting between two whole `List<f64>` stacks: each branch bundles into a rank-0 cell, and the result unbundles back to the flat stack
|
||||
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
|
||||
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(1)]);
|
||||
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![4., 5.]).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
|
||||
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
|
||||
|
||||
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
|
||||
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(4),
|
||||
nodes: vec![
|
||||
(NodeId(0), condition_node),
|
||||
(NodeId(1), if_true_node),
|
||||
(NodeId(2), if_false_node),
|
||||
(NodeId(3), switch_node),
|
||||
(NodeId(4), unbundle_node),
|
||||
],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context
|
||||
.update(&network)
|
||||
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
|
||||
|
||||
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
|
||||
let branch_bundles = promotions
|
||||
.iter()
|
||||
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
|
||||
.count();
|
||||
assert_eq!(branch_bundles, 2, "Both branches should bundle their whole list into one opaque cell");
|
||||
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
|
||||
let context: Context = None;
|
||||
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
|
||||
let list = result.expect("The whole stack should round-trip through the bundle switch back to a flat List<f64>");
|
||||
let values: Vec<f64> = list.iter_element_values().copied().collect();
|
||||
assert_eq!(values, [1., 2., 3.], "The taken branch's whole list should come through unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bundle_unbundles_into_a_list_connector() {
|
||||
// A bundled wire (sourced here from a BundleNode, as a Switch branch produces one) feeding Extend's whole-`List` base connector
|
||||
let stack_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut bundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
bundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::BundleNode<Graphic>");
|
||||
|
||||
let new_layers_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
|
||||
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: vec![(NodeId(0), stack_node), (NodeId(1), bundle_node), (NodeId(2), new_layers_node), (NodeId(3), extend_node)],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("A bundled wire should feed Extend's List<Graphic> connector via the unbundle");
|
||||
|
||||
let promotions = typing_context.promotions(NodeId(3)).expect("Extend's bundled base should be marked for unbundling");
|
||||
assert!(
|
||||
promotions.iter().any(|(index, adapter)| *index == 0 && matches!(adapter, graph_craft::proto::Promotion::Unbundle(_))),
|
||||
"The base connector should unbundle the whole list"
|
||||
);
|
||||
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The unbundle adapter should instantiate");
|
||||
let context: Context = None;
|
||||
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
|
||||
assert!(result.is_some(), "The unbundled stack should flow into Extend as a List<Graphic>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_list_of_scalars_switches_as_one_bundle() {
|
||||
// A single bool selecting between two whole `List<f64>` values, covering a primitive element type and confirming the selected list survives intact
|
||||
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
|
||||
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2.]).into()), vec![NodeId(1)]);
|
||||
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![3., 4., 5.]).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
|
||||
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
|
||||
|
||||
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
|
||||
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
|
||||
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(4),
|
||||
nodes: vec![
|
||||
(NodeId(0), condition_node),
|
||||
(NodeId(1), if_true_node),
|
||||
(NodeId(2), if_false_node),
|
||||
(NodeId(3), switch_node),
|
||||
(NodeId(4), unbundle_node),
|
||||
],
|
||||
};
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context
|
||||
.update(&network)
|
||||
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
|
||||
|
||||
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
|
||||
let branch_bundles = promotions
|
||||
.iter()
|
||||
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
|
||||
.count();
|
||||
assert_eq!(branch_bundles, 2, "Both scalar-list branches should bundle into one opaque cell");
|
||||
|
||||
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
|
||||
let context: Context = None;
|
||||
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
|
||||
let list = result.expect("The whole scalar list should round-trip through the bundle switch");
|
||||
assert_eq!(list.len(), 2, "The true branch's whole list should be selected and preserved intact");
|
||||
}
|
||||
@@ -5,6 +5,7 @@ pub mod util;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use core_types::*;
|
||||
use futures::executor::block_on;
|
||||
use graphene_core::ops::passthrough;
|
||||
|
||||
#[test]
|
||||
@@ -44,8 +45,8 @@ mod tests {
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
|
||||
let compiler = Compiler {};
|
||||
let protograph = compiler.compile_single(network, &crate::node_registry::NODE_REGISTRY).expect("Graph should be generated");
|
||||
let protograph = compiler.compile_single(network).expect("Graph should be generated");
|
||||
|
||||
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
}
|
||||
@@ -1,387 +1,646 @@
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
|
||||
use graphene_std::list::List;
|
||||
use dyn_any::StaticType;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::brush_stroke::BrushTrace;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphene_std::platform_application_io::canvas_utils::CanvasHandle;
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::raster::GPU;
|
||||
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::raster::*;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, NodeIOTypes, RegistryEntry};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Context, Graphic, ProtoNodeIdentifier, concrete};
|
||||
use node_registry_macros::{convert_node, into_node};
|
||||
use graphene_std::render_node::RenderIntermediate;
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{DashPattern, GradientSpreadMethod, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type_fut, future};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "gpu")]
|
||||
use wgpu_executor::WgpuExecutorHandle;
|
||||
|
||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
let mut node_types: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||
// ==========
|
||||
// INTO NODES
|
||||
// ==========
|
||||
into_node!(from: List<Graphic>, to: List<Graphic>),
|
||||
into_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
into_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>),
|
||||
convert_node!(from: List<Vector>, to: List<Graphic>),
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Graphic>),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Graphic>),
|
||||
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
|
||||
convert_node!(from: DVec2, to: DVec2),
|
||||
convert_node!(from: List<Vector>, to: List<Vector>),
|
||||
convert_node!(from: DVec2, to: List<Vector>),
|
||||
convert_node!(from: String, to: String),
|
||||
convert_node!(from: bool, to: String),
|
||||
convert_node!(from: DVec2, to: String),
|
||||
convert_node!(from: IVec2, to: String),
|
||||
convert_node!(from: DAffine2, to: String),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle, async),
|
||||
// TODO: turn into hashmap
|
||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
|
||||
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
// =============
|
||||
// MONITOR NODES
|
||||
// =============
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Footprint>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<u32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<u64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DVec2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientType>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientSpreadMethod>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BrushTrace>]),
|
||||
// Context nullification
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<RenderOutput>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => Item<graphene_std::ContextFeatures>]),
|
||||
#[cfg(target_family = "wasm")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<CanvasHandle>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Option<&wgpu_executor::WgpuExecutor>>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>, Context => Item<graphene_std::ContextFeatures>]),
|
||||
// ==========
|
||||
// MEMO NODES
|
||||
// ==========
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DVec2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientType>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpreadMethod>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Artboard>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Graphic>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Vector>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f32>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Footprint>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<bool>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<u32>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<u64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
|
||||
#[cfg(target_family = "wasm")]
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<CanvasHandle>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderOutput>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BrushTrace>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<&wgpu_executor::WgpuExecutor>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Option<&wgpu_executor::WgpuExecutor>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
|
||||
];
|
||||
// The transform's value-typed rows, served by `transform_value` under the
|
||||
// leveled transform's identifier.
|
||||
node_types.extend(
|
||||
graphene_std::transform_nodes::transform_nodes::transform_value_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::transform_nodes::transform_nodes::transform::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The graphic-lane fill and stroke rows, served under their identifiers.
|
||||
node_types.extend(
|
||||
graphene_std::vector::fill_graphic_leveled_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::fill::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
node_types.extend(
|
||||
graphene_std::vector::stroke_graphic_leveled_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::stroke::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The boolean operation's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::path_bool_nodes::boolean_operation_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The path flattening's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::flatten_path_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::flatten_path::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The solidify's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::solidify_stroke_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::solidify_stroke::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The color assignment's graphic-lane rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::assign_colors_graphic_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::assign_colors::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The mirror's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::mirror_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::mirror::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The morph's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::morph_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::morph::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// Element-wise coercion into `Graphic` for single-typed leveled inputs,
|
||||
// served by the hidden elementwise rows.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::to_graphic_element_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (ProtoNodeIdentifier::new("graphene_core::ops::IntoNode<Graphic>"), entry)),
|
||||
);
|
||||
// The typed-level collapse rows of To Graphic, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::to_graphic_typed_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The unit row of To Graphic: an unconnected content input renders as nothing.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::to_graphic_unit_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The transitional level bridge: a leveled wire materializes into the legacy
|
||||
// list an unconverted consumer expects. The rows are keyed under the legacy
|
||||
// convert identifiers and die with the last legacy consumer.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::level_to_list_entries()
|
||||
.into_iter()
|
||||
.zip([
|
||||
"List<Graphic>",
|
||||
"List<Vector>",
|
||||
"List<Raster<CPU>>",
|
||||
"List<Raster<GPU>>",
|
||||
"List<Color>",
|
||||
"List<GradientStops>",
|
||||
"List<String>",
|
||||
])
|
||||
.map(|(entry, target)| (ProtoNodeIdentifier::with_owned_string(format!("graphene_core::ops::ConvertNode<{target}>")), entry)),
|
||||
);
|
||||
// =============
|
||||
// CONVERT NODES
|
||||
// =============
|
||||
node_types.extend(
|
||||
[
|
||||
convert_node!(from: f32, to: numbers),
|
||||
convert_node!(from: f64, to: numbers),
|
||||
convert_node!(from: i8, to: numbers),
|
||||
convert_node!(from: u8, to: numbers),
|
||||
convert_node!(from: u16, to: numbers),
|
||||
convert_node!(from: i16, to: numbers),
|
||||
convert_node!(from: i32, to: numbers),
|
||||
convert_node!(from: u32, to: numbers),
|
||||
convert_node!(from: i64, to: numbers),
|
||||
convert_node!(from: u64, to: numbers),
|
||||
convert_node!(from: i128, to: numbers),
|
||||
convert_node!(from: u128, to: numbers),
|
||||
convert_node!(from: isize, to: numbers),
|
||||
convert_node!(from: usize, to: numbers),
|
||||
convert_node!(from: numbers, to: DVec2),
|
||||
convert_node!(from: numbers, to: String),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
);
|
||||
// The per-connector input adapter, registered per element type: an `Item` or `List` wire passes through unchanged.
|
||||
// The `name` arm registers an `Into`-based whole-wire shift under the given identifier, serving the `ListDyn` erasure rows.
|
||||
macro_rules! input_adapter_node {
|
||||
(element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_node!(passthrough: Item<$element>, element: $element),
|
||||
input_adapter_node!(passthrough: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
(passthrough: $ty:ty, element: $element:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["input_adapter<", stringify!($element), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::downcast_node::<Context, $ty>(args.pop().unwrap()));
|
||||
let any: DynAnyNode<Context, $ty, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $ty> + Send>>>::new());
|
||||
let params = vec![fn_type_fut!(Context, $ty)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
(name: $name:literal, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat![$name, "<", stringify!($element), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::IntoNode::new(
|
||||
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
|
||||
);
|
||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::IntoNode::new(
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
|
||||
);
|
||||
let params = vec![fn_type_fut!(Context, $from)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
||||
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
||||
macro_rules! input_adapter_row {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["input_adapter<", stringify!($element), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::$node::new(
|
||||
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>)),
|
||||
);
|
||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::$node::new(
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>)),
|
||||
);
|
||||
let params = vec![fn_type_fut!(Context, $from)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
// The promotion adapter inserted by type resolution when an Item wire feeds a List connector: the singleton raise
|
||||
macro_rules! item_to_list_node {
|
||||
(element: $element:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ItemToListNode<", stringify!($element), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::downcast_node::<Context, Item<$element>>(args.pop().unwrap()));
|
||||
let any: DynAnyNode<Context, List<$element>, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::PanicNode::<
|
||||
Context,
|
||||
core::pin::Pin<Box<dyn core::future::Future<Output = Item<$element>> + Send>>,
|
||||
>::new());
|
||||
let params = vec![fn_type_fut!(Context, Item<$element>)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
// A whole-List bundle adapter inserted by type resolution when a List wire feeds an Item<Bundle<X>> connector
|
||||
macro_rules! bundle_node {
|
||||
(element: $element:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::BundleNode<", stringify!($element), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::BundleNode::new(graphene_std::any::downcast_node::<Context, List<$element>>(args.pop().unwrap()));
|
||||
let any: DynAnyNode<Context, Item<Bundle<$element>>, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::BundleNode::new(graphene_std::any::PanicNode::<
|
||||
Context,
|
||||
core::pin::Pin<Box<dyn core::future::Future<Output = List<$element>> + Send>>,
|
||||
>::new());
|
||||
let params = vec![fn_type_fut!(Context, List<$element>)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
// The reverse unbundle adapter inserted by type resolution when an Item<Bundle<X>> wire feeds a List connector
|
||||
macro_rules! unbundle_node {
|
||||
(element: $element:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::UnbundleNode<", stringify!($element), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::downcast_node::<Context, Item<Bundle<$element>>>(args.pop().unwrap()));
|
||||
let any: DynAnyNode<Context, List<$element>, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::PanicNode::<
|
||||
Context,
|
||||
core::pin::Pin<Box<dyn core::future::Future<Output = Item<Bundle<$element>>> + Send>>,
|
||||
>::new());
|
||||
let params = vec![fn_type_fut!(Context, Item<Bundle<$element>>)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
// ==================
|
||||
// RANK ADAPTER NODES
|
||||
// ==================
|
||||
// Registers the rank adapters (input_adapter, ItemToListNode) for each element type
|
||||
macro_rules! rank_adapter_nodes {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.extend(input_adapter_node!(element: $element));
|
||||
entries.push(item_to_list_node!(element: $element));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
}
|
||||
// The single list of value/enum element types that ride ranked wires as framable node parameters.
|
||||
// Each needs both a rank promotion adapter and a cache chain (memoize/monitor/context),
|
||||
// so both registrations below are driven from here by callback, which is what keeps a value type from ending up monitorable but not promotable, or vice versa.
|
||||
macro_rules! ranked_value_types {
|
||||
($register:ident) => {
|
||||
$register!(
|
||||
i32,
|
||||
i64,
|
||||
BlendMode,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
PaintOrder,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
MergeByDistanceAlgorithm,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
BrushTrace,
|
||||
XY,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
NoiseType,
|
||||
FractalType,
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
ArcType,
|
||||
SpiralType,
|
||||
TextAlign,
|
||||
QRCodeErrorCorrectionLevel,
|
||||
Font,
|
||||
InterpolationDistribution,
|
||||
RowsOrColumns,
|
||||
Resource,
|
||||
)
|
||||
};
|
||||
}
|
||||
// Primary element types (graphical data and scalars) get promotion adapters here; their monitor/memoize rows are the
|
||||
// explicit ones near the top of the registry, so they are deliberately absent from the shared value-type list above
|
||||
node_types.extend(rank_adapter_nodes!(
|
||||
Vector,
|
||||
Raster<CPU>,
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
String,
|
||||
f64,
|
||||
f32,
|
||||
u64,
|
||||
u32,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
bool,
|
||||
NodeIdPath,
|
||||
Footprint,
|
||||
Artboard,
|
||||
));
|
||||
node_types.extend(ranked_value_types!(rank_adapter_nodes));
|
||||
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
|
||||
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
|
||||
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
|
||||
#[cfg(feature = "gpu")]
|
||||
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
|
||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `List Length`): any `List` wire erases its element type
|
||||
macro_rules! list_dyn_rows {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
node_types.push(input_adapter_node!(passthrough: ListDyn, element: ListDyn));
|
||||
node_types.extend(list_dyn_rows!(
|
||||
Artboard,
|
||||
Graphic,
|
||||
Vector,
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
f32,
|
||||
f64,
|
||||
u32,
|
||||
u64,
|
||||
bool,
|
||||
String,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
node_types.extend(list_dyn_rows!(Raster<GPU>));
|
||||
// Registers the whole-List bundle adapters for each value type whose entire list may be selected or carried as one opaque cell
|
||||
macro_rules! bundle_adapter_nodes {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.push(bundle_node!(element: $element));
|
||||
entries.push(unbundle_node!(element: $element));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
}
|
||||
node_types.extend(bundle_adapter_nodes!(
|
||||
bool,
|
||||
f32,
|
||||
f64,
|
||||
u32,
|
||||
u64,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
Graphic,
|
||||
Raster<CPU>,
|
||||
Vector,
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
node_types.extend(bundle_adapter_nodes!(Raster<GPU>));
|
||||
// The memoize + monitor + context-nullification triple for each value type in the shared list above: the compiler wraps
|
||||
// a ranked connector's broadcast sibling in a Memoize + context-nullification pair, and test instrumentation monitors any wire.
|
||||
// Node identifiers are passed explicitly since `stringify!` would mangle the path's whitespace through this nested macro.
|
||||
macro_rules! cache_chain_nodes {
|
||||
(each: $value:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
async_node!(identifier: graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => $value]),
|
||||
async_node!(identifier: graphene_core::memo::monitor::IDENTIFIER, graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => $value]),
|
||||
async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item<graphene_std::ContextFeatures>]),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.extend(cache_chain_nodes!(each: Item<$element>));
|
||||
entries.extend(cache_chain_nodes!(each: List<$element>));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
}
|
||||
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
||||
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
||||
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
||||
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
||||
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
||||
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
||||
node_types.extend(input_adapter_row!(from_element: String, element: DashPattern));
|
||||
// A number wire may feed the ranked `Item<DashPattern>` dash connector, each number broadcasting element-wise as a one-length pattern
|
||||
node_types.extend(input_adapter_row!(from_element: f64, element: DashPattern));
|
||||
// A string wire may feed the ranked `Item<BoxCorners>` connector by parsing each element into a set of corner values
|
||||
node_types.extend(input_adapter_row!(from_element: String, element: BoxCorners));
|
||||
// A number wire may feed the ranked `Item<BoxCorners>` connector, each number becoming a uniform radius for all four corners
|
||||
node_types.extend(input_adapter_row!(from_element: f64, element: BoxCorners));
|
||||
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
||||
macro_rules! convert_adapter_node {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
macro_rules! convert_adapter_wildcard {
|
||||
(from: $from:ty, to: [$($to:ty),*]) => {{
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(entries.extend(convert_adapter_node!(from_element: $from, element: $to));)*
|
||||
entries
|
||||
}};
|
||||
}
|
||||
// Numeric wires cast between numeric element types, splat to fill both axes of a `DVec2` connector, and format into a `String` connector
|
||||
node_types.extend(convert_adapter_wildcard!(from: f64, to: [f32, u32, u64, i32, i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: f32, to: [f64, u32, u64, i32, i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: u32, to: [f64, f32, u64, i32, i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: u64, to: [f64, f32, u32, i32, i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: i32, to: [f64, f32, u32, u64, i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: i64, to: [f64, f32, u32, u64, i32, DVec2, String]));
|
||||
// Bool, position, and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||
node_types.extend(convert_adapter_node!(from_element: bool, element: String));
|
||||
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
||||
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||
macro_rules! attribute_value_node {
|
||||
(Item<$element:ty>) => {
|
||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
};
|
||||
(List<$element:ty>) => {
|
||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
};
|
||||
}
|
||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
attribute_value_node!(Item<f64>),
|
||||
attribute_value_node!(Item<u32>),
|
||||
attribute_value_node!(Item<u64>),
|
||||
attribute_value_node!(Item<bool>),
|
||||
attribute_value_node!(Item<String>),
|
||||
attribute_value_node!(Item<DVec2>),
|
||||
attribute_value_node!(Item<DAffine2>),
|
||||
attribute_value_node!(Item<Color>),
|
||||
attribute_value_node!(Item<BlendMode>),
|
||||
attribute_value_node!(Item<GradientType>),
|
||||
attribute_value_node!(Item<GradientSpreadMethod>),
|
||||
attribute_value_node!(Item<NodeIdPath>),
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
attribute_value_node!(List<Raster<GPU>>),
|
||||
attribute_value_node!(List<Graphic>),
|
||||
];
|
||||
node_types.extend(attribute_value_rows);
|
||||
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
||||
macro_rules! transform_list_node {
|
||||
(element: $element:ty) => {
|
||||
async_node!(
|
||||
identifier: ProtoNodeIdentifier::new("transform_nodes::transform_nodes::TransformNode"),
|
||||
graphene_std::transform_nodes::TransformListNode<_, _, _, _, _>,
|
||||
input: Context,
|
||||
fn_params: [Context => List<$element>, Context => Item<DVec2>, Context => Item<f64>, Context => Item<DVec2>, Context => Item<DVec2>]
|
||||
)
|
||||
};
|
||||
}
|
||||
let transform_list_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
transform_list_node!(element: Graphic),
|
||||
transform_list_node!(element: String),
|
||||
transform_list_node!(element: Vector),
|
||||
transform_list_node!(element: Raster<CPU>),
|
||||
#[cfg(feature = "gpu")]
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
let mut map: HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> = HashMap::new();
|
||||
let insert = |map: &mut HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>, id: ProtoNodeIdentifier, entry: RegistryEntry| {
|
||||
let rows = map.entry(id).or_default();
|
||||
if !rows.iter().any(|row| row.io == entry.io) {
|
||||
rows.push(entry);
|
||||
}
|
||||
};
|
||||
|
||||
for (id, entries) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
|
||||
for entry in entries {
|
||||
insert(&mut map, id.clone(), entry.clone());
|
||||
// Rank normalization at this merge is the single convergence point for structurally-built and name-encoded `List` types,
|
||||
// covering the sources which cannot construct them structurally (reflected return values and opaque macro captures)
|
||||
for (id, entry) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
|
||||
for (constructor, types) in entry.iter() {
|
||||
map.entry(id.clone()).or_default().insert(types.clone().normalize_rank(), *constructor);
|
||||
}
|
||||
}
|
||||
|
||||
for (id, entry) in node_types.into_iter() {
|
||||
for (id, node_constructor, types) in node_types.into_iter() {
|
||||
// TODO: this is a hack to remove the newline from the node new_name
|
||||
// This occurs for the ChannelMixerNode presumably because of the long name.
|
||||
// This might be caused by the stringify! macro
|
||||
let mut new_name = id.as_str().replace('\n', " ");
|
||||
|
||||
// Remove struct generics for all nodes except for the IntoNode and ConvertNode
|
||||
if !(new_name.contains("IntoNode") || new_name.contains("ConvertNode"))
|
||||
&& let Some((path, _generics)) = new_name.split_once("<")
|
||||
{
|
||||
// Remove struct generics for all nodes except the adapter identifiers, whose element suffix distinguishes their rows
|
||||
let element_suffixed_adapter = new_name.starts_with("input_adapter<")
|
||||
|| new_name.starts_with("graphene_core::ops::ItemToListNode<")
|
||||
|| new_name.starts_with("graphene_core::ops::BundleNode<")
|
||||
|| new_name.starts_with("graphene_core::ops::UnbundleNode<");
|
||||
if !element_suffixed_adapter && let Some((path, _generics)) = new_name.split_once("<") {
|
||||
new_name = path.to_string();
|
||||
}
|
||||
|
||||
insert(&mut map, ProtoNodeIdentifier::with_owned_string(new_name), entry);
|
||||
map.entry(ProtoNodeIdentifier::with_owned_string(new_name))
|
||||
.or_default()
|
||||
.insert(types.clone().normalize_rank(), node_constructor);
|
||||
}
|
||||
|
||||
map
|
||||
}
|
||||
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = once_cell::sync::Lazy::new(node_registry);
|
||||
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>> = once_cell::sync::Lazy::new(|| node_registry());
|
||||
|
||||
mod node_registry_macros {
|
||||
macro_rules! into_node {
|
||||
(from: $from:ty, to: $to:ty) => {
|
||||
macro_rules! async_node {
|
||||
// TODO: we currently need to annotate the type here because the compiler would otherwise (correctly)
|
||||
// TODO: assign a Pin<Box<dyn Future<Output=T>>> type to the node, which is not what we want for now.
|
||||
//
|
||||
// This `params` variant of the macro wraps the normal `fn_params` variant and is used as a shorthand for writing `T` instead of `() => T`
|
||||
($path:ty, input: $input:ty, params: [$($type:ty),*]) => {
|
||||
async_node!($path, input: $input, fn_params: [ $(() => $type),*])
|
||||
};
|
||||
($path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
|
||||
async_node!(identifier: ProtoNodeIdentifier::new(stringify!($path)), $path, input: $input, fn_params: [$($arg => $type),*])
|
||||
};
|
||||
(identifier: $identifier:expr, $path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let handle = inputs.next().unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
$identifier,
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
args.reverse();
|
||||
let node = <$path>::new($(graphene_std::any::downcast_node::<$arg, $type>(args.pop().expect("Not enough arguments provided to construct node"))),*);
|
||||
let any: DynAnyNode<$input, _, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
macro_rules! convert_node {
|
||||
(from: $from:ty, to: numbers) => {{
|
||||
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||
convert_node!(from: $from, to: f32),
|
||||
convert_node!(from: $from, to: f64),
|
||||
convert_node!(from: $from, to: i8),
|
||||
convert_node!(from: $from, to: u8),
|
||||
convert_node!(from: $from, to: u16),
|
||||
convert_node!(from: $from, to: i16),
|
||||
convert_node!(from: $from, to: i32),
|
||||
convert_node!(from: $from, to: u32),
|
||||
convert_node!(from: $from, to: i64),
|
||||
convert_node!(from: $from, to: u64),
|
||||
convert_node!(from: $from, to: i128),
|
||||
convert_node!(from: $from, to: u128),
|
||||
convert_node!(from: $from, to: isize),
|
||||
convert_node!(from: $from, to: usize),
|
||||
];
|
||||
x
|
||||
}};
|
||||
(from: numbers, to: $to:ty) => {{
|
||||
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||
convert_node!(from: f32, to: $to),
|
||||
convert_node!(from: f64, to: $to),
|
||||
convert_node!(from: i8, to: $to),
|
||||
convert_node!(from: u8, to: $to),
|
||||
convert_node!(from: u16, to: $to),
|
||||
convert_node!(from: i16, to: $to),
|
||||
convert_node!(from: i32, to: $to),
|
||||
convert_node!(from: u32, to: $to),
|
||||
convert_node!(from: i64, to: $to),
|
||||
convert_node!(from: u64, to: $to),
|
||||
convert_node!(from: i128, to: $to),
|
||||
convert_node!(from: u128, to: $to),
|
||||
convert_node!(from: isize, to: $to),
|
||||
convert_node!(from: usize, to: $to),
|
||||
];
|
||||
x
|
||||
}};
|
||||
(from: $from:ty, to: $to:ty) => {
|
||||
convert_node!(from: $from, to: $to, converter: ())
|
||||
};
|
||||
(from: $from:ty, to: $to:ty, converter: $convert:ty, async) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![
|
||||
core_types::registry::record_edge_type::<$from>(),
|
||||
core_types::registry::record_edge_type::<$convert>(),
|
||||
core_types::registry::record_edge_type::<RuntimeHandle>(),
|
||||
core_types::registry::record_edge_type::<SourceId>(),
|
||||
],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 4 {
|
||||
return Err(ConstructionError::Arity { expected: 4, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let mut claim = || {
|
||||
let handle = inputs.next().unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
Ok::<_, ConstructionError>((handle, layout))
|
||||
};
|
||||
let (value, value_layout) = claim()?;
|
||||
let (converter, converter_layout) = claim()?;
|
||||
let (runtime, runtime_layout) = claim()?;
|
||||
let (source, source_layout) = claim()?;
|
||||
let node = graphene_std::ops::ConvertAsyncNode::<$to, _, _, _, _, $from, $convert>::new(
|
||||
value.downcast_record::<$from>()?,
|
||||
converter.downcast_record::<$convert>()?,
|
||||
runtime.downcast_record::<RuntimeHandle>()?,
|
||||
source.downcast_record::<SourceId>()?,
|
||||
&value_layout,
|
||||
&converter_layout,
|
||||
&runtime_layout,
|
||||
&source_layout,
|
||||
);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
},
|
||||
)
|
||||
};
|
||||
(from: $from:ty, to: $to:ty, converter: $convert:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 2 {
|
||||
return Err(ConstructionError::Arity { expected: 2, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let value = inputs.next().unwrap();
|
||||
let value_layout = value.layout().clone();
|
||||
let converter = inputs.next().unwrap();
|
||||
let converter_layout = converter.layout().clone();
|
||||
let node = graphene_std::ops::ConvertNode::<$to, _, _, $from, $convert>::new(
|
||||
value.downcast_record::<$from>()?,
|
||||
converter.downcast_record::<$convert>()?,
|
||||
&value_layout,
|
||||
&converter_layout,
|
||||
);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
{
|
||||
let node = <$path>::new($(
|
||||
graphene_std::any::PanicNode::<$arg, core::pin::Pin<Box<dyn core::future::Future<Output = $type> + Send>>>::new()
|
||||
),*);
|
||||
let params = vec![$(fn_type_fut!($arg, $type)),*];
|
||||
let mut node_io = NodeIO::<'_, $input>::to_async_node_io(&node, params);
|
||||
node_io.call_argument = concrete!(<$input as StaticType>::Static);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use convert_node;
|
||||
pub(crate) use into_node;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graphene_std::Type;
|
||||
|
||||
fn is_record_edge(ty: &Type) -> bool {
|
||||
match ty {
|
||||
Type::Fn(_, output) => matches!(&**output, Type::Record(_)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One wire kind: every row consumes and produces record wires. A plain
|
||||
/// io type here would need a bridge adapter, and those are gone.
|
||||
#[test]
|
||||
fn every_registry_row_is_record_typed() {
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
for (id, entries) in NODE_REGISTRY.iter() {
|
||||
for entry in entries {
|
||||
let plain_output = !matches!(entry.io.return_value, Type::Record(_));
|
||||
let plain_inputs: Vec<usize> = entry.io.inputs.iter().enumerate().filter(|(_, ty)| !is_record_edge(ty)).map(|(index, _)| index).collect();
|
||||
if plain_output || !plain_inputs.is_empty() {
|
||||
plain.push(format!("{} plain_output={plain_output} plain_inputs={plain_inputs:?}", id.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
plain.sort();
|
||||
assert!(plain.is_empty(), "plain io remains in the registry:\n{}", plain.join("\n"));
|
||||
}
|
||||
pub(crate) use async_node;
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::generic;
|
||||
use graph_craft::{concrete, item};
|
||||
use graphene_std::Context;
|
||||
use graphene_std::ContextFeatures;
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -29,15 +29,21 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate_leveled::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::INDEX,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
@@ -48,14 +54,20 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
@@ -65,18 +77,21 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||
context_features: graphene_std::ContextDependencies::new(
|
||||
ContextFeatures::INDEX | ContextFeatures::VARARGS,
|
||||
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
|
||||
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX,
|
||||
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
@@ -99,7 +114,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(std::sync::Arc<PlatformEditorApi>)))];
|
||||
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), item!(&PlatformEditorApi)))];
|
||||
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
|
||||
@@ -16,7 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-hash = { workspace = true, features = ["derive"] }
|
||||
vector-types = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{Context, OwnedContextImpl};
|
||||
use dyn_any::{DynAny, StaticType, StaticTypeSized};
|
||||
use glam::DVec2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::ptr::addr_of;
|
||||
@@ -21,9 +23,6 @@ pub trait ApplicationIo {
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
None
|
||||
}
|
||||
fn gpu_executor_arc(&self) -> Option<Arc<Self::Executor>> {
|
||||
None
|
||||
}
|
||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>;
|
||||
}
|
||||
|
||||
@@ -34,10 +33,6 @@ impl<T: ApplicationIo> ApplicationIo for &T {
|
||||
(**self).gpu_executor()
|
||||
}
|
||||
|
||||
fn gpu_executor_arc(&self) -> Option<Arc<T::Executor>> {
|
||||
(**self).gpu_executor_arc()
|
||||
}
|
||||
|
||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
||||
(**self).load_resource(hash)
|
||||
}
|
||||
@@ -61,7 +56,7 @@ pub trait GetEditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32;
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ExportFormat {
|
||||
#[default]
|
||||
@@ -69,14 +64,14 @@ pub enum ExportFormat {
|
||||
Raster,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TimingInformation {
|
||||
pub time: f64,
|
||||
pub animation_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -90,6 +85,13 @@ pub struct RenderConfig {
|
||||
pub for_eyedropper: bool,
|
||||
}
|
||||
|
||||
impl RenderConfig {
|
||||
/// Wraps this render configuration as the sole vararg of a fresh context, the call argument of a compiled network's boundary node.
|
||||
pub fn into_context(self) -> Context<'static> {
|
||||
OwnedContextImpl::default().with_vararg(Box::new(self)).into_context()
|
||||
}
|
||||
}
|
||||
|
||||
struct Logger;
|
||||
|
||||
impl NodeGraphUpdateSender for Logger {
|
||||
@@ -112,7 +114,6 @@ pub struct EditorApi<Io> {
|
||||
pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>,
|
||||
/// Editor preferences made available to the graph through the `PlatformEditorApi`.
|
||||
pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>,
|
||||
pub runtime: core_types::runtime::RuntimeHandle,
|
||||
}
|
||||
|
||||
impl<Io> Eq for EditorApi<Io> {}
|
||||
@@ -123,7 +124,6 @@ impl<Io: Default> Default for EditorApi<Io> {
|
||||
application_io: None,
|
||||
node_graph_message_sender: Box::new(Logger),
|
||||
editor_preferences: Box::new(DummyPreferences),
|
||||
runtime: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,7 +136,7 @@ impl<Io> Hash for EditorApi<Io> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io> core_types::graphene_hash::CacheHash for EditorApi<Io> {
|
||||
impl<Io> CacheHash for EditorApi<Io> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(self, state);
|
||||
}
|
||||
|
||||
@@ -1,744 +0,0 @@
|
||||
use std::cell::UnsafeCell;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
|
||||
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
|
||||
/// addressable and generations run out after ~3 days of 60fps resets.
|
||||
const OFFSET_BITS: u32 = 40;
|
||||
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
|
||||
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
|
||||
|
||||
/// Out of the encodable range, so no handle, including `NULL`, matches it.
|
||||
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
|
||||
|
||||
pub struct Arena {
|
||||
generation: AtomicU64,
|
||||
offset: AtomicUsize,
|
||||
buf: Box<[UnsafeCell<MaybeUninit<u8>>]>,
|
||||
drops: Mutex<Vec<DropEntry>>,
|
||||
/// Set by a refused reservation and cleared by [`Arena::reset`], so a region
|
||||
/// no evaluation resets can be seen to need one.
|
||||
exhausted: AtomicBool,
|
||||
/// Heap the parked payloads keep alive, which occupancy does not measure:
|
||||
/// a park costs one pointer in the arena and owns its content outside it.
|
||||
retained_heap: AtomicUsize,
|
||||
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
|
||||
/// the header's address in the receiving arena and the moved size, so a
|
||||
/// payload two records share is moved once and a mistyped sharer is
|
||||
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
|
||||
/// generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, usize)>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Arena {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Arena").field("generation", &self.generation).field("size", &self.buf.len()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct DropEntry {
|
||||
offset: usize,
|
||||
/// The parked payload's own size, so [`Arena::move_park`] refuses a
|
||||
/// reference into a park of another type that shares the offset.
|
||||
size: usize,
|
||||
drop_fn: unsafe fn(*mut u8),
|
||||
/// The park glue's estimate of the heap this payload owns, 0 where the
|
||||
/// glue cannot measure it, so the counter is a lower bound.
|
||||
retained: usize,
|
||||
}
|
||||
|
||||
/// The glue a tombstoned entry carries: its payload was moved to another arena,
|
||||
/// which now owns the obligation.
|
||||
unsafe fn inert(_: *mut u8) {}
|
||||
|
||||
/// The entry parking `offset`, `None` where the arena holds no obligation for
|
||||
/// it. Entries are pushed in reserve order, which is offset order, so the
|
||||
/// search is exact; the scan covers a push order that concurrency interleaved.
|
||||
fn entry_at(entries: &[DropEntry], offset: usize) -> Option<usize> {
|
||||
let probe = entries.partition_point(|entry| entry.offset < offset);
|
||||
match entries.get(probe).is_some_and(|entry| entry.offset == offset) {
|
||||
true => Some(probe),
|
||||
false => entries.iter().rposition(|entry| entry.offset == offset),
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
|
||||
// only by its allocating caller before publication, and cross-thread hand-off is
|
||||
// ordered by the Release/Acquire pair on the published handle word. Payloads are
|
||||
// `Send + Sync` by the bound on every allocating method.
|
||||
unsafe impl Sync for Arena {}
|
||||
unsafe impl Send for Arena {}
|
||||
|
||||
impl std::panic::UnwindSafe for Arena {}
|
||||
impl std::panic::RefUnwindSafe for Arena {}
|
||||
|
||||
/// Shared by all arenas, so a foreign handle misses like a stale one.
|
||||
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
|
||||
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
|
||||
fn next_generation() -> Option<u64> {
|
||||
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
(generation <= GENERATION_MASK).then_some(generation)
|
||||
}
|
||||
|
||||
/// Rewinds the shared generation counter so previously issued values are reused.
|
||||
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
|
||||
/// check, which is a debugging aid rather than a guarantee.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
|
||||
/// every [`Arena`] is not sufficient, since nodes also hold handles in
|
||||
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
|
||||
/// concurrently either, since the live check and the rewind are separate steps.
|
||||
pub unsafe fn reset_generation_counter() -> bool {
|
||||
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
|
||||
return false;
|
||||
}
|
||||
NEXT_GENERATION.store(1, Ordering::Release);
|
||||
true
|
||||
}
|
||||
|
||||
impl Arena {
|
||||
pub fn new(capacity: usize) -> Option<Self> {
|
||||
let generation = next_generation()?;
|
||||
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
|
||||
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||
Some(Self {
|
||||
generation: AtomicU64::new(generation),
|
||||
offset: AtomicUsize::new(0),
|
||||
buf,
|
||||
drops: Mutex::new(Vec::new()),
|
||||
exhausted: AtomicBool::new(false),
|
||||
retained_heap: AtomicUsize::new(0),
|
||||
forwarded: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// An arena that refuses every allocation and resolves no handle, so a caller that
|
||||
/// cannot fail can degrade instead of propagating exhaustion.
|
||||
pub fn parked() -> Self {
|
||||
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||
Self {
|
||||
generation: AtomicU64::new(PARKED_GENERATION),
|
||||
offset: AtomicUsize::new(0),
|
||||
buf: Box::new([]),
|
||||
drops: Mutex::new(Vec::new()),
|
||||
exhausted: AtomicBool::new(false),
|
||||
retained_heap: AtomicUsize::new(0),
|
||||
forwarded: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a reservation has been refused since the last [`Arena::reset`].
|
||||
pub fn exhausted(&self) -> bool {
|
||||
self.exhausted.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Bytes handed out since the last [`Arena::reset`], including alignment
|
||||
/// padding, so a caller can flush at a boundary before a refusal.
|
||||
pub fn occupancy(&self) -> usize {
|
||||
self.offset.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.buf.len()
|
||||
}
|
||||
|
||||
/// The heap the parked payloads own, summed from the park glue's hints.
|
||||
/// A lower bound: glue that cannot measure its payload contributes 0.
|
||||
pub fn retained_heap(&self) -> usize {
|
||||
self.retained_heap.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether `ptr` addresses this arena's backbone, which is the provenance
|
||||
/// question a promote asks of every parked reference.
|
||||
pub fn contains(&self, ptr: *const u8) -> bool {
|
||||
let base = self.base() as usize;
|
||||
(ptr as usize).wrapping_sub(base) < self.buf.len()
|
||||
}
|
||||
|
||||
fn base(&self) -> *mut u8 {
|
||||
self.buf.as_ptr() as *mut u8
|
||||
}
|
||||
|
||||
fn reserve(&self, size: usize, align: usize) -> Option<usize> {
|
||||
debug_assert!(align.is_power_of_two());
|
||||
let base = self.base() as usize;
|
||||
let mut start = 0;
|
||||
let reserved = self
|
||||
.offset
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
|
||||
// Alignment is computed on the absolute address; the backbone
|
||||
// allocation itself has no alignment guarantee.
|
||||
let addr = (base.checked_add(current)?.checked_add(align - 1)?) & !(align - 1);
|
||||
start = addr - base;
|
||||
let end = start.checked_add(size)?;
|
||||
(end <= self.buf.len()).then_some(end)
|
||||
})
|
||||
.ok();
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
static ARENA_TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if *ARENA_TRACE.get_or_init(|| std::env::var_os("GRAPHENE_ARENA_DEBUG").is_some()) {
|
||||
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let count = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||
if reserved.is_none() {
|
||||
eprintln!("arena> EXHAUSTED after {count} allocations, wanted {size} bytes\n{}", std::backtrace::Backtrace::force_capture());
|
||||
} else if count % 20000 == 0 {
|
||||
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
}
|
||||
if reserved.is_none() {
|
||||
self.exhausted.store(true, Ordering::Relaxed);
|
||||
return None;
|
||||
}
|
||||
Some(start)
|
||||
}
|
||||
|
||||
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
|
||||
self.alloc_sized(value, 0)
|
||||
}
|
||||
|
||||
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
|
||||
/// which the region's own occupancy cannot see.
|
||||
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
|
||||
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
if std::mem::needs_drop::<T>() {
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, size: size_of::<T>(), drop_fn: glue::<T>, retained });
|
||||
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
}
|
||||
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
|
||||
Some((unsafe { &*ptr }, weak))
|
||||
}
|
||||
|
||||
/// Moves the payload at `src` out of this arena and into `dst`: the header's
|
||||
/// own bytes are copied, its drop obligation is pushed onto `dst` with the
|
||||
/// `retained` hint, and the entry here is tombstoned in place, its glue
|
||||
/// swapped for [`inert`] so the reset costs nothing per entry to honour it.
|
||||
/// The heap the payload owns is neither copied nor freed; ownership travels
|
||||
/// with the obligation and is discharged by `dst`'s flush.
|
||||
///
|
||||
/// THE MOVE'S OWNERSHIP CONTRACT: the source header keeps its bytes and
|
||||
/// stays readable to this generation's remaining sharers, but it owns
|
||||
/// nothing, so no read of it may outlive `dst`'s flush. A payload moved
|
||||
/// once is not moved again: its recorded destination is returned, so a
|
||||
/// fan-out sharer's second move reaches the one header and the obligation
|
||||
/// is never duplicated.
|
||||
///
|
||||
/// `dst` is credited `retained`, which is what a clone of the payload would
|
||||
/// have credited it, and this arena is debited what its own park recorded,
|
||||
/// so neither counter reads worse than it did before the move.
|
||||
///
|
||||
/// `None` where `src` is not this arena's park of `T`'s own size, where
|
||||
/// `T` is zero-sized (whose parks share an offset and so cannot be told
|
||||
/// apart), or where `dst` refused the header.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must address a live `T`, and a park of this arena at that address
|
||||
/// and size must be the `T` itself, not another type's park the address
|
||||
/// coincides with. `T` must own all of its content: the moved header may
|
||||
/// reference no storage of this arena.
|
||||
pub unsafe fn move_park<T: Send + Sync>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T> {
|
||||
(size_of::<T>() != 0).then_some(())?;
|
||||
let offset = (src as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
let mut forwarded = self.forwarded.lock().unwrap();
|
||||
if let Some(&(moved, size)) = forwarded.get(&offset) {
|
||||
(size == size_of::<T>()).then_some(())?;
|
||||
return Some(moved as *const T);
|
||||
}
|
||||
let mut entries = self.drops.lock().unwrap();
|
||||
let entry = entry_at(&entries, offset)?;
|
||||
(entries[entry].size == size_of::<T>()).then_some(())?;
|
||||
let slot = dst.alloc_scratch::<T>(1)?;
|
||||
let target = slot.as_mut_ptr().cast::<T>();
|
||||
// SAFETY: the caller's contract on `src`, into a freshly reserved,
|
||||
// aligned, unaliased slot of the same type.
|
||||
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T>(), target, 1) };
|
||||
let parked = std::mem::replace(&mut entries[entry].retained, 0);
|
||||
entries[entry].drop_fn = inert;
|
||||
drop(entries);
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
dst.drops.lock().unwrap().push(DropEntry {
|
||||
offset: target as usize - dst.base() as usize,
|
||||
size: size_of::<T>(),
|
||||
drop_fn: glue::<T>,
|
||||
retained,
|
||||
});
|
||||
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
|
||||
forwarded.insert(offset, (target as usize, size_of::<T>()));
|
||||
Some(target.cast_const())
|
||||
}
|
||||
|
||||
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
|
||||
let buf = self.alloc_scratch::<T>(src.len())?;
|
||||
for (slot, &value) in buf.iter_mut().zip(src) {
|
||||
slot.write(value);
|
||||
}
|
||||
// SAFETY: every lane written above from `src`.
|
||||
Some(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<T>(), src.len()) })
|
||||
}
|
||||
|
||||
// Not drop-tracked: callers must either consume every written lane or
|
||||
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
let size = size_of::<T>().checked_mul(len)?;
|
||||
let offset = self.reserve(size, align_of::<T>())?;
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
|
||||
// `&mut self`, so the slice cannot outlive the generation.
|
||||
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
|
||||
}
|
||||
|
||||
/// The generation-checked handle for a region this arena holds, `None` for
|
||||
/// a pointer from anywhere else. The handle keeps the region's provenance,
|
||||
/// so a cache stores one where it would otherwise launder an address.
|
||||
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
|
||||
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
ArenaWeak::new(self.generation(), offset)
|
||||
}
|
||||
|
||||
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
|
||||
/// where every handle misses and further allocation is refused.
|
||||
///
|
||||
/// A park [`Arena::move_park`] handed to another arena carries [`inert`]
|
||||
/// glue and a zeroed hint, so it costs the loop nothing beyond the call it
|
||||
/// would have made anyway.
|
||||
pub fn reset(&mut self) -> bool {
|
||||
let base = self.base();
|
||||
let entries = std::mem::take(self.drops.get_mut().unwrap());
|
||||
self.forwarded.get_mut().unwrap().clear();
|
||||
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||
for entry in entries.into_iter().rev() {
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
// Decremented as each payload's heap is freed, so an unwinding reset
|
||||
// leaves the counter matching what is still parked.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
}
|
||||
*self.offset.get_mut() = 0;
|
||||
*self.exhausted.get_mut() = false;
|
||||
let Some(generation) = next_generation() else { return false };
|
||||
self.generation.store(generation, Ordering::Release);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Arena {
|
||||
fn drop(&mut self) {
|
||||
self.reset();
|
||||
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ArenaWeak<T> {
|
||||
word: u64,
|
||||
_marker: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Clone for ArenaWeak<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
impl<T> Copy for ArenaWeak<T> {}
|
||||
|
||||
impl<T> ArenaWeak<T> {
|
||||
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
|
||||
|
||||
/// `None` once either field leaves its encodable range, so an oversized or parked
|
||||
/// arena refuses to hand out a handle rather than truncating it to a live address.
|
||||
fn new(generation: u64, offset: usize) -> Option<Self> {
|
||||
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
|
||||
(generation <= GENERATION_MASK).then_some(Self {
|
||||
word: (generation << OFFSET_BITS) | offset,
|
||||
_marker: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
|
||||
let generation = self.word >> OFFSET_BITS;
|
||||
if generation != arena.generation() {
|
||||
return None;
|
||||
}
|
||||
let offset = (self.word & OFFSET_MASK) as usize;
|
||||
// SAFETY: same generation means the entry was fully written before its
|
||||
// word was published (Release) and cannot move or be overwritten within
|
||||
// a generation (insert-only); the Acquire load that produced this word
|
||||
// ordered the payload writes.
|
||||
Some(unsafe { &*arena.base().add(offset).cast::<T>() })
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ArenaCell<T> {
|
||||
word: AtomicU64,
|
||||
_marker: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Clone for ArenaCell<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
word: AtomicU64::new(self.word.load(Ordering::Acquire)),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for ArenaCell<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ArenaCell").field("word", &self.word.load(Ordering::Relaxed)).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for ArenaCell<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
word: AtomicU64::new(0),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ArenaCell<T> {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn load<'e>(&self, arena: &'e Arena) -> Option<&'e T> {
|
||||
let weak = ArenaWeak::<T> {
|
||||
word: self.word.load(Ordering::Acquire),
|
||||
_marker: PhantomData,
|
||||
};
|
||||
weak.upgrade(arena)
|
||||
}
|
||||
|
||||
pub fn store(&self, weak: ArenaWeak<T>) {
|
||||
self.word.store(weak.word, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
#[test]
|
||||
fn alloc_upgrade_reset_miss() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let cell = ArenaCell::new();
|
||||
let (value, weak) = arena.alloc(41u32).unwrap();
|
||||
assert_eq!(*value, 41);
|
||||
cell.store(weak);
|
||||
assert_eq!(cell.load(&arena), Some(&41));
|
||||
arena.reset();
|
||||
assert_eq!(cell.load(&arena), None, "stale handle must miss");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_survives_reset() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
|
||||
for _ in 0..10 {
|
||||
for _ in 0..16 {
|
||||
assert!(arena.alloc(0u32).is_some());
|
||||
}
|
||||
assert!(arena.alloc(0u32).is_none(), "exhausted within generation");
|
||||
arena.reset();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panics_leave_the_arena_coherent() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
|
||||
assert_ref_unwind_safe::<Arena>();
|
||||
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let cell = ArenaCell::new();
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
|
||||
cell.store(weak);
|
||||
panic!("mid-eval");
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert!(cell.load(&arena).is_some(), "the generation is still live after the caught panic");
|
||||
arena.reset();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "reset reclaims pre-panic allocations");
|
||||
assert!(cell.load(&arena).is_none(), "the bump kills stale handles");
|
||||
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_destructor_leaves_no_resolvable_handle() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Bomb;
|
||||
impl Drop for Bomb {
|
||||
fn drop(&mut self) {
|
||||
panic!("payload destructor");
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let cell = ArenaCell::new();
|
||||
let (_, weak) = arena.alloc(Bomb).unwrap();
|
||||
cell.store(weak);
|
||||
|
||||
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
|
||||
assert!(unwound.is_err(), "the panic must propagate out of reset");
|
||||
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
|
||||
}
|
||||
|
||||
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
|
||||
/// is never observed by a concurrently constructing test.
|
||||
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[test]
|
||||
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let (_, weak) = arena.alloc(41u32).unwrap();
|
||||
|
||||
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
|
||||
assert!(!arena.reset(), "an exhausted counter must report failure");
|
||||
NEXT_GENERATION.store(restore, Ordering::Relaxed);
|
||||
|
||||
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
|
||||
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
|
||||
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_generation_counter_rewinds_only_without_live_arenas() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
|
||||
drop(arena);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_do_not_upgrade_against_a_foreign_arena() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let first = Arena::new(1024).unwrap();
|
||||
let second = Arena::new(1024).unwrap();
|
||||
let (_, weak) = first.alloc(41u32).unwrap();
|
||||
assert_eq!(weak.upgrade(&first), Some(&41));
|
||||
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
|
||||
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_drops_dependents_before_their_dependencies() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
|
||||
struct Probe(u32);
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
ORDER.lock().unwrap().push(self.0);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
for id in 0..3 {
|
||||
arena.alloc(Probe(id)).unwrap();
|
||||
}
|
||||
arena.reset();
|
||||
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sized_parks_account_for_their_retained_heap() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
assert_eq!(arena.retained_heap(), 0);
|
||||
|
||||
let owned = String::from("retained by the park");
|
||||
let length = owned.len();
|
||||
arena.alloc_sized(owned, length).unwrap();
|
||||
assert_eq!(arena.retained_heap(), length, "the park's hint reaches the counter");
|
||||
|
||||
arena.alloc(String::from("unmeasured")).unwrap();
|
||||
assert_eq!(arena.retained_heap(), length, "an unmeasured park contributes nothing");
|
||||
|
||||
arena.reset();
|
||||
assert_eq!(arena.retained_heap(), 0, "the flush frees every parked payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_park_carries_its_heap_and_its_obligation() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut transient = Arena::new(1024).unwrap();
|
||||
let mut persistent = Arena::new(1024).unwrap();
|
||||
|
||||
let owned = String::from("moved, never cloned");
|
||||
let length = owned.len();
|
||||
let heap = owned.as_ptr();
|
||||
let (parked, _) = transient.alloc_sized(owned, length).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
|
||||
let moved = unsafe { transient.move_park::<String>(src, &persistent, length) }.unwrap();
|
||||
assert_eq!(unsafe { &*moved }.as_ptr(), heap, "the move copies the header and leaves the heap where it was");
|
||||
assert!(persistent.contains(moved.cast()), "the header lands in the receiving arena");
|
||||
assert_eq!(transient.retained_heap(), 0, "the parking arena gives the hint up");
|
||||
assert_eq!(persistent.retained_heap(), length, "and the receiving arena takes it");
|
||||
|
||||
transient.reset();
|
||||
assert_eq!(unsafe { &*moved }, "moved, never cloned", "the parking arena's reset leaves a moved payload alone");
|
||||
persistent.reset();
|
||||
assert_eq!(persistent.retained_heap(), 0, "the receiving flush frees it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_park_two_records_share_moves_once_and_frees_once() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
DROPS.store(0, Ordering::Relaxed);
|
||||
let mut transient = Arena::new(1024).unwrap();
|
||||
let mut persistent = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc_sized(Probe(String::from("shared by two records")), 21).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
let first = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
|
||||
let second = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
|
||||
assert_eq!(first, second, "the second move forwards to the header the first wrote");
|
||||
assert_eq!(persistent.retained_heap(), 21, "the hint transfers once, not once per sharer");
|
||||
|
||||
transient.reset();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 0, "a tombstoned entry is skipped by its arena's reset");
|
||||
persistent.reset();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "the flush that owns the obligation frees it exactly once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_refuses_a_mistyped_park_and_its_forwarding() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Owner {
|
||||
_first: String,
|
||||
_tail: u64,
|
||||
}
|
||||
let mut transient = Arena::new(1024).unwrap();
|
||||
let mut persistent = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc(Owner { _first: String::from("a first member"), _tail: 0 }).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "a park of another size is refused");
|
||||
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
|
||||
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
|
||||
|
||||
transient.reset();
|
||||
persistent.reset();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forwarding_map_lives_one_generation() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
DROPS.store(0, Ordering::Relaxed);
|
||||
let mut transient = Arena::new(1024).unwrap();
|
||||
let mut persistent = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc_sized(Probe(String::from("first generation")), 16).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
unsafe { transient.move_park::<Probe>(src, &persistent, 16) }.unwrap();
|
||||
assert_eq!(transient.forwarded.lock().unwrap().len(), 1, "the move tombstoned the entry it left");
|
||||
|
||||
transient.reset();
|
||||
assert!(transient.forwarded.lock().unwrap().is_empty(), "the tombstone set is empty after the reset");
|
||||
|
||||
transient.alloc_sized(Probe(String::from("second generation")), 16).unwrap();
|
||||
transient.reset();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "a fresh park at a tombstoned offset drops normally");
|
||||
persistent.reset();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn occupancy_tracks_the_bump_and_clears_on_reset() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
assert_eq!(arena.occupancy(), 0);
|
||||
assert_eq!(arena.capacity(), 1024);
|
||||
arena.alloc(0u64).unwrap();
|
||||
assert_eq!(arena.occupancy(), 8);
|
||||
arena.reset();
|
||||
assert_eq!(arena.occupancy(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn containment_answers_only_for_this_arena() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let first = Arena::new(1024).unwrap();
|
||||
let second = Arena::new(1024).unwrap();
|
||||
let (value, _) = first.alloc(41u32).unwrap();
|
||||
let ptr = std::ptr::from_ref(value).cast::<u8>();
|
||||
assert!(first.contains(ptr));
|
||||
assert!(!second.contains(ptr));
|
||||
assert!(!first.contains(std::ptr::null()));
|
||||
let heap = Box::new(7u32);
|
||||
assert!(!first.contains(std::ptr::from_ref(&*heap).cast::<u8>()), "heap the arena does not back is outside it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_glue_runs_on_reset() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
arena.alloc(Probe("owns heap".into())).unwrap();
|
||||
arena.alloc(Probe("me too".into())).unwrap();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
|
||||
arena.reset();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
}
|
||||
@@ -1,438 +0,0 @@
|
||||
//! Attribute markers and their census. A marker declares an attribute name
|
||||
//! once, fixing its value type and its name-specific default; the census
|
||||
//! collects every declaration so name resolution, defaults, and diagnostics
|
||||
//! run at graph compile time. One name belongs to one marker, so a name can
|
||||
//! never mean two different types.
|
||||
//!
|
||||
//! Values are `Copy` and pack directly into record fields. Data with drop
|
||||
//! glue rides the arena instead: the marker declares a reference value
|
||||
//! (`&str`), the writing kernel parks the payload in the arena, and the
|
||||
//! record field carries the eval-lifetime reference.
|
||||
|
||||
use crate::list::AnyAttributeValue;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::any::TypeId;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Declares an attribute name: one marker per name, fixing the value type and
|
||||
/// the name-specific default. Declare markers through the [`attribute!`]
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
|
||||
pub trait Attribute: 'static {
|
||||
/// The name as it appears in documents and diagnostics.
|
||||
const NAME: &'static str;
|
||||
/// The value type every read and write of this name shares. The lifetime
|
||||
/// is the evaluation the value flows in; non-reference values ignore it.
|
||||
/// The value outlives that evaluation, so its `'static` instantiation is
|
||||
/// the one the census registers and layouts stamp their type id from.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + 'e;
|
||||
/// The name-specific default, filled where an item lacks the attribute.
|
||||
/// Producing a value for any `'e` from no inputs, reference defaults can
|
||||
/// only point at `'static` data, which is what lets the census fill them
|
||||
/// as plain bytes.
|
||||
fn default<'e>() -> Self::Value<'e> {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Borrows the value out of legacy list storage, whose stored form is the
|
||||
/// owned clone [`Self::read_erased`] produces. `None` where the column is
|
||||
/// absent or holds another type.
|
||||
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>>;
|
||||
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live field of this marker's value type.
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
|
||||
|
||||
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
||||
/// field storage; `None` for plain values, which ride the byte copy.
|
||||
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
|
||||
}
|
||||
|
||||
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
||||
/// (yielding the declared default where the attribute is absent upstream), an
|
||||
/// `Attr<A>` in the return tuple is a write, and the same marker on both
|
||||
/// sides is a modify.
|
||||
pub struct Attr<'e, A: Attribute>(pub A::Value<'e>);
|
||||
|
||||
impl<'e, A: Attribute> Deref for Attr<'e, A> {
|
||||
type Target = A::Value<'e>;
|
||||
|
||||
fn deref(&self) -> &A::Value<'e> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, A: Attribute> Clone for Attr<'e, A> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, A: Attribute> Copy for Attr<'e, A> {}
|
||||
|
||||
impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple(A::NAME).field(&self.0).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A deletion of `A` in a node's return tuple: the name leaves the output
|
||||
/// layout, so downstream reads yield the declared default again. Functionally
|
||||
/// a write of the default; the value carries nothing.
|
||||
pub struct RemoveAttr<A: Attribute>(PhantomData<A>);
|
||||
|
||||
impl<A: Attribute> RemoveAttr<A> {
|
||||
pub const fn new() -> Self {
|
||||
RemoveAttr(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Attribute> Default for RemoveAttr<A> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// A census row: what is known about one declared attribute name.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AttributeInfo {
|
||||
pub name: &'static str,
|
||||
pub value_type: TypeId,
|
||||
pub value_type_name: &'static str,
|
||||
pub default: fn() -> Box<dyn AnyAttributeValue>,
|
||||
pub size: usize,
|
||||
pub align: usize,
|
||||
/// Writes the declared default's bytes into a `size`-long slice.
|
||||
pub write_default_bytes: fn(&mut [u8]),
|
||||
/// The marker's field form at the given level, for layouts built at runtime.
|
||||
pub field_write_at: fn(u8) -> crate::record::FieldWrite,
|
||||
/// Writes a legacy stored value into a field of this marker, parking
|
||||
/// droppable payloads. A wrong-typed stored value leaves the field
|
||||
/// untouched; `None` reports arena exhaustion.
|
||||
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
}
|
||||
|
||||
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||
assert_eq!(out.len(), size_of::<A::Value<'static>>());
|
||||
let value: A::Value<'static> = A::default();
|
||||
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||
}
|
||||
|
||||
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
|
||||
where
|
||||
A::Value<'static>: graphene_hash::CacheHash + PartialEq,
|
||||
{
|
||||
crate::record::FieldWrite::of::<A>(level)
|
||||
}
|
||||
|
||||
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if A::from_stored(stored.as_any()).is_none() {
|
||||
// A wrong-typed stored value reads as absent, so the field keeps its default.
|
||||
return Some(());
|
||||
}
|
||||
match A::REPARK {
|
||||
Some(repark) => unsafe { repark(stored, dst, arena) },
|
||||
None => {
|
||||
let value = A::from_stored(stored.as_any()).expect("checked above");
|
||||
// SAFETY: a marker without re-park glue stores a plain value, so the bytes carry no borrowed data.
|
||||
unsafe { dst.cast::<A::Value<'_>>().write(value) };
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All declared attribute names, keyed by name.
|
||||
pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInfo>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Registers `A` into the census. Called by the [`attribute!`] expansion at
|
||||
/// startup (ctor natively, a `__node_registry_attribute_*` export on wasm).
|
||||
/// Re-registration at the same value type is idempotent; a second marker
|
||||
/// claiming the name at a different value type panics.
|
||||
pub fn register<A: Attribute>()
|
||||
where
|
||||
A::Value<'static>: AnyAttributeValue + graphene_hash::CacheHash + PartialEq,
|
||||
{
|
||||
let info = AttributeInfo {
|
||||
name: A::NAME,
|
||||
value_type: TypeId::of::<A::Value<'static>>(),
|
||||
value_type_name: std::any::type_name::<A::Value<'static>>(),
|
||||
default: || Box::new(A::default()),
|
||||
size: size_of::<A::Value<'static>>(),
|
||||
align: align_of::<A::Value<'static>>(),
|
||||
write_default_bytes: write_default_bytes::<A>,
|
||||
field_write_at: field_write_at::<A>,
|
||||
write_stored: write_stored::<A>,
|
||||
};
|
||||
let conflict = match ATTRIBUTE_REGISTRY.lock().unwrap().entry(A::NAME) {
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(info);
|
||||
None
|
||||
}
|
||||
Entry::Occupied(occupied) => (occupied.get().value_type != info.value_type).then(|| occupied.get().value_type_name),
|
||||
};
|
||||
if let Some(existing) = conflict {
|
||||
panic!("attribute `{}` is declared at two value types: {existing} and {}", A::NAME, info.value_type_name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks up a declared name.
|
||||
pub fn info(name: &str) -> Option<AttributeInfo> {
|
||||
ATTRIBUTE_REGISTRY.lock().unwrap().get(name).copied()
|
||||
}
|
||||
|
||||
/// The name-specific default for `name`, if the name is declared.
|
||||
pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||
info(name).map(|info| (info.default)())
|
||||
}
|
||||
|
||||
/// Declares attribute markers: for each entry, the marker struct, its
|
||||
/// [`Attribute`] impl, and the census registration.
|
||||
///
|
||||
/// ```
|
||||
/// core_types::attribute! {
|
||||
/// /// How visible the content is.
|
||||
/// pub Opacity("opacity"): f64 = 1.;
|
||||
/// /// The item's label, parked in the arena by the writer.
|
||||
/// pub Label("label"): &str;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The trailing `= expr` is the name-specific default; without it the value
|
||||
/// type's `Default` applies. A `&T` value carries the eval lifetime, so its
|
||||
/// default must be `'static` data. An `Option<&T>` value is an optional
|
||||
/// parked reference whose default is `None`, for attributes whose absence
|
||||
/// means something a present value cannot.
|
||||
#[macro_export]
|
||||
macro_rules! attribute {
|
||||
() => {};
|
||||
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): Option<&$value:ty>; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored
|
||||
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
|
||||
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
|
||||
value.as_any().downcast_ref().expect("an optional reference attribute replays its owned clone");
|
||||
let parked = match owned {
|
||||
::core::option::Option::Some(owned) => {
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
|
||||
}
|
||||
::core::option::Option::None => ::core::option::Option::None,
|
||||
};
|
||||
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::attribute!(@register $marker);
|
||||
$crate::attribute!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): &$value:ty $(= $default:expr)?; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = &'e $value;
|
||||
$(
|
||||
fn default<'e>() -> Self::Value<'e> {
|
||||
$default
|
||||
}
|
||||
)?
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference attribute replays its owned clone");
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::attribute!(@register $marker);
|
||||
$crate::attribute!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): $value:ty $(= $default:expr)?; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = $value;
|
||||
$(
|
||||
fn default<'e>() -> Self::Value<'e> {
|
||||
$default
|
||||
}
|
||||
)?
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<$value>().copied()
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
|
||||
}
|
||||
}
|
||||
|
||||
$crate::attribute!(@register $marker);
|
||||
$crate::attribute!($($rest)*);
|
||||
};
|
||||
(@register $marker:ident) => {
|
||||
const _: () = {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[$crate::ctor::ctor]
|
||||
fn register() {
|
||||
$crate::attribute::register::<$marker>();
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[unsafe(export_name = concat!("__node_registry_attribute_", stringify!($marker)))]
|
||||
extern "C" fn register() {
|
||||
$crate::attribute::register::<$marker>();
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
attribute! {
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
pub Transform("transform"): DAffine2;
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
pub BlendMode("blend_mode"): crate::blending::BlendMode;
|
||||
/// Item's opacity multiplier, composed multiplicatively through nested groups.
|
||||
/// Affects content clipped to the item.
|
||||
pub Opacity("opacity"): f64 = 1.;
|
||||
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
|
||||
pub OpacityFill("opacity_fill"): f64 = 1.;
|
||||
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub ClippingMask("clipping_mask"): bool;
|
||||
/// The document node path of the editor layer owning the item.
|
||||
/// Editor tools read it to route clicks and selection back to the originating layer.
|
||||
pub EditorLayerPath("editor:layer_path"): &[crate::uuid::NodeId];
|
||||
/// Maps the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' node's
|
||||
/// text frame in this item's local space. Each item carries the frame relative to its own
|
||||
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
|
||||
/// position its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub EditorTextFrame("editor:text_frame"): DAffine2;
|
||||
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
|
||||
pub Start("start"): u64;
|
||||
/// Byte offset where a regex match ends ('Regex Find All' and 'Regex Capture' text nodes).
|
||||
pub End("end"): u64;
|
||||
/// A regex named-capture-group's name, or empty for unnamed groups.
|
||||
pub Name("name"): &str;
|
||||
/// A JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||
pub Type("type"): &str;
|
||||
/// Artboard's top-left corner in document coordinates.
|
||||
pub Location("location"): DVec2;
|
||||
/// Artboard's width and height.
|
||||
pub Dimensions("dimensions"): DVec2;
|
||||
/// Artboard's background fill.
|
||||
pub Background("background"): crate::Color;
|
||||
/// Whether an artboard clips content to its bounds.
|
||||
pub Clip("clip"): bool;
|
||||
/// Text item's font size in document-space units.
|
||||
pub FontSize("font_size"): f64 = 24.;
|
||||
/// Text item's line height as a ratio of the font size.
|
||||
pub LineHeight("line_height"): f64 = 1.2;
|
||||
/// Text item's extra spacing between letters in document-space units.
|
||||
pub LetterSpacing("letter_spacing"): f64;
|
||||
/// Text item's maximum line-wrap width in document-space units.
|
||||
pub MaxWidth("max_width"): Option<f64>;
|
||||
/// Text item's maximum block height in document-space units, past which lines are not drawn.
|
||||
pub MaxHeight("max_height"): Option<f64>;
|
||||
/// Text item's faux-italic letter tilt angle in degrees.
|
||||
pub LetterTilt("letter_tilt"): f64;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn census_carries_declared_names() {
|
||||
let row = info("opacity").unwrap();
|
||||
assert_eq!(row.value_type, TypeId::of::<f64>());
|
||||
assert_eq!(info("transform").unwrap().value_type, TypeId::of::<DAffine2>());
|
||||
assert_eq!(info("max_width").unwrap().value_type, TypeId::of::<Option<f64>>());
|
||||
assert_eq!(info("background").unwrap().value_type, TypeId::of::<crate::Color>());
|
||||
assert!(info("never_declared").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_specific_default_overrides_the_type_default() {
|
||||
assert_eq!(<Opacity as Attribute>::default(), 1.);
|
||||
assert_eq!(<Name as Attribute>::default(), "");
|
||||
assert_eq!(<FontSize as Attribute>::default(), 24.);
|
||||
assert_eq!(<LineHeight as Attribute>::default(), 1.2);
|
||||
assert_eq!(<MaxWidth as Attribute>::default(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erased_default_downcasts_to_the_declared_type() {
|
||||
let value = default_value("opacity_fill").unwrap();
|
||||
assert_eq!(*value.as_any().downcast_ref::<f64>().unwrap(), 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values_register_at_the_static_instantiation() {
|
||||
let row = info("name").unwrap();
|
||||
assert_eq!(row.value_type, TypeId::of::<&'static str>());
|
||||
assert_eq!(row.size, size_of::<&str>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reregistration_at_the_same_type_is_idempotent() {
|
||||
register::<Opacity>();
|
||||
register::<Opacity>();
|
||||
assert_eq!(info("opacity").unwrap().value_type, TypeId::of::<f64>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "two value types")]
|
||||
fn a_second_marker_at_a_different_type_panics() {
|
||||
struct Conflict;
|
||||
impl Attribute for Conflict {
|
||||
const NAME: &'static str = "opacity";
|
||||
type Value<'e> = bool;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<bool>().copied()
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
|
||||
Box::new(unsafe { ptr.cast::<bool>().read() })
|
||||
}
|
||||
}
|
||||
register::<Conflict>();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::Color;
|
||||
use crate::lane::{LaneColumn, LaneSource};
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq)]
|
||||
@@ -16,7 +15,7 @@ pub trait BoundingBox {
|
||||
/// Returns the bounding box to use when sizing this value's thumbnail in the Layers panel.
|
||||
///
|
||||
/// Diverges from `bounding_box` for types where the rendering bounds wouldn't make a useful thumbnail frame.
|
||||
/// For instance, `GradientStops` is `Infinite` for rendering but returns the line's AABB here, so a `List<Graphic>`
|
||||
/// For instance, `Gradient` is `Infinite` for rendering but returns the line's AABB here, so a `List<Graphic>`
|
||||
/// group of a gradient and a vector frames around the vector's geometry rather than infinity.
|
||||
/// Types with no meaningful contribution (e.g., `Color`) return `Infinite` from both; the runtime substitutes a
|
||||
/// small fallback rectangle at the end if no finite bounds remain after combining.
|
||||
@@ -52,62 +51,3 @@ impl BoundingBox for Color {
|
||||
RenderBoundingBox::Infinite
|
||||
}
|
||||
}
|
||||
|
||||
/// Combined bounding box of a lane source's elements, composing each lane's
|
||||
/// transform attribute with the given transform.
|
||||
pub fn lane_bounding_box<S: LaneSource>(source: &S, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox
|
||||
where
|
||||
S::Element: BoundingBox,
|
||||
{
|
||||
let mut combined_bounds = None;
|
||||
|
||||
let transforms = source.column::<crate::attribute::Transform>();
|
||||
for lane in 0..source.lane_count() {
|
||||
let Some(element) = source.element(lane) else { continue };
|
||||
let lane_transform: DAffine2 = transforms.get(lane);
|
||||
match element.bounding_box(transform * lane_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
|
||||
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
||||
Some(existing) => combined_bounds = Some(crate::math::quad::Quad::combine_bounds(existing, bounds)),
|
||||
None => combined_bounds = Some(bounds),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
match combined_bounds {
|
||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||
None => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`lane_bounding_box`], but `Infinite` lanes are skipped (rather than
|
||||
/// propagating outward) so a finite sibling in a mixed group dictates the
|
||||
/// framing.
|
||||
pub fn lane_thumbnail_bounding_box<S: LaneSource>(source: &S, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox
|
||||
where
|
||||
S::Element: BoundingBox,
|
||||
{
|
||||
let mut combined_bounds = None;
|
||||
let mut any_infinite = false;
|
||||
|
||||
let transforms = source.column::<crate::attribute::Transform>();
|
||||
for lane in 0..source.lane_count() {
|
||||
let Some(element) = source.element(lane) else { continue };
|
||||
let lane_transform: DAffine2 = transforms.get(lane);
|
||||
match element.thumbnail_bounding_box(transform * lane_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => any_infinite = true,
|
||||
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
||||
Some(existing) => combined_bounds = Some(crate::math::quad::Quad::combine_bounds(existing, bounds)),
|
||||
None => combined_bounds = Some(bounds),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
match (combined_bounds, any_infinite) {
|
||||
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||
(None, true) => RenderBoundingBox::Infinite,
|
||||
(None, false) => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,93 +0,0 @@
|
||||
//! The typed surface handed to an `extent(fn)` helper: the node's inputs in
|
||||
//! declaration order, then the queried level. Values read without unsafe or
|
||||
//! internal fields, upstream extents query per level, and the one blessed
|
||||
//! context modification is per-copy derived promotion. Anything beyond this
|
||||
//! vocabulary uses `extent_raw(fn)`, which keeps the full node/ctx/level form.
|
||||
|
||||
use crate::gpoll::{Extent, GPoll};
|
||||
|
||||
/// A wired value input; `get` evaluates the edge and yields the typed element.
|
||||
pub struct ValueIn<'a, T> {
|
||||
read: &'a dyn Fn() -> GPoll<T>,
|
||||
}
|
||||
|
||||
impl<'a, T> ValueIn<'a, T> {
|
||||
pub fn new(read: &'a dyn Fn() -> GPoll<T>) -> Self {
|
||||
Self { read }
|
||||
}
|
||||
|
||||
pub fn get(&self) -> GPoll<T> {
|
||||
(self.read)()
|
||||
}
|
||||
}
|
||||
|
||||
/// An upstream edge's extents. For derived (per-copy) content the query runs
|
||||
/// at the given copy's promoted context; `at` queries copy 0, the uniform
|
||||
/// default. For ordinary edges the copy is ignored.
|
||||
pub struct ExtentIn<'a> {
|
||||
query: &'a dyn Fn(u64, u8) -> GPoll<Extent>,
|
||||
}
|
||||
|
||||
impl<'a> ExtentIn<'a> {
|
||||
pub fn new(query: &'a dyn Fn(u64, u8) -> GPoll<Extent>) -> Self {
|
||||
Self { query }
|
||||
}
|
||||
|
||||
pub fn at(&self, level: LevelIn) -> GPoll<Extent> {
|
||||
(self.query)(0, level.level)
|
||||
}
|
||||
|
||||
pub fn at_copy(&self, copy: u64, level: LevelIn) -> GPoll<Extent> {
|
||||
(self.query)(copy, level.level)
|
||||
}
|
||||
}
|
||||
|
||||
/// A ranked (`IList`) input materialized whole: `get` drives the batch and
|
||||
/// yields the level as a [`List`](crate::node::List), for extents that depend
|
||||
/// on the input's data rather than its counts alone. `total` answers the
|
||||
/// subject's flat count without materializing, so count-shaped extents stay
|
||||
/// cheap: a materializing extent inside another's subject multiplies, and
|
||||
/// nested emitters turn that into a blowup.
|
||||
pub struct ListIn<'a, T> {
|
||||
get: &'a dyn Fn() -> GPoll<crate::node::List<'a, T>>,
|
||||
total: &'a dyn Fn() -> GPoll<crate::gpoll::Extent>,
|
||||
}
|
||||
|
||||
impl<'a, T> ListIn<'a, T> {
|
||||
pub fn new(get: &'a dyn Fn() -> GPoll<crate::node::List<'a, T>>, total: &'a dyn Fn() -> GPoll<crate::gpoll::Extent>) -> Self {
|
||||
Self { get, total }
|
||||
}
|
||||
|
||||
pub fn get(&self) -> GPoll<crate::node::List<'a, T>> {
|
||||
(self.get)()
|
||||
}
|
||||
|
||||
/// The subject wire's total flat extent as a plain query.
|
||||
pub fn total(&self) -> GPoll<crate::gpoll::Extent> {
|
||||
(self.total)()
|
||||
}
|
||||
}
|
||||
|
||||
/// The queried absolute level (innermost `0`), paired with the node's depth.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct LevelIn {
|
||||
pub level: u8,
|
||||
pub depth: u8,
|
||||
}
|
||||
|
||||
impl LevelIn {
|
||||
pub fn new(level: u8, depth: u8) -> Self {
|
||||
Self { level, depth }
|
||||
}
|
||||
|
||||
/// Whether the query targets the node's own pushed (outermost) level.
|
||||
pub fn pushed(&self) -> bool {
|
||||
self.level + 1 == self.depth
|
||||
}
|
||||
|
||||
/// Whether the query targets the topmost level; `pushed` under the name a
|
||||
/// non-creator (concat, remap) reads naturally.
|
||||
pub fn top(&self) -> bool {
|
||||
self.pushed()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use crate::Node;
|
||||
use std::marker::PhantomData;
|
||||
#[derive(Clone)]
|
||||
pub struct FnNode<T: Fn(I) -> O, I, O>(T, PhantomData<(I, O)>);
|
||||
|
||||
impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode<T, I, O> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> Self::Output {
|
||||
self.0(input)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Fn(I) -> O, I, O> FnNode<T, I, O> {
|
||||
pub fn new(f: T) -> Self {
|
||||
FnNode(f, PhantomData)
|
||||
}
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ErrorKind {
|
||||
Node(&'static str),
|
||||
ArenaExhausted,
|
||||
Panic,
|
||||
/// A lane past the end of a lower-bound (`Extent::AtLeast`) level: the
|
||||
/// end-of-data signal for draining consumers, an error for everyone else.
|
||||
PastEnd,
|
||||
}
|
||||
|
||||
impl PartialEq<&str> for ErrorKind {
|
||||
fn eq(&self, other: &&str) -> bool {
|
||||
matches!(self, ErrorKind::Node(kind) if kind == other)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GraphError {
|
||||
pub kind: ErrorKind,
|
||||
pub trace: Vec<usize>,
|
||||
}
|
||||
|
||||
impl GraphError {
|
||||
pub fn new(kind: &'static str) -> Self {
|
||||
Self {
|
||||
kind: ErrorKind::Node(kind),
|
||||
trace: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn traced(mut self, input_index: usize) -> Self {
|
||||
self.trace.push(input_index);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn past_end() -> Self {
|
||||
Self {
|
||||
kind: ErrorKind::PastEnd,
|
||||
trace: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GPoll<T> {
|
||||
Pending,
|
||||
Final(T),
|
||||
Partial(T),
|
||||
Fallback(Box<(T, GraphError)>),
|
||||
Error(Box<GraphError>),
|
||||
}
|
||||
|
||||
impl<T> GPoll<T> {
|
||||
#[inline(always)]
|
||||
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> GPoll<U> {
|
||||
match self {
|
||||
GPoll::Pending => GPoll::Pending,
|
||||
GPoll::Final(value) => GPoll::Final(f(value)),
|
||||
GPoll::Partial(value) => GPoll::Partial(f(value)),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, e) = *boxed;
|
||||
GPoll::Fallback(Box::new((f(value), e)))
|
||||
}
|
||||
GPoll::Error(e) => GPoll::Error(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn and_then<U>(self, f: impl FnOnce(T) -> GPoll<U>) -> GPoll<U> {
|
||||
match self {
|
||||
GPoll::Pending => GPoll::Pending,
|
||||
GPoll::Final(value) => f(value),
|
||||
GPoll::Partial(value) => match f(value) {
|
||||
GPoll::Final(result) => GPoll::Partial(result),
|
||||
other => other,
|
||||
},
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, e) = *boxed;
|
||||
match f(value) {
|
||||
GPoll::Pending => GPoll::Pending,
|
||||
GPoll::Final(result) | GPoll::Partial(result) => GPoll::Fallback(Box::new((result, e))),
|
||||
GPoll::Fallback(inner) => {
|
||||
let (result, _) = *inner;
|
||||
GPoll::Fallback(Box::new((result, e)))
|
||||
}
|
||||
GPoll::Error(inner) => GPoll::Error(inner),
|
||||
}
|
||||
}
|
||||
GPoll::Error(e) => GPoll::Error(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn zip<U>(self, other: GPoll<U>) -> GPoll<(T, U)> {
|
||||
match (self, other) {
|
||||
(GPoll::Error(e), _) | (_, GPoll::Error(e)) => GPoll::Error(e),
|
||||
(GPoll::Pending, _) | (_, GPoll::Pending) => GPoll::Pending,
|
||||
(GPoll::Final(a), GPoll::Final(b)) => GPoll::Final((a, b)),
|
||||
(GPoll::Fallback(boxed), GPoll::Final(b) | GPoll::Partial(b)) => {
|
||||
let (a, e) = *boxed;
|
||||
GPoll::Fallback(Box::new(((a, b), e)))
|
||||
}
|
||||
(GPoll::Final(a) | GPoll::Partial(a), GPoll::Fallback(boxed)) => {
|
||||
let (b, e) = *boxed;
|
||||
GPoll::Fallback(Box::new(((a, b), e)))
|
||||
}
|
||||
(GPoll::Fallback(first), GPoll::Fallback(second)) => {
|
||||
let (a, e) = *first;
|
||||
let (b, _) = *second;
|
||||
GPoll::Fallback(Box::new(((a, b), e)))
|
||||
}
|
||||
(GPoll::Partial(a), GPoll::Final(b) | GPoll::Partial(b)) | (GPoll::Final(a), GPoll::Partial(b)) => GPoll::Partial((a, b)),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn trace(self, input: usize) -> Self {
|
||||
match self {
|
||||
GPoll::Fallback(mut boxed) => {
|
||||
boxed.1.trace.push(input);
|
||||
GPoll::Fallback(boxed)
|
||||
}
|
||||
GPoll::Error(mut e) => {
|
||||
e.trace.push(input);
|
||||
GPoll::Error(e)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fallback(value: T, kind: &'static str) -> Self {
|
||||
GPoll::Fallback(Box::new((value, GraphError::new(kind))))
|
||||
}
|
||||
|
||||
pub fn error(kind: &'static str) -> Self {
|
||||
GPoll::Error(Box::new(GraphError::new(kind)))
|
||||
}
|
||||
|
||||
pub fn arena_exhausted() -> Self {
|
||||
GPoll::Error(Box::new(GraphError {
|
||||
kind: ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn panicked() -> Self {
|
||||
GPoll::Error(Box::new(GraphError {
|
||||
kind: ErrorKind::Panic,
|
||||
trace: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn past_end() -> Self {
|
||||
GPoll::Error(Box::new(GraphError::past_end()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Interrupt {
|
||||
Pending,
|
||||
Error(Box<GraphError>),
|
||||
}
|
||||
|
||||
impl From<GraphError> for Interrupt {
|
||||
fn from(error: GraphError) -> Self {
|
||||
Interrupt::Error(Box::new(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Interrupt> for GPoll<T> {
|
||||
fn from(interrupt: Interrupt) -> Self {
|
||||
match interrupt {
|
||||
Interrupt::Pending => GPoll::Pending,
|
||||
Interrupt::Error(e) => GPoll::Error(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Extent {
|
||||
Free,
|
||||
Exactly(usize),
|
||||
/// A sound lower bound; the true count is discoverable only by draining.
|
||||
AtLeast(usize),
|
||||
}
|
||||
|
||||
impl Extent {
|
||||
pub fn meet(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||
a.zip(b).and_then(|(a, b)| match (a, b) {
|
||||
(Extent::Free, other) | (other, Extent::Free) => GPoll::Final(other),
|
||||
(Extent::Exactly(n), Extent::Exactly(m)) if n == m => GPoll::Final(Extent::Exactly(n)),
|
||||
(Extent::AtLeast(a), Extent::AtLeast(b)) => GPoll::Final(Extent::AtLeast(a.max(b))),
|
||||
(Extent::AtLeast(bound), Extent::Exactly(n)) | (Extent::Exactly(n), Extent::AtLeast(bound)) if n >= bound => GPoll::Final(Extent::Exactly(n)),
|
||||
(Extent::AtLeast(_), Extent::Exactly(n)) | (Extent::Exactly(n), Extent::AtLeast(_)) => GPoll::fallback(Extent::Exactly(n), "extent mismatch"),
|
||||
(Extent::Exactly(n), Extent::Exactly(m)) => GPoll::fallback(Extent::Exactly(n.min(m)), "extent mismatch"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The product of two extents, used to compose nested-level counts; an
|
||||
/// unbounded operand leaves the product unbounded, a lower-bound operand
|
||||
/// keeps the product a lower bound.
|
||||
pub fn mul(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||
a.zip(b).map(|(a, b)| match (a, b) {
|
||||
(Extent::Free, _) | (_, Extent::Free) => Extent::Free,
|
||||
(Extent::Exactly(n), Extent::Exactly(m)) => Extent::Exactly(n * m),
|
||||
(Extent::AtLeast(n) | Extent::Exactly(n), Extent::AtLeast(m) | Extent::Exactly(m)) => Extent::AtLeast(n * m),
|
||||
})
|
||||
}
|
||||
|
||||
/// The sum of two extents, used to concatenate a level; a free operand
|
||||
/// counts as one lane, so a scalar edge joins a concat as a single item,
|
||||
/// and a lower-bound operand keeps the sum a lower bound.
|
||||
pub fn sum(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||
let lanes = |extent| match extent {
|
||||
Extent::Exactly(count) | Extent::AtLeast(count) => count,
|
||||
Extent::Free => 1,
|
||||
};
|
||||
a.zip(b).map(|(a, b)| match (a, b) {
|
||||
(Extent::AtLeast(_), _) | (_, Extent::AtLeast(_)) => Extent::AtLeast(lanes(a) + lanes(b)),
|
||||
_ => Extent::Exactly(lanes(a) + lanes(b)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A query over a node's nesting levels: one level, the product below or above
|
||||
/// it, or the whole domain. The composite [`Node::extent`](crate::node::Node::extent)
|
||||
/// derives these from the per-level [`extent_at`](crate::node::Node::extent_at).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Level {
|
||||
At(u8),
|
||||
Below(u8),
|
||||
Above(u8),
|
||||
Total,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Finality {
|
||||
AllFinal,
|
||||
Partial,
|
||||
}
|
||||
|
||||
impl Finality {
|
||||
pub fn meet(self, other: Finality) -> Finality {
|
||||
match (self, other) {
|
||||
(Finality::AllFinal, Finality::AllFinal) => Finality::AllFinal,
|
||||
_ => Finality::Partial,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn free_is_the_meet_identity() {
|
||||
let meet = Extent::meet(GPoll::Final(Extent::Free), GPoll::Final(Extent::Exactly(4)));
|
||||
assert_eq!(meet, GPoll::Final(Extent::Exactly(4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extent_mismatch_truncates_and_reports() {
|
||||
let meet = Extent::meet(GPoll::Final(Extent::Exactly(3)), GPoll::Final(Extent::Exactly(5)));
|
||||
let GPoll::Fallback(boxed) = meet else {
|
||||
panic!("expected fallback, got {meet:?}");
|
||||
};
|
||||
assert_eq!(boxed.0, Extent::Exactly(3));
|
||||
assert!(boxed.1.kind == "extent mismatch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_dominates_pending_in_zip() {
|
||||
let zipped = GPoll::<u32>::error("boom").zip(GPoll::<u32>::Pending);
|
||||
assert!(matches!(zipped, GPoll::Error(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_builds_root_to_source_path() {
|
||||
let poll = GPoll::<u32>::error("boom").trace(2).trace(0);
|
||||
let GPoll::Error(e) = poll else { unreachable!() };
|
||||
assert_eq!(e.trace, vec![2, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupt_round_trips_to_gpoll() {
|
||||
assert_eq!(GPoll::<u32>::from(Interrupt::Pending), GPoll::Pending);
|
||||
let interrupt = Interrupt::from(GraphError::new("boom"));
|
||||
assert!(matches!(GPoll::<u32>::from(interrupt), GPoll::Error(e) if e.kind == "boom"));
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
//! The read surface over a source of lanes, so readers name census markers
|
||||
//! instead of a storage shape.
|
||||
|
||||
use crate::attribute::Attribute;
|
||||
|
||||
/// One marker's column on a source, resolved once so lane reads skip the key
|
||||
/// lookup.
|
||||
pub trait LaneColumn<'a, A: Attribute> {
|
||||
/// The lane's value, `None` where the source carries no such column.
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>>;
|
||||
|
||||
/// The lane's value, falling back to the marker's census default.
|
||||
fn get(&self, lane: usize) -> A::Value<'a> {
|
||||
self.try_get(lane).unwrap_or_else(A::default)
|
||||
}
|
||||
}
|
||||
|
||||
/// A source of lanes carrying an element and census attributes.
|
||||
pub trait LaneSource {
|
||||
type Element;
|
||||
type Column<'a, A: Attribute>: LaneColumn<'a, A>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
fn lane_count(&self) -> usize;
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&Self::Element>;
|
||||
|
||||
fn column<A: Attribute>(&self) -> Self::Column<'_, A>;
|
||||
|
||||
fn attr<A: Attribute>(&self, lane: usize) -> A::Value<'_> {
|
||||
self.column::<A>().get(lane)
|
||||
}
|
||||
|
||||
/// Distinguishes an absent column from one holding the census default.
|
||||
fn try_attr<A: Attribute>(&self, lane: usize) -> Option<A::Value<'_>> {
|
||||
self.column::<A>().try_get(lane)
|
||||
}
|
||||
}
|
||||
|
||||
/// A bare element as a one-lane source: no columns, so every marker reads its
|
||||
/// census default. The read surface for a de-tabled leaf, whose attributes
|
||||
/// ride the containing lane.
|
||||
pub struct Single<'a, T>(pub &'a T);
|
||||
|
||||
/// The column of a [`Single`]: always absent, so reads fall to the census
|
||||
/// default.
|
||||
pub struct NoColumn;
|
||||
|
||||
impl<'a, A: Attribute> LaneColumn<'a, A> for NoColumn {
|
||||
fn try_get(&self, _lane: usize) -> Option<A::Value<'a>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> LaneSource for Single<'_, T> {
|
||||
type Element = T;
|
||||
type Column<'a, A: Attribute>
|
||||
= NoColumn
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&T> {
|
||||
(lane == 0).then_some(self.0)
|
||||
}
|
||||
|
||||
fn column<A: Attribute>(&self) -> NoColumn {
|
||||
NoColumn
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: crate::bounds::BoundingBox> crate::bounds::BoundingBox for Single<'_, T> {
|
||||
fn bounding_box(&self, transform: glam::DAffine2, include_stroke: bool) -> crate::bounds::RenderBoundingBox {
|
||||
self.0.bounding_box(transform, include_stroke)
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: glam::DAffine2, include_stroke: bool) -> crate::bounds::RenderBoundingBox {
|
||||
self.0.thumbnail_bounding_box(transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
/// One lane of a source re-based as a one-lane source of a leaf element: the
|
||||
/// de-tabled leaf read with its containing lane's attributes.
|
||||
pub struct LeafLane<'a, S, T> {
|
||||
source: &'a S,
|
||||
index: usize,
|
||||
element: &'a T,
|
||||
}
|
||||
|
||||
impl<'a, S, T> LeafLane<'a, S, T> {
|
||||
pub fn new(source: &'a S, index: usize, element: &'a T) -> Self {
|
||||
Self { source, index, element }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LaneColumnAt<'a, S: LaneSource + 'a, A: Attribute> {
|
||||
inner: S::Column<'a, A>,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for LaneColumnAt<'a, S, A> {
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||
(lane == 0).then(|| self.inner.try_get(self.index)).flatten()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: LaneSource, T> LaneSource for LeafLane<'_, S, T> {
|
||||
type Element = T;
|
||||
type Column<'a, A: Attribute>
|
||||
= LaneColumnAt<'a, S, A>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&T> {
|
||||
(lane == 0).then_some(self.element)
|
||||
}
|
||||
|
||||
fn column<A: Attribute>(&self) -> LaneColumnAt<'_, S, A> {
|
||||
LaneColumnAt {
|
||||
inner: self.source.column::<A>(),
|
||||
index: self.index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::LaneSource;
|
||||
use crate::attribute::{EditorLayerPath, Opacity, Transform};
|
||||
use crate::list::List;
|
||||
use crate::uuid::NodeId;
|
||||
use glam::DAffine2;
|
||||
|
||||
#[test]
|
||||
fn a_plain_marker_reads_what_the_legacy_column_stores() {
|
||||
let mut list = List::new_from_element(1u32);
|
||||
let transform = DAffine2::from_translation((3., 4.).into());
|
||||
list.set_attribute(crate::ATTR_TRANSFORM, 0, transform);
|
||||
|
||||
assert_eq!(list.attr::<Transform>(0), transform);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_marker_reads_its_census_default_not_the_value_default() {
|
||||
let list = List::new_from_element(1u32);
|
||||
|
||||
// `Opacity` declares `= 1.`, so the census default must win over `f64::default()`.
|
||||
assert_eq!(list.attr::<Opacity>(0), 1.);
|
||||
assert_eq!(list.attr::<Transform>(0), DAffine2::IDENTITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_marker_borrows_the_stored_owned_form() {
|
||||
let mut list = List::new_from_element(1u32);
|
||||
let path = vec![NodeId(7), NodeId(9)];
|
||||
list.set_attribute(crate::ATTR_EDITOR_LAYER_PATH, 0, path.clone());
|
||||
|
||||
assert_eq!(list.attr::<EditorLayerPath>(0), path.as_slice());
|
||||
assert!(List::new_from_element(1u32).attr::<EditorLayerPath>(0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_of_the_wrong_stored_type_reads_as_absent() {
|
||||
let mut list = List::new_from_element(1u32);
|
||||
list.set_attribute(crate::ATTR_OPACITY, 0, "not an f64".to_string());
|
||||
|
||||
assert_eq!(list.attr::<Opacity>(0), 1.);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,16 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod arena;
|
||||
pub mod attribute;
|
||||
pub mod bounds;
|
||||
pub mod consts;
|
||||
pub mod context;
|
||||
pub mod extent;
|
||||
pub mod gpoll;
|
||||
pub mod lane;
|
||||
pub mod generic;
|
||||
pub mod list;
|
||||
pub mod math;
|
||||
pub mod memo;
|
||||
pub mod misc;
|
||||
pub mod node;
|
||||
pub mod ops;
|
||||
pub mod record;
|
||||
pub mod registry;
|
||||
pub mod render_complexity;
|
||||
pub mod runtime;
|
||||
pub mod transform;
|
||||
pub mod uuid;
|
||||
pub mod value;
|
||||
@@ -31,8 +24,9 @@ pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_TEXT_FRAME, ATTR_END, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT,
|
||||
ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use no_std_types::AsU32;
|
||||
@@ -40,15 +34,113 @@ pub use no_std_types::blending;
|
||||
pub use no_std_types::choice_type;
|
||||
pub use no_std_types::color;
|
||||
pub use no_std_types::shaders;
|
||||
pub use node::Node;
|
||||
pub use num_traits;
|
||||
use std::any::TypeId;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
#[cfg(feature = "wasm")]
|
||||
pub use tsify;
|
||||
pub use types::Cow;
|
||||
|
||||
// pub trait Node: for<'n> NodeIO<'n> {
|
||||
/// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct.
|
||||
/// See `node-graph/README.md` for information on how to define a new node.
|
||||
pub trait Node<'i, Input> {
|
||||
type Output: 'i;
|
||||
/// Evaluates the node with the single specified input.
|
||||
fn eval(&'i self, input: Input) -> Self::Output;
|
||||
/// Resets the node, e.g. the LetNode's cache is set to None.
|
||||
fn reset(&self) {}
|
||||
/// Returns the name of the node for diagnostic purposes.
|
||||
fn node_name(&self) -> &'static str {
|
||||
std::any::type_name::<Self>()
|
||||
}
|
||||
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
mod types;
|
||||
pub use types::*;
|
||||
|
||||
pub trait NodeIO<'i, Input>: Node<'i, Input>
|
||||
where
|
||||
Self::Output: 'i + StaticTypeSized,
|
||||
Input: StaticTypeSized,
|
||||
{
|
||||
fn input_type(&self) -> TypeId {
|
||||
TypeId::of::<Input::Static>()
|
||||
}
|
||||
fn input_type_name(&self) -> &'static str {
|
||||
std::any::type_name::<Input>()
|
||||
}
|
||||
fn output_type(&self) -> TypeId {
|
||||
TypeId::of::<<Self::Output as StaticTypeSized>::Static>()
|
||||
}
|
||||
fn output_type_name(&self) -> &'static str {
|
||||
std::any::type_name::<Self::Output>()
|
||||
}
|
||||
fn to_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes {
|
||||
NodeIOTypes {
|
||||
call_argument: concrete!(<Input as StaticTypeSized>::Static),
|
||||
return_value: concrete!(<Self::Output as StaticTypeSized>::Static),
|
||||
inputs,
|
||||
}
|
||||
}
|
||||
fn to_async_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes
|
||||
where
|
||||
<Self::Output as Future>::Output: StaticTypeSized,
|
||||
Self::Output: Future,
|
||||
{
|
||||
NodeIOTypes {
|
||||
call_argument: concrete!(<Input as StaticTypeSized>::Static),
|
||||
return_value: future!(<<Self::Output as Future>::Output as StaticTypeSized>::Static),
|
||||
inputs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N
|
||||
where
|
||||
N::Output: 'i + StaticTypeSized,
|
||||
I: StaticTypeSized,
|
||||
{
|
||||
}
|
||||
|
||||
impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N {
|
||||
type Output = N::Output;
|
||||
fn eval(&'i self, input: I) -> N::Output {
|
||||
(*self).eval(input)
|
||||
}
|
||||
}
|
||||
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box<N> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc<N> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i, I, O: 'i> Node<'i, I> for Pin<Box<dyn Node<'i, I, Output = O> + 'i>> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
|
||||
fn get_input(&'a self, index: usize) -> Option<&'a T>;
|
||||
fn set_input(&'a mut self, index: usize, value: T);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::attribute::Attribute as _;
|
||||
use crate::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use crate::math::quad::Quad;
|
||||
use crate::transform::ApplyTransform;
|
||||
use dyn_any::{StaticType, StaticTypeSized};
|
||||
use crate::uuid::NodeId;
|
||||
use dyn_any::{DynAny, StaticType, StaticTypeSized};
|
||||
use glam::DAffine2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
@@ -9,42 +10,134 @@ use std::fmt::Debug;
|
||||
// =================================================
|
||||
// Standard attribute keys used across the data flow
|
||||
// =================================================
|
||||
// Each name is declared once by its marker, which documents the attribute and
|
||||
// fixes its value type. The constants re-export the markers' names for the
|
||||
// string-keyed legacy readers and writers. Markers whose value types live
|
||||
// below core-types are declared in their types' crates (vector-types, the
|
||||
// text nodes, graphic-types), each with its own name constants.
|
||||
|
||||
pub const ATTR_TRANSFORM: &str = crate::attribute::Transform::NAME;
|
||||
pub const ATTR_BLEND_MODE: &str = crate::attribute::BlendMode::NAME;
|
||||
pub const ATTR_OPACITY: &str = crate::attribute::Opacity::NAME;
|
||||
pub const ATTR_OPACITY_FILL: &str = crate::attribute::OpacityFill::NAME;
|
||||
pub const ATTR_CLIPPING_MASK: &str = crate::attribute::ClippingMask::NAME;
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = crate::attribute::EditorLayerPath::NAME;
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = crate::attribute::EditorTextFrame::NAME;
|
||||
pub const ATTR_START: &str = crate::attribute::Start::NAME;
|
||||
pub const ATTR_END: &str = crate::attribute::End::NAME;
|
||||
pub const ATTR_NAME: &str = crate::attribute::Name::NAME;
|
||||
pub const ATTR_TYPE: &str = crate::attribute::Type::NAME;
|
||||
pub const ATTR_LOCATION: &str = crate::attribute::Location::NAME;
|
||||
pub const ATTR_DIMENSIONS: &str = crate::attribute::Dimensions::NAME;
|
||||
pub const ATTR_BACKGROUND: &str = crate::attribute::Background::NAME;
|
||||
pub const ATTR_CLIP: &str = crate::attribute::Clip::NAME;
|
||||
pub const ATTR_FONT_SIZE: &str = crate::attribute::FontSize::NAME;
|
||||
pub const ATTR_LINE_HEIGHT: &str = crate::attribute::LineHeight::NAME;
|
||||
pub const ATTR_LETTER_SPACING: &str = crate::attribute::LetterSpacing::NAME;
|
||||
pub const ATTR_MAX_WIDTH: &str = crate::attribute::MaxWidth::NAME;
|
||||
pub const ATTR_MAX_HEIGHT: &str = crate::attribute::MaxHeight::NAME;
|
||||
pub const ATTR_LETTER_TILT: &str = crate::attribute::LetterTilt::NAME;
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
pub const ATTR_TRANSFORM: &str = "transform";
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
pub const ATTR_BLEND_MODE: &str = "blend_mode";
|
||||
/// Item's opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Composed multiplicatively through nested groups. Affects content clipped to the item.
|
||||
pub const ATTR_OPACITY: &str = "opacity";
|
||||
/// Item's fill opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Like opacity but does not affect content clipped to the item.
|
||||
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
|
||||
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
|
||||
/// `NodeIdPath` path from the root network to the layer node owning this item.
|
||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
|
||||
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
|
||||
/// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for
|
||||
/// the original child layers after their content has been collapsed.
|
||||
pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers";
|
||||
/// Optional `Vector` that overrides the item's own geometry for click-target generation.
|
||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
||||
/// by clicking anywhere within their bounds, not just the filled letterform.
|
||||
pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
/// `DAffine2` mapping the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text'
|
||||
/// node's text frame in this item's local space. Each item carries the frame relative to its own
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_START: &str = "start";
|
||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_END: &str = "end";
|
||||
/// `String` for a regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
|
||||
pub const ATTR_NAME: &str = "name";
|
||||
/// `String` for a JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||
pub const ATTR_TYPE: &str = "type";
|
||||
/// Artboard's `DVec2` top-left corner in document coordinates.
|
||||
pub const ATTR_LOCATION: &str = "location";
|
||||
/// Artboard's `DVec2` width and height.
|
||||
pub const ATTR_DIMENSIONS: &str = "dimensions";
|
||||
/// Artboard's `Color` background fill.
|
||||
pub const ATTR_BACKGROUND: &str = "background";
|
||||
/// `bool` for whether an artboard clips content to its bounds.
|
||||
pub const ATTR_CLIP: &str = "clip";
|
||||
/// Gradient's `GradientSpreadMethod` (`Pad`, `Reflect`, or `Repeat`).
|
||||
pub const ATTR_SPREAD_METHOD: &str = "spread_method";
|
||||
/// Gradient's `GradientType` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_TYPE: &str = "gradient_type";
|
||||
/// Vector graphics object's filled area paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_FILL: &str = "fill";
|
||||
/// Vector graphics object's stroke paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_STROKE: &str = "stroke";
|
||||
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
|
||||
pub const ATTR_FONT_SIZE: &str = "font_size";
|
||||
/// Text item's font, as a `Resource` of the loaded font file.
|
||||
pub const ATTR_FONT: &str = "font";
|
||||
/// Text item's line height as a ratio of the font size (`f64`, implicit default `1.2`).
|
||||
pub const ATTR_LINE_HEIGHT: &str = "line_height";
|
||||
/// Text item's extra spacing between letters in document-space units (`f64`, implicit default `0.`).
|
||||
pub const ATTR_LETTER_SPACING: &str = "letter_spacing";
|
||||
/// Text item's maximum line-wrap width in document-space units (`Option<f64>`, implicit default `None`).
|
||||
pub const ATTR_MAX_WIDTH: &str = "max_width";
|
||||
/// Text item's maximum block height in document-space units, past which lines are not drawn (`Option<f64>`, implicit default `None`).
|
||||
pub const ATTR_MAX_HEIGHT: &str = "max_height";
|
||||
/// Text item's faux-italic letter tilt angle in degrees (`f64`, implicit default `0.`).
|
||||
pub const ATTR_LETTER_TILT: &str = "letter_tilt";
|
||||
/// Text item's `TextAlign` horizontal alignment of lines within the block.
|
||||
pub const ATTR_TEXT_ALIGN: &str = "text_align";
|
||||
|
||||
// =====================
|
||||
// TYPE: NodeIdPath
|
||||
// =====================
|
||||
|
||||
/// A single path of `NodeId`s locating a node (or its owning layer) within the nested document graph.
|
||||
/// Wraps a `List<NodeId>` so it flows as one rank-0 value (`Item<NodeIdPath>`) rather than a rank-1
|
||||
/// `List<NodeId>` that the element-wise machinery would wrongly zip over per ID.
|
||||
#[derive(Default, Debug, Clone, PartialEq, CacheHash, DynAny)]
|
||||
pub struct NodeIdPath(pub List<NodeId>);
|
||||
|
||||
impl From<Vec<NodeId>> for NodeIdPath {
|
||||
fn from(ids: Vec<NodeId>) -> Self {
|
||||
Self(ids.into_iter().map(Item::new_from_element).collect())
|
||||
}
|
||||
}
|
||||
|
||||
// ================
|
||||
// TYPE: Bundle
|
||||
// ================
|
||||
|
||||
/// A whole `List<T>` treated as one rank-0 value (`Item<Bundle<T>>`) rather than a rank-1 `List<T>`.
|
||||
/// Bundling a collection lets it pass through a connector that selects or carries the entire collection as one opaque
|
||||
/// cell (such as a Switch branch), instead of the element-wise machinery zipping over it per element.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Bundle<T>(pub List<T>);
|
||||
|
||||
impl<T> Default for Bundle<T> {
|
||||
fn default() -> Self {
|
||||
Self(List::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: CacheHash> CacheHash for Bundle<T> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<List<T>> for Bundle<T> {
|
||||
fn from(list: List<T>) -> Self {
|
||||
Self(list)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: StaticTypeSized> StaticType for Bundle<T> {
|
||||
type Static = Bundle<T::Static>;
|
||||
}
|
||||
|
||||
// ===========================
|
||||
// Implicit attribute defaults
|
||||
// ===========================
|
||||
|
||||
/// The census-declared default for `key`; a mismatched value type degrades
|
||||
/// to the column type's own default in `push_repeated`.
|
||||
/// Overrides the type's default value for certain attributes.
|
||||
fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||
crate::attribute::ATTRIBUTE_REGISTRY.lock().unwrap().get(key).map(|info| (info.default)())
|
||||
match key {
|
||||
ATTR_OPACITY | ATTR_OPACITY_FILL => Some(Box::new(1_f64)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
|
||||
@@ -81,6 +174,13 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
|
||||
/// Returns a debug-formatted string representation of this value.
|
||||
fn display_string(&self) -> String;
|
||||
|
||||
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
|
||||
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher);
|
||||
|
||||
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
|
||||
/// Returns `false` if the underlying types differ.
|
||||
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool;
|
||||
|
||||
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
|
||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
||||
}
|
||||
@@ -111,6 +211,17 @@ impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash +
|
||||
format!("{:?}", self)
|
||||
}
|
||||
|
||||
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
|
||||
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher) {
|
||||
self.cache_hash(&mut DynHasher(state));
|
||||
}
|
||||
|
||||
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
|
||||
/// Returns `false` if the underlying types differ.
|
||||
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool {
|
||||
other.as_any().downcast_ref::<Self>().is_some_and(|other| self == other)
|
||||
}
|
||||
|
||||
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
|
||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute> {
|
||||
let mut attribute: Box<dyn AnyAttribute> = Box::new(Attribute::<T>(Vec::with_capacity(preceding_defaults + 1)));
|
||||
@@ -317,83 +428,12 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
|
||||
}
|
||||
}
|
||||
|
||||
// ============
|
||||
// AttributeDyn
|
||||
// ============
|
||||
|
||||
/// Type-erased list of attribute values, used as a node graph parameter type.
|
||||
/// Lets a node accept any `List<U>` source via the auto-inserted `Convert<AttributeDyn, ()>`
|
||||
/// without monomorphizing over `U` (so the cartesian product of `(content T, source U)` collapses to just `T`).
|
||||
pub struct AttributeDyn(pub Box<dyn AnyAttribute>);
|
||||
|
||||
impl AttributeDyn {
|
||||
/// Number of values in this attribute.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
/// Whether this attribute has zero values.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.len() == 0
|
||||
}
|
||||
|
||||
/// Builds a new attribute matching `target_len` items, taking values from this attribute (wrapping if shorter, truncating if longer).
|
||||
pub fn cloned_to_length(&self, key: &str, target_len: usize) -> Box<dyn AnyAttribute> {
|
||||
let mut result = self.0.new_with_defaults(0);
|
||||
let source_len = self.0.len();
|
||||
if source_len == 0 {
|
||||
pad_with_implicit_default(key, &mut result, target_len);
|
||||
return result;
|
||||
}
|
||||
for i in 0..target_len {
|
||||
let value = self.0.clone_value(i % source_len).expect("source_len > 0");
|
||||
result.push(value);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for AttributeDyn {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone_box())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AttributeDyn {
|
||||
fn default() -> Self {
|
||||
Self(Box::new(Attribute::<bool>(Vec::new())))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for AttributeDyn {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "AttributeDyn(len: {})", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AttributeDyn {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.eq_dyn(&*other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheHash for AttributeDyn {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.cache_hash_dyn(state);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for AttributeDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
|
||||
// ==================
|
||||
// AttributeValueDyn
|
||||
// ==================
|
||||
|
||||
/// Type-erased single attribute value, used as a node graph parameter type.
|
||||
/// Lets a node accept a value of any concrete type via the auto-inserted `Convert<AttributeValueDyn, ()>`
|
||||
/// without monomorphizing over the value type.
|
||||
/// Lets a node accept a value of any valid concrete type via the auto-inserted input adapter conversion without monomorphizing over the value type.
|
||||
pub struct AttributeValueDyn(pub Box<dyn AnyAttributeValue>);
|
||||
|
||||
impl Clone for AttributeValueDyn {
|
||||
@@ -532,6 +572,17 @@ impl Debug for ItemAttributeValues {
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ItemAttributeValues {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.len() == other.0.len()
|
||||
&& self
|
||||
.0
|
||||
.iter()
|
||||
.zip(&other.0)
|
||||
.all(|((self_key, self_value), (other_key, other_value))| self_key == other_key && self_value.eq_dyn(other_value.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemAttributeValues {
|
||||
/// Creates an empty set of attributes.
|
||||
pub fn new() -> Self {
|
||||
@@ -602,9 +653,9 @@ impl ItemAttributeValues {
|
||||
self.0.iter().map(|(key, _)| key.as_str())
|
||||
}
|
||||
|
||||
/// Returns an iterator over the stored (key, value) pairs, in insertion order.
|
||||
pub fn iter(&self) -> impl Iterator<Item = (&str, &dyn AnyAttributeValue)> {
|
||||
self.0.iter().map(|(key, value)| (key.as_str(), &**value))
|
||||
/// Returns a type-erased reference to the value of the attribute with the given key, if it exists.
|
||||
pub fn get_any(&self, key: &str) -> Option<&dyn std::any::Any> {
|
||||
self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None })
|
||||
}
|
||||
|
||||
/// Returns a debug-formatted string representation of the attribute value for the given key, if it exists.
|
||||
@@ -742,11 +793,6 @@ impl Attributes {
|
||||
.find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<T>() } else { None })
|
||||
}
|
||||
|
||||
/// The whole column for the given key, resolved once for repeated lane reads.
|
||||
fn column(&self, key: &str) -> Option<&dyn AnyAttribute> {
|
||||
self.attributes.iter().find_map(|(k, attribute)| (k == key).then_some(&**attribute))
|
||||
}
|
||||
|
||||
/// Removes the entire attribute for the given key, if present.
|
||||
fn remove_attribute(&mut self, key: &str) {
|
||||
if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) {
|
||||
@@ -1031,14 +1077,6 @@ impl<T> List<T> {
|
||||
self.attributes.set_value(key, index, value);
|
||||
}
|
||||
|
||||
/// Replaces (or adds) an attribute from a type-erased source. The source is wrapped or truncated to match this list's item count.
|
||||
pub fn set_attribute_dyn(&mut self, key: impl Into<String>, source: AttributeDyn) {
|
||||
let key = key.into();
|
||||
self.attributes.attributes.retain(|(k, _)| k != &key);
|
||||
let new_attribute = source.cloned_to_length(&key, self.element.len());
|
||||
self.attributes.attributes.push((key, new_attribute));
|
||||
}
|
||||
|
||||
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
|
||||
/// Falls back to default if the value's type doesn't match an existing attribute.
|
||||
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
|
||||
@@ -1109,12 +1147,48 @@ impl<T> List<T> {
|
||||
}
|
||||
|
||||
impl<T: BoundingBox> BoundingBox for List<T> {
|
||||
/// Computes the combined bounding box of all items, composing each item's transform attribute with the given transform.
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
crate::bounds::lane_bounding_box(self, transform, include_stroke)
|
||||
let mut combined_bounds = None;
|
||||
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
||||
match element.bounding_box(transform * item_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
|
||||
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
||||
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
|
||||
None => combined_bounds = Some(bounds),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
match combined_bounds {
|
||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||
None => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
crate::bounds::lane_thumbnail_bounding_box(self, transform, include_stroke)
|
||||
// `Infinite` items are skipped here (rather than propagating outward as in `bounding_box`) so a finite sibling in a mixed group dictates the framing
|
||||
let mut combined_bounds = None;
|
||||
let mut any_infinite = false;
|
||||
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
||||
match element.thumbnail_bounding_box(transform * item_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => any_infinite = true,
|
||||
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
||||
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
|
||||
None => combined_bounds = Some(bounds),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
match (combined_bounds, any_infinite) {
|
||||
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||
(None, true) => RenderBoundingBox::Infinite,
|
||||
(None, false) => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1141,41 +1215,6 @@ impl<T> Default for List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A marker's column on a [`List`], absent when the list carries no such key.
|
||||
pub struct ListColumn<'a, A: crate::attribute::Attribute> {
|
||||
stored: Option<&'a dyn AnyAttribute>,
|
||||
marker: std::marker::PhantomData<A>,
|
||||
}
|
||||
|
||||
impl<'a, A: crate::attribute::Attribute> crate::lane::LaneColumn<'a, A> for ListColumn<'a, A> {
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||
self.stored.and_then(|column| column.get_any(lane)).and_then(A::from_stored)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> crate::lane::LaneSource for List<T> {
|
||||
type Element = T;
|
||||
type Column<'a, A: crate::attribute::Attribute>
|
||||
= ListColumn<'a, A>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
List::len(self)
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&T> {
|
||||
List::element(self, lane)
|
||||
}
|
||||
|
||||
fn column<A: crate::attribute::Attribute>(&self) -> ListColumn<'_, A> {
|
||||
ListColumn {
|
||||
stored: self.attributes.column(A::NAME),
|
||||
marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: CacheHash> CacheHash for List<T> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.element.cache_hash(state);
|
||||
@@ -1245,7 +1284,7 @@ impl<T> FromIterator<Item<T>> for List<T> {
|
||||
/// An owned item containing an element of type `T` and a set of type-erased scalar attributes.
|
||||
///
|
||||
/// Used to build individual items before pushing them into a [`List`], or when consuming items out of a list via [`IntoIterator`].
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Item<T> {
|
||||
element: T,
|
||||
attributes: ItemAttributeValues,
|
||||
@@ -1257,9 +1296,15 @@ impl<T: Default> Default for Item<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for Item<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.element == other.element
|
||||
impl<T: CacheHash> CacheHash for Item<T> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.element.cache_hash(state);
|
||||
|
||||
// Hash every attribute (key + value) so attribute changes invalidate downstream caches, mirroring `List`
|
||||
for (key, attribute) in &self.attributes.0 {
|
||||
std::hash::Hash::hash(key.as_str(), state);
|
||||
attribute.cache_hash_dyn(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1351,6 +1396,42 @@ impl<T> Item<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for Item<T> {
|
||||
fn from(element: T) -> Self {
|
||||
Self::new_from_element(element)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Item<T>> for List<T> {
|
||||
fn from(item: Item<T>) -> Self {
|
||||
Self::new_from_item(item)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for List<T> {
|
||||
fn from(element: T) -> Self {
|
||||
Self::new_from_element(element)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ApplyTransform for Item<T> {
|
||||
/// Right-multiplies the modification into the item's transform attribute.
|
||||
fn apply_transform(&mut self, modification: &DAffine2) {
|
||||
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
*transform *= *modification;
|
||||
}
|
||||
|
||||
/// Left-multiplies the modification into the item's transform attribute.
|
||||
fn left_apply_transform(&mut self, modification: &DAffine2) {
|
||||
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
*transform = *modification * *transform;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: StaticTypeSized> StaticType for Item<T> {
|
||||
type Static = Item<T::Static>;
|
||||
}
|
||||
|
||||
// ===========
|
||||
// ItemIter<T>
|
||||
// ===========
|
||||
|
||||
@@ -61,6 +61,27 @@ impl Clampable for DVec2 {
|
||||
}
|
||||
}
|
||||
|
||||
// Implement for ranked wires (element-wise clamping across the frame)
|
||||
use crate::list::{Item, List};
|
||||
impl<T: Clampable> Clampable for Item<T> {
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
let (element, attributes) = self.into_parts();
|
||||
Item::from_parts(element.clamp_hard_min(min), attributes)
|
||||
}
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
let (element, attributes) = self.into_parts();
|
||||
Item::from_parts(element.clamp_hard_max(max), attributes)
|
||||
}
|
||||
}
|
||||
impl<T: Clampable> Clampable for List<T> {
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
self.into_iter().map(|item| item.clamp_hard_min(min)).collect()
|
||||
}
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
self.into_iter().map(|item| item.clamp_hard_max(max)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[derive(serde::Deserialize)]
|
||||
struct LegacyTable<T> {
|
||||
@@ -69,7 +90,7 @@ struct LegacyTable<T> {
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
pub fn migrate_to_optional_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<no_std_types::color::Color>, D::Error> {
|
||||
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<no_std_types::color::Color, D::Error> {
|
||||
use no_std_types::color::Color;
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -81,8 +102,8 @@ pub fn migrate_to_optional_color<'de, D: serde::Deserializer<'de>>(deserializer:
|
||||
}
|
||||
|
||||
Ok(match ColorFormat::deserialize(deserializer)? {
|
||||
ColorFormat::OptionalColor(color) => color,
|
||||
ColorFormat::List(list) => list.element.into_iter().next(),
|
||||
ColorFormat::OptionalColor(color) => color.unwrap_or(Color::TRANSPARENT),
|
||||
ColorFormat::List(list) => list.element.into_iter().next().unwrap_or(Color::TRANSPARENT),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,698 +0,0 @@
|
||||
use crate::context::InjectIndex;
|
||||
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt, Level};
|
||||
use std::cell::Cell;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::{Deref, Range};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum BatchStatus<'a> {
|
||||
/// Producer-resident lanes, shared: read-only for the caller. The extent
|
||||
/// is the producer's knowledge of the level's total after serving the
|
||||
/// range: a sound lower bound, or exact; a batch shorter than the
|
||||
/// requested range carries `Exactly` and marks the end of the data.
|
||||
Lent(RecordBatch<'a>, Finality, Extent),
|
||||
/// The caller's scratch, filled: the caller is the exclusive owner and may
|
||||
/// mutate the lanes or reclaim the buffer for in-place reuse. The extent
|
||||
/// hint is as for `Lent`.
|
||||
Filled(RecordBatchMut<'a>, Finality, Extent),
|
||||
/// No batch implementation behind this edge; a driver answers with the
|
||||
/// per-lane serve and copy-out loop ([`crate::record::fill_frames`]).
|
||||
Unbatched,
|
||||
Pending,
|
||||
Error(GraphError),
|
||||
NeedBuffer,
|
||||
InvalidRange,
|
||||
}
|
||||
|
||||
impl From<Interrupt> for BatchStatus<'_> {
|
||||
fn from(interrupt: Interrupt) -> Self {
|
||||
match interrupt {
|
||||
Interrupt::Pending => BatchStatus::Pending,
|
||||
Interrupt::Error(error) => BatchStatus::Error(*error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared view over a batch of records in one flat frame buffer: lane `i`
|
||||
/// starts at `frames + i * stride` with `stride = layout.lane_stride()`.
|
||||
/// Frame bytes carry no drop glue (droppable elements ride parked,
|
||||
/// arena-owned), so the view has no drop obligation; `'a` covers the frames
|
||||
/// and the layout.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RecordBatch<'a> {
|
||||
frames: *const u8,
|
||||
stride: usize,
|
||||
len: usize,
|
||||
layout: &'a crate::record::Layout,
|
||||
_lifetime: PhantomData<&'a [u8]>,
|
||||
}
|
||||
|
||||
impl<'a> RecordBatch<'a> {
|
||||
/// # Safety
|
||||
/// `frames` must hold `len` initialized records of `layout`, packed at
|
||||
/// `layout.lane_stride()` stride and valid for `'a`.
|
||||
pub unsafe fn new(frames: *const u8, len: usize, layout: &'a crate::record::Layout) -> Self {
|
||||
Self {
|
||||
frames,
|
||||
stride: layout.lane_stride(),
|
||||
len,
|
||||
layout,
|
||||
_lifetime: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
pub(crate) fn frames_ptr(&self) -> *const u8 {
|
||||
self.frames
|
||||
}
|
||||
|
||||
pub fn get(&self, lane: usize) -> RecordLane<'a> {
|
||||
assert!(lane < self.len, "lane {lane} out of bounds for a batch of {}", self.len);
|
||||
RecordLane {
|
||||
// SAFETY: in-bounds by the assert against the constructor's contract.
|
||||
rec: unsafe { crate::record::Rec::new(self.frames.add(lane * self.stride)) },
|
||||
layout: self.layout,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'a>)) {
|
||||
for lane in 0..self.len {
|
||||
f(lane, self.get(lane));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The exclusive view over caller-owned frames (the `Filled` status): while it
|
||||
/// lives, the borrow of the caller's scratch guarantees nobody else can read
|
||||
/// the lanes, so mutating them or reclaiming the buffer is sound.
|
||||
#[derive(Debug)]
|
||||
pub struct RecordBatchMut<'a> {
|
||||
scratch: &'a mut [MaybeUninit<u64>],
|
||||
len: usize,
|
||||
layout: &'a crate::record::Layout,
|
||||
}
|
||||
|
||||
impl<'a> RecordBatchMut<'a> {
|
||||
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
|
||||
/// which is what makes the initialized prefix a fact rather than a contract.
|
||||
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
|
||||
debug_assert!(len * layout.lane_stride() <= scratch.len() * 8);
|
||||
Self { scratch, len, layout }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// Reads the lanes without giving up exclusivity.
|
||||
pub fn share(&self) -> RecordBatch<'_> {
|
||||
// SAFETY: the constructor's contract, narrowed to the reborrow's scope.
|
||||
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
|
||||
}
|
||||
|
||||
/// Gives up exclusivity for the batch's whole lifetime.
|
||||
pub fn into_shared(self) -> RecordBatch<'a> {
|
||||
// SAFETY: the constructor's contract; the exclusive borrow is consumed.
|
||||
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
|
||||
}
|
||||
|
||||
/// Lane `lane`'s frame for in-place writes through the layout's offsets.
|
||||
pub fn lane_ptr(&mut self, lane: usize) -> *mut u8 {
|
||||
assert!(lane < self.len, "lane {lane} out of bounds for a batch of {}", self.len);
|
||||
// SAFETY: in-bounds by the assert against the constructor's contract.
|
||||
unsafe { self.scratch.as_mut_ptr().cast::<u8>().add(lane * self.layout.lane_stride()) }
|
||||
}
|
||||
|
||||
/// Reclaims the raw buffer, e.g. to rebind it under a same-stride output
|
||||
/// layout for an in-place map.
|
||||
pub fn into_scratch(self) -> &'a mut [MaybeUninit<u64>] {
|
||||
self.scratch
|
||||
}
|
||||
}
|
||||
|
||||
/// One lane's record: its pointer paired with the batch's layout.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RecordLane<'a> {
|
||||
rec: crate::record::Rec<'a>,
|
||||
layout: &'a crate::record::Layout,
|
||||
}
|
||||
|
||||
impl<'a> RecordLane<'a> {
|
||||
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
pub fn rec(&self) -> crate::record::Rec<'a> {
|
||||
self.rec
|
||||
}
|
||||
|
||||
/// The element at offset 0.
|
||||
///
|
||||
/// # Safety
|
||||
/// `U` must be the record's element type, proven at the consumer's wiring.
|
||||
pub unsafe fn element<U: Copy>(&self) -> U {
|
||||
unsafe { self.rec.element::<U>() }
|
||||
}
|
||||
|
||||
/// Attribute `A` through a token, `None` where the token was minted against
|
||||
/// another layout than this lane's.
|
||||
pub fn try_attr_at<A: crate::attribute::Attribute>(&self, field: crate::record::FieldOffset<A>) -> Option<A::Value<'a>> {
|
||||
let offset = field.resolve(self.layout)?;
|
||||
// SAFETY: resolving against this lane's own layout pins the offset and
|
||||
// the field's value type, and the batch's contract makes the lane a live
|
||||
// record of that layout.
|
||||
Some(unsafe { self.rec.read::<A::Value<'a>>(offset) })
|
||||
}
|
||||
|
||||
/// Attribute `A` through a token, or its census default where the token is
|
||||
/// absent or names another layout.
|
||||
pub fn attr_at<A: crate::attribute::Attribute>(&self, field: Option<crate::record::FieldOffset<A>>) -> A::Value<'a> {
|
||||
field.and_then(|field| self.try_attr_at(field)).unwrap_or_else(A::default)
|
||||
}
|
||||
|
||||
/// Attribute `A` at the record's top level, or its census default when the
|
||||
/// layout does not carry it. Mints a token per call; lane loops hoist the
|
||||
/// mint instead.
|
||||
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'a> {
|
||||
self.attr_at(crate::record::FieldOffset::<A>::of(self.layout, 0))
|
||||
}
|
||||
}
|
||||
|
||||
/// One lane of a materialized level, element-typed. In a kernel's element
|
||||
/// position the output frame is copied from this lane.
|
||||
#[derive(Debug)]
|
||||
pub struct Lane<'a, T> {
|
||||
lane: RecordLane<'a>,
|
||||
_element: PhantomData<T>,
|
||||
}
|
||||
|
||||
// A view regardless of `T`: copying a lane copies no record.
|
||||
impl<T> Clone for Lane<'_, T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Copy for Lane<'_, T> {}
|
||||
|
||||
impl<'a, T> Deref for Lane<'a, T> {
|
||||
type Target = RecordLane<'a>;
|
||||
|
||||
fn deref(&self) -> &RecordLane<'a> {
|
||||
&self.lane
|
||||
}
|
||||
}
|
||||
|
||||
/// A materialized nesting level handed to a folding kernel: a thin element-typed
|
||||
/// view over the [`RecordBatch`] the level was collected into. The eventual
|
||||
/// `List` once `IList` is renamed.
|
||||
#[derive(Debug)]
|
||||
pub struct List<'a, T> {
|
||||
batch: RecordBatch<'a>,
|
||||
_element: PhantomData<T>,
|
||||
}
|
||||
|
||||
// A shared view regardless of `T`: copying the list copies no elements.
|
||||
impl<T> Clone for List<'_, T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Copy for List<'_, T> {}
|
||||
|
||||
impl<'a, T> List<'a, T> {
|
||||
/// # Safety
|
||||
/// `T` must be the batch's record element type, proven at the consumer's
|
||||
/// wiring, and the batch's frames must stay valid for the evaluation:
|
||||
/// arena-resident batches qualify, caller stack scratch does not.
|
||||
pub unsafe fn new(batch: RecordBatch<'a>) -> Self {
|
||||
Self { batch, _element: PhantomData }
|
||||
}
|
||||
|
||||
/// The level as a group item over the same frames, without copying.
|
||||
/// Panics where a parked element or field lacks content glue.
|
||||
pub fn as_group_item(&self) -> crate::record::GroupItem<'a> {
|
||||
// SAFETY: `List::new` established the frames stay valid for the
|
||||
// evaluation.
|
||||
unsafe { crate::record::GroupItem::from_resident(self.batch) }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.batch.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.batch.is_empty()
|
||||
}
|
||||
|
||||
pub fn batch(&self) -> RecordBatch<'a> {
|
||||
self.batch
|
||||
}
|
||||
|
||||
pub fn get(&self, index: usize) -> T
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
// SAFETY: `List::new` established that `T` is the batch's element type.
|
||||
unsafe { self.batch.get(index).element::<T>() }
|
||||
}
|
||||
|
||||
/// Borrows lane `index`'s element, through the park for droppable types.
|
||||
pub fn element_ref(&self, index: usize) -> &T {
|
||||
// SAFETY: `List::new` established that `T` is the batch's element type,
|
||||
// and the borrow lives within the batch's own lifetime.
|
||||
unsafe { crate::record::borrow_element::<T>(self.batch.get(index).rec()) }
|
||||
}
|
||||
|
||||
/// Lane `index`'s record, for attribute reads beside the element.
|
||||
pub fn lane(&self, index: usize) -> Lane<'a, T> {
|
||||
Lane {
|
||||
lane: self.batch.get(index),
|
||||
_element: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = T> + '_
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
(0..self.len()).map(move |index| self.get(index))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Copy> IntoIterator for List<'a, T> {
|
||||
type Item = T;
|
||||
type IntoIter = ListIter<'a, T>;
|
||||
|
||||
fn into_iter(self) -> ListIter<'a, T> {
|
||||
ListIter { list: self, position: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ListIter<'a, T> {
|
||||
list: List<'a, T>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl<T: Copy> Iterator for ListIter<'_, T> {
|
||||
type Item = T;
|
||||
|
||||
fn next(&mut self) -> Option<T> {
|
||||
(self.position < self.list.len()).then(|| {
|
||||
let value = self.list.get(self.position);
|
||||
self.position += 1;
|
||||
value
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Node<Input> {
|
||||
/// Serves the node's record through the caller's claim: the writes land
|
||||
/// in the claim and the returned proof is mintable only by its closing
|
||||
/// methods, so the served record is of the claimed layout by
|
||||
/// construction. The caller claims the frame at [`Node::layout`] out of
|
||||
/// its own frame space, and the claim carries what is left, so the node
|
||||
/// takes exactly its own frame out of the caller's free space.
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>;
|
||||
|
||||
/// The count of items at one absolute nesting level (innermost `0`). The
|
||||
/// leveled primitive a structure node overrides to report a pushed level's
|
||||
/// size; the scalar base is one item at every level. Uncertainty rides the
|
||||
/// `GPoll` status axis.
|
||||
fn extent_at<'e>(&self, _input: &Input, _level: u8, _frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
GPoll::Final(Extent::Exactly(1))
|
||||
}
|
||||
|
||||
/// The composite domain query derived from [`extent_at`](Node::extent_at):
|
||||
/// one level, the product of the levels below or above it, or the whole
|
||||
/// domain's flat count. Consumers query this; nodes only write `extent_at`.
|
||||
fn extent<'e>(&self, input: &Input, at: Level, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
let product =
|
||||
|range: core::ops::Range<u8>, frames: &crate::record::Frames<'e>| range.fold(GPoll::Final(Extent::Exactly(1)), |acc, level| Extent::mul(acc, self.extent_at(input, level, frames)));
|
||||
match at {
|
||||
Level::At(level) => self.extent_at(input, level, frames),
|
||||
Level::Below(level) => product(0..level, frames),
|
||||
Level::Above(level) => product((level + 1)..self.depth(), frames),
|
||||
Level::Total => product(0..self.depth(), frames),
|
||||
}
|
||||
}
|
||||
|
||||
/// The node's domain depth (number of nesting levels; `0` = scalar), baked
|
||||
/// into the record layout at wiring.
|
||||
fn depth(&self) -> u8 {
|
||||
self.layout().depth
|
||||
}
|
||||
|
||||
/// Introspection access to node-resident records; `None` for ordinary nodes.
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The record layout of this node's output; the shared empty layout for
|
||||
/// element-only producers. Consumers read their carrier's layout through
|
||||
/// this at wiring, and the wiring layer derives the root buffer's sizing from
|
||||
/// the same layouts, in the dynamic executor and exported source alike.
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
crate::record::empty_layout()
|
||||
}
|
||||
|
||||
/// Installs this node's resolved record layout; a no-op unless it produces records.
|
||||
fn set_layout(&mut self, _layout: crate::record::RecordLayout) {}
|
||||
|
||||
/// Batched evaluation of `range` into caller-provided frame storage of
|
||||
/// `range.len() * layout.lane_stride()` bytes; see [`BatchStatus`]. The
|
||||
/// default advertises no support and drivers fall back to per-lane serves
|
||||
/// with copy-out ([`crate::record::fill_frames`]); overrides exist to beat
|
||||
/// that loop (resident lanes, direct fills, fewer erased calls), never for
|
||||
/// correctness.
|
||||
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||
where
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
let _ = (input, range, scratch, frames);
|
||||
BatchStatus::Unbatched
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for &N
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).serve(input, slot)
|
||||
}
|
||||
|
||||
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).extent_at(input, level, frames)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||
where
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for Box<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).serve(input, slot)
|
||||
}
|
||||
|
||||
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).extent_at(input, level, frames)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||
where
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for std::sync::Arc<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).serve(input, slot)
|
||||
}
|
||||
|
||||
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).extent_at(input, level, frames)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||
where
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StatusCell {
|
||||
finality: Cell<Finality>,
|
||||
error: Cell<Option<GraphError>>,
|
||||
no_partial: bool,
|
||||
}
|
||||
|
||||
impl Default for StatusCell {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl StatusCell {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
finality: Cell::new(Finality::AllFinal),
|
||||
error: Cell::new(None),
|
||||
no_partial: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn no_partial() -> Self {
|
||||
Self { no_partial: true, ..Self::new() }
|
||||
}
|
||||
|
||||
/// Claims the edge's own frame out of `frames`, serves through it, and
|
||||
/// folds the poll's status into the cell. The claim is the caller's, so
|
||||
/// the edge's frame is claimed exactly once per evaluation.
|
||||
#[inline(always)]
|
||||
pub fn eval_input<'e, Input, N: Node<Input> + ?Sized>(&self, input_index: usize, node: &N, input: &Input, frames: &crate::record::Frames<'e>) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
let slot = frames.claim(node.layout());
|
||||
match node.serve(input, slot) {
|
||||
GPoll::Final(served) => Ok(served.value()),
|
||||
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
|
||||
GPoll::Partial(served) => {
|
||||
self.finality.set(Finality::Partial);
|
||||
Ok(served.value())
|
||||
}
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (served, error) = *boxed;
|
||||
let first = self.error.take();
|
||||
self.error.set(first.or(Some(error.traced(input_index))));
|
||||
Ok(served.value())
|
||||
}
|
||||
GPoll::Pending => Err(Interrupt::Pending),
|
||||
GPoll::Error(mut error) => {
|
||||
error.trace.push(input_index);
|
||||
Err(Interrupt::Error(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A new cell holding a copy of the accumulated status; the error stays in
|
||||
/// place, cloned rather than taken.
|
||||
#[inline(always)]
|
||||
pub fn snapshot(&self) -> StatusCell {
|
||||
let error = self.error.take();
|
||||
self.error.set(error.clone());
|
||||
StatusCell {
|
||||
finality: Cell::new(self.finality.get()),
|
||||
error: Cell::new(error),
|
||||
no_partial: self.no_partial,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn finish<T>(self, value: T) -> GPoll<T> {
|
||||
match (self.error.take(), self.finality.get()) {
|
||||
(Some(error), _) => GPoll::Fallback(Box::new((value, error))),
|
||||
(None, Finality::AllFinal) => GPoll::Final(value),
|
||||
(None, Finality::Partial) => GPoll::Partial(value),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
|
||||
match poll {
|
||||
GPoll::Final(value) => self.finish(value),
|
||||
GPoll::Partial(_) if self.no_partial => GPoll::Pending,
|
||||
GPoll::Partial(value) => match self.finish(value) {
|
||||
GPoll::Final(value) => GPoll::Partial(value),
|
||||
other => other,
|
||||
},
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
let first = self.error.take().unwrap_or(error);
|
||||
GPoll::Fallback(Box::new((value, first)))
|
||||
}
|
||||
interrupted => interrupted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct LazyInput<'a, 'f, N> {
|
||||
node: &'a N,
|
||||
cell: &'a StatusCell,
|
||||
input_index: usize,
|
||||
frames: &'a crate::record::Frames<'f>,
|
||||
}
|
||||
|
||||
impl<'a, 'f, N> LazyInput<'a, 'f, N> {
|
||||
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize, frames: &'a crate::record::Frames<'f>) -> Self {
|
||||
Self { node, cell, input_index, frames }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn eval<'e, Input>(&self, ctx: &Input) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||
where
|
||||
N: crate::record::DerivedRecordEdge<'e, Input>,
|
||||
'f: 'e,
|
||||
{
|
||||
self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)
|
||||
}
|
||||
|
||||
/// The edge's composite extent, for kernels that split or shift indices
|
||||
/// over their sources.
|
||||
#[inline(always)]
|
||||
pub fn extent<'e, Input>(&self, ctx: &Input, at: Level) -> GPoll<Extent>
|
||||
where
|
||||
N: Node<Input>,
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
'f: 'e,
|
||||
{
|
||||
self.node.extent(ctx, at, self.frames)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::arena::Arena;
|
||||
use crate::context::ExtractArena;
|
||||
use crate::record::{LiftedSource, serve_edge};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TestInput<'a> {
|
||||
index: u64,
|
||||
arena: &'a Arena,
|
||||
}
|
||||
|
||||
impl InjectIndex for TestInput<'_> {
|
||||
fn set_index(&mut self, index: u64) {
|
||||
self.index = index;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ExtractArena for TestInput<'a> {
|
||||
type ArenaRef = &'a Arena;
|
||||
|
||||
fn arena(&self) -> &'a Arena {
|
||||
self.arena
|
||||
}
|
||||
}
|
||||
|
||||
fn double<'a>() -> LiftedSource<u64, impl Fn(&TestInput<'a>) -> GPoll<u64>> {
|
||||
LiftedSource::new(|input: &TestInput<'a>| GPoll::Final(input.index * 2))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_advertises_no_batch_support() {
|
||||
let frames = crate::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let input = TestInput { index: 0, arena: &arena };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let node = double();
|
||||
assert!(matches!(node.eval_batch(&input, 2..6, Some(&mut scratch), &frames), BatchStatus::Unbatched));
|
||||
assert!(matches!(node.eval_batch(&input, 2..6, None, &frames), BatchStatus::Unbatched));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trait_is_object_safe_across_erased_edges() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let input = TestInput { index: 21, arena: &arena };
|
||||
let node = double();
|
||||
let layout = Node::<TestInput>::layout(&node).clone();
|
||||
let erased: Box<dyn Node<TestInput>> = Box::new(node);
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
let GPoll::Final(value) = serve_edge(&*erased, &input, &frames) else {
|
||||
panic!("the erased edge must serve a final record");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the output.
|
||||
assert_eq!(unsafe { crate::record::read_element::<u64>(layout.rec(&value)) }, 42);
|
||||
assert!(matches!(erased.eval_batch(&input, 0..2, None, &frames), BatchStatus::Unbatched));
|
||||
}
|
||||
}
|
||||
@@ -1,100 +1,69 @@
|
||||
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||
use crate::Node;
|
||||
use crate::transform::Footprint;
|
||||
use glam::DVec2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// Type
|
||||
// TODO: Document this
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||
pub struct TypeNode<N: for<'a> Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>);
|
||||
impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode<N, I, O>
|
||||
where
|
||||
N: for<'n> Node<'n, I, Output = O>,
|
||||
{
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> Self::Output {
|
||||
self.0.eval(input)
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.0.reset();
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.0.serialize()
|
||||
}
|
||||
}
|
||||
impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode<N, I, <N as Node<'i, I>>::Output> {
|
||||
pub fn new(node: N) -> Self {
|
||||
Self(node, PhantomData)
|
||||
}
|
||||
}
|
||||
impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode<N, I, <N as Node<'i, I>>::Output> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1)
|
||||
}
|
||||
}
|
||||
impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Node<'i, I>>::Output> {}
|
||||
|
||||
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
|
||||
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
|
||||
pub trait Convert<T, C>: Sized {
|
||||
/// Converts this type into the (usually inferred) output type.
|
||||
#[must_use]
|
||||
fn convert(self, footprint: Footprint, converter: C) -> T;
|
||||
}
|
||||
|
||||
/// The asynchronous counterpart of [`Convert`]; a conversion pair implements exactly one of the two traits.
|
||||
pub trait ConvertAsync<T, C>: Sized {
|
||||
#[must_use]
|
||||
fn convert(self, footprint: Footprint, converter: C) -> crate::runtime::SourceFuture<T>;
|
||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
||||
}
|
||||
|
||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
/// Converts this type into a `String` using its `ToString` implementation.
|
||||
#[inline]
|
||||
fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ListConvert<U> {
|
||||
fn convert_item(self) -> U;
|
||||
}
|
||||
|
||||
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||
let list: List<U> = self
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let (element, attributes) = row.into_parts();
|
||||
Item::from_parts(element.convert_item(), attributes)
|
||||
})
|
||||
.collect();
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
|
||||
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
|
||||
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
|
||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
||||
AttributeDyn(Box::new(Attribute(values)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
|
||||
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
|
||||
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
|
||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
AttributeValueDyn(Box::new(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases a `List<T>`'s element type, exposing only its attributes and row count. Lets nodes that
|
||||
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
|
||||
/// instead of monomorphizing over every possible carrier list type.
|
||||
impl<T: Send> Convert<ListDyn, ()> for List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Convert<DVec2, ()> for DVec2 {
|
||||
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs `Self` from a single anchor point at the given position. Implemented by the vector crate's
|
||||
/// path type so the `Convert` impl below can build a single-point path without core-types depending on
|
||||
/// that crate (mirroring how [`ListConvert`] bridges per-item list conversions).
|
||||
/// path type so a position wire can convert to a single-point path without core-types depending on that crate.
|
||||
pub trait FromAnchorPosition {
|
||||
fn from_anchor_position(position: DVec2) -> Self;
|
||||
}
|
||||
|
||||
// Converts a position into a vector path composed of a single anchor point
|
||||
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
||||
fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
|
||||
macro_rules! impl_convert {
|
||||
($from:ty, $to:ty) => {
|
||||
impl Convert<$to, ()> for $from {
|
||||
fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self as $to
|
||||
}
|
||||
}
|
||||
@@ -116,7 +85,7 @@ macro_rules! impl_convert {
|
||||
impl_convert!(usize, $to);
|
||||
|
||||
impl Convert<DVec2, ()> for $to {
|
||||
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
DVec2::splat(self as f64)
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,10 @@
|
||||
use crate::concrete;
|
||||
use crate::context::{Context, ContextImpl};
|
||||
use crate::node::Node;
|
||||
use crate::{ContextFeature, ProtoNodeIdentifier, Type, WasmNotSend, WasmNotSync};
|
||||
use dyn_any::DynAny;
|
||||
use graphene_hash::CacheHash;
|
||||
use crate::{ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend};
|
||||
use dyn_any::{DynAny, StaticType};
|
||||
pub use no_std_types::registry::types;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hasher;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
// Translation struct between macro and definition
|
||||
@@ -20,8 +18,6 @@ pub struct NodeMetadata {
|
||||
pub context_features: Vec<ContextFeature>,
|
||||
pub memoize: bool,
|
||||
pub inject_scope: bool,
|
||||
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
|
||||
pub async_source_fields: bool,
|
||||
}
|
||||
|
||||
// Translation struct between macro and definition
|
||||
@@ -29,8 +25,6 @@ pub struct NodeMetadata {
|
||||
pub struct FieldMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
/// Index levels the node pushes when evaluating this input.
|
||||
pub pushed_levels: u8,
|
||||
pub hidden: bool,
|
||||
pub exposed: bool,
|
||||
pub widget_override: RegistryWidgetOverride,
|
||||
@@ -61,548 +55,239 @@ pub enum RegistryValueSource {
|
||||
None,
|
||||
Default(&'static str),
|
||||
Scope(&'static str),
|
||||
SourceId,
|
||||
}
|
||||
|
||||
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>>;
|
||||
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<(NodeConstructor, NodeIOTypes)>>>>;
|
||||
|
||||
pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub use crate::NodeIOTypes;
|
||||
|
||||
/// Element-independent by erasure; the wire's `Type::Record(El)` keeps element reads proven at wiring.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>> + Send + Sync;
|
||||
pub type DynFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n + Send>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type DynEdge = dyn std::any::Any + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type DynEdge = dyn std::any::Any;
|
||||
|
||||
pub fn record_type<T: 'static>() -> Type {
|
||||
Type::Record(Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn record_edge_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
|
||||
}
|
||||
|
||||
/// The record edge type of a token row, generic over the element.
|
||||
pub fn generic_record_edge_type(name: &'static str) -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
|
||||
}
|
||||
|
||||
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
|
||||
let mut hasher = graphene_hash::FxHasher64::new();
|
||||
ctx.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ConstructionError {
|
||||
Arity { expected: usize, got: usize },
|
||||
Type { expected: Box<Type>, found: Box<Type> },
|
||||
}
|
||||
|
||||
pub struct SharedEdge<N: ?Sized> {
|
||||
ptr: std::ptr::NonNull<N>,
|
||||
own: std::sync::Arc<N>,
|
||||
}
|
||||
|
||||
impl<N: ?Sized> SharedEdge<N> {
|
||||
pub fn new(own: std::sync::Arc<N>) -> Self {
|
||||
Self {
|
||||
ptr: std::ptr::NonNull::from(&*own),
|
||||
own,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn share(&self) -> Self {
|
||||
Self { ptr: self.ptr, own: self.own.clone() }
|
||||
}
|
||||
|
||||
/// Re-derives the cached pointer from the owned payload. An exclusive
|
||||
/// re-borrow of the payload invalidates the pointer taken before it, so
|
||||
/// every mutation through `own` ends here.
|
||||
pub fn rederive(&mut self) {
|
||||
self.ptr = std::ptr::NonNull::from(&*self.own);
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the edge is exactly as
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedEdge<N> {}
|
||||
// SAFETY: as in Send.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Sync for SharedEdge<N> {}
|
||||
|
||||
impl<Input, N> Node<Input> for SharedEdge<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
/// A node takes exactly its own frame out of its caller's free space: the
|
||||
/// caller minted the claim and kept the cursor, so the frame accounting is
|
||||
/// structural here and asserted where a claim is split.
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
// SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc
|
||||
// payloads are address stable.
|
||||
unsafe { self.ptr.as_ref() }.serve(input, slot)
|
||||
}
|
||||
|
||||
fn extent_at<'x>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll<crate::gpoll::Extent>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
|
||||
{
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.extent_at(input, level, frames)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a, 'x>(
|
||||
&'a self,
|
||||
input: &'a Input,
|
||||
range: std::ops::Range<u64>,
|
||||
scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>,
|
||||
frames: &crate::record::Frames<'x>,
|
||||
) -> crate::node::BatchStatus<'a>
|
||||
where
|
||||
Input: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
|
||||
{
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EdgeHandle {
|
||||
node: Box<DynEdge>,
|
||||
share: fn(&DynEdge) -> Box<DynEdge>,
|
||||
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||
layout: fn(&DynEdge) -> &crate::record::Layout,
|
||||
set_layout: fn(&mut DynEdge, crate::record::RecordLayout),
|
||||
ty: Type,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EdgeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for EdgeHandle {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for EdgeHandle {}
|
||||
|
||||
impl EdgeHandle {
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_edge_type::<T>())
|
||||
}
|
||||
|
||||
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
|
||||
where
|
||||
N: ?Sized + 'static + for<'c> Node<ContextImpl<'c>>,
|
||||
SharedEdge<N>: WasmNotSend + WasmNotSync,
|
||||
{
|
||||
Self {
|
||||
node: Box::new(SharedEdge::new(node)),
|
||||
share: |edge| Box::new(edge.downcast_ref::<SharedEdge<N>>().expect("share hook matches the stored edge type").share()),
|
||||
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedEdge<N>>().expect("serialize hook matches the stored edge type")),
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type")),
|
||||
set_layout: |edge, layout| {
|
||||
let shared = edge.downcast_mut::<SharedEdge<N>>().expect("set_layout hook matches the stored edge type");
|
||||
let node = std::sync::Arc::get_mut(&mut shared.own).expect("layout is installed before the node is shared");
|
||||
Node::<ContextImpl>::set_layout(node, layout);
|
||||
shared.rederive();
|
||||
},
|
||||
ty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ty(&self) -> &Type {
|
||||
&self.ty
|
||||
}
|
||||
|
||||
pub fn duplicate(&self) -> Self {
|
||||
Self {
|
||||
node: (self.share)(&*self.node),
|
||||
share: self.share,
|
||||
serialize: self.serialize,
|
||||
layout: self.layout,
|
||||
set_layout: self.set_layout,
|
||||
ty: self.ty.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(self.serialize)(&*self.node)
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &crate::record::Layout {
|
||||
(self.layout)(&*self.node)
|
||||
}
|
||||
|
||||
pub fn set_layout(&mut self, layout: crate::record::RecordLayout) {
|
||||
(self.set_layout)(&mut *self.node, layout);
|
||||
}
|
||||
|
||||
pub fn downcast_record<T: 'static>(self) -> Result<SharedEdge<ErasedRecordNode>, ConstructionError> {
|
||||
self.downcast_erased(record_edge_type::<T>())
|
||||
}
|
||||
|
||||
/// The erased record edge, for callers that dispatch on the layout rather
|
||||
/// than a static element type. `None` for an edge erased to another node type.
|
||||
pub fn record_edge(self) -> Option<SharedEdge<ErasedRecordNode>> {
|
||||
self.node.downcast::<SharedEdge<ErasedRecordNode>>().ok().map(|edge| *edge)
|
||||
}
|
||||
|
||||
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
|
||||
let found = self.ty;
|
||||
self.node.downcast::<SharedEdge<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
|
||||
expected: Box::new(expected),
|
||||
found: Box::new(found),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegistryEntry {
|
||||
pub io: NodeIOTypes,
|
||||
pub constructor: NodeConstructor,
|
||||
/// Declarative record-io metadata for the compiler layout pass; `None` for
|
||||
/// nodes whose layout the pass does not yet fold (routing/opaque, hand-written
|
||||
/// rows), which keep the construction-time path.
|
||||
pub layout_meta: Option<crate::record::LayoutMeta>,
|
||||
}
|
||||
|
||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
if inputs.len() != entry.io.inputs.len() {
|
||||
return Err(ConstructionError::Arity {
|
||||
expected: entry.io.inputs.len(),
|
||||
got: inputs.len(),
|
||||
});
|
||||
}
|
||||
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
|
||||
if handle.ty() != expected {
|
||||
return Err(ConstructionError::Type {
|
||||
expected: Box::new(expected.clone()),
|
||||
found: Box::new(handle.ty().clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
(entry.constructor)(inputs)
|
||||
}
|
||||
|
||||
pub type DynFuture<'n, T> = Pin<Box<dyn std::future::Future<Output = T> + 'n>>;
|
||||
pub type LocalFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n>>;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type Any<'n> = Box<dyn DynAny<'n> + 'n>;
|
||||
pub type FutureAny<'n> = DynFuture<'n, Any<'n>>;
|
||||
// TODO: is this safe? This is assumed to be send+sync.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n;
|
||||
pub type TypeErasedPinnedRef<'n> = Pin<&'n TypeErasedNode<'n>>;
|
||||
pub type TypeErasedRef<'n> = &'n TypeErasedNode<'n>;
|
||||
pub type TypeErasedBox<'n> = Box<TypeErasedNode<'n>>;
|
||||
pub type TypeErasedPinned<'n> = Pin<Box<TypeErasedNode<'n>>>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::SourceId;
|
||||
use crate::arena::Arena;
|
||||
use crate::context::{Ctx, EvalScope, ExtractArena, ExtractIndices};
|
||||
use crate::gpoll::GPoll;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
pub type SharedNodeContainer = std::sync::Arc<NodeContainer>;
|
||||
|
||||
use crate::record::{FrameClaim, Layout, LiftedSource, Served, element_write, read_element, serve_edge};
|
||||
pub type NodeConstructor = fn(Vec<SharedNodeContainer>) -> DynFuture<'static, TypeErasedBox<'static>>;
|
||||
|
||||
fn counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(count.fetch_add(1, Ordering::Relaxed) + 1))
|
||||
#[derive(Clone)]
|
||||
pub struct NodeContainer {
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
pub node: *const TypeErasedNode<'static>,
|
||||
#[cfg(not(feature = "dealloc_nodes"))]
|
||||
pub node: TypeErasedRef<'static>,
|
||||
}
|
||||
|
||||
impl Deref for NodeContainer {
|
||||
type Target = TypeErasedNode<'static>;
|
||||
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { &*(self.node) }
|
||||
#[cfg(not(feature = "dealloc_nodes"))]
|
||||
self.node
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
/// Serves a parked borrow of its own value: the element is a reference into
|
||||
/// the evaluation's arena, so its lifetime is the serving one.
|
||||
struct LendNode {
|
||||
value: String,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl LendNode {
|
||||
fn new(value: &str) -> Self {
|
||||
Self {
|
||||
value: value.to_string(),
|
||||
layout: Layout::default().with_writes(0, element_write::<&'static String>(), &[]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input: Ctx> Node<Input> for LendNode {
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
Input: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
match input.arena().alloc(self.value.clone()) {
|
||||
Some((parked, _)) => slot.lift_served(GPoll::Final(parked), input.arena()),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let node = LendNode::new("held");
|
||||
let layout = Node::<ContextImpl>::layout(&node).clone();
|
||||
let handle = EdgeHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
||||
assert_eq!(*handle.ty(), concrete!(String));
|
||||
|
||||
let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
|
||||
let GPoll::Final(value) = serve_edge(&wired, &ctx, &frames) else {
|
||||
panic!("borrow-carrying output must serve through the erased edge");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the borrow.
|
||||
let held = unsafe { read_element::<&String>(layout.rec(&value)) };
|
||||
assert_eq!(held, "held");
|
||||
assert_eq!(held.len(), 4);
|
||||
}
|
||||
|
||||
/// Evaluates its content at three promoted index levels and serves the
|
||||
/// collected elements.
|
||||
struct RepeatNode<Node0, T> {
|
||||
content: Node0,
|
||||
inner: Layout,
|
||||
layout: Layout,
|
||||
_marker: std::marker::PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<Node0, T: Clone + Send + Sync + dyn_any::StaticTypeSized> RepeatNode<Node0, T>
|
||||
where
|
||||
Vec<T>: Clone + Send + Sync + dyn_any::StaticTypeSized,
|
||||
<Vec<T> as dyn_any::StaticTypeSized>::Static: Clone + Send + Sync,
|
||||
{
|
||||
fn new(content: Node0, inner: Layout) -> Self {
|
||||
Self {
|
||||
content,
|
||||
inner,
|
||||
layout: Layout::default().with_writes(0, element_write::<Vec<T>>(), &[]),
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, T, Node0> Node<C> for RepeatNode<Node0, T>
|
||||
where
|
||||
C: Ctx + crate::context::DeriveCtx,
|
||||
T: Clone + 'static,
|
||||
Vec<T>: Send + Sync + dyn_any::StaticTypeSized,
|
||||
Node0: for<'x> crate::record::DerivedRecordEdge<'x, crate::context::Derived<'x, C>>,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let cell = crate::node::StatusCell::new();
|
||||
let spilled = input.index_head();
|
||||
let mut result = Vec::new();
|
||||
for index in 0..3 {
|
||||
// The element copies out by value, so the content's frame is
|
||||
// dead when the scope ends.
|
||||
let scope = slot.frames().scope();
|
||||
let derived = input.promoted(&spilled, index);
|
||||
match self.content.eval_derived(&cell, 0, &derived, &scope) {
|
||||
// SAFETY: the content served at its own layout, whose
|
||||
// element is `T`.
|
||||
Ok(value) => result.push(unsafe { read_element::<T>(self.inner.rec(&value)) }),
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
}
|
||||
}
|
||||
slot.lift_served(cell.finish(result), input.arena())
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let levels = LiftedSource::<Vec<usize>, _>::new(|input: &ContextImpl| GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default()));
|
||||
let levels_layout = Node::<ContextImpl>::layout(&levels).clone();
|
||||
let inner = RepeatNode::<_, Vec<usize>>::new(levels, levels_layout);
|
||||
let inner_layout = Node::<ContextImpl>::layout(&inner).clone();
|
||||
let nested = RepeatNode::<_, Vec<Vec<usize>>>::new(inner, inner_layout);
|
||||
let layout = Node::<ContextImpl>::layout(&nested).clone();
|
||||
let erased: Box<ErasedRecordNode> = Box::new(nested);
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let GPoll::Final(value) = serve_edge(&*erased, &ctx, &frames) else {
|
||||
panic!("nested repeat must evaluate");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the output.
|
||||
let outer = unsafe { read_element::<Vec<Vec<Vec<usize>>>>(layout.rec(&value)) };
|
||||
assert_eq!(outer.len(), 3);
|
||||
assert_eq!(outer[2][1], vec![1, 2, 0]);
|
||||
assert_eq!(outer[0][0], vec![0, 0, 0]);
|
||||
}
|
||||
|
||||
/// Shifts the footprint's resolution and serves its content's element under
|
||||
/// the derived context.
|
||||
struct ShiftFootprintNode<Node0> {
|
||||
content: Node0,
|
||||
inner: Layout,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl<Node0> ShiftFootprintNode<Node0> {
|
||||
fn new(content: Node0, inner: Layout) -> Self {
|
||||
Self {
|
||||
content,
|
||||
inner,
|
||||
layout: Layout::default().with_writes(0, element_write::<u32>(), &[]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, Node0> Node<C> for ShiftFootprintNode<Node0>
|
||||
where
|
||||
C: Ctx + crate::context::DeriveCtx + crate::context::ExtractFootprint,
|
||||
Node0: for<'x> crate::record::DerivedRecordEdge<'x, crate::context::Derived<'x, C>>,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
use crate::transform::Footprint;
|
||||
let cell = crate::node::StatusCell::new();
|
||||
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
|
||||
footprint.resolution.x += 7;
|
||||
// The element copies out by value, so the content's frame is dead
|
||||
// when the scope ends.
|
||||
let value = {
|
||||
let scope = slot.frames().scope();
|
||||
let derived = input.with_footprint(&footprint);
|
||||
match self.content.eval_derived(&cell, 0, &derived, &scope) {
|
||||
// SAFETY: the content served at its own layout, whose
|
||||
// element is the resolution.
|
||||
Ok(value) => unsafe { read_element::<u32>(self.inner.rec(&value)) },
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
}
|
||||
};
|
||||
slot.lift_served(cell.finish(value), input.arena())
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_ctx_footprint_replace_reaches_the_content() {
|
||||
use crate::context::ExtractFootprint;
|
||||
use crate::transform::Footprint;
|
||||
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let resolution = LiftedSource::<u32, _>::new(|input: &ContextImpl| GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0)));
|
||||
let resolution_layout = Node::<ContextImpl>::layout(&resolution).clone();
|
||||
let shifted = ShiftFootprintNode::new(resolution, resolution_layout);
|
||||
let shifted_layout = Node::<ContextImpl>::layout(&shifted).clone();
|
||||
let graph = ShiftFootprintNode::new(shifted, shifted_layout);
|
||||
let layout = Node::<ContextImpl>::layout(&graph).clone();
|
||||
|
||||
let GPoll::Final(value) = serve_edge(&graph, &ctx, &frames) else {
|
||||
panic!("the footprint shift must reach the content");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the resolution.
|
||||
assert_eq!(unsafe { read_element::<u32>(layout.rec(&value)) }, Footprint::DEFAULT.resolution.x + 14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construct_checks_arity_and_types() {
|
||||
fn construct_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
let mut args = args.into_iter();
|
||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
|
||||
drop(value);
|
||||
Ok(crate::value::record_value_edge(0u32))
|
||||
}
|
||||
let entry = RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_edge_type::<String>()]),
|
||||
constructor: construct_strlen,
|
||||
};
|
||||
|
||||
let owned = crate::value::record_value_edge("typed".to_string());
|
||||
assert!(construct(&entry, vec![owned]).is_ok());
|
||||
|
||||
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
|
||||
|
||||
let mistyped = crate::value::record_value_edge(1.0f64);
|
||||
assert_eq!(
|
||||
construct(&entry, vec![mistyped]).unwrap_err(),
|
||||
ConstructionError::Type {
|
||||
expected: Box::new(record_edge_type::<String>()),
|
||||
found: Box::new(record_edge_type::<f64>()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let counting = counting();
|
||||
let layout = Node::<ContextImpl>::layout(&counting).clone();
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||
let duplicate = handle.duplicate();
|
||||
assert_eq!(*duplicate.ty(), record_edge_type::<u32>());
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let first = handle.downcast_record::<u32>().unwrap();
|
||||
let second = duplicate.downcast_record::<u32>().unwrap();
|
||||
// SAFETY: each record was served at `layout`, whose element is the count.
|
||||
let count = |value| unsafe { layout.rec(&value).element::<u32>() };
|
||||
assert_eq!(serve_edge(&first, &ctx, &frames).map(count), GPoll::Final(1));
|
||||
assert_eq!(serve_edge(&second, &ctx, &frames).map(count), GPoll::Final(2));
|
||||
|
||||
drop(first);
|
||||
assert_eq!(serve_edge(&second, &ctx, &frames).map(count), GPoll::Final(3));
|
||||
#[cfg(not(feature = "dealloc_nodes"))]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.node
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Marks NodeContainer as Sync. This dissallows the use of threadlocal storage for nodes as this would invalidate references to them.
|
||||
// TODO: implement this on a higher level wrapper to avoid missuse
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
unsafe impl Send for NodeContainer {}
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
unsafe impl Sync for NodeContainer {}
|
||||
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
impl Drop for NodeContainer {
|
||||
fn drop(&mut self) {
|
||||
unsafe { self.dealloc_unchecked() }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NodeContainer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("NodeContainer").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeContainer {
|
||||
pub fn new(node: TypeErasedBox<'static>) -> SharedNodeContainer {
|
||||
let node = Box::leak(node);
|
||||
Self { node }.into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
unsafe fn dealloc_unchecked(&mut self) {
|
||||
unsafe {
|
||||
drop(Box::from_raw(self.node as *mut TypeErasedNode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Boxes the input and downcasts the output.
|
||||
/// Wraps around a node taking Box<dyn DynAny> and returning Box<dyn DynAny>
|
||||
#[derive(Clone)]
|
||||
pub struct DowncastBothNode<I, O> {
|
||||
node: SharedNodeContainer,
|
||||
_i: PhantomData<I>,
|
||||
_o: PhantomData<O>,
|
||||
}
|
||||
impl<'input, O, I> Node<'input, I> for DowncastBothNode<I, O>
|
||||
where
|
||||
O: 'input + StaticType + WasmNotSend,
|
||||
I: 'input + StaticType + WasmNotSend,
|
||||
{
|
||||
type Output = DynFuture<'input, O>;
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
fn eval(&'input self, input: I) -> Self::Output {
|
||||
{
|
||||
let node_name = self.node.node_name();
|
||||
let input = Box::new(input);
|
||||
let future = self.node.eval(input);
|
||||
Box::pin(async move {
|
||||
let out = dyn_any::downcast(future.await).unwrap_or_else(|e| panic!("DowncastBothNode wrong output type: {e} in: \n{node_name}"));
|
||||
*out
|
||||
})
|
||||
}
|
||||
}
|
||||
fn reset(&self) {
|
||||
self.node.reset();
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.node.serialize()
|
||||
}
|
||||
}
|
||||
impl<I, O> DowncastBothNode<I, O> {
|
||||
pub const fn new(node: SharedNodeContainer) -> Self {
|
||||
Self {
|
||||
node,
|
||||
_i: PhantomData,
|
||||
_o: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct FutureWrapperNode<Node> {
|
||||
node: Node,
|
||||
}
|
||||
|
||||
impl<'i, T: 'i + WasmNotSend, N> Node<'i, T> for FutureWrapperNode<N>
|
||||
where
|
||||
N: Node<'i, T, Output: WasmNotSend> + WasmNotSend,
|
||||
{
|
||||
type Output = DynFuture<'i, N::Output>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, input: T) -> Self::Output {
|
||||
let result = self.node.eval(input);
|
||||
Box::pin(async move { result })
|
||||
}
|
||||
#[inline(always)]
|
||||
fn reset(&self) {
|
||||
self.node.reset();
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.node.serialize()
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> FutureWrapperNode<N> {
|
||||
pub const fn new(node: N) -> Self {
|
||||
Self { node }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DynAnyNode<I, O, Node> {
|
||||
node: Node,
|
||||
_i: PhantomData<I>,
|
||||
_o: PhantomData<O>,
|
||||
}
|
||||
|
||||
impl<'input, I, O, N> Node<'input, Any<'input>> for DynAnyNode<I, O, N>
|
||||
where
|
||||
I: 'input + StaticType + WasmNotSend,
|
||||
O: 'input + StaticType + WasmNotSend,
|
||||
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
|
||||
{
|
||||
type Output = FutureAny<'input>;
|
||||
#[inline]
|
||||
fn eval(&'input self, input: Any<'input>) -> Self::Output {
|
||||
let node_name = std::any::type_name::<N>();
|
||||
let output = |input| {
|
||||
let result = self.node.eval(input);
|
||||
async move { Box::new(result.await) as Any<'input> }
|
||||
};
|
||||
match dyn_any::downcast(input) {
|
||||
Ok(input) => Box::pin(output(*input)),
|
||||
Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.node.reset();
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.node.serialize()
|
||||
}
|
||||
}
|
||||
impl<'input, I, O, N> DynAnyNode<I, O, N>
|
||||
where
|
||||
I: 'input + StaticType,
|
||||
O: 'input + StaticType,
|
||||
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
|
||||
{
|
||||
pub const fn new(node: N) -> Self {
|
||||
Self {
|
||||
node,
|
||||
_i: PhantomData,
|
||||
_o: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct PanicNode<I: WasmNotSend, O: WasmNotSend>(PhantomData<I>, PhantomData<O>);
|
||||
|
||||
impl<'i, I: 'i + WasmNotSend, O: 'i + WasmNotSend> Node<'i, I> for PanicNode<I, O> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, _: I) -> Self::Output {
|
||||
unimplemented!("This node should never be evaluated")
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: WasmNotSend, O: WasmNotSend> PanicNode<I, O> {
|
||||
pub const fn new() -> Self {
|
||||
Self(PhantomData, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: WasmNotSend, O: WasmNotSend> Default for PanicNode<I, O> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Evaluate safety
|
||||
unsafe impl<I: WasmNotSend, O: WasmNotSend> Sync for PanicNode<I, O> {}
|
||||
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user