mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f67dbc4b41 | ||
|
|
3d6b50a99b | ||
|
|
475c67facc | ||
|
|
58178fd48e | ||
|
|
3d7e85c054 | ||
|
|
95f2b3bbad | ||
|
|
515a5265fe | ||
|
|
2f65a3aee2 | ||
|
|
1964fdb99e | ||
|
|
117da97dd5 | ||
|
|
f88896a887 | ||
|
|
0eab6aa93c | ||
|
|
581bb05f5d | ||
|
|
048c458789 | ||
|
|
d241cdcb2e | ||
|
|
a770448bc9 | ||
|
|
2090e9979a |
No files matched your search
Generated
+19
@@ -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"
|
||||
@@ -2038,6 +2047,7 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"raster-types",
|
||||
@@ -2180,6 +2190,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"vector-types",
|
||||
@@ -2392,6 +2403,7 @@ dependencies = [
|
||||
"graphite-proc-macros",
|
||||
"js-sys",
|
||||
"log",
|
||||
"node-macro",
|
||||
"serde",
|
||||
"serde-wasm-bindgen",
|
||||
"serde_bytes",
|
||||
@@ -4992,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"
|
||||
@@ -6575,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::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":{"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::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"}},"visible":true,"skip_deduplication":false,"contextLine 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::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
|
||||
{"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::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
|
||||
{"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::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":{"OptionalDAffine2":[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":{"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":[{"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>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphiLine 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::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":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"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":"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":{"OptionalDAffine2":null},"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":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":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.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-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":{"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.0Line 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::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":{"OptionalDAffine2":[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}},{"Value":{"tagged_value":{"StrinLine 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::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
|
||||
{"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
|
||||
@@ -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)
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -3,17 +3,29 @@ use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup,
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessage, PathStep};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{format_rounded, round_away_float_noise};
|
||||
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::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;
|
||||
@@ -176,10 +188,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(io) = introspected_data.downcast_ref::<IORecord<Context, List<NodeId>>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, 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>,
|
||||
@@ -188,27 +200,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>,
|
||||
])
|
||||
}
|
||||
|
||||
@@ -246,6 +337,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"
|
||||
@@ -324,12 +466,53 @@ impl TableItemLayout for Artboard {
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
@@ -345,6 +528,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),
|
||||
@@ -440,6 +624,7 @@ impl TableItemLayout for Vector {
|
||||
VectorTableTab::Points => {
|
||||
table_rows.push(column_headings(&["", "position"]));
|
||||
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
|
||||
let position = DVec2::new(round_away_float_noise(position.x), round_away_float_noise(position.y));
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{position}")).narrow(true).widget_instance(),
|
||||
@@ -512,7 +697,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)]
|
||||
}
|
||||
}
|
||||
@@ -537,7 +722,7 @@ impl TableItemLayout for Color {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for GradientStops {
|
||||
impl TableItemLayout for Gradient {
|
||||
fn type_name() -> &'static str {
|
||||
"Gradient"
|
||||
}
|
||||
@@ -585,6 +770,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)"
|
||||
@@ -600,6 +800,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)"
|
||||
@@ -726,45 +957,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)])]
|
||||
@@ -905,12 +1164,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,
|
||||
@@ -919,9 +1176,12 @@ macro_rules! known_item_types {
|
||||
Vec2,
|
||||
Option<f64>,
|
||||
f64,
|
||||
f32,
|
||||
u8,
|
||||
u32,
|
||||
u64,
|
||||
i32,
|
||||
i64,
|
||||
bool,
|
||||
String,
|
||||
Vector,
|
||||
@@ -929,6 +1189,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,
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -949,6 +1245,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),* $(,)? ) => {
|
||||
$(
|
||||
@@ -1005,10 +1305,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));
|
||||
// `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),* $(,)? ) => {
|
||||
@@ -1041,19 +1341,17 @@ fn format_transform_matrix(transform: DAffine2) -> String {
|
||||
} else {
|
||||
transform.to_scale_angle_translation()
|
||||
};
|
||||
let rotation = if angle == -0. { 0. } else { angle.to_degrees() };
|
||||
let round = |x: f64| (x * 1e3).round() / 1e3;
|
||||
let rotation = format_rounded(angle.to_degrees(), 3);
|
||||
|
||||
format!(
|
||||
"Location: ({} px, {} px) — Rotation: {rotation:2}° — Scale: ({}x, {}x)",
|
||||
round(translation.x),
|
||||
round(translation.y),
|
||||
round(scale.x),
|
||||
round(scale.y)
|
||||
"Location: ({} px, {} px) — Rotation: {rotation}° — Scale: ({}x, {}x)",
|
||||
format_rounded(translation.x, 3),
|
||||
format_rounded(translation.y, 3),
|
||||
format_rounded(scale.x, 3),
|
||||
format_rounded(scale.y, 3)
|
||||
)
|
||||
}
|
||||
|
||||
fn format_dvec2(value: DVec2) -> String {
|
||||
let round = |x: f64| (x * 1e3).round() / 1e3;
|
||||
format!("({} px, {} px)", round(value.x), round(value.y))
|
||||
format!("({} px, {} px)", format_rounded(value.x, 3), format_rounded(value.y, 3))
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -2774,7 +2774,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
let has_fill = fill_graphic_list.is_some_and(|list| is_paint_present(list));
|
||||
// `Vector.stroke` captures stroke geometry, even with weight 0 or transparent paint.
|
||||
// So stroke visibility must be checked from `ATTR_STROKE`, the paint source of truth.
|
||||
// So stroke visibility must be checked from `graphic_types::attr::Stroke`, the paint source of truth.
|
||||
let stroke_visible = stroke_graphic_list.is_some_and(|list| list.element(0).is_some_and(|g| !g.is_fully_transparent()));
|
||||
let has_stroke = stroke.as_ref().is_some_and(|s| s.has_renderable_stroke()) && stroke_visible;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -460,11 +460,15 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
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;
|
||||
};
|
||||
@@ -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) {
|
||||
@@ -716,7 +725,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
};
|
||||
|
||||
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(TaggedValue::Color(color), false), true);
|
||||
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::<graphene_std::list::List<f64>>::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,9 +14,8 @@ 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)]
|
||||
@@ -176,7 +175,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::value(TaggedValue::String(attr::editor::LayerPath::name().to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
@@ -202,7 +201,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 {
|
||||
@@ -287,11 +286,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(TaggedValue), 1),
|
||||
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()
|
||||
},
|
||||
@@ -306,7 +305,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::value(TaggedValue::String(attr::editor::LayerPath::name().to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
@@ -322,7 +321,7 @@ 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),
|
||||
@@ -336,11 +335,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()
|
||||
@@ -448,9 +447,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()
|
||||
},
|
||||
@@ -463,7 +462,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)
|
||||
@@ -539,8 +538,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()
|
||||
},
|
||||
@@ -570,11 +569,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()
|
||||
},
|
||||
@@ -599,7 +598,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)),
|
||||
@@ -802,9 +801,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()
|
||||
},
|
||||
@@ -821,7 +820,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 {
|
||||
@@ -879,7 +878,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)),
|
||||
@@ -919,7 +918,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)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -994,7 +993,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)],
|
||||
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()
|
||||
},
|
||||
@@ -1006,7 +1005,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.)),
|
||||
@@ -1076,7 +1075,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),
|
||||
@@ -1085,7 +1084,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),
|
||||
@@ -1094,7 +1093,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),
|
||||
@@ -1103,7 +1102,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),
|
||||
@@ -1117,7 +1116,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 {
|
||||
@@ -1171,20 +1170,20 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Split Vec2",
|
||||
category: "Math: Vector",
|
||||
category: "Math: Vec2",
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(NodeNetwork {
|
||||
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()
|
||||
@@ -1235,89 +1234,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 {
|
||||
@@ -1345,25 +1272,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()
|
||||
},
|
||||
]
|
||||
@@ -1445,7 +1372,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,
|
||||
@@ -1469,7 +1396,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()
|
||||
@@ -2202,3 +2129,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");
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -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 {
|
||||
|
||||
@@ -19,7 +19,7 @@ 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;
|
||||
@@ -32,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};
|
||||
|
||||
@@ -213,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) => {
|
||||
@@ -234,96 +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(),
|
||||
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::Ref(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -855,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();
|
||||
@@ -1167,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)
|
||||
}
|
||||
@@ -1259,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],
|
||||
@@ -1268,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],
|
||||
@@ -1304,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)],
|
||||
@@ -1401,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)
|
||||
@@ -1494,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],
|
||||
@@ -1550,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,
|
||||
@@ -1575,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)
|
||||
@@ -1635,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],
|
||||
@@ -2168,7 +2212,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
// Corner Radius
|
||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::<f64>::INDEX, true, context));
|
||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::INDEX, true, context));
|
||||
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
||||
@@ -2188,20 +2232,15 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
};
|
||||
if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() {
|
||||
// Values
|
||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::<f64>::INDEX) else {
|
||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::INDEX) else {
|
||||
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")
|
||||
@@ -2216,14 +2255,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
||||
value: TaggedValue::F64(uniform_val),
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
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 {
|
||||
@@ -2236,8 +2274,8 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
||||
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::BoxCorners(BoxCorners::from(corner_values.to_vec())),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2248,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::<f64>::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::<f64>::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()
|
||||
};
|
||||
@@ -2334,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 {
|
||||
@@ -2350,12 +2391,14 @@ 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();
|
||||
};
|
||||
@@ -2443,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,
|
||||
@@ -2453,9 +2496,6 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
Other,
|
||||
}
|
||||
|
||||
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::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::<List<Graphic>>::INDEX, false, context));
|
||||
|
||||
@@ -2467,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::<List<Graphic>>::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 {
|
||||
@@ -2537,28 +2568,33 @@ 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::<List<Graphic>>::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
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,
|
||||
@@ -2586,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)
|
||||
}
|
||||
})
|
||||
@@ -2603,7 +2639,11 @@ 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::<List<Graphic>>::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")
|
||||
@@ -2669,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);
|
||||
@@ -2713,8 +2768,8 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
_ => &StrokeJoin::Miter,
|
||||
};
|
||||
|
||||
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::<List<f64>>::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;
|
||||
@@ -2740,10 +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::<List<f64>>::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 == std::any::type_name::<List<Graphic>>() => Self::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => Self::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => Self::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => Self::Vector,
|
||||
n if n == 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,11 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::messages::prelude::ViewportMessageHandler;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::ATTR_TRANSFORM;
|
||||
use graphene_std::attr;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::{self, Subpath};
|
||||
@@ -1168,7 +1169,7 @@ impl OverlayContextInternal {
|
||||
// Use the existing bezier_to_path infrastructure to convert Vector to BezPath
|
||||
let mut path = BezPath::new();
|
||||
let mut last_point = None;
|
||||
let transform: DAffine2 = text_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform = text_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
let Some(element) = text_list.element(index) else { continue };
|
||||
for (_, bezier, start_id, end_id) in element.segment_iter() {
|
||||
@@ -1189,7 +1190,7 @@ impl OverlayContextInternal {
|
||||
|
||||
let width = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.x).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.x, 2),
|
||||
};
|
||||
let x_transform = DAffine2::from_translation((quad.top_left() + quad.top_right()) / 2.);
|
||||
self.text(width, COLOR_OVERLAY_BLUE, None, x_transform, 4., [Pivot::Middle, Pivot::End]);
|
||||
@@ -1200,7 +1201,7 @@ impl OverlayContextInternal {
|
||||
|
||||
let height = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.y).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.y, 2),
|
||||
};
|
||||
let y_transform = DAffine2::from_translation((quad.top_left() + quad.bottom_left()) / 2.);
|
||||
let height_pivot = if translation.x > -1e-3 { Pivot::Start } else { Pivot::End };
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::consts::{
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
|
||||
use crate::messages::viewport::ViewportMessageHandler;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
@@ -1090,7 +1091,7 @@ impl OverlayContext {
|
||||
|
||||
let width = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.x).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.x, 2),
|
||||
};
|
||||
let x_transform = DAffine2::from_translation((quad.top_left() + quad.top_right()) / 2.);
|
||||
self.text(width, COLOR_OVERLAY_BLUE, None, x_transform, 4., [Pivot::Middle, Pivot::End]);
|
||||
@@ -1101,7 +1102,7 @@ impl OverlayContext {
|
||||
|
||||
let height = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.y).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.y, 2),
|
||||
};
|
||||
let y_transform = DAffine2::from_translation((quad.top_left() + quad.bottom_left()) / 2.);
|
||||
let height_pivot = if translation.x > -1e-3 { Pivot::Start } else { Pivot::End };
|
||||
|
||||
@@ -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:?}"
|
||||
);
|
||||
}
|
||||
@@ -41,10 +41,10 @@ pub struct DocumentMetadata {
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
||||
/// Per-layer `graphic_types::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>>>,
|
||||
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
|
||||
/// Per-layer `graphic_types::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>>>,
|
||||
/// Transform from document space to viewport space.
|
||||
|
||||
@@ -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;
|
||||
@@ -2499,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 {
|
||||
@@ -2516,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);
|
||||
@@ -2533,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 +3454,12 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_vector_data = new_layer_vector_data;
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_FILL` snapshot.
|
||||
/// Update the per-layer `graphic_types::attr::Fill` snapshot.
|
||||
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.
|
||||
/// Update the per-layer `graphic_types::attr::Stroke` snapshot.
|
||||
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;
|
||||
}
|
||||
@@ -6105,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);
|
||||
|
||||
+38
-22
@@ -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 == std::any::type_name::<List<Graphic>>() => FrontendGraphDataType::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => FrontendGraphDataType::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => FrontendGraphDataType::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => FrontendGraphDataType::Vector,
|
||||
n if n == 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)
|
||||
}
|
||||
|
||||
@@ -333,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",
|
||||
@@ -1121,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();
|
||||
|
||||
@@ -1285,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()
|
||||
@@ -1321,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
|
||||
@@ -1333,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.
|
||||
@@ -1572,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);
|
||||
@@ -1582,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),
|
||||
@@ -1608,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);
|
||||
}
|
||||
@@ -1640,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
|
||||
@@ -1652,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)
|
||||
@@ -1683,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()?;
|
||||
@@ -1854,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();
|
||||
@@ -1986,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);
|
||||
@@ -2202,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();
|
||||
@@ -2217,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 {
|
||||
@@ -2246,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);
|
||||
@@ -2257,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);
|
||||
@@ -2406,7 +2596,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
&& 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.clone();
|
||||
let context_features = node_definition.node_template.document_node.context_features;
|
||||
document.network_interface.set_context_features(node_id, network_path, context_features);
|
||||
}
|
||||
|
||||
@@ -2444,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
|
||||
@@ -2480,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
|
||||
// ==================================
|
||||
@@ -2565,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(())
|
||||
}
|
||||
|
||||
@@ -2572,6 +2813,13 @@ 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 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]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
|
||||
@@ -4,18 +4,18 @@ 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::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;
|
||||
|
||||
@@ -101,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")
|
||||
@@ -310,7 +310,7 @@ pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &No
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -329,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 {
|
||||
@@ -363,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::<List<Graphic>>::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.
|
||||
@@ -570,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::<List<f64>>::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) {
|
||||
@@ -626,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,
|
||||
@@ -649,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,
|
||||
};
|
||||
|
||||
@@ -667,7 +669,11 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||
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.
|
||||
@@ -687,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();
|
||||
@@ -700,8 +706,9 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
|
||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
|
||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
||||
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
|
||||
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,
|
||||
}
|
||||
})()
|
||||
@@ -799,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,
|
||||
};
|
||||
|
||||
@@ -826,7 +833,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
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);
|
||||
@@ -977,6 +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), &[]);
|
||||
|
||||
layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(List<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),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -571,7 +571,37 @@ pub fn wrap_to_tau(angle: f64) -> f64 {
|
||||
}
|
||||
|
||||
pub fn format_rounded(value: f64, precision: usize) -> String {
|
||||
format!("{value:.precision$}").trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
// Denoised values within floating point noise of zero (including -0) display as unsigned zero, unless the precision is fine enough to display them
|
||||
let value = round_away_float_noise(value);
|
||||
let value = if value.abs() < f64::min(1e-12, 0.5 * 10_f64.powi(-(precision as i32))) { 0. } else { value };
|
||||
let formatted = format!("{value:.precision$}");
|
||||
|
||||
// Trailing zeros are trimmed only when the display is exact, so a truncated value keeps its decimal places (like "0.00" or "3.10") to indicate the truncation
|
||||
if formatted.parse::<f64>() == Ok(value) {
|
||||
formatted.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
} else {
|
||||
formatted
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
|
||||
/// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
|
||||
/// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
|
||||
pub fn round_away_float_noise(value: f64) -> f64 {
|
||||
if value == 0. || !value.is_finite() {
|
||||
return if value == 0. { 0. } else { value };
|
||||
}
|
||||
|
||||
let exponent = value.abs().log10().floor() as i32;
|
||||
for significant_digits in 1..=12 {
|
||||
let scale = 10_f64.powi(significant_digits - 1 - exponent);
|
||||
let rounded = (value * scale).round() / scale;
|
||||
if ((rounded - value) / value).abs() < 1e-13 {
|
||||
return rounded;
|
||||
}
|
||||
}
|
||||
|
||||
value
|
||||
}
|
||||
|
||||
/// Gives the approximated angle to display in degrees, given an angle in degrees.
|
||||
@@ -613,3 +643,78 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
|
||||
Some((grid_type, spacing, columns, rows, angles))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_snaps_noisy_values() {
|
||||
assert_eq!(round_away_float_noise(0.1 + 0.2), 0.3);
|
||||
assert_eq!(round_away_float_noise(0.3000000000000012), 0.3);
|
||||
assert_eq!(round_away_float_noise(2.99999999999993), 3.);
|
||||
assert_eq!(round_away_float_noise(45.00000000000001), 45.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_honest_values() {
|
||||
assert_eq!(round_away_float_noise(1. / 3.), 1. / 3.);
|
||||
assert_eq!(round_away_float_noise(0.2394023940209349), 0.2394023940209349);
|
||||
assert_eq!(round_away_float_noise(0.25), 0.25);
|
||||
assert_eq!(round_away_float_noise(-17.5), -17.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_deliberate_values_with_zero_runs() {
|
||||
assert_eq!(round_away_float_noise(0.30000005), 0.30000005);
|
||||
assert_eq!(round_away_float_noise(0.3000000000001), 0.3000000000001);
|
||||
assert_eq!(round_away_float_noise(1.00000001), 1.00000001);
|
||||
assert_eq!(round_away_float_noise(2.9999993), 2.9999993);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_normalizes_zero() {
|
||||
let result = round_away_float_noise(-0.);
|
||||
assert_eq!(result, 0.);
|
||||
assert!(result.is_sign_positive());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_trims_trailing_zeros_when_exact() {
|
||||
assert_eq!(format_rounded(0.25, 2), "0.25");
|
||||
assert_eq!(format_rounded(3.1, 2), "3.1");
|
||||
assert_eq!(format_rounded(45., 2), "45");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_keeps_decimal_places_when_truncated() {
|
||||
assert_eq!(format_rounded(0.0003, 2), "0.00");
|
||||
assert_eq!(format_rounded(-0.0003, 2), "-0.00");
|
||||
assert_eq!(format_rounded(0.0003, 3), "0.000");
|
||||
assert_eq!(format_rounded(3.10001, 2), "3.10");
|
||||
assert_eq!(format_rounded(45.001, 2), "45.00");
|
||||
assert_eq!(format_rounded(std::f64::consts::PI, 2), "3.14");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_denoises_before_judging_exactness() {
|
||||
assert_eq!(format_rounded(29.999999999999996, 2), "30");
|
||||
assert_eq!(format_rounded(45.00000000000001, 2), "45");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_shows_true_and_noise_zeros_plainly() {
|
||||
assert_eq!(format_rounded(0., 2), "0");
|
||||
assert_eq!(format_rounded(-0., 2), "0");
|
||||
assert_eq!(format_rounded(1e-15, 2), "0");
|
||||
assert_eq!(format_rounded(-1e-15, 2), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_keeps_tiny_values_at_displayable_precision() {
|
||||
assert_eq!(format_rounded(5e-13, 20), "0.0000000000005");
|
||||
assert_eq!(format_rounded(-5e-13, 20), "-0.0000000000005");
|
||||
assert_eq!(format_rounded(0., 20), "0");
|
||||
assert_eq!(format_rounded(-0., 20), "0");
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// All non-color stroke-related options surfaced in the control bar popover.
|
||||
@@ -215,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::<List<f64>>::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;
|
||||
}
|
||||
|
||||
|
||||
@@ -572,6 +572,7 @@ impl Fsm for ArtboardToolFsmState {
|
||||
mod test_artboard {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::attr;
|
||||
use graphene_std::list::List;
|
||||
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
||||
@@ -601,8 +602,8 @@ mod test_artboard {
|
||||
let artboards = get_artboards(editor).await;
|
||||
let artboards = (0..artboards.len())
|
||||
.map(|index| {
|
||||
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 location = artboards.attr_cloned_or_default::<attr::Location>(index);
|
||||
let dimensions = artboards.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
ArtboardLayoutDocument::new(location, dimensions)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -205,17 +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::List;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<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::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
|
||||
instrumented.grab_all_input_as::<fill::FillInput<List<Graphic>>, Item<Color>>(&editor.runtime).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -245,7 +247,7 @@ 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);
|
||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
||||
let color = fills.first().unwrap().element();
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
|
||||
}
|
||||
|
||||
@@ -258,7 +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);
|
||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
||||
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()
|
||||
@@ -2015,19 +2015,19 @@ mod test_gradient {
|
||||
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,
|
||||
@@ -2068,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,
|
||||
};
|
||||
|
||||
@@ -2147,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,
|
||||
@@ -2184,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,
|
||||
@@ -2655,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,
|
||||
@@ -2726,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,
|
||||
@@ -2827,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,
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::messages::portfolio::document::utility_types::transformation::{Axis,
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::pivot::{PivotGizmo, PivotGizmoType};
|
||||
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
|
||||
use crate::messages::tool::tool_messages::select_tool;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::{ToolData, ToolType};
|
||||
@@ -217,7 +218,7 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
|
||||
|
||||
let format_rounded = |value: f64, precision: usize| {
|
||||
if self.typing.digits.is_empty() || !self.transform_operation.can_begin_typing() {
|
||||
format!("{value:.precision$}").trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
format_rounded(value, precision)
|
||||
} else {
|
||||
self.typing.string.clone()
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ 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, Context, Graphic, NodeInputDecleration};
|
||||
use graphene_std::{Context, Graphic, NodeInputDecleration, attr};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -82,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
|
||||
@@ -92,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,
|
||||
}
|
||||
@@ -450,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}"));
|
||||
}
|
||||
@@ -461,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();
|
||||
@@ -492,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;
|
||||
};
|
||||
@@ -519,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>,
|
||||
@@ -588,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>,
|
||||
) {
|
||||
@@ -610,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
|
||||
@@ -817,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))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -868,7 +870,7 @@ fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[NodeId]) -> boo
|
||||
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
||||
if let Some(list) = introspected_output::<List<Vector>>(data) {
|
||||
let vector = list.element(0)?;
|
||||
let item_transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let item_transform = list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let bounds = vector.nonzero_bounding_box();
|
||||
let bounding_box_affine = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
return Some((bounding_box_affine, item_transform));
|
||||
@@ -913,9 +915,18 @@ mod test {
|
||||
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 {
|
||||
@@ -938,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);
|
||||
@@ -974,15 +991,21 @@ mod test {
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
{
|
||||
// This is quite inflexible since it only allows the footprint as inputs.
|
||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() {
|
||||
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, Input::Result>>() {
|
||||
} 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, Input::Result>>() {
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else {
|
||||
warn!("cannot downcast type for introspection");
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1001,6 +1024,18 @@ mod test {
|
||||
.filter_map(Instrumented::downcast::<Input>) // Some might not resolve (e.g. generics that don't work properly)
|
||||
}
|
||||
|
||||
/// 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(Instrumented::downcast_record::<Output>)
|
||||
}
|
||||
|
||||
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
@@ -1012,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,
|
||||
|
||||
@@ -9,8 +9,9 @@ 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::attr;
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::list::List;
|
||||
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"))]
|
||||
@@ -378,7 +379,7 @@ impl NodeRuntime {
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
|
||||
match self.executor.input_type() {
|
||||
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()),
|
||||
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)),
|
||||
@@ -441,6 +442,28 @@ impl NodeRuntime {
|
||||
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:?}");
|
||||
@@ -514,8 +537,8 @@ impl NodeRuntime {
|
||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
||||
let mut combined: Option<[DVec2; 2]> = None;
|
||||
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 location = artboards.attr_cloned_or_default::<attr::Location>(index);
|
||||
let dimensions = artboards.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
let bounds = [location, location + dimensions];
|
||||
combined = Some(match combined {
|
||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
|
||||
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
|
||||
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "/src/managers/input";
|
||||
import { roundAwayFloatNoise } from "/src/utility-functions/numbers";
|
||||
import { browserVersion } from "/src/utility-functions/platform";
|
||||
import type { ActionShortcut, EditorWrapper, NumberInputIncrementBehavior, NumberInputMode } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
@@ -213,9 +214,19 @@
|
||||
function displayText(displayValue: number | undefined, unit: string): string {
|
||||
if (displayValue === undefined) return "-";
|
||||
|
||||
const roundingPower = 10 ** Math.max(displayDecimalPlaces, 0);
|
||||
const decimalPlaces = Math.max(displayDecimalPlaces, 0);
|
||||
const roundingPower = 10 ** decimalPlaces;
|
||||
|
||||
// Values within floating point noise of zero (including -0) display as unsigned zero, unless the field's decimal precision is fine enough to display them
|
||||
const effectiveValue = Math.abs(displayValue) < Math.min(1e-12, 0.5 / roundingPower) ? 0 : roundAwayFloatNoise(displayValue);
|
||||
const unitlessDisplayValue = Math.round(effectiveValue * roundingPower) / roundingPower;
|
||||
|
||||
// Trailing zeros are trimmed only when the display is exact, so a truncated value keeps its decimal places (like "0.00" or "3.10") to indicate the truncation
|
||||
if (unitlessDisplayValue !== effectiveValue) {
|
||||
const sign = unitlessDisplayValue === 0 && effectiveValue < 0 ? "-" : "";
|
||||
return `${sign}${unitlessDisplayValue.toFixed(decimalPlaces)}${unPluralize(unit, displayValue)}`;
|
||||
}
|
||||
|
||||
const unitlessDisplayValue = Math.round(displayValue * roundingPower) / roundingPower;
|
||||
return `${unitlessDisplayValue}${unPluralize(unit, displayValue)}`;
|
||||
}
|
||||
|
||||
@@ -230,9 +241,8 @@
|
||||
// ===========================
|
||||
|
||||
function onTextFocused() {
|
||||
// The degree of precision allowed in the number that's shown when editing the number field, where additional precision is removed to round out floating point errors.
|
||||
const MAX_PRECISION = 12;
|
||||
const noFloatingImprecisionValue = value === undefined ? undefined : Number(value.toPrecision(MAX_PRECISION));
|
||||
// The number shown when editing the field, with floating point imprecision noise removed
|
||||
const noFloatingImprecisionValue = value === undefined ? undefined : roundAwayFloatNoise(value);
|
||||
|
||||
if (value === undefined) text = "";
|
||||
else if (unitIsHiddenWhenEditing) text = `${noFloatingImprecisionValue}`;
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
|
||||
// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
|
||||
// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
|
||||
export function roundAwayFloatNoise(value: number): number {
|
||||
if (value === 0 || !Number.isFinite(value)) return value === 0 ? 0 : value;
|
||||
|
||||
const exponent = Math.floor(Math.log10(Math.abs(value)));
|
||||
for (let significantDigits = 1; significantDigits <= 12; significantDigits += 1) {
|
||||
const scale = 10 ** (significantDigits - 1 - exponent);
|
||||
const rounded = Math.round(value * scale) / scale;
|
||||
if (Math.abs((rounded - value) / value) < 1e-13) return rounded;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
@@ -220,7 +232,7 @@ pub enum DocumentNodeMetadata {
|
||||
impl DocumentNodeMetadata {
|
||||
pub fn ty(&self) -> Type {
|
||||
match self {
|
||||
DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>),
|
||||
DocumentNodeMetadata::DocumentNodePath => item!(core_types::list::NodeIdPath),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -235,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 {
|
||||
@@ -270,6 +282,7 @@ 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"),
|
||||
@@ -723,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| {
|
||||
@@ -995,7 +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::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false),
|
||||
},
|
||||
previous_export => {
|
||||
*export = previous_export;
|
||||
|
||||
@@ -2,18 +2,20 @@ use super::DocumentNode;
|
||||
use crate::application_io::PlatformEditorApi;
|
||||
use crate::application_io::resource::Resource;
|
||||
use crate::proto::{Any as DAny, FutureAny};
|
||||
use brush_nodes::brush_stroke::BrushStroke;
|
||||
use brush_nodes::brush_stroke::{BrushStroke, BrushTrace};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
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;
|
||||
@@ -28,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);
|
||||
};
|
||||
@@ -54,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>),
|
||||
@@ -82,10 +109,10 @@ 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`.
|
||||
@@ -118,7 +145,7 @@ 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::ContextFeatures(features) => features.cache_hash(state),
|
||||
Self::RenderOutput(x) => x.cache_hash(state),
|
||||
@@ -138,46 +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 == 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) => {
|
||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Box::new(list)
|
||||
}
|
||||
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::ContextFeatures(features) => Box::new(features),
|
||||
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,73 +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 == 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) => {
|
||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Arc::new(list)
|
||||
}
|
||||
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::ContextFeatures(features) => Arc::new(features),
|
||||
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!(()),
|
||||
Self::TypeDefault(td) => Type::Concrete(td.clone()),
|
||||
Self::F64Array(_) => concrete!(List<f64>),
|
||||
Self::Color(_) => concrete!(List<Color>),
|
||||
Self::Gradient(_) => concrete!(List<GradientStops>),
|
||||
Self::BrushStrokes(_) => concrete!(List<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!(List<NodeId>),
|
||||
Self::RenderOutput(_) => item!(RenderOutput),
|
||||
Self::NodeIdPath(_) => item!(NodeIdPath),
|
||||
Self::DocumentNode(_) => concrete!(DocumentNode),
|
||||
Self::ContextFeatures(_) => concrete!(ContextFeatures),
|
||||
Self::EditorApi(_) => concrete!(&PlatformEditorApi),
|
||||
Self::ResourceHash(_) => concrete!(ResourceHash),
|
||||
}
|
||||
Self::ContextFeatures(_) => item!(ContextFeatures),
|
||||
Self::EditorApi(_) => item!(&PlatformEditorApi),
|
||||
Self::ResourceHash(_) => item!(ResourceHash),
|
||||
};
|
||||
|
||||
// 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
|
||||
@@ -273,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()))),
|
||||
}
|
||||
@@ -295,43 +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::Ref(_) => None,
|
||||
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 == 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 == std::any::type_name::<List<Color>>() { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||
if name == std::any::type_name::<List<GradientStops>>() { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
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::<List<f64>>() { return Some(TaggedValue::F64Array(Vec::new())) }
|
||||
if name == std::any::type_name::<List<BrushStroke>>() { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||
// 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::<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 == 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,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:?})"),
|
||||
@@ -403,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),
|
||||
@@ -445,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),
|
||||
@@ -452,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 {
|
||||
@@ -513,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,
|
||||
@@ -531,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,
|
||||
@@ -570,7 +651,6 @@ impl TaggedValue {
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Ref(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
let ty = concrete_type.id?;
|
||||
use std::any::TypeId;
|
||||
@@ -585,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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -607,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.
|
||||
@@ -614,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
|
||||
@@ -636,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()
|
||||
@@ -648,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)?;
|
||||
@@ -656,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)));
|
||||
}
|
||||
_ => {}
|
||||
@@ -709,7 +833,7 @@ impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<
|
||||
type Output = FutureAny<'i>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
|
||||
Box::pin(async move { Box::new(self.0.as_ref()) as DAny<'i> })
|
||||
Box::pin(async move { Box::new(Item::new_from_element(self.0.as_ref())) as DAny<'i> })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -780,26 +904,26 @@ 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.",
|
||||
"`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,
|
||||
@@ -808,6 +932,57 @@ mod typedefault_dispatch {
|
||||
);
|
||||
}};
|
||||
}
|
||||
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 paint_default_parsing {
|
||||
use super::*;
|
||||
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 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 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -370,16 +370,13 @@ impl ProtoNetwork {
|
||||
let mut combined_deps = ContextFeatures::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let (extract, inject) = {
|
||||
let dependencies = &self.nodes[node_index].1.context_features;
|
||||
(dependencies.extract, dependencies.inject)
|
||||
};
|
||||
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(_) => return (extract, Some(id)),
|
||||
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
ConstructionArgs::Inline(_) => return (extract, Some(id)),
|
||||
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
|
||||
};
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
@@ -392,15 +389,15 @@ impl ProtoNetwork {
|
||||
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 |= extract;
|
||||
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);
|
||||
|
||||
// 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.into_iter()) {
|
||||
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
|
||||
if let Some(new_id) = new_id {
|
||||
*child_node = new_id;
|
||||
} else if we_introduce_new_deps || deps != combined_deps {
|
||||
@@ -410,7 +407,7 @@ impl ProtoNetwork {
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
|
||||
// Which dependencies do we supply (and don't need ourselves)?
|
||||
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.difference(net_injections);
|
||||
@@ -637,6 +634,31 @@ pub struct TypingContext {
|
||||
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 {
|
||||
@@ -661,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()
|
||||
@@ -734,6 +767,9 @@ impl TypingContext {
|
||||
// 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,
|
||||
@@ -771,6 +807,75 @@ impl TypingContext {
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -57,7 +57,7 @@ pub async fn export_document(
|
||||
}
|
||||
|
||||
// Execute the graph
|
||||
let result = executor.execute(render_config).await?;
|
||||
let result = executor.execute(render_config.into_context()).await?;
|
||||
|
||||
// Handle the result based on output type
|
||||
match result {
|
||||
@@ -195,7 +195,7 @@ pub async fn export_gif(
|
||||
}
|
||||
|
||||
// Execute the graph for this frame
|
||||
let result = executor.execute(render_config).await?;
|
||||
let result = executor.execute(render_config.into_context()).await?;
|
||||
|
||||
// Extract RGBA data from result
|
||||
let (data, img_width, img_height) = match result {
|
||||
|
||||
@@ -6,11 +6,12 @@ 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);
|
||||
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))).unwrap())
|
||||
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap())
|
||||
});
|
||||
});
|
||||
group.finish();
|
||||
|
||||
@@ -10,7 +10,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
let (executor, _) = setup_network(name);
|
||||
|
||||
// Warm up the cache by running once
|
||||
let context = RenderConfig::default();
|
||||
let context = RenderConfig::default().into_context();
|
||||
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
|
||||
|
||||
executor
|
||||
@@ -19,7 +19,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = RenderConfig::default();
|
||||
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
|
||||
|
||||
@@ -6,12 +6,13 @@ use graphene_std::application_io::RenderConfig;
|
||||
|
||||
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 context = context.clone();
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| setup_network(name),
|
||||
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
|
||||
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap(),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = application_io::RenderConfig::default();
|
||||
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 so its teardown happens outside the measured section
|
||||
|
||||
@@ -137,7 +137,7 @@ impl DynamicExecutor {
|
||||
|
||||
impl<I> Executor<I, TaggedValue> for &DynamicExecutor
|
||||
where
|
||||
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
|
||||
I: StaticType + 'static + Send + Sync,
|
||||
{
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> {
|
||||
Box::pin(async move {
|
||||
@@ -262,7 +262,7 @@ impl BorrowTree {
|
||||
/// 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 + std::panic::UnwindSafe,
|
||||
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));
|
||||
@@ -413,7 +413,19 @@ impl BorrowTree {
|
||||
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
|
||||
ConstructionArgs::Nodes(ids) => {
|
||||
let ids = ids.to_vec();
|
||||
let construction_nodes = self.node_deps(&ids);
|
||||
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);
|
||||
@@ -430,19 +442,4 @@ impl BorrowTree {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
#[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 = futures::executor::block_on(tree.eval(NodeId(0), ()));
|
||||
assert_eq!(result, Some(2u32));
|
||||
}
|
||||
}
|
||||
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::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.attr_cloned_or_default::<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.attr_cloned_or_default::<core_types::attr::Transform>(0);
|
||||
let second: DAffine2 = list.attr_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.attr_cloned_or_default::<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");
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
use dyn_any::StaticType;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::DocumentNode;
|
||||
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::application_io::Texture;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
|
||||
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")]
|
||||
@@ -17,103 +18,24 @@ use graphene_std::raster::color::Color;
|
||||
use graphene_std::raster::*;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::render_node::RenderIntermediate;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
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, convert_node, into_node};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "gpu")]
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
// TODO: turn into hashmap
|
||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
|
||||
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = 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>),
|
||||
// Type-erased attribute conversions for the `Attach Attribute` node, so it monomorphizes only over the destination `List` type.
|
||||
convert_node!(from: List<Artboard>, to: AttributeDyn),
|
||||
convert_node!(from: List<Graphic>, to: AttributeDyn),
|
||||
convert_node!(from: List<Vector>, to: AttributeDyn),
|
||||
convert_node!(from: List<Raster<CPU>>, to: AttributeDyn),
|
||||
convert_node!(from: List<Color>, to: AttributeDyn),
|
||||
convert_node!(from: List<GradientStops>, to: AttributeDyn),
|
||||
convert_node!(from: List<f64>, to: AttributeDyn),
|
||||
convert_node!(from: List<bool>, to: AttributeDyn),
|
||||
convert_node!(from: List<String>, to: AttributeDyn),
|
||||
convert_node!(from: List<DAffine2>, to: AttributeDyn),
|
||||
convert_node!(from: List<BlendMode>, to: AttributeDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: AttributeDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: AttributeDyn),
|
||||
convert_node!(from: List<Artboard>, to: ListDyn),
|
||||
convert_node!(from: List<Graphic>, to: ListDyn),
|
||||
convert_node!(from: List<Vector>, to: ListDyn),
|
||||
convert_node!(from: List<Raster<CPU>>, to: ListDyn),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: ListDyn),
|
||||
convert_node!(from: List<Color>, to: ListDyn),
|
||||
convert_node!(from: List<GradientStops>, to: ListDyn),
|
||||
convert_node!(from: List<f64>, to: ListDyn),
|
||||
convert_node!(from: List<bool>, to: ListDyn),
|
||||
convert_node!(from: List<String>, to: ListDyn),
|
||||
convert_node!(from: List<u8>, to: ListDyn),
|
||||
convert_node!(from: List<NodeId>, to: ListDyn),
|
||||
convert_node!(from: List<DAffine2>, to: ListDyn),
|
||||
convert_node!(from: List<BlendMode>, to: ListDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: ListDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: ListDyn),
|
||||
// Type-erased attribute value conversions for the `Write Attribute` node, so it monomorphizes only over the destination `List` type.
|
||||
convert_node!(from: f64, to: AttributeValueDyn),
|
||||
convert_node!(from: u32, to: AttributeValueDyn),
|
||||
convert_node!(from: u64, to: AttributeValueDyn),
|
||||
convert_node!(from: bool, to: AttributeValueDyn),
|
||||
convert_node!(from: String, to: AttributeValueDyn),
|
||||
convert_node!(from: DVec2, to: AttributeValueDyn),
|
||||
convert_node!(from: DAffine2, to: AttributeValueDyn),
|
||||
convert_node!(from: Color, to: AttributeValueDyn),
|
||||
convert_node!(from: BlendMode, to: AttributeValueDyn),
|
||||
convert_node!(from: graphene_std::vector::style::GradientType, to: AttributeValueDyn),
|
||||
convert_node!(from: graphene_std::vector::style::GradientSpreadMethod, to: AttributeValueDyn),
|
||||
convert_node!(from: List<String>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<NodeId>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Color>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<GradientStops>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Vector>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Raster<CPU>>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Graphic>, to: AttributeValueDyn),
|
||||
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
into_node!(from: &PlatformEditorApi, to: &WgpuExecutor),
|
||||
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: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
|
||||
// =============
|
||||
// MONITOR NODES
|
||||
// =============
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ()]),
|
||||
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>]),
|
||||
@@ -121,207 +43,540 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
#[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<GradientStops>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Image<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => String]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => IVec2]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DVec2]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DAffine2]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => bool]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => f64]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u32]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u64]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => BlendMode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Texture]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<f64>]),
|
||||
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 => List<NodeId>]),
|
||||
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<u8>]),
|
||||
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<graphene_std::vector::style::GradientType>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeDyn]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
|
||||
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 => Graphic]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DocumentNode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::LuminanceCalculation]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlue]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlueAlpha]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::NoiseType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::FractalType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularDistanceFunction]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularReturnType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::DomainWarpType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RelativeAbsolute]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::SelectiveColorChoice]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
|
||||
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 => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => 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<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 => CanvasHandle, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextFeatures]),
|
||||
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 => ()]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
|
||||
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 => Image<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
|
||||
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 => List<NodeId>]),
|
||||
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<u8>]),
|
||||
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<graphene_std::vector::style::GradientType>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
|
||||
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 => CanvasHandle]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f64]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f32]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u32]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u64]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DVec2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => String]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Footprint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi]),
|
||||
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 => Option<f64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Graphic]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlue]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlueAlpha]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::NoiseType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::FractalType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularDistanceFunction]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularReturnType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::DomainWarpType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RelativeAbsolute]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::SelectiveColorChoice]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
|
||||
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>]),
|
||||
];
|
||||
// =============
|
||||
// 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();
|
||||
|
||||
// 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(), *constructor);
|
||||
map.entry(id.clone()).or_default().insert(types.clone().normalize_rank(), *constructor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,14 +586,18 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// 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();
|
||||
}
|
||||
|
||||
map.entry(ProtoNodeIdentifier::with_owned_string(new_name)).or_default().insert(types.clone(), node_constructor);
|
||||
map.entry(ProtoNodeIdentifier::with_owned_string(new_name))
|
||||
.or_default()
|
||||
.insert(types.clone().normalize_rank(), node_constructor);
|
||||
}
|
||||
|
||||
map
|
||||
@@ -357,8 +616,11 @@ mod node_registry_macros {
|
||||
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(stringify!($path)),
|
||||
$identifier,
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
args.reverse();
|
||||
@@ -380,105 +642,5 @@ mod node_registry_macros {
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! into_node {
|
||||
(from: $from:ty, to: $to:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_std::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_std::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
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
macro_rules! convert_node {
|
||||
(from: $from:ty, to: numbers) => {{
|
||||
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = 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, NodeConstructor, NodeIOTypes)> = 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) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let mut args = args.drain(..);
|
||||
let node = graphene_std::ops::ConvertNode::new(
|
||||
graphene_std::any::downcast_node::<Context, $from>(args.next().expect("Convert node did not get first argument")),
|
||||
graphene_std::any::downcast_node::<Context, $convert>(args.next().expect("Convert node did not get converter argument")),
|
||||
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_std::ops::ConvertNode::new(
|
||||
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $convert> + Send>>>::new(),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
||||
);
|
||||
let params = vec![fn_type_fut!(Context, $from), fn_type_fut!(Context, $convert)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use async_node;
|
||||
pub(crate) use convert_node;
|
||||
pub(crate) use into_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;
|
||||
@@ -30,14 +30,20 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
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::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
|
||||
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!(graphene_std::application_io::RenderConfig),
|
||||
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::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!(&PlatformEditorApi)))];
|
||||
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), item!(&PlatformEditorApi)))];
|
||||
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
|
||||
@@ -16,6 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
core-types = { 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;
|
||||
@@ -54,7 +56,7 @@ pub trait GetEditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32;
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ExportFormat {
|
||||
#[default]
|
||||
@@ -62,14 +64,14 @@ pub enum ExportFormat {
|
||||
Raster,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
||||
#[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)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -83,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 {
|
||||
@@ -127,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,414 +0,0 @@
|
||||
use std::cell::UnsafeCell;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{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>>,
|
||||
}
|
||||
|
||||
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,
|
||||
drop_fn: unsafe fn(*mut u8),
|
||||
}
|
||||
|
||||
// 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()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
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;
|
||||
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()?;
|
||||
Some(start)
|
||||
}
|
||||
|
||||
pub fn alloc<T: Send + Sync>(&self, value: T) -> 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, drop_fn: glue::<T> });
|
||||
}
|
||||
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
|
||||
Some((unsafe { &*ptr }, weak))
|
||||
}
|
||||
|
||||
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) })
|
||||
}
|
||||
|
||||
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
|
||||
/// where every handle misses and further allocation is refused.
|
||||
pub fn reset(&mut self) -> bool {
|
||||
let base = self.base();
|
||||
let entries = std::mem::take(self.drops.get_mut().unwrap());
|
||||
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)) }
|
||||
}
|
||||
*self.offset.get_mut() = 0;
|
||||
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<*const 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 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Typed attribute keys.
|
||||
//!
|
||||
//! Each key is a zero-sized marker implementing [`Attr`], which ties the name (the string
|
||||
//! stored in the attribute store) to the Rust value type.
|
||||
//!
|
||||
//! Keys are declared with the [`node_macro::attrs!`] macro: `Name: Type` entries, where
|
||||
//! `namespace { ... }` blocks contribute a `namespace:` name prefix. The key name is
|
||||
//! derived mechanically from the ident (UpperCamel -> snake_case). An optional `= value`
|
||||
//! after the type declares the key's implicit default (see [`Attr::implicit_default`]).
|
||||
|
||||
use crate::Color;
|
||||
use crate::list::NodeIdPath;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub trait Attr {
|
||||
type Value: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static;
|
||||
fn name() -> &'static str;
|
||||
|
||||
/// The value an item without this attribute is considered to have: the value type's `Default`,
|
||||
/// unless the key's `attrs!` declaration overrides it with `= value`.
|
||||
fn implicit_default() -> Self::Value {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
Transform: DAffine2,
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
BlendMode: crate::blending::BlendMode,
|
||||
/// Item's opacity multiplier, composed multiplicatively through nested groups. Affects content clipped to the item.
|
||||
Opacity: f64 = 1.,
|
||||
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
|
||||
OpacityFill: f64 = 1.,
|
||||
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
ClippingMask: bool,
|
||||
/// Byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
Start: u64,
|
||||
/// Byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
End: u64,
|
||||
/// A regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
|
||||
Name: String,
|
||||
/// A JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||
Type: String,
|
||||
/// Artboard's top-left corner in document coordinates.
|
||||
Location: DVec2,
|
||||
/// Artboard's width and height.
|
||||
Dimensions: DVec2,
|
||||
/// Artboard's background fill.
|
||||
Background: Color,
|
||||
/// Whether an artboard clips content to its bounds.
|
||||
Clip: bool,
|
||||
/// Text item's font size in document-space units.
|
||||
FontSize: f64,
|
||||
/// Text item's line height as a ratio of the font size.
|
||||
LineHeight: f64,
|
||||
/// Text item's extra spacing between letters in document-space units.
|
||||
LetterSpacing: f64,
|
||||
/// Text item's maximum line-wrap width in document-space units.
|
||||
MaxWidth: Option<f64>,
|
||||
/// Text item's maximum block height in document-space units, past which lines are not drawn.
|
||||
MaxHeight: Option<f64>,
|
||||
/// Text item's faux-italic letter tilt angle in degrees.
|
||||
LetterTilt: f64,
|
||||
editor {
|
||||
/// 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.
|
||||
LayerPath: NodeIdPath,
|
||||
/// Affine 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.
|
||||
TextFrame: DAffine2,
|
||||
},
|
||||
}
|
||||
@@ -15,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.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,191 +0,0 @@
|
||||
use crate::gpoll::Finality;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::mem::{ManuallyDrop, MaybeUninit};
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
|
||||
const SLOT_EMPTY: u8 = 0;
|
||||
const SLOT_FINAL: u8 = 1;
|
||||
const SLOT_PARTIAL: u8 = 2;
|
||||
|
||||
pub struct FrameTable<T, const CAP: usize> {
|
||||
slots: [FrameSlot<T>; CAP],
|
||||
}
|
||||
|
||||
struct FrameSlot<T> {
|
||||
key: AtomicU64,
|
||||
state: AtomicU8,
|
||||
value: UnsafeCell<MaybeUninit<T>>,
|
||||
}
|
||||
|
||||
pub enum Lookup<'t, T> {
|
||||
Hit(Finality, &'t T),
|
||||
Vacant(VacantSlot<'t, T>),
|
||||
Full,
|
||||
}
|
||||
|
||||
pub struct VacantSlot<'t, T> {
|
||||
slot: &'t FrameSlot<T>,
|
||||
}
|
||||
|
||||
impl<T, const CAP: usize> Default for FrameTable<T, CAP> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const CAP: usize> FrameTable<T, CAP> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: std::array::from_fn(|_| FrameSlot {
|
||||
key: AtomicU64::new(0),
|
||||
state: AtomicU8::new(SLOT_EMPTY),
|
||||
value: UnsafeCell::new(MaybeUninit::uninit()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
|
||||
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
|
||||
let key = if hash == 0 { 1 } else { hash };
|
||||
for probe in 0..CAP {
|
||||
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
|
||||
let stored = slot.key.load(Ordering::Acquire);
|
||||
if stored == key {
|
||||
return match slot.state.load(Ordering::Acquire) {
|
||||
// SAFETY: a published state was stored with Release after the
|
||||
// value write; the Acquire load above ordered that write.
|
||||
SLOT_FINAL => Lookup::Hit(Finality::AllFinal, unsafe { (*slot.value.get()).assume_init_ref() }),
|
||||
SLOT_PARTIAL => Lookup::Hit(Finality::Partial, unsafe { (*slot.value.get()).assume_init_ref() }),
|
||||
_ => Lookup::Full,
|
||||
};
|
||||
}
|
||||
if stored == 0 && slot.key.compare_exchange(0, key, Ordering::AcqRel, Ordering::Acquire).is_ok() {
|
||||
return Lookup::Vacant(VacantSlot { slot });
|
||||
}
|
||||
}
|
||||
Lookup::Full
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
|
||||
fn drop(&mut self) {
|
||||
for slot in &self.slots {
|
||||
if slot.state.load(Ordering::Acquire) != SLOT_EMPTY {
|
||||
// SAFETY: a non-empty state is only ever stored after the value
|
||||
// write in `publish`.
|
||||
unsafe { (*slot.value.get()).assume_init_drop() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'t, T> VacantSlot<'t, T> {
|
||||
pub fn publish(self, value: T, finality: Finality) -> &'t T {
|
||||
let slot = ManuallyDrop::new(self).slot;
|
||||
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
|
||||
// its state is still SLOT_EMPTY, so nobody reads the value yet.
|
||||
let lent = unsafe { &*(*slot.value.get()).write(value) };
|
||||
let state = match finality {
|
||||
Finality::AllFinal => SLOT_FINAL,
|
||||
Finality::Partial => SLOT_PARTIAL,
|
||||
};
|
||||
slot.state.store(state, Ordering::Release);
|
||||
lent
|
||||
}
|
||||
|
||||
pub fn release(self) {
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees the reservation, so an early return or panic between `lookup` and
|
||||
/// `publish` cannot retire the slot for the rest of the table's life.
|
||||
impl<T> Drop for VacantSlot<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
self.slot.key.store(0, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
#[test]
|
||||
fn publish_then_hit_with_finality() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else {
|
||||
panic!("fresh table must be vacant");
|
||||
};
|
||||
assert_eq!(*slot.publish(41, Finality::Partial), 41);
|
||||
let Lookup::Hit(finality, value) = table.lookup(7) else {
|
||||
panic!("published key must hit");
|
||||
};
|
||||
assert_eq!((finality, *value), (Finality::Partial, 41));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn released_slot_is_vacant_again() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
|
||||
slot.release();
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_reservation_frees_the_slot() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
|
||||
drop(slot);
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighboring_hashes_do_not_share_an_entry() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
|
||||
slot.publish(600, Finality::AllFinal);
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_zero_hash_round_trips() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
|
||||
slot.publish(11, Finality::AllFinal);
|
||||
let Lookup::Hit(_, value) = table.lookup(0) else {
|
||||
panic!("the remapped sentinel hash must still hit");
|
||||
};
|
||||
assert_eq!(*value, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_keys_probe_past_collisions_until_full() {
|
||||
let table = FrameTable::<u32, 4>::new();
|
||||
for hash in [2, 4, 6, 8] {
|
||||
let Lookup::Vacant(slot) = table.lookup(hash) else {
|
||||
panic!("hash {hash} should find a vacant slot");
|
||||
};
|
||||
slot.publish(hash as u32, Finality::AllFinal);
|
||||
}
|
||||
assert!(matches!(table.lookup(100), Lookup::Full));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_runs_glue_for_published_values_only() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let table = FrameTable::<Probe, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(1) else { unreachable!() };
|
||||
slot.publish(Probe, Finality::AllFinal);
|
||||
let Lookup::Vacant(reserved_but_unpublished) = table.lookup(2) else { unreachable!() };
|
||||
reserved_but_unpublished.release();
|
||||
drop(table);
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ErrorKind {
|
||||
Node(&'static str),
|
||||
ArenaExhausted,
|
||||
Panic,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[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(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[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),
|
||||
}
|
||||
|
||||
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::Exactly(n), Extent::Exactly(m)) => GPoll::fallback(Extent::Exactly(n.min(m)), "extent mismatch"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[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,26 +1,23 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod arena;
|
||||
pub mod attr;
|
||||
pub mod bounds;
|
||||
pub mod consts;
|
||||
pub mod context;
|
||||
pub mod frame_table;
|
||||
pub mod generic;
|
||||
pub mod gpoll;
|
||||
pub mod list;
|
||||
pub mod math;
|
||||
pub mod memo;
|
||||
pub mod misc;
|
||||
pub mod node;
|
||||
pub mod ops;
|
||||
pub mod registry;
|
||||
pub mod render_complexity;
|
||||
pub mod runtime;
|
||||
pub mod transform;
|
||||
pub mod uuid;
|
||||
pub mod value;
|
||||
|
||||
pub use crate as core_types;
|
||||
pub use attr::Attr;
|
||||
pub use blending::*;
|
||||
pub use color::Color;
|
||||
pub use context::*;
|
||||
@@ -28,11 +25,6 @@ pub use ctor;
|
||||
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_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;
|
||||
pub use no_std_types::blending;
|
||||
|
||||
@@ -1,99 +1,68 @@
|
||||
use crate::attr::{self, Attr};
|
||||
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;
|
||||
|
||||
// =================================================
|
||||
// Standard attribute keys used across the data flow
|
||||
// =================================================
|
||||
// =====================
|
||||
// TYPE: NodeIdPath
|
||||
// =====================
|
||||
|
||||
/// 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";
|
||||
/// `List<NodeId>` 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";
|
||||
/// 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
|
||||
// ===========================
|
||||
|
||||
/// Overrides the type's default value for certain attributes.
|
||||
fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||
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`]).
|
||||
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`attr::implicit_default_value`]).
|
||||
fn pad_with_implicit_default(key: &str, attribute: &mut Box<dyn AnyAttribute>, count: usize) {
|
||||
match implicit_default_value(key) {
|
||||
match attr::implicit_default_value(key) {
|
||||
Some(default) => attribute.push_repeated(&*default, count),
|
||||
None => {
|
||||
for _ in 0..count {
|
||||
@@ -125,6 +94,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>;
|
||||
}
|
||||
@@ -155,6 +131,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)));
|
||||
@@ -361,83 +348,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 {
|
||||
@@ -498,12 +414,18 @@ impl ListDyn {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
/// Returns a reference to the attribute value at the given key and item index, downcast to `U`, if present and matching.
|
||||
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
/// Returns a reference to the attribute value at the given runtime key and item index, downcast to `U`, if present and matching.
|
||||
/// For keys known at compile time use [`Self::attr`]; this variant is for keys only known at runtime (e.g. the attribute nodes).
|
||||
pub fn attribute_dyn<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
self.attributes
|
||||
.iter()
|
||||
.find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<U>() } else { None })
|
||||
}
|
||||
|
||||
/// Returns a reference to the value of the typed attribute at the given item index, if present.
|
||||
pub fn attr<A: Attr>(&self, index: usize) -> Option<&A::Value> {
|
||||
self.attribute_dyn(A::name(), index)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<List<T>> for ListDyn {
|
||||
@@ -576,6 +498,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 {
|
||||
@@ -613,8 +546,8 @@ impl ItemAttributeValues {
|
||||
.find_map(|(existing_key, value)| if existing_key == key { (**value).as_any_mut().downcast_mut::<T>() } else { None })
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the value, inserting a default if it doesn't exist or has the wrong type.
|
||||
pub fn get_or_insert_default_mut<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> &mut T {
|
||||
/// Gets a mutable reference to the value, inserting the provided default if it doesn't exist or has the wrong type.
|
||||
pub fn get_or_insert_with_mut<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str, default: impl FnOnce() -> T) -> &mut T {
|
||||
let needs_insert = match self.0.iter().position(|(existing_key, _)| existing_key == key) {
|
||||
Some(index) => {
|
||||
if (*self.0[index].1).as_any().downcast_ref::<T>().is_some() {
|
||||
@@ -628,7 +561,7 @@ impl ItemAttributeValues {
|
||||
};
|
||||
|
||||
if needs_insert {
|
||||
self.0.push((key.to_string(), Box::new(T::default())));
|
||||
self.0.push((key.to_string(), Box::new(default())));
|
||||
}
|
||||
|
||||
self.get_mut::<T>(key).expect("Attribute was just ensured to exist with correct type")
|
||||
@@ -646,6 +579,11 @@ impl ItemAttributeValues {
|
||||
self.0.iter().map(|(key, _)| key.as_str())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// The `overrides` function can provide custom formatting for specific type.
|
||||
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||
@@ -688,6 +626,35 @@ impl ItemAttributeValues {
|
||||
self.0.push((key.to_string(), value));
|
||||
}
|
||||
}
|
||||
|
||||
// ==================
|
||||
// Typed key variants
|
||||
// ==================
|
||||
|
||||
/// Gets a reference to the value of the typed attribute, if present.
|
||||
pub fn attr<A: Attr>(&self) -> Option<&A::Value> {
|
||||
self.get(A::name())
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the value of the typed attribute, if present.
|
||||
pub fn attr_mut<A: Attr>(&mut self) -> Option<&mut A::Value> {
|
||||
self.get_mut(A::name())
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the value of the typed attribute, inserting the key's default value if absent.
|
||||
pub fn attr_mut_or_insert_default<A: Attr>(&mut self) -> &mut A::Value {
|
||||
self.get_or_insert_with_mut(A::name(), A::implicit_default)
|
||||
}
|
||||
|
||||
/// Inserts the typed attribute's value, replacing any existing entry.
|
||||
pub fn set_attr<A: Attr>(&mut self, value: A::Value) {
|
||||
self.insert(A::name(), value);
|
||||
}
|
||||
|
||||
/// Removes and returns the value of the typed attribute, if present.
|
||||
pub fn remove_attr<A: Attr>(&mut self) -> Option<A::Value> {
|
||||
self.remove(A::name())
|
||||
}
|
||||
}
|
||||
|
||||
// ==========
|
||||
@@ -991,9 +958,9 @@ impl<T> List<T> {
|
||||
self.attributes.keys()
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Attribute-oriented iteration
|
||||
// ============================
|
||||
// =================
|
||||
// Element iteration
|
||||
// =================
|
||||
|
||||
/// Returns an iterator over shared references to all element values.
|
||||
pub fn iter_element_values(&self) -> std::slice::Iter<'_, T> {
|
||||
@@ -1005,28 +972,6 @@ impl<T> List<T> {
|
||||
self.element.iter_mut()
|
||||
}
|
||||
|
||||
/// Returns an iterator over shared references to the values of a typed attribute, or `None` if the attribute doesn't exist or has the wrong type.
|
||||
pub fn iter_attribute_values<U: 'static>(&self, key: &str) -> Option<std::slice::Iter<'_, U>> {
|
||||
self.attributes.get_attribute_slice::<U>(key).map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Returns an iterator over mutable references to the values of a typed attribute attribute, or `None` if the attribute doesn't exist or has the wrong type.
|
||||
pub fn iter_attribute_values_mut<U: 'static>(&mut self, key: &str) -> Option<std::slice::IterMut<'_, U>> {
|
||||
self.attributes.get_attribute_slice_mut::<U>(key).map(|s| s.iter_mut())
|
||||
}
|
||||
|
||||
/// Returns an iterator that yields cloned attribute values for the given key, falling back to `U::default()` for each item if the attribute is missing or has the wrong type.
|
||||
pub fn iter_attribute_values_or_default<U: Clone + Default + 'static>(&self, key: &str) -> impl Iterator<Item = U> + '_ {
|
||||
let slice = self.attributes.get_attribute_slice::<U>(key);
|
||||
let len = self.element.len();
|
||||
(0..len).map(move |i| slice.map_or_else(U::default, |s| s[i].clone()))
|
||||
}
|
||||
|
||||
/// Returns a mutable iterator over a typed attribute, creating the attribute with default values if it doesn't exist or has the wrong type.
|
||||
pub fn iter_attribute_values_mut_or_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> std::slice::IterMut<'_, U> {
|
||||
self.attributes.get_or_create_attribute_slice_mut::<U>(key).iter_mut()
|
||||
}
|
||||
|
||||
// ======================
|
||||
// Indexed element access
|
||||
// ======================
|
||||
@@ -1045,34 +990,12 @@ impl<T> List<T> {
|
||||
// Indexed attribute access
|
||||
// ========================
|
||||
|
||||
/// Returns a shared reference to the attribute value at the given item index and key, if it exists and can be downcast to the requested type.
|
||||
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
/// Returns a shared reference to the attribute value at the given item index and runtime key, if it exists and can be downcast to the requested type.
|
||||
/// For keys known at compile time use [`Self::attr`]; this variant is for keys only known at runtime (e.g. the attribute nodes).
|
||||
pub fn attribute_dyn<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
self.attributes.get_value(key, index)
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value at the given item index and key, or `U::default()` if absent or of a different type.
|
||||
pub fn attribute_cloned_or_default<U: Clone + Default + 'static>(&self, key: &str, index: usize) -> U {
|
||||
self.attributes.get_value::<U>(key, index).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value at the given item index and key, or the provided default if absent or of a different type.
|
||||
pub fn attribute_cloned_or<U: Clone + 'static>(&self, key: &str, index: usize, default: U) -> U {
|
||||
self.attributes.get_value::<U>(key, index).cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Sets the attribute value at the given item index and key, creating the attribute with defaults if it doesn't exist.
|
||||
pub fn set_attribute<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, index: usize, value: U) {
|
||||
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) {
|
||||
@@ -1087,17 +1010,6 @@ impl<T> List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the entire attribute for the given key, if present.
|
||||
pub fn remove_attribute(&mut self, key: &str) {
|
||||
self.attributes.remove_attribute(key);
|
||||
}
|
||||
|
||||
/// Runs the given closure on a mutable reference to the attribute value at the given item index,
|
||||
/// creating the attribute with defaults if it doesn't exist, and returns the closure's result.
|
||||
pub fn with_attribute_mut_or_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static, R, F: FnOnce(&mut U) -> R>(&mut self, key: &str, index: usize, f: F) -> R {
|
||||
f(self.attributes.get_or_insert_default_value::<U>(key, index))
|
||||
}
|
||||
|
||||
/// Returns a debug-formatted display string for the attribute at the given item index and key.
|
||||
pub fn attribute_display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||
self.attributes.display_value(key, index, overrides)
|
||||
@@ -1108,16 +1020,69 @@ impl<T> List<T> {
|
||||
self.attributes.get_any_value(key, index)
|
||||
}
|
||||
|
||||
// ====================
|
||||
// Split borrow helpers
|
||||
// ====================
|
||||
// ==================
|
||||
// Typed key variants
|
||||
// ==================
|
||||
|
||||
/// Returns disjoint mutable references to the element slice and a typed attribute slice, creating the attribute with defaults if it doesn't exist.
|
||||
/// Returns a shared reference to the value of the typed attribute at the given item index, if present.
|
||||
pub fn attr<A: Attr>(&self, index: usize) -> Option<&A::Value> {
|
||||
self.attributes.get_value(A::name(), index)
|
||||
}
|
||||
|
||||
/// Returns a clone of the value of the typed attribute at the given item index, or the key's default value if absent.
|
||||
pub fn attr_cloned_or_default<A: Attr>(&self, index: usize) -> A::Value {
|
||||
self.attr::<A>(index).cloned().unwrap_or_else(A::implicit_default)
|
||||
}
|
||||
|
||||
/// Returns a clone of the value of the typed attribute at the given item index, or the provided default if absent.
|
||||
pub fn attr_cloned_or<A: Attr>(&self, index: usize, default: A::Value) -> A::Value {
|
||||
self.attr::<A>(index).cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Sets the value of the typed attribute at the given item index, creating the attribute with defaults if it doesn't exist.
|
||||
pub fn set_attr<A: Attr>(&mut self, index: usize, value: A::Value) {
|
||||
self.attributes.set_value(A::name(), index, value);
|
||||
}
|
||||
|
||||
/// Removes the entire typed attribute, if present.
|
||||
pub fn remove_attr<A: Attr>(&mut self) {
|
||||
self.attributes.remove_attribute(A::name());
|
||||
}
|
||||
|
||||
/// Runs the given closure on a mutable reference to the value of the typed attribute at the given item index,
|
||||
/// creating the attribute with defaults if it doesn't exist, and returns the closure's result.
|
||||
pub fn with_attr_mut_or_default<A: Attr, R, F: FnOnce(&mut A::Value) -> R>(&mut self, index: usize, f: F) -> R {
|
||||
f(self.attributes.get_or_insert_default_value::<A::Value>(A::name(), index))
|
||||
}
|
||||
|
||||
/// Returns an iterator over shared references to the values of the typed attribute, or `None` if it doesn't exist.
|
||||
pub fn iter_attr_values<A: Attr>(&self) -> Option<std::slice::Iter<'_, A::Value>> {
|
||||
self.attributes.get_attribute_slice::<A::Value>(A::name()).map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Returns an iterator over mutable references to the values of the typed attribute, or `None` if it doesn't exist.
|
||||
pub fn iter_attr_values_mut<A: Attr>(&mut self) -> Option<std::slice::IterMut<'_, A::Value>> {
|
||||
self.attributes.get_attribute_slice_mut::<A::Value>(A::name()).map(|s| s.iter_mut())
|
||||
}
|
||||
|
||||
/// Returns an iterator that yields cloned values of the typed attribute, falling back to the key's default value for each item if the attribute is missing.
|
||||
pub fn iter_attr_values_or_default<A: Attr>(&self) -> impl Iterator<Item = A::Value> + '_ {
|
||||
let slice = self.attributes.get_attribute_slice::<A::Value>(A::name());
|
||||
let len = self.element.len();
|
||||
(0..len).map(move |i| slice.map_or_else(A::implicit_default, |s| s[i].clone()))
|
||||
}
|
||||
|
||||
/// Returns a mutable iterator over the typed attribute, creating the attribute with defaults if it doesn't exist.
|
||||
pub fn iter_attr_values_mut_or_default<A: Attr>(&mut self) -> std::slice::IterMut<'_, A::Value> {
|
||||
self.attributes.get_or_create_attribute_slice_mut::<A::Value>(A::name()).iter_mut()
|
||||
}
|
||||
|
||||
/// Returns disjoint mutable references to the element slice and the typed attribute's slice, creating the attribute with defaults if it doesn't exist.
|
||||
/// This enables simultaneous mutable access to elements and a single attribute without borrowing conflicts.
|
||||
pub fn element_and_attribute_slices_mut<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> (&mut [T], &mut [U]) {
|
||||
pub fn element_and_attr_slices_mut<A: Attr>(&mut self) -> (&mut [T], &mut [A::Value]) {
|
||||
let Self { element, attributes } = self;
|
||||
let attribute_position = attributes.find_or_create_attribute::<U>(key);
|
||||
let attribute = (*attributes.attributes[attribute_position].1).as_any_mut().downcast_mut::<Attribute<U>>().unwrap();
|
||||
let attribute_position = attributes.find_or_create_attribute::<A::Value>(A::name());
|
||||
let attribute = (*attributes.attributes[attribute_position].1).as_any_mut().downcast_mut::<Attribute<A::Value>>().unwrap();
|
||||
(element.as_mut_slice(), &mut attribute.0)
|
||||
}
|
||||
|
||||
@@ -1147,7 +1112,7 @@ impl<T: BoundingBox> BoundingBox for List<T> {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
let mut combined_bounds = None;
|
||||
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attr_values_or_default::<crate::attr::Transform>()) {
|
||||
match element.bounding_box(transform * item_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
|
||||
@@ -1169,7 +1134,7 @@ impl<T: BoundingBox> BoundingBox for List<T> {
|
||||
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)) {
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attr_values_or_default::<crate::attr::Transform>()) {
|
||||
match element.thumbnail_bounding_box(transform * item_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => any_infinite = true,
|
||||
@@ -1241,14 +1206,14 @@ impl<T: PartialEq> PartialEq for List<T> {
|
||||
impl<T> ApplyTransform for List<T> {
|
||||
/// Right-multiplies the modification into each item's transform attribute.
|
||||
fn apply_transform(&mut self, modification: &DAffine2) {
|
||||
for transform in self.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in self.iter_attr_values_mut_or_default::<crate::attr::Transform>() {
|
||||
*transform *= *modification;
|
||||
}
|
||||
}
|
||||
|
||||
/// Left-multiplies the modification into each item's transform attribute.
|
||||
fn left_apply_transform(&mut self, modification: &DAffine2) {
|
||||
for transform in self.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in self.iter_attr_values_mut_or_default::<crate::attr::Transform>() {
|
||||
*transform = *modification * *transform;
|
||||
}
|
||||
}
|
||||
@@ -1280,7 +1245,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,
|
||||
@@ -1292,9 +1257,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1339,53 +1310,93 @@ impl<T> Item<T> {
|
||||
&mut self.attributes
|
||||
}
|
||||
|
||||
/// Returns a reference to the attribute value for the given key, if it exists and is of the requested type.
|
||||
pub fn attribute<U: 'static>(&self, key: &str) -> Option<&U> {
|
||||
self.attributes.get(key)
|
||||
// ======================
|
||||
// Typed attribute access
|
||||
// ======================
|
||||
|
||||
/// Returns a reference to the value of the typed attribute, if present.
|
||||
pub fn attr<A: Attr>(&self) -> Option<&A::Value> {
|
||||
self.attributes.attr::<A>()
|
||||
}
|
||||
|
||||
/// Returns the attribute value for the given key, or the provided default if absent or of a different type.
|
||||
pub fn attribute_or<'a, U: 'static>(&'a self, key: &str, default: &'a U) -> &'a U {
|
||||
self.attribute(key).unwrap_or(default)
|
||||
/// Returns a reference to the value of the typed attribute, or the provided default if absent.
|
||||
pub fn attr_or<'a, A: Attr>(&'a self, default: &'a A::Value) -> &'a A::Value {
|
||||
self.attr::<A>().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value for the given key, or the provided default if absent or of a different type.
|
||||
pub fn attribute_cloned_or<U: Clone + 'static>(&self, key: &str, default: U) -> U {
|
||||
self.attribute(key).cloned().unwrap_or(default)
|
||||
/// Returns a clone of the value of the typed attribute, or the provided default if absent.
|
||||
pub fn attr_cloned_or<A: Attr>(&self, default: A::Value) -> A::Value {
|
||||
self.attr::<A>().cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value for the given key, or `U`'s default value if absent or of a different type.
|
||||
pub fn attribute_cloned_or_default<U: Clone + Default + 'static>(&self, key: &str) -> U {
|
||||
self.attribute(key).cloned().unwrap_or_default()
|
||||
/// Returns a clone of the value of the typed attribute, or the key's default value if absent.
|
||||
pub fn attr_cloned_or_default<A: Attr>(&self) -> A::Value {
|
||||
self.attr::<A>().cloned().unwrap_or_else(A::implicit_default)
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the attribute value for the given key, if it exists and is of the requested type.
|
||||
pub fn attribute_mut<U: 'static>(&mut self, key: &str) -> Option<&mut U> {
|
||||
self.attributes.get_mut(key)
|
||||
/// Returns a mutable reference to the value of the typed attribute, if present.
|
||||
pub fn attr_mut<A: Attr>(&mut self) -> Option<&mut A::Value> {
|
||||
self.attributes.attr_mut::<A>()
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the attribute value for the given key, inserting a default value if absent or of a different type.
|
||||
pub fn attribute_mut_or_insert_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> &mut U {
|
||||
self.attributes.get_or_insert_default_mut(key)
|
||||
/// Returns a mutable reference to the value of the typed attribute, inserting the key's default value if absent.
|
||||
pub fn attr_mut_or_insert_default<A: Attr>(&mut self) -> &mut A::Value {
|
||||
self.attributes.attr_mut_or_insert_default::<A>()
|
||||
}
|
||||
|
||||
/// Sets the attribute value for the given key, replacing any existing entry with the same key.
|
||||
pub fn set_attribute<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, value: U) {
|
||||
self.attributes.insert(key, value);
|
||||
/// Sets the value of the typed attribute, replacing any existing entry.
|
||||
pub fn set_attr<A: Attr>(&mut self, value: A::Value) {
|
||||
self.attributes.set_attr::<A>(value);
|
||||
}
|
||||
|
||||
/// Sets the attribute value for the given key and returns the item, enabling builder-style chaining.
|
||||
pub fn with_attribute<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(mut self, key: impl Into<String>, value: U) -> Self {
|
||||
self.set_attribute(key, value);
|
||||
/// Sets the value of the typed attribute and returns the item, enabling builder-style chaining.
|
||||
pub fn with_attr<A: Attr>(mut self, value: A::Value) -> Self {
|
||||
self.set_attr::<A>(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Removes and returns the attribute value for the given key, if it exists and is of the requested type.
|
||||
pub fn remove_attribute<U: 'static>(&mut self, key: &str) -> Option<U> {
|
||||
self.attributes.remove(key)
|
||||
/// Removes and returns the value of the typed attribute, if present.
|
||||
pub fn remove_attr<A: Attr>(&mut self) -> Option<A::Value> {
|
||||
self.attributes.remove_attr::<A>()
|
||||
}
|
||||
}
|
||||
|
||||
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.attr_mut_or_insert_default::<crate::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.attr_mut_or_insert_default::<crate::attr::Transform>();
|
||||
*transform = *modification * *transform;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: StaticTypeSized> StaticType for Item<T> {
|
||||
type Static = Item<T::Static>;
|
||||
}
|
||||
|
||||
// ===========
|
||||
// ItemIter<T>
|
||||
// ===========
|
||||
@@ -1422,6 +1433,7 @@ impl<T> DoubleEndedIterator for ItemIter<T> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::attr;
|
||||
|
||||
// An item that doesn't set opacity must read as fully opaque even once a sibling introduces the
|
||||
// opacity attribute, otherwise the dense store pads it with f64's `0.` default and it vanishes.
|
||||
@@ -1430,29 +1442,76 @@ mod tests {
|
||||
// Collecting items (the path Boolean Operation takes when merging operands)
|
||||
let mut collected = List::<()>::new();
|
||||
collected.push(Item::new_from_element(()));
|
||||
collected.push(Item::new_from_element(()).with_attribute(ATTR_OPACITY, 1_f64));
|
||||
assert_eq!(collected.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 1.);
|
||||
collected.push(Item::new_from_element(()).with_attr::<attr::Opacity>(1.));
|
||||
assert_eq!(collected.attr::<attr::Opacity>(0), Some(&1.));
|
||||
|
||||
// Extending one list with another
|
||||
let mut base = List::<()>::new();
|
||||
base.push(Item::new_from_element(()));
|
||||
let mut tail = List::<()>::new();
|
||||
tail.push(Item::new_from_element(()).with_attribute(ATTR_OPACITY_FILL, 1_f64));
|
||||
tail.push(Item::new_from_element(()).with_attr::<attr::OpacityFill>(1.));
|
||||
base.extend(tail);
|
||||
assert_eq!(base.attribute_cloned_or_default::<f64>(ATTR_OPACITY_FILL, 0), 1.);
|
||||
assert_eq!(base.attr::<attr::OpacityFill>(0), Some(&1.));
|
||||
|
||||
// Setting one item's opacity leaves the others opaque, not transparent
|
||||
let mut indexed = List::<()>::new();
|
||||
indexed.push(Item::new_from_element(()));
|
||||
indexed.push(Item::new_from_element(()));
|
||||
indexed.set_attribute(ATTR_OPACITY, 1, 0.5_f64);
|
||||
assert_eq!(indexed.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 1.);
|
||||
assert_eq!(indexed.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 1), 0.5);
|
||||
indexed.set_attr::<attr::Opacity>(1, 0.5);
|
||||
assert_eq!(indexed.attr::<attr::Opacity>(0), Some(&1.));
|
||||
assert_eq!(indexed.attr::<attr::Opacity>(1), Some(&0.5));
|
||||
|
||||
// A non-opacity numeric attribute still falls back to its type default
|
||||
// A non-opacity numeric attribute still pads with its type default
|
||||
let mut other = List::<()>::new();
|
||||
other.push(Item::new_from_element(()));
|
||||
other.push(Item::new_from_element(()).with_attribute(ATTR_START, 5_u64));
|
||||
assert_eq!(other.attribute_cloned_or_default::<u64>(ATTR_START, 0), 0);
|
||||
other.push(Item::new_from_element(()).with_attr::<attr::Start>(5));
|
||||
assert_eq!(other.attr::<attr::Start>(0), Some(&0));
|
||||
}
|
||||
|
||||
// The typed keys must resolve to the same names as the string constants, and the typed
|
||||
// and string-keyed accessors must hit the same storage.
|
||||
#[test]
|
||||
fn typed_attribute_keys() {
|
||||
assert_eq!(attr::Transform::name(), "transform");
|
||||
assert_eq!(attr::BlendMode::name(), "blend_mode");
|
||||
assert_eq!(attr::Opacity::name(), "opacity");
|
||||
assert_eq!(attr::OpacityFill::name(), "opacity_fill");
|
||||
assert_eq!(attr::ClippingMask::name(), "clipping_mask");
|
||||
assert_eq!(attr::editor::LayerPath::name(), "editor:layer_path");
|
||||
assert_eq!(attr::editor::TextFrame::name(), "editor:text_frame");
|
||||
assert_eq!(attr::Start::name(), "start");
|
||||
assert_eq!(attr::End::name(), "end");
|
||||
assert_eq!(attr::Name::name(), "name");
|
||||
assert_eq!(attr::Type::name(), "type");
|
||||
assert_eq!(attr::Location::name(), "location");
|
||||
assert_eq!(attr::Dimensions::name(), "dimensions");
|
||||
assert_eq!(attr::Background::name(), "background");
|
||||
assert_eq!(attr::Clip::name(), "clip");
|
||||
assert_eq!(attr::FontSize::name(), "font_size");
|
||||
assert_eq!(attr::LineHeight::name(), "line_height");
|
||||
assert_eq!(attr::LetterSpacing::name(), "letter_spacing");
|
||||
assert_eq!(attr::MaxWidth::name(), "max_width");
|
||||
assert_eq!(attr::MaxHeight::name(), "max_height");
|
||||
assert_eq!(attr::LetterTilt::name(), "letter_tilt");
|
||||
|
||||
// Typed writes are visible through dynamic string reads and vice versa
|
||||
let mut item = Item::new_from_element(());
|
||||
item.set_attr::<attr::Opacity>(0.5);
|
||||
assert_eq!(item.attributes().get::<f64>("opacity"), Some(&0.5));
|
||||
item.attributes_mut().insert("start", 5_u64);
|
||||
assert_eq!(item.attr::<attr::Start>(), Some(&5));
|
||||
|
||||
// A missing attribute reads as the key's declared default
|
||||
let empty = Item::new_from_element(());
|
||||
assert_eq!(empty.attr_cloned_or_default::<attr::Opacity>(), 1.);
|
||||
assert_eq!(empty.attr_cloned_or_default::<attr::Start>(), 0);
|
||||
|
||||
// The generated implicit-default lookup drives dense-store padding
|
||||
let mut list = List::<()>::new();
|
||||
list.push(Item::new_from_element(()));
|
||||
list.push(Item::new_from_element(()));
|
||||
list.set_attr::<attr::Opacity>(1, 0.5);
|
||||
assert_eq!(list.attr_cloned_or_default::<attr::Opacity>(0), 1.);
|
||||
assert_eq!(list.attr_cloned_or_default::<attr::Opacity>(1), 0.5);
|
||||
}
|
||||
}
|
||||
@@ -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,424 +0,0 @@
|
||||
use crate::context::InjectIndex;
|
||||
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt};
|
||||
use std::cell::Cell;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum BatchStatus<'a, T> {
|
||||
Lent(&'a [T], Finality),
|
||||
Filled(FilledBatch<'a, T>, Finality),
|
||||
Pending,
|
||||
Error(GraphError),
|
||||
NeedBuffer,
|
||||
InvalidRange,
|
||||
}
|
||||
|
||||
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
|
||||
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
|
||||
#[derive(Debug)]
|
||||
pub struct FilledBatch<'a, T> {
|
||||
values: &'a mut [T],
|
||||
}
|
||||
|
||||
impl<'a, T> FilledBatch<'a, T> {
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
|
||||
Self {
|
||||
values: unsafe { assume_init_prefix_mut(scratch, len) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn values(&self) -> &[T] {
|
||||
self.values
|
||||
}
|
||||
|
||||
pub fn into_values(self) -> &'a mut [T] {
|
||||
let mut guard = std::mem::ManuallyDrop::new(self);
|
||||
std::mem::take(&mut guard.values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for FilledBatch<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: every lane was initialized when the guard was built and none has
|
||||
// been moved out, since `into_values` consumes the guard instead.
|
||||
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
pub unsafe fn assume_init_prefix_mut<T>(scratch: &mut [MaybeUninit<T>], len: usize) -> &mut [T] {
|
||||
debug_assert!(len <= scratch.len());
|
||||
unsafe { std::slice::from_raw_parts_mut(scratch.as_mut_ptr().cast::<T>(), len) }
|
||||
}
|
||||
|
||||
pub trait Node<Input> {
|
||||
type Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
|
||||
|
||||
fn extent(&self, _input: &Input) -> GPoll<Extent> {
|
||||
GPoll::Final(Extent::Free)
|
||||
}
|
||||
|
||||
/// Introspection access to node-resident records; `None` for ordinary nodes.
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
where
|
||||
Input: InjectIndex + Copy,
|
||||
{
|
||||
let Some(scratch) = scratch else {
|
||||
return BatchStatus::NeedBuffer;
|
||||
};
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
if scratch.len() < len {
|
||||
return BatchStatus::InvalidRange;
|
||||
}
|
||||
let mut local = *input;
|
||||
let mut finality = Finality::AllFinal;
|
||||
for offset in 0..len {
|
||||
local.set_index(range.start + offset as u64);
|
||||
let abort = match self.eval(&local) {
|
||||
GPoll::Final(value) => {
|
||||
scratch[offset].write(value);
|
||||
None
|
||||
}
|
||||
GPoll::Partial(value) => {
|
||||
scratch[offset].write(value);
|
||||
finality = Finality::Partial;
|
||||
None
|
||||
}
|
||||
GPoll::Pending => Some(BatchStatus::Pending),
|
||||
GPoll::Fallback(boxed) => Some(BatchStatus::Error(boxed.1)),
|
||||
GPoll::Error(e) => Some(BatchStatus::Error(*e)),
|
||||
};
|
||||
if let Some(status) = abort {
|
||||
for written in scratch[..offset].iter_mut() {
|
||||
// SAFETY: every lane before `offset` was written by this loop.
|
||||
unsafe { written.assume_init_drop() };
|
||||
}
|
||||
return status;
|
||||
}
|
||||
}
|
||||
// SAFETY: all `len` lanes were written by the loop above.
|
||||
BatchStatus::Filled(unsafe { FilledBatch::new(scratch, len) }, finality)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for &N
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
where
|
||||
Input: InjectIndex + Copy,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for Box<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
where
|
||||
Input: InjectIndex + Copy,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for std::sync::Arc<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
where
|
||||
Input: InjectIndex + Copy,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn no_partial() -> Self {
|
||||
Self { no_partial: true, ..Self::new() }
|
||||
}
|
||||
|
||||
pub fn eval_input<Input, N: Node<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
|
||||
match node.eval(input) {
|
||||
GPoll::Final(value) => Ok(value),
|
||||
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
|
||||
GPoll::Partial(value) => {
|
||||
self.finality.set(Finality::Partial);
|
||||
Ok(value)
|
||||
}
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
let first = self.error.take();
|
||||
self.error.set(first.or(Some(error.traced(input_index))));
|
||||
Ok(value)
|
||||
}
|
||||
GPoll::Pending => Err(Interrupt::Pending),
|
||||
GPoll::Error(mut error) => {
|
||||
error.trace.push(input_index);
|
||||
Err(Interrupt::Error(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
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, N> {
|
||||
node: &'a N,
|
||||
cell: &'a StatusCell,
|
||||
input_index: usize,
|
||||
}
|
||||
|
||||
impl<'a, N> LazyInput<'a, N> {
|
||||
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize) -> Self {
|
||||
Self { node, cell, input_index }
|
||||
}
|
||||
|
||||
pub fn eval<Input>(&self, ctx: &Input) -> Result<N::Output, Interrupt>
|
||||
where
|
||||
N: Node<Input>,
|
||||
{
|
||||
self.cell.eval_input(self.input_index, self.node, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TestInput {
|
||||
index: u64,
|
||||
}
|
||||
|
||||
impl InjectIndex for TestInput {
|
||||
fn set_index(&mut self, index: u64) {
|
||||
self.index = index;
|
||||
}
|
||||
}
|
||||
|
||||
struct Double;
|
||||
|
||||
impl Node<TestInput> for Double {
|
||||
type Output = u64;
|
||||
|
||||
fn eval(&self, input: &TestInput) -> GPoll<u64> {
|
||||
GPoll::Final(input.index * 2)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_loop_fills_scratch_per_lane() {
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = Double.eval_batch(&input, 2..6, Some(&mut scratch));
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes.values(), &[4, 6, 8, 10]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_filled_batch_reclaims_every_lane() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
#[derive(Clone)]
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
struct Probes;
|
||||
impl Node<TestInput> for Probes {
|
||||
type Output = Probe;
|
||||
|
||||
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
|
||||
GPoll::Final(Probe)
|
||||
}
|
||||
}
|
||||
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 3];
|
||||
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Filled(..)));
|
||||
drop(status);
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_without_scratch_requests_a_buffer() {
|
||||
let input = TestInput { index: 0 };
|
||||
assert!(matches!(Double.eval_batch(&input, 0..4, None), BatchStatus::NeedBuffer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undersized_scratch_is_an_invalid_range() {
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 2];
|
||||
assert!(matches!(Double.eval_batch(&input, 0..4, Some(&mut scratch)), BatchStatus::InvalidRange));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_lane_downgrades_batch_finality() {
|
||||
struct PartialAtThree;
|
||||
impl Node<TestInput> for PartialAtThree {
|
||||
type Output = u64;
|
||||
fn eval(&self, input: &TestInput) -> GPoll<u64> {
|
||||
match input.index {
|
||||
3 => GPoll::Partial(input.index),
|
||||
index => GPoll::Final(index),
|
||||
}
|
||||
}
|
||||
}
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = PartialAtThree.eval_batch(&input, 0..4, Some(&mut scratch));
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes.values(), &[0, 1, 2, 3]);
|
||||
assert_eq!(finality, Finality::Partial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abort_drops_already_written_lanes() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
struct PendingAtTwo;
|
||||
impl Node<TestInput> for PendingAtTwo {
|
||||
type Output = Probe;
|
||||
fn eval(&self, input: &TestInput) -> GPoll<Probe> {
|
||||
match input.index {
|
||||
2 => GPoll::Pending,
|
||||
_ => GPoll::Final(Probe),
|
||||
}
|
||||
}
|
||||
}
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = PendingAtTwo.eval_batch(&input, 0..4, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Pending));
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trait_is_object_safe_across_erased_edges() {
|
||||
let erased: Box<dyn Node<TestInput, Output = u64>> = Box::new(Double);
|
||||
let input = TestInput { index: 21 };
|
||||
assert_eq!(erased.eval(&input), GPoll::Final(42));
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 2];
|
||||
let status = erased.eval_batch(&input, 0..2, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Filled(_, Finality::AllFinal)));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
use crate::Node;
|
||||
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||
use crate::transform::Footprint;
|
||||
use glam::DVec2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -55,71 +53,12 @@ impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ListConvert<U> {
|
||||
fn convert_item(self) -> U;
|
||||
}
|
||||
|
||||
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
async 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> {
|
||||
async 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 {
|
||||
async 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> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Convert<DVec2, ()> for DVec2 {
|
||||
async 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 {
|
||||
async 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) => {
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
use crate::SourceId;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + 'static>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type DynRuntime = dyn Runtime + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynRuntime = dyn Runtime;
|
||||
|
||||
pub trait Runtime {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RuntimeHandle(pub Arc<DynRuntime>);
|
||||
|
||||
// SAFETY: wasm is single threaded, so the handle never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for RuntimeHandle {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for RuntimeHandle {}
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
fn cache_hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
|
||||
}
|
||||
|
||||
pub trait Spawner {
|
||||
fn spawn(&self, task: SourceFuture);
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type DynSpawner = dyn Spawner + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynSpawner = dyn Spawner;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type DynNotifier = dyn Fn() + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynNotifier = dyn Fn();
|
||||
|
||||
impl<S: Spawner + ?Sized> Spawner for Box<S> {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
(**self).spawn(task)
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropped tasks never complete.
|
||||
pub struct NoopSpawner;
|
||||
|
||||
impl Spawner for NoopSpawner {
|
||||
fn spawn(&self, _task: SourceFuture) {
|
||||
log::warn!("async source spawned before a host spawner is wired; the task is dropped");
|
||||
}
|
||||
}
|
||||
|
||||
pub type DynGraphRuntime = GraphRuntime<Box<DynSpawner>>;
|
||||
|
||||
impl Default for RuntimeHandle {
|
||||
fn default() -> Self {
|
||||
Self(Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>)))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphRuntime<S> {
|
||||
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
|
||||
dirty: Arc<AtomicBool>,
|
||||
notifier: Arc<Mutex<Arc<DynNotifier>>>,
|
||||
spawner: S,
|
||||
}
|
||||
|
||||
// SAFETY: wasm is single threaded, so the runtime never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Send for GraphRuntime<S> {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Sync for GraphRuntime<S> {}
|
||||
|
||||
impl<S> GraphRuntime<S> {
|
||||
pub fn new(spawner: S) -> Self {
|
||||
Self {
|
||||
generations: Arc::default(),
|
||||
dirty: Arc::default(),
|
||||
notifier: Arc::new(Mutex::new(Arc::new(|| {}))),
|
||||
spawner,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_notifier(&self, notifier: Arc<DynNotifier>) {
|
||||
*self.notifier.lock().unwrap_or_else(PoisonError::into_inner) = notifier;
|
||||
}
|
||||
|
||||
pub fn retain_sources(&self, live: &[SourceId]) {
|
||||
let mut generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
for source in live {
|
||||
generations.entry(*source).or_insert(0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Vec<(SourceId, u64)> {
|
||||
let generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
|
||||
snapshot.sort_unstable();
|
||||
snapshot
|
||||
}
|
||||
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.dirty.swap(false, Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn spawner(&self) -> &S {
|
||||
&self.spawner
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Spawner> Runtime for GraphRuntime<S> {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) {
|
||||
let generations = Arc::clone(&self.generations);
|
||||
let dirty = Arc::clone(&self.dirty);
|
||||
let notifier = Arc::clone(&self.notifier);
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
future.await;
|
||||
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(generation) = generations.get_mut(&source) {
|
||||
*generation += 1;
|
||||
dirty.store(true, Ordering::Release);
|
||||
drop(generations);
|
||||
let notifier = Arc::clone(¬ifier.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
notifier();
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -217,6 +217,23 @@ impl From<()> for Footprint {
|
||||
}
|
||||
}
|
||||
|
||||
/// Consumes an item's `transform` attribute by baking it into the underlying value itself.
|
||||
pub trait BakeTransform {
|
||||
fn bake_transform(&mut self, transform: &DAffine2);
|
||||
}
|
||||
|
||||
impl BakeTransform for DAffine2 {
|
||||
fn bake_transform(&mut self, transform: &DAffine2) {
|
||||
*self = *transform * *self;
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeTransform for DVec2 {
|
||||
fn bake_transform(&mut self, transform: &DAffine2) {
|
||||
*self = transform.transform_point2(*self);
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ApplyTransform {
|
||||
fn apply_transform(&mut self, modification: &DAffine2);
|
||||
fn left_apply_transform(&mut self, modification: &DAffine2);
|
||||
|
||||
@@ -52,8 +52,48 @@ macro_rules! generic {
|
||||
($type:ty) => {{ $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) }};
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of an `Item` holding the given element type, e.g. `item!(f64)` is the type of an `Item<f64>`.
|
||||
/// The two-argument form tags the element descriptor with an alias, preserving the source spelling for widget dispatch.
|
||||
#[macro_export]
|
||||
macro_rules! item {
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Item(Box::new($crate::item!($inner)))
|
||||
};
|
||||
($element:ty) => {
|
||||
$crate::Type::Item(Box::new($crate::concrete!($element)))
|
||||
};
|
||||
($element:ty, $alias:ty) => {
|
||||
$crate::Type::Item(Box::new($crate::concrete!($element, $alias)))
|
||||
};
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of a `List` holding the given element type, e.g. `list!(f64)` is the type of a `List<f64>`.
|
||||
#[macro_export]
|
||||
macro_rules! list {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::List(Box::new($crate::list!($inner)))
|
||||
};
|
||||
($element:ty) => {
|
||||
$crate::Type::List(Box::new($crate::concrete!($element)))
|
||||
};
|
||||
}
|
||||
|
||||
// The `List<...>`/`Item<...>` rules must appear before the generic `$type:ty` rules, and in each macro that sees the literal tokens,
|
||||
// because a type captured as `ty` becomes opaque to any inner macro's ranked pattern
|
||||
#[macro_export]
|
||||
macro_rules! future {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Future(Box::new($crate::list!($inner)))
|
||||
};
|
||||
(List<$inner:ty>, $name:ty) => {
|
||||
$crate::Type::Future(Box::new($crate::list!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Future(Box::new($crate::item!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>, $name:ty) => {
|
||||
$crate::Type::Future(Box::new($crate::item!($inner, $name)))
|
||||
};
|
||||
($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }};
|
||||
($type:ty, $name:ty) => {
|
||||
$crate::Type::Future(Box::new(concrete!($type, $name)))
|
||||
@@ -62,9 +102,27 @@ macro_rules! future {
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! fn_type {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::list!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::item!($inner)))
|
||||
};
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner, $inner)))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner)))
|
||||
};
|
||||
($in_type:ty, $type:ty, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type, $outname)))
|
||||
};
|
||||
@@ -74,9 +132,27 @@ macro_rules! fn_type {
|
||||
}
|
||||
#[macro_export]
|
||||
macro_rules! fn_type_fut {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
|
||||
};
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner, $inner)))))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
|
||||
};
|
||||
($in_type:ty, $type:ty, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type, $outname)))
|
||||
};
|
||||
@@ -99,6 +175,15 @@ impl NodeIOTypes {
|
||||
Self { call_argument, return_value, inputs }
|
||||
}
|
||||
|
||||
/// Applies [`Type::normalize_rank`] to every type in the signature.
|
||||
pub fn normalize_rank(self) -> Self {
|
||||
Self {
|
||||
call_argument: self.call_argument.normalize_rank(),
|
||||
return_value: self.return_value.normalize_rank(),
|
||||
inputs: self.inputs.into_iter().map(Type::normalize_rank).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn empty() -> Self {
|
||||
let tds1 = TypeDescriptor {
|
||||
id: None,
|
||||
@@ -235,7 +320,10 @@ pub enum Type {
|
||||
Fn(Box<Type>, Box<Type>),
|
||||
/// Represents a future which promises to return the inner type.
|
||||
Future(Box<Type>),
|
||||
Ref(Box<Type>),
|
||||
/// Represents a recursive [Type] allowing nested levels of types to represent the type of an Item<T>.
|
||||
Item(Box<Type>),
|
||||
/// Represents a list of this recursive [Type] allowing nested levels of types to represent the type of a List<T>.
|
||||
List(Box<Type>),
|
||||
}
|
||||
|
||||
impl Default for Type {
|
||||
@@ -309,7 +397,8 @@ impl Type {
|
||||
Self::Concrete(ty) => Some(ty.size),
|
||||
Self::Fn(_, _) => None,
|
||||
Self::Future(_) => None,
|
||||
Self::Ref(_) => None,
|
||||
Self::Item(_) => None,
|
||||
Self::List(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,7 +408,8 @@ impl Type {
|
||||
Self::Concrete(ty) => Some(ty.align),
|
||||
Self::Fn(_, _) => None,
|
||||
Self::Future(_) => None,
|
||||
Self::Ref(_) => None,
|
||||
Self::Item(_) => None,
|
||||
Self::List(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,7 +419,8 @@ impl Type {
|
||||
Self::Concrete(_) => self,
|
||||
Self::Fn(_, output) => output.nested_type(),
|
||||
Self::Future(output) => output.nested_type(),
|
||||
Self::Ref(inner) => inner.nested_type(),
|
||||
Self::Item(_) => self,
|
||||
Self::List(_) => self,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +433,8 @@ impl Type {
|
||||
Self::Concrete(_) => None,
|
||||
Self::Fn(_, output) => output.replace_nested(f),
|
||||
Self::Future(output) => output.replace_nested(f),
|
||||
Self::Ref(inner) => inner.replace_nested(f),
|
||||
Self::Item(_) => None,
|
||||
Self::List(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,7 +444,62 @@ impl Type {
|
||||
Type::Concrete(ty) => simplify_identifier_name(&ty.name),
|
||||
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
|
||||
Type::Future(ty) => ty.identifier_name(),
|
||||
Type::Ref(ty) => ty.identifier_name(),
|
||||
Type::Item(element) => element.identifier_name(),
|
||||
Type::List(element) => format!("{}[]", element.identifier_name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of a `List` holding elements of the given type, the expression-position counterpart of [`list!`].
|
||||
pub fn list_of(element: Type) -> Type {
|
||||
Type::List(Box::new(element))
|
||||
}
|
||||
|
||||
/// The element type if this is a rank-1 `List` wire type.
|
||||
pub fn list_element(&self) -> Option<&Type> {
|
||||
match self {
|
||||
Type::List(element) => Some(element),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The element name if this is the type of an `Item<Bundle<X>>` cell carrying a whole list, e.g. `f64` from `Item<Bundle<f64>>`.
|
||||
/// The `Bundle` layer stays name-encoded inside the structural `Item` since it has no structural variant.
|
||||
pub fn bundle_element_name(&self) -> Option<&str> {
|
||||
let Type::Item(element) = self else { return None };
|
||||
let Type::Concrete(descriptor) = element.as_ref() else { return None };
|
||||
descriptor.name.strip_prefix("core_types::list::Bundle<")?.strip_suffix('>')
|
||||
}
|
||||
|
||||
/// Converts a name-encoded `List` or `Item` concrete type into its structural form, recursively.
|
||||
/// Structurally-built types pass through unchanged, so sources which cannot construct ranked types
|
||||
/// (reflection and opaque macro captures) converge with macro-built ones at this single point.
|
||||
pub fn normalize_rank(self) -> Type {
|
||||
fn parse_element(element_name: &str) -> Type {
|
||||
let element = Type::Concrete(TypeDescriptor {
|
||||
id: None,
|
||||
name: Cow::Owned(element_name.to_string()),
|
||||
alias: None,
|
||||
size: 0,
|
||||
align: 0,
|
||||
});
|
||||
element.normalize_rank()
|
||||
}
|
||||
|
||||
match self {
|
||||
Type::Concrete(descriptor) => {
|
||||
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::List<").and_then(|rest| rest.strip_suffix('>')) {
|
||||
return Type::List(Box::new(parse_element(element_name)));
|
||||
}
|
||||
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::Item<").and_then(|rest| rest.strip_suffix('>')) {
|
||||
return Type::Item(Box::new(parse_element(element_name)));
|
||||
}
|
||||
Type::Concrete(descriptor)
|
||||
}
|
||||
Type::Fn(input, output) => Type::Fn(Box::new(input.normalize_rank()), Box::new(output.normalize_rank())),
|
||||
Type::Future(inner) => Type::Future(Box::new(inner.normalize_rank())),
|
||||
Type::Item(element) => Type::Item(Box::new(element.normalize_rank())),
|
||||
Type::List(element) => Type::List(Box::new(element.normalize_rank())),
|
||||
Type::Generic(_) => self,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -377,12 +524,13 @@ pub fn make_type_user_readable(ty: &str) -> String {
|
||||
.replace("UVec2", "Vec2")
|
||||
.replace("&str", "String");
|
||||
|
||||
rewrite_list_as_array_brackets(&ty)
|
||||
rewrite_ranked_type_wrappers(&ty)
|
||||
}
|
||||
|
||||
/// Rewrites `List<T>` as `T[]`. Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
|
||||
/// Respects word boundaries so unrelated identifiers that happen to end in `List` are not affected.
|
||||
fn rewrite_list_as_array_brackets(input: &str) -> String {
|
||||
/// Rewrites `List<T>` and the whole-collection `Bundle<T>` as `T[]`, and unwraps `Item<T>` to `T`, so ranked wires read as their element type.
|
||||
/// Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
|
||||
/// Respects word boundaries so unrelated identifiers that happen to end in `List` or `Item` are not affected.
|
||||
fn rewrite_ranked_type_wrappers(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut result = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
@@ -393,12 +541,31 @@ fn rewrite_list_as_array_brackets(input: &str) -> String {
|
||||
let inner_start = i + b"List<".len();
|
||||
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
|
||||
let inner = &input[inner_start..close];
|
||||
result.push_str(&rewrite_list_as_array_brackets(inner));
|
||||
result.push_str(&rewrite_ranked_type_wrappers(inner));
|
||||
result.push_str("[]");
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if at_word_boundary && bytes[i..].starts_with(b"Bundle<") {
|
||||
let inner_start = i + b"Bundle<".len();
|
||||
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
|
||||
let inner = &input[inner_start..close];
|
||||
result.push_str(&rewrite_ranked_type_wrappers(inner));
|
||||
result.push_str("[]");
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if at_word_boundary && bytes[i..].starts_with(b"Item<") {
|
||||
let inner_start = i + b"Item<".len();
|
||||
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
|
||||
let inner = &input[inner_start..close];
|
||||
result.push_str(&rewrite_ranked_type_wrappers(inner));
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if bytes[i].is_ascii() {
|
||||
result.push(bytes[i] as char);
|
||||
i += 1;
|
||||
@@ -447,7 +614,8 @@ impl std::fmt::Display for Type {
|
||||
Type::Concrete(ty) => write!(f, "{ty}"),
|
||||
Type::Fn(_, return_value) => write!(f, "{return_value}"),
|
||||
Type::Future(ty) => write!(f, "{ty}"),
|
||||
Type::Ref(ty) => write!(f, "{ty}"),
|
||||
Type::Item(element) => write!(f, "{element}"),
|
||||
Type::List(element) => write!(f, "{element}[]"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::Node;
|
||||
use crate::list::Item;
|
||||
use crate::registry::DynFuture;
|
||||
use crate::{Node, WasmNotSend};
|
||||
use std::cell::{Cell, RefCell, RefMut};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -110,6 +112,26 @@ impl<T: Clone> From<T> for ClonedNode<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Yields a precomputed `Item<T>` as a ready future, ignoring its input context.
|
||||
/// Generated list-content variants feed each already-evaluated content slot through this so the kernel's own
|
||||
/// context modifications become no-ops (the slot was evaluated once, up front, at the ambient footprint).
|
||||
pub struct PrecomputedItemNode<T>(pub Item<T>);
|
||||
|
||||
impl<'i, T: Clone + WasmNotSend + 'i, I: 'i> Node<'i, I> for PrecomputedItemNode<T> {
|
||||
type Output = DynFuture<'i, Item<T>>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
let item = self.0.clone();
|
||||
Box::pin(async move { item })
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PrecomputedItemNode<T> {
|
||||
pub const fn new(item: Item<T>) -> Self {
|
||||
Self(item)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
/// The DebugClonedNode logs every time it is evaluated.
|
||||
/// This is useful for debugging.
|
||||
|
||||
@@ -57,6 +57,7 @@ impl_via_hash! {
|
||||
bool, char,
|
||||
u8, u16, u32, u64, u128, usize,
|
||||
i8, i16, i32, i64, i128, isize,
|
||||
core::time::Duration,
|
||||
// glam integer vector types have Hash
|
||||
glam::UVec2, glam::UVec3, glam::UVec4,
|
||||
glam::IVec2, glam::IVec3, glam::IVec4,
|
||||
@@ -68,7 +69,6 @@ impl_via_hash! {
|
||||
#[cfg(feature = "std")]
|
||||
impl_via_hash! {
|
||||
String,
|
||||
core::time::Duration,
|
||||
}
|
||||
|
||||
impl<'a> CacheHash for std::borrow::Cow<'a, str> {
|
||||
@@ -236,142 +236,3 @@ impl_tuple!(A, B, C);
|
||||
impl_tuple!(A, B, C, D);
|
||||
impl_tuple!(A, B, C, D, E);
|
||||
impl_tuple!(A, B, C, D, E, F);
|
||||
|
||||
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
|
||||
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
|
||||
/// a real wrong-value memo hit in the prototype.
|
||||
#[derive(Clone)]
|
||||
pub struct FxHasher64 {
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
const K: u64 = 0xf1357aea2e62a9c5;
|
||||
const SEED: u64 = 0x517cc1b727220a95;
|
||||
const SEED1: u64 = 0x243f6a8885a308d3;
|
||||
const SEED2: u64 = 0x13198a2e03707344;
|
||||
const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0;
|
||||
|
||||
impl Default for FxHasher64 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FxHasher64 {
|
||||
pub const fn new() -> Self {
|
||||
Self { hash: SEED }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn add_to_hash(&mut self, i: u64) {
|
||||
self.hash = self.hash.wrapping_add(i).wrapping_mul(K);
|
||||
}
|
||||
}
|
||||
|
||||
impl core::hash::Hasher for FxHasher64 {
|
||||
#[inline]
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
self.add_to_hash(hash_bytes(bytes));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u8(&mut self, i: u8) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u16(&mut self, i: u16) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u32(&mut self, i: u32) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u64(&mut self, i: u64) {
|
||||
self.add_to_hash(i);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u128(&mut self, i: u128) {
|
||||
self.add_to_hash(i as u64);
|
||||
self.add_to_hash((i >> 64) as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_usize(&mut self, i: usize) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn finish(&self) -> u64 {
|
||||
self.hash.rotate_left(26)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn multiply_mix(x: u64, y: u64) -> u64 {
|
||||
let full = (x as u128) * (y as u128);
|
||||
(full as u64) ^ ((full >> 64) as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn hash_bytes(bytes: &[u8]) -> u64 {
|
||||
let len = bytes.len();
|
||||
let mut s0 = SEED1;
|
||||
let mut s1 = SEED2;
|
||||
|
||||
if len <= 16 {
|
||||
if len >= 8 {
|
||||
s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap());
|
||||
s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
|
||||
} else if len >= 4 {
|
||||
s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64;
|
||||
s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
|
||||
} else if len > 0 {
|
||||
let lo = bytes[0];
|
||||
let mid = bytes[len / 2];
|
||||
let hi = bytes[len - 1];
|
||||
s0 ^= lo as u64;
|
||||
s1 ^= ((hi as u64) << 8) | mid as u64;
|
||||
}
|
||||
} else {
|
||||
let mut off = 0;
|
||||
while off < len - 16 {
|
||||
let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap());
|
||||
let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap());
|
||||
let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y);
|
||||
s0 = s1;
|
||||
s1 = t;
|
||||
off += 16;
|
||||
}
|
||||
|
||||
let suffix = &bytes[len - 16..];
|
||||
s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap());
|
||||
s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap());
|
||||
}
|
||||
|
||||
multiply_mix(s0, s1) ^ (len as u64)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::FxHasher64;
|
||||
use core::hash::Hasher;
|
||||
|
||||
#[test]
|
||||
fn leading_zero_words_are_not_absorbed() {
|
||||
let hash_words = |words: &[u64]| {
|
||||
let mut hasher = FxHasher64::new();
|
||||
for &word in words {
|
||||
hasher.write_u64(word);
|
||||
}
|
||||
hasher.finish()
|
||||
};
|
||||
assert_ne!(hash_words(&[]), hash_words(&[0]), "a zero word must change the hash of the empty input");
|
||||
assert_ne!(hash_words(&[0]), hash_words(&[0, 0]), "zero words must accumulate distinct states");
|
||||
assert_ne!(hash_words(&[0, 7]), hash_words(&[7]), "a leading zero word must not be absorbed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Typed attribute keys whose value types live in this crate. See `core_types::attr` for the trait and macro.
|
||||
|
||||
use crate::graphic::Graphic;
|
||||
use core_types::list::List;
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Vector graphics object's filled area paint.
|
||||
Fill: List<Graphic>,
|
||||
/// Vector graphics object's stroke paint.
|
||||
Stroke: List<Graphic>,
|
||||
editor {
|
||||
/// 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.
|
||||
MergedLayers: List<Graphic>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attr::Attr;
|
||||
|
||||
// Key names are the stored document format — pinned as literals so a key rename shows up as a breaking change.
|
||||
#[test]
|
||||
fn key_names_are_pinned() {
|
||||
assert_eq!(Fill::name(), "fill");
|
||||
assert_eq!(Stroke::name(), "stroke");
|
||||
assert_eq!(editor::MergedLayers::name(), "editor:merged_layers");
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,32 @@
|
||||
use core_types::Color;
|
||||
use core_types::attr::{self, Attr};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, ItemAttributeValues, List};
|
||||
use core_types::ops::{FromAnchorPosition, ListConvert};
|
||||
use core_types::list::{Item, ItemAttributeValues, List};
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use std::borrow::Cow;
|
||||
use vector_types::GradientStops;
|
||||
use vector_types::Gradient;
|
||||
pub use vector_types::Vector;
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
|
||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||
#[derive(Clone, Debug, Default, CacheHash, PartialEq, DynAny)]
|
||||
pub enum Graphic {
|
||||
/// The absence of graphical content, like CSS's `none` keyword: painting it produces nothing.
|
||||
#[default]
|
||||
None,
|
||||
Graphic(List<Graphic>),
|
||||
Vector(List<Vector>),
|
||||
RasterCPU(List<Raster<CPU>>),
|
||||
RasterGPU(List<Raster<GPU>>),
|
||||
Color(List<Color>),
|
||||
Gradient(List<GradientStops>),
|
||||
Gradient(List<Gradient>),
|
||||
Text(List<String>),
|
||||
}
|
||||
|
||||
impl Default for Graphic {
|
||||
fn default() -> Self {
|
||||
Self::Graphic(List::new())
|
||||
}
|
||||
}
|
||||
|
||||
// Graphic
|
||||
impl From<List<Graphic>> for Graphic {
|
||||
fn from(graphic: List<Graphic>) -> Self {
|
||||
@@ -91,14 +88,14 @@ impl From<List<Color>> for Graphic {
|
||||
// Note: List conversions handled by blanket impl in gcore
|
||||
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
|
||||
|
||||
// GradientStops
|
||||
impl From<GradientStops> for Graphic {
|
||||
fn from(gradient: GradientStops) -> Self {
|
||||
// Gradient
|
||||
impl From<Gradient> for Graphic {
|
||||
fn from(gradient: Gradient) -> Self {
|
||||
Graphic::Gradient(List::new_from_element(gradient))
|
||||
}
|
||||
}
|
||||
impl From<List<GradientStops>> for Graphic {
|
||||
fn from(gradient: List<GradientStops>) -> Self {
|
||||
impl From<List<Gradient>> for Graphic {
|
||||
fn from(gradient: List<Gradient>) -> Self {
|
||||
Graphic::Gradient(gradient)
|
||||
}
|
||||
}
|
||||
@@ -123,32 +120,32 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
// Whether the parent carries each attribute: a structural fact (column presence), never a value comparison.
|
||||
// Flattening composes a parent attribute onto its children only when the parent has it,
|
||||
// so an absent parent attribute never invents a column the children didn't already have.
|
||||
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
|
||||
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
|
||||
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
|
||||
let parent_has_layer_path = current_graphic_item.attribute::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH).is_some();
|
||||
let parent_has_transform = current_graphic_item.attr::<attr::Transform>().is_some();
|
||||
let parent_has_opacity = current_graphic_item.attr::<attr::Opacity>().is_some();
|
||||
let parent_has_fill = current_graphic_item.attr::<attr::OpacityFill>().is_some();
|
||||
let parent_has_layer_path = current_graphic_item.attr::<attr::editor::LayerPath>().is_some();
|
||||
|
||||
let layer_path: List<NodeId> = current_graphic_item.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
|
||||
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
let layer_path = current_graphic_item.attr_cloned_or_default::<attr::editor::LayerPath>();
|
||||
let current_transform = current_graphic_item.attr_cloned_or_default::<attr::Transform>();
|
||||
let current_opacity = current_graphic_item.attr_cloned_or_default::<attr::Opacity>();
|
||||
let current_fill = current_graphic_item.attr_cloned_or_default::<attr::OpacityFill>();
|
||||
|
||||
match current_graphic_item.into_element() {
|
||||
// Compose the parent's transform/opacity/fill onto each child, but only for attributes the parent carries.
|
||||
// A child lacking one is padded with the composition identity (`1.` for opacity/fill, identity for transform), so composing through it is a no-op.
|
||||
Graphic::Graphic(mut sub_list) => {
|
||||
if parent_has_transform {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for v in sub_list.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*v = current_transform * *v;
|
||||
}
|
||||
}
|
||||
if parent_has_opacity {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY) {
|
||||
for v in sub_list.iter_attr_values_mut_or_default::<attr::Opacity>() {
|
||||
*v *= current_opacity;
|
||||
}
|
||||
}
|
||||
if parent_has_fill {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY_FILL) {
|
||||
for v in sub_list.iter_attr_values_mut_or_default::<attr::OpacityFill>() {
|
||||
*v *= current_fill;
|
||||
}
|
||||
}
|
||||
@@ -159,22 +156,22 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
other => {
|
||||
if let Some(typed_list) = extract_variant(other) {
|
||||
for mut item in typed_list.into_iter() {
|
||||
// Each `|| item.attribute(...)` keeps an attribute the item itself carries
|
||||
// Each `|| item.attr::<...>()` keeps an attribute the item itself carries
|
||||
// (recomposed with the parent's identity value) even when the parent lacks it
|
||||
if parent_has_transform || item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some() {
|
||||
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
item.set_attribute(ATTR_TRANSFORM, current_transform * item_transform);
|
||||
if parent_has_transform || item.attr::<attr::Transform>().is_some() {
|
||||
let item_transform = item.attr_cloned_or_default::<attr::Transform>();
|
||||
item.set_attr::<attr::Transform>(current_transform * item_transform);
|
||||
}
|
||||
if parent_has_opacity || item.attribute::<f64>(ATTR_OPACITY).is_some() {
|
||||
let item_opacity: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
item.set_attribute(ATTR_OPACITY, current_opacity * item_opacity);
|
||||
if parent_has_opacity || item.attr::<attr::Opacity>().is_some() {
|
||||
let item_opacity = item.attr_cloned_or_default::<attr::Opacity>();
|
||||
item.set_attr::<attr::Opacity>(current_opacity * item_opacity);
|
||||
}
|
||||
if parent_has_fill || item.attribute::<f64>(ATTR_OPACITY_FILL).is_some() {
|
||||
let item_fill: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
item.set_attribute(ATTR_OPACITY_FILL, current_fill * item_fill);
|
||||
if parent_has_fill || item.attr::<attr::OpacityFill>().is_some() {
|
||||
let item_fill = item.attr_cloned_or_default::<attr::OpacityFill>();
|
||||
item.set_attr::<attr::OpacityFill>(current_fill * item_fill);
|
||||
}
|
||||
if parent_has_layer_path {
|
||||
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
item.set_attr::<attr::editor::LayerPath>(layer_path.clone());
|
||||
}
|
||||
|
||||
output.push(item);
|
||||
@@ -196,9 +193,9 @@ pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
|
||||
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||
}
|
||||
|
||||
/// Look up the paint graphics stored under attribute for a vector item, in the canonical `List<Graphic>` form.
|
||||
pub fn graphic_list_at<'a>(list: &'a List<Vector>, index: usize, attribute: &str) -> Option<Cow<'a, List<Graphic>>> {
|
||||
list.attribute::<List<Graphic>>(attribute, index)
|
||||
/// Look up the paint graphics stored under the typed attribute for a vector item, in the canonical `List<Graphic>` form.
|
||||
pub fn graphic_list_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> Option<Cow<'_, List<Graphic>>> {
|
||||
list.attr::<A>(index)
|
||||
.map(Cow::Borrowed)
|
||||
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
|
||||
.filter(|graphic_list| is_paint_present(graphic_list))
|
||||
@@ -206,25 +203,25 @@ pub fn graphic_list_at<'a>(list: &'a List<Vector>, index: usize, attribute: &str
|
||||
|
||||
/// Whether the item carries a non-blank canonical `List<Graphic>` paint attribute,
|
||||
/// checked by borrowing without cloning the renderable list.
|
||||
pub fn has_paint_at(list: &List<Vector>, index: usize, attribute: &str) -> bool {
|
||||
list.attribute::<List<Graphic>>(attribute, index).is_some_and(is_paint_present)
|
||||
pub fn has_paint_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> bool {
|
||||
list.attr::<A>(index).is_some_and(is_paint_present)
|
||||
}
|
||||
|
||||
/// Stores a paint attribute in its canonical `List<Graphic>` form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
|
||||
attributes.insert(key, paint.into_graphic_list());
|
||||
pub fn set_paint_attribute<A: Attr<Value = List<Graphic>>>(attributes: &mut ItemAttributeValues, paint: impl IntoGraphicList) {
|
||||
attributes.set_attr::<A>(paint.into_graphic_list());
|
||||
}
|
||||
|
||||
/// Stores a paint attribute at a list index in its canonical `List<Graphic>` form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
|
||||
list.set_attribute(key, index, paint.into_graphic_list());
|
||||
pub fn set_paint_attribute_at<A: Attr<Value = List<Graphic>>, T>(list: &mut List<T>, index: usize, paint: impl IntoGraphicList) {
|
||||
list.set_attr::<A>(index, paint.into_graphic_list());
|
||||
}
|
||||
|
||||
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
|
||||
/// canonical `List<Graphic>` fill and stroke attributes.
|
||||
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
|
||||
fn bake_list_transform<T>(list: &mut List<T>, transform: DAffine2) {
|
||||
for item_transform in list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for item_transform in list.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*item_transform = transform * *item_transform;
|
||||
}
|
||||
}
|
||||
@@ -232,6 +229,7 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
|
||||
for graphic in graphics.iter_element_values_mut() {
|
||||
match graphic {
|
||||
Graphic::None => {}
|
||||
Graphic::Graphic(list) => bake_list_transform(list, transform),
|
||||
Graphic::Vector(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPU(list) => bake_list_transform(list, transform),
|
||||
@@ -243,7 +241,7 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
}
|
||||
}
|
||||
|
||||
for paint_key in [ATTR_FILL, ATTR_STROKE] {
|
||||
for paint_key in [crate::attr::Fill::name(), crate::attr::Stroke::name()] {
|
||||
if let Some(graphics) = attributes.get_mut::<List<Graphic>>(paint_key) {
|
||||
bake_graphic_paint_transform(graphics, transform);
|
||||
}
|
||||
@@ -274,7 +272,7 @@ impl TryFromGraphic for Color {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for GradientStops {
|
||||
impl TryFromGraphic for Gradient {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Gradient(t) = graphic { Some(t) } else { None }
|
||||
}
|
||||
@@ -307,12 +305,12 @@ impl IntoGraphicList for List<Graphic> {
|
||||
|
||||
impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
// Propagate `editor:layer_path` from item 0 onto the wrapper Graphic item so a subsequent
|
||||
// `flatten_graphic_list` doesn't overwrite the inner Vector's stamp with an empty value
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
// Propagate the `editor:layer_path` column (if present) from item 0 onto the wrapper Graphic item so a
|
||||
// subsequent `flatten_graphic_list` doesn't drop the inner Vector's layer stamp
|
||||
let layer_path = self.attr::<attr::editor::LayerPath>(0).cloned();
|
||||
let mut graphic_list = List::new_from_element(Graphic::Vector(self));
|
||||
if !layer_path.is_empty() {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
if let Some(layer_path) = layer_path {
|
||||
graphic_list.set_attr::<attr::editor::LayerPath>(0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
}
|
||||
@@ -336,7 +334,7 @@ impl IntoGraphicList for List<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<GradientStops> {
|
||||
impl IntoGraphicList for List<Gradient> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::Gradient(self))
|
||||
}
|
||||
@@ -344,32 +342,32 @@ impl IntoGraphicList for List<GradientStops> {
|
||||
|
||||
impl IntoGraphicList for List<String> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
let layer_path = self.attr::<attr::editor::LayerPath>(0).cloned();
|
||||
let mut graphic_list = List::new_from_element(Graphic::Text(self));
|
||||
if !layer_path.is_empty() {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
if let Some(layer_path) = layer_path {
|
||||
graphic_list.set_attr::<attr::editor::LayerPath>(0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for DAffine2 {
|
||||
impl IntoGraphicList for Item<DAffine2> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::default())
|
||||
}
|
||||
}
|
||||
|
||||
// DAffine2
|
||||
impl From<DAffine2> for Graphic {
|
||||
fn from(_: DAffine2) -> Self {
|
||||
impl From<Item<DAffine2>> for Graphic {
|
||||
fn from(_: Item<DAffine2>) -> Self {
|
||||
Graphic::default()
|
||||
}
|
||||
}
|
||||
|
||||
// DVec2
|
||||
impl From<DVec2> for Graphic {
|
||||
fn from(position: DVec2) -> Self {
|
||||
Graphic::Vector(List::new_from_element(Vector::from_anchor_position(position)))
|
||||
impl From<Item<DVec2>> for Graphic {
|
||||
fn from(position: Item<DVec2>) -> Self {
|
||||
Graphic::Vector(List::new_from_element(Vector::from_anchor_position(position.into_element())))
|
||||
}
|
||||
}
|
||||
// Note: List conversions handled by blanket impl in gcore
|
||||
@@ -419,10 +417,11 @@ impl Graphic {
|
||||
|
||||
pub fn had_clip_enabled(&self) -> bool {
|
||||
fn all_clipped<T>(list: &List<T>) -> bool {
|
||||
list.iter_attribute_values_or_default::<bool>(ATTR_CLIPPING_MASK).all(|clip| clip)
|
||||
list.iter_attr_values_or_default::<attr::ClippingMask>().all(|clip| clip)
|
||||
}
|
||||
|
||||
match self {
|
||||
Graphic::None => true,
|
||||
Graphic::Vector(list) => all_clipped(list),
|
||||
Graphic::Graphic(list) => all_clipped(list),
|
||||
Graphic::RasterCPU(list) => all_clipped(list),
|
||||
@@ -437,12 +436,12 @@ impl Graphic {
|
||||
match self {
|
||||
Graphic::Vector(vector) => (0..vector.len()).all(|index| {
|
||||
let Some(element) = vector.element(index) else { return false };
|
||||
let opacity: f64 = vector.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity = vector.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
|
||||
let fill_opaque_or_absent = graphic_list_at(vector, index, ATTR_FILL).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
let fill_opaque_or_absent = graphic_list_at::<crate::attr::Fill>(vector, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
|
||||
let stroke_invisible_or_transparent = element.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|
||||
|| graphic_list_at(vector, index, ATTR_STROKE).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
|| graphic_list_at::<crate::attr::Stroke>(vector, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
|
||||
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
|
||||
}),
|
||||
@@ -452,17 +451,20 @@ impl Graphic {
|
||||
|
||||
pub fn is_opaque(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => false,
|
||||
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
|
||||
Graphic::Vector(list) => {
|
||||
let is_paint_opaque_at = |key: &str, index: usize| graphic_list_at(list, index, key).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()));
|
||||
fn is_paint_opaque_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> bool {
|
||||
graphic_list_at::<A>(list, index).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()))
|
||||
}
|
||||
|
||||
!list.is_empty()
|
||||
&& (0..list.len()).all(|i| {
|
||||
let Some(vector) = list.element(i) else { return false };
|
||||
let opacity: f64 = list.attribute_cloned_or(ATTR_OPACITY, i, 1.);
|
||||
let opacity_fill: f64 = list.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
|
||||
let fill_opaque = opacity_fill >= 1. - f64::EPSILON && is_paint_opaque_at(ATTR_FILL, i);
|
||||
let stroke_opaque_or_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_opaque_at(ATTR_STROKE, i);
|
||||
let opacity = list.attr_cloned_or_default::<attr::Opacity>(i);
|
||||
let opacity_fill = list.attr_cloned_or_default::<attr::OpacityFill>(i);
|
||||
let fill_opaque = opacity_fill >= 1. - f64::EPSILON && is_paint_opaque_at::<crate::attr::Fill>(list, i);
|
||||
let stroke_opaque_or_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_opaque_at::<crate::attr::Stroke>(list, i);
|
||||
opacity >= 1. - f64::EPSILON && fill_opaque && stroke_opaque_or_invisible
|
||||
})
|
||||
}
|
||||
@@ -474,19 +476,21 @@ impl Graphic {
|
||||
|
||||
pub fn is_fully_transparent(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => true,
|
||||
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||
Graphic::Vector(list) => (0..list.len()).all(|i| {
|
||||
let Some(vector) = list.element(i) else { return false };
|
||||
let is_paint_fully_transparent_at =
|
||||
|key: &str, index: usize| graphic_list_at(list, index, key).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
fn is_paint_fully_transparent_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> bool {
|
||||
graphic_list_at::<A>(list, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()))
|
||||
}
|
||||
|
||||
let opacity: f64 = list.attribute_cloned_or(ATTR_OPACITY, i, 1.);
|
||||
let opacity = list.attr_cloned_or_default::<attr::Opacity>(i);
|
||||
if opacity <= f64::EPSILON {
|
||||
return true;
|
||||
}
|
||||
let opacity_fill: f64 = list.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
|
||||
let fill_invisible = opacity_fill <= f64::EPSILON || is_paint_fully_transparent_at(ATTR_FILL, i);
|
||||
let stroke_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_fully_transparent_at(ATTR_STROKE, i);
|
||||
let opacity_fill = list.attr_cloned_or_default::<attr::OpacityFill>(i);
|
||||
let fill_invisible = opacity_fill <= f64::EPSILON || is_paint_fully_transparent_at::<crate::attr::Fill>(list, i);
|
||||
let stroke_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_fully_transparent_at::<crate::attr::Stroke>(list, i);
|
||||
fill_invisible && stroke_invisible
|
||||
}),
|
||||
Graphic::Color(list) => list.iter_element_values().all(|color| color.a() == 0.),
|
||||
@@ -501,9 +505,10 @@ impl Graphic {
|
||||
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_opaque()
|
||||
}
|
||||
|
||||
/// Returns true if this graphic's inner list is empty.
|
||||
/// Returns true if this graphic contains no content.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => true,
|
||||
Graphic::Graphic(list) => list.is_empty(),
|
||||
Graphic::Vector(list) => list.is_empty(),
|
||||
Graphic::Color(list) => list.is_empty(),
|
||||
@@ -518,6 +523,7 @@ impl Graphic {
|
||||
impl BoundingBox for Graphic {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::None => RenderBoundingBox::None,
|
||||
Graphic::Vector(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::RasterCPU(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -530,6 +536,7 @@ impl BoundingBox for Graphic {
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::None => RenderBoundingBox::None,
|
||||
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -541,25 +548,10 @@ impl BoundingBox for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
impl ListConvert<Graphic> for Vector {
|
||||
fn convert_item(self) -> Graphic {
|
||||
Graphic::Vector(List::new_from_element(self))
|
||||
}
|
||||
}
|
||||
impl ListConvert<Graphic> for Raster<CPU> {
|
||||
fn convert_item(self) -> Graphic {
|
||||
Graphic::RasterCPU(List::new_from_element(self))
|
||||
}
|
||||
}
|
||||
impl ListConvert<Graphic> for Raster<GPU> {
|
||||
fn convert_item(self) -> Graphic {
|
||||
Graphic::RasterGPU(List::new_from_element(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for Graphic {
|
||||
fn render_complexity(&self) -> usize {
|
||||
match self {
|
||||
Self::None => 0,
|
||||
Self::Graphic(list) => list.render_complexity(),
|
||||
Self::Vector(list) => list.render_complexity(),
|
||||
Self::RasterCPU(list) => list.render_complexity(),
|
||||
@@ -656,7 +648,7 @@ mod tests {
|
||||
fn flatten_does_not_invent_attributes() {
|
||||
let graphics = List::new_from_element(vector_graphic());
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
for key in [ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH] {
|
||||
for key in [attr::Opacity::name(), attr::OpacityFill::name(), attr::Transform::name(), attr::editor::LayerPath::name()] {
|
||||
assert!(!flattened.attribute_keys().any(|k| k == key), "flatten invented the `{key}` attribute");
|
||||
}
|
||||
}
|
||||
@@ -665,20 +657,19 @@ mod tests {
|
||||
#[test]
|
||||
fn flatten_propagates_present_attributes() {
|
||||
let mut graphics = List::new_from_element(vector_graphic());
|
||||
graphics.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
graphics.set_attr::<attr::Opacity>(0, 0.5);
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
assert_eq!(flattened.attr_cloned_or_default::<attr::Opacity>(0), 0.5);
|
||||
|
||||
let mut group = List::new_from_element(Graphic::Graphic(List::new_from_element(vector_graphic())));
|
||||
group.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
group.set_attr::<attr::Opacity>(0, 0.5);
|
||||
let flattened: List<Vector> = group.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
assert_eq!(flattened.attr_cloned_or_default::<attr::Opacity>(0), 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod graphic_is_opaque_tests {
|
||||
use core_types::ATTR_SPREAD_METHOD;
|
||||
use vector_types::{GradientSpreadMethod, GradientStop};
|
||||
|
||||
use super::*;
|
||||
@@ -688,9 +679,9 @@ mod graphic_is_opaque_tests {
|
||||
Graphic::Color(List::new_from_element(color))
|
||||
}
|
||||
|
||||
fn gradient_graphic(gradient: GradientStops) -> Graphic {
|
||||
fn gradient_graphic(gradient: Gradient) -> Graphic {
|
||||
let mut gradient_list = List::new_from_element(gradient);
|
||||
gradient_list.set_attribute(ATTR_SPREAD_METHOD, 0, GradientSpreadMethod::Pad);
|
||||
gradient_list.set_attr::<vector_types::attr::SpreadMethod>(0, GradientSpreadMethod::Pad);
|
||||
Graphic::Gradient(gradient_list)
|
||||
}
|
||||
|
||||
@@ -716,7 +707,7 @@ mod graphic_is_opaque_tests {
|
||||
fn gradient_with_all_opaque_stops_is_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
let gradient = Gradient::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -736,7 +727,7 @@ mod graphic_is_opaque_tests {
|
||||
fn gradient_with_transparent_stop_is_not_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
let gradient = Gradient::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod artboard;
|
||||
pub mod attr;
|
||||
pub mod graphic;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
@@ -20,11 +21,11 @@ pub mod migrations {
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use vector_types::vector::{PointDomain, RegionDomain, SegmentDomain, misc::HandleId, style::Stroke};
|
||||
use vector_types::{GradientStops, Vector, vector};
|
||||
use vector_types::{Gradient, Vector, vector};
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Gradient {
|
||||
pub stops: GradientStops,
|
||||
pub struct LegacyGradient {
|
||||
pub stops: Gradient,
|
||||
pub gradient_type: vector::style::GradientType,
|
||||
pub start: DVec2,
|
||||
pub end: DVec2,
|
||||
@@ -36,11 +37,11 @@ pub mod migrations {
|
||||
pub transform: DAffine2,
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
impl LegacyGradient {
|
||||
/// Converts a legacy bounding-box-relative gradient (`start`/`end` in [0,1]) into an absolute one in the geometry's local space.
|
||||
/// `bounding_box` maps [0,1] onto the geometry's bounding box; `layer_transform` is the layer's own transform,
|
||||
/// used to bake the elliptical adjustment that reproduces the legacy isotropic radial through a non-uniform layer.
|
||||
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> Gradient {
|
||||
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> LegacyGradient {
|
||||
let start = bounding_box.transform_point2(self.start);
|
||||
let end = bounding_box.transform_point2(self.end);
|
||||
let direction = end - start;
|
||||
@@ -63,7 +64,7 @@ pub mod migrations {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
|
||||
Gradient {
|
||||
LegacyGradient {
|
||||
start,
|
||||
end,
|
||||
transform,
|
||||
@@ -80,15 +81,15 @@ pub mod migrations {
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Fill {
|
||||
pub enum LegacyFill {
|
||||
#[default]
|
||||
None,
|
||||
Solid(Color),
|
||||
Gradient(Gradient),
|
||||
Gradient(LegacyGradient),
|
||||
}
|
||||
|
||||
/// The legacy `fill` field is intentionally omitted because vector payload migration only
|
||||
/// recovers editable vector data. The fill/stroke paints are migrated from the the node inputs.
|
||||
/// recovers editable vector data. The fill/stroke paints are migrated from the node inputs.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[cfg_attr(test, derive(Default, serde::Serialize))]
|
||||
pub(super) struct PathStyle {
|
||||
@@ -162,7 +163,7 @@ pub mod migrations {
|
||||
.unwrap()
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("fill".into(), serde_json::to_value(legacy::Fill::default()).unwrap());
|
||||
.insert("fill".into(), serde_json::to_value(legacy::LegacyFill::default()).unwrap());
|
||||
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
|
||||
|
||||
assert_eq!(migrated.stroke.unwrap().weight, 12.);
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod blending;
|
||||
pub mod choice_type;
|
||||
pub mod color;
|
||||
pub mod context;
|
||||
pub mod list;
|
||||
pub mod registry;
|
||||
pub mod shaders;
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! A zero-cost stand-in for `core_types::list::Item` used when node kernels are compiled for the GPU.
|
||||
//!
|
||||
//! Shader node kernels compile twice: under `std` against the real attribute-carrying `Item`, and under
|
||||
//! `no_std` (SPIR-V) against this transparent wrapper, imported as `Item`. Only the element-access surface is
|
||||
//! provided, since rust-gpu cannot allocate and attributes have no per-pixel meaning; attribute use fails the
|
||||
//! shader build. It is named distinctly from `Item` so a search for the canonical type finds only that one.
|
||||
|
||||
/// A rank-0 wire value holding a single element, mirroring the element-access API of the real `Item`.
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq)]
|
||||
pub struct ShaderItem<T> {
|
||||
element: T,
|
||||
}
|
||||
|
||||
impl<T> ShaderItem<T> {
|
||||
/// Constructs an item with the given element.
|
||||
pub fn new_from_element(element: T) -> Self {
|
||||
Self { element }
|
||||
}
|
||||
|
||||
/// Returns a shared reference to this item's element.
|
||||
pub fn element(&self) -> &T {
|
||||
&self.element
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to this item's element.
|
||||
pub fn element_mut(&mut self) -> &mut T {
|
||||
&mut self.element
|
||||
}
|
||||
|
||||
/// Consumes this item and returns the owned element.
|
||||
pub fn into_element(self) -> T {
|
||||
self.element
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for ShaderItem<T> {
|
||||
fn from(element: T) -> Self {
|
||||
Self::new_from_element(element)
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,13 @@ use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
|
||||
use core_types::{Color, attr};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientType;
|
||||
use graphic_types::vector_types::vector::style::{PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use std::fmt::Write;
|
||||
use vector_types::GradientStops;
|
||||
use vector_types::Gradient;
|
||||
use vector_types::gradient::GradientSpreadMethod;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
@@ -76,7 +76,7 @@ impl RenderExt for List<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderExt for List<GradientStops> {
|
||||
impl RenderExt for List<Gradient> {
|
||||
type Output = u64;
|
||||
|
||||
/// Adds the gradient def through mutating the first argument, returning the gradient ID.
|
||||
@@ -93,9 +93,9 @@ impl RenderExt for List<GradientStops> {
|
||||
let mut stop = String::new();
|
||||
|
||||
let Some(stops) = self.element(0) else { return 0 };
|
||||
let gradient_type: GradientType = self.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let local_gradient_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = self.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
let gradient_type = self.attr_cloned_or_default::<vector_types::attr::GradientType>(0);
|
||||
let local_gradient_transform = self.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let spread_method = self.attr_cloned_or_default::<vector_types::attr::SpreadMethod>(0);
|
||||
|
||||
for (position, color, original_midpoint) in stops.interpolated_samples() {
|
||||
stop.push_str("<stop");
|
||||
@@ -241,6 +241,7 @@ impl RenderExt for List<Graphic> {
|
||||
let gradient_id = gradient_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target);
|
||||
format!(r##" {paint_attr}="url(#{gradient_id})""##)
|
||||
}
|
||||
Some(Graphic::None) => format!(r#" {paint_attr}="none""#),
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) | Some(Graphic::Text(_)) => {
|
||||
let bounds = if target == PaintTarget::Stroke {
|
||||
// To prevent a wraparound artefact occurring when the tile boundary and the stroke region are perfectly aligned, the local coordinate is expanded slightly.
|
||||
|
||||
@@ -1,29 +1,26 @@
|
||||
use crate::render_ext::{PaintTarget, RenderExt};
|
||||
use crate::to_peniko::{BlendModeExt, ToPenikoColor};
|
||||
use core_types::CacheHash;
|
||||
use core_types::attr;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::BoundingBox;
|
||||
use core_types::bounds::RenderBoundingBox;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::consts::DEFAULT_FONT_SIZE;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::{NodeId, generate_uuid};
|
||||
use core_types::{
|
||||
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_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_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_hash::CacheHashWrapper;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::attr as graphic_attr;
|
||||
use graphic_types::graphic::{graphic_list_at, has_paint_at, is_paint_present, set_paint_attribute};
|
||||
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster, Texture};
|
||||
use graphic_types::vector_types::gradient::{GradientStops, GradientType};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientType};
|
||||
use graphic_types::vector_types::subpath::Subpath;
|
||||
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
|
||||
use graphic_types::vector_types::vector::style::{PaintOrder, RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
@@ -39,6 +36,8 @@ use std::fmt::Write;
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use text_nodes::attr as text_attr;
|
||||
use vector_types::attr as vector_attr;
|
||||
use vector_types::gradient::GradientSpreadMethod;
|
||||
use vello::*;
|
||||
|
||||
@@ -360,7 +359,7 @@ fn emit_svg_fill_path(
|
||||
attributes.push("d", d);
|
||||
let matrix = format_transform_matrix(element_transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
let defs = &mut attributes.0.svg_defs;
|
||||
let fill_attribute = fill_graphic_list
|
||||
@@ -394,12 +393,12 @@ pub(crate) fn gradient_placement(transform: DAffine2, gradient_type: GradientTyp
|
||||
}
|
||||
}
|
||||
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<Gradient>, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
let stops = gradient_list.element(0)?;
|
||||
|
||||
let gradient_type: GradientType = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let gradient_transform: DAffine2 = gradient_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = gradient_list.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
let gradient_type = gradient_list.attr_cloned_or_default::<vector_attr::GradientType>(0);
|
||||
let gradient_transform = gradient_list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let spread_method = gradient_list.attr_cloned_or_default::<vector_attr::SpreadMethod>(0);
|
||||
|
||||
let mut peniko_stops = peniko::ColorStops::new();
|
||||
for (position, color, _) in stops.interpolated_samples() {
|
||||
@@ -457,10 +456,10 @@ pub struct RenderMetadata {
|
||||
pub text_frames: HashMap<NodeId, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_data: HashMap<NodeId, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` row attribute, exposed so message handlers can read it.
|
||||
/// Per-layer `graphic_types::attr::Fill` row attribute, exposed so message handlers can read it.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub fill_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
/// Per-layer `ATTR_STROKE` row attribute, exposed so message handlers can read it.
|
||||
/// Per-layer `graphic_types::attr::Stroke` row attribute, exposed so message handlers can read it.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub stroke_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
pub backgrounds: Vec<Background>,
|
||||
@@ -546,6 +545,7 @@ pub trait Render: BoundingBox + RenderComplexity {
|
||||
impl Render for Graphic {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.render_svg(render, render_params),
|
||||
Graphic::Vector(list) => list.render_svg(render, render_params),
|
||||
Graphic::RasterCPU(list) => list.render_svg(render, render_params),
|
||||
@@ -558,6 +558,7 @@ impl Render for Graphic {
|
||||
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::Vector(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::RasterCPU(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
@@ -571,6 +572,7 @@ impl Render for Graphic {
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
if let Some(element_id) = element_id {
|
||||
match self {
|
||||
Graphic::None => {}
|
||||
Graphic::Graphic(_) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
}
|
||||
@@ -578,9 +580,9 @@ impl Render for Graphic {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
let layer_path: List<NodeId> = list.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
let layer_path: List<NodeId> = list.attr_cloned_or_default::<attr::editor::LayerPath>(0).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let transform = list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
|
||||
metadata.first_element_source_id.insert(element_id, layer);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
@@ -591,7 +593,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::RasterGPU(list) => {
|
||||
@@ -599,7 +601,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::Color(list) => {
|
||||
@@ -607,7 +609,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::Gradient(list) => {
|
||||
@@ -615,7 +617,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::Text(list) => {
|
||||
@@ -623,13 +625,14 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::Vector(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::RasterCPU(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
@@ -642,6 +645,7 @@ impl Render for Graphic {
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::Vector(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::RasterCPU(list) => list.add_upstream_click_targets(click_targets),
|
||||
@@ -654,6 +658,7 @@ impl Render for Graphic {
|
||||
|
||||
fn add_upstream_outline_targets(&self, outlines: &mut Vec<ClickTarget>) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::Vector(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::RasterCPU(list) => list.add_upstream_outline_targets(outlines),
|
||||
@@ -666,6 +671,7 @@ impl Render for Graphic {
|
||||
|
||||
fn contains_artboard(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => false,
|
||||
Graphic::Graphic(list) => list.contains_artboard(),
|
||||
Graphic::Vector(list) => list.contains_artboard(),
|
||||
Graphic::RasterCPU(list) => list.contains_artboard(),
|
||||
@@ -678,6 +684,7 @@ impl Render for Graphic {
|
||||
|
||||
fn new_ids_from_hash(&mut self, reference: Option<NodeId>) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.new_ids_from_hash(reference),
|
||||
Graphic::Vector(list) => list.new_ids_from_hash(reference),
|
||||
Graphic::RasterCPU(_) => (),
|
||||
@@ -691,10 +698,10 @@ impl Render for Graphic {
|
||||
|
||||
/// Reads the artboard metadata for the item at `index` from a `List<Artboard>`.
|
||||
fn read_artboard_attributes(list: &List<Artboard>, index: usize) -> (DVec2, DVec2, Color, bool) {
|
||||
let location: DVec2 = list.attribute_cloned_or_default(ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = list.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
|
||||
let background: Color = list.attribute_cloned_or_default(ATTR_BACKGROUND, index);
|
||||
let clip: bool = list.attribute_cloned_or_default(ATTR_CLIP, index);
|
||||
let location = list.attr_cloned_or_default::<attr::Location>(index);
|
||||
let dimensions = list.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
let background = list.attr_cloned_or_default::<attr::Background>(index);
|
||||
let clip = list.attr_cloned_or_default::<attr::Clip>(index);
|
||||
(location, dimensions, background, clip)
|
||||
}
|
||||
|
||||
@@ -729,7 +736,7 @@ impl Render for List<Artboard> {
|
||||
|attributes| {
|
||||
let matrix = format_transform_matrix(DAffine2::from_translation(location));
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
if clip {
|
||||
@@ -792,7 +799,7 @@ impl Render for List<Artboard> {
|
||||
let Some(content) = self.element(index).map(Artboard::as_graphic_list) else { continue };
|
||||
let (location, dimensions, _background, clip) = read_artboard_attributes(self, index);
|
||||
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let element_id = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = element_id {
|
||||
@@ -815,7 +822,7 @@ impl Render for List<Artboard> {
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let dimensions: DVec2 = self.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
|
||||
let dimensions = self.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
let subpath_rectangle = Subpath::new_rectangle(DVec2::ZERO, dimensions);
|
||||
click_targets.push(ClickTarget::new_with_subpath(subpath_rectangle, 0.));
|
||||
}
|
||||
@@ -831,10 +838,10 @@ impl Render for List<Graphic> {
|
||||
let mut mask_state = None;
|
||||
|
||||
for index in 0..self.len() {
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
render.parent_tag(
|
||||
@@ -842,7 +849,7 @@ impl Render for List<Graphic> {
|
||||
|attributes| {
|
||||
let matrix = format_transform_matrix(transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -887,11 +894,11 @@ impl Render for List<Graphic> {
|
||||
let mut mask_element_and_transform = None;
|
||||
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let transform = transform * item_transform;
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
let mut layer = false;
|
||||
@@ -963,8 +970,8 @@ impl Render for List<Graphic> {
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
@@ -984,7 +991,7 @@ impl Render for List<Graphic> {
|
||||
let mut all_upstream_outlines = Vec::new();
|
||||
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
let mut new_click_targets = Vec::new();
|
||||
@@ -1011,7 +1018,7 @@ impl Render for List<Graphic> {
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
let mut new_click_targets = Vec::new();
|
||||
|
||||
@@ -1027,7 +1034,7 @@ impl Render for List<Graphic> {
|
||||
|
||||
fn add_upstream_outline_targets(&self, outlines: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
let mut new_outlines = Vec::new();
|
||||
|
||||
@@ -1046,9 +1053,9 @@ impl Render for List<Graphic> {
|
||||
}
|
||||
|
||||
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {
|
||||
let (elements, layers) = self.element_and_attribute_slices_mut::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH);
|
||||
let (elements, layers) = self.element_and_attr_slices_mut::<attr::editor::LayerPath>();
|
||||
for (element, layer) in elements.iter_mut().zip(layers.iter()) {
|
||||
element.new_ids_from_hash(layer.iter_element_values().next_back().copied());
|
||||
element.new_ids_from_hash(layer.0.iter_element_values().next_back().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1057,10 +1064,10 @@ impl Render for List<Vector> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
let Some(vector) = self.element(index) else { continue };
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
|
||||
// Only consider strokes with non-zero weight, since default strokes with zero weight would prevent assigning the correct stroke transform
|
||||
let has_real_stroke = vector.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
@@ -1089,10 +1096,10 @@ impl Render for List<Vector> {
|
||||
MaskType::Mask
|
||||
};
|
||||
|
||||
let fill_graphic_list = graphic_list_at(self, index, ATTR_FILL);
|
||||
let fill_graphic_list = graphic_list_at::<graphic_attr::Fill>(self, index);
|
||||
let fill_graphic = fill_graphic_list.as_ref().and_then(|l| l.element(0));
|
||||
|
||||
let stroke_graphic_list = graphic_list_at(self, index, ATTR_STROKE);
|
||||
let stroke_graphic_list = graphic_list_at::<graphic_attr::Stroke>(self, index);
|
||||
let stroke_graphic = stroke_graphic_list.as_ref().and_then(|l| l.element(0));
|
||||
|
||||
let path_is_closed = vector.stroke_bezier_paths().all(|path| path.closed());
|
||||
@@ -1127,8 +1134,8 @@ impl Render for List<Vector> {
|
||||
|
||||
// The mask must draw at full alpha so the SVG `<mask>`/`<clipPath>` fully zeroes the path interior.
|
||||
// The wrapping SVG group (above) handles the user-set opacity.
|
||||
let mut mask_item = Item::new_from_element(cloned_vector).with_attribute(ATTR_TRANSFORM, item_transform);
|
||||
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
let mut mask_item = Item::new_from_element(cloned_vector).with_attr::<attr::Transform>(item_transform);
|
||||
set_paint_attribute::<graphic_attr::Fill>(mask_item.attributes_mut(), List::new_from_element(Color::BLACK));
|
||||
let vector_item = List::new_from_item(mask_item);
|
||||
|
||||
(id, mask_type, vector_item)
|
||||
@@ -1156,7 +1163,7 @@ impl Render for List<Vector> {
|
||||
attributes.push("d", path.clone());
|
||||
let matrix = format_transform_matrix(element_transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
let defs = &mut attributes.0.svg_defs;
|
||||
@@ -1273,10 +1280,10 @@ impl Render for List<Vector> {
|
||||
use graphic_types::vector_types::vector;
|
||||
|
||||
let Some(element) = self.element(index) else { continue };
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let multiplied_transform = parent_transform * item_transform;
|
||||
let has_real_stroke = element.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
|
||||
@@ -1302,8 +1309,8 @@ impl Render for List<Vector> {
|
||||
}
|
||||
}
|
||||
|
||||
let fill_graphic_list = graphic_list_at(self, index, ATTR_FILL);
|
||||
let stroke_graphic_list = graphic_list_at(self, index, ATTR_STROKE);
|
||||
let fill_graphic_list = graphic_list_at::<graphic_attr::Fill>(self, index);
|
||||
let stroke_graphic_list = graphic_list_at::<graphic_attr::Stroke>(self, index);
|
||||
|
||||
// If we're using opacity or a blend mode, we need to push a layer
|
||||
let blend_mode = match render_params.render_mode {
|
||||
@@ -1348,6 +1355,7 @@ impl Render for List<Vector> {
|
||||
for paint_index in 0..fill_graphic.len() {
|
||||
let Some(paint) = fill_graphic.element(paint_index) else { continue };
|
||||
match paint {
|
||||
Graphic::None => continue,
|
||||
Graphic::Color(list) => {
|
||||
let Some(color) = list.element(0) else { continue };
|
||||
|
||||
@@ -1430,6 +1438,7 @@ impl Render for List<Vector> {
|
||||
};
|
||||
|
||||
match stroke_graphic {
|
||||
Graphic::None => continue,
|
||||
Graphic::Color(list) => {
|
||||
let Some(color) = list.element(0) else { continue };
|
||||
let brush = peniko::Brush::Solid(SRGBA8::from(*color).to_peniko_color());
|
||||
@@ -1474,8 +1483,8 @@ impl Render for List<Vector> {
|
||||
|
||||
// The mask must draw at full alpha so `SrcOut` fully zeroes the path interior.
|
||||
// The outer opacity/blend layer (above) handles the user-set opacity.
|
||||
let mut mask_item = Item::new_from_element(cloned_element).with_attribute(ATTR_TRANSFORM, item_transform);
|
||||
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
let mut mask_item = Item::new_from_element(cloned_element).with_attr::<attr::Transform>(item_transform);
|
||||
set_paint_attribute::<graphic_attr::Fill>(mask_item.attributes_mut(), List::new_from_element(Color::BLACK));
|
||||
let vector_list = List::new_from_item(mask_item);
|
||||
|
||||
let bounds = element.bounding_box_with_transform(multiplied_transform).unwrap_or(layer_bounds);
|
||||
@@ -1546,10 +1555,10 @@ impl Render for List<Vector> {
|
||||
}
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
// Aggregate all items' targets per element_id so multi-item lists (e.g. 'Text' node with "Separate Glyphs" active) produce hit areas for every glyph.
|
||||
// Aggregate all items' targets per element_id so multi-item lists (e.g. the "Text to Vector Glyphs" node) produce hit areas for every glyph.
|
||||
// Targets are baked relative to item 0's transform since `Graphic::collect_metadata` records that as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if !self.is_empty() {
|
||||
self.attribute_cloned_or_default(ATTR_TRANSFORM, 0)
|
||||
self.attr_cloned_or_default::<attr::Transform>(0)
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
@@ -1564,8 +1573,8 @@ impl Render for List<Vector> {
|
||||
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = caller_element_id.or(layer) {
|
||||
@@ -1578,7 +1587,7 @@ impl Render for List<Vector> {
|
||||
}
|
||||
|
||||
// Use click-target override if the item provides one (e.g. 'Text' node's per-glyph bboxes)
|
||||
let click_target_vector = self.attribute::<Vector>(ATTR_EDITOR_CLICK_TARGET, index).unwrap_or(source);
|
||||
let click_target_vector = self.attr::<vector_attr::editor::ClickTarget>(index).unwrap_or(source);
|
||||
|
||||
let item_relative_transform = item_zero_inverse * transform;
|
||||
|
||||
@@ -1598,24 +1607,24 @@ impl Render for List<Vector> {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = metadata.vector_data.entry(element_id) {
|
||||
e.insert(Arc::new(source.clone()));
|
||||
|
||||
if let Some(fill_graphic) = graphic_list_at(self, index, ATTR_FILL) {
|
||||
if let Some(fill_graphic) = graphic_list_at::<graphic_attr::Fill>(self, index) {
|
||||
metadata.fill_attributes.insert(element_id, Arc::new(fill_graphic.into_owned()));
|
||||
}
|
||||
if let Some(stroke_graphic) = graphic_list_at(self, index, ATTR_STROKE) {
|
||||
if let Some(stroke_graphic) = graphic_list_at::<graphic_attr::Stroke>(self, index) {
|
||||
metadata.stroke_attributes.insert(element_id, Arc::new(stroke_graphic.into_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
// Surface `editor:text_frame` for the Text tool's drag cage
|
||||
if let Some(&frame) = self.attribute::<DAffine2>(ATTR_EDITOR_TEXT_FRAME, index) {
|
||||
if let Some(&frame) = self.attr::<attr::editor::TextFrame>(index) {
|
||||
metadata.text_frames.entry(element_id).or_insert(frame);
|
||||
}
|
||||
}
|
||||
|
||||
// If this item carries a snapshot of upstream graphic content (e.g. it was produced by Boolean Operation,
|
||||
// Flatten Path, Morph, or any other destructive merge), recurse into that snapshot so the editor can
|
||||
// Combine Paths, Morph, or any other destructive merge), recurse into that snapshot so the editor can
|
||||
// surface the original child layers' click targets.
|
||||
let upstream_nested_layers = self.attribute_cloned_or_default::<List<Graphic>>(ATTR_EDITOR_MERGED_LAYERS, index);
|
||||
let upstream_nested_layers = self.attr_cloned_or_default::<graphic_attr::editor::MergedLayers>(index);
|
||||
if !upstream_nested_layers.is_empty() {
|
||||
let mut upstream_footprint = footprint;
|
||||
upstream_footprint.transform *= transform;
|
||||
@@ -1635,10 +1644,10 @@ impl Render for List<Vector> {
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
// Use click-target override geometry if the item provides one (e.g. 'Text' node's per-glyph bounding boxes)
|
||||
let vector = self.attribute::<Vector>(ATTR_EDITOR_CLICK_TARGET, index).unwrap_or(source);
|
||||
let vector = self.attr::<vector_attr::editor::ClickTarget>(index).unwrap_or(source);
|
||||
|
||||
extend_targets_from_vector(click_targets, self, index, vector, transform);
|
||||
}
|
||||
@@ -1648,7 +1657,7 @@ impl Render for List<Vector> {
|
||||
// Source geometry only, ignoring `editor:click_target`, so outlines reflect actual letterforms
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
extend_targets_from_vector(outlines, self, index, source, transform);
|
||||
}
|
||||
@@ -1664,7 +1673,7 @@ impl Render for List<Vector> {
|
||||
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
|
||||
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
|
||||
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, vector_list: &List<Vector>, index: usize, geometry: &Vector, transform: DAffine2) {
|
||||
let filled = has_paint_at(vector_list, index, ATTR_FILL);
|
||||
let filled = has_paint_at::<graphic_attr::Fill>(vector_list, index);
|
||||
|
||||
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
|
||||
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
|
||||
@@ -1720,10 +1729,10 @@ impl Render for List<Raster<CPU>> {
|
||||
for index in 0..self.len() {
|
||||
let Some(image) = self.element(index) else { continue };
|
||||
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
|
||||
if image.data.is_empty() {
|
||||
continue;
|
||||
@@ -1742,7 +1751,7 @@ impl Render for List<Raster<CPU>> {
|
||||
let matrix = transform * DAffine2::from_scale(1. / size);
|
||||
let matrix = format_transform_matrix(matrix);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
attributes.push("width", size.x.to_string());
|
||||
@@ -1785,7 +1794,7 @@ impl Render for List<Raster<CPU>> {
|
||||
attributes.push("href", base64_string);
|
||||
let matrix = format_transform_matrix(transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -1807,9 +1816,9 @@ impl Render for List<Raster<CPU>> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let blend_mode = blend_mode_attr.to_peniko();
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -1824,7 +1833,7 @@ impl Render for List<Raster<CPU>> {
|
||||
layer = true;
|
||||
}
|
||||
|
||||
let transform_attribute: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform_attribute = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
let outline_transform: DAffine2 = transform * transform_attribute;
|
||||
@@ -1864,7 +1873,7 @@ impl Render for List<Raster<CPU>> {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than one item of the `List<Raster<...>>`
|
||||
if !self.is_empty() {
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(0);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
|
||||
// If this raster carries a snapshot of upstream graphic content (e.g. it was produced by Rasterize,
|
||||
@@ -1873,7 +1882,7 @@ impl Render for List<Raster<CPU>> {
|
||||
// The snapshot was captured before Rasterize shifted its input transforms to align with the rasterization
|
||||
// area, so the children are already in the coordinate space matching `footprint` here — we must NOT
|
||||
// multiply in `transform` (which is the rasterization area, not a layer-stack transform).
|
||||
let upstream_nested_layers = self.attribute_cloned_or_default::<List<Graphic>>(ATTR_EDITOR_MERGED_LAYERS, 0);
|
||||
let upstream_nested_layers = self.attr_cloned_or_default::<graphic_attr::editor::MergedLayers>(0);
|
||||
if !upstream_nested_layers.is_empty() {
|
||||
upstream_nested_layers.collect_metadata(metadata, footprint, None);
|
||||
}
|
||||
@@ -1896,10 +1905,10 @@ impl Render for List<Raster<GPU>> {
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
let Some(raster) = self.element(index) else { continue };
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let clip_attr: bool = self.attribute_cloned_or_default(ATTR_CLIPPING_MASK, index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let clip_attr = self.attr_cloned_or_default::<attr::ClippingMask>(index);
|
||||
let blend_mode = match render_params.render_mode {
|
||||
RenderMode::Outline => peniko::Mix::Normal,
|
||||
_ => blend_mode_attr.to_peniko(),
|
||||
@@ -1918,7 +1927,7 @@ impl Render for List<Raster<GPU>> {
|
||||
layer = true;
|
||||
}
|
||||
|
||||
let transform_attribute: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform_attribute = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
let outline_transform = transform * transform_attribute;
|
||||
@@ -1959,7 +1968,7 @@ impl Render for List<Raster<GPU>> {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than one item of the `List<Raster<...>>`
|
||||
if !self.is_empty() {
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(0);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
|
||||
// If this raster carries a snapshot of upstream graphic content (e.g. it was produced by Rasterize,
|
||||
@@ -1968,7 +1977,7 @@ impl Render for List<Raster<GPU>> {
|
||||
// The snapshot was captured before Rasterize shifted its input transforms to align with the rasterization
|
||||
// area, so the children are already in the coordinate space matching `footprint` here — we must NOT
|
||||
// multiply in `transform` (which is the rasterization area, not a layer-stack transform).
|
||||
let upstream_nested_layers = self.attribute_cloned_or_default::<List<Graphic>>(ATTR_EDITOR_MERGED_LAYERS, 0);
|
||||
let upstream_nested_layers = self.attr_cloned_or_default::<graphic_attr::editor::MergedLayers>(0);
|
||||
if !upstream_nested_layers.is_empty() {
|
||||
upstream_nested_layers.collect_metadata(metadata, footprint, None);
|
||||
}
|
||||
@@ -1990,9 +1999,9 @@ impl Render for List<Raster<GPU>> {
|
||||
impl Render for List<Color> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
for (index, color) in self.iter_element_values().enumerate() {
|
||||
let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
render.leaf_tag("polyline", |attributes| {
|
||||
// Stand-in for an infinite background. Chrome's SVG renderer keeps internal coordinates in f32 and loses
|
||||
// precision past ~2^24 (~16.7 million), causing tile-boundary artifacts that pop in and out during panning.
|
||||
@@ -2021,9 +2030,9 @@ impl Render for List<Color> {
|
||||
use vello::peniko;
|
||||
|
||||
for (index, color) in self.iter_element_values().enumerate() {
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let blend_mode = blend_mode_attr.to_peniko();
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
@@ -2047,7 +2056,7 @@ impl Render for List<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for List<GradientStops> {
|
||||
impl Render for List<Gradient> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
// For thumbnails the gradient fills a finite rect at the footprint's document space bounds, with a 1-unit margin to cover the `as u32` truncation of `Footprint::resolution`.
|
||||
// The viewBox crops the overshoot. Canvas rendering keeps the polyline path since Chrome rejects rects larger than ~20 million.
|
||||
@@ -2061,12 +2070,12 @@ impl Render for List<GradientStops> {
|
||||
|
||||
for index in 0..self.len() {
|
||||
let Some(gradient) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let spread_method: GradientSpreadMethod = self.attribute_cloned_or_default(ATTR_SPREAD_METHOD, index);
|
||||
let gradient_type: GradientType = self.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let spread_method = self.attr_cloned_or_default::<vector_attr::SpreadMethod>(index);
|
||||
let gradient_type = self.attr_cloned_or_default::<vector_attr::GradientType>(index);
|
||||
let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" };
|
||||
render.leaf_tag(tag, |attributes| {
|
||||
if let Some((min, size)) = thumbnail_rect {
|
||||
@@ -2150,13 +2159,13 @@ impl Render for List<GradientStops> {
|
||||
for (((index, gradient), spread_method), gradient_type) in self
|
||||
.iter_element_values()
|
||||
.enumerate()
|
||||
.zip(self.iter_attribute_values_or_default::<GradientSpreadMethod>(ATTR_SPREAD_METHOD))
|
||||
.zip(self.iter_attribute_values_or_default::<GradientType>(ATTR_GRADIENT_TYPE))
|
||||
.zip(self.iter_attr_values_or_default::<vector_attr::SpreadMethod>())
|
||||
.zip(self.iter_attr_values_or_default::<vector_attr::GradientType>())
|
||||
{
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let gradient_transform = parent_transform * transform;
|
||||
|
||||
let blend_mode = blend_mode_attr.to_peniko();
|
||||
@@ -2304,16 +2313,16 @@ fn draw_glyph_run_to_bezpaths(glyph_run: &parley::GlyphRun<'_, ()>, x_offset: f3
|
||||
fn text_item_size_and_transform(list: &List<String>, index: usize) -> Option<(DVec2, DAffine2)> {
|
||||
let text = list.element(index)?;
|
||||
let font: Resource = {
|
||||
let f: Resource = list.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
let f = list.attr_cloned_or_default::<text_attr::Font>(index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = list.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = list.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = list.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = list.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = list.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let align: text_nodes::TextAlign = list.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let font_size = list.attr_cloned_or::<attr::FontSize>(index, DEFAULT_FONT_SIZE);
|
||||
let line_height = list.attr_cloned_or::<attr::LineHeight>(index, 1.2);
|
||||
let letter_spacing = list.attr_cloned_or_default::<attr::LetterSpacing>(index);
|
||||
let max_width = list.attr_cloned_or_default::<attr::MaxWidth>(index);
|
||||
let max_height = list.attr_cloned_or_default::<attr::MaxHeight>(index);
|
||||
let align = list.attr_cloned_or_default::<text_attr::TextAlign>(index);
|
||||
let transform = list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
font_size,
|
||||
@@ -2365,7 +2374,7 @@ pub fn graphic_list_bounding_box(list: &List<Graphic>, transform: DAffine2) -> R
|
||||
let mut any_infinite = false;
|
||||
|
||||
for index in 0..list.len() {
|
||||
let item_transform = transform * list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
|
||||
let item_transform = transform * list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let Some(graphic) = list.element(index) else { continue };
|
||||
let bounds = match graphic {
|
||||
Graphic::Text(text_list) => text_list_bounding_box(text_list, item_transform),
|
||||
@@ -2399,21 +2408,21 @@ impl Render for List<String> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let font: Resource = {
|
||||
let f: Resource = self.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
let f = self.attr_cloned_or_default::<text_attr::Font>(index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = self.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = self.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = self.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = self.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = self.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let letter_tilt: f64 = self.attribute_cloned_or(ATTR_LETTER_TILT, index, 0.);
|
||||
let align: text_nodes::TextAlign = self.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let font_size = self.attr_cloned_or::<attr::FontSize>(index, DEFAULT_FONT_SIZE);
|
||||
let line_height = self.attr_cloned_or::<attr::LineHeight>(index, 1.2);
|
||||
let letter_spacing = self.attr_cloned_or_default::<attr::LetterSpacing>(index);
|
||||
let max_width = self.attr_cloned_or_default::<attr::MaxWidth>(index);
|
||||
let max_height = self.attr_cloned_or_default::<attr::MaxHeight>(index);
|
||||
let letter_tilt = self.attr_cloned_or_default::<attr::LetterTilt>(index);
|
||||
let align = self.attr_cloned_or_default::<text_attr::TextAlign>(index);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
@@ -2484,21 +2493,21 @@ impl Render for List<String> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let font: Resource = {
|
||||
let f: Resource = self.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
let f = self.attr_cloned_or_default::<text_attr::Font>(index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = self.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = self.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = self.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = self.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = self.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let letter_tilt: f64 = self.attribute_cloned_or(ATTR_LETTER_TILT, index, 0.);
|
||||
let align: text_nodes::TextAlign = self.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let font_size = self.attr_cloned_or::<attr::FontSize>(index, DEFAULT_FONT_SIZE);
|
||||
let line_height = self.attr_cloned_or::<attr::LineHeight>(index, 1.2);
|
||||
let letter_spacing = self.attr_cloned_or_default::<attr::LetterSpacing>(index);
|
||||
let max_width = self.attr_cloned_or_default::<attr::MaxWidth>(index);
|
||||
let max_height = self.attr_cloned_or_default::<attr::MaxHeight>(index);
|
||||
let letter_tilt = self.attr_cloned_or_default::<attr::LetterTilt>(index);
|
||||
let align = self.attr_cloned_or_default::<text_attr::TextAlign>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
@@ -2549,7 +2558,7 @@ impl Render for List<String> {
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
// Click targets are baked relative to item 0's transform, which `Graphic::collect_metadata` records as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if !self.is_empty() {
|
||||
self.attribute_cloned_or_default(ATTR_TRANSFORM, 0)
|
||||
self.attr_cloned_or_default::<attr::Transform>(0)
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
@@ -2562,7 +2571,7 @@ impl Render for List<String> {
|
||||
let mut accumulated_click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>> = HashMap::new();
|
||||
|
||||
for index in 0..self.len() {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let Some(element_id) = caller_element_id.or(layer) else { continue };
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Typed attribute keys whose value types live in this crate. See `core_types::attr` for the trait and macro.
|
||||
|
||||
use crate::gradient::GradientSpreadMethod;
|
||||
use crate::vector::Vector;
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Gradient's spread method (`Pad`, `Reflect`, or `Repeat`).
|
||||
SpreadMethod: GradientSpreadMethod,
|
||||
/// Gradient's type (`Linear` or `Radial`).
|
||||
GradientType: crate::gradient::GradientType,
|
||||
editor {
|
||||
/// 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.
|
||||
ClickTarget: Vector,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attr::Attr;
|
||||
|
||||
// Key names are the stored document format — pinned as literals so a key rename shows up as a breaking change.
|
||||
#[test]
|
||||
fn key_names_are_pinned() {
|
||||
assert_eq!(SpreadMethod::name(), "spread_method");
|
||||
assert_eq!(GradientType::name(), "gradient_type");
|
||||
assert_eq!(editor::ClickTarget::name(), "editor:click_target");
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,10 @@ pub enum GradientType {
|
||||
// TODO: Someday we could switch this to a Box[T] to avoid over-allocation
|
||||
/// A list of colors (linear, unassociated alpha) associated with positions (in the range 0 to 1) along a gradient.
|
||||
///
|
||||
/// Not exposed via Tsify; use [`GradientStopsUI`] at the JS boundary.
|
||||
/// Not exposed via Tsify; use [`GradientUI`] at the JS boundary.
|
||||
#[derive(Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
|
||||
pub struct GradientStops {
|
||||
pub struct Gradient {
|
||||
/// The position of this stop, a factor from 0-1 along the length of the full gradient.
|
||||
pub position: Vec<f64>,
|
||||
/// The midpoint to the right of this stop, a factor from 0-1 along the distance to the next stop. The final stop's midpoint is ignored.
|
||||
@@ -29,18 +29,18 @@ pub struct GradientStops {
|
||||
pub color: Vec<Color>,
|
||||
}
|
||||
|
||||
/// JS-boundary version of [`GradientStops`] where stop colors are [`SRGBA8`] byte triples instead of linear-light [`Color`].
|
||||
/// JS-boundary version of [`Gradient`] where stop colors are [`SRGBA8`] byte triples instead of linear-light [`Color`].
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Debug, Clone, PartialEq, Default, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct GradientStopsUI {
|
||||
pub struct GradientUI {
|
||||
pub position: Vec<f64>,
|
||||
pub midpoint: Vec<f64>,
|
||||
pub color: Vec<SRGBA8>,
|
||||
}
|
||||
|
||||
impl From<&GradientStops> for GradientStopsUI {
|
||||
fn from(s: &GradientStops) -> Self {
|
||||
impl From<&Gradient> for GradientUI {
|
||||
fn from(s: &Gradient) -> Self {
|
||||
Self {
|
||||
position: s.position.clone(),
|
||||
midpoint: s.midpoint.clone(),
|
||||
@@ -49,8 +49,8 @@ impl From<&GradientStops> for GradientStopsUI {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&GradientStopsUI> for GradientStops {
|
||||
fn from(s: &GradientStopsUI) -> Self {
|
||||
impl From<&GradientUI> for Gradient {
|
||||
fn from(s: &GradientUI) -> Self {
|
||||
Self {
|
||||
position: s.position.clone(),
|
||||
midpoint: s.midpoint.clone(),
|
||||
@@ -59,7 +59,7 @@ impl From<&GradientStopsUI> for GradientStops {
|
||||
}
|
||||
}
|
||||
|
||||
impl GradientStopsUI {
|
||||
impl GradientUI {
|
||||
/// CSS `linear-gradient(...)` string. Stops are emitted as `#rrggbbaa` hex (already gamma-encoded bytes).
|
||||
pub fn to_css_linear_gradient(&self) -> String {
|
||||
if self.position.len() <= 1 {
|
||||
@@ -67,7 +67,7 @@ impl GradientStopsUI {
|
||||
return format!("linear-gradient(to right, #{hex} 0%, #{hex} 100%)");
|
||||
}
|
||||
// Sample via the midpoint-aware subdivision used for SVG/Vello stops so browser interpolation matches
|
||||
let stops: GradientStops = self.into();
|
||||
let stops: Gradient = self.into();
|
||||
let pieces = stops
|
||||
.interpolated_samples()
|
||||
.into_iter()
|
||||
@@ -83,7 +83,7 @@ impl GradientStopsUI {
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
impl<'de> serde::Deserialize<'de> for GradientStops {
|
||||
impl<'de> serde::Deserialize<'de> for Gradient {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct NewFormat {
|
||||
@@ -117,7 +117,7 @@ impl<'de> serde::Deserialize<'de> for GradientStops {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GradientStops {
|
||||
impl Default for Gradient {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
position: vec![0., 1.],
|
||||
@@ -127,7 +127,7 @@ impl Default for GradientStops {
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for GradientStops {
|
||||
impl RenderComplexity for Gradient {
|
||||
fn render_complexity(&self) -> usize {
|
||||
1
|
||||
}
|
||||
@@ -158,7 +158,7 @@ pub struct GradientStop {
|
||||
}
|
||||
|
||||
pub struct GradientStopsIter<'a> {
|
||||
stops: &'a GradientStops,
|
||||
stops: &'a Gradient,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
@@ -187,7 +187,7 @@ impl<'a> Iterator for GradientStopsIter<'a> {
|
||||
|
||||
impl ExactSizeIterator for GradientStopsIter<'_> {}
|
||||
|
||||
impl<'a> IntoIterator for &'a GradientStops {
|
||||
impl<'a> IntoIterator for &'a Gradient {
|
||||
type Item = GradientStop;
|
||||
type IntoIter = GradientStopsIter<'a>;
|
||||
|
||||
@@ -196,7 +196,7 @@ impl<'a> IntoIterator for &'a GradientStops {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for GradientStops {
|
||||
impl IntoIterator for Gradient {
|
||||
type Item = GradientStop;
|
||||
type IntoIter = std::vec::IntoIter<GradientStop>;
|
||||
|
||||
@@ -211,7 +211,7 @@ impl IntoIterator for GradientStops {
|
||||
}
|
||||
}
|
||||
|
||||
impl GradientStops {
|
||||
impl Gradient {
|
||||
pub fn new(stops: impl IntoIterator<Item = GradientStop>) -> Self {
|
||||
let mut position = Vec::new();
|
||||
let mut midpoint = Vec::new();
|
||||
@@ -465,7 +465,7 @@ impl GradientStops {
|
||||
let color = a.color.lerp(&b.color, time as f32);
|
||||
GradientStop { position, midpoint: 0.5, color }
|
||||
});
|
||||
GradientStops::new(stops)
|
||||
Gradient::new(stops)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -540,19 +540,19 @@ pub fn initial_gradient_transform_for_bounding_box(bounds: [DVec2; 2]) -> DAffin
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
pub fn migrate_to_gradient_stops<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<GradientStops, D::Error> {
|
||||
pub fn migrate_to_gradient<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Gradient, D::Error> {
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct LegacyTable {
|
||||
#[serde(alias = "instances", alias = "instance")]
|
||||
element: Vec<GradientStops>,
|
||||
element: Vec<Gradient>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[cfg_attr(feature = "serde", serde(untagged))]
|
||||
enum GradientStopsFormat {
|
||||
Stops(GradientStops),
|
||||
Stops(Gradient),
|
||||
List(LegacyTable),
|
||||
}
|
||||
|
||||
@@ -562,7 +562,7 @@ pub fn migrate_to_gradient_stops<'de, D: serde::Deserializer<'de>>(deserializer:
|
||||
})
|
||||
}
|
||||
|
||||
impl core_types::bounds::BoundingBox for GradientStops {
|
||||
impl core_types::bounds::BoundingBox for Gradient {
|
||||
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> core_types::bounds::RenderBoundingBox {
|
||||
core_types::bounds::RenderBoundingBox::Infinite
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
pub mod attr;
|
||||
pub mod gradient;
|
||||
pub mod math;
|
||||
pub mod subpath;
|
||||
@@ -8,7 +9,7 @@ pub mod vector;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use core_types as gcore;
|
||||
pub use gradient::{GradientSpreadMethod, GradientStop, GradientStops, GradientType};
|
||||
pub use gradient::{Gradient, GradientSpreadMethod, GradientStop, GradientType};
|
||||
pub use math::{QuadExt, RectExt};
|
||||
pub use subpath::Subpath;
|
||||
pub use vector::Vector;
|
||||
|
||||
@@ -47,7 +47,7 @@ impl MergeByDistanceExt for Vector {
|
||||
// Collect points and segments to delete at the end to avoid invalidating indices
|
||||
let mut points_to_delete = FxHashSet::default();
|
||||
let mut segments_to_delete = FxHashSet::default();
|
||||
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position.into_iter()) {
|
||||
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) {
|
||||
// Remove any segments where both endpoints are in the collapse set
|
||||
segments_to_delete.extend(self.segment_domain.iter().filter_map(|(id, start_offset, end_offset, _)| {
|
||||
let start = self.point_domain.ids()[start_offset];
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::PointId;
|
||||
use super::algorithms::offset_subpath::MAX_ABSOLUTE_DIFFERENCE;
|
||||
use crate::subpath::{BezierHandles, ManipulatorGroup};
|
||||
use crate::vector::{SegmentId, Vector};
|
||||
use core_types::list::{Item, List};
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveDeriv, PathSeg, Point, QuadBez};
|
||||
@@ -49,6 +50,77 @@ pub enum RowsOrColumns {
|
||||
Columns,
|
||||
}
|
||||
|
||||
/// A box's four corner values, such as a rectangle's corner radii, expanded on read from any number of stored
|
||||
/// values by the CSS `border-radius` shorthand rules.
|
||||
///
|
||||
/// Wraps a `List<f64>` so the Data panel can introspect its values, mirroring how `DashPattern` wraps its lengths,
|
||||
/// while remaining a single rank-0 value on the wire.
|
||||
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
|
||||
pub struct BoxCorners(pub List<f64>);
|
||||
|
||||
impl BoxCorners {
|
||||
/// Expands the stored values to the four corners, clockwise from the top-left, by the CSS `border-radius` shorthand rules.
|
||||
/// - `[]` → `[0, 0, 0, 0]`
|
||||
/// - `[a]` → `[a, a, a, a]`
|
||||
/// - `[a, b]` → `[a, b, a, b]`
|
||||
/// - `[a, b, c]` → `[a, b, c, b]`
|
||||
/// - `[a, b, c, d, …]` → `[a, b, c, d]`
|
||||
pub fn to_corner_values(&self) -> [f64; 4] {
|
||||
let values: Vec<f64> = self.0.iter_element_values().copied().collect();
|
||||
match values.as_slice() {
|
||||
[] => [0., 0., 0., 0.],
|
||||
&[a] => [a, a, a, a],
|
||||
&[a, b] => [a, b, a, b],
|
||||
&[a, b, c] => [a, b, c, b],
|
||||
&[a, b, c, d, ..] => [a, b, c, d],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `List<f64>` is a runtime-only wire type, so serialize the corners as their bare values to keep documents stable
|
||||
#[cfg(feature = "serde")]
|
||||
impl serde::Serialize for BoxCorners {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_seq(self.0.iter_element_values())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de> serde::Deserialize<'de> for BoxCorners {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
Ok(Self::from(<Vec<f64> as serde::Deserialize>::deserialize(deserializer)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for BoxCorners {
|
||||
fn from(value: f64) -> Self {
|
||||
Self(List::new_from_element(value))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<f64>> for BoxCorners {
|
||||
fn from(values: Vec<f64>) -> Self {
|
||||
Self(values.into_iter().map(Item::new_from_element).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for BoxCorners {
|
||||
fn from(text: &str) -> Self {
|
||||
Self::from(
|
||||
text.split([',', ' '])
|
||||
.filter(|piece| !piece.is_empty())
|
||||
.filter_map(|piece| piece.parse::<f64>().ok())
|
||||
.collect::<Vec<f64>>(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for BoxCorners {
|
||||
fn from(text: String) -> Self {
|
||||
Self::from(text.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
pub trait AsU64 {
|
||||
fn as_u64(&self) -> u64;
|
||||
}
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
pub use crate::gradient::*;
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::Transform;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
/// Describes an editable fill choice, storing color or gradient stops without gradient placement metadata.
|
||||
/// The editor's in-memory paint picker state, storing color or gradient stops without gradient placement metadata.
|
||||
/// Not stored in documents: paint inputs hold the picked value as a plain color, gradient, or no-paint type default.
|
||||
///
|
||||
/// Can be None, a solid [Color], or a linear/radial [GradientStops].
|
||||
/// Can be None, a solid [Color], or a linear/radial [Gradient].
|
||||
///
|
||||
/// In the future we'll probably also add a pattern fill.
|
||||
///
|
||||
@@ -22,11 +24,11 @@ pub enum FillChoice {
|
||||
#[default]
|
||||
None,
|
||||
Solid(Color),
|
||||
Gradient(GradientStops),
|
||||
Gradient(Gradient),
|
||||
}
|
||||
|
||||
// TODO: Deprecate [`FillChoice`] and keep this, renamed, as the main widget-controlling type
|
||||
/// JS-boundary version of [`FillChoice`] where the solid color is [`SRGBA8`] and the gradient is [`GradientStopsUI`].
|
||||
/// JS-boundary version of [`FillChoice`] where the solid color is [`SRGBA8`] and the gradient is [`GradientUI`].
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Default, Debug, Clone, PartialEq, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
@@ -34,7 +36,7 @@ pub enum FillChoiceUI {
|
||||
#[default]
|
||||
None,
|
||||
Solid(SRGBA8),
|
||||
Gradient(GradientStopsUI),
|
||||
Gradient(GradientUI),
|
||||
}
|
||||
|
||||
impl From<&FillChoice> for FillChoiceUI {
|
||||
@@ -42,7 +44,7 @@ impl From<&FillChoice> for FillChoiceUI {
|
||||
match value {
|
||||
FillChoice::None => Self::None,
|
||||
FillChoice::Solid(color) => Self::Solid(SRGBA8::from(*color)),
|
||||
FillChoice::Gradient(stops) => Self::Gradient(GradientStopsUI::from(stops)),
|
||||
FillChoice::Gradient(stops) => Self::Gradient(GradientUI::from(stops)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +54,7 @@ impl From<&FillChoiceUI> for FillChoice {
|
||||
match value {
|
||||
FillChoiceUI::None => Self::None,
|
||||
FillChoiceUI::Solid(srgba) => Self::Solid(Color::from(*srgba)),
|
||||
FillChoiceUI::Gradient(stops) => Self::Gradient(GradientStops::from(stops)),
|
||||
FillChoiceUI::Gradient(stops) => Self::Gradient(Gradient::from(stops)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,7 +65,7 @@ impl FillChoiceUI {
|
||||
Some(*c)
|
||||
}
|
||||
|
||||
pub fn as_gradient(&self) -> Option<&GradientStopsUI> {
|
||||
pub fn as_gradient(&self) -> Option<&GradientUI> {
|
||||
let Self::Gradient(g) = self else { return None };
|
||||
Some(g)
|
||||
}
|
||||
@@ -88,7 +90,7 @@ impl FillChoice {
|
||||
Some(*color)
|
||||
}
|
||||
|
||||
pub fn as_gradient(&self) -> Option<&GradientStops> {
|
||||
pub fn as_gradient(&self) -> Option<&Gradient> {
|
||||
let Self::Gradient(gradient) = self else { return None };
|
||||
Some(gradient)
|
||||
}
|
||||
@@ -201,6 +203,65 @@ fn daffine2_identity() -> DAffine2 {
|
||||
DAffine2::IDENTITY
|
||||
}
|
||||
|
||||
/// A stroke's dash pattern: a sequence of lengths that alternate dash, gap, dash, gap, and so on. An odd-length
|
||||
/// sequence repeats with the dash and gap roles swapped.
|
||||
///
|
||||
/// Wraps a `List<f64>` so the Data panel can introspect its lengths, mirroring how `Artboard` wraps a `List<Graphic>`,
|
||||
/// while remaining a single rank-0 value on the wire.
|
||||
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
|
||||
pub struct DashPattern(pub List<f64>);
|
||||
|
||||
impl DashPattern {
|
||||
/// Returns the dash lengths with any negative values clamped to zero.
|
||||
pub fn clamped_lengths(&self) -> Vec<f64> {
|
||||
self.0.iter_element_values().map(|length| length.max(0.)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
// `List<f64>` is a runtime-only wire type, so serialize the pattern as its bare lengths to keep documents stable
|
||||
#[cfg(feature = "serde")]
|
||||
impl serde::Serialize for DashPattern {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_seq(self.0.iter_element_values())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de> serde::Deserialize<'de> for DashPattern {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
Ok(Self::from(<Vec<f64> as serde::Deserialize>::deserialize(deserializer)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for DashPattern {
|
||||
fn from(length: f64) -> Self {
|
||||
Self(List::new_from_element(length))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<f64>> for DashPattern {
|
||||
fn from(lengths: Vec<f64>) -> Self {
|
||||
Self(lengths.into_iter().map(Item::new_from_element).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for DashPattern {
|
||||
fn from(text: &str) -> Self {
|
||||
Self::from(
|
||||
text.split([',', ' '])
|
||||
.filter(|piece| !piece.is_empty())
|
||||
.filter_map(|piece| piece.parse::<f64>().ok())
|
||||
.collect::<Vec<f64>>(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for DashPattern {
|
||||
fn from(text: String) -> Self {
|
||||
Self::from(text.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
|
||||
|
||||
@@ -629,6 +629,10 @@ where
|
||||
deserializer.deserialize_seq(visitor)
|
||||
}
|
||||
|
||||
/// Distance below which a path's closing point is treated as coincident with its start point.
|
||||
/// Matches Kurbo's default path accuracy, so points within an offset operation's own precision are not split into separate anchors.
|
||||
const CLOSE_POINT_TOLERANCE: f64 = 1e-6;
|
||||
|
||||
pub struct AppendBezpath<'a> {
|
||||
first_point: Option<Point>,
|
||||
last_point: Option<Point>,
|
||||
@@ -657,7 +661,11 @@ impl<'a> AppendBezpath<'a> {
|
||||
}
|
||||
|
||||
fn append_segment_and_close_path(&mut self, point: Point, handle: BezierHandles) {
|
||||
let handle = if self.first_point.unwrap() != point {
|
||||
// A path's final point may return to approximately (but not bit-exactly) its start before closing, e.g. a contour
|
||||
// produced by Kurbo's path offsetting. Treat a near-coincident final point as already on the start so we don't
|
||||
// introduce a redundant duplicate anchor and a zero-length closing segment.
|
||||
let endpoints_coincide = (self.first_point.unwrap() - point).hypot2() <= CLOSE_POINT_TOLERANCE * CLOSE_POINT_TOLERANCE;
|
||||
let handle = if !endpoints_coincide {
|
||||
// If the first point is not the same as the last point of the path then we append the segment
|
||||
// with given handle and point and then close the path with linear handle.
|
||||
self.append_segment(point, handle);
|
||||
|
||||
@@ -63,11 +63,19 @@ impl core_types::ops::FromAnchorPosition for Vector {
|
||||
}
|
||||
}
|
||||
|
||||
// Identity item conversion so `List<Vector>` satisfies the blanket `Convert<List<U>, ()> for List<T>`, letting its
|
||||
// auto-inserted input wrapper be a `ConvertNode` (which also accepts a `DVec2` anchor position) rather than an `IntoNode`.
|
||||
impl core_types::ops::ListConvert<Vector> for Vector {
|
||||
fn convert_item(self) -> Vector {
|
||||
self
|
||||
// Lets a position wire feed a ranked vector connector through the input adapter's element conversion
|
||||
impl From<DVec2> for Vector {
|
||||
fn from(position: DVec2) -> Self {
|
||||
<Self as core_types::ops::FromAnchorPosition>::from_anchor_position(position)
|
||||
}
|
||||
}
|
||||
|
||||
impl core_types::transform::BakeTransform for Vector {
|
||||
fn bake_transform(&mut self, transform: &glam::DAffine2) {
|
||||
for (_, point) in self.point_domain.positions_mut() {
|
||||
*point = transform.transform_point2(*point);
|
||||
}
|
||||
self.segment_domain.transform(*transform);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ impl PipelineCache {
|
||||
pub async fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
|
||||
let executor = self.executor.get().expect("PipelineCache not initialized");
|
||||
let entry = self.pipeline.get().expect("PipelineCache not initialized");
|
||||
let pipeline = (&**entry)
|
||||
let pipeline = (**entry)
|
||||
.downcast_ref::<P>()
|
||||
.unwrap_or_else(|| panic!("PipelineCache type mismatch: run::<{}>() but init used a different pipeline type", std::any::type_name::<P>(),));
|
||||
pipeline.run(executor, args).await
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::WgpuExecutor;
|
||||
use core_types::Color;
|
||||
use core_types::Ctx;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::ops::Convert;
|
||||
@@ -20,7 +19,7 @@ fn upload_to_texture(device: &wgpu::Device, queue: &wgpu::Queue, image: &Raster<
|
||||
device.create_texture_with_data(
|
||||
queue,
|
||||
&TextureDescriptor {
|
||||
label: Some("upload_texture node texture"),
|
||||
label: Some("upload_to_texture staging texture"),
|
||||
size: Extent3d {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
@@ -247,15 +246,3 @@ impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> {
|
||||
converter.convert(device).await.expect("Failed to download texture data")
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads an raster texture from the CPU to the GPU. This is now deprecated and the Convert node should be used in the future.
|
||||
///
|
||||
/// Accepts either individual raster data or a `List` of raster elements and converts it to the GPU format using the WgpuExecutor's device and queue.
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn upload_texture<'a: 'n, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T,
|
||||
executor: &'a WgpuExecutor,
|
||||
) -> List<Raster<GPU>> {
|
||||
input.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
@@ -13,6 +13,9 @@ license = "Apache-2.0"
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[features]
|
||||
disable-registration = []
|
||||
|
||||
[dependencies]
|
||||
# Workspace dependencies
|
||||
syn = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
use crate::crate_ident::CrateIdent;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::parse::ParseStream;
|
||||
use syn::{Attribute, Expr, Ident, Token, Type, braced, token};
|
||||
|
||||
/// Implementation of the `attrs!` macro declaring typed attribute keys.
|
||||
///
|
||||
/// Grammar: `Name: Type`, comma-separated; `namespace { ... }` blocks nest and contribute a
|
||||
/// `namespace:` prefix to the key name, which is otherwise derived mechanically from the key
|
||||
/// ident (UpperCamel → snake_case). An optional `= value` after the type declares the key's
|
||||
/// implicit default, overriding the value type's `Default` for items lacking the attribute.
|
||||
pub fn attrs_impl(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
let entries: Entries = syn::parse2(input)?;
|
||||
let crate_ident = CrateIdent::default();
|
||||
let core = crate_ident.gcore()?;
|
||||
|
||||
let items = entries.0.iter().map(|entry| generate_entry(entry, core, "")).collect::<syn::Result<Vec<_>>>()?;
|
||||
let lookup = generate_implicit_default_lookup(&entries.0, core);
|
||||
|
||||
Ok(quote! {
|
||||
#(#items)*
|
||||
#lookup
|
||||
})
|
||||
}
|
||||
|
||||
struct Entries(Vec<Entry>);
|
||||
|
||||
enum Entry {
|
||||
Key {
|
||||
docs: Vec<Attribute>,
|
||||
ident: Ident,
|
||||
ty: Box<Type>,
|
||||
default: Option<Box<Expr>>,
|
||||
},
|
||||
Namespace {
|
||||
docs: Vec<Attribute>,
|
||||
ident: Ident,
|
||||
entries: Vec<Entry>,
|
||||
},
|
||||
}
|
||||
|
||||
impl syn::parse::Parse for Entries {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self(parse_entries(input)?))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_entries(input: ParseStream) -> syn::Result<Vec<Entry>> {
|
||||
let mut entries = Vec::new();
|
||||
while !input.is_empty() {
|
||||
let docs = input.call(Attribute::parse_outer)?;
|
||||
let ident: Ident = input.parse()?;
|
||||
if input.peek(token::Brace) {
|
||||
let content;
|
||||
braced!(content in input);
|
||||
entries.push(Entry::Namespace {
|
||||
docs,
|
||||
ident,
|
||||
entries: parse_entries(&content)?,
|
||||
});
|
||||
} else {
|
||||
input.parse::<Token![:]>()?;
|
||||
let ty = Box::new(input.parse::<Type>()?);
|
||||
let default = if input.peek(Token![=]) {
|
||||
input.parse::<Token![=]>()?;
|
||||
Some(Box::new(input.parse::<Expr>()?))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
entries.push(Entry::Key { docs, ident, ty, default });
|
||||
}
|
||||
if !input.is_empty() {
|
||||
input.parse::<Token![,]>()?;
|
||||
}
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn generate_entry(entry: &Entry, core: &TokenStream, prefix: &str) -> syn::Result<TokenStream> {
|
||||
match entry {
|
||||
Entry::Key { docs, ident, ty, default } => {
|
||||
let name = key_name(ident, prefix);
|
||||
let implicit_default = default.as_ref().map(|value| {
|
||||
quote! {
|
||||
fn implicit_default() -> Self::Value {
|
||||
#value
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(quote! {
|
||||
#(#docs)*
|
||||
pub struct #ident;
|
||||
impl #core::attr::Attr for #ident {
|
||||
type Value = #ty;
|
||||
fn name() -> &'static str {
|
||||
#name
|
||||
}
|
||||
#implicit_default
|
||||
}
|
||||
})
|
||||
}
|
||||
Entry::Namespace { docs, ident, entries } => {
|
||||
let child_prefix = child_prefix(ident, prefix);
|
||||
let items = entries.iter().map(|entry| generate_entry(entry, core, &child_prefix)).collect::<syn::Result<Vec<_>>>()?;
|
||||
Ok(quote! {
|
||||
#(#docs)*
|
||||
pub mod #ident {
|
||||
use super::*;
|
||||
#(#items)*
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a string-keyed lookup of the boxed implicit defaults for erased attribute code paths,
|
||||
/// or nothing if no key in this invocation declares a `= value` default.
|
||||
fn generate_implicit_default_lookup(entries: &[Entry], core: &TokenStream) -> Option<TokenStream> {
|
||||
let mut defaulted_keys = Vec::new();
|
||||
collect_defaulted_key_paths(entries, &TokenStream::new(), &mut defaulted_keys);
|
||||
|
||||
if defaulted_keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(quote! {
|
||||
/// The boxed implicit default for the key named `key`, if that key declares one with `= value` in `attrs!`.
|
||||
pub fn implicit_default_value(key: &str) -> ::std::option::Option<::std::boxed::Box<dyn #core::list::AnyAttributeValue>> {
|
||||
#(
|
||||
if key == <#defaulted_keys as #core::attr::Attr>::name() {
|
||||
return ::std::option::Option::Some(::std::boxed::Box::new(<#defaulted_keys as #core::attr::Attr>::implicit_default()));
|
||||
}
|
||||
)*
|
||||
::std::option::Option::None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Walks the entry tree collecting module-qualified paths (like `namespace::Key`) of keys that declare a default.
|
||||
fn collect_defaulted_key_paths(entries: &[Entry], module_path: &TokenStream, paths: &mut Vec<TokenStream>) {
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Entry::Key { ident, default: Some(_), .. } => paths.push(quote!(#module_path #ident)),
|
||||
Entry::Key { .. } => {}
|
||||
Entry::Namespace { ident, entries, .. } => collect_defaulted_key_paths(entries, "e!(#module_path #ident::), paths),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_name(ident: &Ident, prefix: &str) -> String {
|
||||
let snake = snake_case(&ident.to_string());
|
||||
if prefix.is_empty() { snake } else { format!("{prefix}:{snake}") }
|
||||
}
|
||||
|
||||
fn child_prefix(ident: &Ident, prefix: &str) -> String {
|
||||
if prefix.is_empty() { ident.to_string() } else { format!("{prefix}:{ident}") }
|
||||
}
|
||||
|
||||
fn snake_case(name: &str) -> String {
|
||||
let mut result = String::with_capacity(name.len() + 4);
|
||||
for (i, c) in name.chars().enumerate() {
|
||||
if c.is_uppercase() {
|
||||
if i > 0 {
|
||||
result.push('_');
|
||||
}
|
||||
result.extend(c.to_lowercase());
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ use proc_macro::TokenStream;
|
||||
use proc_macro_error2::proc_macro_error;
|
||||
use syn::GenericParam;
|
||||
|
||||
mod attrs;
|
||||
mod buffer_struct;
|
||||
mod codegen;
|
||||
mod crate_ident;
|
||||
@@ -33,6 +34,13 @@ pub fn derive_choice_type(input_item: TokenStream) -> TokenStream {
|
||||
derive_choice_type::derive_choice_type_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Declares typed attribute keys implementing the `Attr` trait, plus a wire-name lookup for their
|
||||
/// implicit defaults. See `core_types::attr` for the trait and syntax.
|
||||
#[proc_macro]
|
||||
pub fn attrs(input: TokenStream) -> TokenStream {
|
||||
attrs::attrs_impl(input.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Derive a struct to implement `ShaderStruct`, see that for docs.
|
||||
#[proc_macro_derive(BufferStruct)]
|
||||
pub fn derive_buffer_struct(input_item: TokenStream) -> TokenStream {
|
||||
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user