mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3902163e03 | ||
|
|
99824a70a9 | ||
|
|
c25410185c | ||
|
|
93665c5e9d | ||
|
|
ccb02ddf8d | ||
|
|
305cd02332 | ||
|
|
3394695fb9 | ||
|
|
47f56b481c | ||
|
|
bdab64eb29 | ||
|
|
0fe91cc0fd | ||
|
|
06672ddb39 | ||
|
|
e060233d7c | ||
|
|
70e0c51fae | ||
|
|
3e46541ea0 | ||
|
|
526e760792 | ||
|
|
4749e2518f | ||
|
|
07acbfad9f | ||
|
|
aca1805fcf | ||
|
|
35b9153f27 | ||
|
|
93ca25ebe5 | ||
|
|
6ef640c288 | ||
|
|
0f21bbc337 | ||
|
|
fee15b9048 | ||
|
|
6c52714194 | ||
|
|
f5f1b09eec | ||
|
|
5528af9617 | ||
|
|
1863e9ea67 | ||
|
|
ea17f690a2 | ||
|
|
6d3951b26f | ||
|
|
225c2cde98 | ||
|
|
3799e55491 | ||
|
|
74a80b61bd | ||
|
|
951005e5cf |
No files matched your search
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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":fLine 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":fLine 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":""}}],[194878846429432339,{"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],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":""}}],[194878846429432339,{"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],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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::adjustments::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":{"I64":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":{"I64":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_vaLine 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"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_Line 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"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::sLine 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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"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::sLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"node_id":14158287945315818946,"outLine 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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":{"node_id":14158287945315818946,"outLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":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":{"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]]]},"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":{"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":"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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::OwnedContextImpLine 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":{"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":"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":{"GradientRamp":{"stops":{"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}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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":2Line 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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_Line 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::AsGraphicNode"}},"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::IntoGroupNode"}},"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::AsGraphicNode"}},"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::IntoGroupNode"}},"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_Line truncated
|
||||
@@ -292,16 +292,24 @@ impl<L: Layout> Gdd<L> {
|
||||
(working, self.layout)
|
||||
}
|
||||
|
||||
/// Resolve every proto-node declaration referenced by the registry or its history into a
|
||||
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
|
||||
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
|
||||
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
|
||||
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
|
||||
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
|
||||
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
|
||||
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
|
||||
/// because resource loads are.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
|
||||
use document_graph_storage::Implementation;
|
||||
|
||||
let registry = self.session.registry();
|
||||
let mut declarations = document_graph_storage::Declarations::new();
|
||||
|
||||
for (id, hash) in self.session.all_declaration_resources() {
|
||||
let Some(hash) = hash else {
|
||||
for node in registry.node_instances.values() {
|
||||
let Implementation::ProtoNode(id) = node.implementation() else { continue };
|
||||
if declarations.contains_key(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
|
||||
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
||||
continue;
|
||||
};
|
||||
@@ -311,7 +319,7 @@ impl<L: Layout> Gdd<L> {
|
||||
};
|
||||
match document_graph_storage::decode_declaration(resource.as_ref()) {
|
||||
Ok(proto) => {
|
||||
declarations.insert(id, proto);
|
||||
declarations.insert(*id, proto);
|
||||
}
|
||||
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
|
||||
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
|
||||
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
|
||||
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
|
||||
/// interaction.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
|
||||
@@ -60,8 +60,8 @@ impl<L: Layout> Gdd<L> {
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
) -> Result<(), Error> {
|
||||
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
@@ -70,10 +70,10 @@ impl<L: Layout> Gdd<L> {
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
// identical bytes on every commit is an idempotent no-op.
|
||||
for bytes in conversion.declaration_bytes.values() {
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(conversion.declarations)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
|
||||
@@ -117,17 +117,33 @@ impl TryFrom<&NodeNetwork> for Registry {
|
||||
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
|
||||
|
||||
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
|
||||
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
|
||||
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
|
||||
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
|
||||
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
|
||||
/// the `ResourceId`/`ResourceHash` references.
|
||||
pub struct RuntimeConversion {
|
||||
pub registry: Registry,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
pub declarations: crate::Declarations,
|
||||
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
|
||||
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
|
||||
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||
}
|
||||
|
||||
impl RuntimeConversion {
|
||||
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
|
||||
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
|
||||
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
|
||||
/// their byte store instead.
|
||||
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
|
||||
self.declaration_bytes
|
||||
.iter()
|
||||
.map(|(hash, bytes)| {
|
||||
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
|
||||
Ok((ResourceId::from_hash(hash), proto))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
|
||||
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
|
||||
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
|
||||
@@ -161,7 +177,6 @@ impl Registry {
|
||||
let mut ctx = ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
@@ -180,7 +195,6 @@ impl Registry {
|
||||
Ok(RuntimeConversion {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
@@ -275,8 +289,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
||||
declaration_ids: HashMap<String, ResourceId>,
|
||||
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
|
||||
declaration_bytes: DeclarationBytes,
|
||||
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
|
||||
declarations: crate::Declarations,
|
||||
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
|
||||
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
|
||||
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||
@@ -614,7 +626,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
|
||||
}
|
||||
|
||||
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
|
||||
/// import, and a reflection node's metadata.
|
||||
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
|
||||
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
|
||||
let mut attributes = crate::Attributes::new();
|
||||
let timestamp = TimeStamp::ORIGIN;
|
||||
@@ -665,7 +677,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
|
||||
register_declaration_resource(registry, id, hash, ctx.peer);
|
||||
ctx.declaration_bytes.insert(hash, bytes);
|
||||
ctx.declarations.insert(id, proto);
|
||||
ctx.declaration_ids.insert(identifier_str, id);
|
||||
|
||||
Implementation::ProtoNode(id)
|
||||
@@ -759,7 +770,6 @@ impl<'m> ScopedConversion<'m> {
|
||||
ctx: ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
@@ -819,10 +829,9 @@ impl<'m> ScopedConversion<'m> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
|
||||
/// declarations decoded for its declaration cache.
|
||||
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
|
||||
(self.ctx.declaration_bytes, self.ctx.declarations)
|
||||
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
|
||||
pub fn finish(self) -> DeclarationBytes {
|
||||
self.ctx.declaration_bytes
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,9 +38,10 @@ pub struct NetworkMetadataEntry {
|
||||
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
|
||||
/// (the node-graph nav, in `session.json`) with a network across reparenting.
|
||||
pub network_id: crate::NetworkId,
|
||||
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
|
||||
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
|
||||
pub reference: Option<String>,
|
||||
/// The display order of the network's pinned nodes.
|
||||
/// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
|
||||
/// a shared set with per-peer ordering could never reconcile.
|
||||
pub pinned_order: Vec<RuntimeNodeId>,
|
||||
}
|
||||
|
||||
@@ -97,12 +98,9 @@ pub trait NodeMetadataSource {
|
||||
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The definition the network was instantiated from, if it still names one.
|
||||
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The display order of the network's pinned nodes.
|
||||
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
|
||||
Vec::new()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -64,7 +64,8 @@ impl Session {
|
||||
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
|
||||
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
|
||||
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
|
||||
/// conversion, whose extracted declarations the caller persists and caches.
|
||||
/// proto-node declaration bytes the conversion extracted, keyed by content hash, for the caller
|
||||
/// to persist into its byte store (`document-graph-storage` itself is byte-unaware).
|
||||
///
|
||||
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
|
||||
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
||||
@@ -75,11 +76,11 @@ impl Session {
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
Ok((hot_ops, conversion))
|
||||
Ok((hot_ops, conversion.declaration_bytes))
|
||||
}
|
||||
|
||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
||||
@@ -478,40 +479,6 @@ impl Session {
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
|
||||
/// with its content hash, or `None` where the hash never resolved.
|
||||
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
|
||||
let registry = &self.document.working_registry;
|
||||
|
||||
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
|
||||
for delta in self.document.history.iter() {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
|
||||
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
|
||||
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
|
||||
hashes.insert(*id, *hash);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let current_nodes = registry.node_instances.values();
|
||||
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
|
||||
RegistryDelta::AddNode { node, .. } => Some(node),
|
||||
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
current_nodes
|
||||
.chain(historic_nodes)
|
||||
.filter_map(|node| match node.implementation() {
|
||||
Implementation::ProtoNode(id) => Some(*id),
|
||||
Implementation::Network(_) => None,
|
||||
})
|
||||
.map(|id| (id, hashes.get(&id).copied()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn hot_log(&self) -> &[HotOp] {
|
||||
&self.document.hot_log
|
||||
}
|
||||
|
||||
@@ -20,10 +20,12 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
|
||||
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
||||
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
|
||||
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
|
||||
/// `Declarations` map for the back-conversion.
|
||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
|
||||
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
|
||||
(conversion.registry, conversion.declarations)
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
(conversion.registry, declarations)
|
||||
}
|
||||
|
||||
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
|
||||
@@ -475,7 +477,7 @@ fn test_ui_metadata_round_trip() {
|
||||
);
|
||||
|
||||
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
|
||||
let declarations = conversion.declarations;
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
||||
|
||||
@@ -266,7 +266,7 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
|
||||
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
|
||||
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
|
||||
/// rather than failing the conversion: a pinned node can have been deleted.
|
||||
/// rather than failing the conversion: the preview target or a pinned node can have been deleted.
|
||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
let to_runtime_id = |storage_id: NodeId| {
|
||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||
|
||||
@@ -215,6 +215,10 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<Gradient>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<f32>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<i32>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
@@ -271,6 +275,10 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<Gradient>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<f32>,
|
||||
Item<u32>,
|
||||
Item<u64>,
|
||||
Item<i32>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
@@ -569,7 +577,7 @@ impl TableItemLayout for Coverage {
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
"Transfer Curve"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
let points = self.points().len();
|
||||
@@ -834,12 +842,37 @@ impl TableItemLayout for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i64 {
|
||||
macro_rules! impl_table_item_layout_for_number {
|
||||
($($ty:ty => $type_name:literal),* $(,)?) => {
|
||||
$(
|
||||
impl TableItemLayout for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
$type_name
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_number!(
|
||||
u32 => "Number (u32)",
|
||||
i32 => "Number (i32)",
|
||||
u64 => "Number (u64)",
|
||||
i64 => "Number (i64)",
|
||||
);
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Integer"
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
|
||||
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
@@ -935,6 +968,26 @@ fn string_preview(value: &str) -> String {
|
||||
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
|
||||
}
|
||||
|
||||
impl TableItemLayout for Option<f64> {
|
||||
fn type_name() -> &'static str {
|
||||
"Option<f64>"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Option<f64>".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let text = match self {
|
||||
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
|
||||
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for DVec2 {
|
||||
fn type_name() -> &'static str {
|
||||
"Vec2"
|
||||
@@ -1219,8 +1272,13 @@ macro_rules! known_item_types {
|
||||
DVec2,
|
||||
Affine2,
|
||||
Vec2,
|
||||
Option<f64>,
|
||||
f64,
|
||||
f32,
|
||||
u8,
|
||||
u32,
|
||||
u64,
|
||||
i32,
|
||||
i64,
|
||||
bool,
|
||||
String,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::{Declarations, Registry};
|
||||
use document_graph_storage::Registry;
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
|
||||
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
|
||||
@@ -25,19 +25,6 @@ pub struct DocumentHistory {
|
||||
/// future built by `load_document` resolves.
|
||||
#[derivative(Debug = "ignore")]
|
||||
storage: Option<document_format::GddV1>,
|
||||
/// Decoded proto-node declarations for every registry state the cursor can reach, filled at mount
|
||||
/// and extended on each staging, so a cursor rebuild never touches the byte store.
|
||||
#[derivative(Debug = "ignore")]
|
||||
declarations: Declarations,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CursorMoveError {
|
||||
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
|
||||
NotMoved,
|
||||
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
|
||||
RebuildFailed,
|
||||
}
|
||||
|
||||
impl DocumentHistory {
|
||||
@@ -93,10 +80,9 @@ impl DocumentHistory {
|
||||
self.storage.as_mut()
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
self.storage = Some(storage);
|
||||
self.declarations = declarations;
|
||||
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
|
||||
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
|
||||
self.storage = storage;
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
|
||||
@@ -109,10 +95,11 @@ impl DocumentHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
|
||||
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
|
||||
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
|
||||
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
|
||||
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
|
||||
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
|
||||
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
|
||||
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
|
||||
/// round-trip check, off by default for its perf cost.
|
||||
pub fn stage_snapshot(
|
||||
&mut self,
|
||||
deltas: &[EditorDelta],
|
||||
@@ -124,27 +111,19 @@ impl DocumentHistory {
|
||||
) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
// A working copy that does not hold the document yet has no baseline for a batch of changes to apply
|
||||
// to. Reading that from the working copy rather than from the caller means a path that mounts storage
|
||||
// and then commits does not have to know which of the two cases it is in.
|
||||
// A working copy that does not hold the document yet has no baseline for a batch of changes to
|
||||
// apply to, so the first commit writes the whole document and every later one stages only what
|
||||
// the store recorded. Reading that from the working copy rather than from the caller means a path
|
||||
// that mounts storage and then commits does not have to know which of the two it is.
|
||||
let staged = match storage.registry().node_instances.is_empty() {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
// An autosave with nothing edited since the last commit still persists the view state below.
|
||||
false if deltas.is_empty() => Ok(Declarations::new()),
|
||||
// The batch is drained by the time it reaches here, so a failed staging would leave the working copy
|
||||
// permanently behind. Converting the whole document restages the same edit from whatever the working
|
||||
// copy holds, including a batch that failed partway through.
|
||||
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store).or_else(|error| {
|
||||
log::error!("Staging recorded deltas failed, falling back to a whole document snapshot: {error}");
|
||||
Self::stage_whole_document(storage, interface, registry, byte_store)
|
||||
}),
|
||||
false if deltas.is_empty() => Ok(()),
|
||||
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store),
|
||||
};
|
||||
match staged {
|
||||
Ok(declarations) => self.declarations.extend(declarations),
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
if let Err(error) = staged {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings, legacy_document);
|
||||
@@ -154,7 +133,7 @@ impl DocumentHistory {
|
||||
///
|
||||
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
|
||||
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<Declarations, String> {
|
||||
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
storage
|
||||
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
|
||||
@@ -173,19 +152,19 @@ impl DocumentHistory {
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<Declarations, String> {
|
||||
) -> Result<(), String> {
|
||||
let peer = storage.session().peer();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
|
||||
|
||||
storage
|
||||
.stage_constructed_ops(constructed.ops, &constructed.declarations.bytes, byte_store)
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(constructed.declarations.decoded)
|
||||
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
|
||||
/// dual-write soak validates the new format against.
|
||||
/// dual-write soak validates the new format against. Both staging paths persist them; they differ
|
||||
/// only in how the graph ops are derived.
|
||||
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
@@ -210,48 +189,31 @@ impl DocumentHistory {
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
|
||||
/// first, and rebuild the interface from the rewound registry using the declaration cache.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
|
||||
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
|
||||
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
|
||||
/// unmounted, or the move failed.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
|
||||
self.retire_storage_interaction();
|
||||
|
||||
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
|
||||
let storage = self.storage.as_mut()?;
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
return None;
|
||||
}
|
||||
storage.undo().map(|_| ())
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
return None;
|
||||
}
|
||||
storage.redo().map(|_| ())
|
||||
};
|
||||
if let Err(error) = moved {
|
||||
log::error!("Storage undo/redo cursor move failed: {error}");
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
return None;
|
||||
}
|
||||
|
||||
storage
|
||||
.registry()
|
||||
.to_runtime_with_full_metadata(&self.declarations)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
|
||||
.map_err(|error| {
|
||||
log::error!("Storage undo/redo rebuild failed: {error}");
|
||||
CursorMoveError::RebuildFailed
|
||||
})
|
||||
}
|
||||
|
||||
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
|
||||
/// direction whose rebuild failed.
|
||||
pub fn revert_cursor(&mut self, undo: bool) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let reverted = if undo { storage.redo() } else { storage.undo() };
|
||||
if let Err(error) = reverted {
|
||||
log::error!("Storage undo/redo cursor revert failed: {error}");
|
||||
}
|
||||
Some(storage.clone())
|
||||
}
|
||||
|
||||
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
|
||||
@@ -278,7 +240,13 @@ impl DocumentHistory {
|
||||
}
|
||||
};
|
||||
let target = &conversion.registry;
|
||||
let declarations = &conversion.declarations;
|
||||
let declarations = match conversion.declarations() {
|
||||
Ok(declarations) => declarations,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: declaration rebuild failed: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let stored = storage.registry();
|
||||
if !stored.value_equal(target) {
|
||||
@@ -292,7 +260,7 @@ impl DocumentHistory {
|
||||
panic!("storage round-trip: timestamp order inconsistent between stored and target");
|
||||
}
|
||||
|
||||
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
|
||||
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(&declarations) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: to_runtime failed: {error}");
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::DocumentHistory;
|
||||
use super::document_diff::diff_networks;
|
||||
use super::node_graph::document_node_definitions;
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
|
||||
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
|
||||
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
|
||||
use super::{CursorMoveError, DocumentHistory};
|
||||
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
|
||||
@@ -32,7 +32,6 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use document_graph_storage::Declarations;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
@@ -407,8 +406,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
|
||||
self.layer_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -1809,7 +1808,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
impl DocumentMessageHandler {
|
||||
/// Build a document handler from a `.gdd` working copy.
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
let mut document = Self {
|
||||
network_interface: interface,
|
||||
name,
|
||||
@@ -1822,7 +1821,7 @@ impl DocumentMessageHandler {
|
||||
Ok(resource_registry) => document.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
|
||||
}
|
||||
document.history.set_storage(storage, declarations);
|
||||
document.history.set_storage(Some(storage));
|
||||
|
||||
document
|
||||
}
|
||||
@@ -2017,9 +2016,9 @@ impl DocumentMessageHandler {
|
||||
self.history.storage_mut()
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
self.history.set_storage(storage, declarations);
|
||||
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
|
||||
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
|
||||
self.history.set_storage(storage);
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
|
||||
@@ -2092,23 +2091,24 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor and swap in the interface rebuilt from it. `had_oracle` records
|
||||
/// whether the legacy snapshot already applied, so the rebuild can be compared against it.
|
||||
fn drive_storage_undo_redo(&mut self, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
match self.history.move_cursor(undo) {
|
||||
Ok(rebuilt) => self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses),
|
||||
Err(CursorMoveError::NotMoved) => {}
|
||||
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
|
||||
Err(CursorMoveError::RebuildFailed) => {
|
||||
if !had_oracle {
|
||||
self.history.revert_cursor(undo);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Move the `Gdd` undo/redo cursor and spawn the async future that rebuilds the
|
||||
/// interface from the cursor and swaps it in. `had_oracle` records whether the legacy snapshot already
|
||||
/// applied, so the completion can compare; it travels with the spawned message. Returns whether the
|
||||
/// cursor moved, so callers know a rebuild is pending.
|
||||
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
|
||||
let Some(gdd) = self.history.move_cursor(undo) else { return false };
|
||||
|
||||
responses.add(crate::messages::portfolio::document_storage_io::rebuild_gdd_cursor(
|
||||
gdd,
|
||||
resource_storage.resources_mut(),
|
||||
document_id,
|
||||
had_oracle,
|
||||
));
|
||||
true
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
|
||||
rebuilt.load_structure();
|
||||
@@ -2419,7 +2419,7 @@ impl DocumentMessageHandler {
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
true
|
||||
@@ -2427,7 +2427,7 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(legacy_applied, true, validate, responses);
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
@@ -2461,7 +2461,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
true
|
||||
@@ -2469,7 +2469,7 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
@@ -2804,9 +2804,9 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
|
||||
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_i64, 1_i64);
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::I64(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);
|
||||
@@ -2828,7 +2828,7 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::I64(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);
|
||||
|
||||
+1
-1
@@ -287,7 +287,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided, referencing
|
||||
// its control path input by the Blend template's named position or the Morph proto node's parameter symbol
|
||||
let (path_input_connector, layer_alias, path_alias) = if let Some(count) = blend_count {
|
||||
let blend_node_id = modify_inputs.insert_blend_data(layer, count as i64);
|
||||
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
|
||||
(InputConnector::node_at_index(blend_node_id, BLEND_PATH_INPUT_INDEX), "Blend", "Blend Path")
|
||||
} else {
|
||||
let morph_node_id = modify_inputs.insert_morph_data(layer);
|
||||
|
||||
@@ -94,10 +94,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
|
||||
}
|
||||
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> NodeId {
|
||||
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(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::I64(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, &[]);
|
||||
|
||||
@@ -15,7 +15,7 @@ pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
pub(crate) use document_diff::diff_networks;
|
||||
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
|
||||
pub(crate) use document_history::DocumentHistory;
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -352,10 +352,10 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
// 3: Floor (integer count per subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(f64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -376,7 +376,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::I64(0), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -479,7 +479,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::I64(10), false),
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
@@ -801,7 +801,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(f64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
@@ -811,14 +811,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::I64(0), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::I64(0), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
@@ -833,7 +833,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::I64(0), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
@@ -927,6 +927,7 @@ fn static_node_properties() -> NodeProperties {
|
||||
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
|
||||
map.insert("selective_color_properties".to_string(), Box::new(node_properties::selective_color_properties));
|
||||
map.insert("exposure_properties".to_string(), Box::new(node_properties::exposure_properties));
|
||||
map.insert("math_properties".to_string(), Box::new(node_properties::math_properties));
|
||||
map.insert("format_number_properties".to_string(), Box::new(node_properties::format_number_properties));
|
||||
map.insert("string_capitalization_properties".to_string(), Box::new(node_properties::string_capitalization_properties));
|
||||
map.insert("rectangle_properties".to_string(), Box::new(node_properties::rectangle_properties));
|
||||
|
||||
@@ -2730,7 +2730,7 @@ impl NodeGraphMessageHandler {
|
||||
log::error!("Could not get position for node: {node_id}");
|
||||
continue;
|
||||
};
|
||||
// Asked of the preview itself rather than inferred from the export, which previewing does not rewire
|
||||
// Asked of the preview itself rather than inferred from the export, which previewing no longer rewires
|
||||
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
|
||||
|
||||
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
|
||||
|
||||
@@ -207,6 +207,7 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
|
||||
|
||||
match input.as_value()? {
|
||||
TaggedValue::F64(value) => Some(*value),
|
||||
TaggedValue::F32(value) => Some(*value as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -299,14 +300,16 @@ pub(crate) fn property_from_type(
|
||||
Type::Concrete(concrete_type) => {
|
||||
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
|
||||
// Aliased types (ambiguous values)
|
||||
Some("Percentage") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
|
||||
Some("SignedPercentage") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
|
||||
Some("Angle") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
|
||||
Some("Percentage") | Some("PercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
|
||||
Some("SignedPercentage") | Some("SignedPercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
|
||||
Some("Angle") | Some("AngleF32") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
|
||||
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
|
||||
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
|
||||
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
|
||||
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
Some("SignedInteger") => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some("SeedValue") => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
|
||||
Some("TextArea") => text_area_widget(default_info).into(),
|
||||
|
||||
@@ -323,8 +326,9 @@ pub(crate) fn property_from_type(
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if id_is::<f64>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
|
||||
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),
|
||||
@@ -1124,11 +1128,27 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::I64(x)) => widgets.extend_from_slice(&[
|
||||
Some(&TaggedValue::F32(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::I64(x.value.unwrap().round() as i64)))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F32(x.value.unwrap() as f32)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::U32(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U32((x.value.unwrap()) as u32)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::U64(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U64((x.value.unwrap()) as u64)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
@@ -1699,7 +1719,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
let exposed = input.is_some_and(|input| input.is_exposed());
|
||||
let value = input
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|tagged| if let TaggedValue::F64(value) = tagged { Some(*value) } else { None })
|
||||
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None })
|
||||
.unwrap_or(0.);
|
||||
(exposed, value)
|
||||
})
|
||||
@@ -1822,7 +1842,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: TaggedValue::F64(scale.value(scale_position)).into(),
|
||||
value: TaggedValue::F32(scale.value(scale_position) as f32).into(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -1858,7 +1878,11 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
.value(Some(current))
|
||||
.min_width(60)
|
||||
.max_width(60)
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::F64(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_update(update_value_at_index(
|
||||
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
|
||||
node_id,
|
||||
input_index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
@@ -1882,8 +1906,8 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
Some(TaggedValue::HueSaturationRange(range)) => *range,
|
||||
_ => HueSaturationRange::Master,
|
||||
};
|
||||
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::F64(value)) => *value as f32,
|
||||
let f32_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::F32(value)) => *value,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
@@ -1951,9 +1975,9 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
Gradient::from((0..=stops).map(stop).collect::<Vec<_>>())
|
||||
};
|
||||
let saturation_track = if colorize_value {
|
||||
toward_hue(slider_value(&hue) / 360.)
|
||||
toward_hue(f32_value(&hue) / 360.)
|
||||
} else if let Some([_, range_start, range_end, _]) = &range_values {
|
||||
let (start, end) = (slider_value(range_start), slider_value(range_end));
|
||||
let (start, end) = (f32_value(range_start), f32_value(range_end));
|
||||
let center = start + (end - start).rem_euclid(360.) / 2.;
|
||||
toward_hue(center / 360.)
|
||||
} else {
|
||||
@@ -2098,6 +2122,7 @@ fn slider_row(
|
||||
// An exposed input shows only its label and source
|
||||
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
|
||||
Some(&TaggedValue::F32(value)) => (value as f64, |value| TaggedValue::F32(value as f32)),
|
||||
_ => return widgets,
|
||||
};
|
||||
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
|
||||
@@ -2159,7 +2184,7 @@ fn gradient_slider_row(
|
||||
.ok()
|
||||
.and_then(|document_node| document_node.inputs.get(input_index))
|
||||
.and_then(|input| input.as_non_exposed_value())
|
||||
.and_then(|tagged| if let TaggedValue::F64(value) = tagged { Some(*value) } else { None });
|
||||
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None });
|
||||
|
||||
// Only add the slider and number widgets when the input is not exposed
|
||||
if let Some(current) = current {
|
||||
@@ -2168,7 +2193,7 @@ fn gradient_slider_row(
|
||||
max: value_max,
|
||||
default: Some(default_value),
|
||||
};
|
||||
let value_at = move |position| TaggedValue::F64(slider.value(position));
|
||||
let value_at = move |position| TaggedValue::F32(slider.value(position) as f32);
|
||||
|
||||
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
row.push(
|
||||
@@ -2191,7 +2216,11 @@ fn gradient_slider_row(
|
||||
.min_width(60)
|
||||
.max_width(60)
|
||||
.display_decimal_places(0)
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::F64(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_update(update_value_at_index(
|
||||
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
|
||||
node_id,
|
||||
input_index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
@@ -2613,7 +2642,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
|
||||
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::I64(x)) => x,
|
||||
Some(&TaggedValue::U32(x)) => x,
|
||||
_ => 2,
|
||||
};
|
||||
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
|
||||
@@ -3375,6 +3404,63 @@ pub fn offset_path_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||
}
|
||||
|
||||
pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::math::*;
|
||||
|
||||
let expression = (|| {
|
||||
let mut widgets = start_widgets(&ParameterWidgetsInfo::new(node_id, ExpressionInput, true, context));
|
||||
|
||||
let document_node = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => document_node,
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in offset_path_properties: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
let Some(input) = document_node.input(ExpressionInput) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(x.clone())
|
||||
.centered(true)
|
||||
.on_update(update_value(
|
||||
|x: &TextInput| {
|
||||
TaggedValue::String({
|
||||
let mut expression = x.value.trim().to_string();
|
||||
|
||||
if ["+", "-", "*", "/", "^"].iter().any(|&infix| infix == expression) {
|
||||
expression = format!("A {expression} B");
|
||||
} else if expression == "^" {
|
||||
expression = String::from("A^B");
|
||||
} else if expression == "%" || expression == "mod" {
|
||||
expression = String::from("mod(a, b)");
|
||||
}
|
||||
|
||||
expression
|
||||
})
|
||||
},
|
||||
node_id,
|
||||
ExpressionInput,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
])
|
||||
}
|
||||
widgets
|
||||
})();
|
||||
let operand_b = number_widget(ParameterWidgetsInfo::new(node_id, OperandBInput, true, context), NumberInput::default());
|
||||
let operand_a_hint = vec![TextLabel::new("(Operand A is the primary input)").widget_instance()];
|
||||
|
||||
vec![
|
||||
LayoutGroup::row(expression).with_tooltip_description(r#"A math expression that may incorporate "A" and/or "B", such as "sqrt(A + B) - B^2"."#),
|
||||
LayoutGroup::row(operand_b).with_tooltip_description(r#"The value of "B" when calculating the expression."#),
|
||||
LayoutGroup::row(operand_a_hint).with_tooltip_description(r#""A" is fed by the value from the previous node in the primary data flow, or it is 0 if disconnected."#),
|
||||
]
|
||||
}
|
||||
|
||||
pub struct ParameterWidgetsInfo<'a> {
|
||||
document_id: DocumentId,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
|
||||
@@ -33,7 +33,7 @@ impl FrontendGraphDataType {
|
||||
"Color" => Self::Color,
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
let network = interface.document_network().clone();
|
||||
|
||||
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
|
||||
@@ -137,7 +137,7 @@ fn editor_interface_rebuild_round_trip() {
|
||||
|
||||
let network = original.document_network().clone();
|
||||
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
|
||||
|
||||
@@ -256,7 +256,7 @@ fn rebuilt_interface_keeps_storage_identities() {
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
|
||||
|
||||
@@ -272,7 +272,10 @@ fn rebuilt_interface_keeps_storage_identities() {
|
||||
assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities");
|
||||
}
|
||||
|
||||
/// Migrating an opened document must leave the recorded-delta buffer empty.
|
||||
/// Opening an old document runs its upgrades through the ordinary mutators, so the store records them.
|
||||
/// Those recordings are the document arriving rather than edits to it, so the migration has to leave
|
||||
/// the buffer empty instead of handing the first commit a pile of changes to the document's own
|
||||
/// starting state.
|
||||
#[test]
|
||||
fn migrating_a_document_records_no_changes() {
|
||||
let mut document = load_demo("painted-dreams.graphite");
|
||||
@@ -305,7 +308,7 @@ fn pinned_order_round_trips_through_the_registry() {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.set_storage(reopened, declarations);
|
||||
document.set_storage(Some(reopened));
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
@@ -678,7 +678,7 @@ async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourc
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
editor.active_document_mut().set_storage(gdd, Default::default());
|
||||
editor.active_document_mut().set_storage(Some(gdd));
|
||||
HashMapResourceStorage::new()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
use super::*;
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
// Replay: putting a delta back into the interface, the inverse of the store recording one.
|
||||
//
|
||||
// Mechanism only. A mutator decides policy, validates, and lays nodes out, then records what it
|
||||
// settled on; replaying reproduces that outcome rather than deciding it again. A peer running
|
||||
// different layout rules must still end up with the state the delta describes.
|
||||
impl NodeNetworkInterface {
|
||||
/// Mirrors a delta into the interface without recording it.
|
||||
///
|
||||
@@ -18,7 +23,8 @@ impl NodeNetworkInterface {
|
||||
fn mirror(&mut self, delta: &EditorDelta) {
|
||||
match delta {
|
||||
// The metadata arrives separately, so a node lands with default metadata that the paired
|
||||
// snapshot then fills in
|
||||
// snapshot then fills in. Replacing an entry and adding one are the same write here; they
|
||||
// differ only in what the storage side has to remove first.
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
|
||||
let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default());
|
||||
self.insert_node_entry(NodeLocator::new(*node_id, network_path), template);
|
||||
|
||||
@@ -30,10 +30,11 @@ impl NodeNetworkInterface {
|
||||
self.unload_stack_dependents(network_path);
|
||||
|
||||
let Some(history) = self.selection_history_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in selected_nodes_mut");
|
||||
log::error!("Could not get nested network_metadata in selected_nodes");
|
||||
return None;
|
||||
};
|
||||
|
||||
// Initialize default value if selection_undo_history is empty
|
||||
if history.undo.is_empty() {
|
||||
history.undo.push_back(SelectedNodes::default());
|
||||
}
|
||||
@@ -80,7 +81,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn try_load_stack_dependents(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in try_load_stack_dependents");
|
||||
log::error!("Could not get nested network_metadata in stack_dependents");
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -100,7 +101,7 @@ impl NodeNetworkInterface {
|
||||
return None;
|
||||
};
|
||||
let Some(stack_dependents) = transient.stack_dependents.get_loaded_mut() else {
|
||||
log::error!("Could not load stack dependents in try_get_stack_dependents");
|
||||
log::error!("could not load stack_dependents");
|
||||
return None;
|
||||
};
|
||||
Some(stack_dependents)
|
||||
@@ -147,7 +148,7 @@ impl NodeNetworkInterface {
|
||||
.get(&OutputConnector::primary_output(current_node))
|
||||
.map(|layer_outward_wires| layer_outward_wires.first().copied())
|
||||
}) else {
|
||||
log::error!("Cannot load outward wires in load_stack_dependents_for_nodes");
|
||||
log::error!("Cannot load outward wires in load_stack_dependents");
|
||||
return;
|
||||
};
|
||||
let Some(first_downstream_input) = first_downstream_input else {
|
||||
@@ -187,7 +188,7 @@ impl NodeNetworkInterface {
|
||||
new_owned_nodes.insert(*layer_sole_dependent);
|
||||
}
|
||||
let Some(layer_node) = self.node_metadata(&upstream_layer, network_path) else {
|
||||
log::error!("Could not get layer node in load_stack_dependents_for_nodes");
|
||||
log::error!("Could not get layer node in load_stack_dependents");
|
||||
continue;
|
||||
};
|
||||
layer_node.transient_metadata.owned_nodes.store(new_owned_nodes);
|
||||
@@ -231,7 +232,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get current network in load_stack_dependents_for_nodes");
|
||||
log::error!("Could not get current network in load_stack_dependents");
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -276,11 +277,11 @@ impl NodeNetworkInterface {
|
||||
self.load_import_export_ports(network_path);
|
||||
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_ports");
|
||||
log::error!("Could not get nested network_metadata in export_ports");
|
||||
return None;
|
||||
};
|
||||
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
|
||||
log::error!("Could not load import export ports in import_export_ports");
|
||||
log::error!("could not load import ports");
|
||||
return None;
|
||||
};
|
||||
Some(ports)
|
||||
@@ -296,7 +297,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in load_import_export_ports");
|
||||
log::error!("Could not get nested network_metadata in export_ports");
|
||||
return;
|
||||
};
|
||||
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
|
||||
@@ -304,7 +305,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in unload_import_export_ports");
|
||||
log::error!("Could not get nested network_metadata in unload_export_ports");
|
||||
return;
|
||||
};
|
||||
transient.import_export_ports.unload();
|
||||
@@ -312,13 +313,13 @@ impl NodeNetworkInterface {
|
||||
// Always unload all wires connected to them as well
|
||||
let number_of_imports = self.number_of_imports(network_path);
|
||||
let Some(outward_wires) = self.outward_wires(network_path) else {
|
||||
log::error!("Could not get outward wires in unload_import_export_ports");
|
||||
log::error!("Could not get outward wires in remove_import");
|
||||
return;
|
||||
};
|
||||
let mut input_connectors = Vec::new();
|
||||
for import_index in 0..number_of_imports {
|
||||
let Some(outward_wires_for_import) = outward_wires.get(&OutputConnector::Import(import_index)).cloned() else {
|
||||
log::error!("Could not get outward wires for import in unload_import_export_ports");
|
||||
log::error!("Could not get outward wires for import in remove_import");
|
||||
return;
|
||||
};
|
||||
input_connectors.extend(outward_wires_for_import);
|
||||
@@ -342,7 +343,7 @@ impl NodeNetworkInterface {
|
||||
return None;
|
||||
};
|
||||
let Some(click_targets) = transient.modify_import_export.get_loaded_mut() else {
|
||||
log::error!("Could not load modify import export in modify_import_export");
|
||||
log::error!("could not load modify import export ports");
|
||||
return None;
|
||||
};
|
||||
Some(click_targets)
|
||||
@@ -350,7 +351,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn load_modify_import_export(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in load_modify_import_export");
|
||||
log::error!("Could not get nested network_metadata in modify_import_export");
|
||||
return;
|
||||
};
|
||||
network_metadata
|
||||
@@ -361,7 +362,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) {
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in unload_modify_import_export");
|
||||
log::error!("Could not get nested network_metadata in unload_export_ports");
|
||||
return;
|
||||
};
|
||||
transient.modify_import_export.unload();
|
||||
@@ -387,7 +388,7 @@ impl NodeNetworkInterface {
|
||||
.all_nodes_bounding_box
|
||||
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
|
||||
if bounding_box.is_none() {
|
||||
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
|
||||
log::error!("could not load all nodes bounding box");
|
||||
}
|
||||
bounding_box
|
||||
}
|
||||
@@ -423,7 +424,7 @@ impl NodeNetworkInterface {
|
||||
return None;
|
||||
};
|
||||
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
|
||||
log::error!("Could not load outward wires in outward_wires");
|
||||
log::error!("could not load outward wires");
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -440,7 +441,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
fn load_outward_wires(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in load_outward_wires");
|
||||
log::error!("Could not get nested network_metadata in outward_wires");
|
||||
return;
|
||||
};
|
||||
network_metadata.transient_metadata.outward_wires.ensure_loaded(|| self.compute_outward_wires(network_path));
|
||||
@@ -468,7 +469,7 @@ impl NodeNetworkInterface {
|
||||
// A missing entry means a wire references a node output or import that does not exist, so log it and register the connector anyway rather than crashing
|
||||
let push_outward_wire = |outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, output_connector: OutputConnector, input_connector: InputConnector| {
|
||||
let outward_wires_entry = outward_wires.entry(output_connector).or_insert_with(|| {
|
||||
log::error!("Output connector {output_connector:?} should be initialized in compute_outward_wires");
|
||||
log::error!("Output connector {output_connector:?} should be initialized in load_outward_wires");
|
||||
Vec::new()
|
||||
});
|
||||
outward_wires_entry.push(input_connector);
|
||||
@@ -545,7 +546,7 @@ impl NodeNetworkInterface {
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
||||
}
|
||||
|
||||
/// Unloads layer width if the node is a layer.
|
||||
/// Unloads layer width if the node is a layer
|
||||
pub fn try_unload_layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
let is_layer = self.is_layer(node_id, network_path);
|
||||
|
||||
@@ -553,6 +554,7 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
};
|
||||
|
||||
// If the node is a layer, then the width and click targets need to be recalculated
|
||||
if is_layer {
|
||||
transient.layer_width.unload();
|
||||
}
|
||||
@@ -597,8 +599,14 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
|
||||
// The export keeps its own solid wire while previewing, since previewing does not rewire it
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, false, network_path) else {
|
||||
let dashed = match self.previewing(network_path) {
|
||||
Previewing::Yes { .. } => match input {
|
||||
InputConnector::Node { .. } => false,
|
||||
InputConnector::Export(export_index) => *export_index == 0,
|
||||
},
|
||||
Previewing::No => false,
|
||||
};
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
|
||||
log::error!("Could not load wire path from input");
|
||||
return;
|
||||
};
|
||||
@@ -655,7 +663,7 @@ impl NodeNetworkInterface {
|
||||
fn unload_wires_for_node(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
let number_of_outputs = self.number_of_outputs(node_id, network_path);
|
||||
let Some(outward_wires) = self.outward_wires(network_path) else {
|
||||
log::error!("Could not get outward wires in unload_wires_for_node");
|
||||
log::error!("Could not get outward wires in reorder_export");
|
||||
return;
|
||||
};
|
||||
let mut input_connectors = Vec::new();
|
||||
@@ -682,6 +690,9 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
|
||||
/// is really connected to.
|
||||
///
|
||||
/// Previewing does not rewire the export, so both are shown: the solid wire says what the document
|
||||
/// renders, and this one says what this peer is looking at instead.
|
||||
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
let input = InputConnector::Export(0);
|
||||
|
||||
@@ -715,7 +726,7 @@ impl NodeNetworkInterface {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed: true,
|
||||
dashed: false,
|
||||
is_list,
|
||||
center_path_string,
|
||||
});
|
||||
@@ -738,7 +749,7 @@ impl NodeNetworkInterface {
|
||||
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:?}");
|
||||
log::error!("Could not get output port for wire start: {:?}", upstream_output);
|
||||
return None;
|
||||
};
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
@@ -775,7 +786,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
let transient = self.node_transient_mut(node_id, network_path)?;
|
||||
let Some(click_targets) = transient.click_targets.get_loaded_mut() else {
|
||||
log::error!("Could not load click targets in node_click_targets");
|
||||
log::error!("Could not load node type metadata when getting click targets");
|
||||
return None;
|
||||
};
|
||||
Some(click_targets)
|
||||
@@ -783,7 +794,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||
log::error!("Could not get nested node_metadata in load_node_click_targets");
|
||||
log::error!("Could not get nested node_metadata in node_click_targets");
|
||||
return;
|
||||
};
|
||||
node_metadata.transient_metadata.click_targets.ensure_loaded(|| self.compute_node_click_targets(node_id, network_path));
|
||||
@@ -810,18 +821,16 @@ impl NodeNetworkInterface {
|
||||
let node_metadata = self.node_metadata(node_id, network_path)?;
|
||||
let result = node_metadata.transient_metadata.click_targets.with_loaded(read);
|
||||
if result.is_none() {
|
||||
log::error!("Could not load click targets in with_node_click_targets_if_loaded");
|
||||
log::error!("Could not load node type metadata when getting click targets");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||
.flatten()
|
||||
self.load_node_click_targets(node_id, network_path);
|
||||
self.try_get_node_bounding_box(node_id, network_path)
|
||||
}
|
||||
|
||||
/// The bounding box only if the click targets are already loaded, for a caller that is walking many
|
||||
/// nodes and cannot afford to load each one it looks at.
|
||||
pub fn try_get_node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_node_click_targets_if_loaded(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||
.flatten()
|
||||
@@ -839,7 +848,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
let Some(transient) = self.node_transient_mut(node_id, network_path) else {
|
||||
log::error!("Could not get nested node_metadata in unload_node_click_targets");
|
||||
log::error!("Could not get nested node_metadata in unload_node_click_target");
|
||||
return;
|
||||
};
|
||||
transient.click_targets.unload();
|
||||
|
||||
+6
-4
@@ -127,7 +127,7 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
|
||||
}
|
||||
|
||||
/// The check answers for the network with the proposed input substituted, so it has to see a loop that
|
||||
/// closes through intermediate nodes rather than only one that connects two neighbors.
|
||||
/// closes through intermediate nodes rather than only one that connects two neighbours.
|
||||
#[tokio::test]
|
||||
async fn a_cycle_closing_through_a_chain_is_rejected() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -451,8 +451,9 @@ async fn the_evaluated_network_renders_the_previewed_node() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The previewed node is marked for the frontend so it can be highlighted. The mark comes from the
|
||||
/// preview state itself, not from the export.
|
||||
/// The previewed node is marked for the frontend so it can be highlighted. Derived from the preview
|
||||
/// itself: it used to be inferred from the export, which previewing no longer rewires, so inferring it
|
||||
/// would silently mark nothing.
|
||||
#[tokio::test]
|
||||
async fn the_previewed_node_is_flagged_for_the_frontend() {
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
|
||||
@@ -486,7 +487,8 @@ async fn the_previewed_node_is_flagged_for_the_frontend() {
|
||||
}
|
||||
|
||||
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
|
||||
/// node on its own, with a stack as the case that matters.
|
||||
/// node on its own. A stack is the case that matters: every layer walks through the ones below it, so
|
||||
/// a shared memo is what keeps the batch from being quadratic.
|
||||
#[tokio::test]
|
||||
async fn batched_positions_agree_with_resolving_each_node() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
+58
-76
@@ -82,15 +82,7 @@ pub enum NetworkMetadataChange {
|
||||
|
||||
pub struct ConstructedOps {
|
||||
pub ops: Vec<RegistryDelta>,
|
||||
pub declarations: BatchDeclarations,
|
||||
}
|
||||
|
||||
/// The proto-node declarations a batch extracted: the bytes for the caller's byte store, and the same
|
||||
/// declarations decoded for its declaration cache, which a cursor rebuild reads instead of the bytes.
|
||||
#[derive(Default)]
|
||||
pub struct BatchDeclarations {
|
||||
pub bytes: DeclarationBytes,
|
||||
pub decoded: document_graph_storage::Declarations,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
}
|
||||
|
||||
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
|
||||
@@ -108,62 +100,54 @@ pub fn construct_batch(
|
||||
peer: document_graph_storage::PeerId,
|
||||
) -> Result<ConstructedOps, ConversionError> {
|
||||
let identities = IdentitiesOnly(metadata);
|
||||
let context = ConversionContext {
|
||||
resources,
|
||||
identities: &identities,
|
||||
resolver: PathResolver::new(Some(&identities), peer),
|
||||
peer,
|
||||
};
|
||||
let resolver = PathResolver::new(Some(&identities), peer);
|
||||
let mut batch = BatchRegistry::new(working);
|
||||
let mut ops = Vec::new();
|
||||
let mut declarations = BatchDeclarations::default();
|
||||
let mut declaration_bytes = DeclarationBytes::new();
|
||||
let mut batch_removed_nodes = Vec::new();
|
||||
|
||||
// In delta order, so each delta reads what the ones before it did
|
||||
// In delta order, so each delta reads what the ones before it did. Removals accumulate as they are
|
||||
// met rather than being gathered up front, since a removal can name a node an earlier delta added.
|
||||
for delta in deltas {
|
||||
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
|
||||
delta.construct(resources, peer, &identities, &resolver, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declaration_bytes)?;
|
||||
}
|
||||
|
||||
batch_removed_nodes.sort();
|
||||
batch_removed_nodes.dedup();
|
||||
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
|
||||
Ok(ConstructedOps { ops, declarations })
|
||||
}
|
||||
|
||||
/// What every delta in a batch converts against, fixed for the whole batch.
|
||||
struct ConversionContext<'a> {
|
||||
resources: &'a ResourceRegistry,
|
||||
identities: &'a dyn NodeMetadataSource,
|
||||
resolver: PathResolver<'a>,
|
||||
peer: document_graph_storage::PeerId,
|
||||
Ok(ConstructedOps { ops, declaration_bytes })
|
||||
}
|
||||
|
||||
impl EditorDelta {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn construct(
|
||||
&self,
|
||||
context: &ConversionContext,
|
||||
resources: &ResourceRegistry,
|
||||
peer: document_graph_storage::PeerId,
|
||||
identities: &dyn NodeMetadataSource,
|
||||
resolver: &PathResolver,
|
||||
batch: &mut BatchRegistry,
|
||||
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
declarations: &mut BatchDeclarations,
|
||||
declaration_bytes: &mut DeclarationBytes,
|
||||
) -> Result<(), ConversionError> {
|
||||
match self {
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
|
||||
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
|
||||
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
|
||||
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
|
||||
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
|
||||
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
|
||||
ops.push(RegistryDelta::ChangeNodeAttribute {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
id: resolver.node_id(network_path, *node_id),
|
||||
delta: AttributeDelta {
|
||||
key: node_attr::VISIBLE.to_string(),
|
||||
value: (!visible).then_some(serde_json::Value::Bool(false)),
|
||||
@@ -178,23 +162,23 @@ impl EditorDelta {
|
||||
input,
|
||||
}) => {
|
||||
ops.push(RegistryDelta::ChangeNodeInput {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
id: resolver.node_id(network_path, *node_id),
|
||||
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
|
||||
new_input: context.resolver.convert_input_at(input, network_path)?,
|
||||
new_input: resolver.convert_input_at(input, network_path)?,
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
|
||||
ops.push(RegistryDelta::SetNetworkExport {
|
||||
id: context.resolver.network_id(network_path),
|
||||
id: resolver.network_id(network_path),
|
||||
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
|
||||
export: input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?,
|
||||
export: input.as_ref().map(|input| resolver.convert_input_at(input, network_path)).transpose()?,
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
|
||||
ops.push(RegistryDelta::ChangeNodeAttribute {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
id: resolver.node_id(network_path, *node_id),
|
||||
delta: document_graph_storage::from_runtime::encode_call_argument(call_argument)?,
|
||||
});
|
||||
}
|
||||
@@ -205,22 +189,24 @@ impl EditorDelta {
|
||||
context_features,
|
||||
}) => {
|
||||
ops.push(RegistryDelta::ChangeNodeAttribute {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
id: resolver.node_id(network_path, *node_id),
|
||||
delta: document_graph_storage::from_runtime::encode_context_features(context_features)?,
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
|
||||
construct_metadata_snapshot(network_path, *node_id, metadata, batch, &context.resolver, ops)?;
|
||||
construct_metadata_snapshot(network_path, *node_id, metadata, batch, resolver, ops)?;
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
|
||||
// The slots' `ui::*` attributes arrive with the paired input metadata delta
|
||||
// Only the slots are written, so the node's attributes and everything nested under it are
|
||||
// left as they are: an edit made earlier in this batch is not reverted by the rebuild.
|
||||
// The slots' `ui::*` attributes arrive with the paired input metadata delta.
|
||||
let inputs = inputs
|
||||
.iter()
|
||||
.map(|input| {
|
||||
Ok(document_graph_storage::InputSlot {
|
||||
input: context.resolver.convert_input_at(input, network_path)?,
|
||||
input: resolver.convert_input_at(input, network_path)?,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: convert_input_attributes(input)?,
|
||||
})
|
||||
@@ -228,13 +214,13 @@ impl EditorDelta {
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
ops.push(RegistryDelta::SetNodeInputs {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
id: resolver.node_id(network_path, *node_id),
|
||||
inputs,
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadata { network_path, node_id, change } => {
|
||||
ops.extend(node_metadata_ops(context.resolver.node_id(network_path, *node_id), change)?);
|
||||
ops.extend(node_metadata_ops(resolver.node_id(network_path, *node_id), change)?);
|
||||
}
|
||||
|
||||
EditorDelta::NodeInputMetadata {
|
||||
@@ -242,10 +228,12 @@ impl EditorDelta {
|
||||
node_id,
|
||||
input_metadata,
|
||||
} => {
|
||||
let global_id = context.resolver.node_id(network_path, *node_id);
|
||||
let global_id = resolver.node_id(network_path, *node_id);
|
||||
let source = InputMetadataSource(input_metadata);
|
||||
let working_node = batch.node(global_id);
|
||||
|
||||
// An insert shifts every later slot, so the array is asserted whole: a `ui::` key the slot
|
||||
// no longer carries is cleared rather than left behind at its old index.
|
||||
for input_index in 0..input_metadata.len() {
|
||||
let mut encoded = Attributes::new();
|
||||
encode_input_ui_attributes(&mut encoded, &source, network_path, *node_id, input_index, TimeStamp::ORIGIN)?;
|
||||
@@ -268,7 +256,7 @@ impl EditorDelta {
|
||||
value: reference.clone().map(serde_json::Value::String),
|
||||
},
|
||||
NetworkMetadataChange::PinnedOrder(order) => {
|
||||
let stored: Vec<_> = order.iter().map(|node_id| context.resolver.node_id(network_path, *node_id)).collect();
|
||||
let stored: Vec<_> = order.iter().map(|node_id| resolver.node_id(network_path, *node_id)).collect();
|
||||
AttributeDelta {
|
||||
key: network_attr::PINNED_ORDER.to_string(),
|
||||
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
|
||||
@@ -277,7 +265,7 @@ impl EditorDelta {
|
||||
};
|
||||
|
||||
ops.push(RegistryDelta::ChangeNetworkAttribute {
|
||||
id: context.resolver.network_id(network_path),
|
||||
id: resolver.network_id(network_path),
|
||||
delta,
|
||||
});
|
||||
}
|
||||
@@ -308,7 +296,8 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
||||
})
|
||||
};
|
||||
|
||||
// The empty string is the runtime's own sentinel for an unset name
|
||||
// Absence is how the encoder spells an unset flag, and the empty string is the runtime's own
|
||||
// sentinel for an unset name.
|
||||
let flag = |value: bool| value.then_some(serde_json::Value::Bool(true));
|
||||
let non_empty = |value: &str| (!value.is_empty()).then(|| serde_json::Value::String(value.to_string()));
|
||||
Ok(match change {
|
||||
@@ -336,30 +325,31 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
||||
|
||||
/// Converts through the same encoders as a whole-document conversion, with identities only as the
|
||||
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn construct_structural_additions(
|
||||
network_path: &[NodeId],
|
||||
node_id: NodeId,
|
||||
node: &graph_craft::document::DocumentNode,
|
||||
batch: &mut BatchRegistry,
|
||||
context: &ConversionContext,
|
||||
resources: &ResourceRegistry,
|
||||
identities: &dyn NodeMetadataSource,
|
||||
peer: document_graph_storage::PeerId,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
declarations: &mut BatchDeclarations,
|
||||
declaration_bytes: &mut DeclarationBytes,
|
||||
) -> Result<(), ConversionError> {
|
||||
let mut scoped = ScopedConversion::new(context.identities, context.peer);
|
||||
let mut scoped = ScopedConversion::new(identities, peer);
|
||||
let mut scratch = Registry::default();
|
||||
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
|
||||
let (bytes, decoded) = scoped.finish();
|
||||
declarations.bytes.extend(bytes);
|
||||
declarations.decoded.extend(decoded);
|
||||
declaration_bytes.extend(scoped.finish());
|
||||
|
||||
let mut networks: Vec<_> = scratch.networks.iter().map(|(id, network)| (*id, network.clone())).collect();
|
||||
networks.sort_by_key(|(id, _)| *id);
|
||||
let mut networks: Vec<_> = scratch.networks.iter().collect();
|
||||
networks.sort_by_key(|(id, _)| **id);
|
||||
for (id, network) in networks {
|
||||
ops.push(RegistryDelta::AddNetwork { id, network: network.clone() });
|
||||
batch.record_network(id, network);
|
||||
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
|
||||
}
|
||||
|
||||
// Recorded as well as emitted, so a later delta in this batch can read these nodes back
|
||||
// Recorded as well as emitted, so a later delta in this batch that reads one of these nodes back
|
||||
// finds it rather than looking only at the registry the batch started from.
|
||||
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
|
||||
nodes.sort_by_key(|(id, _)| **id);
|
||||
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
|
||||
@@ -386,7 +376,7 @@ fn construct_structural_additions(
|
||||
for id in tagged {
|
||||
if batch.resource(id).is_none()
|
||||
&& !scratch.resources.contains_key(&id)
|
||||
&& let Some(entry) = convert_resource_entry(context.resources, id, context.peer)?
|
||||
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
|
||||
{
|
||||
batch.record_resource(id, entry.clone());
|
||||
ops.push(RegistryDelta::AddResource { id, entry });
|
||||
@@ -506,7 +496,7 @@ fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegi
|
||||
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
|
||||
}
|
||||
for id in &removed_networks {
|
||||
let Some(snapshot) = batch.network(*id) else { continue };
|
||||
let Some(snapshot) = batch.working.networks.get(id) else { continue };
|
||||
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
|
||||
}
|
||||
|
||||
@@ -562,15 +552,18 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
|
||||
}
|
||||
|
||||
/// The registry a delta is constructed against: what the batch started from, plus the nodes deltas
|
||||
/// earlier in the same batch have added, since a delta can read back or remove a node an earlier one
|
||||
/// added.
|
||||
/// earlier in the same batch have added.
|
||||
///
|
||||
/// A delta that reads a node back cannot read only the starting registry. A node added and removed
|
||||
/// within one batch is not in it, and a later delta that rebuilds a node would rebuild the version
|
||||
/// that predates the batch. Additions are tracked rather than the whole registry copied, so the cost
|
||||
/// is the size of the batch rather than of the document.
|
||||
///
|
||||
/// Nodes are also indexed by network, so a removal closure walks only the subtree it removes instead
|
||||
/// of rescanning every node for each nested network it meets.
|
||||
struct BatchRegistry<'a> {
|
||||
working: &'a Registry,
|
||||
added: HashMap<document_graph_storage::NodeId, document_graph_storage::Node>,
|
||||
added_networks: HashMap<document_graph_storage::NetworkId, document_graph_storage::Network>,
|
||||
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
|
||||
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
|
||||
}
|
||||
@@ -584,7 +577,6 @@ impl<'a> BatchRegistry<'a> {
|
||||
Self {
|
||||
working,
|
||||
added: HashMap::new(),
|
||||
added_networks: HashMap::new(),
|
||||
added_resources: HashMap::new(),
|
||||
by_network,
|
||||
}
|
||||
@@ -596,12 +588,6 @@ impl<'a> BatchRegistry<'a> {
|
||||
self.added.insert(id, node);
|
||||
}
|
||||
|
||||
/// Records a network an earlier delta in this batch added, so removing the node that owns it finds
|
||||
/// the network to remove alongside it.
|
||||
fn record_network(&mut self, id: document_graph_storage::NetworkId, network: document_graph_storage::Network) {
|
||||
self.added_networks.insert(id, network);
|
||||
}
|
||||
|
||||
/// Records a resource this batch added. Returns whether it is new to the batch, so the caller emits
|
||||
/// one addition for a resource several nodes reference.
|
||||
fn record_resource(&mut self, id: ResourceId, entry: document_graph_storage::ResourceEntry) -> bool {
|
||||
@@ -612,10 +598,6 @@ impl<'a> BatchRegistry<'a> {
|
||||
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
|
||||
}
|
||||
|
||||
fn network(&self, id: document_graph_storage::NetworkId) -> Option<&document_graph_storage::Network> {
|
||||
self.added_networks.get(&id).or_else(|| self.working.networks.get(&id))
|
||||
}
|
||||
|
||||
fn resource(&self, id: ResourceId) -> Option<&document_graph_storage::ResourceEntry> {
|
||||
self.added_resources.get(&id).or_else(|| self.working.resources.get(&id))
|
||||
}
|
||||
|
||||
+10
-34
@@ -195,8 +195,9 @@ async fn per_field_metadata_edits_match_the_diff() {
|
||||
assert_same_stored_effect(&working, constructed, diffed, "per-field metadata edits");
|
||||
}
|
||||
|
||||
/// The encoding spells "unset" as an absent attribute, so a per-field delta that sets a field back to
|
||||
/// its unset value must clear the key rather than write a sentinel.
|
||||
/// The encoding spells "unset" as an absent attribute, so a field set back to its unset value has to
|
||||
/// clear the key rather than write a sentinel. The wholesale copy got this by omitting the key; a
|
||||
/// per-field delta has to say it, and saying it wrong leaves the old value stored.
|
||||
#[tokio::test]
|
||||
async fn clearing_a_metadata_field_removes_the_attribute() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -226,9 +227,9 @@ async fn clearing_a_metadata_field_removes_the_attribute() {
|
||||
assert_same_stored_effect(&working, constructed, diffed, "cleared metadata fields");
|
||||
}
|
||||
|
||||
/// The deltas the interface emits for a real edit must store what a whole-document conversion of the
|
||||
/// result would. Taking them from the interface rather than writing them by hand is what catches a
|
||||
/// setter that forgets to emit, or emits the wrong field.
|
||||
/// The gate emission exists for: what the store says it wrote has to be what a whole-document
|
||||
/// conversion of the result would show. Hand-written deltas cannot catch a setter that forgets to
|
||||
/// emit, or emits the wrong field; taking them from the interface after a real edit can.
|
||||
#[tokio::test]
|
||||
async fn emitted_deltas_reproduce_the_diff() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -386,9 +387,10 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
|
||||
assert_same_stored_effect(&working, constructed, diffed, "rename then arity change");
|
||||
}
|
||||
|
||||
/// What an edit records must be enough to reproduce it: applying the recorded deltas to a clone of the
|
||||
/// interface taken before the edit must yield the edited interface. A write recorded wrongly or not at
|
||||
/// all surfaces here rather than as drift on another peer.
|
||||
/// The gate replay exists for: what the store recorded has to be enough to reproduce the write that
|
||||
/// produced it. Clone the interface before an edit, apply what the edit recorded onto the clone, and
|
||||
/// the two should agree. Something the store failed to record, or recorded wrongly, surfaces here
|
||||
/// rather than as drift on another peer.
|
||||
async fn assert_replay_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
@@ -550,29 +552,3 @@ async fn removing_a_nested_network_node_matches_the_diff() {
|
||||
let diffed = compute_deltas(&working, &convert(&editor));
|
||||
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
|
||||
}
|
||||
|
||||
/// A group carries a nested network, so adding and removing one inside a batch has to cancel out the
|
||||
/// network as well as the nodes. The proto-node case above does not reach this, since a proto node has
|
||||
/// no network of its own.
|
||||
#[tokio::test]
|
||||
async fn a_group_added_and_removed_in_one_batch_leaves_nothing_behind() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
let group = only_group(&editor);
|
||||
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
|
||||
|
||||
let emitted = editor.active_document_mut().network_interface.take_deltas();
|
||||
let constructed = construct(&editor, &emitted, &working);
|
||||
let diffed = compute_deltas(&working, &convert(&editor));
|
||||
assert_same_stored_effect(&working, constructed, diffed, "group added then removed in one batch");
|
||||
}
|
||||
+14
-10
@@ -21,6 +21,7 @@ impl NodeNetworkInterface {
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
let mut port_click_targets = Ports::new();
|
||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||
// Create input/output click targets
|
||||
let mut input_row_count = 0;
|
||||
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
||||
if input.is_exposed() {
|
||||
@@ -58,6 +59,7 @@ impl NodeNetworkInterface {
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
}
|
||||
} else {
|
||||
// Layer inputs
|
||||
port_click_targets.insert_layer_input(0, node_top_left);
|
||||
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
|
||||
port_click_targets.insert_layer_input(1, node_top_left);
|
||||
@@ -65,7 +67,7 @@ impl NodeNetworkInterface {
|
||||
port_click_targets.insert_layer_output(node_top_left);
|
||||
|
||||
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
|
||||
log::error!("Could not get layer width in compute_node_click_targets");
|
||||
log::error!("Could not get layer width in load_node_click_targets");
|
||||
0
|
||||
});
|
||||
let width = layer_width_cells * GRID_SIZE;
|
||||
@@ -77,6 +79,7 @@ impl NodeNetworkInterface {
|
||||
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
||||
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
||||
|
||||
// Update visibility button click target
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||
@@ -98,7 +101,8 @@ impl NodeNetworkInterface {
|
||||
None
|
||||
};
|
||||
|
||||
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
|
||||
// Update grip button click target, which is positioned to the left of the leftmost icon.
|
||||
// The grip is 8px wide but spans the full layer-vertical-center band.
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||
@@ -109,8 +113,8 @@ impl NodeNetworkInterface {
|
||||
);
|
||||
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
|
||||
// so the rest of the layer still drills into the subgraph on double-click
|
||||
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
|
||||
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
|
||||
|
||||
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
||||
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
||||
@@ -143,7 +147,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
};
|
||||
|
||||
// The layer click target spans the layer and its chain background
|
||||
// Create layer click target, which is contains the layer and the chain background
|
||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||
|
||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||
@@ -176,7 +180,7 @@ impl NodeNetworkInterface {
|
||||
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
|
||||
for (import_index, import_click_target) in import_exports.output_ports() {
|
||||
let Some(import_bounding_box) = import_click_target.bounding_box() else {
|
||||
log::error!("Could not get export bounding box in compute_modify_import_export");
|
||||
log::error!("Could not get export bounding box in load_modify_import_export");
|
||||
continue;
|
||||
};
|
||||
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
|
||||
@@ -196,7 +200,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
for (export_index, export_click_target) in import_exports.input_ports() {
|
||||
let Some(export_bounding_box) = export_click_target.bounding_box() else {
|
||||
log::error!("Could not get export bounding box in compute_modify_import_export");
|
||||
log::error!("Could not get export bounding box in load_modify_import_export");
|
||||
continue;
|
||||
};
|
||||
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
|
||||
@@ -271,16 +275,16 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
||||
log::error!("Could not get all nodes bounding box in import_export_position");
|
||||
log::error!("Could not get all nodes bounding box in load_export_ports");
|
||||
return None;
|
||||
};
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
log::error!("Could not get current network in import_export_position");
|
||||
log::error!("Could not get current network in load_export_ports");
|
||||
return None;
|
||||
};
|
||||
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_position");
|
||||
log::error!("Could not get nested network_metadata in load_export_ports");
|
||||
return None;
|
||||
};
|
||||
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
|
||||
+10
-5
@@ -9,14 +9,19 @@ impl NodeNetworkInterface {
|
||||
/// Unloads everything a node's position feeds: its own geometry, the geometry of every node placed
|
||||
/// relative to it, and the network bounds. A chain node also sets the width of the layer encapsulating
|
||||
/// its chain, so that layer reloads too.
|
||||
pub(crate) fn invalidate_position(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
if self.is_chain(node_id, network_path)
|
||||
&& let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path)
|
||||
{
|
||||
///
|
||||
/// Takes the changed nodes as a batch, so a run of moves walks the upstream cone once.
|
||||
pub(crate) fn invalidate_positions(&mut self, node_ids: Vec<NodeId>, network_path: &[NodeId]) {
|
||||
let encapsulating_layers = node_ids
|
||||
.iter()
|
||||
.filter(|node_id| self.is_chain(node_id, network_path))
|
||||
.filter_map(|node_id| self.downstream_layer_for_chain_node(node_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
for downstream_layer in encapsulating_layers {
|
||||
self.unload_node_click_targets(&downstream_layer, network_path);
|
||||
}
|
||||
|
||||
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
|
||||
self.unload_upstream_node_click_targets(node_ids, network_path);
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,18 +9,18 @@ impl NodeNetworkInterface {
|
||||
self.position_from_downstream(node_id, network_path, &mut HashSet::new(), &mut HashMap::new())
|
||||
}
|
||||
|
||||
/// The positions of many nodes at once, sharing one memo so a stack is walked once rather than once per node.
|
||||
/// The positions of many nodes at once, resolving each one only once.
|
||||
///
|
||||
/// The memo is deliberately not kept between calls, since layout reads positions between a write and its invalidation.
|
||||
/// Asking node by node re-walks the same downstream chain for every node on it, which is quadratic
|
||||
/// down a tall stack. Sharing one memo across the batch keeps a node reached on someone else.s walk,
|
||||
/// so the whole set costs one pass. Not cached between calls: a position read between a write and its
|
||||
/// invalidation would be stale, and the layout code does exactly that.
|
||||
pub(crate) fn positions(&self, node_ids: impl IntoIterator<Item = NodeId>, network_path: &[NodeId]) -> Vec<(NodeId, IVec2)> {
|
||||
let mut resolved = HashMap::new();
|
||||
node_ids
|
||||
.into_iter()
|
||||
.filter_map(|node_id| {
|
||||
let Some(position) = self.position_from_downstream(&node_id, network_path, &mut HashSet::new(), &mut resolved) else {
|
||||
log::error!("Could not get position for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let position = self.position_from_downstream(&node_id, network_path, &mut HashSet::new(), &mut resolved)?;
|
||||
Some((node_id, position))
|
||||
})
|
||||
.collect()
|
||||
@@ -54,10 +54,10 @@ impl NodeNetworkInterface {
|
||||
position
|
||||
}
|
||||
|
||||
/// Reads a node's stored position, resolving a stack or chain position against the node it is placed relative to.
|
||||
/// The position itself, once the memo has been missed and the cycle guard passed.
|
||||
fn resolve_position(&self, node_id: &NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
|
||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||
log::error!("Could not get nested node_metadata in resolve_position");
|
||||
log::error!("Could not get nested node_metadata in position_from_downstream");
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -140,7 +140,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_position(node_id, network_path);
|
||||
self.invalidate_positions(vec![*node_id], network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a layer to a stack position
|
||||
@@ -155,7 +155,7 @@ impl NodeNetworkInterface {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
self.invalidate_position(node_id, network_path);
|
||||
self.invalidate_positions(vec![*node_id], network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a node to a stack position without changing its y offset
|
||||
@@ -184,7 +184,7 @@ impl NodeNetworkInterface {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
self.invalidate_position(node_id, network_path);
|
||||
self.invalidate_positions(vec![*node_id], network_path);
|
||||
}
|
||||
|
||||
pub(crate) fn valid_upstream_chain_nodes(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
@@ -240,6 +240,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Input connector is the input to the layer
|
||||
pub fn try_set_upstream_to_chain(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) {
|
||||
// If the new input is to a non layer node on the same y position as the input connector, or the input connector is the side input of a layer, then set it to chain position
|
||||
let valid_upstream_chain_nodes = self.valid_upstream_chain_nodes(input_connector, network_path);
|
||||
|
||||
for node_id in &valid_upstream_chain_nodes {
|
||||
@@ -306,6 +307,7 @@ impl NodeNetworkInterface {
|
||||
log::error!("Could not get position in set_upstream_chain_to_absolute");
|
||||
return;
|
||||
};
|
||||
// Set any chain nodes to absolute positioning
|
||||
if self.is_chain(upstream_id, network_path) {
|
||||
self.set_absolute_position(upstream_id, previous_position, network_path);
|
||||
// Reload click target of the layer which used to encapsulate the chain
|
||||
@@ -378,6 +380,7 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
if is_layer && outward_wires.len() == 1 && outward_wires[0].input_index() == 0 {
|
||||
// A layer left feeding the bottom of a node keeps the position it already resolved to
|
||||
if let Some(downstream_node_id) = outward_wires[0].node_id()
|
||||
&& self.is_layer(&downstream_node_id, network_path)
|
||||
{
|
||||
@@ -394,6 +397,8 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn nodes_sorted_top_to_bottom<'a>(&mut self, node_ids: impl Iterator<Item = &'a NodeId>, network_path: &[NodeId]) -> Option<Vec<NodeId>> {
|
||||
// Resolved as one batch: every node here is likely on the same stack, so walking each one
|
||||
// separately would re-walk that stack per node.
|
||||
let mut node_ids_with_position = self.positions(node_ids.copied(), network_path);
|
||||
|
||||
node_ids_with_position.sort_unstable_by_key(|(_, position)| position.y);
|
||||
@@ -421,7 +426,7 @@ impl NodeNetworkInterface {
|
||||
if shifted_any {
|
||||
self.transaction_modified();
|
||||
}
|
||||
self.invalidate_position(layer, network_path);
|
||||
self.invalidate_positions(vec![*layer], network_path);
|
||||
}
|
||||
|
||||
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
|
||||
@@ -620,7 +625,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves every node the shift pushed out of place back to where it started, as far as nothing has since
|
||||
/// Returns every node the shift pushed out of place to where it started, as far as nothing has since
|
||||
/// moved into its way. `seed_nodes` are the nodes the caller asked to move, which keep their new place.
|
||||
fn settle_drag_offsets(&mut self, seed_nodes: &HashSet<NodeId>, network_path: &[NodeId]) {
|
||||
let Some(stack_dependents) = self
|
||||
@@ -680,6 +685,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
fn vertical_shift_with_push(&mut self, node_id: &NodeId, shift_sign: i32, shifted_nodes: &mut HashSet<NodeId>, network_path: &[NodeId]) {
|
||||
// Do not shift a node more than once
|
||||
if shifted_nodes.contains(node_id) {
|
||||
return;
|
||||
}
|
||||
@@ -712,6 +718,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
// Shift the nodes that are owned by the layer (if any)
|
||||
if let Some(owned_nodes) = self.with_owned_nodes_if_loaded(node_id, network_path, |owned_nodes| owned_nodes.clone()) {
|
||||
for owned_node in owned_nodes {
|
||||
if self.is_absolute(&owned_node, network_path) {
|
||||
@@ -725,8 +732,9 @@ impl NodeNetworkInterface {
|
||||
self.load_all_node_click_targets(network_path);
|
||||
self.try_load_stack_dependents(network_path);
|
||||
|
||||
// Check collisions and for all owned nodes and recursively shift them
|
||||
let nodes_to_shift = self.with_stack_dependents_if_loaded(network_path, |stack_dependents| {
|
||||
// Borrow the owned nodes for the sweep rather than cloning them per call
|
||||
// Hot path during drags: borrow the owned nodes for the sweep rather than cloning them per call
|
||||
let collect_collisions = |owned_nodes: &HashSet<NodeId>| {
|
||||
let mut nodes_to_shift = Vec::new();
|
||||
|
||||
@@ -850,7 +858,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
self.invalidate_position(node_id, network_path);
|
||||
self.invalidate_positions(vec![*node_id], network_path);
|
||||
}
|
||||
|
||||
/// The grid rows a node occupies when stacked, as absolute `(top, bottom)` rows. A layer's box starts
|
||||
@@ -901,8 +909,10 @@ impl NodeNetworkInterface {
|
||||
self.set_input_for_import(&post_node, layer_output, network_path);
|
||||
}
|
||||
NodeInput::Node { .. } => {
|
||||
// Subsequent child: the layer takes over the post node's input, and the old upstream moves onto the layer's stack input
|
||||
// Subsequent child: insert layer between post_node and its current upstream...
|
||||
// 1. Disconnect old upstream from post_node, wire layer output to post_node
|
||||
self.set_input_for_import(&post_node, layer_output, network_path);
|
||||
// 2. Wire old upstream into layer's primary (stack) input
|
||||
self.set_input_for_import(&InputConnector::primary_input(layer.to_node()), post_node_input, network_path);
|
||||
}
|
||||
NodeInput::Import { .. } => {
|
||||
@@ -942,11 +952,12 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
};
|
||||
|
||||
// A layer already under this parent vacates its own slot when it disconnects, shifting the target down one
|
||||
if let Some(moved_layer_previous_index) = parent.children(&self.document_metadata).position(|child| child == layer)
|
||||
&& moved_layer_previous_index < insert_index
|
||||
{
|
||||
insert_index -= 1;
|
||||
// If the moved layer is a child of the new parent, then get its index after the disconnect
|
||||
if let Some(moved_layer_previous_index) = parent.children(&self.document_metadata).position(|child| child == layer) {
|
||||
// Adjust the insert index if the layer's previous index is less than the insert index
|
||||
if moved_layer_previous_index < insert_index {
|
||||
insert_index -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect layer to move
|
||||
@@ -1032,7 +1043,7 @@ impl NodeNetworkInterface {
|
||||
let shift = final_layer_position - previous_layer_position;
|
||||
self.shift_absolute_node_position(&layer.to_node(), shift, network_path);
|
||||
}
|
||||
// Move to the top of a stack
|
||||
// Move to the top of a stack.
|
||||
NodeInput::Node { node_id, .. } => {
|
||||
let Some(stack_top_position) = self.position(&node_id, network_path) else {
|
||||
log::error!("Could not get stack x position in move_layer_to_stack");
|
||||
@@ -1169,12 +1180,12 @@ impl NodeNetworkInterface {
|
||||
self.set_input(&InputConnector::primary_input(*node_id), current_input, network_path);
|
||||
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
|
||||
|
||||
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do
|
||||
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do.
|
||||
if !self.is_absolute(node_id, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room
|
||||
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room.
|
||||
let Some(feeder) = feeder else { return };
|
||||
let Some(node_position) = self.position(node_id, network_path) else { return };
|
||||
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
|
||||
@@ -1187,7 +1198,7 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
}
|
||||
|
||||
// Deduplicate, since `UpstreamFlow` can yield a shared node more than once and each node must shift only once
|
||||
// Deduplicate, since `UpstreamFlow` can yield a shared node more than once and we must shift each node only once.
|
||||
let upstream_nodes: HashSet<NodeId> = self.upstream_flow_back_from_nodes(vec![feeder], network_path, FlowType::UpstreamFlow).collect();
|
||||
for upstream_node in &upstream_nodes {
|
||||
self.shift_node(upstream_node, IVec2::new(-NODE_CHAIN_WIDTH, 0), network_path);
|
||||
@@ -1225,6 +1236,7 @@ impl NodeNetworkInterface {
|
||||
self.create_wire(&OutputConnector::primary_output(*node_id), &parent_input, network_path);
|
||||
}
|
||||
|
||||
// Mark this lone node as chain-positioned
|
||||
self.set_chain_position(node_id, network_path);
|
||||
}
|
||||
// Chain already has nodes: splice this node between the parent and the chain's existing final downstream node
|
||||
|
||||
+58
-23
@@ -2,33 +2,62 @@ use super::*;
|
||||
|
||||
// Public mutable methods
|
||||
impl NodeNetworkInterface {
|
||||
/// Walk every network at every nesting level, invoking `visit` with each network's path and a mutable
|
||||
/// reference to its metadata. Only nodes that contain a nested network are recursed into.
|
||||
fn for_each_network_metadata_mut(&mut self, mut visit: impl FnMut(&[NodeId], &mut NodeNetworkMetadata)) {
|
||||
let mut stack = vec![vec![]];
|
||||
while let Some(path) = stack.pop() {
|
||||
let Some(self_network_metadata) = self.network_metadata_mut(&path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
visit(&path, self_network_metadata);
|
||||
|
||||
// Only nodes that contain a nested network have metadata to recurse into, so skip leaf nodes.
|
||||
stack.extend(
|
||||
self_network_metadata
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.iter()
|
||||
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
|
||||
.map(|(node_id, _)| {
|
||||
let mut current_path: Vec<NodeId> = path.clone();
|
||||
current_path.push(*node_id);
|
||||
current_path
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
|
||||
self.for_each_network_view_state_mut(|path, view| {
|
||||
self.for_each_network_metadata_mut(|path, self_network_metadata| {
|
||||
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
|
||||
*view.navigation = other_network_metadata.persistent_metadata.navigation_metadata.clone();
|
||||
self_network_metadata.persistent_metadata.navigation_metadata = other_network_metadata.persistent_metadata.navigation_metadata.clone();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Copy all transient view and selection state from `other_interface` onto `self` at every nesting level:
|
||||
/// navigation metadata (pan/zoom), selection undo/redo history, and the document-to-viewport camera. Lets
|
||||
/// an interface rebuilt from storage keep the user's current view rather than reset it.
|
||||
/// an interface rebuilt from storage keep the user's current view rather than reset it. `resolved_types`
|
||||
/// is a separate runtime cache the caller handles.
|
||||
pub fn copy_all_transient_view_state(&mut self, other_interface: &NodeNetworkInterface) {
|
||||
self.for_each_network_view_state_mut(|path, view| {
|
||||
self.for_each_network_metadata_mut(|path, self_network_metadata| {
|
||||
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
|
||||
let self_persistent = &mut self_network_metadata.persistent_metadata;
|
||||
let other_persistent = &other_network_metadata.persistent_metadata;
|
||||
*view.navigation = other_persistent.navigation_metadata.clone();
|
||||
self_persistent.navigation_metadata = other_persistent.navigation_metadata.clone();
|
||||
|
||||
// The preview is this peer's and survives a rebuild, unless it names a node the rebuilt
|
||||
// network no longer contains (e.g. after a storage undo), in which case there is nothing
|
||||
// left to look at.
|
||||
*view.previewing = match other_persistent.previewing {
|
||||
Previewing::Yes { previewed } if !view.nodes.contains_key(&previewed.node_id) => Previewing::No,
|
||||
self_persistent.previewing = match other_persistent.previewing {
|
||||
Previewing::Yes { previewed } if !self_persistent.node_metadata.contains_key(&previewed.node_id) => Previewing::No,
|
||||
previewing => previewing,
|
||||
};
|
||||
|
||||
*view.selection.undo = other_persistent.selection_undo_history.clone();
|
||||
*view.selection.redo = other_persistent.selection_redo_history.clone();
|
||||
self_persistent.selection_undo_history = other_persistent.selection_undo_history.clone();
|
||||
self_persistent.selection_redo_history = other_persistent.selection_redo_history.clone();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -96,9 +125,9 @@ impl NodeNetworkInterface {
|
||||
self.unload_outward_wires(network_path);
|
||||
|
||||
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
||||
if let Some(encapsulating_transient) = self.encapsulating_network_transient_mut(network_path) {
|
||||
encapsulating_transient.outward_wires.unload();
|
||||
encapsulating_transient.all_nodes_bounding_box.unload();
|
||||
if let Some(encapsulating_network_metadata) = self.encapsulating_network_metadata_mut(network_path) {
|
||||
encapsulating_network_metadata.transient_metadata.outward_wires.unload();
|
||||
encapsulating_network_metadata.transient_metadata.all_nodes_bounding_box.unload();
|
||||
}
|
||||
|
||||
// Update the click targets for the encapsulating node, if it exists. There is no encapsulating node if the network is the document network
|
||||
@@ -113,7 +142,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a new input at insert index. If the insert index is -1 it is inserted at the end. The input_name is used by the encapsulating node.
|
||||
/// Inserts a new input at insert index. If the insert index is -1 it is inserted at the end. The output_name is used by the encapsulating node.
|
||||
pub fn add_import(&mut self, default_value: TaggedValue, exposed: bool, insert_index: isize, input_name: &str, input_description: &str, network_path: &[NodeId]) {
|
||||
let mut encapsulating_network_path = network_path.to_vec();
|
||||
let Some(node_id) = encapsulating_network_path.pop() else {
|
||||
@@ -402,7 +431,7 @@ impl NodeNetworkInterface {
|
||||
Some(node.replace_inputs(new_inputs, new_input_metadata))
|
||||
}
|
||||
|
||||
/// Used when opening an old document to add the persistent metadata for each input if it doesn't exist, which is where the name/description are saved.
|
||||
/// Used when opening an old document to add the persistent metadata for each input if it doesnt exist, which is where the name/description are saved.
|
||||
pub fn validate_input_metadata(&mut self, node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId]) {
|
||||
let number_of_inputs = node.inputs.len();
|
||||
let definition = self.reference(node_id, network_path).as_ref().and_then(resolve_document_node_type);
|
||||
@@ -531,7 +560,7 @@ impl NodeNetworkInterface {
|
||||
self.set_to_node_or_layer(layer_id, layer_path, false);
|
||||
}
|
||||
|
||||
// A no-op unless one of the two inputs is a wire
|
||||
// A no-op unless one of the two inputs is a wire, which covers every case the match distinguishes
|
||||
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
|
||||
|
||||
match (&old_input, &new_input) {
|
||||
@@ -601,10 +630,11 @@ impl NodeNetworkInterface {
|
||||
/// Whether writing `new_input` at `input_connector` would leave the network cyclic.
|
||||
///
|
||||
/// Asked of the network as it stands, with the proposed input substituted only while the question is
|
||||
/// answered, so nothing is written. An input that is not there reports `true`, so the caller abandons
|
||||
/// a write that would fail anyway.
|
||||
/// answered, so nothing is written and nothing is recorded. An input that is not there reports
|
||||
/// `true`, so the caller abandons a write that would fail anyway.
|
||||
///
|
||||
/// Writing an export can never close a cycle, since nothing takes an export as its input.
|
||||
/// Writing an export can never close a cycle: the dependency graph is built from what nodes take as
|
||||
/// input, and an export is not something a node can take.
|
||||
fn would_create_cycle(&self, input_connector: &InputConnector, new_input: &NodeInput, network_path: &[NodeId]) -> bool {
|
||||
let InputConnector::Node { node_id, input_index } = input_connector else { return false };
|
||||
|
||||
@@ -703,7 +733,9 @@ impl NodeNetworkInterface {
|
||||
/// Used to insert a group of nodes into the network
|
||||
pub fn insert_node_group(&mut self, nodes: Vec<(NodeId, NodeTemplate)>, new_ids: HashMap<NodeId, NodeId>, network_path: &[NodeId]) {
|
||||
for (old_node_id, mut node_template) in nodes {
|
||||
// Get the new node template
|
||||
node_template = self.map_ids(node_template, &old_node_id, &new_ids, network_path);
|
||||
// Insert node into network
|
||||
let node_id = *new_ids.get(&old_node_id).unwrap();
|
||||
self.insert_node_entry(NodeLocator::new(node_id, network_path), node_template);
|
||||
|
||||
@@ -818,7 +850,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
// Prune this network's pinned display order down to the nodes that still exist
|
||||
// Prune this network's pinned display order down to the nodes that still exist, dropping any that were actually removed
|
||||
let surviving_nodes = self.nested_network(network_path).map(|network| network.nodes.keys().copied().collect::<HashSet<_>>());
|
||||
if let Some(surviving_nodes) = surviving_nodes
|
||||
&& let Some(mut network) = self.network_mut(network_path)
|
||||
@@ -826,7 +858,7 @@ impl NodeNetworkInterface {
|
||||
network.retain_pinned(|node_id| surviving_nodes.contains(node_id));
|
||||
}
|
||||
|
||||
// Purge the deleted nodes' cached wire paths, which the per-node unload can no longer reach
|
||||
// Purge the deleted nodes' cached wire paths, since the per-node unload can no longer reach them once the nodes are gone
|
||||
if let Some(network_metadata) = self.network_metadata(network_path) {
|
||||
network_metadata
|
||||
.transient_metadata
|
||||
@@ -836,7 +868,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
// The per-node unload cannot reach nodes that no longer exist
|
||||
// Instead of unloaded all node click targets, just unload the nodes upstream from the deleted nodes. unload_upstream_node_click_targets will not work since the nodes have been deleted.
|
||||
self.unload_all_nodes_click_targets(network_path);
|
||||
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||
@@ -855,7 +887,7 @@ impl NodeNetworkInterface {
|
||||
network.set_previewing(Previewing::No);
|
||||
}
|
||||
|
||||
// The wire the downstream inputs reconnect to, which is the first exposed input of the node being removed
|
||||
// Check whether the being-deleted node's first (primary) input is a node
|
||||
let reconnect_to_input = self.document_node(node_id, network_path).and_then(|node| {
|
||||
node.inputs
|
||||
.iter()
|
||||
@@ -863,6 +895,7 @@ impl NodeNetworkInterface {
|
||||
.filter(|input| matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }))
|
||||
.cloned()
|
||||
});
|
||||
// Get all upstream references
|
||||
let number_of_outputs = self.number_of_outputs(node_id, network_path);
|
||||
let Some(all_outward_wires) = self.outward_wires(network_path) else {
|
||||
log::error!("Could not get outward wires in remove_references_from_network");
|
||||
@@ -962,6 +995,7 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
node.set_pinned(pinned);
|
||||
|
||||
// Track the node in this network's pinned display order: append when newly pinned, prune when unpinned
|
||||
if let Some(mut network) = self.network_mut(network_path) {
|
||||
network.record_pinned(*node_id, pinned);
|
||||
}
|
||||
@@ -1116,7 +1150,8 @@ impl NodeNetworkInterface {
|
||||
/// Renders `toggle_id` instead of the network's export, or stops doing so if it already is.
|
||||
///
|
||||
/// Per-peer and not a change to the document: the export keeps whatever it is wired to, and the
|
||||
/// compile path substitutes the previewed node into the graph it evaluates, so no other peer sees it.
|
||||
/// compile path substitutes the previewed node into the graph it evaluates. So there is nothing to
|
||||
/// restore when the preview ends, and nothing another peer would see.
|
||||
pub fn toggle_preview(&mut self, toggle_id: NodeId, network_path: &[NodeId]) {
|
||||
let previewing = match self.previewing(network_path) {
|
||||
Previewing::Yes { previewed } if previewed.node_id == toggle_id => Previewing::No,
|
||||
|
||||
@@ -25,6 +25,10 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// The document network as it should be evaluated, which is the document itself with the previewed
|
||||
/// node substituted for the export.
|
||||
///
|
||||
/// Previewing is this peer's alone, so it is applied to the copy being compiled rather than written
|
||||
/// into the document. Every path that compiles the graph goes through here, so none of them can
|
||||
/// render the export while the user is previewing something else.
|
||||
pub fn network_to_evaluate(&self) -> NodeNetwork {
|
||||
let mut network = self.document_network().clone();
|
||||
|
||||
@@ -919,3 +923,32 @@ impl NodeNetworkInterface {
|
||||
Self::from_trees(node_network, network_metadata)
|
||||
}
|
||||
}
|
||||
|
||||
// Private mutable getters for use within the network interface
|
||||
impl NodeNetworkInterface {
|
||||
/// Mutably get the network which the encapsulating node of the currently viewed network is part of. Will always be None in the document network.
|
||||
pub(super) fn encapsulating_network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
|
||||
let mut encapsulating_path = network_path.to_vec();
|
||||
encapsulating_path.pop()?;
|
||||
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
|
||||
log::error!("Could not get parent network in encapsulating_node_metadata");
|
||||
return None;
|
||||
};
|
||||
Some(parent_metadata)
|
||||
}
|
||||
|
||||
/// Get the node metadata for the node which encapsulates the currently viewed network. Will always be None in the document network.
|
||||
pub(super) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
|
||||
let mut encapsulating_path = network_path.to_vec();
|
||||
let encapsulating_node_id = encapsulating_path.pop()?;
|
||||
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
|
||||
log::error!("Could not get parent network in encapsulating_node_metadata");
|
||||
return None;
|
||||
};
|
||||
let Some(encapsulating_node_metadata) = parent_metadata.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id) else {
|
||||
log::error!("Could not get encapsulating node metadata in encapsulating_node_metadata");
|
||||
return None;
|
||||
};
|
||||
Some(encapsulating_node_metadata)
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -147,6 +147,8 @@ impl DocumentSettings<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of the position extraction in `NodeMetadataSource::position`.
|
||||
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
|
||||
/// The stored position of a node, which pairs with `is_layer` to reconstruct the runtime node type.
|
||||
pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position {
|
||||
match node_type {
|
||||
@@ -161,8 +163,6 @@ pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of the position extraction in `NodeMetadataSource::position`.
|
||||
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
|
||||
pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata {
|
||||
match (position, is_layer) {
|
||||
(Position::Absolute([x, y]), true) => NodeTypePersistentMetadata::layer(IVec2::new(x, y)),
|
||||
@@ -179,6 +179,9 @@ pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersis
|
||||
}
|
||||
|
||||
/// Builds a `NodeNetworkInterface` from a `NodeNetwork` plus the metadata vecs `Registry::to_runtime_with_full_metadata` emits.
|
||||
///
|
||||
/// Sets private fields directly (rather than via public setters) because we're constructing a fresh self-consistent snapshot;
|
||||
/// the setters' transient-cache invalidation isn't needed.
|
||||
pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<NodeMetadataEntry>, network_entries: Vec<NetworkMetadataEntry>) -> Result<NodeNetworkInterface, InterfaceRebuildError> {
|
||||
let mut network_metadata = NodeNetworkMetadata::default();
|
||||
seed_metadata_tree(&network, &mut network_metadata);
|
||||
|
||||
@@ -0,0 +1,936 @@
|
||||
use super::*;
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
/// Holds one of the two parallel trees so that only this module can write it.
|
||||
///
|
||||
/// `Deref` passes reads straight through, so a query reads the tree as though the interface held it
|
||||
/// directly. There is deliberately no `DerefMut` and the field is private to this module, so the only
|
||||
/// route to a `&mut` is the store API below, and a write that skips it does not compile rather than
|
||||
/// silently going unrecorded.
|
||||
///
|
||||
/// Transparent to serde, so wrapping a field does not change the document format.
|
||||
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Guarded<T>(T);
|
||||
|
||||
impl<T> std::ops::Deref for Guarded<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Guarded<T> {
|
||||
/// Both of these are private to the store, which is what makes the wrapper worth having: a sibling
|
||||
/// module can neither write a tree in place nor swap a different one into its place.
|
||||
fn new(value: T) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A network's selection undo and redo stacks, borrowed together since every operation on one is
|
||||
/// paired with one on the other.
|
||||
pub(crate) struct SelectionHistoryMut<'a> {
|
||||
pub(crate) undo: &'a mut VecDeque<SelectedNodes>,
|
||||
pub(crate) redo: &'a mut VecDeque<SelectedNodes>,
|
||||
}
|
||||
|
||||
/// Addresses one node: the network it lives in, and its ID within that network.
|
||||
///
|
||||
/// The store is the only place node identity is used for addressing, so this is the one type that
|
||||
/// changes when identity stops being derived from the node's location.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct NodeLocator<'a> {
|
||||
pub node_id: NodeId,
|
||||
pub network_path: &'a [NodeId],
|
||||
}
|
||||
|
||||
impl<'a> NodeLocator<'a> {
|
||||
pub fn new(node_id: NodeId, network_path: &'a [NodeId]) -> Self {
|
||||
Self { node_id, network_path }
|
||||
}
|
||||
|
||||
/// The path of the network this node owns, if it implements one.
|
||||
pub fn owned_network_path(&self) -> Vec<NodeId> {
|
||||
[self.network_path, &[self.node_id]].concat()
|
||||
}
|
||||
}
|
||||
|
||||
/// The graph and metadata halves of one node, resolved together so the two parallel trees are never
|
||||
/// reached separately and cannot drift apart.
|
||||
///
|
||||
/// Holds the halves directly rather than the interface, so a write cannot reach back out to query the
|
||||
/// graph or unload a cache: what a write invalidates is declared, not performed here.
|
||||
pub(crate) struct NodeMut<'a> {
|
||||
node: &'a mut DocumentNode,
|
||||
metadata: &'a mut DocumentNodePersistentMetadata,
|
||||
deltas: NodeDeltas<'a>,
|
||||
}
|
||||
|
||||
/// Where a node's writes record what they changed, carrying the node's address so each setter names
|
||||
/// what it wrote without its caller repeating it.
|
||||
struct NodeDeltas<'a> {
|
||||
deltas: &'a mut Vec<EditorDelta>,
|
||||
locator: NodeLocator<'a>,
|
||||
}
|
||||
|
||||
impl NodeDeltas<'_> {
|
||||
fn metadata(&mut self, change: NodeMetadataChange) {
|
||||
self.deltas.push(EditorDelta::NodeMetadata {
|
||||
network_path: self.locator.network_path.to_vec(),
|
||||
node_id: self.locator.node_id,
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
/// The nested network a node owns is addressed by the node's own path extended with its ID, which
|
||||
/// is the path a scoped conversion resolves that network's ID from.
|
||||
fn owned_network(&mut self, change: NetworkMetadataChange) {
|
||||
self.deltas.push(EditorDelta::NetworkMetadata {
|
||||
network_path: self.locator.owned_network_path(),
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
fn graph(&mut self, delta: RuntimeDelta) {
|
||||
self.deltas.push(EditorDelta::Graph(delta));
|
||||
}
|
||||
|
||||
fn input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
|
||||
self.deltas.push(EditorDelta::NodeInputMetadata {
|
||||
network_path: self.locator.network_path.to_vec(),
|
||||
node_id: self.locator.node_id,
|
||||
input_metadata,
|
||||
});
|
||||
}
|
||||
|
||||
fn snapshot(&mut self, metadata: Box<DocumentNodePersistentMetadata>) {
|
||||
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
|
||||
network_path: self.locator.network_path.to_vec(),
|
||||
node_id: self.locator.node_id,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
fn network_path(&self) -> Vec<NodeId> {
|
||||
self.locator.network_path.to_vec()
|
||||
}
|
||||
|
||||
fn node_id(&self) -> NodeId {
|
||||
self.locator.node_id
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeMut<'_> {
|
||||
/// Places the node at an absolute grid position, keeping whether it is displayed as a layer or a node.
|
||||
pub(crate) fn set_absolute_position(&mut self, position: IVec2) -> bool {
|
||||
let node_type = match self.metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::layer(position),
|
||||
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::node(position),
|
||||
};
|
||||
self.set_node_type(node_type)
|
||||
}
|
||||
|
||||
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
|
||||
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
|
||||
let shifted = match self.metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Absolute(position),
|
||||
}) => NodeTypePersistentMetadata::layer(position + shift),
|
||||
NodeTypePersistentMetadata::Node(ref node) => match node.position {
|
||||
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
|
||||
NodePosition::Chain => return false,
|
||||
},
|
||||
NodeTypePersistentMetadata::Layer(_) => return false,
|
||||
};
|
||||
self.set_node_type(shifted)
|
||||
}
|
||||
|
||||
/// Stacks a layer `y_offset` below the sibling it feeds. Nodes are never stacked.
|
||||
pub(crate) fn set_stack_position(&mut self, y_offset: u32) -> bool {
|
||||
if !self.metadata.is_layer() {
|
||||
return false;
|
||||
}
|
||||
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Stack(y_offset),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Chains a node to the left of the layer it feeds. Layers are never chained.
|
||||
pub(crate) fn set_chain_position(&mut self) -> bool {
|
||||
if self.metadata.is_layer() {
|
||||
return false;
|
||||
}
|
||||
self.set_node_type(NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)))
|
||||
}
|
||||
|
||||
/// Whether the node is displayed as a layer, which decides the kinds of position it can hold.
|
||||
pub(crate) fn is_layer(&self) -> bool {
|
||||
self.metadata.is_layer()
|
||||
}
|
||||
|
||||
/// Whether the node is rendered, which the compiler reads to replace it with a passthrough.
|
||||
pub(crate) fn set_visible(&mut self, visible: bool) -> bool {
|
||||
let changed = self.node.visible != visible;
|
||||
self.node.visible = visible;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetVisibility {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
visible,
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The type of argument the node can be evaluated with.
|
||||
pub(crate) fn set_call_argument(&mut self, call_argument: Type) -> bool {
|
||||
let changed = self.node.call_argument != call_argument;
|
||||
self.node.call_argument = call_argument;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetCallArgument {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
call_argument: self.node.call_argument.clone(),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The Extract and Inject annotations the node declares for the Context.
|
||||
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
|
||||
let changed = self.node.context_features != context_features;
|
||||
self.node.context_features = context_features;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetContextFeatures {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
context_features: self.node.context_features,
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The user-chosen name for this instance, empty when it has none.
|
||||
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
|
||||
let changed = self.metadata.display_name != display_name;
|
||||
self.metadata.display_name = display_name;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::DisplayName(self.metadata.display_name.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_locked(&mut self, locked: bool) -> bool {
|
||||
let changed = self.metadata.locked != locked;
|
||||
self.metadata.locked = locked;
|
||||
if changed {
|
||||
self.deltas.metadata(NodeMetadataChange::Locked(locked));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_pinned(&mut self, pinned: bool) -> bool {
|
||||
let changed = self.metadata.pinned != pinned;
|
||||
self.metadata.pinned = pinned;
|
||||
if changed {
|
||||
self.deltas.metadata(NodeMetadataChange::Pinned(pinned));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Whether the node is displayed as a layer or a node, together with its position, which are one
|
||||
/// choice: a layer and a node do not have the same kinds of position.
|
||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||
let changed = self.metadata.node_type_metadata != node_type;
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The definition this node's nested network was instantiated from, dropped once the node is edited
|
||||
/// away from it. Only network nodes carry one.
|
||||
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
|
||||
let Some(network_metadata) = self.metadata.network_metadata.as_mut() else { return false };
|
||||
let changed = network_metadata.persistent_metadata.reference != reference;
|
||||
network_metadata.persistent_metadata.reference = reference;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::Reference(network_metadata.persistent_metadata.reference.clone());
|
||||
self.deltas.owned_network(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_input_name(&mut self, input_index: usize, input_name: String) -> bool {
|
||||
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
|
||||
let changed = input_metadata.persistent_metadata.input_name != input_name;
|
||||
input_metadata.persistent_metadata.input_name = input_name;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::InputName {
|
||||
index: input_index,
|
||||
name: input_metadata.persistent_metadata.input_name.clone(),
|
||||
};
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The identifier of the widget override the properties panel uses for this input, or `None` for the
|
||||
/// widget generated from its type.
|
||||
pub(crate) fn set_widget_override(&mut self, input_index: usize, widget_override: Option<String>) -> bool {
|
||||
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
|
||||
input_metadata.persistent_metadata.widget_override = widget_override;
|
||||
|
||||
let change = NodeMetadataChange::WidgetOverride {
|
||||
index: input_index,
|
||||
widget_override: input_metadata.persistent_metadata.widget_override.clone(),
|
||||
};
|
||||
self.deltas.metadata(change);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn set_output_name(&mut self, output_index: usize, output_name: String) -> bool {
|
||||
let Some(existing) = self.metadata.output_names.get_mut(output_index) else { return false };
|
||||
let changed = *existing != output_name;
|
||||
*existing = output_name;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The encapsulating node's names for every one of the network's exports, replaced together since
|
||||
/// they are stored as one array.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
|
||||
let changed = self.metadata.output_names != output_names;
|
||||
self.metadata.output_names = output_names;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The metadata array the node's inputs index, one entry per input.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
|
||||
&self.metadata.input_metadata
|
||||
}
|
||||
|
||||
/// Grows `output_names` to one entry per export, which an older document may be missing.
|
||||
pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) {
|
||||
if self.metadata.output_names.len() == number_of_exports {
|
||||
return;
|
||||
}
|
||||
self.metadata.output_names.resize(number_of_exports, String::new());
|
||||
|
||||
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
|
||||
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
|
||||
/// entry for the added index. Restores the parallel-array invariant for an older document.
|
||||
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
|
||||
if self.metadata.input_metadata.len() >= number_of_inputs {
|
||||
return;
|
||||
}
|
||||
for added_input_index in self.metadata.input_metadata.len()..number_of_inputs {
|
||||
self.metadata.input_metadata.push(defaults(added_input_index).unwrap_or_default());
|
||||
}
|
||||
self.emit_input_metadata();
|
||||
}
|
||||
|
||||
/// Swaps in a new implementation together with the nested network metadata that belongs to it.
|
||||
///
|
||||
/// Replaces the node and everything nested under it, since the nested network goes with the
|
||||
/// implementation.
|
||||
pub(crate) fn replace_implementation(&mut self, implementation: DocumentNodeImplementation, network_metadata: Option<NodeNetworkMetadata>) {
|
||||
self.node.implementation = implementation;
|
||||
self.metadata.network_metadata = network_metadata;
|
||||
|
||||
let delta = RuntimeDelta::ReplaceNode {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
node: Box::new(self.node.clone()),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
let metadata = Box::new(self.metadata.clone());
|
||||
self.deltas.snapshot(metadata);
|
||||
}
|
||||
|
||||
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
|
||||
/// which is the write a metadata snapshot describes.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
|
||||
*self.metadata = metadata;
|
||||
|
||||
let snapshot = Box::new(self.metadata.clone());
|
||||
self.deltas.snapshot(snapshot);
|
||||
}
|
||||
|
||||
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
|
||||
self.metadata.input_metadata = input_metadata;
|
||||
self.emit_input_metadata();
|
||||
}
|
||||
|
||||
/// Swaps in new inputs together with their metadata, returning the inputs replaced.
|
||||
pub(crate) fn replace_inputs(&mut self, inputs: Vec<NodeInput>, input_metadata: Vec<InputMetadata>) -> Vec<NodeInput> {
|
||||
self.metadata.input_metadata = input_metadata;
|
||||
let previous = std::mem::replace(&mut self.node.inputs, inputs);
|
||||
|
||||
self.emit_inputs();
|
||||
previous
|
||||
}
|
||||
|
||||
/// Records the node's input list and the metadata array indexed by it, which change together
|
||||
/// whenever the number or order of slots does.
|
||||
fn emit_inputs(&mut self) {
|
||||
let delta = RuntimeDelta::SetInputs {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
inputs: self.node.inputs.clone(),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
self.emit_input_metadata();
|
||||
}
|
||||
|
||||
fn emit_input_metadata(&mut self) {
|
||||
let input_metadata = self.metadata.input_metadata.clone();
|
||||
self.deltas.input_metadata(input_metadata);
|
||||
}
|
||||
}
|
||||
|
||||
/// The persistent metadata of one network, resolved once so a run of writes walks the tree a single time.
|
||||
///
|
||||
/// Metadata only: the graph half of a network is its export slots, which are addressed through
|
||||
/// [`NodeNetworkInterface::set_input_slot`] like any other input.
|
||||
pub(crate) struct NetworkMut<'a> {
|
||||
metadata: &'a mut NodeNetworkPersistentMetadata,
|
||||
deltas: &'a mut Vec<EditorDelta>,
|
||||
network_path: &'a [NodeId],
|
||||
}
|
||||
|
||||
impl NetworkMut<'_> {
|
||||
/// Which node the network renders instead of its export.
|
||||
///
|
||||
/// Per-peer view state, so this is not recorded: the document is untouched, and the compile path
|
||||
/// substitutes the previewed node into the graph it evaluates.
|
||||
pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool {
|
||||
let changed = self.metadata.previewing != previewing;
|
||||
self.metadata.previewing = previewing;
|
||||
changed
|
||||
}
|
||||
|
||||
/// The definition this network was instantiated from, dropped once it is edited away from it.
|
||||
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
|
||||
let changed = self.metadata.reference != reference;
|
||||
self.metadata.reference = reference;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::Reference(self.metadata.reference.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The display order of pinned nodes in the Properties panel.
|
||||
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
||||
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
||||
self.metadata.pinned_node_order = pinned_node_order;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Appends a newly pinned node to the display order, or drops one that is no longer pinned.
|
||||
pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool {
|
||||
let order = &mut self.metadata.pinned_node_order;
|
||||
let changed = match pinned {
|
||||
true if !order.contains(&node_id) => {
|
||||
order.push(node_id);
|
||||
true
|
||||
}
|
||||
true => false,
|
||||
false => {
|
||||
let before = order.len();
|
||||
order.retain(|id| *id != node_id);
|
||||
order.len() != before
|
||||
}
|
||||
};
|
||||
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Drops every node the order names that is no longer in the network.
|
||||
pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool {
|
||||
let before = self.metadata.pinned_node_order.len();
|
||||
self.metadata.pinned_node_order.retain(&surviving);
|
||||
|
||||
let changed = self.metadata.pinned_node_order.len() != before;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn emit(&mut self, change: NetworkMetadataChange) {
|
||||
self.deltas.push(EditorDelta::NetworkMetadata {
|
||||
network_path: self.network_path.to_vec(),
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
/// The transform from node graph space to viewport space.
|
||||
pub(crate) fn set_navigation_transform(&mut self, transform: DAffine2) -> bool {
|
||||
let changed = self.metadata.navigation_metadata.node_graph_to_viewport != transform;
|
||||
self.metadata.navigation_metadata.node_graph_to_viewport = transform;
|
||||
changed
|
||||
}
|
||||
|
||||
/// The width of the node graph in viewport space.
|
||||
pub(crate) fn set_navigation_width(&mut self, node_graph_width: f64) -> bool {
|
||||
let changed = self.metadata.navigation_metadata.node_graph_width != node_graph_width;
|
||||
self.metadata.navigation_metadata.node_graph_width = node_graph_width;
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
// The store: the only writer of the node graph and its parallel metadata tree. Every write keeps the
|
||||
// two halves in step by construction, so the invariants checked by `validate_invariants` hold without
|
||||
// each caller restating them.
|
||||
impl NodeNetworkInterface {
|
||||
/// Builds an interface around a freshly-assembled pair of trees, for a document arriving from
|
||||
/// storage or from an older format rather than being edited into existence.
|
||||
///
|
||||
/// The only way to install them, since `Guarded` cannot be constructed outside this module either.
|
||||
/// Nothing is recorded: the trees are the document, not a set of changes to it.
|
||||
pub(super) fn from_trees(network: NodeNetwork, network_metadata: NodeNetworkMetadata) -> Self {
|
||||
Self {
|
||||
network: Guarded::new(MemoNetwork::new(network)),
|
||||
network_metadata: Guarded::new(network_metadata),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The transient caches of a network.
|
||||
///
|
||||
/// Deliberately separate from the document write API: unloading a cache is not a change to the
|
||||
/// document, so there is nothing to record. Handing these out through their own accessor is what
|
||||
/// lets the document-writing ones stay closed.
|
||||
pub(super) fn network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
|
||||
Some(&mut self.network_metadata_mut(network_path)?.transient_metadata)
|
||||
}
|
||||
|
||||
/// The transient caches of one node, for the same reason.
|
||||
pub(super) fn node_transient_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeTransientMetadata> {
|
||||
let network_metadata = self.network_metadata_mut(network_path)?;
|
||||
Some(&mut network_metadata.persistent_metadata.node_metadata.get_mut(node_id)?.transient_metadata)
|
||||
}
|
||||
|
||||
/// What the selection was, for the undo and redo of selection alone.
|
||||
///
|
||||
/// Stored in the persistent tree but not part of the document: which nodes a peer has selected is
|
||||
/// that peer's, so these writes are not recorded and do not reach storage.
|
||||
pub(super) fn selection_history_mut(&mut self, network_path: &[NodeId]) -> Option<SelectionHistoryMut<'_>> {
|
||||
let persistent = &mut self.network_metadata_mut(network_path)?.persistent_metadata;
|
||||
Some(SelectionHistoryMut {
|
||||
undo: &mut persistent.selection_undo_history,
|
||||
redo: &mut persistent.selection_redo_history,
|
||||
})
|
||||
}
|
||||
|
||||
/// The graph of the network at `network_path`. Private: every write to it is one of the primitives
|
||||
/// below, which is what keeps a change from going unrecorded.
|
||||
fn network_graph_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
|
||||
self.document_network_mut().nested_network_mut(network_path)
|
||||
}
|
||||
|
||||
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
|
||||
///
|
||||
/// Nothing is recorded: a migration produces the document the peer should have had rather than
|
||||
/// changing the one they have. Not a route for editing, which goes through the writes below.
|
||||
pub(super) fn migrate_graph(&mut self, migrate: impl FnOnce(&mut NodeNetwork)) {
|
||||
migrate(self.document_network_mut());
|
||||
}
|
||||
|
||||
/// Where the node graph is panned and zoomed to.
|
||||
///
|
||||
/// Per-peer view state like the selection: it rides in the persistent tree but is persisted to
|
||||
/// `session.json` rather than the registry, so these writes are deliberately not recorded.
|
||||
pub(super) fn navigation_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NavigationMetadata> {
|
||||
Some(&mut self.network_metadata_mut(network_path)?.persistent_metadata.navigation_metadata)
|
||||
}
|
||||
|
||||
/// The root of the graph tree. The only `&mut` to it in the codebase, since `Guarded` withholds one
|
||||
/// everywhere else.
|
||||
fn document_network_mut(&mut self) -> &mut NodeNetwork {
|
||||
self.network.get_mut().network_mut()
|
||||
}
|
||||
|
||||
/// The metadata tree at `network_path`. The only `&mut` to it, for the same reason.
|
||||
pub(super) fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
|
||||
self.network_metadata.get_mut().nested_metadata_mut(network_path)
|
||||
}
|
||||
|
||||
/// The persistent metadata of a network, or `None` if the network is missing.
|
||||
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
|
||||
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
|
||||
Some(NetworkMut {
|
||||
metadata,
|
||||
deltas: &mut self.deltas,
|
||||
network_path,
|
||||
})
|
||||
}
|
||||
|
||||
/// Both halves of a node, or `None` if either is missing.
|
||||
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
|
||||
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
|
||||
let metadata = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(locator.network_path)?
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.get_mut(&locator.node_id)?;
|
||||
|
||||
Some(NodeMut {
|
||||
node,
|
||||
metadata: &mut metadata.persistent_metadata,
|
||||
deltas: NodeDeltas { deltas: &mut self.deltas, locator },
|
||||
})
|
||||
}
|
||||
|
||||
/// Inserts an input and its metadata at `index`, clamped to the end. Returns whether the node was found.
|
||||
pub(crate) fn insert_input_slot(&mut self, locator: NodeLocator, index: usize, input: NodeInput, metadata: InputMetadata) -> bool {
|
||||
let Some(mut node) = self.node_mut(locator) else {
|
||||
log::error!("Could not get node {} in _input_slot", locator.node_id);
|
||||
return false;
|
||||
};
|
||||
|
||||
let index = index.min(node.node.inputs.len());
|
||||
node.node.inputs.insert(index, input);
|
||||
node.metadata.input_metadata.insert(index.min(node.metadata.input_metadata.len()), metadata);
|
||||
node.emit_inputs();
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes the input at `index` together with its metadata, returning both.
|
||||
pub(crate) fn remove_input_slot(&mut self, locator: NodeLocator, index: usize) -> Option<(NodeInput, InputMetadata)> {
|
||||
let Some(mut node) = self.node_mut(locator) else {
|
||||
log::error!("Could not get node {} in _input_slot", locator.node_id);
|
||||
return None;
|
||||
};
|
||||
|
||||
if index >= node.node.inputs.len() {
|
||||
log::error!("Input index {index} out of bounds in remove_input_slot for node {}", locator.node_id);
|
||||
return None;
|
||||
}
|
||||
|
||||
let input = node.node.inputs.remove(index);
|
||||
let metadata = (index < node.metadata.input_metadata.len()).then(|| node.metadata.input_metadata.remove(index));
|
||||
node.emit_inputs();
|
||||
Some((input, metadata.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Moves the input at `from` to `to`, carrying its metadata with it.
|
||||
///
|
||||
/// Records the removal and the insertion separately, so the list is briefly one slot short. Both
|
||||
/// land in the same batch, where the second supersedes the first.
|
||||
pub(crate) fn move_input_slot(&mut self, locator: NodeLocator, from: usize, to: usize) -> bool {
|
||||
let Some((input, metadata)) = self.remove_input_slot(locator, from) else { return false };
|
||||
self.insert_input_slot(locator, to, input, metadata)
|
||||
}
|
||||
|
||||
/// Inserts an export at `index`, clamped to the end, along with the name the encapsulating node shows
|
||||
/// for it. The document network has no encapsulating node, so it carries no name.
|
||||
pub(crate) fn insert_export_slot(&mut self, network_path: &[NodeId], index: usize, export: NodeInput, output_name: String) -> bool {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in insert_export_slot");
|
||||
return false;
|
||||
};
|
||||
|
||||
let index = index.min(network.exports.len());
|
||||
network.exports.insert(index, export);
|
||||
|
||||
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
|
||||
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
|
||||
output_names.insert(index.min(output_names.len()), output_name);
|
||||
}
|
||||
self.emit_exports_from(network_path, index, None);
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes the export at `index` together with the encapsulating node's name for it.
|
||||
pub(crate) fn remove_export_slot(&mut self, network_path: &[NodeId], index: usize) -> Option<NodeInput> {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in remove_export_slot");
|
||||
return None;
|
||||
};
|
||||
|
||||
if index >= network.exports.len() {
|
||||
log::error!("Export index {index} out of bounds in remove_export_slot");
|
||||
return None;
|
||||
}
|
||||
let export = network.exports.remove(index);
|
||||
// The list shrank by one, so what was the last index now has no slot and has to be cleared.
|
||||
let vacated = network.exports.len();
|
||||
|
||||
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
|
||||
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
|
||||
if index < output_names.len() {
|
||||
output_names.remove(index);
|
||||
}
|
||||
}
|
||||
self.emit_exports_from(network_path, index, Some(vacated));
|
||||
Some(export)
|
||||
}
|
||||
|
||||
/// Records every export slot from `index` on, plus a clear for `vacated` when the list shrank.
|
||||
///
|
||||
/// Export slots are addressed by index, so inserting or removing one changes the meaning of every
|
||||
/// later slot and each has to be restated. The encapsulating node's names for them ride along as one
|
||||
/// whole-array metadata write.
|
||||
fn emit_exports_from(&mut self, network_path: &[NodeId], index: usize, vacated: Option<usize>) {
|
||||
let Some(network) = self.network.network().nested_network(network_path) else { return };
|
||||
let exports: Vec<_> = network.exports.iter().skip(index).cloned().collect();
|
||||
|
||||
for (offset, export) in exports.into_iter().enumerate() {
|
||||
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: index + offset,
|
||||
input: Some(export),
|
||||
}));
|
||||
}
|
||||
if let Some(vacated) = vacated {
|
||||
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: vacated,
|
||||
input: None,
|
||||
}));
|
||||
}
|
||||
|
||||
let Some((&node_id, parent_path)) = network_path.split_last() else { return };
|
||||
let Some(metadata) = self.encapsulating_node_metadata(network_path) else { return };
|
||||
let change = NodeMetadataChange::OutputNames(metadata.persistent_metadata.output_names.clone());
|
||||
self.deltas.push(EditorDelta::NodeMetadata {
|
||||
network_path: parent_path.to_vec(),
|
||||
node_id,
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
/// Moves the export at `from` to `to`, carrying the encapsulating node's name for it.
|
||||
pub(crate) fn move_export_slot(&mut self, network_path: &[NodeId], from: usize, to: usize) -> bool {
|
||||
let name = self
|
||||
.encapsulating_node_metadata(network_path)
|
||||
.and_then(|metadata| metadata.persistent_metadata.output_names.get(from).cloned())
|
||||
.unwrap_or_default();
|
||||
let Some(export) = self.remove_export_slot(network_path, from) else { return false };
|
||||
self.insert_export_slot(network_path, to, export, name)
|
||||
}
|
||||
|
||||
/// Writes the input at `connector`, returning the input it replaced.
|
||||
pub(crate) fn set_input_slot(&mut self, connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> Option<NodeInput> {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in set_input_slot");
|
||||
return None;
|
||||
};
|
||||
|
||||
let slot = match connector {
|
||||
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
|
||||
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
|
||||
};
|
||||
let Some(slot) = slot else {
|
||||
log::error!("Could not get input {connector:?} in set_input_slot");
|
||||
return None;
|
||||
};
|
||||
|
||||
if *slot == input {
|
||||
return Some(input);
|
||||
}
|
||||
let previous = std::mem::replace(slot, input.clone());
|
||||
|
||||
self.deltas.push(EditorDelta::Graph(match connector {
|
||||
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
|
||||
network_path: network_path.to_vec(),
|
||||
node_id: *node_id,
|
||||
input_index: *input_index,
|
||||
input,
|
||||
},
|
||||
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: *export_index,
|
||||
input: Some(input),
|
||||
},
|
||||
}));
|
||||
|
||||
Some(previous)
|
||||
}
|
||||
|
||||
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
|
||||
///
|
||||
/// For a change expressed as an operation on the existing value rather than as a replacement of it.
|
||||
/// Reading the value out, editing it, and writing it back would copy it twice; the recorded delta
|
||||
/// still carries the whole result, since the storage op is a whole-value write.
|
||||
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
|
||||
let slot = match connector {
|
||||
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
|
||||
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
|
||||
};
|
||||
let Some(slot) = slot else {
|
||||
log::error!("Could not get input {connector:?} in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
let Some(mut value) = slot.as_value_mut() else {
|
||||
log::error!("Input {connector:?} is not a value in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
|
||||
edit(&mut value);
|
||||
drop(value);
|
||||
|
||||
let input = slot.clone();
|
||||
self.deltas.push(EditorDelta::Graph(match connector {
|
||||
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
|
||||
network_path: network_path.to_vec(),
|
||||
node_id: *node_id,
|
||||
input_index: *input_index,
|
||||
input,
|
||||
},
|
||||
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: *export_index,
|
||||
input: Some(input),
|
||||
},
|
||||
}));
|
||||
true
|
||||
}
|
||||
|
||||
/// Inserts a node and its metadata, returning the entry it replaced.
|
||||
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
|
||||
if !self.network_pair_exists(locator.network_path) {
|
||||
log::error!("Could not get network {:?} in insert_node_entry", locator.network_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let (document_node, persistent_metadata) = template.into_parts();
|
||||
let node = Box::new(document_node.clone());
|
||||
let metadata = Box::new(persistent_metadata.clone());
|
||||
|
||||
let previous_node = self
|
||||
.network
|
||||
.get_mut()
|
||||
.network_mut()
|
||||
.nested_network_mut(locator.network_path)?
|
||||
.nodes
|
||||
.insert(locator.node_id, document_node);
|
||||
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
|
||||
locator.node_id,
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata,
|
||||
transient_metadata: DocumentNodeTransientMetadata::default(),
|
||||
},
|
||||
);
|
||||
|
||||
// Overwriting an existing entry replaces the node and everything nested under it, which is what
|
||||
// distinguishes the two from the storage side.
|
||||
let network_path = locator.network_path.to_vec();
|
||||
let node_id = locator.node_id;
|
||||
self.deltas.push(EditorDelta::Graph(match previous_node.is_some() {
|
||||
true => RuntimeDelta::ReplaceNode {
|
||||
network_path: network_path.clone(),
|
||||
node_id,
|
||||
node,
|
||||
},
|
||||
false => RuntimeDelta::AddNode {
|
||||
network_path: network_path.clone(),
|
||||
node_id,
|
||||
node,
|
||||
},
|
||||
}));
|
||||
self.deltas.push(EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata });
|
||||
|
||||
previous_node
|
||||
.zip(previous_metadata)
|
||||
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
|
||||
}
|
||||
|
||||
/// Removes a node and its metadata, returning them joined as a template.
|
||||
pub(crate) fn remove_node_entry(&mut self, locator: NodeLocator) -> Option<NodeTemplate> {
|
||||
if !self.network_pair_exists(locator.network_path) {
|
||||
log::error!("Could not get network {:?} in remove_node_entry", locator.network_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
|
||||
let metadata = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(locator.network_path)?
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.remove(&locator.node_id);
|
||||
|
||||
if node.is_some() {
|
||||
self.deltas.push(EditorDelta::Graph(RuntimeDelta::RemoveNode {
|
||||
network_path: locator.network_path.to_vec(),
|
||||
node_id: locator.node_id,
|
||||
}));
|
||||
}
|
||||
|
||||
node.zip(metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
|
||||
}
|
||||
|
||||
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
|
||||
/// halves out of step.
|
||||
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
|
||||
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
|
||||
}
|
||||
|
||||
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
|
||||
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
|
||||
std::mem::take(&mut self.deltas)
|
||||
}
|
||||
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the
|
||||
/// document. Bringing an old document up to date produces the document rather than changing it, so
|
||||
/// there is nothing to report.
|
||||
pub(crate) fn discard_deltas(&mut self) {
|
||||
self.deltas.clear();
|
||||
}
|
||||
|
||||
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
|
||||
/// once its signature is edited.
|
||||
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
|
||||
if let Some(mut network) = self.network_mut(network_path) {
|
||||
network.set_reference(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
//! Every route to a mutable reference inside the two trees, gathered here so the whole mutable
|
||||
//! surface can be read in one place.
|
||||
//!
|
||||
//! Two tiers of visibility carry the rule. `pub(super)` reaches only the rest of `store` and hands
|
||||
//! out the raw trees, so an unrecorded write to the document cannot be spelled outside this module.
|
||||
//! `pub(in super::super)` reaches the rest of the network interface, and hands out only state the
|
||||
//! registry never holds: transient caches, and this peer's view state.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
// ===== Raw trees, reachable only from the store =====
|
||||
|
||||
/// The root of the graph tree.
|
||||
fn document_network_mut(&mut self) -> &mut NodeNetwork {
|
||||
self.network.get_mut().network_mut()
|
||||
}
|
||||
|
||||
/// The graph of the network at `network_path`, written only by the store's primitives.
|
||||
pub(super) fn network_graph_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
|
||||
self.document_network_mut().nested_network_mut(network_path)
|
||||
}
|
||||
|
||||
/// The metadata tree at `network_path`.
|
||||
fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
|
||||
self.network_metadata.get_mut().nested_metadata_mut(network_path)
|
||||
}
|
||||
|
||||
/// The metadata of the node that encapsulates the network at `network_path`, or `None` for the
|
||||
/// document network, which no node encapsulates.
|
||||
pub(super) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
|
||||
let mut encapsulating_path = network_path.to_vec();
|
||||
let encapsulating_node_id = encapsulating_path.pop()?;
|
||||
self.network_metadata_mut(&encapsulating_path)?.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id)
|
||||
}
|
||||
|
||||
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
|
||||
///
|
||||
/// Nothing is recorded: a migration produces the document the peer should have had rather than
|
||||
/// changing the one they have.
|
||||
pub(in super::super) fn migrate_graph(&mut self, migrate: impl FnOnce(&mut NodeNetwork)) {
|
||||
migrate(self.document_network_mut());
|
||||
}
|
||||
|
||||
// ===== Recorded writes =====
|
||||
|
||||
/// The persistent metadata of a network, or `None` if the network is missing.
|
||||
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
|
||||
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
|
||||
Some(NetworkMut::new(metadata, &mut self.deltas, network_path))
|
||||
}
|
||||
|
||||
/// Both halves of a node, or `None` if either is missing.
|
||||
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
|
||||
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
|
||||
let metadata = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(locator.network_path)?
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.get_mut(&locator.node_id)?;
|
||||
|
||||
Some(NodeMut::new(node, &mut metadata.persistent_metadata, &mut self.deltas, locator))
|
||||
}
|
||||
|
||||
// ===== Unrecorded state, reachable from the whole network interface =====
|
||||
|
||||
/// The transient caches of a network, which are not part of the document and so record nothing.
|
||||
pub(in super::super) fn network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
|
||||
Some(&mut self.network_metadata_mut(network_path)?.transient_metadata)
|
||||
}
|
||||
|
||||
/// The transient caches of one node.
|
||||
pub(in super::super) fn node_transient_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeTransientMetadata> {
|
||||
let network_metadata = self.network_metadata_mut(network_path)?;
|
||||
Some(&mut network_metadata.persistent_metadata.node_metadata.get_mut(node_id)?.transient_metadata)
|
||||
}
|
||||
|
||||
/// The transient caches of the network that the network at `network_path` sits inside.
|
||||
pub(in super::super) fn encapsulating_network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
|
||||
let mut encapsulating_path = network_path.to_vec();
|
||||
encapsulating_path.pop()?;
|
||||
self.network_transient_mut(&encapsulating_path)
|
||||
}
|
||||
|
||||
/// The selection undo and redo stacks. Per-peer state that is not recorded and does not reach storage.
|
||||
pub(in super::super) fn selection_history_mut(&mut self, network_path: &[NodeId]) -> Option<SelectionHistoryMut<'_>> {
|
||||
let persistent = &mut self.network_metadata_mut(network_path)?.persistent_metadata;
|
||||
Some(SelectionHistoryMut {
|
||||
undo: &mut persistent.selection_undo_history,
|
||||
redo: &mut persistent.selection_redo_history,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the node graph is panned and zoomed to. This write is not recorded.
|
||||
pub(in super::super) fn navigation_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NavigationMetadata> {
|
||||
Some(&mut self.network_metadata_mut(network_path)?.persistent_metadata.navigation_metadata)
|
||||
}
|
||||
|
||||
/// Visits every network at every nesting level with its view state, for restoring what the peer was
|
||||
/// looking at onto an interface rebuilt from storage.
|
||||
pub(in super::super) fn for_each_network_view_state_mut(&mut self, mut visit: impl FnMut(&[NodeId], NetworkViewStateMut)) {
|
||||
let mut stack = vec![Vec::new()];
|
||||
while let Some(network_path) = stack.pop() {
|
||||
let Some(network_metadata) = self.network_metadata_mut(&network_path) else { continue };
|
||||
let persistent = &mut network_metadata.persistent_metadata;
|
||||
|
||||
stack.extend(
|
||||
persistent
|
||||
.node_metadata
|
||||
.iter()
|
||||
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
|
||||
.map(|(node_id, _)| [network_path.as_slice(), &[*node_id]].concat()),
|
||||
);
|
||||
|
||||
visit(
|
||||
&network_path,
|
||||
NetworkViewStateMut {
|
||||
navigation: &mut persistent.navigation_metadata,
|
||||
previewing: &mut persistent.previewing,
|
||||
selection: SelectionHistoryMut {
|
||||
undo: &mut persistent.selection_undo_history,
|
||||
redo: &mut persistent.selection_redo_history,
|
||||
},
|
||||
nodes: &persistent.node_metadata,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One network's per-peer view state: what a rebuild restores, and what the registry never records.
|
||||
pub(crate) struct NetworkViewStateMut<'a> {
|
||||
pub(crate) navigation: &'a mut NavigationMetadata,
|
||||
pub(crate) previewing: &'a mut Previewing,
|
||||
pub(crate) selection: SelectionHistoryMut<'a>,
|
||||
/// The network's nodes, for a view field that may only name one that still exists.
|
||||
pub(crate) nodes: &'a HashMap<NodeId, DocumentNodeMetadata>,
|
||||
}
|
||||
-500
@@ -1,500 +0,0 @@
|
||||
//! The recorded-write cursors: the only handles through which a node or a network is edited.
|
||||
//!
|
||||
//! Each setter writes its field and records a delta naming exactly what it wrote, so a write cannot
|
||||
//! reach the document without also reaching the delta buffer.
|
||||
|
||||
use super::*;
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
/// A network's selection undo and redo stacks, borrowed together since every operation on one is
|
||||
/// paired with one on the other.
|
||||
pub(crate) struct SelectionHistoryMut<'a> {
|
||||
pub(crate) undo: &'a mut VecDeque<SelectedNodes>,
|
||||
pub(crate) redo: &'a mut VecDeque<SelectedNodes>,
|
||||
}
|
||||
|
||||
/// Addresses one node: the network it lives in, and its ID within that network.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct NodeLocator<'a> {
|
||||
pub node_id: NodeId,
|
||||
pub network_path: &'a [NodeId],
|
||||
}
|
||||
|
||||
impl<'a> NodeLocator<'a> {
|
||||
pub fn new(node_id: NodeId, network_path: &'a [NodeId]) -> Self {
|
||||
Self { node_id, network_path }
|
||||
}
|
||||
|
||||
/// The path of the network this node owns, if it implements one.
|
||||
pub fn owned_network_path(&self) -> Vec<NodeId> {
|
||||
[self.network_path, &[self.node_id]].concat()
|
||||
}
|
||||
}
|
||||
|
||||
/// The graph and metadata halves of one node, resolved together so the two parallel trees are never
|
||||
/// reached separately and cannot drift apart.
|
||||
///
|
||||
/// Holds the halves directly rather than the interface, so a write cannot reach back out to query the
|
||||
/// graph or unload a cache: what a write invalidates is declared, not performed here.
|
||||
pub(crate) struct NodeMut<'a> {
|
||||
pub(super) node: &'a mut DocumentNode,
|
||||
pub(super) metadata: &'a mut DocumentNodePersistentMetadata,
|
||||
deltas: NodeDeltas<'a>,
|
||||
}
|
||||
|
||||
impl<'a> NodeMut<'a> {
|
||||
pub(super) fn new(node: &'a mut DocumentNode, metadata: &'a mut DocumentNodePersistentMetadata, deltas: &'a mut Vec<EditorDelta>, locator: NodeLocator<'a>) -> Self {
|
||||
Self {
|
||||
node,
|
||||
metadata,
|
||||
deltas: NodeDeltas { deltas, locator },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a node's writes record what they changed, carrying the node's address so each setter names
|
||||
/// what it wrote without its caller repeating it.
|
||||
struct NodeDeltas<'a> {
|
||||
pub(super) deltas: &'a mut Vec<EditorDelta>,
|
||||
locator: NodeLocator<'a>,
|
||||
}
|
||||
|
||||
impl NodeDeltas<'_> {
|
||||
fn metadata(&mut self, change: NodeMetadataChange) {
|
||||
self.deltas.push(EditorDelta::NodeMetadata {
|
||||
network_path: self.locator.network_path.to_vec(),
|
||||
node_id: self.locator.node_id,
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
/// Records a change to the network this node owns, addressed by the node's path extended with its ID.
|
||||
fn owned_network(&mut self, change: NetworkMetadataChange) {
|
||||
self.deltas.push(EditorDelta::NetworkMetadata {
|
||||
network_path: self.locator.owned_network_path(),
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
fn graph(&mut self, delta: RuntimeDelta) {
|
||||
self.deltas.push(EditorDelta::Graph(delta));
|
||||
}
|
||||
|
||||
fn input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
|
||||
self.deltas.push(EditorDelta::NodeInputMetadata {
|
||||
network_path: self.locator.network_path.to_vec(),
|
||||
node_id: self.locator.node_id,
|
||||
input_metadata,
|
||||
});
|
||||
}
|
||||
|
||||
fn snapshot(&mut self, metadata: Box<DocumentNodePersistentMetadata>) {
|
||||
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
|
||||
network_path: self.locator.network_path.to_vec(),
|
||||
node_id: self.locator.node_id,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
fn network_path(&self) -> Vec<NodeId> {
|
||||
self.locator.network_path.to_vec()
|
||||
}
|
||||
|
||||
fn node_id(&self) -> NodeId {
|
||||
self.locator.node_id
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeMut<'_> {
|
||||
/// Places the node at an absolute grid position, keeping whether it is displayed as a layer or a node.
|
||||
pub(crate) fn set_absolute_position(&mut self, position: IVec2) -> bool {
|
||||
let node_type = match self.metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::layer(position),
|
||||
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::node(position),
|
||||
};
|
||||
self.set_node_type(node_type)
|
||||
}
|
||||
|
||||
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
|
||||
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
|
||||
let shifted = match self.metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Absolute(position),
|
||||
}) => NodeTypePersistentMetadata::layer(position + shift),
|
||||
NodeTypePersistentMetadata::Node(ref node) => match node.position {
|
||||
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
|
||||
NodePosition::Chain => return false,
|
||||
},
|
||||
NodeTypePersistentMetadata::Layer(_) => return false,
|
||||
};
|
||||
self.set_node_type(shifted)
|
||||
}
|
||||
|
||||
/// Stacks a layer `y_offset` below the sibling it feeds. Nodes are never stacked.
|
||||
pub(crate) fn set_stack_position(&mut self, y_offset: u32) -> bool {
|
||||
if !self.metadata.is_layer() {
|
||||
return false;
|
||||
}
|
||||
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Stack(y_offset),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Chains a node to the left of the layer it feeds. Layers are never chained.
|
||||
pub(crate) fn set_chain_position(&mut self) -> bool {
|
||||
if self.metadata.is_layer() {
|
||||
return false;
|
||||
}
|
||||
self.set_node_type(NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)))
|
||||
}
|
||||
|
||||
/// Whether the node is displayed as a layer, which decides the kinds of position it can hold.
|
||||
pub(crate) fn is_layer(&self) -> bool {
|
||||
self.metadata.is_layer()
|
||||
}
|
||||
|
||||
/// Whether the node is rendered, which the compiler reads to replace it with a passthrough.
|
||||
pub(crate) fn set_visible(&mut self, visible: bool) -> bool {
|
||||
let changed = self.node.visible != visible;
|
||||
self.node.visible = visible;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetVisibility {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
visible,
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The type of argument the node can be evaluated with.
|
||||
pub(crate) fn set_call_argument(&mut self, call_argument: Type) -> bool {
|
||||
let changed = self.node.call_argument != call_argument;
|
||||
self.node.call_argument = call_argument;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetCallArgument {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
call_argument: self.node.call_argument.clone(),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The Extract and Inject annotations the node declares for the Context.
|
||||
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
|
||||
let changed = self.node.context_features != context_features;
|
||||
self.node.context_features = context_features;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetContextFeatures {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
context_features: self.node.context_features,
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The user-chosen name for this instance, empty when it has none.
|
||||
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
|
||||
let changed = self.metadata.display_name != display_name;
|
||||
self.metadata.display_name = display_name;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::DisplayName(self.metadata.display_name.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_locked(&mut self, locked: bool) -> bool {
|
||||
let changed = self.metadata.locked != locked;
|
||||
self.metadata.locked = locked;
|
||||
if changed {
|
||||
self.deltas.metadata(NodeMetadataChange::Locked(locked));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_pinned(&mut self, pinned: bool) -> bool {
|
||||
let changed = self.metadata.pinned != pinned;
|
||||
self.metadata.pinned = pinned;
|
||||
if changed {
|
||||
self.deltas.metadata(NodeMetadataChange::Pinned(pinned));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Whether the node is displayed as a layer or a node, together with its position.
|
||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||
let changed = self.metadata.node_type_metadata != node_type;
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The definition this node's nested network was instantiated from. Only network nodes carry one.
|
||||
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
|
||||
let Some(network_metadata) = self.metadata.network_metadata.as_mut() else { return false };
|
||||
let changed = network_metadata.persistent_metadata.reference != reference;
|
||||
network_metadata.persistent_metadata.reference = reference;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::Reference(network_metadata.persistent_metadata.reference.clone());
|
||||
self.deltas.owned_network(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_input_name(&mut self, input_index: usize, input_name: String) -> bool {
|
||||
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
|
||||
let changed = input_metadata.persistent_metadata.input_name != input_name;
|
||||
input_metadata.persistent_metadata.input_name = input_name;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::InputName {
|
||||
index: input_index,
|
||||
name: input_metadata.persistent_metadata.input_name.clone(),
|
||||
};
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The identifier of the widget override the properties panel uses for this input, or `None` for the
|
||||
/// widget generated from its type.
|
||||
pub(crate) fn set_widget_override(&mut self, input_index: usize, widget_override: Option<String>) -> bool {
|
||||
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
|
||||
let changed = input_metadata.persistent_metadata.widget_override != widget_override;
|
||||
input_metadata.persistent_metadata.widget_override = widget_override;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::WidgetOverride {
|
||||
index: input_index,
|
||||
widget_override: input_metadata.persistent_metadata.widget_override.clone(),
|
||||
};
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn set_output_name(&mut self, output_index: usize, output_name: String) -> bool {
|
||||
let Some(existing) = self.metadata.output_names.get_mut(output_index) else { return false };
|
||||
let changed = *existing != output_name;
|
||||
*existing = output_name;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The encapsulating node's names for every one of the network's exports, replaced together since
|
||||
/// they are stored as one array.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
|
||||
let changed = self.metadata.output_names != output_names;
|
||||
self.metadata.output_names = output_names;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The metadata array the node's inputs index, one entry per input.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
|
||||
&self.metadata.input_metadata
|
||||
}
|
||||
|
||||
/// Grows `output_names` to one entry per export, which an older document may be missing.
|
||||
pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) {
|
||||
if self.metadata.output_names.len() == number_of_exports {
|
||||
return;
|
||||
}
|
||||
self.metadata.output_names.resize(number_of_exports, String::new());
|
||||
|
||||
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
|
||||
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
|
||||
/// entry for the added index. Restores the parallel-array invariant for an older document.
|
||||
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
|
||||
if self.metadata.input_metadata.len() >= number_of_inputs {
|
||||
return;
|
||||
}
|
||||
for added_input_index in self.metadata.input_metadata.len()..number_of_inputs {
|
||||
self.metadata.input_metadata.push(defaults(added_input_index).unwrap_or_default());
|
||||
}
|
||||
self.emit_input_metadata();
|
||||
}
|
||||
|
||||
/// Swaps in a new implementation together with the nested network metadata that belongs to it.
|
||||
///
|
||||
/// Replaces the node and everything nested under it, since the nested network goes with the
|
||||
/// implementation.
|
||||
pub(crate) fn replace_implementation(&mut self, implementation: DocumentNodeImplementation, network_metadata: Option<NodeNetworkMetadata>) {
|
||||
self.node.implementation = implementation;
|
||||
self.metadata.network_metadata = network_metadata;
|
||||
|
||||
let delta = RuntimeDelta::ReplaceNode {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
node: Box::new(self.node.clone()),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
let metadata = Box::new(self.metadata.clone());
|
||||
self.deltas.snapshot(metadata);
|
||||
}
|
||||
|
||||
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
|
||||
/// which is the write a metadata snapshot describes.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
|
||||
*self.metadata = metadata;
|
||||
|
||||
let snapshot = Box::new(self.metadata.clone());
|
||||
self.deltas.snapshot(snapshot);
|
||||
}
|
||||
|
||||
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
|
||||
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
|
||||
self.metadata.input_metadata = input_metadata;
|
||||
self.emit_input_metadata();
|
||||
}
|
||||
|
||||
/// Swaps in new inputs together with their metadata, returning the inputs replaced.
|
||||
pub(crate) fn replace_inputs(&mut self, inputs: Vec<NodeInput>, input_metadata: Vec<InputMetadata>) -> Vec<NodeInput> {
|
||||
self.metadata.input_metadata = input_metadata;
|
||||
let previous = std::mem::replace(&mut self.node.inputs, inputs);
|
||||
|
||||
self.emit_inputs();
|
||||
previous
|
||||
}
|
||||
|
||||
/// Records the node's input list and the metadata array indexed by it, which change together
|
||||
/// whenever the number or order of slots does.
|
||||
pub(super) fn emit_inputs(&mut self) {
|
||||
let delta = RuntimeDelta::SetInputs {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
inputs: self.node.inputs.clone(),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
self.emit_input_metadata();
|
||||
}
|
||||
|
||||
fn emit_input_metadata(&mut self) {
|
||||
let input_metadata = self.metadata.input_metadata.clone();
|
||||
self.deltas.input_metadata(input_metadata);
|
||||
}
|
||||
}
|
||||
|
||||
/// The persistent metadata of one network, resolved once so a run of writes walks the tree a single time.
|
||||
///
|
||||
/// Metadata only: the graph half of a network is its export slots, which are addressed through
|
||||
/// [`NodeNetworkInterface::set_input_slot`] like any other input.
|
||||
pub(crate) struct NetworkMut<'a> {
|
||||
pub(super) metadata: &'a mut NodeNetworkPersistentMetadata,
|
||||
pub(super) deltas: &'a mut Vec<EditorDelta>,
|
||||
pub(super) network_path: &'a [NodeId],
|
||||
}
|
||||
|
||||
impl<'a> NetworkMut<'a> {
|
||||
pub(super) fn new(metadata: &'a mut NodeNetworkPersistentMetadata, deltas: &'a mut Vec<EditorDelta>, network_path: &'a [NodeId]) -> Self {
|
||||
Self { metadata, deltas, network_path }
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkMut<'_> {
|
||||
/// Which node the network renders instead of its export. This write is not recorded.
|
||||
pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool {
|
||||
let changed = self.metadata.previewing != previewing;
|
||||
self.metadata.previewing = previewing;
|
||||
changed
|
||||
}
|
||||
|
||||
/// The definition this network was instantiated from.
|
||||
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
|
||||
let changed = self.metadata.reference != reference;
|
||||
self.metadata.reference = reference;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::Reference(self.metadata.reference.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The display order of pinned nodes in the Properties panel.
|
||||
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
||||
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
||||
self.metadata.pinned_node_order = pinned_node_order;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Appends a newly pinned node to the display order, or drops one that is no longer pinned.
|
||||
pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool {
|
||||
let order = &mut self.metadata.pinned_node_order;
|
||||
let changed = match pinned {
|
||||
true if !order.contains(&node_id) => {
|
||||
order.push(node_id);
|
||||
true
|
||||
}
|
||||
true => false,
|
||||
false => {
|
||||
let before = order.len();
|
||||
order.retain(|id| *id != node_id);
|
||||
order.len() != before
|
||||
}
|
||||
};
|
||||
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Drops every node the order names that is no longer in the network.
|
||||
pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool {
|
||||
let before = self.metadata.pinned_node_order.len();
|
||||
self.metadata.pinned_node_order.retain(&surviving);
|
||||
|
||||
let changed = self.metadata.pinned_node_order.len() != before;
|
||||
if changed {
|
||||
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
|
||||
self.emit(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn emit(&mut self, change: NetworkMetadataChange) {
|
||||
self.deltas.push(EditorDelta::NetworkMetadata {
|
||||
network_path: self.network_path.to_vec(),
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
/// The transform from node graph space to viewport space.
|
||||
pub(crate) fn set_navigation_transform(&mut self, transform: DAffine2) -> bool {
|
||||
let changed = self.metadata.navigation_metadata.node_graph_to_viewport != transform;
|
||||
self.metadata.navigation_metadata.node_graph_to_viewport = transform;
|
||||
changed
|
||||
}
|
||||
|
||||
/// The width of the node graph in viewport space.
|
||||
pub(crate) fn set_navigation_width(&mut self, node_graph_width: f64) -> bool {
|
||||
let changed = self.metadata.navigation_metadata.node_graph_width != node_graph_width;
|
||||
self.metadata.navigation_metadata.node_graph_width = node_graph_width;
|
||||
changed
|
||||
}
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
use super::*;
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
mod accessors;
|
||||
mod cursor;
|
||||
|
||||
pub use cursor::NodeLocator;
|
||||
pub(crate) use cursor::{NetworkMut, NodeMut, SelectionHistoryMut};
|
||||
|
||||
/// Holds one of the two parallel trees so that only this module can write it.
|
||||
///
|
||||
/// `Deref` passes reads straight through, so a query reads the tree as though the interface held it
|
||||
/// directly. There is deliberately no `DerefMut` and the field is private to this module, so the only
|
||||
/// route to a `&mut` is the store API below, and a write that skips it does not compile rather than
|
||||
/// silently going unrecorded.
|
||||
///
|
||||
/// Transparent to serde, so wrapping a field does not change the document format.
|
||||
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Guarded<T>(T);
|
||||
|
||||
impl<T> std::ops::Deref for Guarded<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Guarded<T> {
|
||||
fn new(value: T) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
// The store: the only writer of the node graph and its parallel metadata tree, keeping the two halves
|
||||
// in step by construction.
|
||||
impl NodeNetworkInterface {
|
||||
/// Builds an interface around a freshly-assembled pair of trees, for a document arriving from
|
||||
/// storage or from an older format rather than being edited into existence. Nothing is recorded: the
|
||||
/// trees are the document, not a set of changes to it.
|
||||
pub(super) fn from_trees(network: NodeNetwork, network_metadata: NodeNetworkMetadata) -> Self {
|
||||
Self {
|
||||
network: Guarded::new(MemoNetwork::new(network)),
|
||||
network_metadata: Guarded::new(network_metadata),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts an input and its metadata at `index`, clamped to the end. Returns whether the node was found.
|
||||
pub(crate) fn insert_input_slot(&mut self, locator: NodeLocator, index: usize, input: NodeInput, metadata: InputMetadata) -> bool {
|
||||
let Some(mut node) = self.node_mut(locator) else {
|
||||
log::error!("Could not get node {} in insert_input_slot", locator.node_id);
|
||||
return false;
|
||||
};
|
||||
|
||||
let index = index.min(node.node.inputs.len());
|
||||
node.node.inputs.insert(index, input);
|
||||
node.metadata.input_metadata.insert(index.min(node.metadata.input_metadata.len()), metadata);
|
||||
node.emit_inputs();
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes the input at `index` together with its metadata, returning both.
|
||||
pub(crate) fn remove_input_slot(&mut self, locator: NodeLocator, index: usize) -> Option<(NodeInput, InputMetadata)> {
|
||||
let Some(mut node) = self.node_mut(locator) else {
|
||||
log::error!("Could not get node {} in remove_input_slot", locator.node_id);
|
||||
return None;
|
||||
};
|
||||
|
||||
if index >= node.node.inputs.len() {
|
||||
log::error!("Input index {index} out of bounds in remove_input_slot for node {}", locator.node_id);
|
||||
return None;
|
||||
}
|
||||
|
||||
let input = node.node.inputs.remove(index);
|
||||
let metadata = (index < node.metadata.input_metadata.len()).then(|| node.metadata.input_metadata.remove(index));
|
||||
node.emit_inputs();
|
||||
Some((input, metadata.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Moves the input at `from` to `to`, carrying its metadata with it.
|
||||
///
|
||||
/// Records the removal and the insertion separately, so the list is briefly one slot short. Both
|
||||
/// land in the same batch, where the second supersedes the first.
|
||||
pub(crate) fn move_input_slot(&mut self, locator: NodeLocator, from: usize, to: usize) -> bool {
|
||||
let Some((input, metadata)) = self.remove_input_slot(locator, from) else { return false };
|
||||
self.insert_input_slot(locator, to, input, metadata)
|
||||
}
|
||||
|
||||
/// Inserts an export at `index`, clamped to the end, along with the name the encapsulating node shows
|
||||
/// for it. The document network has no encapsulating node, so it carries no name.
|
||||
pub(crate) fn insert_export_slot(&mut self, network_path: &[NodeId], index: usize, export: NodeInput, output_name: String) -> bool {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in insert_export_slot");
|
||||
return false;
|
||||
};
|
||||
|
||||
let index = index.min(network.exports.len());
|
||||
network.exports.insert(index, export);
|
||||
|
||||
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
|
||||
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
|
||||
output_names.insert(index.min(output_names.len()), output_name);
|
||||
}
|
||||
self.emit_exports_from(network_path, index, None);
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes the export at `index` together with the encapsulating node's name for it.
|
||||
pub(crate) fn remove_export_slot(&mut self, network_path: &[NodeId], index: usize) -> Option<NodeInput> {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in remove_export_slot");
|
||||
return None;
|
||||
};
|
||||
|
||||
if index >= network.exports.len() {
|
||||
log::error!("Export index {index} out of bounds in remove_export_slot");
|
||||
return None;
|
||||
}
|
||||
let export = network.exports.remove(index);
|
||||
// The list shrank by one, so what was the last index now has no slot and has to be cleared.
|
||||
let vacated = network.exports.len();
|
||||
|
||||
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
|
||||
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
|
||||
if index < output_names.len() {
|
||||
output_names.remove(index);
|
||||
}
|
||||
}
|
||||
self.emit_exports_from(network_path, index, Some(vacated));
|
||||
Some(export)
|
||||
}
|
||||
|
||||
/// Records every export slot from `index` on, plus a clear for `vacated` when the list shrank.
|
||||
///
|
||||
/// Export slots are addressed by index, so inserting or removing one changes the meaning of every
|
||||
/// later slot and each has to be restated. The encapsulating node's names for them ride along as one
|
||||
/// whole-array metadata write.
|
||||
fn emit_exports_from(&mut self, network_path: &[NodeId], index: usize, vacated: Option<usize>) {
|
||||
let Some(network) = self.network.network().nested_network(network_path) else { return };
|
||||
let exports: Vec<_> = network.exports.iter().skip(index).cloned().collect();
|
||||
|
||||
for (offset, export) in exports.into_iter().enumerate() {
|
||||
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: index + offset,
|
||||
input: Some(export),
|
||||
}));
|
||||
}
|
||||
if let Some(vacated) = vacated {
|
||||
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: vacated,
|
||||
input: None,
|
||||
}));
|
||||
}
|
||||
|
||||
let Some((&node_id, parent_path)) = network_path.split_last() else { return };
|
||||
let Some(metadata) = self.encapsulating_node_metadata(network_path) else { return };
|
||||
let change = NodeMetadataChange::OutputNames(metadata.persistent_metadata.output_names.clone());
|
||||
self.deltas.push(EditorDelta::NodeMetadata {
|
||||
network_path: parent_path.to_vec(),
|
||||
node_id,
|
||||
change,
|
||||
});
|
||||
}
|
||||
|
||||
/// Moves the export at `from` to `to`, carrying the encapsulating node's name for it.
|
||||
pub(crate) fn move_export_slot(&mut self, network_path: &[NodeId], from: usize, to: usize) -> bool {
|
||||
let name = self
|
||||
.encapsulating_node_metadata(network_path)
|
||||
.and_then(|metadata| metadata.persistent_metadata.output_names.get(from).cloned())
|
||||
.unwrap_or_default();
|
||||
let Some(export) = self.remove_export_slot(network_path, from) else { return false };
|
||||
self.insert_export_slot(network_path, to, export, name)
|
||||
}
|
||||
|
||||
/// Writes the input at `connector`, returning the input it replaced.
|
||||
pub(crate) fn set_input_slot(&mut self, connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> Option<NodeInput> {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in set_input_slot");
|
||||
return None;
|
||||
};
|
||||
|
||||
let Some(slot) = input_slot_mut(network, connector) else {
|
||||
log::error!("Could not get input {connector:?} in set_input_slot");
|
||||
return None;
|
||||
};
|
||||
|
||||
if *slot == input {
|
||||
return Some(input);
|
||||
}
|
||||
let previous = std::mem::replace(slot, input.clone());
|
||||
|
||||
self.deltas.push(input_write_delta(connector, network_path, input));
|
||||
Some(previous)
|
||||
}
|
||||
|
||||
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
|
||||
///
|
||||
/// For a change expressed as an operation on the existing value rather than as a replacement of it,
|
||||
/// which avoids copying the value out and back. The recorded delta still carries the whole result,
|
||||
/// since the storage op is a whole-value write.
|
||||
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
|
||||
let Some(slot) = input_slot_mut(network, connector) else {
|
||||
log::error!("Could not get input {connector:?} in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
let Some(mut value) = slot.as_value_mut() else {
|
||||
log::error!("Input {connector:?} is not a value in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
|
||||
edit(&mut value);
|
||||
drop(value);
|
||||
|
||||
let input = slot.clone();
|
||||
self.deltas.push(input_write_delta(connector, network_path, input));
|
||||
true
|
||||
}
|
||||
|
||||
/// Inserts a node and its metadata, returning the entry it replaced.
|
||||
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
|
||||
if !self.network_pair_exists(locator.network_path) {
|
||||
log::error!("Could not get network {:?} in insert_node_entry", locator.network_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let (document_node, persistent_metadata) = template.into_parts();
|
||||
let node = Box::new(document_node.clone());
|
||||
let metadata = Box::new(persistent_metadata.clone());
|
||||
|
||||
let previous_node = self
|
||||
.network
|
||||
.get_mut()
|
||||
.network_mut()
|
||||
.nested_network_mut(locator.network_path)?
|
||||
.nodes
|
||||
.insert(locator.node_id, document_node);
|
||||
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
|
||||
locator.node_id,
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata,
|
||||
transient_metadata: DocumentNodeTransientMetadata::default(),
|
||||
},
|
||||
);
|
||||
|
||||
// Overwriting an existing entry replaces the node and everything nested under it, which is what
|
||||
// distinguishes the two from the storage side.
|
||||
let network_path = locator.network_path.to_vec();
|
||||
let node_id = locator.node_id;
|
||||
self.deltas.push(EditorDelta::Graph(match previous_node.is_some() {
|
||||
true => RuntimeDelta::ReplaceNode {
|
||||
network_path: network_path.clone(),
|
||||
node_id,
|
||||
node,
|
||||
},
|
||||
false => RuntimeDelta::AddNode {
|
||||
network_path: network_path.clone(),
|
||||
node_id,
|
||||
node,
|
||||
},
|
||||
}));
|
||||
self.deltas.push(EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata });
|
||||
|
||||
previous_node
|
||||
.zip(previous_metadata)
|
||||
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
|
||||
}
|
||||
|
||||
/// Removes a node and its metadata, returning them joined as a template.
|
||||
pub(crate) fn remove_node_entry(&mut self, locator: NodeLocator) -> Option<NodeTemplate> {
|
||||
if !self.network_pair_exists(locator.network_path) {
|
||||
log::error!("Could not get network {:?} in remove_node_entry", locator.network_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
|
||||
let metadata = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(locator.network_path)?
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.remove(&locator.node_id);
|
||||
|
||||
if node.is_some() {
|
||||
self.deltas.push(EditorDelta::Graph(RuntimeDelta::RemoveNode {
|
||||
network_path: locator.network_path.to_vec(),
|
||||
node_id: locator.node_id,
|
||||
}));
|
||||
}
|
||||
|
||||
node.zip(metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
|
||||
}
|
||||
|
||||
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
|
||||
/// halves out of step.
|
||||
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
|
||||
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
|
||||
}
|
||||
|
||||
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
|
||||
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
|
||||
std::mem::take(&mut self.deltas)
|
||||
}
|
||||
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the document.
|
||||
pub(crate) fn discard_deltas(&mut self) {
|
||||
self.deltas.clear();
|
||||
}
|
||||
|
||||
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
|
||||
/// once its signature is edited.
|
||||
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
|
||||
if let Some(mut network) = self.network_mut(network_path) {
|
||||
network.set_reference(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot `connector` addresses, whether it is a node's input or one of the network's exports.
|
||||
fn input_slot_mut<'a>(network: &'a mut NodeNetwork, connector: &InputConnector) -> Option<&'a mut NodeInput> {
|
||||
match connector {
|
||||
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
|
||||
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a whole-value write to `connector` records, which is a different delta for an input than for
|
||||
/// an export.
|
||||
fn input_write_delta(connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> EditorDelta {
|
||||
EditorDelta::Graph(match connector {
|
||||
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
|
||||
network_path: network_path.to_vec(),
|
||||
node_id: *node_id,
|
||||
input_index: *input_index,
|
||||
input,
|
||||
},
|
||||
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: *export_index,
|
||||
input: Some(input),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -338,12 +338,12 @@ impl RootNode {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
|
||||
/// Which node the node graph renders instead of the network's export.
|
||||
///
|
||||
/// Per-peer view state, not part of the document: the export keeps whatever it is wired to, and the
|
||||
/// compile path substitutes the previewed node into the graph it evaluates. So previewing a node
|
||||
/// changes nothing another peer would see.
|
||||
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
|
||||
/// changes nothing another peer would see, and there is nothing to restore when it ends.
|
||||
pub enum Previewing {
|
||||
Yes {
|
||||
previewed: RootNode,
|
||||
|
||||
@@ -339,6 +339,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_math_nodes::LogicalOrNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::math::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::MathNode", "graphene_core::ops::MathNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::max::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::MaxNode", "graphene_core::ops::MaxNode"],
|
||||
@@ -416,17 +420,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_math_nodes::ToF64Node", "graphene_core::ops::ToF64Node", "math_nodes::ToF64Node", "math_nodes::AsF64Node"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::as_integer::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::ToU32Node",
|
||||
"graphene_core::ops::ToU32Node",
|
||||
"math_nodes::ToU32Node",
|
||||
"math_nodes::AsU32Node",
|
||||
"graphene_math_nodes::ToU64Node",
|
||||
"graphene_core::ops::ToU64Node",
|
||||
"math_nodes::ToU64Node",
|
||||
"math_nodes::AsU64Node",
|
||||
],
|
||||
node: graphene_std::math_nodes::as_u_32::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::ToU32Node", "graphene_core::ops::ToU32Node", "math_nodes::ToU32Node"],
|
||||
},
|
||||
NodeReplacement {
|
||||
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.
|
||||
@@ -1265,132 +1264,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math f(x)"
|
||||
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math f(…)", which reads the pair as `a` and `b`.
|
||||
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
let is_old_math = matches!(name, "math_nodes::MathNode" | "graphene_math_nodes::MathNode" | "graphene_core::ops::MathNode");
|
||||
(is_old_math && node.inputs.len() >= 3).then(|| (*node_id, path, node.inputs.clone()))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, old_inputs) in &math_nodes {
|
||||
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves wires from cache, as in the Transform pass above
|
||||
let _ = document.network_interface.outward_wires(network_path);
|
||||
let (operand_a, expression, operand_b) = (&old_inputs[0], &old_inputs[1], &old_inputs[2]);
|
||||
|
||||
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
|
||||
let static_expression = match expression.as_value() {
|
||||
Some(TaggedValue::String(expression)) => Some(expression.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let mut references_b = false;
|
||||
let lexable = static_expression
|
||||
.as_deref()
|
||||
.and_then(|source| {
|
||||
math_parser::lexer::rename_identifiers(source, |name| {
|
||||
references_b |= name.eq_ignore_ascii_case("b");
|
||||
None
|
||||
})
|
||||
})
|
||||
.is_some();
|
||||
|
||||
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
|
||||
let inline_b_constant = match operand_b.as_value() {
|
||||
Some(TaggedValue::F64(constant)) => Some(*constant),
|
||||
_ => None,
|
||||
};
|
||||
let fx_expression = match &static_expression {
|
||||
Some(source) if lexable && !references_b => math_parser::lexer::rename_identifiers(source, |name| name.eq_ignore_ascii_case("a").then(|| "x".to_string())),
|
||||
Some(source) if lexable && let Some(constant) = inline_b_constant => math_parser::lexer::rename_identifiers(source, |name| {
|
||||
if name.eq_ignore_ascii_case("a") {
|
||||
Some("x".to_string())
|
||||
} else if name.eq_ignore_ascii_case("b") {
|
||||
Some(format!("({constant:?})"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(fx_expression) = fx_expression {
|
||||
// "Math f(x)": forward the old `A` input and the rewritten expression; the old `B` input is dropped
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
if document.network_interface.replace_inputs(node_id, network_path, &mut node_template).is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), operand_a.clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::String(fx_expression), false), network_path);
|
||||
} else {
|
||||
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
|
||||
let as_list_input = |input: &NodeInput| match input.as_value() {
|
||||
Some(TaggedValue::F64(value)) => NodeInput::value(TaggedValue::F64Array(vec![*value]), input.is_exposed()),
|
||||
_ => input.clone(),
|
||||
};
|
||||
let Some(extend_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::graphic::extend::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let extend_template = extend_definition.default_node_template();
|
||||
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_f::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
if document.network_interface.replace_inputs(node_id, network_path, &mut node_template).is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Wire inputs cannot ride along on an inserted template, so the Extend node's operands are set after insertion
|
||||
let extend_node_id = NodeId::new();
|
||||
let math_position = document.network_interface.position(node_id, network_path);
|
||||
document.network_interface.insert_node(extend_node_id, extend_template, network_path);
|
||||
if let Some(math_position) = math_position {
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&extend_node_id, math_position + IVec2::new(-7, 1), network_path);
|
||||
}
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(extend_node_id, 0), as_list_input(operand_a), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(extend_node_id, 1), as_list_input(operand_b), network_path);
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::node(extend_node_id, 0), network_path);
|
||||
|
||||
// A static expression is rewritten to the exact-lowercase positional spellings, escaping the old node's
|
||||
// constants `e` and `i` behind the `\` prefix that always reaches the builtin; a wired or unlexable one forwards untouched
|
||||
let positional_expression = match (&static_expression, lexable) {
|
||||
(Some(source), true) => math_parser::lexer::rename_identifiers(source, |name| {
|
||||
if name.eq_ignore_ascii_case("a") || name.eq_ignore_ascii_case("b") {
|
||||
return Some(name.to_ascii_lowercase());
|
||||
}
|
||||
matches!(name, "e" | "i").then(|| format!("\\{name}"))
|
||||
})
|
||||
.map(|rewritten| NodeInput::value(TaggedValue::String(rewritten), false)),
|
||||
_ => None,
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), positional_expression.unwrap_or_else(|| expression.clone()), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Record which old text nodes are chain-positioned now, before `migrate_node`'s staged input-count migrations run, since those set
|
||||
// the upstream chain to absolute; the split below re-chains exactly the nodes that were originally part of a layer chain.
|
||||
let text_nodes_in_chain: std::collections::HashSet<NodeId> = document
|
||||
@@ -1498,52 +1371,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
let narrowed_integer_inputs: &[(DefinitionIdentifier, &[usize])] = &[
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::vector::index_points::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::item_at_index::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::remove_at_index::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::shift::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::list_indices::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::graphic::list_slice::IDENTIFIER), &[1, 2]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::string_slice::IDENTIFIER), &[1, 2]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::regex::regex_find::IDENTIFIER), &[2]),
|
||||
(DefinitionIdentifier::Network("Regex Find".into()), &[2]),
|
||||
(DefinitionIdentifier::ProtoNode(graphene_std::vector::path_is_closed::IDENTIFIER), &[1]),
|
||||
(DefinitionIdentifier::Network("Blend".into()), &[1]),
|
||||
];
|
||||
let fractional_value_inputs: Vec<(NodeId, Vec<NodeId>, usize, i64, bool)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.flat_map(|(node_id, node, path)| {
|
||||
let Some(reference) = document.network_interface.reference(node_id, &path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some((_, indices)) = narrowed_integer_inputs.iter().find(|(identifier, _)| reference == *identifier) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
indices
|
||||
.iter()
|
||||
.filter_map(|&index| {
|
||||
let NodeInput::Value { tagged_value, exposed } = node.inputs.get(index)? else { return None };
|
||||
let TaggedValue::F64(value) = &**tagged_value else { return None };
|
||||
Some((*node_id, path.clone(), index, *value as i64, *exposed))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, index, integer, exposed) in fractional_value_inputs {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::I64(integer), exposed), &network_path);
|
||||
}
|
||||
|
||||
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
|
||||
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
|
||||
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
|
||||
@@ -1603,29 +1430,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Rebuild the Blend subgraph that still floors its Count import, since the now-integer Count enters through As Number instead
|
||||
if let DocumentNodeImplementation::Network(inner) = &node.implementation
|
||||
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Blend".into()))
|
||||
&& inner.nodes.values().any(|n| {
|
||||
matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::floor::IDENTIFIER)
|
||||
&& n.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. }))
|
||||
}) && let Some(node_definition) = resolve_network_node_type("Blend")
|
||||
{
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Rebuild the Regex Find subgraph that still imports its Match Index as a decimal, since that index is now an integer
|
||||
if let DocumentNodeImplementation::Network(inner) = &node.implementation
|
||||
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Regex Find".into()))
|
||||
&& inner.nodes.values().any(|n| {
|
||||
n.inputs
|
||||
.iter()
|
||||
.any(|input| matches!(input, NodeInput::Import { import_type, import_index: 2 } if *import_type == item!(f64)))
|
||||
}) && let Some(node_definition) = resolve_network_node_type("Regex Find")
|
||||
{
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
|
||||
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
|
||||
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
|
||||
@@ -2447,18 +2251,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
let output_level = |index: usize, default: f64| match old_inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::F64(percent)) => percent / 100.,
|
||||
let output_level = |index: usize, default: f32| match old_inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::F32(percent)) => percent / 100.,
|
||||
_ => default,
|
||||
};
|
||||
let (output_minimums, output_maximums) = (output_level(4, 0.), output_level(5, 1.));
|
||||
for (index, input) in old_inputs.iter().take(6).enumerate() {
|
||||
let input = match (index, input.as_value()) {
|
||||
(2, Some(TaggedValue::F64(percent))) => {
|
||||
(2, Some(TaggedValue::F32(percent))) => {
|
||||
// The old node's midtones-to-gamma mapping, from https://stackoverflow.com/questions/39510072/algorithm-for-adjustment-of-image-levels
|
||||
let midtones = output_minimums + (output_maximums - output_minimums) * percent / 100.;
|
||||
let gamma = if midtones < 0.5 { 1. + 9. * (1. - midtones * 2.) } else { ((1. - midtones) * 2.).max(0.01) };
|
||||
NodeInput::value(TaggedValue::F64(gamma.clamp(0.01, 9.99)), input.is_exposed())
|
||||
NodeInput::value(TaggedValue::F32(gamma.clamp(0.01, 9.99)), input.is_exposed())
|
||||
}
|
||||
_ => input.clone(),
|
||||
};
|
||||
@@ -2568,7 +2372,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
let new_spacing_value = NodeInput::value(TaggedValue::PointSpacingType(graphene_std::vector::misc::PointSpacingType::Separation), false);
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::I64(100), false);
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::U32(100), false);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), new_spacing_value, network_path);
|
||||
@@ -2589,7 +2393,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
if let NodeInput::Value { tagged_value, exposed } = quantity_value
|
||||
&& let TaggedValue::F64(value) = **tagged_value
|
||||
{
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::I64(value as i64), *exposed);
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::U32(value as u32), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), new_quantity_value, network_path);
|
||||
}
|
||||
}
|
||||
@@ -2603,12 +2407,12 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut new_node_template)?;
|
||||
|
||||
// The two six-input layouts differ only in where the DVec2 "angles" and the u32 "columns"/"rows" sit:
|
||||
// Legacy: [primary, grid_type, spacing, angles (DVec2), columns (int), rows (int)]
|
||||
// Modern: [primary, grid_type, spacing, columns (int), rows (int), angles (DVec2)]
|
||||
// So a DVec2 "angles" at index 3, or anything but angles at index 5, marks the legacy order. Checking both slots classifies
|
||||
// Legacy: [primary, grid_type, spacing, angles (DVec2), columns (u32), rows (u32)]
|
||||
// Modern: [primary, grid_type, spacing, columns (u32), rows (u32), angles (DVec2)]
|
||||
// So a DVec2 "angles" at index 3, or a u32 "rows" at index 5, marks the legacy order. Checking both slots classifies
|
||||
// correctly even when one of them is a wired or imported connection rather than a literal value.
|
||||
let index_3_is_angles = matches!(old_inputs.get(3), Some(NodeInput::Value { tagged_value, .. }) if matches!(**tagged_value, TaggedValue::DVec2(_)));
|
||||
let index_5_is_rows = matches!(old_inputs.get(5), Some(NodeInput::Value { tagged_value, .. }) if !matches!(**tagged_value, TaggedValue::DVec2(_)));
|
||||
let index_5_is_rows = matches!(old_inputs.get(5), Some(NodeInput::Value { tagged_value, .. }) if matches!(**tagged_value, TaggedValue::U32(_)));
|
||||
let legacy_angles_layout = index_3_is_angles || index_5_is_rows;
|
||||
|
||||
if legacy_angles_layout {
|
||||
@@ -2637,7 +2441,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
node_path.push(*node_id);
|
||||
|
||||
document.network_interface.add_import(TaggedValue::None, false, 0, "Primary", "", &node_path);
|
||||
document.network_interface.add_import(TaggedValue::I64(0), false, 1, "Loop Level", "TODO", &node_path);
|
||||
document.network_interface.add_import(TaggedValue::U32(0), false, 1, "Loop Level", "TODO", &node_path);
|
||||
}
|
||||
|
||||
// Drop the placeholder primary input the "Read Vector" node used to carry, since it reads its value from the context
|
||||
@@ -2698,7 +2502,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::I64(0), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::U32(0), false), network_path);
|
||||
}
|
||||
|
||||
// Migrate from the old source/target v1 "Morph" node to the new `List<Vector>`-based v2 "Morph" node.
|
||||
@@ -3341,226 +3145,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
|
||||
#[test]
|
||||
fn old_math_nodes_split_into_the_expression_node_pair() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
|
||||
let math_id = NodeId(1);
|
||||
let (source_a_id, source_b_id, source_expression_id) = (NodeId(2), NodeId(3), NodeId(4));
|
||||
|
||||
// Builds a document holding one old Math node with the given inputs, plus three source nodes to wire from
|
||||
let build_document = |identifier: &'static str, inputs: Vec<NodeInput>| {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
for source_id in [source_a_id, source_b_id, source_expression_id] {
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
}
|
||||
document.network_interface.insert_node(
|
||||
math_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false); 3],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
for (index, input) in inputs.into_iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(math_id, index), input, &[]);
|
||||
}
|
||||
document
|
||||
};
|
||||
|
||||
let implementation_of = |document: &DocumentMessageHandler, node_id: NodeId| match &document.network_interface.document_network().nodes[&node_id].implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
|
||||
other => panic!("expected a proto node implementation, got {other:?}"),
|
||||
};
|
||||
let find_extend = |document: &DocumentMessageHandler| {
|
||||
document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::graphic::extend::IDENTIFIER))
|
||||
.map(|(extend_id, _)| *extend_id)
|
||||
.expect("an Extend node should be spliced in")
|
||||
};
|
||||
|
||||
// A static expression that never reads `B` becomes "Math f(x)" with `A` renamed to `x` and the `B` input dropped
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
NodeInput::value(TaggedValue::String("2 - 0.2A".into()), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
];
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(node.inputs.len(), 2, "the old `B` input should be dropped");
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
|
||||
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
|
||||
}
|
||||
|
||||
// A constant `B` inlines into the rewritten string as a parenthesized literal; an alias spelling of the old identifier also matches
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
NodeInput::value(TaggedValue::String("sqrt(A + B) - B^2".into()), false),
|
||||
NodeInput::value(TaggedValue::F64(3.), false),
|
||||
];
|
||||
let mut document = build_document("graphene_core::ops::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::String("sqrt(x + (3.0)) - (3.0)^2".into()))
|
||||
);
|
||||
}
|
||||
|
||||
// A wired `B` keeps both wires by joining them through a spliced Extend node, with the expression rewritten to the
|
||||
// lowercase positional spellings and the old constants escaped behind the `\` prefix that still reaches them
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
NodeInput::value(TaggedValue::String("A * B + e".into()), false),
|
||||
NodeInput::node(source_b_id, 0),
|
||||
];
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.first(), Some(&NodeInput::node(extend_id, 0)));
|
||||
assert_eq!(
|
||||
network.nodes[&math_id].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::String("a * b + \\e".into()))
|
||||
);
|
||||
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::node(source_b_id, 0)));
|
||||
}
|
||||
|
||||
// A wired expression cannot be inspected, so it splices too, wrapping unwired constant operands as one-item list values
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::value(TaggedValue::F64(2.), true),
|
||||
NodeInput::node(source_expression_id, 0),
|
||||
NodeInput::value(TaggedValue::F64(5.), false),
|
||||
];
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::value(TaggedValue::F64Array(vec![2.]), true)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::value(TaggedValue::F64Array(vec![5.]), false)));
|
||||
}
|
||||
}
|
||||
|
||||
// The Blend network's Count is now an integer, so an old instance rounds its stored F64 count and swaps the Floor its
|
||||
// subgraph used to whole-number the count for the As Number that brings the integer into the network's decimal math
|
||||
#[test]
|
||||
fn blend_count_narrows_to_i64_and_its_subgraph_is_rebuilt() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut node_template = resolve_network_node_type("Blend").expect("Blend should exist").default_node_template();
|
||||
node_template.inputs[1] = NodeInput::value(TaggedValue::F64(6.9), false);
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::I64(6)),
|
||||
"the count truncates as the retired Floor did, so the document keeps drawing six"
|
||||
);
|
||||
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&NodeId(3)].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
|
||||
// The rebuild above is keyed on the retired Floor that took the Count import, since the subgraph keeps another Floor
|
||||
// for its subpath index and a current Blend would otherwise lose any edit made inside it on every load
|
||||
#[test]
|
||||
fn current_blend_subgraph_survives_migration() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut node_template = resolve_network_node_type("Blend").expect("Blend should exist").default_node_template();
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::F64(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
let DocumentNodeImplementation::Network(inner) = &document.network_interface.document_network().nodes[&node_id].implementation else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::F64(42.)));
|
||||
}
|
||||
|
||||
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
|
||||
// that fed the decimal index to its two item-at-index nodes
|
||||
#[test]
|
||||
fn regex_find_match_index_narrows_to_i64_and_its_subgraph_is_rebuilt() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut node_template = resolve_network_node_type("Regex Find").expect("Regex Find should exist").default_node_template();
|
||||
node_template.inputs[2] = NodeInput::value(TaggedValue::F64(1.6), false);
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::F64(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(2).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::I64(1)),
|
||||
"the match index truncates as the retired cast did"
|
||||
);
|
||||
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&NodeId(0)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&NodeId(1)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::I64(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_legacy_image_shape_stores_its_resource_as_secondary_input() {
|
||||
use graphene_std::raster::Image;
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
//! Asynchronous `.gdd` working-copy IO, spawned by `PortfolioMessageHandler` as `FutureMessage`s:
|
||||
//! building/opening containers and opening `.gdd` archives into documents.
|
||||
//! The `validate` flag is the `validate_storage_round_trip` preference; when
|
||||
//! building/opening containers, opening `.gdd` archives into documents, and rebuilding the interface
|
||||
//! from the undo/redo cursor. The `validate` flag is the `validate_storage_round_trip` preference; when
|
||||
//! set, the registry build is compared against the legacy oracle (logged, not fatal) for the soak.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout};
|
||||
use document_graph_storage::Declarations;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graph_craft::application_io::resource::{LoadResource, ResourceStorage};
|
||||
use graph_craft::document::NodeNetwork;
|
||||
|
||||
use super::document::DocumentMessageHandler;
|
||||
@@ -87,6 +86,27 @@ pub(super) async fn open_gdd_document(
|
||||
})
|
||||
}
|
||||
|
||||
/// `FutureMessage` that rebuilds a document's interface from a post-move `Gdd` cursor snapshot and
|
||||
/// delivers it via [`PortfolioMessage::GddUndoRedoRebuilt`] (`None` interface on failure, logged here).
|
||||
pub(crate) async fn rebuild_gdd_cursor(gdd: GddV1, store_handle: ResourcesHandle, document_id: DocumentId, had_oracle: bool) -> Message {
|
||||
let declarations = gdd.declarations(&store_handle).await;
|
||||
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
|
||||
Ok((network, node_entries, network_entries)) => match build_interface_from_storage(network, node_entries, network_entries) {
|
||||
Ok(interface) => Some(Box::new(interface)),
|
||||
Err(error) => {
|
||||
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to build interface: {error}");
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to convert registry to runtime: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
Message::Portfolio(PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface })
|
||||
}
|
||||
|
||||
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
|
||||
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
|
||||
/// Returns `None` only if neither the build nor the legacy fallback worked.
|
||||
@@ -164,7 +184,7 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
|
||||
);
|
||||
}
|
||||
}
|
||||
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None));
|
||||
return Some(DocumentMessageHandler::from_storage(interface, gdd, String::new(), None));
|
||||
}
|
||||
|
||||
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
|
||||
@@ -176,8 +196,9 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
|
||||
|
||||
/// Soak check that the reopened `.gdd`'s stored registry, converted back to a runtime network, matches
|
||||
/// the legacy load. Logs divergence only (legacy stays authoritative); runs once per open.
|
||||
pub(super) fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, declarations: &Declarations, document_id: DocumentId) {
|
||||
let mut candidate = match gdd.registry().to_runtime_with_metadata(declarations) {
|
||||
pub(super) async fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, byte_store: &dyn LoadResource, document_id: DocumentId) {
|
||||
let declarations = gdd.declarations(byte_store).await;
|
||||
let mut candidate = match gdd.registry().to_runtime_with_metadata(&declarations) {
|
||||
Ok((network, _entries)) => network,
|
||||
Err(error) => {
|
||||
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
|
||||
|
||||
@@ -45,18 +45,17 @@ pub enum PortfolioMessage {
|
||||
DeleteDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Delivers an asynchronously-built `Gdd` working copy, with the proto-node declarations its history
|
||||
/// references, into its document. Emitted by the mount future spawned in `load_document`. The `mounted`
|
||||
/// payload is non-serializable and a clone carries none (`clone_to_none`), so it travels exactly once.
|
||||
/// `reopened` is true when an existing working copy was opened: the persisted cursor is trusted as-is
|
||||
/// and the mount-time re-commit is skipped, since re-committing would stack a spurious interaction on
|
||||
/// the restored cursor and make the first undo a no-op.
|
||||
/// Delivers an asynchronously-built `Gdd` working copy into its document, emitted by the mount future
|
||||
/// spawned in `load_document`. The `gdd` payload is non-serializable and a clone carries none
|
||||
/// (`clone_to_none`), so it travels exactly once. `reopened` is true when an existing working copy was
|
||||
/// opened: the persisted cursor is trusted as-is and the mount-time re-commit is skipped, since
|
||||
/// re-committing would stack a spurious interaction on the restored cursor and make the first undo a no-op.
|
||||
DocumentStorageMounted {
|
||||
document_id: DocumentId,
|
||||
reopened: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
mounted: Option<Box<(document_format::GddV1, document_graph_storage::Declarations)>>,
|
||||
gdd: Option<Box<document_format::GddV1>>,
|
||||
},
|
||||
DestroyAllDocuments,
|
||||
EditorPreferences,
|
||||
@@ -97,6 +96,17 @@ pub enum PortfolioMessage {
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
document: Option<Box<DocumentMessageHandler>>,
|
||||
},
|
||||
/// Delivers the interface rebuilt from the `Gdd` undo/redo cursor so the async rebuild can swap into the
|
||||
/// live document. `interface` is `None` if the rebuild failed (logged at the source). `had_oracle` records
|
||||
/// whether the legacy snapshot applied synchronously, so the swap can debug-compare against it. Travels
|
||||
/// once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
|
||||
GddUndoRedoRebuilt {
|
||||
document_id: DocumentId,
|
||||
had_oracle: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
interface: Option<Box<crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface>>,
|
||||
},
|
||||
LoadDocument {
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
@@ -148,8 +158,7 @@ pub enum PortfolioMessage {
|
||||
UpdateOpenDocumentsList,
|
||||
}
|
||||
|
||||
/// Clone helper for non-serializable payloads: a cloned message carries none of the `Gdd` working copy,
|
||||
/// its declarations, or the built document.
|
||||
/// Clone helper for the non-serializable `gdd` payload: a cloned mount message carries no `Gdd`.
|
||||
fn clone_to_none<T>(_: &Option<T>) -> Option<T> {
|
||||
None
|
||||
}
|
||||
@@ -309,17 +309,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
}
|
||||
PortfolioMessage::DocumentStorageMounted { document_id, reopened, mounted } => {
|
||||
PortfolioMessage::DocumentStorageMounted { document_id, reopened, gdd } => {
|
||||
let Some(document) = self.documents.get_mut(&document_id) else {
|
||||
// Document was closed before its working copy finished mounting.
|
||||
return;
|
||||
};
|
||||
let Some(mounted) = mounted else {
|
||||
log::error!("DocumentStorageMounted for {document_id:?} arrived without its payload");
|
||||
return;
|
||||
};
|
||||
let (gdd, declarations) = *mounted;
|
||||
document.set_storage(gdd, declarations);
|
||||
document.set_storage(gdd.map(|gdd| *gdd));
|
||||
if !reopened {
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
document.retire_storage_interaction();
|
||||
@@ -552,6 +547,18 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
self.load_document(document, document_id, resource_storage, preferences.validate_storage_round_trip, responses);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface } => {
|
||||
let Some(document) = self.documents.get_mut(&document_id) else {
|
||||
// Document was closed before its undo/redo rebuild completed; drop the payload.
|
||||
return;
|
||||
};
|
||||
let Some(interface) = interface.map(|boxed| *boxed) else {
|
||||
// The rebuild failed and already logged; leave the live document untouched.
|
||||
return;
|
||||
};
|
||||
|
||||
document.apply_gdd_cursor_rebuild(interface, had_oracle, preferences.validate_storage_round_trip, responses);
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
@@ -1311,16 +1318,14 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
};
|
||||
|
||||
let declarations = gdd.declarations(byte_store.as_ref()).await;
|
||||
|
||||
if validate && reopened {
|
||||
compare_storage_against_runtime(&gdd, &legacy_network, &declarations, document_id);
|
||||
compare_storage_against_runtime(&gdd, &legacy_network, byte_store.as_ref(), document_id).await;
|
||||
}
|
||||
|
||||
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
|
||||
document_id,
|
||||
reopened,
|
||||
mounted: Some(Box::new((gdd, declarations))),
|
||||
gdd: Some(Box::new(gdd)),
|
||||
})
|
||||
};
|
||||
future.into()
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@ impl RowColumnGizmo {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, self.gizmo_type.parameter()),
|
||||
input: NodeInput::value(TaggedValue::I64((self.initial_dimension() as i32 + dimensions_to_add).max(1) as i64), false),
|
||||
input: NodeInput::value(TaggedValue::U32((self.initial_dimension() as i32 + dimensions_to_add).max(1) as u32), false),
|
||||
});
|
||||
|
||||
responses.add(GraphOperationMessage::TransformChange {
|
||||
|
||||
+1
-1
@@ -209,7 +209,7 @@ impl NumberOfPointsDial {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, sides_parameter),
|
||||
input: NodeInput::value(TaggedValue::I64(new_point_count as i64), false),
|
||||
input: NodeInput::value(TaggedValue::U32(new_point_count as u32), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
+1
-1
@@ -349,7 +349,7 @@ impl PointRadiusHandle {
|
||||
|
||||
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
|
||||
|
||||
let Some(&TaggedValue::I64(sides)) = parameters.value(star::SidesInput) else {
|
||||
let Some(&TaggedValue::U32(sides)) = parameters.value(star::SidesInput) else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
|
||||
@@ -109,11 +109,7 @@ impl Polygon {
|
||||
pub fn create_node(vertices: u32) -> NodeTemplate {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER);
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Regular Polygon can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::I64(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
])
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::U32(vertices), false)), Some(NodeInput::value(TaggedValue::F64(0.5), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -173,19 +169,19 @@ impl Polygon {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(&TaggedValue::I64(n)) = node_inputs.get(1).unwrap().as_value() else {
|
||||
let Some(&TaggedValue::U32(n)) = node_inputs.get(1).unwrap().as_value() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_dimension = if decrease { n.saturating_sub(1).max(3) } else { n.saturating_add(1) };
|
||||
let new_dimension = if decrease { (n - 1).max(3) } else { n + 1 };
|
||||
|
||||
responses.add(ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::Vertices(new_dimension.max(0) as u32),
|
||||
options: ShapeOptionsUpdate::Vertices(new_dimension),
|
||||
});
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::regular_polygon::SidesInput),
|
||||
input: NodeInput::value(TaggedValue::I64(new_dimension), false),
|
||||
input: NodeInput::value(TaggedValue::U32(new_dimension), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
@@ -211,8 +211,11 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
|
||||
let sign_num = if end[1] > start[1] { 1. } else { -1. };
|
||||
let new_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
|
||||
if let Some(&TaggedValue::I64(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput)
|
||||
&& sides % 2 != 0
|
||||
if new_layer
|
||||
.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput)
|
||||
.unwrap_or(&TaggedValue::U32(0))
|
||||
.to_u32()
|
||||
% 2 == 1
|
||||
{
|
||||
let Some(polygon_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::regular_polygon::IDENTIFIER)) else {
|
||||
return;
|
||||
@@ -225,8 +228,11 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(&TaggedValue::I64(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput)
|
||||
&& sides % 2 != 0
|
||||
if new_layer
|
||||
.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput)
|
||||
.unwrap_or(&TaggedValue::U32(0))
|
||||
.to_u32()
|
||||
% 2 == 1
|
||||
{
|
||||
let Some(star_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::star::IDENTIFIER)) else {
|
||||
return;
|
||||
@@ -301,13 +307,13 @@ pub fn anchor_overlays(document: &DocumentMessageHandler, overlay_context: &mut
|
||||
pub fn extract_star_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(u32, f64, f64)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::I64(sides)), Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) =
|
||||
let (Some(&TaggedValue::U32(sides)), Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) =
|
||||
(node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value(), node_inputs.get(3)?.as_value())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some((sides.max(0) as u32, radius_1, radius_2))
|
||||
Some((sides, radius_1, radius_2))
|
||||
}
|
||||
|
||||
/// Extract the node input values of Polygon.
|
||||
@@ -316,11 +322,11 @@ pub fn extract_polygon_parameters(layer: Option<LayerNodeIdentifier>, document:
|
||||
let node_inputs =
|
||||
NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::I64(n)), Some(&TaggedValue::F64(radius))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value()) else {
|
||||
let (Some(&TaggedValue::U32(n)), Some(&TaggedValue::F64(radius))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value()) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some((n.max(0) as u32, radius))
|
||||
Some((n, radius))
|
||||
}
|
||||
|
||||
/// Extract the node input values of an arc.
|
||||
@@ -594,7 +600,7 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
|
||||
let parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(IDENTIFIER)?;
|
||||
|
||||
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::DVec2(spacing)), Some(&TaggedValue::I64(columns)), Some(&TaggedValue::I64(rows)), Some(&TaggedValue::DVec2(angles))) = (
|
||||
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::DVec2(spacing)), Some(&TaggedValue::U32(columns)), Some(&TaggedValue::U32(rows)), Some(&TaggedValue::DVec2(angles))) = (
|
||||
parameters.value(GridTypeInput),
|
||||
parameters.value(SpacingInput),
|
||||
parameters.value(ColumnsInput),
|
||||
@@ -604,7 +610,7 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
return None;
|
||||
};
|
||||
|
||||
Some((grid_type, spacing, columns.max(0) as u32, rows.max(0) as u32, angles))
|
||||
Some((grid_type, spacing, columns, rows, angles))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -111,7 +111,7 @@ impl Star {
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Star node can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::I64(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::U32(vertices), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.25), false)),
|
||||
])
|
||||
|
||||
@@ -343,16 +343,17 @@ fn sync_shape_options_from_selection(options: &mut ShapeToolOptions, tool_data:
|
||||
// The rest (Ellipse, Rectangle, Line) just keep `shape_type` in step and rely on the shared Stroke/Fill controls.
|
||||
match shape_type {
|
||||
ShapeType::Polygon | ShapeType::Star => {
|
||||
// Both `regular_polygon` and `star` take their side count as an `i64`, which the control bar tracks as a `u32`, so a negative count clamps to zero
|
||||
// Both `regular_polygon` and `star` are generic over `T: AsU64`, but the control bar widget always writes `u32`,
|
||||
// and existing call sites (e.g. `polygon_shape.rs`) read it back as `TaggedValue::U32`.
|
||||
let sides_parameter = if shape_type == ShapeType::Polygon {
|
||||
ParameterRef::from(regular_polygon::SidesInput)
|
||||
} else {
|
||||
ParameterRef::from(star::SidesInput)
|
||||
};
|
||||
if let Some(&TaggedValue::I64(sides)) = layer_view.parameter_value(sides_parameter)
|
||||
&& options.vertices != sides.max(0) as u32
|
||||
if let Some(&TaggedValue::U32(sides)) = layer_view.parameter_value(sides_parameter)
|
||||
&& options.vertices != sides
|
||||
{
|
||||
options.vertices = sides.max(0) as u32;
|
||||
options.vertices = sides;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -622,7 +623,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
ShapeType::Star => ParameterRef::from(star::SidesInput),
|
||||
_ => return,
|
||||
};
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, sides_parameter, TaggedValue::I64(vertices as i64), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, sides_parameter, TaggedValue::U32(vertices), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::ArcType(arc_type) => {
|
||||
self.options.arc_type = arc_type;
|
||||
|
||||
@@ -181,23 +181,18 @@
|
||||
text = displayText(sanitized, unit);
|
||||
}
|
||||
|
||||
// Rounds half away from zero, the graph's one Number to Integer rule, where `Math.round` would carry -1.5 up to -1
|
||||
function roundToInteger(value: number): number {
|
||||
return Math.sign(value) * Math.round(Math.abs(value));
|
||||
}
|
||||
|
||||
// Called internally to update the value indirectly by informing the parent component of the new value,
|
||||
// so it can update the prop for this component, finally yielding the value change.
|
||||
function updateValue(newValue: number | undefined): number | undefined {
|
||||
// Check if the new value is valid, otherwise we use the old value (rounded if it's an integer)
|
||||
const oldValue = value !== undefined && isInteger ? roundToInteger(value) : value;
|
||||
const oldValue = value !== undefined && isInteger ? Math.round(value) : value;
|
||||
let newValueValidated = newValue !== undefined ? newValue : oldValue;
|
||||
|
||||
if (newValueValidated !== undefined) {
|
||||
if (typeof min === "number" && !Number.isNaN(min)) newValueValidated = Math.max(newValueValidated, min);
|
||||
if (typeof max === "number" && !Number.isNaN(max)) newValueValidated = Math.min(newValueValidated, max);
|
||||
|
||||
if (isInteger) newValueValidated = roundToInteger(newValueValidated);
|
||||
if (isInteger) newValueValidated = Math.round(newValueValidated);
|
||||
|
||||
rangeSliderValue = newValueValidated;
|
||||
rangeSliderValueAsRendered = newValueValidated;
|
||||
@@ -534,7 +529,7 @@
|
||||
cumulativeDragDelta += dragDelta;
|
||||
|
||||
const combined = initialValue + cumulativeDragDelta;
|
||||
const combineSnapped = snapping || isInteger ? roundToInteger(combined) : combined;
|
||||
const combineSnapped = snapping || isInteger ? Math.round(combined) : combined;
|
||||
|
||||
const newValue = updateValue(combineSnapped);
|
||||
|
||||
@@ -582,7 +577,7 @@
|
||||
}
|
||||
|
||||
// Snap the slider value to the nearest integer if the Ctrl key is held, or the widget is set to integer mode.
|
||||
const snappedValue = ctrlKeyDown || isInteger ? roundToInteger(roundedValue) : roundedValue;
|
||||
const snappedValue = ctrlKeyDown || isInteger ? Math.round(roundedValue) : roundedValue;
|
||||
|
||||
// The first "input" event upon mousedown means we transition to a "Deciding" state, allowing us to wait for the
|
||||
// next event to determine if the user is dragging (to slide the slider) or releasing (to edit the numerical text field).
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::ast::BinaryOp;
|
||||
use crate::value::{Complex, Number, Value, complex_divide, complex_log_gamma};
|
||||
use crate::value::{Complex, Number, Value};
|
||||
use num_complex::ComplexFloat;
|
||||
use std::f64::consts::{LN_2, PI, TAU};
|
||||
use std::f64::consts::LN_2;
|
||||
|
||||
pub type BuiltinFunction = fn(&[Value]) -> Option<Value>;
|
||||
|
||||
@@ -14,10 +13,10 @@ fn integer_operand(value: f64) -> Option<u128> {
|
||||
(value.is_finite() && value.abs() <= EXACT_INTEGER_LIMIT).then(|| (value as i64).unsigned_abs() as u128)
|
||||
}
|
||||
|
||||
/// Reads a combinatorics count as a whole number from zero up to f64's exactly-representable limit, or `None` for a fractional one rather than rounding it.
|
||||
fn whole_count(value: &Value) -> Option<u64> {
|
||||
let value = value.as_real()?;
|
||||
(value.fract() == 0. && (0. ..=EXACT_INTEGER_LIMIT).contains(&value)).then_some(value as u64)
|
||||
/// Rounds a combinatorics operand to the nearest whole number, or `None` when it is negative, non-finite, or beyond f64's exactly-representable integer range.
|
||||
fn whole_operand(value: f64) -> Option<u64> {
|
||||
let value = value.round();
|
||||
(0. ..=EXACT_INTEGER_LIMIT).contains(&value).then_some(value as u64)
|
||||
}
|
||||
|
||||
/// Accumulates one multiplicative `step` per iteration, stopping once the running product reaches infinity, since it stays there.
|
||||
@@ -33,25 +32,19 @@ fn bounded_product(steps: impl Iterator<Item = u64>, step: impl Fn(f64, u64) ->
|
||||
product
|
||||
}
|
||||
|
||||
/// Every argument as a real number, or `None` if any is complex or there are no arguments at all.
|
||||
fn real_operands(values: &[Value]) -> Option<impl Iterator<Item = f64> + Clone + '_> {
|
||||
if values.is_empty() || !values.iter().all(|value| value.as_real().is_some()) {
|
||||
return None;
|
||||
}
|
||||
Some(values.iter().filter_map(Value::as_real))
|
||||
}
|
||||
|
||||
/// Every argument in the complex plane, or `None` if there are no arguments at all.
|
||||
fn complex_operands(values: &[Value]) -> Option<impl Iterator<Item = Complex> + Clone + '_> {
|
||||
/// Collects every argument as a real number, or `None` if any is complex or there are no arguments at all.
|
||||
fn real_operands(values: &[Value]) -> Option<Vec<f64>> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(values.iter().map(|Value::Number(number)| number.as_complex()))
|
||||
}
|
||||
|
||||
/// The [`power_of_two_scale`] of the numbers' largest part.
|
||||
fn scale_of(numbers: impl Iterator<Item = Complex>) -> f64 {
|
||||
power_of_two_scale(numbers.flat_map(|number| [number.re, number.im]))
|
||||
values
|
||||
.iter()
|
||||
.map(|value| match value {
|
||||
Value::Number(Number::Real(real)) => Some(*real),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Applies a one-argument function that may climb into the complex plane: a real result that does not exist,
|
||||
@@ -74,8 +67,8 @@ fn climbing(values: &[Value], real_function: fn(f64) -> f64, complex_function: f
|
||||
|
||||
/// The power of two at or below the largest magnitude, dividing by which is exact and brings every value within ±2, so sums and
|
||||
/// squares of the scaled values neither overflow nor underflow. It's 1 when the largest magnitude is zero, subnormal, or infinite.
|
||||
fn power_of_two_scale(reals: impl Iterator<Item = f64>) -> f64 {
|
||||
let largest = reals.fold(0_f64, |largest, real| largest.max(real.abs()));
|
||||
fn power_of_two_scale(reals: &[f64]) -> f64 {
|
||||
let largest = reals.iter().fold(0_f64, |largest, real| largest.max(real.abs()));
|
||||
if !largest.is_normal() {
|
||||
return 1.;
|
||||
}
|
||||
@@ -84,15 +77,15 @@ fn power_of_two_scale(reals: impl Iterator<Item = f64>) -> f64 {
|
||||
f64::from_bits(largest.to_bits() & (0x7FF << 52))
|
||||
}
|
||||
|
||||
/// Computes the variance of the arguments, the mean of `|x - mean|²`, divided by the returned scale, over the count less `correction`
|
||||
/// (1 for a sample, undefined for a single value, or 0 for a population). Staying scaled lets a standard deviation take its root before overflowing.
|
||||
/// Computes the variance of the real arguments divided by the returned scale, over the count less `correction` (1 for a sample,
|
||||
/// undefined for a single value, or 0 for a population). Staying scaled lets a standard deviation take its root before overflowing.
|
||||
fn scaled_variance(values: &[Value], correction: usize) -> Option<(f64, f64)> {
|
||||
let numbers = complex_operands(values)?;
|
||||
let divisor = values.len().checked_sub(correction).filter(|divisor| *divisor > 0)? as f64;
|
||||
let scale = scale_of(numbers.clone());
|
||||
let reals = real_operands(values)?;
|
||||
let divisor = reals.len().checked_sub(correction).filter(|divisor| *divisor > 0)? as f64;
|
||||
let scale = power_of_two_scale(&reals);
|
||||
|
||||
let mean = numbers.clone().map(|number| number / scale).sum::<Complex>() / values.len() as f64;
|
||||
let variance = numbers.map(|number| (number / scale - mean).norm_sqr()).sum::<f64>() / divisor;
|
||||
let mean = reals.iter().map(|real| real / scale).sum::<f64>() / reals.len() as f64;
|
||||
let variance = reals.iter().map(|real| (real / scale - mean).powi(2)).sum::<f64>() / divisor;
|
||||
Some((variance, scale))
|
||||
}
|
||||
|
||||
@@ -137,61 +130,6 @@ fn checked_lcm(a: u128, b: u128) -> Option<u128> {
|
||||
(a / gcd(a, b)).checked_mul(b)
|
||||
}
|
||||
|
||||
/// `choose(n, r)` over a whole nonnegative top, exact while it fits, and zero once `r` exceeds `n`.
|
||||
fn whole_binomial(n: f64, r: u64) -> f64 {
|
||||
if r as f64 > n {
|
||||
return 0.;
|
||||
}
|
||||
|
||||
// Multiplying then dividing at each step keeps every intermediate whole, and the smaller of `r` and `n - r` halves the steps
|
||||
let r = r.min((n - r as f64) as u64);
|
||||
bounded_product(1..=r, |accumulated, k| accumulated * (n - r as f64 + k as f64) / k as f64)
|
||||
}
|
||||
|
||||
/// `pick(n, r)` over a whole nonnegative top, and zero once `r` exceeds `n`.
|
||||
fn whole_falling_factorial(n: f64, r: u64) -> f64 {
|
||||
if r as f64 > n {
|
||||
return 0.;
|
||||
}
|
||||
bounded_product(0..r, |accumulated, k| accumulated * (n - k as f64))
|
||||
}
|
||||
|
||||
/// The falling factorial `x (x - 1) ... (x - r + 1)` over any top, or the binomial coefficient dividing it by `r!`, by direct
|
||||
/// product (a negative whole top as `(-1)^r` times that of `|x| + r - 1`), or past a few thousand terms of any other top, the gamma function.
|
||||
fn combinatorial(x: Number, r: u64, binomial: bool) -> Value {
|
||||
if let Some(real) = x.as_real()
|
||||
&& (real.fract() == 0. || real.is_infinite())
|
||||
{
|
||||
let sign = if real < 0. && r % 2 == 1 { -1. } else { 1. };
|
||||
let top = if real < 0. { r as f64 - 1. - real } else { real };
|
||||
let product = if binomial { whole_binomial(top, r) } else { whole_falling_factorial(top, r) };
|
||||
return Value::from_f64(sign * product);
|
||||
}
|
||||
|
||||
// The direct product keeps small cases exact at a step per count, so only a count past a few thousand takes the gamma function
|
||||
const DIRECT_PRODUCT_LIMIT: u64 = 4096;
|
||||
let z = x.as_complex();
|
||||
let product = (r <= DIRECT_PRODUCT_LIMIT).then(|| {
|
||||
if binomial {
|
||||
(1..=r).fold(Complex::from(1.), |accumulated, k| accumulated * (z - (k - 1) as f64) / k as f64)
|
||||
} else {
|
||||
(0..r).fold(Complex::from(1.), |accumulated, k| accumulated * (z - k as f64))
|
||||
}
|
||||
});
|
||||
|
||||
// An overflowed product has NaN cross terms, so the gamma function takes over with the overflow's direction
|
||||
let result = match product {
|
||||
Some(product) if !Number::Complex(product).is_nan() => product,
|
||||
_ => {
|
||||
let count_log = if binomial { complex_log_gamma(Complex::from(r as f64 + 1.)) } else { Complex::from(0.) };
|
||||
(complex_log_gamma(z + 1.) - complex_log_gamma(z - r as f64 + 1.) - count_log).exp()
|
||||
}
|
||||
};
|
||||
|
||||
// A real top has a real answer, so the rounding residue in the imaginary part is dropped
|
||||
Value::Number(if x.as_real().is_some() { Number::Real(result.re) } else { Number::Complex(result) })
|
||||
}
|
||||
|
||||
/// Resolves a base-suffixed function name like `log2` or `root3.25` into the corresponding two-argument
|
||||
/// function and the baked-in second argument parsed from the suffix.
|
||||
pub fn suffixed_function(name: &str) -> Option<(BuiltinFunction, f64)> {
|
||||
@@ -290,14 +228,12 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
|
||||
Some(if root.is_nan() { Value::from(Complex::new(*x, 0.).powf(1. / *n)) } else { Value::from_f64(root) })
|
||||
}
|
||||
[Value::Number(Number::Complex(x)), Value::Number(Number::Real(n))] => Some(Value::from(x.powf(1. / *n))),
|
||||
// A complex degree is the general power `x^(1/n)`
|
||||
[Value::Number(x), Value::Number(n)] => Some(Value::from(x.as_complex().powc(n.as_complex().inv()))),
|
||||
_ => None,
|
||||
}),
|
||||
|
||||
// Geometry Functions
|
||||
// Folding pairwise hypotenuses gives the root of the sum of squares without ever squaring, avoiding overflow
|
||||
"hypot" => variadic(|values| Some(Value::from_f64(real_operands(values)?.fold(0., f64::hypot)))),
|
||||
"hypot" => variadic(|values| Some(Value::from_f64(real_operands(values)?.into_iter().fold(0., f64::hypot)))),
|
||||
|
||||
"atan2" => fixed_arity(|values| match values {
|
||||
[Value::Number(Number::Real(y)), Value::Number(Number::Real(x))] => Some(Value::Number(Number::Real(y.atan2(*x)))),
|
||||
@@ -353,24 +289,20 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
|
||||
Some(Value::Number(Number::Real(max)))
|
||||
}),
|
||||
|
||||
// Statistics across one or more arguments, with the median and mode over real ones since they need an order
|
||||
// Statistics across one or more real arguments
|
||||
// TODO: Offer `avg` and `average` as autocomplete aliases in the expression widget, resolving to `mean`
|
||||
"mean" => variadic(|values| {
|
||||
let numbers = complex_operands(values)?;
|
||||
let scale = scale_of(numbers.clone());
|
||||
Some(Value::from(numbers.map(|number| number / scale).sum::<Complex>() / values.len() as f64 * scale))
|
||||
let reals = real_operands(values)?;
|
||||
let scale = power_of_two_scale(&reals);
|
||||
Some(Value::from_f64(reals.iter().map(|real| real / scale).sum::<f64>() / reals.len() as f64 * scale))
|
||||
}),
|
||||
|
||||
"median" => variadic(|values| {
|
||||
let mut reals: Vec<f64> = real_operands(values)?.collect();
|
||||
let mut reals = real_operands(values)?;
|
||||
reals.sort_by(f64::total_cmp);
|
||||
let middle = reals.len() / 2;
|
||||
// An even count has no single middle value, so the two straddling it are averaged
|
||||
let median = if reals.len().is_multiple_of(2) {
|
||||
reals[middle - 1].midpoint(reals[middle])
|
||||
} else {
|
||||
reals[middle]
|
||||
};
|
||||
let median = if reals.len() % 2 == 0 { reals[middle - 1].midpoint(reals[middle]) } else { reals[middle] };
|
||||
|
||||
Some(Value::from_f64(median))
|
||||
}),
|
||||
@@ -381,54 +313,41 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
|
||||
"stdev" => variadic(|values| scaled_variance(values, 1).map(|(variance, scale)| Value::from_f64(variance.sqrt() * scale))),
|
||||
"stdevpop" => variadic(|values| scaled_variance(values, 0).map(|(variance, scale)| Value::from_f64(variance.sqrt() * scale))),
|
||||
|
||||
// The principal root of the product, from the mean of the magnitudes' logarithms (so nothing overflows) and the product's
|
||||
// argument wrapped into `(-π, π]`, so `geomean(-1, -4)` is 2 and `geomean(-1, 2)` climbs to `i√2` like `sqrt(-2)`
|
||||
"geomean" => variadic(|values| {
|
||||
let numbers = complex_operands(values)?;
|
||||
// One value is its own mean exactly, where the polar form below would leave a residue on a negative one
|
||||
if let [value] = values {
|
||||
return Some(*value);
|
||||
let reals = real_operands(values)?;
|
||||
// A negative operand has no real geometric mean, and averaging the logarithms keeps the product from overflowing
|
||||
if reals.iter().any(|real| *real < 0.) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let count = values.len() as f64;
|
||||
let log_magnitude = numbers.clone().map(|number| number.norm().ln()).sum::<f64>() / count;
|
||||
let argument = numbers.map(|number| number.arg()).sum::<f64>().rem_euclid(TAU);
|
||||
let argument = if argument > PI { argument - TAU } else { argument };
|
||||
Some(Value::from(Complex::new(log_magnitude, argument / count).exp()))
|
||||
Some(Value::from_f64((reals.iter().map(|real| real.ln()).sum::<f64>() / reals.len() as f64).exp()))
|
||||
}),
|
||||
|
||||
"harmmean" => variadic(|values| {
|
||||
let numbers = complex_operands(values)?;
|
||||
let reals = real_operands(values)?;
|
||||
|
||||
// A zero operand makes the mean zero, and only infinite ones make it their own mean, each contributing a zero reciprocal
|
||||
let smallest = numbers.clone().map(|number| number.norm()).fold(f64::INFINITY, f64::min);
|
||||
if smallest == 0. {
|
||||
return Some(Value::from_f64(0.));
|
||||
// Like the geometric mean, a negative operand has no meaningful harmonic mean, while a zero one makes it zero
|
||||
if reals.iter().any(|real| *real < 0.) {
|
||||
return None;
|
||||
}
|
||||
if smallest.is_infinite() {
|
||||
return Some(Value::from(numbers.sum::<Complex>() / values.len() as f64));
|
||||
let smallest = reals.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
if smallest == 0. || smallest.is_infinite() {
|
||||
return Some(Value::from_f64(smallest));
|
||||
}
|
||||
|
||||
// Dividing the smallest magnitude by each operand keeps every reciprocal term within 1, so their sum can't overflow
|
||||
let scaled_reciprocal_sum = Number::Complex(numbers.map(|number| complex_divide(Complex::from(smallest), number)).sum::<Complex>()).canonical();
|
||||
|
||||
// Reciprocals that cancel, as in `harmmean(-1, 1)`, sum to zero, and the language's own division takes that to infinity
|
||||
let count = Number::Real(values.len() as f64);
|
||||
count
|
||||
.binary_op(BinaryOp::Div, scaled_reciprocal_sum)?
|
||||
.binary_op(BinaryOp::Mul, Number::Real(smallest))
|
||||
.map(Value::Number)
|
||||
// Dividing the smallest operand by each keeps every reciprocal term within 1, so their sum can't overflow
|
||||
let scaled_reciprocal_sum = reals.iter().map(|real| smallest / real).sum::<f64>();
|
||||
Some(Value::from_f64(reals.len() as f64 / scaled_reciprocal_sum * smallest))
|
||||
}),
|
||||
|
||||
"rms" => variadic(|values| {
|
||||
let numbers = complex_operands(values)?;
|
||||
let scale = scale_of(numbers.clone());
|
||||
let mean_square = numbers.map(|number| (number / scale).norm_sqr()).sum::<f64>() / values.len() as f64;
|
||||
let reals = real_operands(values)?;
|
||||
let scale = power_of_two_scale(&reals);
|
||||
let mean_square = reals.iter().map(|real| (real / scale).powi(2)).sum::<f64>() / reals.len() as f64;
|
||||
Some(Value::from_f64(mean_square.sqrt() * scale))
|
||||
}),
|
||||
|
||||
"mode" => variadic(|values| {
|
||||
let mut reals: Vec<f64> = real_operands(values)?.collect();
|
||||
let mut reals = real_operands(values)?;
|
||||
reals.sort_by(f64::total_cmp);
|
||||
|
||||
// In ascending order, the first run of the greatest length is the smallest of the most frequent values, and no mode exists when no value repeats
|
||||
@@ -509,24 +428,46 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
|
||||
}),
|
||||
|
||||
"gcd" => variadic(|values| {
|
||||
let reduced = real_operands(values)?.try_fold(0_u128, |accumulated, real| Some(gcd(accumulated, integer_operand(real)?)))?;
|
||||
let reduced = real_operands(values)?
|
||||
.into_iter()
|
||||
.try_fold(0_u128, |accumulated, real| Some(gcd(accumulated, integer_operand(real)?)))?;
|
||||
Some(Value::from_f64(reduced as f64))
|
||||
}),
|
||||
|
||||
"lcm" => variadic(|values| {
|
||||
let reduced = real_operands(values)?.try_fold(1_u128, |accumulated, real| checked_lcm(accumulated, integer_operand(real)?))?;
|
||||
let reduced = real_operands(values)?
|
||||
.into_iter()
|
||||
.try_fold(1_u128, |accumulated, real| checked_lcm(accumulated, integer_operand(real)?))?;
|
||||
Some(Value::from_f64(reduced as f64))
|
||||
}),
|
||||
|
||||
// Combinatorics over any top and a whole count: `choose(x, r)` is the binomial coefficient and `pick(x, r)` the falling factorial
|
||||
"choose" => fixed_arity(|values| {
|
||||
let [Value::Number(x), r] = values else { return None };
|
||||
Some(combinatorial(*x, whole_count(r)?, true))
|
||||
// Combinatorics over whole numbers: `choose(n, r)` is the binomial coefficient and `pick(n, r)` the falling factorial
|
||||
"choose" => fixed_arity(|values| match values {
|
||||
[Value::Number(Number::Real(n)), Value::Number(Number::Real(r))] => {
|
||||
let (n, r) = (whole_operand(*n)?, whole_operand(*r)?);
|
||||
if r > n {
|
||||
return Some(Value::from_f64(0.));
|
||||
}
|
||||
|
||||
// Multiplying then dividing at each step keeps every intermediate whole, and the smaller of `r` and `n - r` halves the steps
|
||||
let r = r.min(n - r);
|
||||
let binomial = bounded_product(1..=r, |accumulated, k| accumulated * (n - r + k) as f64 / k as f64);
|
||||
Some(Value::from_f64(binomial))
|
||||
}
|
||||
_ => None,
|
||||
}),
|
||||
|
||||
"pick" => fixed_arity(|values| {
|
||||
let [Value::Number(x), r] = values else { return None };
|
||||
Some(combinatorial(*x, whole_count(r)?, false))
|
||||
"pick" => fixed_arity(|values| match values {
|
||||
[Value::Number(Number::Real(n)), Value::Number(Number::Real(r))] => {
|
||||
let (n, r) = (whole_operand(*n)?, whole_operand(*r)?);
|
||||
if r > n {
|
||||
return Some(Value::from_f64(0.));
|
||||
}
|
||||
|
||||
let falling_factorial = bounded_product(0..r, |accumulated, k| accumulated * (n - k) as f64);
|
||||
Some(Value::from_f64(falling_factorial))
|
||||
}
|
||||
_ => None,
|
||||
}),
|
||||
|
||||
// The conjugate negates the imaginary part
|
||||
|
||||
@@ -483,33 +483,6 @@ impl<'a> Iterator for Lexer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces each whole identifier for which `rename` returns a new spelling, so `b` never matches inside `logb`, and leaves all other source text untouched.
|
||||
/// Returns `None` if the source fails to lex.
|
||||
pub fn rename_identifiers(source: &str, mut rename: impl FnMut(&str) -> Option<String>) -> Option<String> {
|
||||
let mut lexer = Lexer::new(source);
|
||||
let mut result = String::with_capacity(source.len());
|
||||
let mut copied_up_to = 0;
|
||||
|
||||
while let Some(token) = lexer.next_token() {
|
||||
match token {
|
||||
Token::Error => return None,
|
||||
Token::Ident(name) => {
|
||||
if let Some(new_name) = rename(name) {
|
||||
// An `Ident` always borrows directly from the source, so its span is recoverable by pointer offset
|
||||
let start = name.as_ptr() as usize - source.as_ptr() as usize;
|
||||
result.push_str(&source[copied_up_to..start]);
|
||||
result.push_str(&new_name);
|
||||
copied_up_to = start + name.len();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
result.push_str(&source[copied_up_to..]);
|
||||
Some(result)
|
||||
}
|
||||
|
||||
impl<'src> Input<'src> for Lexer<'src> {
|
||||
type Token = Token<'src>;
|
||||
type Span = Span;
|
||||
|
||||
@@ -147,9 +147,6 @@ mod tests {
|
||||
"gcd(inf, 6)",
|
||||
"gcd(10000000000000000000, 2)",
|
||||
"mod(5, 0)",
|
||||
"choose(2.5, 1.5)",
|
||||
"pick(3, 0.5)",
|
||||
"choose(3, -1)",
|
||||
"(-1)!",
|
||||
"(-2)!",
|
||||
"(-inf)!",
|
||||
@@ -181,52 +178,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combinatorics_extend_past_the_whole_numbers() {
|
||||
// Compared relatively like the factorial: a count up to a few thousand multiplies out directly, and a larger one goes
|
||||
// through the gamma function, whose logarithms in the tens of thousands cost a couple of digits
|
||||
for (input, expected, tolerance) in [
|
||||
("choose(0.5, 200)", Complex::from(-9.992306256589706e-5), 1e-12),
|
||||
("choose(10.5, 100)", Complex::from(-7.091868840771164e-17), 1e-12),
|
||||
("choose(-2.5, 7)", Complex::from(-17.80517578125), 1e-12),
|
||||
("choose(-0.5, 50)", Complex::from(0.07958923738717877), 1e-12),
|
||||
("pick(-2.5, 7)", Complex::from(-89738.0859375), 1e-12),
|
||||
("choose(1e22, 2)", Complex::from(5e43), 1e-12),
|
||||
("choose(1.5 + 2i, 3)", Complex::new(-1.0625, -1.4166666666666667), 1e-12),
|
||||
("pick(1.5 + 2i, 3)", Complex::new(-6.375, -8.5), 1e-12),
|
||||
("choose(0.5, 5000)", Complex::from(-7.979444083790532e-7), 1e-10),
|
||||
("choose(10.5, 8000)", Complex::from(-4.9672984268570704e-39), 1e-10),
|
||||
("choose(-0.5, 5000)", Complex::from(0.007978646139382154), 1e-10),
|
||||
("choose(1.5 + 2i, 5000)", Complex::new(-2.541871408941716e-8, -8.84744846043224e-9), 1e-10),
|
||||
] {
|
||||
let Value::Number(actual) = evaluate(input).unwrap().unwrap();
|
||||
let actual = actual.as_complex();
|
||||
assert!((actual - expected).norm() / expected.norm() < tolerance, "`{input}`: expected {expected}, got {actual}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simple_complex_quotients_are_exact() {
|
||||
// Smith's algorithm rounds nothing on these, where dividing by the norm twice loses an ulp
|
||||
for (input, expected) in [
|
||||
("(1 + i) / (1 - i)", Complex::new(0., 1.)),
|
||||
("2 / (1 - i)", Complex::new(1., 1.)),
|
||||
("(3 + 4i) / (1 + 2i)", Complex::new(2.2, -0.4)),
|
||||
("harmmean(i, 1)", Complex::new(1., 1.)),
|
||||
] {
|
||||
assert_eq!(evaluate(input).unwrap().unwrap(), Value::from(expected), "`{input}`");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_combinatorics_are_exact() {
|
||||
// The direct product leaves no rounding behind on these, where the gamma function would
|
||||
for (input, expected) in [("choose(2.5, 2)", 1.875), ("pick(2.5, 2)", 3.75), ("choose(-0.5, 2)", 0.375)] {
|
||||
assert_eq!(evaluate(input).unwrap().unwrap().as_real(), Some(expected), "`{input}`");
|
||||
}
|
||||
assert_eq!(evaluate("choose(i, 2)").unwrap().unwrap(), Value::from(Complex::new(-0.5, -0.5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_values_are_admitted_where_read() {
|
||||
struct Host;
|
||||
@@ -258,8 +209,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn statistics_without_an_answer_are_errors() {
|
||||
// No value repeats, so no mode exists
|
||||
assert!(evaluate("mode(1, 2, 3)").unwrap().is_err());
|
||||
// No value repeats, so no mode exists, and negative operands have no geometric or harmonic mean
|
||||
for input in ["mode(1, 2, 3)", "geomean(-1, 4)", "harmmean(1, -1)"] {
|
||||
assert!(evaluate(input).unwrap().is_err(), "expected `{input}` to be an evaluation error");
|
||||
}
|
||||
|
||||
// A single value has no spread to estimate a sample from
|
||||
for input in ["variance(5)", "stdev(5)"] {
|
||||
@@ -346,23 +299,6 @@ mod tests {
|
||||
assert_eq!(eval("\\sin(pi / 2)"), Some(1.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_identifiers_is_token_exact() {
|
||||
let a_to_x = |name: &str| name.eq_ignore_ascii_case("a").then(|| "x".to_string());
|
||||
|
||||
// Only whole identifiers rename, so function names and other tokens that merely contain the letter stay untouched
|
||||
assert_eq!(crate::lexer::rename_identifiers("2 - 0.2A", a_to_x).as_deref(), Some("2 - 0.2x"));
|
||||
assert_eq!(crate::lexer::rename_identifiers("atan(a) + tau", a_to_x).as_deref(), Some("atan(x) + tau"));
|
||||
assert_eq!(
|
||||
crate::lexer::rename_identifiers("sqrt(A + B) - B^2", |name| name.eq_ignore_ascii_case("b").then(|| "(3)".to_string())).as_deref(),
|
||||
Some("sqrt(A + (3)) - (3)^2")
|
||||
);
|
||||
assert_eq!(crate::lexer::rename_identifiers("logb + b", |name| (name == "b").then(|| "c".to_string())).as_deref(), Some("logb + c"));
|
||||
|
||||
// A string that fails to lex reports `None` rather than renaming unreliably
|
||||
assert_eq!(crate::lexer::rename_identifiers("a + \u{200b}b", a_to_x), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_led_function_suffixes_fail_to_parse() {
|
||||
// A `.`-led base suffix is an error (the supported spelling is `log0.5`)
|
||||
@@ -669,22 +605,6 @@ mod tests {
|
||||
statistics_rms: "rms(3, 4)" => 12.5_f64.sqrt(),
|
||||
statistics_mode: "mode(2, 3, 3, 1, 2)" => 2.,
|
||||
statistics_count: "count(1, 2, 3)" => 3.,
|
||||
statistics_mean_complex: "mean(i, 3i)" => Complex::new(0., 2.),
|
||||
statistics_mean_lands_real: "mean(1 + i, 3 - i)" => 2.,
|
||||
statistics_variance_complex: "variance(i, -i)" => 2.,
|
||||
statistics_stdev_population_complex: "stdevpop(1 + i, 1 - i)" => 1.,
|
||||
statistics_rms_complex: "rms(3i, 4)" => 12.5_f64.sqrt(),
|
||||
statistics_geomean_single: "geomean(-3)" => -3.,
|
||||
statistics_geomean_negative_pair: "geomean(-1, -4)" => 2.,
|
||||
statistics_geomean_climbs: "geomean(-1, 2)" => Complex::new(0., 2_f64.sqrt()),
|
||||
statistics_geomean_complex: "geomean(i, 1)" => Complex::new(std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2),
|
||||
statistics_harmmean_negative: "harmmean(-1, -3)" => -1.5,
|
||||
statistics_harmmean_cancelling: "harmmean(-1, 1)" => f64::INFINITY,
|
||||
statistics_harmmean_complex: "harmmean(i, 1)" => Complex::new(1., 1.),
|
||||
statistics_geomean_infinite: "geomean(inf, 1)" => f64::INFINITY,
|
||||
statistics_harmmean_infinite_operand: "harmmean(inf, 1)" => 2.,
|
||||
statistics_harmmean_all_infinite: "harmmean(-inf, -inf)" => f64::NEG_INFINITY,
|
||||
statistics_harmmean_huge: "harmmean(1e308, 1e308)" => 1e308,
|
||||
logical_xor_odd_parity: "xor(1, 1, 1)" => 1.,
|
||||
logical_xor_even_parity: "xor(1, 0, 1)" => 0.,
|
||||
mapping_remap: "remap(5, 0, 10, 0, 100)" => 50.,
|
||||
@@ -695,28 +615,15 @@ mod tests {
|
||||
gcd_negative_operand: "gcd(-24, 18)" => 6.,
|
||||
lcm_negative_operand: "lcm(-4, 6)" => 12.,
|
||||
|
||||
// Combinatorics over any top and a whole count
|
||||
// Combinatorics over whole numbers
|
||||
combinatorics_choose: "choose(5, 2)" => 10.,
|
||||
combinatorics_choose_symmetric: "choose(30, 28)" => 435.,
|
||||
combinatorics_choose_beyond_n: "choose(3, 5)" => 0.,
|
||||
combinatorics_choose_fractional_top: "choose(2.4, 1)" => 2.4,
|
||||
combinatorics_choose_half: "choose(0.5, 2)" => -0.125,
|
||||
combinatorics_choose_negative_top: "choose(-1, 3)" => -1.,
|
||||
combinatorics_choose_negative_top_larger: "choose(-5, 3)" => -35.,
|
||||
combinatorics_choose_zero_count: "choose(2.5, 0)" => 1.,
|
||||
combinatorics_choose_complex_top: "choose(i, 2)" => Complex::new(-0.5, -0.5),
|
||||
combinatorics_pick: "pick(5, 2)" => 20.,
|
||||
combinatorics_pick_all: "pick(4, 4)" => 24.,
|
||||
combinatorics_pick_fractional_top: "pick(2.5, 2)" => 3.75,
|
||||
combinatorics_pick_negative_top: "pick(-5, 3)" => -210.,
|
||||
combinatorics_pick_complex_top: "pick(i, 2)" => Complex::new(-1., -1.),
|
||||
// A result beyond f64 stops at infinity instead of stepping through quadrillions of terms
|
||||
combinatorics_choose_overflows: "choose(9007199254740992, 4503599627370496)" => f64::INFINITY,
|
||||
combinatorics_pick_overflows: "pick(9007199254740992, 9007199254740992)" => f64::INFINITY,
|
||||
combinatorics_pick_fractional_overflows: "pick(0.5, 200)" => f64::NEG_INFINITY,
|
||||
combinatorics_pick_complex_overflows: "|pick(1.5 + 2i, 300)|" => f64::INFINITY,
|
||||
combinatorics_choose_infinite_top: "choose(inf, 2)" => f64::INFINITY,
|
||||
combinatorics_pick_negative_infinite_top: "pick(-inf, 3)" => f64::NEG_INFINITY,
|
||||
|
||||
// Truth values are the numbers 1 and 0
|
||||
constant_truth_values: "true + true - false" => 2.,
|
||||
@@ -762,8 +669,6 @@ mod tests {
|
||||
root_negative_odd: "root(-8, 3)" => -2.,
|
||||
root_negative_odd_reciprocal: "root(-8, -3)" => -0.5,
|
||||
root_negative_even: "root(-4, 2)" => Complex::new(0., 2.),
|
||||
root_complex_degree: "root(8, 3i)" => Complex::new(0.7692389013639721, -0.6389612763136348),
|
||||
root_complex_degree_lands_real: "root(i, i)" => std::f64::consts::FRAC_PI_2.exp(),
|
||||
|
||||
// Equality spans real and complex operands
|
||||
mixed_equality: "1 == i" => 0.,
|
||||
@@ -777,27 +682,6 @@ mod tests {
|
||||
value_identity_signed_zero: "1/(-0)" => f64::INFINITY,
|
||||
value_identity_ceiling: "1/ceil(-0.5)" => f64::INFINITY,
|
||||
|
||||
// Division by zero heads to infinity part by part with each part's own sign, like an overflow, rather than turning indeterminate
|
||||
division_by_zero_imaginary: "i / 0" => Complex::new(0., f64::INFINITY),
|
||||
division_by_zero_complex: "(1 + i) / 0" => Complex::new(f64::INFINITY, f64::INFINITY),
|
||||
division_by_zero_complex_signs: "(1 - i) / 0" => Complex::new(f64::INFINITY, f64::NEG_INFINITY),
|
||||
division_scaled_tiny: "(1e-200i) / (1e-200i)" => 1.,
|
||||
division_scaled_huge: "(1e200 + 1e200i) / (1e200 + 1e200i)" => 1.,
|
||||
division_scaled_max: "(1e308 + 1e308i) / (1e308 + 1e308i)" => 1.,
|
||||
division_scaled_max_dividend: "(1e308 + 1e308i) / (1 + i)" => 1e308,
|
||||
division_scaled_max_dividend_signs: "(1e308 - 1e308i) / (1 + i)" => Complex::new(0., -1e308),
|
||||
|
||||
// A whole exponent on a complex base multiplies out exactly
|
||||
power_imaginary_square: "i^2" => -1.,
|
||||
power_imaginary_cube: "i^3" => Complex::new(0., -1.),
|
||||
power_imaginary_zero: "i^0" => 1.,
|
||||
power_imaginary_huge: "i^(2^70)" => 1.,
|
||||
power_complex_square: "(3 + 4i)^2" => Complex::new(-7., 24.),
|
||||
power_complex_negative: "(1 + i)^-2" => Complex::new(0., -0.5),
|
||||
power_complex_negative_tiny: "(1e-200i)^-1" => Complex::new(0., -1e200),
|
||||
power_complex_negative_underflow: "|(1e-200i)^-2|" => f64::INFINITY,
|
||||
power_complex_overflow: "|(1.5 + 2i)^1000|" => f64::INFINITY,
|
||||
|
||||
// Domain climbs: a real input whose answer is complex resolves into the `1, i` plane
|
||||
climb_sqrt: "sqrt(-4)" => Complex::new(0., 2.),
|
||||
climb_ln: "ln(-1)" => Complex::new(0., std::f64::consts::PI),
|
||||
|
||||
@@ -97,9 +97,7 @@ impl Reducer {
|
||||
|
||||
Reducer::Function(function) => {
|
||||
let values: Vec<Value> = items.iter().map(|&item| Value::from_f64(item)).collect();
|
||||
// Canonical like a settled result, so a mean that lands on the real line reads as real
|
||||
let Value::Number(result) = function(&values)?;
|
||||
result.canonical().as_real()
|
||||
function(&values)?.as_real()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::ast::{BinaryOp, UnaryOp};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Mul;
|
||||
|
||||
pub type Complex = num_complex::Complex<f64>;
|
||||
|
||||
@@ -187,8 +186,7 @@ impl Number {
|
||||
BinaryOp::Add => lhs + rhs,
|
||||
BinaryOp::Sub => lhs - rhs,
|
||||
BinaryOp::Mul => lhs * rhs,
|
||||
BinaryOp::Div => complex_divide(lhs, rhs),
|
||||
BinaryOp::Pow if rhs.im == 0. => return complex_real_power(lhs, rhs.re),
|
||||
BinaryOp::Div => lhs / rhs,
|
||||
BinaryOp::Pow => lhs.powc(rhs),
|
||||
BinaryOp::Leq | BinaryOp::Lt | BinaryOp::Geq | BinaryOp::Gt => {
|
||||
return None;
|
||||
@@ -204,7 +202,7 @@ impl Number {
|
||||
BinaryOp::Add => lhs_complex + rhs,
|
||||
BinaryOp::Sub => lhs_complex - rhs,
|
||||
BinaryOp::Mul => lhs_complex * rhs,
|
||||
BinaryOp::Div => complex_divide(lhs_complex, rhs),
|
||||
BinaryOp::Div => lhs_complex / rhs,
|
||||
BinaryOp::Pow => lhs_complex.powc(rhs),
|
||||
_ => return None,
|
||||
};
|
||||
@@ -217,9 +215,8 @@ impl Number {
|
||||
BinaryOp::Add => lhs + rhs_complex,
|
||||
BinaryOp::Sub => lhs - rhs_complex,
|
||||
BinaryOp::Mul => lhs * rhs_complex,
|
||||
BinaryOp::Div if rhs == 0. => complex_over_zero(lhs, rhs),
|
||||
BinaryOp::Div => lhs / rhs,
|
||||
BinaryOp::Pow => return complex_real_power(lhs, rhs),
|
||||
BinaryOp::Div => lhs / rhs_complex,
|
||||
BinaryOp::Pow => lhs.powf(rhs),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Number::Complex(result))
|
||||
@@ -251,72 +248,6 @@ impl Number {
|
||||
}
|
||||
}
|
||||
|
||||
/// Division by a real zero, sending each nonzero part to the infinity of its own sign as an overflow would, so `i / 0` is `∞i`.
|
||||
fn complex_over_zero(dividend: Complex, zero: f64) -> Complex {
|
||||
let part_over_zero = |part: f64| if part == 0. { 0. } else { part / zero };
|
||||
Complex::new(part_over_zero(dividend.re), part_over_zero(dividend.im))
|
||||
}
|
||||
|
||||
/// Complex division by Smith's algorithm, scaling by the divisor's larger part so neither `|divisor|²` nor the quotient
|
||||
/// overflows or underflows while the answer fits, and a simple quotient like `(1 + i) / (1 - i)` stays exact.
|
||||
pub(crate) fn complex_divide(dividend: Complex, divisor: Complex) -> Complex {
|
||||
// Every part is halved when one passes half of f64::MAX, keeping the quotient while the sums below stay in range
|
||||
let largest_part = [dividend.re, dividend.im, divisor.re, divisor.im].into_iter().map(f64::abs).fold(0., f64::max);
|
||||
let (dividend, divisor) = if largest_part > f64::MAX / 2. { (dividend / 2., divisor / 2.) } else { (dividend, divisor) };
|
||||
|
||||
let Complex { re: a, im: b } = dividend;
|
||||
let Complex { re: c, im: d } = divisor;
|
||||
if c.abs() >= d.abs() {
|
||||
let ratio = d / c;
|
||||
let denominator = c + d * ratio;
|
||||
Complex::new((a + b * ratio) / denominator, (b - a * ratio) / denominator)
|
||||
} else {
|
||||
let ratio = c / d;
|
||||
let denominator = d + c * ratio;
|
||||
Complex::new((a * ratio + b) / denominator, (b * ratio - a) / denominator)
|
||||
}
|
||||
}
|
||||
|
||||
/// A complex base under a real exponent: a whole exponent multiplies out exactly by squaring, so `i^2` is `-1` where the polar
|
||||
/// form leaves a `sin(π)` residue, and any other exponent takes the polar form.
|
||||
fn complex_real_power(base: Complex, exponent: f64) -> Option<Number> {
|
||||
if exponent.fract() != 0. || exponent.abs() >= u128::MAX as f64 {
|
||||
return Some(Number::Complex(base.powf(exponent)));
|
||||
}
|
||||
|
||||
let power = match exponent.abs() as u128 {
|
||||
0 => Complex::from(1.),
|
||||
count => whole_power(base, count),
|
||||
};
|
||||
// An overflowed product has NaN cross terms, so the polar form takes over with the overflow's direction
|
||||
if Number::Complex(power).is_nan() {
|
||||
return Some(Number::Complex(base.powf(exponent)));
|
||||
}
|
||||
|
||||
if exponent < 0. {
|
||||
return Number::Real(1.).binary_op(BinaryOp::Div, Number::Complex(power).canonical());
|
||||
}
|
||||
Some(Number::Complex(power))
|
||||
}
|
||||
|
||||
/// `base^n` for a whole `n` of at least 1 by repeated squaring, in O(log n) multiplications.
|
||||
fn whole_power<T: Copy + Mul<Output = T>>(mut base: T, mut exponent: u128) -> T {
|
||||
while exponent & 1 == 0 {
|
||||
base = base * base;
|
||||
exponent >>= 1;
|
||||
}
|
||||
|
||||
let mut result = base;
|
||||
while exponent > 1 {
|
||||
exponent >>= 1;
|
||||
base = base * base;
|
||||
if exponent & 1 == 1 {
|
||||
result = result * base;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The factorial of a real number: the exact product for a whole number, and `x! = Γ(x + 1)` past the whole numbers, or
|
||||
/// `None` at the negative integers (the gamma function's poles, where no signed limit exists) and at -∞.
|
||||
fn real_factorial(x: f64) -> Option<f64> {
|
||||
@@ -367,7 +298,7 @@ fn complex_gamma(z: Complex) -> Complex {
|
||||
}
|
||||
|
||||
/// The natural logarithm of the gamma function over the complex plane, by the same approximation and reflection as [`real_gamma`].
|
||||
pub(crate) fn complex_log_gamma(z: Complex) -> Complex {
|
||||
fn complex_log_gamma(z: Complex) -> Complex {
|
||||
if z.re < 0.5 {
|
||||
// Shifting the real part into `[0, 1)` keeps the sine exact, with a half turn (a sign) for each odd shift
|
||||
let shift = z.re.floor();
|
||||
|
||||
+73
-48
@@ -13,37 +13,52 @@ pub struct DocumentNode {
|
||||
pub inputs: Vec<NodeInput>,
|
||||
pub call_argument: Type,
|
||||
pub implementation: DocumentNodeImplementation,
|
||||
pub visible: bool,
|
||||
pub skip_deduplication: bool,
|
||||
pub context_features: ContextDependencies,
|
||||
pub visible: bool,
|
||||
pub original_location: OriginalLocation,
|
||||
}
|
||||
```
|
||||
(Explanatory comments omitted; the actual definition is currently found in [`node-graph/graph-craft/src/document.rs`](https://github.com/GraphiteEditor/Graphite/blob/master/node-graph/graph-craft/src/document.rs))
|
||||
|
||||
Each `DocumentNode` is of a particular type, for example the "Opacity" node type. The blueprint for a type is a `DocumentNodeDefinition`, found in `editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs`:
|
||||
Each `DocumentNode` is of a particular type, for example the "Opacity" node type. You can define your own type of document node in `editor/src/messages/portfolio/document/node_graph/node_graph_message_handler/document_node_types.rs`. A sample document node type definition for the opacity node is shown:
|
||||
|
||||
```rs
|
||||
pub struct DocumentNodeDefinition {
|
||||
pub identifier: &'static str,
|
||||
pub node_template: NodeTemplate,
|
||||
pub category: &'static str,
|
||||
pub description: Cow<'static, str>,
|
||||
pub properties: Option<&'static str>,
|
||||
}
|
||||
DocumentNodeDefinition {
|
||||
name: "Opacity",
|
||||
category: "Image Adjustments",
|
||||
implementation: DocumentNodeImplementation::proto("graphene_core::raster::OpacityNode"),
|
||||
inputs: vec![
|
||||
DocumentInputType::value("Image", TaggedValue::ImageFrame(ImageFrame::empty()), true),
|
||||
DocumentInputType::value("Factor", TaggedValue::F32(100.), false),
|
||||
],
|
||||
outputs: vec![DocumentOutputType::new("Image", FrontendGraphDataType::Raster)],
|
||||
properties: node_properties::multiply_opacity,
|
||||
..Default::default()
|
||||
},
|
||||
```
|
||||
|
||||
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
The identifier here must be the same as that of the proto-node which will be discussed soon (usually the path to the node implementation).
|
||||
|
||||
> [!NOTE]
|
||||
> Nodes defined in `graphene_core` are re-exported by `graphene_std`. However if the strings for the type names do not match exactly then you will encounter an error.
|
||||
|
||||
## Properties panel
|
||||
|
||||
Each input of a node is a `NodeInput`: either a wire from another node or a constant `TaggedValue` (a dynamically typed value that serializes with serde) paired with an exposed flag, which is whether the input is shown as a connector in the node graph by default. Both come from the function signature. A parameter's type picks the `TaggedValue` variant, `#[default(...)]` sets the value a new node starts with and the value an input falls back to when its wire is disconnected, and `#[expose]` shows a secondary input's connector, while the primary input always has one. In the Opacity node, `content` is the primary input while `opacity` and `fill` appear only in the Properties panel by default, keeping the graph uncluttered.
|
||||
The input names are shown in the graph when an input is exposed (with a dot in the properties panel). The default input is used when a node is first created or when a link is disconnected. An input is comprised from a `TaggedValue` (allowing serialization of a dynamic type with serde) in addition to an exposed boolean, which defines if the input is shown as a dot in the node graph UI by default. In the opacity node, the "Color" input is shown but the "Factor" input is hidden from the graph by default, allowing for a less cluttered graph.
|
||||
|
||||
The Properties panel is generated from the same signature, which can be seen by selecting the Opacity node in the graph. A number parameter becomes a number input whose bounds and slider come from `#[soft]`, `#[hard]`, and `#[range]` (see [Additional Macro Options](#additional-macro-options)), or from a typedef such as `Percentage`, which stands for a 0 to 100 `%` slider. A `bool` becomes a checkbox and a `ChoiceType` enum becomes a dropdown. When the generated widget isn't right, `#[widget(ParsedWidgetOverride::Hidden)]` hides it and `#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]` names a hand-written widget function in `node_properties.rs`, which is how the Opacity node pairs each percentage with the checkbox that enables it.
|
||||
The properties field is a function that defines a number input, which can be seen by selecting the opacity node in the graph. The code for this property is shown below:
|
||||
|
||||
```rs
|
||||
pub fn multiply_opacity(document_node: &DocumentNode, node_id: NodeId, _context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
let factor = number_widget(document_node, node_id, 1, "Factor", NumberInput::default().min(0.).max(100.).unit("%"), true);
|
||||
|
||||
vec![LayoutGroup::Row { widgets: factor }]
|
||||
}
|
||||
```
|
||||
|
||||
## Graphene (proto node executor)
|
||||
|
||||
The node crates under `node-graph/nodes/`, such as the Graphene core crate (`gcore/`) and the Graphene standard library (`gstd/`), are where the implementations of nodes are located.
|
||||
The graphene crate (found in `gcore/`) and the graphene standard library (found in `gstd/`) is where actual implementation for nodes are located.
|
||||
|
||||
Implementing a node is done by defining a `struct` implementing the `Node` trait. The `Node` trait has a required function named `eval` that takes one generic input. A sample implementation for an opacity node acting on a color is seen below:
|
||||
|
||||
@@ -79,44 +94,17 @@ fn test_opacity_node() {
|
||||
}
|
||||
```
|
||||
|
||||
The `graphene_core::value::CopiedNode` is a node that, when evaluated, copies `10_f64` and returns it.
|
||||
The `graphene_core::value::CopiedNode` is a node that, when evaluated, copies `10_f32` and returns it.
|
||||
|
||||
## Creating a new node
|
||||
|
||||
Instead of manually implementing the `Node` trait with complex generics, one can use the `node` macro, which is applied to a function like `opacity`. This generates the struct, its `Node` implementation, the node registry entries, the document node definition, and the Properties panel entries. The first parameter is the evaluation context and the second is the primary input, and each parameter rides its wire as an `Item<T>` (one value with its attributes) or a `List<T>` (a whole list). Doc comments on the function and its parameters become the tooltips shown in the editor (omitted here). This is the Opacity node as it exists in `node-graph/nodes/blending/src/lib.rs`:
|
||||
Instead of manually implementing the `Node` trait with complex generics, one can use the `node` macro, which can be applied to a function like `opacity`. This will generate the struct, implementation, node_registry entry, document node definition and properties panel entries:
|
||||
|
||||
```rs
|
||||
#[node_macro::node(category("Blending"))]
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
content: Item<T>,
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
#[default(true)]
|
||||
has_opacity: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[default(100.)]
|
||||
opacity: Item<Percentage>,
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_fill: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[default(100.)]
|
||||
fill: Item<Percentage>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
let (has_opacity, opacity, has_fill, fill) = (*has_opacity.element(), *opacity.element(), *has_fill.element(), *fill.element());
|
||||
|
||||
if has_opacity {
|
||||
let multiplied = content.attribute_cloned_or(ATTR_OPACITY, 1.) * (opacity / 100.);
|
||||
content.set_attribute(ATTR_OPACITY, multiplied);
|
||||
}
|
||||
|
||||
if has_fill {
|
||||
let multiplied = content.attribute_cloned_or(ATTR_OPACITY_FILL, 1.) * (fill / 100.);
|
||||
content.set_attribute(ATTR_OPACITY_FILL, multiplied);
|
||||
}
|
||||
|
||||
content
|
||||
#[node_macro::node(category("Raster: Adjustments"))]
|
||||
fn opacity(_input: (), #[default(424242)] color: Color, #[range] #[soft(0..100)] opacity_multiplier: f64) -> Color {
|
||||
let opacity_multiplier = opacity_multiplier as f32 / 100.;
|
||||
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -133,7 +121,44 @@ When the document graph is executed, the following steps occur:
|
||||
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
|
||||
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
|
||||
|
||||
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize and monitor nodes.
|
||||
The definition for the constructor of a node that applies the opacity transformation to each pixel of an image:
|
||||
```rs
|
||||
(
|
||||
// Matches against the string defined in the document node.
|
||||
ProtoNodeIdentifier::new("graphene_core::raster::OpacityNode"),
|
||||
// This function is run when converting the `ProtoNode` struct into the desired struct.
|
||||
|args| {
|
||||
Box::pin(async move {
|
||||
// Creates an instance of the struct that defines the node.
|
||||
let node = construct_node!(args, graphene_core::raster::OpacityNode<_>, [f64]).await;
|
||||
// Create a new map image node, that calls the `node` for each pixel.
|
||||
let map_node = graphene_std::raster::MapImageNode::new(graphene_core::value::ValueNode::new(node));
|
||||
// Wraps this in a type erased future `Box<Pin<dyn core::future::Future<Output = T> + 'n>>` - this allows it to work with async.
|
||||
let map_node = graphene_std::any::FutureWrapperNode::new(map_node);
|
||||
// The `DynAnyNode` downcasts its input from a `Box<dyn DynAny>` i.e. dynamically typed, to the desired statically typed input value. It then runs the wrapped node and converts the result back into a dynamically typed `Box<dyn DynAny>`.
|
||||
let any: DynAnyNode<Image<Color>, _, _> = graphene_std::any::DynAnyNode::new(graphene_core::value::ValueNode::new(map_node));
|
||||
// Nodes are stored as type erased, which means they are `Box<dyn NodeIo + Node>`. This allows us to create dynamic graphs, using dynamic dispatch so we do not have to know all node combinations at compile time.
|
||||
any.into_type_erased()
|
||||
})
|
||||
},
|
||||
// Defines the call argument, return value, and inputs.
|
||||
NodeIOTypes::new(concrete!(Image<Color>), concrete!(Image<Color>), vec![fn_type!((), f64)]),
|
||||
),
|
||||
```
|
||||
|
||||
Nodes in the borrow stack take a `Box<dyn DynAny>` as input and output another `Box<dyn DynAny>`, to allow for any type. To use a specific type, we must downcast the values that have been passed in.
|
||||
However the `OpacityNode` only works on one pixel at a time, so we first insert a `MapImageNode` to call the `OpacityNode` for every pixel in the image.
|
||||
Finally we call `.into_type_erased()` on the result and that is inserted into the borrow stack.
|
||||
|
||||
We also need to add an implementation so that the user can change the opacity of just a single color. To simplify this process for raster nodes, a `raster_node!` macro is available which can simplify the definition of the opacity node to:
|
||||
```rs
|
||||
raster_node!(graphene_core::raster::OpacityNode<_>, params: [f64]),
|
||||
```
|
||||
|
||||
There is also the more general `register_node!` for nodes that do not need to run per pixel.
|
||||
```rs
|
||||
register_node!(graphene_core::transform_nodes::SetTransformNode<_>, input: Vector, params: [DAffine2]),
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
|
||||
@@ -1311,7 +1311,7 @@ mod test {
|
||||
(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)],
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0), NodeInput::import(concrete!(u32), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1341,7 +1341,7 @@ mod test {
|
||||
(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)],
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0), NodeInput::import(concrete!(u32), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1400,7 +1400,7 @@ mod test {
|
||||
nodes: [(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::value(TaggedValue::I64(2), false)],
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0), NodeInput::value(TaggedValue::U32(2), false)],
|
||||
implementation: DocumentNodeImplementation::Network(add_network()),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1422,7 +1422,7 @@ mod test {
|
||||
fn resolve_proto_node_add() {
|
||||
let document_node = DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
call_argument: concrete!(i64),
|
||||
call_argument: concrete!(u32),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1430,7 +1430,7 @@ mod test {
|
||||
let proto_node = document_node.resolve_proto_node();
|
||||
let reference = ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"),
|
||||
call_argument: concrete!(i64),
|
||||
call_argument: concrete!(u32),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1447,7 +1447,7 @@ mod test {
|
||||
NodeId(10),
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"),
|
||||
call_argument: concrete!(i64),
|
||||
call_argument: concrete!(u32),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(14)]),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(1), NodeId(0)]),
|
||||
@@ -1479,7 +1479,7 @@ mod test {
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
|
||||
call_argument: concrete!(core_types::Context),
|
||||
construction_args: ConstructionArgs::Value(TaggedValue::I64(2).into()),
|
||||
construction_args: ConstructionArgs::Value(TaggedValue::U32(2).into()),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(1), NodeId(4)]),
|
||||
inputs_source: HashMap::new(),
|
||||
@@ -1509,7 +1509,7 @@ mod test {
|
||||
(
|
||||
NodeId(10),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::node(NodeId(14), 0)],
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0), NodeInput::node(NodeId(14), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
|
||||
original_location: OriginalLocation {
|
||||
inputs_source: [(Source { node: vec![], index: 0 }, 1)].into(),
|
||||
@@ -1522,7 +1522,7 @@ mod test {
|
||||
(
|
||||
NodeId(14),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::I64(2), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::U32(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(4)]),
|
||||
@@ -1559,7 +1559,7 @@ mod test {
|
||||
NodeId(10),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(14), 0)],
|
||||
call_argument: concrete!(i64),
|
||||
call_argument: concrete!(u32),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(1), NodeId(0)]),
|
||||
@@ -1573,7 +1573,7 @@ mod test {
|
||||
(
|
||||
NodeId(14),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::I64(2), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::U32(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(1), NodeId(4)]),
|
||||
@@ -1612,7 +1612,7 @@ mod test {
|
||||
(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0)],
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1620,7 +1620,7 @@ mod test {
|
||||
(
|
||||
NodeId(2),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 1)],
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -519,11 +519,10 @@ tagged_value! {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
#[serde(alias = "F32")] // TODO: Eventually remove this document upgrade code
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_i64")] // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "U32", alias = "U64")]
|
||||
I64(i64),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
#[serde(alias = "IVec2", alias = "UVec2", alias = "Vec2")]
|
||||
@@ -604,7 +603,9 @@ impl TaggedValue {
|
||||
match self {
|
||||
TaggedValue::None => "()".to_string(),
|
||||
TaggedValue::String(x) => format!("\"{x}\""),
|
||||
TaggedValue::I64(x) => x.to_string() + "_i64",
|
||||
TaggedValue::U32(x) => x.to_string() + "_u32",
|
||||
TaggedValue::U64(x) => x.to_string() + "_u64",
|
||||
TaggedValue::F32(x) => x.to_string() + "_f32",
|
||||
TaggedValue::F64(x) => x.to_string() + "_f64",
|
||||
TaggedValue::Bool(x) => x.to_string(),
|
||||
TaggedValue::BlendMode(x) => "BlendMode::".to_string() + &x.to_string(),
|
||||
@@ -701,7 +702,9 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<()>() => TaggedValue::None,
|
||||
() if ty == TypeId::of::<String>() => TaggedValue::String(string.into()),
|
||||
() if ty == TypeId::of::<f64>() => FromStr::from_str(string).map(TaggedValue::F64).ok()?,
|
||||
() if ty == TypeId::of::<i64>() => FromStr::from_str(string).map(TaggedValue::I64).ok()?,
|
||||
() if ty == TypeId::of::<f32>() => FromStr::from_str(string).map(TaggedValue::F32).ok()?,
|
||||
() if ty == TypeId::of::<u64>() => FromStr::from_str(string).map(TaggedValue::U64).ok()?,
|
||||
() 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()?,
|
||||
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
|
||||
@@ -722,6 +725,13 @@ impl TaggedValue {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_u32(&self) -> u32 {
|
||||
match self {
|
||||
TaggedValue::U32(x) => *x,
|
||||
_ => panic!("Passed value is not of type u32"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored form of a paint input's red-slash "no paint" choice: the `Item<Graphic>` type default, materializing as a `Graphic::None` paint.
|
||||
pub fn no_paint() -> Self {
|
||||
TaggedValue::TypeDefault(item!(Graphic))
|
||||
@@ -854,7 +864,9 @@ impl Display for TaggedValue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
TaggedValue::String(x) => f.write_str(x),
|
||||
TaggedValue::I64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::U32(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::U64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::F32(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::F64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::Bool(x) => f.write_fmt(format_args!("{x}")),
|
||||
_ => panic!("Cannot convert to string"),
|
||||
@@ -1153,35 +1165,3 @@ mod gradient_shape_migration {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
#[cfg(test)]
|
||||
mod retired_numeric_variants {
|
||||
use super::*;
|
||||
|
||||
fn load(payload: serde_json::Value) -> TaggedValue {
|
||||
deserialize_tagged_value_with_legacy_migration(payload)
|
||||
.expect("The numeric payload should deserialize")
|
||||
.into_inner()
|
||||
.as_ref()
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_tags_read_as_integers() {
|
||||
assert_eq!(load(serde_json::json!({ "U32": 7 })), TaggedValue::I64(7));
|
||||
assert_eq!(load(serde_json::json!({ "U64": 9 })), TaggedValue::I64(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsigned_value_past_the_signed_range_saturates() {
|
||||
assert_eq!(load(serde_json::json!({ "U64": u64::MAX })), TaggedValue::I64(i64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_float_tag_reads_the_digits_it_stored() {
|
||||
// The stored text is what the author chose, so reading it as f64 beats widening the 32-bit value it parsed into
|
||||
assert_eq!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::F64(2.2));
|
||||
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::F64(2.2_f32 as f64));
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ impl Default for ProtoNode {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
identifier: graphene_core::ops::passthrough::IDENTIFIER,
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::I64(0).into()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(0).into()),
|
||||
call_argument: concrete!(()),
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
@@ -1059,7 +1059,7 @@ mod test {
|
||||
// If this assert fails: These NodeIds seem to be changing when you modify TaggedValue, just update them.
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec![NodeId(7074930193456627328), NodeId(651950451264872860), NodeId(15983493604836528424), NodeId(2458326405488235061)]
|
||||
vec![NodeId(9617677014563055585), NodeId(3306304180790283913), NodeId(4482673701109291121), NodeId(1535890178157254933)]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1109,7 +1109,7 @@ mod test {
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("value"),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::I64(2).into()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(2).into()),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
|
||||
@@ -36,7 +36,8 @@ pub enum RuntimeDelta {
|
||||
input: NodeInput,
|
||||
},
|
||||
/// A node's whole input list, which is how a change to the number or order of its slots is
|
||||
/// expressed, since `SetInput` addresses one index and cannot move the others.
|
||||
/// expressed, since `SetInput` addresses one index and cannot move the others. Everything nested
|
||||
/// under the node is left alone, unlike `ReplaceNode`.
|
||||
SetInputs {
|
||||
network_path: Vec<NodeId>,
|
||||
node_id: NodeId,
|
||||
|
||||
@@ -9,13 +9,13 @@ use graphene_std::vector::Vector;
|
||||
#[test]
|
||||
fn push_node_sync() {
|
||||
let mut tree = BorrowTree::default();
|
||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::I64(2_i64).into()), vec![]);
|
||||
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<i64>> = futures::executor::block_on(tree.eval(NodeId(0), ()));
|
||||
assert_eq!(result.map(|item| *item.element()), Some(2_i64));
|
||||
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.
|
||||
|
||||
@@ -58,14 +58,20 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Footprint>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<u32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<u64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u32>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DVec2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
@@ -125,10 +131,13 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
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]),
|
||||
@@ -324,6 +333,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
macro_rules! ranked_value_types {
|
||||
($register:ident) => {
|
||||
$register!(
|
||||
i32,
|
||||
i64,
|
||||
BlendMode,
|
||||
StrokeJoin,
|
||||
@@ -384,6 +394,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Gradient,
|
||||
String,
|
||||
f64,
|
||||
f32,
|
||||
u64,
|
||||
u32,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
bool,
|
||||
@@ -414,8 +427,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
f32,
|
||||
f64,
|
||||
i64,
|
||||
u32,
|
||||
u64,
|
||||
bool,
|
||||
String,
|
||||
DVec2,
|
||||
@@ -441,13 +456,13 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
}};
|
||||
}
|
||||
node_types.extend(bundle_adapter_nodes!(
|
||||
// Numeric family
|
||||
bool,
|
||||
f32,
|
||||
f64,
|
||||
i64,
|
||||
u32,
|
||||
u64,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
// Graphic family
|
||||
Graphic,
|
||||
Raster<CPU>,
|
||||
Vector,
|
||||
@@ -530,10 +545,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
}};
|
||||
}
|
||||
// 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: [i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: i64, to: [f64, DVec2, String]));
|
||||
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]));
|
||||
// A bool embeds in number types as exactly 0 or 1 and formats as text as true or false, but deliberately has no `DVec2` row, which would silently turn a stray bool wire into (1., 1.)
|
||||
node_types.extend(convert_adapter_wildcard!(from: bool, to: [f64, i64, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: bool, to: [f64, f32, u32, u64, i32, i64, String]));
|
||||
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
||||
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
||||
@@ -548,7 +567,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
}
|
||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
attribute_value_node!(Item<f64>),
|
||||
attribute_value_node!(Item<i64>),
|
||||
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>),
|
||||
|
||||
@@ -113,10 +113,10 @@ pub const ATTR_FONT: &str = "font";
|
||||
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 (`f64`, implicit default `0.`, which leaves the width unbounded).
|
||||
/// 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
|
||||
/// (`f64`, implicit default `0.`, which leaves the height unbounded).
|
||||
/// (`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";
|
||||
|
||||
@@ -124,24 +124,6 @@ pub fn migrate_to_f64_array<'de, D: serde::Deserializer<'de>>(deserializer: D) -
|
||||
})
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Reads an integer stored by the retired unsigned variants, whose upper range reached past [`i64::MAX`] and saturates there.
|
||||
pub fn migrate_to_i64<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
|
||||
use serde::Deserialize;
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", serde(untagged))]
|
||||
enum IntegerFormat {
|
||||
Signed(i64),
|
||||
Unsigned(u64),
|
||||
}
|
||||
|
||||
Ok(match IntegerFormat::deserialize(deserializer)? {
|
||||
IntegerFormat::Signed(value) => value,
|
||||
IntegerFormat::Unsigned(value) => i64::try_from(value).unwrap_or(i64::MAX),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses a number from text, reading infinity as `∞` (optionally signed) as well as the `inf` and `infinity` spellings.
|
||||
pub fn parse_f64(text: &str) -> Option<f64> {
|
||||
let (negative, unsigned) = match text.strip_prefix('-') {
|
||||
|
||||
@@ -75,37 +75,30 @@ pub trait FromAnchorPosition {
|
||||
fn from_anchor_position(position: DVec2) -> Self;
|
||||
}
|
||||
|
||||
/// Implements the [`Convert`] trait between Rust's primitive numeric types. A float narrowing to an integer rounds to the
|
||||
/// nearest whole number (half away from zero), the graph's one Number to Integer rule, so float noise like 5.999999 reaches
|
||||
/// an integer connector as 6 rather than truncating to 5. Every other pair is a plain `as` cast.
|
||||
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
|
||||
macro_rules! impl_convert {
|
||||
($from:ty => $to:ty) => {
|
||||
($from:ty, $to:ty) => {
|
||||
impl Convert<$to, ()> for $from {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self as $to
|
||||
}
|
||||
}
|
||||
};
|
||||
($from:ty => round $to:ty) => {
|
||||
impl Convert<$to, ()> for $from {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self.round() as $to
|
||||
}
|
||||
}
|
||||
};
|
||||
(from_integers $to:ty) => {
|
||||
impl_convert!(i8 => $to);
|
||||
impl_convert!(u8 => $to);
|
||||
impl_convert!(u16 => $to);
|
||||
impl_convert!(i16 => $to);
|
||||
impl_convert!(i32 => $to);
|
||||
impl_convert!(u32 => $to);
|
||||
impl_convert!(i64 => $to);
|
||||
impl_convert!(u64 => $to);
|
||||
impl_convert!(i128 => $to);
|
||||
impl_convert!(u128 => $to);
|
||||
impl_convert!(isize => $to);
|
||||
impl_convert!(usize => $to);
|
||||
($to:ty) => {
|
||||
impl_convert!(f32, $to);
|
||||
impl_convert!(f64, $to);
|
||||
impl_convert!(i8, $to);
|
||||
impl_convert!(u8, $to);
|
||||
impl_convert!(u16, $to);
|
||||
impl_convert!(i16, $to);
|
||||
impl_convert!(i32, $to);
|
||||
impl_convert!(u32, $to);
|
||||
impl_convert!(i64, $to);
|
||||
impl_convert!(u64, $to);
|
||||
impl_convert!(i128, $to);
|
||||
impl_convert!(u128, $to);
|
||||
impl_convert!(isize, $to);
|
||||
impl_convert!(usize, $to);
|
||||
|
||||
impl Convert<DVec2, ()> for $to {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
@@ -113,31 +106,21 @@ macro_rules! impl_convert {
|
||||
}
|
||||
}
|
||||
};
|
||||
(float $to:ty) => {
|
||||
impl_convert!(f32 => $to);
|
||||
impl_convert!(f64 => $to);
|
||||
impl_convert!(from_integers $to);
|
||||
};
|
||||
(integer $to:ty) => {
|
||||
impl_convert!(f32 => round $to);
|
||||
impl_convert!(f64 => round $to);
|
||||
impl_convert!(from_integers $to);
|
||||
};
|
||||
}
|
||||
impl_convert!(float f32);
|
||||
impl_convert!(float f64);
|
||||
impl_convert!(integer i8);
|
||||
impl_convert!(integer u8);
|
||||
impl_convert!(integer u16);
|
||||
impl_convert!(integer i16);
|
||||
impl_convert!(integer i32);
|
||||
impl_convert!(integer u32);
|
||||
impl_convert!(integer i64);
|
||||
impl_convert!(integer u64);
|
||||
impl_convert!(integer i128);
|
||||
impl_convert!(integer u128);
|
||||
impl_convert!(integer isize);
|
||||
impl_convert!(integer usize);
|
||||
impl_convert!(f32);
|
||||
impl_convert!(f64);
|
||||
impl_convert!(i8);
|
||||
impl_convert!(u8);
|
||||
impl_convert!(u16);
|
||||
impl_convert!(i16);
|
||||
impl_convert!(i32);
|
||||
impl_convert!(u32);
|
||||
impl_convert!(i64);
|
||||
impl_convert!(u64);
|
||||
impl_convert!(i128);
|
||||
impl_convert!(u128);
|
||||
impl_convert!(isize);
|
||||
impl_convert!(usize);
|
||||
|
||||
/// Implements the [`Convert`] trait from `bool` into each numeric type, embedding `false` and `true` as exactly 0 and 1.
|
||||
/// The reverse direction is deliberately absent: a number only becomes a truth value through an explicit comparison.
|
||||
@@ -153,17 +136,3 @@ macro_rules! impl_convert_from_bool {
|
||||
};
|
||||
}
|
||||
impl_convert_from_bool!(f32, f64, i8, u8, u16, i16, i32, u32, i64, u64, i128, u128, isize, usize);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_float_narrows_to_the_nearest_integer() {
|
||||
let footprint = Footprint::default();
|
||||
assert_eq!(Convert::<i64, ()>::convert(5.999_999_f64, footprint, ()).await, 6, "float noise rounds up to the whole number it meant");
|
||||
assert_eq!(Convert::<i64, ()>::convert(2.5_f64, footprint, ()).await, 3, "ties round away from zero");
|
||||
assert_eq!(Convert::<i64, ()>::convert(-1.5_f64, footprint, ()).await, -2);
|
||||
assert_eq!(Convert::<f64, ()>::convert(7_i64, footprint, ()).await, 7., "an integer widens exactly");
|
||||
}
|
||||
}
|
||||
@@ -522,11 +522,7 @@ pub fn make_type_user_readable(ty: &str) -> String {
|
||||
.replace("DVec2", "Vec2")
|
||||
.replace("IVec2", "Vec2")
|
||||
.replace("UVec2", "Vec2")
|
||||
.replace("&str", "String")
|
||||
// The numeric ladder's rung names label its wires
|
||||
.replace("f64", "Number")
|
||||
.replace("i64", "Integer")
|
||||
.replace("bool", "Bool");
|
||||
.replace("&str", "String");
|
||||
|
||||
rewrite_ranked_type_wrappers(&ty)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
pub mod types {
|
||||
/// 0% - 100%
|
||||
pub type Percentage = f64;
|
||||
/// 0% - 100%
|
||||
pub type PercentageF32 = f32;
|
||||
/// -100% - 100%
|
||||
pub type SignedPercentage = f64;
|
||||
/// -100% - 100%
|
||||
pub type SignedPercentageF32 = f32;
|
||||
/// -180° - 180°
|
||||
pub type Angle = f64;
|
||||
/// -180° - 180°
|
||||
pub type AngleF32 = f32;
|
||||
/// Ends in the unit of x
|
||||
pub type Multiplier = f64;
|
||||
/// Non-negative integer with px unit
|
||||
@@ -15,6 +21,10 @@ pub mod types {
|
||||
pub type Fraction = f64;
|
||||
/// Non-negative number broken into whole and fractional parts
|
||||
pub type Progression = f64;
|
||||
/// Signed integer that's actually a float because we don't handle type conversions very well yet
|
||||
pub type SignedInteger = f64;
|
||||
/// Unsigned integer to be used for random seeds
|
||||
pub type SeedValue = u32;
|
||||
/// DVec2 with px unit
|
||||
pub type PixelSize = glam::DVec2;
|
||||
/// String with one or more than one line
|
||||
|
||||
@@ -3023,8 +3023,8 @@ fn text_item_size_and_transform(item: ItemRef<'_, String>) -> Option<(DVec2, DAf
|
||||
let font_size: f64 = item.attribute_cloned_or(ATTR_FONT_SIZE, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = item.attribute_cloned_or(ATTR_LINE_HEIGHT, 1.2);
|
||||
let letter_spacing: f64 = item.attribute_cloned_or(ATTR_LETTER_SPACING, 0.);
|
||||
let max_width = item.attribute::<f64>(ATTR_MAX_WIDTH).copied().filter(|width| *width > 0.);
|
||||
let max_height = item.attribute::<f64>(ATTR_MAX_HEIGHT).copied().filter(|height| *height > 0.);
|
||||
let max_width: Option<f64> = item.attribute_cloned_or(ATTR_MAX_WIDTH, None);
|
||||
let max_height: Option<f64> = item.attribute_cloned_or(ATTR_MAX_HEIGHT, None);
|
||||
let align: text_nodes::TextAlign = item.attribute_cloned_or_default(ATTR_TEXT_ALIGN);
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
|
||||
@@ -3144,8 +3144,8 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende
|
||||
let font_size: f64 = item.attribute_cloned_or(ATTR_FONT_SIZE, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = item.attribute_cloned_or(ATTR_LINE_HEIGHT, 1.2);
|
||||
let letter_spacing: f64 = item.attribute_cloned_or(ATTR_LETTER_SPACING, 0.);
|
||||
let max_width = item.attribute::<f64>(ATTR_MAX_WIDTH).copied().filter(|width| *width > 0.);
|
||||
let max_height = item.attribute::<f64>(ATTR_MAX_HEIGHT).copied().filter(|height| *height > 0.);
|
||||
let max_width: Option<f64> = item.attribute_cloned_or(ATTR_MAX_WIDTH, None);
|
||||
let max_height: Option<f64> = item.attribute_cloned_or(ATTR_MAX_HEIGHT, None);
|
||||
let letter_tilt: f64 = item.attribute_cloned_or(ATTR_LETTER_TILT, 0.);
|
||||
let align: text_nodes::TextAlign = item.attribute_cloned_or_default(ATTR_TEXT_ALIGN);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -3225,8 +3225,8 @@ fn render_text_item_to_vello(item: ItemRef<'_, String>, scene: &mut Scene, trans
|
||||
let font_size: f64 = item.attribute_cloned_or(ATTR_FONT_SIZE, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = item.attribute_cloned_or(ATTR_LINE_HEIGHT, 1.2);
|
||||
let letter_spacing: f64 = item.attribute_cloned_or(ATTR_LETTER_SPACING, 0.);
|
||||
let max_width = item.attribute::<f64>(ATTR_MAX_WIDTH).copied().filter(|width| *width > 0.);
|
||||
let max_height = item.attribute::<f64>(ATTR_MAX_HEIGHT).copied().filter(|height| *height > 0.);
|
||||
let max_width: Option<f64> = item.attribute_cloned_or(ATTR_MAX_WIDTH, None);
|
||||
let max_height: Option<f64> = item.attribute_cloned_or(ATTR_MAX_HEIGHT, None);
|
||||
let letter_tilt: f64 = item.attribute_cloned_or(ATTR_LETTER_TILT, 0.);
|
||||
let align: text_nodes::TextAlign = item.attribute_cloned_or_default(ATTR_TEXT_ALIGN);
|
||||
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
|
||||
|
||||
@@ -101,6 +101,25 @@ impl From<String> for BoxCorners {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait AsU64 {
|
||||
fn as_u64(&self) -> u64;
|
||||
}
|
||||
impl AsU64 for u32 {
|
||||
fn as_u64(&self) -> u64 {
|
||||
*self as u64
|
||||
}
|
||||
}
|
||||
impl AsU64 for u64 {
|
||||
fn as_u64(&self) -> u64 {
|
||||
*self
|
||||
}
|
||||
}
|
||||
impl AsU64 for f64 {
|
||||
fn as_u64(&self) -> u64 {
|
||||
*self as u64
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::parsing::*;
|
||||
use crate::shader_nodes::STD_FEATURE_GATE;
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{ToTokens, format_ident, quote, quote_spanned};
|
||||
@@ -154,15 +153,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
value => value.regular().expect("a non-node field is a value field").ty.clone(),
|
||||
})
|
||||
.collect();
|
||||
let shader_field_types: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.zip(field_types.iter())
|
||||
.map(|(field, field_type)| match field.ty.regular() {
|
||||
Some(regular) => regular.body_ty().clone(),
|
||||
None => field_type.clone(),
|
||||
})
|
||||
.collect();
|
||||
let has_shader_variant = regular_fields.iter().any(|field| field.ty.regular().is_some_and(|regular| regular.narrowed_body_ty.is_some()));
|
||||
|
||||
// Only regular fields have UI metadata (data fields are internal state)
|
||||
let widget_override: Vec<_> = regular_fields
|
||||
@@ -792,32 +782,11 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
}
|
||||
|
||||
let node_fn = |field_types: &[Type]| {
|
||||
quote! {
|
||||
#(#description_doc_attrs)*
|
||||
#[inline]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#vis #async_keyword fn #fn_name <'n, #(#fn_generics,)*> (#input_ident: #input_type #(, #data_field_idents: #data_field_types)* #(, #field_idents: #field_types)*) -> #output_type #where_clause #body
|
||||
}
|
||||
};
|
||||
// A shader node's fn is emitted twice from the one body: as declared, in f64, for the CPU, and with the f32 parameter
|
||||
// counterparts for the shader build, which cannot represent a 64-bit float. The body casts to f32 only where it meets a Color channel.
|
||||
let node_fn = if has_shader_variant {
|
||||
let cpu_fn = node_fn(&field_types);
|
||||
let shader_fn = node_fn(&shader_field_types);
|
||||
quote! {
|
||||
#[cfg(feature = #STD_FEATURE_GATE)]
|
||||
#cpu_fn
|
||||
|
||||
#[cfg(not(feature = #STD_FEATURE_GATE))]
|
||||
#shader_fn
|
||||
}
|
||||
} else {
|
||||
node_fn(&field_types)
|
||||
};
|
||||
|
||||
Ok(quote! {
|
||||
#node_fn
|
||||
#(#description_doc_attrs)*
|
||||
#[inline]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#vis #async_keyword fn #fn_name <'n, #(#fn_generics,)*> (#input_ident: #input_type #(, #data_field_idents: #data_field_types)* #(, #field_idents: #field_types)*) -> #output_type #where_clause #body
|
||||
|
||||
#cfg
|
||||
#[automatically_derived]
|
||||
|
||||
@@ -329,16 +329,6 @@ pub struct RegularParsedField {
|
||||
pub number_mode_range: bool,
|
||||
pub implementations: Punctuated<Type, Comma>,
|
||||
pub gpu_image: bool,
|
||||
/// Set for a shader node's `f64` or `i64` parameter: `ty` keeps the type it was declared with, which the graph and the
|
||||
/// CPU fn use, while the shader build's fn variant and the GPU uniform take this `f32` or `i32` counterpart.
|
||||
pub narrowed_body_ty: Option<Type>,
|
||||
}
|
||||
|
||||
impl RegularParsedField {
|
||||
/// The type the shader build's fn variant is handed: the 32-bit counterpart of a shader node's declared `f64` or `i64`, otherwise `ty` itself.
|
||||
pub fn body_ty(&self) -> &Type {
|
||||
self.narrowed_body_ty.as_ref().unwrap_or(&self.ty)
|
||||
}
|
||||
}
|
||||
|
||||
/// a param of `impl Node` with `#[implementation(in -> out)]`
|
||||
@@ -608,10 +598,7 @@ pub(crate) fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Resu
|
||||
let fn_generics = input_fn.sig.generics.params.into_iter().collect();
|
||||
let is_async = input_fn.sig.asyncness.is_some();
|
||||
|
||||
let (input, mut fields) = parse_inputs(&input_fn.sig.inputs)?;
|
||||
if matches!(attributes.shader_node, Some(ShaderNodeType::PerPixelAdjust(_))) {
|
||||
narrow_shader_fields(&mut fields)?;
|
||||
}
|
||||
let (input, fields) = parse_inputs(&input_fn.sig.inputs)?;
|
||||
let output_type = parse_output(&input_fn.sig.output)?;
|
||||
let output_element = peel_item(&output_type);
|
||||
let where_clause = input_fn.sig.generics.where_clause;
|
||||
@@ -980,7 +967,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
value_source,
|
||||
implementations,
|
||||
gpu_image,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
name,
|
||||
description,
|
||||
@@ -1015,71 +1001,6 @@ fn parse_node_type(ty: &Type) -> (bool, Option<Type>, Option<Type>) {
|
||||
(false, None, None)
|
||||
}
|
||||
|
||||
/// A `PerPixelAdjust` shader node is declared with the catalog's `f64` and `i64` parameters, and its fn is emitted twice
|
||||
/// from the one body: as declared for the CPU, and with the `f32` and `i32` counterparts recorded here for the shader
|
||||
/// build, which cannot represent a 64-bit number. Declaring `f32` or `i32` directly is refused so the node's definition
|
||||
/// only ever speaks the graph's types.
|
||||
fn narrow_shader_fields(fields: &mut [ParsedField]) -> syn::Result<()> {
|
||||
for field in fields.iter_mut() {
|
||||
let Some(regular) = field.ty.regular() else { continue };
|
||||
let declared = regular.ty.clone();
|
||||
|
||||
if peel_list(&declared).is_some() {
|
||||
return Err(Error::new_spanned(
|
||||
&declared,
|
||||
"A per-pixel shader node cannot take a `List` parameter, since its values ride in a uniform buffer and the shader cannot allocate; declare an `Item` instead",
|
||||
));
|
||||
}
|
||||
|
||||
let element = peel_item(&declared).unwrap_or_else(|| declared.clone());
|
||||
if ["f32", "i32", "PercentageF32", "SignedPercentageF32", "AngleF32"].iter().any(|name| is_primitive_type(&element, name)) {
|
||||
return Err(Error::new_spanned(
|
||||
&declared,
|
||||
"A shader node's parameters are declared as `f64` or `i64`, the graph's Number and Integer types; the macro narrows them to the `f32` or `i32` the shader computes with",
|
||||
));
|
||||
}
|
||||
|
||||
// The registry's f64 typedefs, like `Percentage` and `Angle`, spell the graph's Number by its widget meaning and narrow the same way
|
||||
let spells_f64 = ["f64", "Percentage", "SignedPercentage", "Angle", "Multiplier", "PixelLength", "Length", "Fraction", "Progression"];
|
||||
let counterpart: Type = if spells_f64.iter().any(|name| is_primitive_type(&element, name)) {
|
||||
parse_quote!(f32)
|
||||
} else if is_primitive_type(&element, "i64") {
|
||||
parse_quote!(i32)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let body_ty = if peel_item(&declared).is_some() {
|
||||
replace_wrapper_element(&declared, counterpart)
|
||||
} else {
|
||||
counterpart
|
||||
};
|
||||
|
||||
let mut regular = regular.clone();
|
||||
regular.narrowed_body_ty = Some(body_ty);
|
||||
field.ty = ParsedFieldType::classify(regular);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Swaps the element type inside a wrapper like `Item<T>`, keeping the wrapper's path as it was written.
|
||||
fn replace_wrapper_element(ty: &Type, element: Type) -> Type {
|
||||
let mut ty = ty.clone();
|
||||
if let Type::Path(type_path) = &mut ty
|
||||
&& let Some(segment) = type_path.path.segments.last_mut()
|
||||
&& let syn::PathArguments::AngleBracketed(arguments) = &mut segment.arguments
|
||||
&& let Some(syn::GenericArgument::Type(inner)) = arguments.args.first_mut()
|
||||
{
|
||||
*inner = element;
|
||||
}
|
||||
ty
|
||||
}
|
||||
|
||||
fn is_primitive_type(ty: &Type, name: &str) -> bool {
|
||||
let Type::Path(type_path) = ty else { return false };
|
||||
type_path.path.segments.last().is_some_and(|segment| segment.ident == name)
|
||||
}
|
||||
|
||||
fn is_integer_type(ty: &Type) -> bool {
|
||||
let Type::Path(type_path) = ty else { return false };
|
||||
let Some(segment) = type_path.path.segments.last() else { return false };
|
||||
@@ -1293,7 +1214,6 @@ mod tests {
|
||||
number_mode_range: false,
|
||||
implementations: Punctuated::new(),
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -1382,7 +1302,6 @@ mod tests {
|
||||
number_mode_range: false,
|
||||
implementations: Punctuated::new(),
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -1452,7 +1371,6 @@ mod tests {
|
||||
number_mode_range: false,
|
||||
implementations: Punctuated::new(),
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -1525,7 +1443,6 @@ mod tests {
|
||||
p
|
||||
},
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -1600,7 +1517,6 @@ mod tests {
|
||||
number_mode_range: true,
|
||||
implementations: Punctuated::new(),
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -1683,7 +1599,6 @@ mod tests {
|
||||
number_mode_range: false,
|
||||
implementations: Punctuated::new(),
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -1846,54 +1761,4 @@ mod tests {
|
||||
// verify that the error span is the one we specified
|
||||
assert_eq!(error.span().start(), problem_span.start());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shader_node_parameters_narrow_for_the_body() {
|
||||
let attr = quote!(category("Raster: Adjustment"), shader_node(PerPixelAdjust));
|
||||
let input = quote!(
|
||||
fn adjust<T: Adjust<Color>>(_: impl Ctx, #[gpu_image] image: Item<T>, amount: Item<f64>, scale: f64, steps: Item<i64>) -> Item<T> {
|
||||
image
|
||||
}
|
||||
);
|
||||
let parsed = parse_node_fn(attr.clone(), input).unwrap();
|
||||
|
||||
let types = |index: usize| {
|
||||
let regular = parsed.fields[index].ty.regular().unwrap();
|
||||
let body = regular.narrowed_body_ty.as_ref().map(|ty| ty.to_token_stream().to_string());
|
||||
(regular.ty.to_token_stream().to_string(), body)
|
||||
};
|
||||
assert_eq!(types(0), ("Item < T >".to_string(), None), "the image parameter is left alone");
|
||||
assert_eq!(
|
||||
types(1),
|
||||
("Item < f64 >".to_string(), Some("Item < f32 >".to_string())),
|
||||
"an Item<f64> stays on the wire and reaches the body as Item<f32>"
|
||||
);
|
||||
assert_eq!(types(2), ("f64".to_string(), Some("f32".to_string())), "a bare f64 reaches the body as f32");
|
||||
assert_eq!(
|
||||
types(3),
|
||||
("Item < i64 >".to_string(), Some("Item < i32 >".to_string())),
|
||||
"an Item<i64> stays on the wire and reaches the body as Item<i32>"
|
||||
);
|
||||
|
||||
let declared_f32 = quote!(
|
||||
fn adjust<T: Adjust<Color>>(_: impl Ctx, #[gpu_image] image: Item<T>, amount: Item<f32>) -> Item<T> {
|
||||
image
|
||||
}
|
||||
);
|
||||
assert!(parse_node_fn(attr.clone(), declared_f32).is_err(), "a shader node must not declare f32 itself");
|
||||
|
||||
let declared_i32 = quote!(
|
||||
fn adjust<T: Adjust<Color>>(_: impl Ctx, #[gpu_image] image: Item<T>, steps: Item<i32>) -> Item<T> {
|
||||
image
|
||||
}
|
||||
);
|
||||
assert!(parse_node_fn(attr.clone(), declared_i32).is_err(), "a shader node must not declare i32 itself");
|
||||
|
||||
let declared_list = quote!(
|
||||
fn adjust<T: Adjust<Color>>(_: impl Ctx, #[gpu_image] image: Item<T>, amounts: List<f64>) -> Item<T> {
|
||||
image
|
||||
}
|
||||
);
|
||||
assert!(parse_node_fn(attr, declared_list).is_err(), "a uniform cannot carry a List");
|
||||
}
|
||||
}
|
||||
@@ -36,8 +36,6 @@ pub(crate) enum ShaderNodeType {
|
||||
/// recursively generating more gpu nodes. But it still counts as a gpu node and will get the
|
||||
/// `#[cfg(feature = "std")]` feature gate around it's impl.
|
||||
ShaderNode,
|
||||
/// A per-pixel color adjustment compiled to a fragment shader. Its parameters are declared `f64` and `i64` like the rest
|
||||
/// of the catalog, and the fn is emitted a second time with their `f32` and `i32` counterparts for the shader build.
|
||||
PerPixelAdjust(PerPixelAdjust),
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::crate_ident::CrateIdent;
|
||||
use crate::parsing::{Input, NodeFnAttributes, ParsedField, ParsedFieldType, ParsedNodeFn, ParsedValueSource, RegularParsedField, peel_item};
|
||||
use crate::parsing::{Input, NodeFnAttributes, ParsedField, ParsedFieldType, ParsedNodeFn, ParsedValueSource, RegularParsedField};
|
||||
use crate::shader_nodes::{SHADER_NODES_FEATURE_GATE, ShaderCodegen, ShaderNodeType, ShaderTokens};
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
@@ -42,17 +42,13 @@ impl ShaderCodegen for PerPixelAdjust {
|
||||
ident: Cow::Owned(format_ident!("image_{}", &ident.ident)),
|
||||
ty: quote!(Image2d),
|
||||
item_wrapped: element_ty.is_some(),
|
||||
narrowed: false,
|
||||
param_type: ParamType::Image { binding: 0 },
|
||||
})
|
||||
} else {
|
||||
// The uniform holds the 32-bit types the shader computes with, so a parameter declared f64 or i64 takes its counterpart here
|
||||
let body_ty = regular.body_ty();
|
||||
Ok(Param {
|
||||
ident: Cow::Borrowed(&ident.ident),
|
||||
item_wrapped: element_ty.is_some(),
|
||||
narrowed: regular.narrowed_body_ty.is_some(),
|
||||
ty: peel_item(body_ty).unwrap_or_else(|| body_ty.clone()).to_token_stream(),
|
||||
ty: element_ty.map(|element_ty| element_ty.to_token_stream()).unwrap_or_else(|| regular.ty.to_token_stream()),
|
||||
param_type: ParamType::Uniform,
|
||||
})
|
||||
}
|
||||
@@ -147,22 +143,13 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
ParamType::Uniform => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// Ranked connectors compile against the no_std `Item` stand-in on the GPU, so wrapping and unwrapping here is free.
|
||||
// A narrowed uniform casts to whichever width the fn variant being compiled takes: f32 for the shader, f64 on the CPU.
|
||||
// Ranked connectors compile against the no_std `Item` stand-in on the GPU, so wrapping and unwrapping here is free
|
||||
let call_args = self
|
||||
.params
|
||||
.iter()
|
||||
.map(|param| {
|
||||
let Param {
|
||||
ident,
|
||||
param_type,
|
||||
item_wrapped,
|
||||
narrowed,
|
||||
..
|
||||
} = param;
|
||||
.map(|Param { ident, param_type, item_wrapped, .. }| {
|
||||
let bare_value = match param_type {
|
||||
ParamType::Image { .. } => quote!(Color::from_vec4(#ident.fetch_with(texel_coord, lod(0)))),
|
||||
ParamType::Uniform if *narrowed => quote!(uniform.#ident as _),
|
||||
ParamType::Uniform => quote!(uniform.#ident),
|
||||
};
|
||||
if *item_wrapped { quote!(Item::new_from_element(#bare_value)) } else { bare_value }
|
||||
@@ -232,10 +219,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
..regular.clone()
|
||||
})
|
||||
} else {
|
||||
ParsedFieldType::classify(RegularParsedField {
|
||||
narrowed_body_ty: None,
|
||||
..regular.clone()
|
||||
})
|
||||
f.ty.clone()
|
||||
};
|
||||
Ok(ParsedField { pat_ident, ty, ..f.clone() })
|
||||
})
|
||||
@@ -265,7 +249,6 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
number_mode_range: false,
|
||||
implementations: Default::default(),
|
||||
gpu_image: false,
|
||||
narrowed_body_ty: None,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
@@ -295,15 +278,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
ParamType::Image { .. } => None,
|
||||
ParamType::Uniform => {
|
||||
let ident = p.ident.as_ref();
|
||||
let value = if p.item_wrapped { quote!(#ident.into_element()) } else { quote!(#ident) };
|
||||
// A parameter declared f64 or i64 narrows to the shader's 32-bit counterpart as it enters the uniform; an
|
||||
// integer saturates rather than wrapping, matching how the float overflows to infinity instead of flipping
|
||||
let ty = &p.ty;
|
||||
Some(match (p.narrowed, ty.to_string().as_str()) {
|
||||
(true, "i32") => quote!(#ident: (#value).clamp(i32::MIN as _, i32::MAX as _) as i32),
|
||||
(true, _) => quote!(#ident: #value as #ty),
|
||||
(false, _) => quote!(#ident: #value),
|
||||
})
|
||||
Some(if p.item_wrapped { quote!(#ident: #ident.into_element()) } else { quote!(#ident) })
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -377,8 +352,6 @@ struct Param<'a> {
|
||||
ident: Cow<'a, Ident>,
|
||||
ty: TokenStream,
|
||||
item_wrapped: bool,
|
||||
/// Whether the parameter is declared `f64` or `i64` and narrows to the shader's 32-bit counterpart as it enters the uniform.
|
||||
narrowed: bool,
|
||||
param_type: ParamType,
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
let validators: &[fn(&ParsedNodeFn)] = &[
|
||||
// Add more validators here as needed
|
||||
validate_implementations_for_generics,
|
||||
validate_implementations_row_counts,
|
||||
validate_primary_input_expose,
|
||||
validate_min_max,
|
||||
validate_range_slider_bounds,
|
||||
@@ -224,47 +223,6 @@ fn ranked_input_violations(parsed: &ParsedNodeFn) -> Vec<(proc_macro2::Span, Str
|
||||
violations
|
||||
}
|
||||
|
||||
/// Implementations rows pair positionally, so every parameter list must hold the same number of rows.
|
||||
fn validate_implementations_row_counts(parsed: &ParsedNodeFn) {
|
||||
for (span, message) in implementations_row_count_violations(parsed) {
|
||||
emit_error!(span, "{}", message);
|
||||
}
|
||||
}
|
||||
|
||||
fn implementations_row_count_violations(parsed: &ParsedNodeFn) -> Vec<(proc_macro2::Span, String)> {
|
||||
if parsed.attributes.skip_impl {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let field_rows = parsed.fields.iter().filter(|field| !field.is_data_field).map(|field| {
|
||||
let rows = match &field.ty {
|
||||
ParsedFieldType::Node(NodeParsedField { implementations, .. }) => implementations.len(),
|
||||
value => value.regular().expect("a non-node field is a value field").implementations.len(),
|
||||
};
|
||||
(&field.pat_ident, rows)
|
||||
});
|
||||
// An `impl Ctx` input gets one synthesized `Context` row, so the ctx input only counts when written out with more
|
||||
let ctx_rows = (&parsed.input.pat_ident, parsed.input.implementations.len());
|
||||
let rows_per_input: Vec<_> = std::iter::once(ctx_rows).filter(|(_, rows)| *rows > 1).chain(field_rows).collect();
|
||||
let Some(&(longest, most_rows)) = rows_per_input.iter().max_by_key(|(_, rows)| *rows) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
rows_per_input
|
||||
.iter()
|
||||
.filter(|(_, rows)| *rows != 0 && *rows != most_rows)
|
||||
.map(|(pat_ident, rows)| {
|
||||
(
|
||||
pat_ident.span(),
|
||||
format!(
|
||||
"The #[implementations(...)] of `{}` lists {rows} rows while `{}` lists {most_rows}, but rows pair positionally so every list needs the same count",
|
||||
pat_ident.ident, longest.ident
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns whether the type is exactly one of the function's generic parameters, like `T`.
|
||||
fn is_bare_generic(ty: &Type, fn_generics: &[GenericParam]) -> bool {
|
||||
let Type::Path(type_path) = ty else { return false };
|
||||
@@ -644,31 +602,4 @@ mod tests {
|
||||
);
|
||||
assert_eq!(data_field_messages, Vec::<String>::new());
|
||||
}
|
||||
|
||||
fn row_count_violations(input: TokenStream) -> Vec<String> {
|
||||
let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse");
|
||||
implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_without_an_implementations_list_pass_beside_any_length() {
|
||||
let messages = row_count_violations(quote::quote!(
|
||||
fn tag<T>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] list: List<T>, value: impl Node<Context, Output = Item<f64>>, label: Item<String>) -> List<T> {
|
||||
list
|
||||
}
|
||||
));
|
||||
assert_eq!(messages, Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_implementations_row_counts_are_rejected() {
|
||||
let messages = row_count_violations(quote::quote!(
|
||||
fn triple<A, B, C>(_: impl Ctx, #[implementations(f64, u32, DVec2)] a: Item<A>, #[implementations(f64, u32)] b: Item<B>, #[implementations(f64)] c: Item<C>) -> Item<A> {
|
||||
a
|
||||
}
|
||||
));
|
||||
assert_eq!(messages.len(), 2, "{messages:?}");
|
||||
assert!(messages[0].contains("of `b` lists 2 rows while `a` lists 3"), "{messages:?}");
|
||||
assert!(messages[1].contains("of `c` lists 1 rows while `a` lists 3"), "{messages:?}");
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,9 @@ async fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<u32>,
|
||||
Context -> Item<u64>,
|
||||
Context -> Item<f32>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<String>,
|
||||
Context -> Item<DAffine2>,
|
||||
@@ -114,7 +116,9 @@ async fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<u32>,
|
||||
Context -> Item<u64>,
|
||||
Context -> Item<f32>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<String>,
|
||||
Context -> Item<DAffine2>,
|
||||
|
||||
@@ -56,8 +56,16 @@ fn read_number(ctx: impl Ctx + ExtractVarArgs) -> Item<f64> {
|
||||
return item.clone();
|
||||
}
|
||||
|
||||
// An integer list widens to f64, keeping the item's attributes
|
||||
if let Some(item) = var_arg.downcast_ref::<Item<i64>>() {
|
||||
// Numeric lists carry several possible element types, so probe each and widen to f64, keeping the item's attributes
|
||||
if let Some(item) = var_arg.downcast_ref::<Item<f32>>() {
|
||||
let (element, attributes) = item.clone().into_parts();
|
||||
return Item::from_parts(element as f64, attributes);
|
||||
}
|
||||
if let Some(item) = var_arg.downcast_ref::<Item<u32>>() {
|
||||
let (element, attributes) = item.clone().into_parts();
|
||||
return Item::from_parts(element as f64, attributes);
|
||||
}
|
||||
if let Some(item) = var_arg.downcast_ref::<Item<u64>>() {
|
||||
let (element, attributes) = item.clone().into_parts();
|
||||
return Item::from_parts(element as f64, attributes);
|
||||
}
|
||||
@@ -72,14 +80,13 @@ async fn read_position(
|
||||
/// The number of nested loops to traverse outwards (from the innermost loop) to get the position from. The most upstream loop is level 0, and downstream loops add levels.
|
||||
///
|
||||
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
|
||||
#[hard(0..)]
|
||||
loop_level: Item<i64>,
|
||||
loop_level: Item<u32>,
|
||||
) -> Item<DVec2> {
|
||||
let loop_level = *loop_level.element();
|
||||
Item::new_from_element(ctx.try_position().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(DVec2::ZERO))
|
||||
}
|
||||
|
||||
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this index off from the generic math nodes.
|
||||
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
|
||||
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
|
||||
/// Produces the index of the current iteration of a loop by reading from the evaluation context, which is supplied by downstream nodes such as *Repeat*.
|
||||
///
|
||||
@@ -91,8 +98,7 @@ async fn read_index(
|
||||
/// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels.
|
||||
///
|
||||
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
|
||||
#[hard(0..)]
|
||||
loop_level: Item<i64>,
|
||||
loop_level: Item<u32>,
|
||||
) -> Item<f64> {
|
||||
let loop_level = *loop_level.element();
|
||||
Item::new_from_element(ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(0) as f64)
|
||||
|
||||
@@ -16,7 +16,9 @@ async fn context_modification<T>(
|
||||
/// The data to pass through, evaluated with the stripped down context.
|
||||
#[implementations(
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<u32>,
|
||||
Context -> Item<u64>,
|
||||
Context -> Item<f32>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<String>,
|
||||
Context -> Item<DAffine2>,
|
||||
|
||||
@@ -4,7 +4,7 @@ use glam::{DAffine2, DVec2};
|
||||
|
||||
/// Meant for debugging purposes, not general use. Logs the input value to the console and passes it through unchanged.
|
||||
#[node_macro::node(category("Debug"), name("Log to Console"))]
|
||||
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, i64, DVec2, DAffine2, String)] value: Item<T>) -> Item<T> {
|
||||
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: Item<T>) -> Item<T> {
|
||||
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
|
||||
log::debug!("{value:#?}");
|
||||
value
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::{CacheHash, Ctx};
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
use glam::{DVec2, IVec2, UVec2};
|
||||
|
||||
/// Obtains the X or Y component of a vec2.
|
||||
///
|
||||
/// The inverse of this node is **Combine Vec2**, which composes a vec2 from its X and Y components.
|
||||
#[node_macro::node(name("Extract XY"), category("Math: Vec2"))]
|
||||
fn extract_xy(_: impl Ctx, vector: Item<DVec2>, axis: Item<XY>) -> Item<f64> {
|
||||
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: Item<T>, axis: Item<XY>) -> Item<f64> {
|
||||
let vector = vector.into_element();
|
||||
let axis = axis.into_element();
|
||||
|
||||
let result = match axis {
|
||||
XY::X => vector.x,
|
||||
XY::Y => vector.y,
|
||||
XY::X => vector.into().x,
|
||||
XY::Y => vector.into().y,
|
||||
};
|
||||
|
||||
Item::new_from_element(result)
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Mutex;
|
||||
///
|
||||
/// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo), skip_impl)]
|
||||
async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, content: impl Node<I, Output = T>, #[data] cache: Arc<Mutex<Option<(u64, T)>>>) -> T {
|
||||
async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, #[data] cache: Arc<Mutex<Option<(u64, T)>>>, content: impl Node<I, Output = T>) -> T {
|
||||
// Caches the output of a given node called with a specific input.
|
||||
//
|
||||
// A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result.
|
||||
@@ -38,10 +38,10 @@ type MonitorValue<I, T> = Arc<Mutex<Option<Arc<IORecord<I, T>>>>>;
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"), skip_impl)]
|
||||
async fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(
|
||||
input: I,
|
||||
content: impl Node<I, Output = T>,
|
||||
#[allow(clippy::type_complexity)]
|
||||
#[data]
|
||||
io: MonitorValue<I, T>,
|
||||
content: impl Node<I, Output = T>,
|
||||
) -> T {
|
||||
let output = content.eval(input.clone()).await;
|
||||
*io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() }));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
||||
use core_types::registry::types::Angle;
|
||||
use core_types::registry::types::{Angle, SeedValue, SignedInteger};
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
@@ -22,8 +22,10 @@ pub fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -36,14 +38,14 @@ pub fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
|
||||
)]
|
||||
list: T,
|
||||
/// The index of the item to remove, starting from 0 for the first item. Negative indices count backwards from the end of the list, starting from -1 for the last item.
|
||||
index: Item<i64>,
|
||||
index: Item<SignedInteger>,
|
||||
) -> T {
|
||||
let index = index.into_element();
|
||||
let index = index.into_element() as i32;
|
||||
|
||||
if index < 0 {
|
||||
list.omit_index_from_end(usize::try_from(index.unsigned_abs()).unwrap_or(usize::MAX))
|
||||
list.omit_index_from_end(index.unsigned_abs() as usize)
|
||||
} else {
|
||||
list.omit_index(usize::try_from(index).unwrap_or(usize::MAX))
|
||||
list.omit_index(index as usize)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +58,10 @@ pub fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -69,23 +73,23 @@ pub fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
|
||||
)]
|
||||
list: List<T>,
|
||||
/// The index of the item to retrieve, starting from 0 for the first item. Negative indices count backwards from the end of the list, starting from -1 for the last item.
|
||||
index: Item<i64>,
|
||||
index: Item<SignedInteger>,
|
||||
) -> Item<T> {
|
||||
let len = list.len();
|
||||
let index = index.into_element();
|
||||
let index = index.into_element() as i32;
|
||||
let resolved = if index < 0 {
|
||||
let from_end = index.unsigned_abs();
|
||||
if from_end > len as u64 {
|
||||
let from_end = index.unsigned_abs() as usize;
|
||||
if from_end > len {
|
||||
return Item::default();
|
||||
}
|
||||
len - from_end as usize
|
||||
len - from_end
|
||||
} else {
|
||||
index.min(len as i64) as usize
|
||||
index as usize
|
||||
};
|
||||
list.clone_item(resolved).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Keeps chosen items from a list (those corresponding to `true` values) and discards the others (those corresponding to `false` values) based on the *Keep Pattern* `Bool` list. A short pattern is repeated over the remainder of the filtered list, allowing a pattern like `[true, false]` to keep every other item starting from the first. An empty pattern keeps all items.
|
||||
/// Keeps chosen items from a list (those corresponding to `true` values) and discards the others (those corresponding to `false` values) based on the *Keep Pattern* bool list. A short pattern is repeated over the remainder of the filtered list, allowing a pattern like `[true, false]` to keep every other item starting from the first. An empty pattern keeps all items.
|
||||
#[node_macro::node(category("General"))]
|
||||
fn filter<T: Send + Sync + 'static>(
|
||||
_: impl Ctx,
|
||||
@@ -93,8 +97,10 @@ fn filter<T: Send + Sync + 'static>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -126,8 +132,10 @@ fn reverse<T: Send + Sync + 'static>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -151,8 +159,10 @@ fn shift<T: Send + Sync + 'static>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -165,12 +175,12 @@ fn shift<T: Send + Sync + 'static>(
|
||||
)]
|
||||
list: List<T>,
|
||||
/// How many positions to shift each item. Positive values shift items toward the start of the list, negative toward the end.
|
||||
amount: Item<i64>,
|
||||
amount: Item<SignedInteger>,
|
||||
/// Whether items shifted off one end wrap around to the other. When off, they are dropped and the list gets shorter.
|
||||
#[default(true)]
|
||||
wrap: Item<bool>,
|
||||
) -> List<T> {
|
||||
let amount = amount.into_element();
|
||||
let amount = amount.into_element() as i64;
|
||||
let wrap = wrap.into_element();
|
||||
let len = list.len() as i64;
|
||||
if len == 0 {
|
||||
@@ -184,7 +194,7 @@ fn shift<T: Send + Sync + 'static>(
|
||||
} else if amount >= 0 {
|
||||
items.into_iter().skip(amount.min(len) as usize).collect()
|
||||
} else {
|
||||
items.into_iter().take((len + amount.max(-len)) as usize).collect()
|
||||
items.into_iter().take((len + amount).max(0) as usize).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,8 +206,10 @@ fn shuffle<T: Send + Sync + 'static>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -210,13 +222,12 @@ fn shuffle<T: Send + Sync + 'static>(
|
||||
)]
|
||||
list: List<T>,
|
||||
/// Seed to determine the unique variation of the random shuffle ordering. The same seed always produces the same ordering.
|
||||
#[hard(0..)]
|
||||
seed: Item<i64>,
|
||||
seed: Item<SeedValue>,
|
||||
) -> List<T> {
|
||||
let seed = seed.into_element();
|
||||
let mut items: Vec<Item<T>> = list.into_iter().collect();
|
||||
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(seed.into());
|
||||
items.shuffle(&mut rng);
|
||||
|
||||
items.into_iter().collect()
|
||||
@@ -234,16 +245,13 @@ fn number_sequence(
|
||||
step: Item<f64>,
|
||||
/// How many numbers to generate.
|
||||
#[default(10)]
|
||||
#[hard(0..)]
|
||||
count: Item<i64>,
|
||||
count: Item<u32>,
|
||||
) -> List<f64> {
|
||||
let (start, step, count) = (*start.element(), *step.element(), count.into_element());
|
||||
|
||||
(0..count).map(|i| Item::new_from_element(start + step * i as f64)).collect()
|
||||
}
|
||||
|
||||
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall these indices off from the generic math nodes.
|
||||
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
|
||||
/// Counts out the index of each item in a list (0, 1, 2, and so on), producing a list of numbers with one for each item.
|
||||
#[node_macro::node(category("General"))]
|
||||
fn list_indices(
|
||||
@@ -251,11 +259,11 @@ fn list_indices(
|
||||
/// The list whose items are counted.
|
||||
list: ListDyn,
|
||||
/// The number that the count begins from for the first item.
|
||||
start_index: Item<i64>,
|
||||
start_index: Item<SignedInteger>,
|
||||
) -> List<f64> {
|
||||
let start_index = start_index.into_element();
|
||||
|
||||
(0..list.len()).map(|index| Item::new_from_element(start_index as f64 + index as f64)).collect()
|
||||
(0..list.len()).map(|index| Item::new_from_element(start_index + index as f64)).collect()
|
||||
}
|
||||
|
||||
/// Extracts a portion of a list, starting at "Start" and ending before "End".
|
||||
@@ -268,8 +276,10 @@ fn list_slice<T: Send + Sync + 'static>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -282,15 +292,23 @@ fn list_slice<T: Send + Sync + 'static>(
|
||||
)]
|
||||
list: List<T>,
|
||||
/// The index of the first item in the portion. Negative indices count from the end of the list.
|
||||
start: Item<i64>,
|
||||
start: Item<SignedInteger>,
|
||||
/// The index the portion ends before, which is not included. Zero or negative indices count from the end of the list.
|
||||
end: Item<i64>,
|
||||
end: Item<SignedInteger>,
|
||||
) -> List<T> {
|
||||
let (start, end) = (start.into_element(), end.into_element());
|
||||
let total_items = list.len() as i64;
|
||||
let total_items = list.len();
|
||||
|
||||
let start = if start < 0 { (total_items + start).max(0) } else { start.min(total_items) } as usize;
|
||||
let end = if end <= 0 { (total_items + end).max(0) } else { end.min(total_items) } as usize;
|
||||
let start = if start < 0. {
|
||||
total_items.saturating_sub(start.abs() as usize)
|
||||
} else {
|
||||
(start as usize).min(total_items)
|
||||
};
|
||||
let end = if end <= 0. {
|
||||
total_items.saturating_sub(end.abs() as usize)
|
||||
} else {
|
||||
(end as usize).min(total_items)
|
||||
};
|
||||
|
||||
if start >= end {
|
||||
return List::new();
|
||||
@@ -316,12 +334,22 @@ impl ElementOrder for bool {
|
||||
self.cmp(other)
|
||||
}
|
||||
}
|
||||
impl ElementOrder for f32 {
|
||||
fn element_order(&self, other: &Self) -> Ordering {
|
||||
self.total_cmp(other)
|
||||
}
|
||||
}
|
||||
impl ElementOrder for f64 {
|
||||
fn element_order(&self, other: &Self) -> Ordering {
|
||||
self.total_cmp(other)
|
||||
}
|
||||
}
|
||||
impl ElementOrder for i64 {
|
||||
impl ElementOrder for u32 {
|
||||
fn element_order(&self, other: &Self) -> Ordering {
|
||||
self.cmp(other)
|
||||
}
|
||||
}
|
||||
impl ElementOrder for u64 {
|
||||
fn element_order(&self, other: &Self) -> Ordering {
|
||||
self.cmp(other)
|
||||
}
|
||||
@@ -342,17 +370,17 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
|
||||
_: impl Ctx,
|
||||
/// The list of data to reorder.
|
||||
#[implementations(
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f32>, List<f64>, List<u32>, List<u64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f32>, List<f64>, List<u32>, List<u64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f32>, List<f64>, List<u32>, List<u64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
/// The optional list of orderable values, corresponding item-to-item with the input list, to sort by instead of the items' own values.
|
||||
#[expose]
|
||||
#[implementations(
|
||||
List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>,
|
||||
List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>,
|
||||
List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>,
|
||||
List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>, List<f64>,
|
||||
List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>, List<String>,
|
||||
List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>, List<bool>,
|
||||
)]
|
||||
sort_order: List<U>,
|
||||
/// Reverses the sorted list order, following descending order instead of ascending (numbers largest-to-smallest, strings Z-to-A, etc.).
|
||||
@@ -389,8 +417,10 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -405,8 +435,10 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
Context -> List<f32>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<i64>,
|
||||
Context -> List<u32>,
|
||||
Context -> List<u64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
@@ -522,8 +554,10 @@ async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -541,6 +575,7 @@ async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
/// The attribute name (key) to write or replace.
|
||||
name: Item<String>,
|
||||
/// The node that produces the attribute value for each item. Called once per item with the item's index in context.
|
||||
#[implementations(Context -> Item<AttributeValueDyn>)]
|
||||
value: impl Node<'n, Context<'static>, Output = Item<AttributeValueDyn>>,
|
||||
) -> List<T> {
|
||||
let name = name.into_element();
|
||||
@@ -572,7 +607,7 @@ fn read_attribute_vector(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Number` or `Integer` attribute from the input list, outputting each value as an element of a new `Number[]`.
|
||||
/// Reads a named numeric attribute (`f64`, `u64`, or `u32`) from the input list, outputting each value as an element of a new `f64[]`. Integer values are converted to `f64`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_number(
|
||||
_: impl Ctx,
|
||||
@@ -583,14 +618,18 @@ fn read_attribute_number(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let value = content.attribute::<f64>(&name, index).copied().or_else(|| content.attribute::<i64>(&name, index).map(|v| *v as f64));
|
||||
let value = content
|
||||
.attribute::<f64>(&name, index)
|
||||
.copied()
|
||||
.or_else(|| content.attribute::<u64>(&name, index).map(|v| *v as f64))
|
||||
.or_else(|| content.attribute::<u32>(&name, index).map(|v| *v as f64));
|
||||
let Some(value) = value else { continue };
|
||||
result.push(Item::new_from_element(value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Bool` attribute from the input list, outputting each value as an element of a new `Bool[]`.
|
||||
/// Reads a named `bool` attribute from the input list, outputting each value as an element of a new `bool[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_bool(
|
||||
_: impl Ctx,
|
||||
@@ -624,7 +663,7 @@ fn read_attribute_string(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Transform` attribute from the input list, outputting each value as an element of a new `Transform[]`.
|
||||
/// Reads a named `DAffine2` transform attribute from the input list, outputting each value as an element of a new `DAffine2[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_transform(
|
||||
_: impl Ctx,
|
||||
@@ -819,8 +858,10 @@ pub async fn extend<T: 'n + Send + Clone>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -838,8 +879,10 @@ pub async fn extend<T: 'n + Send + Clone>(
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
List<f32>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
@@ -1091,36 +1134,27 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn shift_wraps_items_around() {
|
||||
let forward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(1_i64), Item::new_from_element(true));
|
||||
let forward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(1.), Item::new_from_element(true));
|
||||
assert_eq!(elements(&forward), [2., 3., 4., 1.]);
|
||||
|
||||
let backward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(-1_i64), Item::new_from_element(true));
|
||||
assert_eq!(elements(&backward), [4., 1., 2., 3.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_wraps_by_more_than_the_list_length() {
|
||||
let forward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(5_i64), Item::new_from_element(true));
|
||||
assert_eq!(elements(&forward), [2., 3., 4., 1.], "a wrapping shift past the length keeps rotating");
|
||||
|
||||
let backward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(-5_i64), Item::new_from_element(true));
|
||||
let backward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(-1.), Item::new_from_element(true));
|
||||
assert_eq!(elements(&backward), [4., 1., 2., 3.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_without_wrapping_drops_items() {
|
||||
let dropped_front = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(1_i64), Item::new_from_element(false));
|
||||
let dropped_front = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(1.), Item::new_from_element(false));
|
||||
assert_eq!(elements(&dropped_front), [2., 3., 4.]);
|
||||
|
||||
let dropped_back = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(-1_i64), Item::new_from_element(false));
|
||||
let dropped_back = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(-1.), Item::new_from_element(false));
|
||||
assert_eq!(elements(&dropped_back), [1., 2., 3.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_is_deterministic_and_preserves_elements() {
|
||||
let original = [1., 2., 3., 4., 5., 6., 7., 8.];
|
||||
let first = shuffle((), list_of(original), Item::new_from_element(42_i64));
|
||||
let second = shuffle((), list_of(original), Item::new_from_element(42_i64));
|
||||
let first = shuffle((), list_of(original), Item::new_from_element(42_u32));
|
||||
let second = shuffle((), list_of(original), Item::new_from_element(42_u32));
|
||||
assert_eq!(elements(&first), elements(&second), "the same seed should always produce the same ordering");
|
||||
|
||||
let mut recovered = elements(&first);
|
||||
@@ -1130,34 +1164,34 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn number_sequence_generates_evenly_spaced_numbers() {
|
||||
let sequence = number_sequence((), (), Item::new_from_element(0.), Item::new_from_element(2.), Item::new_from_element(4_i64));
|
||||
let sequence = number_sequence((), (), Item::new_from_element(0.), Item::new_from_element(2.), Item::new_from_element(4_u32));
|
||||
assert_eq!(elements(&sequence), [0., 2., 4., 6.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_indices_counts_each_item() {
|
||||
let indices = list_indices((), ListDyn::from(list_of(["a".to_string(), "b".to_string(), "c".to_string()])), Item::new_from_element(0_i64));
|
||||
let indices = list_indices((), ListDyn::from(list_of(["a".to_string(), "b".to_string(), "c".to_string()])), Item::new_from_element(0.));
|
||||
assert_eq!(elements(&indices), [0., 1., 2.]);
|
||||
|
||||
let from_one = list_indices((), ListDyn::from(list_of(["a".to_string(), "b".to_string(), "c".to_string()])), Item::new_from_element(1_i64));
|
||||
let from_one = list_indices((), ListDyn::from(list_of(["a".to_string(), "b".to_string(), "c".to_string()])), Item::new_from_element(1.));
|
||||
assert_eq!(elements(&from_one), [1., 2., 3.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_slice_takes_the_portion_between_start_and_end() {
|
||||
let portion = list_slice((), list_of([1., 2., 3., 4., 5.]), Item::new_from_element(1_i64), Item::new_from_element(3_i64));
|
||||
let portion = list_slice((), list_of([1., 2., 3., 4., 5.]), Item::new_from_element(1.), Item::new_from_element(3.));
|
||||
assert_eq!(elements(&portion), [2., 3.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_slice_resolves_negative_indices_from_the_end() {
|
||||
let portion = list_slice((), list_of([1., 2., 3., 4., 5.]), Item::new_from_element(-2_i64), Item::new_from_element(0_i64));
|
||||
let portion = list_slice((), list_of([1., 2., 3., 4., 5.]), Item::new_from_element(-2.), Item::new_from_element(0.));
|
||||
assert_eq!(elements(&portion), [4., 5.], "an end of zero reaches through the end of the list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_slice_yields_nothing_when_start_reaches_end() {
|
||||
let portion = list_slice((), list_of([1., 2., 3., 4., 5.]), Item::new_from_element(3_i64), Item::new_from_element(3_i64));
|
||||
let portion = list_slice((), list_of([1., 2., 3., 4., 5.]), Item::new_from_element(3.), Item::new_from_element(3.));
|
||||
assert!(elements(&portion).is_empty());
|
||||
}
|
||||
|
||||
|
||||
@@ -85,10 +85,10 @@ fn text(
|
||||
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
|
||||
}
|
||||
if has_max_width {
|
||||
item.set_attribute(ATTR_MAX_WIDTH, max_width);
|
||||
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
|
||||
}
|
||||
if has_max_height {
|
||||
item.set_attribute(ATTR_MAX_HEIGHT, max_height);
|
||||
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
|
||||
}
|
||||
if align != TextAlign::default() {
|
||||
item.set_attribute(ATTR_TEXT_ALIGN, align);
|
||||
|
||||
+306
-176
@@ -12,46 +12,91 @@ use math_parser::ast;
|
||||
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
|
||||
use math_parser::lexer::Constant;
|
||||
use math_parser::reducer::classify_reducer;
|
||||
use math_parser::value::Value;
|
||||
use math_parser::value::{Number, Value};
|
||||
use rand::{Rng, SeedableRng};
|
||||
use std::ops::{Add, Mul, Rem, Sub};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// A parsed source and its tree, which an invalid source lacks.
|
||||
type ParsedSource = Option<(String, Option<Arc<ast::Node>>)>;
|
||||
/// The struct that stores the context for the maths parser.
|
||||
/// This is currently just limited to supplying `a` and `b` until we add better node graph support and UI for variadic inputs.
|
||||
struct MathNodeContext {
|
||||
a: f64,
|
||||
b: f64,
|
||||
}
|
||||
|
||||
/// The last expression a node parsed, reused while its source stays the same, so a list of thousands of items or a run of
|
||||
/// frames parses once. An invalid source is remembered too, so it is logged once rather than per item.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ParseCache(Arc<Mutex<ParsedSource>>);
|
||||
|
||||
impl ParseCache {
|
||||
/// The parse tree of `source`, or `None` for an invalid expression.
|
||||
fn parse(&self, source: &str) -> Option<Arc<ast::Node>> {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((cached_source, tree)) = cached.as_ref()
|
||||
&& cached_source == source
|
||||
{
|
||||
return tree.clone();
|
||||
impl ValueProvider for MathNodeContext {
|
||||
fn get_value(&self, name: &str) -> Option<Value> {
|
||||
if name.eq_ignore_ascii_case("a") {
|
||||
Some(Value::from_f64(self.a))
|
||||
} else if name.eq_ignore_ascii_case("b") {
|
||||
Some(Value::from_f64(self.b))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
let tree = match ast::Node::try_parse_from_str(source) {
|
||||
Ok(tree) => Some(Arc::new(tree)),
|
||||
Err(error) => {
|
||||
warn!("Invalid expression: `{source}`\n{error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
*cached = Some((source.to_string(), tree.clone()));
|
||||
tree
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a parsed expression with the given variable bindings, logging and returning `None` on failure.
|
||||
fn evaluate_expression(expression: &ast::Node, provider: impl ValueProvider) -> Option<Value> {
|
||||
match expression.eval(&EvalContext::new(provider, NothingMap)) {
|
||||
/// Calculates a mathematical expression with input values "A" and "B".
|
||||
#[node_macro::node(category("Math: Arithmetic"), properties("math_properties"))]
|
||||
fn math<T: num_traits::float::Float>(
|
||||
_: impl Ctx,
|
||||
/// The value of "A" when calculating the expression.
|
||||
#[implementations(f64, f32)]
|
||||
operand_a: Item<T>,
|
||||
/// A math expression that may incorporate "A" and/or "B", such as `sqrt(A + B) - B^2`.
|
||||
#[default("A + B")]
|
||||
expression: Item<String>,
|
||||
/// The value of "B" when calculating the expression.
|
||||
#[implementations(f64, f32)]
|
||||
#[default(1.)]
|
||||
operand_b: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (operand_a, attributes) = operand_a.into_parts();
|
||||
let (expression, operand_b) = (expression.element(), *operand_b.element());
|
||||
|
||||
let node = match ast::Node::try_parse_from_str(expression) {
|
||||
Ok(expr) => expr,
|
||||
Err(e) => {
|
||||
warn!("Invalid expression: `{expression}`\n{e}");
|
||||
return Item::from_parts(T::from(0.).unwrap(), attributes);
|
||||
}
|
||||
};
|
||||
let context = EvalContext::new(
|
||||
MathNodeContext {
|
||||
a: operand_a.to_f64().unwrap(),
|
||||
b: operand_b.to_f64().unwrap(),
|
||||
},
|
||||
NothingMap,
|
||||
);
|
||||
|
||||
let value = match node.eval(&context) {
|
||||
Ok(value) => value,
|
||||
Err(e) => {
|
||||
warn!("Expression evaluation error: {e:?}");
|
||||
return Item::from_parts(T::from(0.).unwrap(), attributes);
|
||||
}
|
||||
};
|
||||
|
||||
let Value::Number(num) = value;
|
||||
let result = match num {
|
||||
Number::Real(val) => T::from(val).unwrap(),
|
||||
Number::Complex(c) => T::from(c.re).unwrap(),
|
||||
};
|
||||
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
|
||||
/// Parses and evaluates a math expression with the given variable bindings, logging and returning `None` on failure.
|
||||
fn evaluate_expression(expression: &str, provider: impl ValueProvider) -> Option<Value> {
|
||||
let node = match ast::Node::try_parse_from_str(expression) {
|
||||
Ok(node) => node,
|
||||
Err(error) => {
|
||||
warn!("Invalid expression: `{expression}`\n{error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match node.eval(&EvalContext::new(provider, NothingMap)) {
|
||||
Ok(value) => Some(value),
|
||||
Err(error) => {
|
||||
warn!("Expression evaluation error: {error:?}");
|
||||
@@ -89,6 +134,15 @@ fn output<T: ExpressionValue>(result: Option<Value>) -> T {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
impl ExpressionValue for f32 {
|
||||
fn into_f64(self) -> f64 {
|
||||
self as f64
|
||||
}
|
||||
fn from_value(value: &Value) -> Option<Self> {
|
||||
value.as_f32()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExpressionValue for bool {
|
||||
fn into_f64(self) -> f64 {
|
||||
self as u8 as f64
|
||||
@@ -119,18 +173,17 @@ impl ValueProvider for SingleVariableMathContext {
|
||||
fn math_fx<T: ExpressionValue>(
|
||||
_: impl Ctx,
|
||||
/// The value passed into the expression as `x`.
|
||||
#[implementations(f64, bool)]
|
||||
#[implementations(f64, f32, bool)]
|
||||
value: Item<T>,
|
||||
/// The expression evaluated for the input value, in terms of `x`, such as `4sin(x/2)`.
|
||||
#[name("f(x) =")]
|
||||
#[default("x")]
|
||||
fx: Item<String>,
|
||||
#[data] parsed: ParseCache,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let x = value.into_f64();
|
||||
let result = output(parsed.parse(fx.element()).and_then(|expression| evaluate_expression(&expression, SingleVariableMathContext { x })));
|
||||
let result = output(evaluate_expression(fx.element(), SingleVariableMathContext { x }));
|
||||
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
@@ -166,12 +219,11 @@ impl ValueProvider for PositionalMathContext {
|
||||
fn math_f<T: ExpressionValue>(
|
||||
_: impl Ctx,
|
||||
/// The items the expression reads.
|
||||
#[implementations(List<f64>, List<bool>)]
|
||||
#[implementations(List<f64>, List<f32>, List<bool>)]
|
||||
values: List<T>,
|
||||
/// The expression evaluated over the items, such as `a * b + c`, or a lone operator or function applied across all of them.
|
||||
#[name("f(…) =")]
|
||||
f: Item<String>,
|
||||
#[data] parsed: ParseCache,
|
||||
) -> Item<T> {
|
||||
let expression = f.element();
|
||||
let items: Vec<f64> = values.iter_element_values().map(|&value| value.into_f64()).collect();
|
||||
@@ -186,7 +238,7 @@ fn math_f<T: ExpressionValue>(
|
||||
return Item::new_from_element(output(Some(Value::from_f64(result))));
|
||||
}
|
||||
|
||||
let result = output(parsed.parse(expression).and_then(|expression| evaluate_expression(&expression, bindings)));
|
||||
let result = output(evaluate_expression(expression, bindings));
|
||||
Item::new_from_element(result)
|
||||
}
|
||||
|
||||
@@ -195,10 +247,10 @@ fn math_f<T: ExpressionValue>(
|
||||
fn add<A: Add<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The left-hand side of the addition operation.
|
||||
#[implementations(f64, i64, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
|
||||
augend: Item<A>,
|
||||
/// The right-hand side of the addition operation.
|
||||
#[implementations(f64, i64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
|
||||
addend: Item<B>,
|
||||
) -> Item<<A as Add<B>>::Output> {
|
||||
let (augend, attributes) = augend.into_parts();
|
||||
@@ -211,10 +263,10 @@ fn add<A: Add<B>, B>(
|
||||
fn subtract<A: Sub<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The left-hand side of the subtraction operation.
|
||||
#[implementations(f64, i64, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
|
||||
minuend: Item<A>,
|
||||
/// The right-hand side of the subtraction operation.
|
||||
#[implementations(f64, i64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
|
||||
subtrahend: Item<B>,
|
||||
) -> Item<<A as Sub<B>>::Output> {
|
||||
let (minuend, attributes) = minuend.into_parts();
|
||||
@@ -227,11 +279,11 @@ fn subtract<A: Sub<B>, B>(
|
||||
fn multiply<A: Mul<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The left-hand side of the multiplication operation.
|
||||
#[implementations(f64, i64, DVec2, f64, DVec2, DAffine2)]
|
||||
#[implementations(f64, f32, u32, DVec2, f64, DVec2, DAffine2)]
|
||||
multiplier: Item<A>,
|
||||
/// The right-hand side of the multiplication operation.
|
||||
#[default(1.)]
|
||||
#[implementations(f64, i64, DVec2, DVec2, f64, DAffine2)]
|
||||
#[implementations(f64, f32, u32, DVec2, DVec2, f64, DAffine2)]
|
||||
multiplicand: Item<B>,
|
||||
) -> Item<<A as Mul<B>>::Output> {
|
||||
let (multiplier, attributes) = multiplier.into_parts();
|
||||
@@ -249,9 +301,15 @@ impl SafeDivide for f64 {
|
||||
if denominator == 0. { 0. } else { self / denominator }
|
||||
}
|
||||
}
|
||||
impl SafeDivide for i64 {
|
||||
type Output = i64;
|
||||
fn safe_divide(self, denominator: i64) -> i64 {
|
||||
impl SafeDivide for f32 {
|
||||
type Output = f32;
|
||||
fn safe_divide(self, denominator: f32) -> f32 {
|
||||
if denominator == 0. { 0. } else { self / denominator }
|
||||
}
|
||||
}
|
||||
impl SafeDivide for u32 {
|
||||
type Output = u32;
|
||||
fn safe_divide(self, denominator: u32) -> u32 {
|
||||
self.checked_div(denominator).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
@@ -281,11 +339,11 @@ impl SafeDivide<DVec2> for f64 {
|
||||
fn divide<A: SafeDivide<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The left-hand side of the division operation.
|
||||
#[implementations(f64, i64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
|
||||
numerator: Item<A>,
|
||||
/// The right-hand side of the division operation.
|
||||
#[default(1.)]
|
||||
#[implementations(f64, i64, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
|
||||
denominator: Item<B>,
|
||||
) -> Item<<A as SafeDivide<B>>::Output> {
|
||||
let (numerator, attributes) = numerator.into_parts();
|
||||
@@ -301,6 +359,11 @@ impl Componentwise for f64 {
|
||||
f(self)
|
||||
}
|
||||
}
|
||||
impl Componentwise for f32 {
|
||||
fn componentwise(self, f: impl Fn(f64) -> f64) -> Self {
|
||||
f(self as f64) as f32
|
||||
}
|
||||
}
|
||||
impl Componentwise for DVec2 {
|
||||
fn componentwise(self, f: impl Fn(f64) -> f64) -> Self {
|
||||
DVec2::new(f(self.x), f(self.y))
|
||||
@@ -314,7 +377,7 @@ impl Componentwise for DVec2 {
|
||||
fn reciprocal<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The number for which the reciprocal is calculated.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -329,11 +392,11 @@ fn reciprocal<T: Componentwise>(
|
||||
fn modulo<A: Rem<B, Output: Add<B, Output: Rem<B, Output = A::Output>>>, B: Copy>(
|
||||
_: impl Ctx,
|
||||
/// The left-hand side of the modulo operation.
|
||||
#[implementations(f64, i64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
|
||||
numerator: Item<A>,
|
||||
/// The right-hand side of the modulo operation.
|
||||
#[default(2.)]
|
||||
#[implementations(f64, i64, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
|
||||
modulus: Item<B>,
|
||||
/// Ensures the result is always positive, even if the numerator is negative.
|
||||
#[default(true)]
|
||||
@@ -356,20 +419,16 @@ impl Exponent for f64 {
|
||||
self.powf(power)
|
||||
}
|
||||
}
|
||||
impl Exponent for i64 {
|
||||
type Output = i64;
|
||||
// Only ±1 stay representable once the exponent is negative or too large, so everything else falls to 0
|
||||
fn power(self, power: i64) -> i64 {
|
||||
if let Ok(power) = u32::try_from(power) {
|
||||
return self.checked_pow(power).unwrap_or(0);
|
||||
}
|
||||
|
||||
match self {
|
||||
1 => 1,
|
||||
-1 if power % 2 == 0 => 1,
|
||||
-1 => -1,
|
||||
_ => 0,
|
||||
}
|
||||
impl Exponent for f32 {
|
||||
type Output = f32;
|
||||
fn power(self, power: f32) -> f32 {
|
||||
self.powf(power)
|
||||
}
|
||||
}
|
||||
impl Exponent for u32 {
|
||||
type Output = u32;
|
||||
fn power(self, power: u32) -> u32 {
|
||||
self.pow(power)
|
||||
}
|
||||
}
|
||||
impl Exponent for DVec2 {
|
||||
@@ -398,10 +457,10 @@ impl Exponent<DVec2> for f64 {
|
||||
fn exponent<A: Exponent<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The base number that is raised to the power.
|
||||
#[implementations(f64, i64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
|
||||
base: Item<A>,
|
||||
/// The power to which the base number is raised.
|
||||
#[implementations(f64, i64, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
|
||||
#[default(2.)]
|
||||
power: Item<B>,
|
||||
) -> Item<<A as Exponent<B>>::Output> {
|
||||
@@ -432,6 +491,12 @@ impl NthRoot for f64 {
|
||||
scalar_nth_root(self, degree)
|
||||
}
|
||||
}
|
||||
impl NthRoot for f32 {
|
||||
type Output = f32;
|
||||
fn nth_root(self, degree: f32) -> f32 {
|
||||
scalar_nth_root(self as f64, degree as f64) as f32
|
||||
}
|
||||
}
|
||||
impl NthRoot for DVec2 {
|
||||
type Output = DVec2;
|
||||
fn nth_root(self, degree: DVec2) -> DVec2 {
|
||||
@@ -459,12 +524,12 @@ fn root<A: NthRoot<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The number inside the radical for which the `n`th root is calculated.
|
||||
#[default(2.)]
|
||||
#[implementations(f64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, DVec2, DVec2, f64)]
|
||||
radicand: Item<A>,
|
||||
/// The degree of the root to be calculated. Square root is 2, cube root is 3, and so on.
|
||||
/// Degrees 0 or less are invalid and will produce an output of 0.
|
||||
#[default(2.)]
|
||||
#[implementations(f64, f64, DVec2, DVec2)]
|
||||
#[implementations(f64, f32, f64, DVec2, DVec2)]
|
||||
degree: Item<B>,
|
||||
) -> Item<<A as NthRoot<B>>::Output> {
|
||||
let (radicand, attributes) = radicand.into_parts();
|
||||
@@ -494,6 +559,18 @@ impl Logarithm for f64 {
|
||||
scalar_logarithm(self, base)
|
||||
}
|
||||
}
|
||||
impl Logarithm for f32 {
|
||||
type Output = f32;
|
||||
fn logarithm(self, base: f32) -> f32 {
|
||||
// The f32 representation of e widens inexactly, so match it against e at f32 precision and substitute the exact f64 e
|
||||
let base = if (base - std::f32::consts::E).abs() < f32::EPSILON * 10. {
|
||||
std::f64::consts::E
|
||||
} else {
|
||||
base as f64
|
||||
};
|
||||
scalar_logarithm(self as f64, base) as f32
|
||||
}
|
||||
}
|
||||
impl Logarithm for DVec2 {
|
||||
type Output = DVec2;
|
||||
fn logarithm(self, base: DVec2) -> DVec2 {
|
||||
@@ -520,11 +597,11 @@ impl Logarithm<DVec2> for f64 {
|
||||
fn logarithm<A: Logarithm<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// The number for which the logarithm is calculated.
|
||||
#[implementations(f64, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, DVec2, DVec2, f64)]
|
||||
value: Item<A>,
|
||||
/// The base of the logarithm, such as 2 (binary), 10 (decimal), and e (natural logarithm).
|
||||
#[default(2.)]
|
||||
#[implementations(f64, f64, DVec2, DVec2)]
|
||||
#[implementations(f64, f32, f64, DVec2, DVec2)]
|
||||
base: Item<B>,
|
||||
) -> Item<<A as Logarithm<B>>::Output> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -539,7 +616,7 @@ fn logarithm<A: Logarithm<B>, B>(
|
||||
fn sine<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The given angle.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
theta: Item<T>,
|
||||
/// Whether the given angle should be interpreted as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
@@ -558,7 +635,7 @@ fn sine<T: Componentwise>(
|
||||
fn cosine<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The given angle.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
theta: Item<T>,
|
||||
/// Whether the given angle should be interpreted as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
@@ -577,7 +654,7 @@ fn cosine<T: Componentwise>(
|
||||
fn tangent<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The given angle.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
theta: Item<T>,
|
||||
/// Whether the given angle should be interpreted as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
@@ -591,32 +668,34 @@ fn tangent<T: Componentwise>(
|
||||
|
||||
/// The inverse sine trigonometric function (`asin`) calculates the angle whose sine is the input value.
|
||||
#[node_macro::node(category("Math: Trig"))]
|
||||
fn sine_inverse(
|
||||
fn sine_inverse<T: num_traits::float::Float>(
|
||||
_: impl Ctx,
|
||||
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
|
||||
value: Item<f64>,
|
||||
#[implementations(f64, f32)]
|
||||
value: Item<T>,
|
||||
/// Whether the resulting angle should be given in as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let angle = value.clamp(-1., 1.).asin();
|
||||
let angle = value.clamp(T::from(-1.).unwrap(), T::from(1.).unwrap()).asin();
|
||||
let result = if *radians.element() { angle } else { angle.to_degrees() };
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
|
||||
/// The inverse cosine trigonometric function (`acos`) calculates the angle whose cosine is the input value.
|
||||
#[node_macro::node(category("Math: Trig"))]
|
||||
fn cosine_inverse(
|
||||
fn cosine_inverse<T: num_traits::float::Float>(
|
||||
_: impl Ctx,
|
||||
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
|
||||
value: Item<f64>,
|
||||
#[implementations(f64, f32)]
|
||||
value: Item<T>,
|
||||
/// Whether the resulting angle should be given in as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let angle = value.clamp(-1., 1.).acos();
|
||||
let angle = value.clamp(T::from(-1.).unwrap(), T::from(1.).unwrap()).acos();
|
||||
let result = if *radians.element() { angle } else { angle.to_degrees() };
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
@@ -630,7 +709,7 @@ fn cosine_inverse(
|
||||
fn tangent_inverse<T: TangentInverse>(
|
||||
_: impl Ctx,
|
||||
/// The given value for which the angle is calculated.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
value: Item<T>,
|
||||
/// Whether the resulting angle should be given in as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
@@ -644,6 +723,12 @@ pub trait TangentInverse {
|
||||
type Output: num_traits::float::Float;
|
||||
fn atan(self, radians: bool) -> Self::Output;
|
||||
}
|
||||
impl TangentInverse for f32 {
|
||||
type Output = f32;
|
||||
fn atan(self, radians: bool) -> Self::Output {
|
||||
if radians { self.atan() } else { self.atan().to_degrees() }
|
||||
}
|
||||
}
|
||||
impl TangentInverse for f64 {
|
||||
type Output = f64;
|
||||
fn atan(self, radians: bool) -> Self::Output {
|
||||
@@ -661,30 +746,35 @@ impl TangentInverse for DVec2 {
|
||||
///
|
||||
/// For example, 0.5 in the input range `[0, 1]` would map to 0 in the output range `[-180, 180]`.
|
||||
#[node_macro::node(category("Math: Numeric"))]
|
||||
fn remap(
|
||||
fn remap<U: num_traits::float::Float>(
|
||||
_: impl Ctx,
|
||||
/// The value to be mapped between ranges.
|
||||
value: Item<f64>,
|
||||
#[implementations(f64, f32)]
|
||||
value: Item<U>,
|
||||
/// The lower bound of the input range.
|
||||
input_min: Item<f64>,
|
||||
#[implementations(f64, f32)]
|
||||
input_min: Item<U>,
|
||||
/// The upper bound of the input range.
|
||||
#[implementations(f64, f32)]
|
||||
#[default(1.)]
|
||||
input_max: Item<f64>,
|
||||
input_max: Item<U>,
|
||||
/// The lower bound of the output range.
|
||||
output_min: Item<f64>,
|
||||
#[implementations(f64, f32)]
|
||||
output_min: Item<U>,
|
||||
/// The upper bound of the output range.
|
||||
#[implementations(f64, f32)]
|
||||
#[default(1.)]
|
||||
output_max: Item<f64>,
|
||||
output_max: Item<U>,
|
||||
/// Whether to constrain the result within the output range instead of extrapolating beyond its bounds.
|
||||
clamped: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
) -> Item<U> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
let (input_min, input_max, output_min, output_max) = (*input_min.element(), *input_max.element(), *output_min.element(), *output_max.element());
|
||||
|
||||
let input_range = input_max - input_min;
|
||||
|
||||
// Handle division by zero
|
||||
if input_range.abs() < f64::EPSILON {
|
||||
if input_range.abs() < U::epsilon() {
|
||||
return Item::from_parts(output_min, attributes);
|
||||
}
|
||||
|
||||
@@ -715,6 +805,11 @@ impl Lerp for f64 {
|
||||
self * (1. - factor) + end * factor
|
||||
}
|
||||
}
|
||||
impl Lerp for f32 {
|
||||
fn lerp(self, end: Self, factor: f64) -> Self {
|
||||
(self as f64 * (1. - factor) + end as f64 * factor) as f32
|
||||
}
|
||||
}
|
||||
impl Lerp for DVec2 {
|
||||
fn lerp(self, end: Self, factor: f64) -> Self {
|
||||
self * (1. - factor) + end * factor
|
||||
@@ -728,11 +823,11 @@ impl Lerp for DVec2 {
|
||||
fn lerp<T: Lerp>(
|
||||
_: impl Ctx,
|
||||
/// The value produced when the factor is 0.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
start: Item<T>,
|
||||
/// The value produced when the factor is 1.
|
||||
#[default(1.)]
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
end: Item<T>,
|
||||
/// The mix between the start (at 0) and end (at 1) values.
|
||||
#[default(0.5)]
|
||||
@@ -761,15 +856,14 @@ fn random(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// Seed to determine the unique variation of which number is generated.
|
||||
#[hard(0..)]
|
||||
seed: Item<i64>,
|
||||
seed: Item<u64>,
|
||||
/// The smaller end of the range within which the random number is generated.
|
||||
min: Item<f64>,
|
||||
/// The larger end of the range within which the random number is generated.
|
||||
#[default(1.)]
|
||||
max: Item<f64>,
|
||||
) -> Item<f64> {
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(*seed.element() as u64);
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(*seed.element());
|
||||
let result = rng.random::<f64>();
|
||||
let (min, max) = (*min.element(), *max.element());
|
||||
let (min, max) = if min < max { (min, max) } else { (max, min) };
|
||||
@@ -777,21 +871,28 @@ fn random(
|
||||
}
|
||||
|
||||
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
|
||||
/// Converts a `Number` to the `Integer` type, which may be the required type for certain node inputs.
|
||||
#[node_macro::node(category("Type Assertion"))]
|
||||
fn as_integer(_: impl Ctx, value: Item<i64>) -> Item<i64> {
|
||||
/// Converts a number to an integer of the type u32, which may be the required type for certain node inputs.
|
||||
#[node_macro::node(name("As u32"), category("Type Assertion"))]
|
||||
fn as_u32(_: impl Ctx, value: Item<u32>) -> Item<u32> {
|
||||
value
|
||||
}
|
||||
|
||||
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
|
||||
/// Converts an `Integer` or `Bool` to the `Number` type, which may be the required type for certain node inputs. A `Bool` becomes 0 (false) or 1 (true).
|
||||
/// Converts a number to an integer of the type u64, which may be the required type for certain node inputs.
|
||||
#[node_macro::node(name("As u64"), category("Type Assertion"))]
|
||||
fn as_u64(_: impl Ctx, value: Item<u64>) -> Item<u64> {
|
||||
value
|
||||
}
|
||||
|
||||
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
|
||||
/// Converts an integer or bool to the decimal number type, which may be the required type for certain node inputs. A bool becomes 0 (false) or 1 (true).
|
||||
#[node_macro::node(category("Type Assertion"))]
|
||||
fn as_number(_: impl Ctx, value: Item<f64>) -> Item<f64> {
|
||||
value
|
||||
}
|
||||
|
||||
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
|
||||
/// Passes a true or false value through as the type `Bool`, which may be the required type for certain node inputs.
|
||||
/// Passes a true or false value through as the type bool, which may be the required type for certain node inputs.
|
||||
#[node_macro::node(category("Type Assertion"))]
|
||||
fn as_bool(_: impl Ctx, value: Item<bool>) -> Item<bool> {
|
||||
value
|
||||
@@ -804,7 +905,7 @@ fn as_bool(_: impl Ctx, value: Item<bool>) -> Item<bool> {
|
||||
fn round<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The number to be rounded to the nearest whole number.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -819,7 +920,7 @@ fn round<T: Componentwise>(
|
||||
fn floor<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The number to be rounded down.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -834,7 +935,7 @@ fn floor<T: Componentwise>(
|
||||
fn ceiling<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The number to be rounded up.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -850,11 +951,21 @@ impl AbsoluteValue for DVec2 {
|
||||
DVec2::new(self.x.abs(), self.y.abs())
|
||||
}
|
||||
}
|
||||
impl AbsoluteValue for f32 {
|
||||
fn abs(self) -> Self {
|
||||
self.abs()
|
||||
}
|
||||
}
|
||||
impl AbsoluteValue for f64 {
|
||||
fn abs(self) -> Self {
|
||||
self.abs()
|
||||
}
|
||||
}
|
||||
impl AbsoluteValue for i32 {
|
||||
fn abs(self) -> Self {
|
||||
self.abs()
|
||||
}
|
||||
}
|
||||
impl AbsoluteValue for i64 {
|
||||
fn abs(self) -> Self {
|
||||
self.abs()
|
||||
@@ -868,7 +979,7 @@ impl AbsoluteValue for i64 {
|
||||
fn absolute_value<T: AbsoluteValue>(
|
||||
_: impl Ctx,
|
||||
/// The number to be made positive.
|
||||
#[implementations(f64, i64, DVec2)]
|
||||
#[implementations(f64, f32, i32, i64, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -883,7 +994,7 @@ fn absolute_value<T: AbsoluteValue>(
|
||||
fn sign<T: Componentwise>(
|
||||
_: impl Ctx,
|
||||
/// The number whose sign is checked.
|
||||
#[implementations(f64, DVec2)]
|
||||
#[implementations(f64, f32, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -914,12 +1025,21 @@ impl MinMax for f64 {
|
||||
if self > other { self } else { other }
|
||||
}
|
||||
}
|
||||
impl MinMax for i64 {
|
||||
type Output = i64;
|
||||
fn minimum(self, other: i64) -> i64 {
|
||||
impl MinMax for f32 {
|
||||
type Output = f32;
|
||||
fn minimum(self, other: f32) -> f32 {
|
||||
if self < other { self } else { other }
|
||||
}
|
||||
fn maximum(self, other: i64) -> i64 {
|
||||
fn maximum(self, other: f32) -> f32 {
|
||||
if self > other { self } else { other }
|
||||
}
|
||||
}
|
||||
impl MinMax for u32 {
|
||||
type Output = u32;
|
||||
fn minimum(self, other: u32) -> u32 {
|
||||
if self < other { self } else { other }
|
||||
}
|
||||
fn maximum(self, other: u32) -> u32 {
|
||||
if self > other { self } else { other }
|
||||
}
|
||||
}
|
||||
@@ -967,10 +1087,10 @@ impl MinMax<DVec2> for f64 {
|
||||
fn min<A: MinMax<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// One of the two numbers, of which the lesser is returned.
|
||||
#[implementations(f64, i64, String, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, DVec2, f64)]
|
||||
value: Item<A>,
|
||||
/// The other of the two numbers, of which the lesser is returned.
|
||||
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, f64, DVec2)]
|
||||
other_value: Item<B>,
|
||||
) -> Item<<A as MinMax<B>>::Output> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -985,10 +1105,10 @@ fn min<A: MinMax<B>, B>(
|
||||
fn max<A: MinMax<B>, B>(
|
||||
_: impl Ctx,
|
||||
/// One of the two numbers, of which the greater is returned.
|
||||
#[implementations(f64, i64, String, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, DVec2, f64)]
|
||||
value: Item<A>,
|
||||
/// The other of the two numbers, of which the greater is returned.
|
||||
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, f64, DVec2)]
|
||||
other_value: Item<B>,
|
||||
) -> Item<<A as MinMax<B>>::Output> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -1003,13 +1123,13 @@ fn max<A: MinMax<B>, B>(
|
||||
fn clamp<A: MinMax<B>, B: MinMax<Output = B> + Clone>(
|
||||
_: impl Ctx,
|
||||
/// The number to be clamped, which is restricted to the range between the minimum and maximum values.
|
||||
#[implementations(f64, i64, String, DVec2, DVec2, f64)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, DVec2, f64)]
|
||||
value: Item<A>,
|
||||
/// The left (smaller) side of the range. The output is never less than this number.
|
||||
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, f64, DVec2)]
|
||||
min: Item<B>,
|
||||
/// The right (greater) side of the range. The output is never greater than this number.
|
||||
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
|
||||
#[implementations(f64, f32, u32, String, DVec2, f64, DVec2)]
|
||||
#[default(1)]
|
||||
max: Item<B>,
|
||||
) -> Item<<A as MinMax<B>>::Output>
|
||||
@@ -1025,38 +1145,47 @@ where
|
||||
|
||||
/// The greatest common divisor (GCD) calculates the largest positive integer that divides both of the two input numbers without leaving a remainder.
|
||||
#[node_macro::node(category("Math: Numeric"))]
|
||||
fn greatest_common_divisor(
|
||||
fn greatest_common_divisor<T: num_traits::int::PrimInt>(
|
||||
_: impl Ctx,
|
||||
/// One of the two numbers for which the GCD is calculated.
|
||||
value: Item<i64>,
|
||||
#[implementations(u32, u64, i32)]
|
||||
value: Item<T>,
|
||||
/// The other of the two numbers for which the GCD is calculated.
|
||||
other_value: Item<i64>,
|
||||
) -> Item<i64> {
|
||||
#[implementations(u32, u64, i32)]
|
||||
other_value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
let other_value = *other_value.element();
|
||||
|
||||
let gcd = math_parser::constants::gcd(value.unsigned_abs() as u128, other_value.unsigned_abs() as u128);
|
||||
let gcd = math_parser::constants::gcd(integer_magnitude(value), integer_magnitude(other_value));
|
||||
|
||||
// A result too large for the output type (like the GCD of `i64::MIN` and 0) saturates at the type's maximum
|
||||
Item::from_parts(i64::try_from(gcd).unwrap_or(i64::MAX), attributes)
|
||||
// A result too large for the output type (like the GCD of `i32::MIN` and 0) saturates at the type's maximum
|
||||
Item::from_parts(T::from(gcd).unwrap_or_else(T::max_value), attributes)
|
||||
}
|
||||
|
||||
/// The least common multiple (LCM) calculates the smallest positive integer that is a multiple of both of the two input numbers.
|
||||
#[node_macro::node(category("Math: Numeric"))]
|
||||
fn least_common_multiple(
|
||||
fn least_common_multiple<T: num_traits::int::PrimInt>(
|
||||
_: impl Ctx,
|
||||
/// One of the two numbers for which the LCM is calculated.
|
||||
value: Item<i64>,
|
||||
#[implementations(u32, u64, i32)]
|
||||
value: Item<T>,
|
||||
/// The other of the two numbers for which the LCM is calculated.
|
||||
other_value: Item<i64>,
|
||||
) -> Item<i64> {
|
||||
#[implementations(u32, u64, i32)]
|
||||
other_value: Item<T>,
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
let other_value = *other_value.element();
|
||||
|
||||
let lcm = math_parser::constants::lcm(value.unsigned_abs() as u128, other_value.unsigned_abs() as u128);
|
||||
let lcm = math_parser::constants::lcm(integer_magnitude(value), integer_magnitude(other_value));
|
||||
|
||||
// A result too large for the output type saturates at the type's maximum rather than overflowing
|
||||
Item::from_parts(i64::try_from(lcm).unwrap_or(i64::MAX), attributes)
|
||||
Item::from_parts(T::from(lcm).unwrap_or_else(T::max_value), attributes)
|
||||
}
|
||||
|
||||
/// Reads an integer's magnitude as a `u128`, which every implemented input type fits within.
|
||||
fn integer_magnitude<T: num_traits::int::PrimInt>(value: T) -> u128 {
|
||||
value.to_i128().map_or(0, i128::unsigned_abs)
|
||||
}
|
||||
|
||||
/// Adds together all the numbers in the input list, producing their total.
|
||||
@@ -1103,7 +1232,7 @@ fn all(_: impl Ctx, values: List<bool>) -> Item<bool> {
|
||||
fn is_nonzero<T: Default + std::cmp::PartialEq>(
|
||||
_: impl Ctx,
|
||||
/// The value compared against zero.
|
||||
#[implementations(f64, i64, DVec2)]
|
||||
#[implementations(f64, f32, u32, u64, i32, i64, DVec2)]
|
||||
value: Item<T>,
|
||||
) -> Item<bool> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -1116,10 +1245,10 @@ fn is_nonzero<T: Default + std::cmp::PartialEq>(
|
||||
fn less_than<T: std::cmp::PartialOrd<T>>(
|
||||
_: impl Ctx,
|
||||
/// The number on the left-hand side of the comparison.
|
||||
#[implementations(f64, i64)]
|
||||
#[implementations(f64, f32, u32)]
|
||||
value: Item<T>,
|
||||
/// The number on the right-hand side of the comparison.
|
||||
#[implementations(f64, i64)]
|
||||
#[implementations(f64, f32, u32)]
|
||||
other_value: Item<T>,
|
||||
/// Uses the less-than-or-equal operation (`<=`) instead of the less-than operation (`<`).
|
||||
or_equal: Item<bool>,
|
||||
@@ -1137,10 +1266,10 @@ fn less_than<T: std::cmp::PartialOrd<T>>(
|
||||
fn greater_than<T: std::cmp::PartialOrd<T>>(
|
||||
_: impl Ctx,
|
||||
/// The number on the left-hand side of the comparison.
|
||||
#[implementations(f64, i64)]
|
||||
#[implementations(f64, f32, u32)]
|
||||
value: Item<T>,
|
||||
/// The number on the right-hand side of the comparison.
|
||||
#[implementations(f64, i64)]
|
||||
#[implementations(f64, f32, u32)]
|
||||
other_value: Item<T>,
|
||||
/// Uses the greater-than-or-equal operation (`>=`) instead of the greater-than operation (`>`).
|
||||
or_equal: Item<bool>,
|
||||
@@ -1157,10 +1286,10 @@ fn greater_than<T: std::cmp::PartialOrd<T>>(
|
||||
fn equals<T: std::cmp::PartialEq<T>>(
|
||||
_: impl Ctx,
|
||||
/// One of the two values to compare for equality.
|
||||
#[implementations(f64, i64, DVec2, bool, String)]
|
||||
#[implementations(f64, f32, u32, DVec2, bool, String)]
|
||||
value: Item<T>,
|
||||
/// The other of the two values to compare for equality.
|
||||
#[implementations(f64, i64, DVec2, bool, String)]
|
||||
#[implementations(f64, f32, u32, DVec2, bool, String)]
|
||||
other_value: Item<T>,
|
||||
) -> Item<bool> {
|
||||
let value = value.into_element();
|
||||
@@ -1173,10 +1302,10 @@ fn equals<T: std::cmp::PartialEq<T>>(
|
||||
fn not_equals<T: std::cmp::PartialEq<T>>(
|
||||
_: impl Ctx,
|
||||
/// One of the two values to compare for inequality.
|
||||
#[implementations(f64, i64, DVec2, bool, String)]
|
||||
#[implementations(f64, f32, u32, DVec2, bool, String)]
|
||||
value: Item<T>,
|
||||
/// The other of the two values to compare for inequality.
|
||||
#[implementations(f64, i64, DVec2, bool, String)]
|
||||
#[implementations(f64, f32, u32, DVec2, bool, String)]
|
||||
other_value: Item<T>,
|
||||
) -> Item<bool> {
|
||||
let value = value.into_element();
|
||||
@@ -1235,8 +1364,10 @@ async fn switch<T: 'n + Send>(
|
||||
#[implementations(
|
||||
Context -> Item<String>,
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<f32>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<u32>,
|
||||
Context -> Item<u64>,
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<DAffine2>,
|
||||
Context -> Item<Vector>,
|
||||
@@ -1248,8 +1379,10 @@ async fn switch<T: 'n + Send>(
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
Context -> Item<Bundle<f32>>,
|
||||
Context -> Item<Bundle<f64>>,
|
||||
Context -> Item<Bundle<i64>>,
|
||||
Context -> Item<Bundle<u32>>,
|
||||
Context -> Item<Bundle<u64>>,
|
||||
Context -> Item<Bundle<DVec2>>,
|
||||
Context -> Item<Bundle<DAffine2>>,
|
||||
Context -> Item<Bundle<Vector>>,
|
||||
@@ -1265,8 +1398,10 @@ async fn switch<T: 'n + Send>(
|
||||
#[implementations(
|
||||
Context -> Item<String>,
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<f32>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<u32>,
|
||||
Context -> Item<u64>,
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<DAffine2>,
|
||||
Context -> Item<Vector>,
|
||||
@@ -1278,8 +1413,10 @@ async fn switch<T: 'n + Send>(
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
Context -> Item<Bundle<f32>>,
|
||||
Context -> Item<Bundle<f64>>,
|
||||
Context -> Item<Bundle<i64>>,
|
||||
Context -> Item<Bundle<u32>>,
|
||||
Context -> Item<Bundle<u64>>,
|
||||
Context -> Item<Bundle<DVec2>>,
|
||||
Context -> Item<Bundle<DAffine2>>,
|
||||
Context -> Item<Bundle<Vector>>,
|
||||
@@ -1297,7 +1434,7 @@ async fn switch<T: 'n + Send>(
|
||||
if *condition.element() { if_true.eval(ctx).await } else { if_false.eval(ctx).await }
|
||||
}
|
||||
|
||||
/// Constructs a `Bool` value which may be set to true or false.
|
||||
/// Constructs a bool value which may be set to true or false.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn bool_value(_: impl Ctx, _primary: (), #[name("Bool")] bool_value: Item<bool>) -> Item<bool> {
|
||||
bool_value
|
||||
@@ -1829,6 +1966,18 @@ mod test {
|
||||
assert_eq!(logarithm((), vec2(8., 100.), vec2(2., 10.)).into_element(), DVec2::new(3., 2.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn logarithm_f32_base_e_and_near_e() {
|
||||
assert_eq!(
|
||||
logarithm((), Item::new_from_element(8_f32), Item::new_from_element(std::f32::consts::E)).into_element(),
|
||||
8_f64.ln() as f32
|
||||
);
|
||||
assert_eq!(
|
||||
logarithm((), Item::new_from_element(8_f32), Item::new_from_element(2.7_f32)).into_element(),
|
||||
8_f64.log(2.7_f32 as f64) as f32
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn round_floor_ceiling_vec2() {
|
||||
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
|
||||
@@ -1839,50 +1988,35 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn test_basic_expression() {
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(0.), Item::new_from_element("2 + 2".to_string()));
|
||||
let result = math((), Item::new_from_element(0.), Item::new_from_element("2 + 2".to_string()), Item::new_from_element(0.));
|
||||
assert_eq!(result.into_element(), 4.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complex_expression() {
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(0.), Item::new_from_element("(5 * 3) + (10 / 2)".to_string()));
|
||||
let result = math((), Item::new_from_element(0.), Item::new_from_element("(5 * 3) + (10 / 2)".to_string()), Item::new_from_element(0.));
|
||||
assert_eq!(result.into_element(), 20.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_variable_binding() {
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(7.), Item::new_from_element("x * 2".to_string()));
|
||||
assert_eq!(result.into_element(), 14.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_expression() {
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(0.), Item::new_from_element("invalid".to_string()));
|
||||
fn test_default_expression() {
|
||||
let result = math((), Item::new_from_element(0.), Item::new_from_element("0".to_string()), Item::new_from_element(0.));
|
||||
assert_eq!(result.into_element(), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expressions_parse_once_per_source() {
|
||||
let cache = ParseCache::default();
|
||||
let first = cache.parse("x * 2").unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &cache.parse("x * 2").unwrap()));
|
||||
assert!(!Arc::ptr_eq(&first, &cache.parse("x * 3").unwrap()));
|
||||
assert!(cache.parse("invalid(").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_boolean_items() {
|
||||
// Booleans read as exactly 0 and 1, and logical results convert back
|
||||
assert!(!math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("!x".to_string())).into_element());
|
||||
assert!(math_fx((), &ParseCache::default(), Item::new_from_element(false), Item::new_from_element("x == 0".to_string())).into_element());
|
||||
assert!(!math_fx((), Item::new_from_element(true), Item::new_from_element("!x".to_string())).into_element());
|
||||
assert!(math_fx((), Item::new_from_element(false), Item::new_from_element("x == 0".to_string())).into_element());
|
||||
|
||||
// A result that is not exactly 0 or 1 cannot be a truth value, so it reads as false
|
||||
assert!(!math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("x + 1".to_string())).into_element());
|
||||
assert!(!math_fx((), Item::new_from_element(true), Item::new_from_element("x + 1".to_string())).into_element());
|
||||
|
||||
let bools = || [true, true, false].into_iter().map(Item::new_from_element).collect::<List<bool>>();
|
||||
assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("&&".to_string())).into_element());
|
||||
assert!(math_f((), &ParseCache::default(), bools(), Item::new_from_element("||".to_string())).into_element());
|
||||
assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("xor".to_string())).into_element());
|
||||
assert!(!math_f((), bools(), Item::new_from_element("&&".to_string())).into_element());
|
||||
assert!(math_f((), bools(), Item::new_from_element("||".to_string())).into_element());
|
||||
assert!(!math_f((), bools(), Item::new_from_element("xor".to_string())).into_element());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1899,13 +2033,9 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_positional_and_reducer_expressions() {
|
||||
let values = || [4., 1., 7.].into_iter().map(Item::new_from_element).collect::<List<f64>>();
|
||||
|
||||
// A full expression reads the items positionally as `a`, `b`, `c`, while a lone token applies across all of them
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("a - b + c".to_string())).into_element(), 10.);
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("min".to_string())).into_element(), 1.);
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("+".to_string())).into_element(), 12.);
|
||||
fn test_invalid_expression() {
|
||||
let result = math((), Item::new_from_element(0.), Item::new_from_element("invalid".to_string()), Item::new_from_element(0.));
|
||||
assert_eq!(result.into_element(), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@ use no_std_types::blending::BlendMode;
|
||||
use no_std_types::color::{Color, Pixel};
|
||||
#[cfg(not(feature = "std"))]
|
||||
use no_std_types::list::ShaderItem as Item;
|
||||
use no_std_types::registry::types::Percentage;
|
||||
use no_std_types::registry::types::PercentageF32;
|
||||
#[cfg(feature = "std")]
|
||||
use raster_types::{CPU, Raster};
|
||||
#[cfg(feature = "std")]
|
||||
@@ -82,13 +82,13 @@ fn mix<T: Blend<Color> + Send>(
|
||||
#[gpu_image]
|
||||
under: Item<T>,
|
||||
blend_mode: Item<BlendMode>,
|
||||
#[default(100.)] opacity: Item<Percentage>,
|
||||
#[default(100.)] opacity: Item<PercentageF32>,
|
||||
) -> Item<T> {
|
||||
let mut over = over;
|
||||
let blend_mode = blend_mode.into_element();
|
||||
let opacity = (opacity.into_element() / 100.) as f32;
|
||||
let opacity = opacity.into_element();
|
||||
|
||||
let blended = over.element().blend(under.element(), |a, b| blend_colors(a, b, blend_mode, opacity));
|
||||
let blended = over.element().blend(under.element(), |a, b| blend_colors(a, b, blend_mode, opacity / 100.));
|
||||
*over.element_mut() = blended;
|
||||
over
|
||||
}
|
||||
@@ -106,7 +106,7 @@ fn color_overlay<T: Adjust<Color>>(
|
||||
image: Item<T>,
|
||||
#[default(Color::BLACK)] color: Item<Color>,
|
||||
blend_mode: Item<BlendMode>,
|
||||
#[default(100.)] opacity: Item<Percentage>,
|
||||
#[default(100.)] opacity: Item<PercentageF32>,
|
||||
) -> Item<T> {
|
||||
let mut image = image;
|
||||
let color = color.into_element();
|
||||
@@ -117,7 +117,7 @@ fn color_overlay<T: Adjust<Color>>(
|
||||
|
||||
image.element_mut().adjust(|pixel| {
|
||||
let overlay = apply_blend_mode(color, *pixel, blend_mode);
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity as f32;
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
|
||||
});
|
||||
|
||||
@@ -37,8 +37,6 @@ async fn dehaze(_: impl Ctx, image_frame: Item<Raster<CPU>>, strength: Item<Perc
|
||||
|
||||
// There is no real point in modifying these values because they do not change the final result all that much.
|
||||
// The authors of the paper recommended using these values to get a reasonable balance of performance and quality.
|
||||
// TODO: The patch size and guided filter radius are whole source pixels, so the effect's scale follows the image's resolution.
|
||||
// Derive them from the footprint so the dehaze acts at a document-space scale independent of how the image was sampled.
|
||||
const PATCH_SIZE: u32 = 15;
|
||||
const TOP_PERCENT: f64 = 0.001;
|
||||
const RADIUS: u32 = 60;
|
||||
|
||||
@@ -105,8 +105,6 @@ async fn blur(
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
|
||||
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
|
||||
// window that varies continuously rather than snapping to whole source pixels
|
||||
let blurred_image = if radius < 0.1 {
|
||||
// Minimum blur radius
|
||||
image
|
||||
@@ -135,8 +133,6 @@ async fn median_filter(
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
|
||||
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
|
||||
// window that varies continuously rather than snapping to whole source pixels
|
||||
let filtered_image = if radius < 0.5 {
|
||||
// Minimum filter radius
|
||||
image
|
||||
|
||||
@@ -9,7 +9,7 @@ async fn image_color_palette(
|
||||
image: Item<Raster<CPU>>,
|
||||
#[default(4)]
|
||||
#[hard(1..)]
|
||||
count: Item<i64>,
|
||||
count: Item<u32>,
|
||||
) -> List<Color> {
|
||||
const GRID: f32 = 3.;
|
||||
|
||||
|
||||
@@ -274,7 +274,7 @@ pub fn noise_pattern(
|
||||
ctx: impl ExtractFootprint + Ctx,
|
||||
_primary: (),
|
||||
#[default(true)] clip: Item<bool>,
|
||||
#[hard(0..)] seed: Item<i64>,
|
||||
seed: Item<u32>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_scale")]
|
||||
#[default(10.)]
|
||||
scale: Item<f64>,
|
||||
@@ -286,8 +286,7 @@ pub fn noise_pattern(
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_type")] fractal_type: Item<FractalType>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_octaves")]
|
||||
#[default(3)]
|
||||
#[hard(1..10)]
|
||||
fractal_octaves: Item<i64>,
|
||||
fractal_octaves: Item<u32>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_lacunarity")]
|
||||
#[default(2.)]
|
||||
fractal_lacunarity: Item<f64>,
|
||||
|
||||
@@ -14,8 +14,10 @@ async fn repeat<T: Send + Clone + 'static>(
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
Context -> List<f32>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<i64>,
|
||||
Context -> List<u32>,
|
||||
Context -> List<u64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
@@ -29,7 +31,7 @@ async fn repeat<T: Send + Clone + 'static>(
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
#[default(1)]
|
||||
#[hard(1..)]
|
||||
count: Item<i64>,
|
||||
count: Item<u32>,
|
||||
reverse: Item<bool>,
|
||||
) -> List<T> {
|
||||
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
|
||||
@@ -59,8 +61,10 @@ pub async fn repeat_array<T: Send + Clone + 'static>(
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
Context -> List<f32>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<i64>,
|
||||
Context -> List<u32>,
|
||||
Context -> List<u64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
@@ -78,7 +82,7 @@ pub async fn repeat_array<T: Send + Clone + 'static>(
|
||||
angle: Item<Angle>,
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: Item<i64>,
|
||||
count: Item<u32>,
|
||||
) -> List<T> {
|
||||
let (direction, angle, count) = (direction.into_element(), angle.into_element(), count.into_element());
|
||||
let angle = angle.to_radians();
|
||||
@@ -116,8 +120,10 @@ async fn repeat_radial<T: Send + Clone + 'static>(
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
Context -> List<f32>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<i64>,
|
||||
Context -> List<u32>,
|
||||
Context -> List<u64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
@@ -135,7 +141,7 @@ async fn repeat_radial<T: Send + Clone + 'static>(
|
||||
radius: Item<f64>,
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: Item<i64>,
|
||||
count: Item<u32>,
|
||||
) -> List<T> {
|
||||
let (start_angle, radius, count) = (start_angle.into_element(), radius.into_element(), count.into_element());
|
||||
|
||||
@@ -171,8 +177,10 @@ async fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
Context -> List<f32>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<i64>,
|
||||
Context -> List<u32>,
|
||||
Context -> List<u64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
@@ -275,7 +283,7 @@ mod test {
|
||||
let rect = RectangleNode::new(
|
||||
FutureWrapperNode(()),
|
||||
ExtractXyNode::new(
|
||||
ReadPositionNode::new(FutureWrapperNode(()), FutureWrapperNode(Item::new_from_element(0_i64))),
|
||||
ReadPositionNode::new(FutureWrapperNode(()), FutureWrapperNode(Item::new_from_element(0_u32))),
|
||||
FutureWrapperNode(Item::new_from_element(XY::Y)),
|
||||
),
|
||||
FutureWrapperNode(Item::new_from_element(2_f64)),
|
||||
|
||||
@@ -28,8 +28,7 @@ fn format_json(
|
||||
///
|
||||
/// This is not a maximum line length guarantee. Deep nesting and long keys or values may exceed this length.
|
||||
#[default(120)]
|
||||
#[hard(0..)]
|
||||
break_length: Item<i64>,
|
||||
break_length: Item<u32>,
|
||||
/// Always break a container (array or object) across lines if it holds another container, even if it would fit within the break length. (Requires *Multi-Line* to take effect.)
|
||||
#[default(true)]
|
||||
break_nested: Item<bool>,
|
||||
|
||||
@@ -11,7 +11,7 @@ use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::float_noise::round_away_float_noise;
|
||||
use core_types::misc::{format_f64, parse_f64};
|
||||
use core_types::registry::types::TextArea;
|
||||
use core_types::registry::types::{SeedValue, SignedInteger, TextArea};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -224,25 +224,22 @@ fn lorem_ipsum(
|
||||
_primary: (),
|
||||
/// Total length of generated text in the chosen denomination (characters, words, sentences, or paragraphs), including the classic "Lorem ipsum dolor sit amet…" intro. A length in characters is never exceeded but may fall a few characters short, since words are never cut.
|
||||
#[default(50)]
|
||||
#[hard(0..)]
|
||||
length: Item<i64>,
|
||||
length: Item<u32>,
|
||||
/// How the desired quantity of generated text is counted.
|
||||
length_in: Item<TextDenomination>,
|
||||
/// Length of the classic "Lorem ipsum dolor sit amet…" intro to include at the start of the generated text. Disable by setting this to 0.
|
||||
#[default(8)]
|
||||
#[hard(0..)]
|
||||
#[name("\"Lorem…\" Intro")]
|
||||
lorem_intro: Item<i64>,
|
||||
lorem_intro: Item<u32>,
|
||||
/// How the desired quantity of classic intro text is counted for inclusion at the start.
|
||||
///
|
||||
/// If one paragraph is chosen, the full intro is included and the randomized continuation begins on the next paragraph; otherwise the continuation may follow in the same paragraph.
|
||||
#[name("\"Lorem…\" Intro In")]
|
||||
lorem_intro_in: Item<TextDenomination>,
|
||||
/// Seed to determine unique variations on the randomized text generated after the optional classic intro.
|
||||
#[hard(0..)]
|
||||
seed: Item<i64>,
|
||||
seed: Item<SeedValue>,
|
||||
) -> Item<String> {
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(*seed.element() as u64);
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64((*seed.element()).into());
|
||||
let rng = |n| rng.random_range(0..n);
|
||||
|
||||
let text = ipsum::generate(
|
||||
@@ -284,14 +281,22 @@ fn string_replace(_: impl Ctx, string: Item<String>, from: Item<TextArea>, to: I
|
||||
///
|
||||
/// Negative indices count from the end of the string. If the index of "Start" equals or exceeds "End", the result is an empty string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_slice(_: impl Ctx, string: Item<String>, start: Item<i64>, end: Item<i64>) -> Item<String> {
|
||||
fn string_slice(_: impl Ctx, string: Item<String>, start: Item<SignedInteger>, end: Item<SignedInteger>) -> Item<String> {
|
||||
let mut string = string;
|
||||
let (start, end) = (*start.element(), *end.element());
|
||||
|
||||
let total_graphemes = string.element().graphemes(true).count() as i64;
|
||||
let total_graphemes = string.element().graphemes(true).count();
|
||||
|
||||
let start = if start < 0 { (total_graphemes + start).max(0) } else { start.min(total_graphemes) } as usize;
|
||||
let end = if end <= 0 { (total_graphemes + end).max(0) } else { end.min(total_graphemes) } as usize;
|
||||
let start = if start < 0. {
|
||||
total_graphemes.saturating_sub(start.abs() as usize)
|
||||
} else {
|
||||
(start as usize).min(total_graphemes)
|
||||
};
|
||||
let end = if end <= 0. {
|
||||
total_graphemes.saturating_sub(end.abs() as usize)
|
||||
} else {
|
||||
(end as usize).min(total_graphemes)
|
||||
};
|
||||
|
||||
let result = if start >= end {
|
||||
String::new()
|
||||
@@ -311,8 +316,7 @@ fn string_truncate(
|
||||
string: Item<String>,
|
||||
/// The maximum number of characters allowed, including the suffix if one is appended.
|
||||
#[default(80)]
|
||||
#[hard(0..)]
|
||||
length: Item<i64>,
|
||||
length: Item<u32>,
|
||||
/// A suffix appended to indicate truncation occurred, unless empty. Its length counts towards the character budget.
|
||||
#[default("…")]
|
||||
suffix: Item<String>,
|
||||
@@ -343,8 +347,7 @@ fn format_number(
|
||||
number: Item<f64>,
|
||||
/// The amount of digits after the decimal point. The value is rounded to fit. Set to 0 to show only whole numbers.
|
||||
#[default(2)]
|
||||
#[hard(0..)]
|
||||
decimal_places: Item<i64>,
|
||||
decimal_places: Item<u32>,
|
||||
/// The character(s) used as the decimal point.
|
||||
#[default(".")]
|
||||
decimal_separator: Item<String>,
|
||||
@@ -556,7 +559,7 @@ fn string_repeat(
|
||||
/// The number of times the string should appear in the output.
|
||||
#[default(2)]
|
||||
#[hard(1..)]
|
||||
count: Item<i64>,
|
||||
count: Item<u32>,
|
||||
/// The string placed between each repetition.
|
||||
#[default("\\n")]
|
||||
separator: Item<String>,
|
||||
@@ -571,7 +574,7 @@ fn string_repeat(
|
||||
|
||||
let count = *count.element() as usize;
|
||||
|
||||
let mut result = String::with_capacity((string.element().len() + separator.len()).saturating_mul(count));
|
||||
let mut result = String::with_capacity((string.element().len() + separator.len()) * count);
|
||||
for i in 0..count {
|
||||
if i > 0 {
|
||||
result.push_str(&separator);
|
||||
@@ -591,8 +594,7 @@ fn string_pad(
|
||||
string: Item<String>,
|
||||
/// The target character length after padding. When "Up To" is set, this length concerns only the portion before (or after) that substring.
|
||||
#[default(10)]
|
||||
#[hard(0..)]
|
||||
length: Item<i64>,
|
||||
length: Item<u32>,
|
||||
/// The repeated substring used to fill the remaining space. A multi-charcter substring may end partway through its final repetition.
|
||||
#[default("#")]
|
||||
padding: Item<String>,
|
||||
@@ -886,7 +888,7 @@ fn string_capitalization(
|
||||
string
|
||||
}
|
||||
|
||||
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this count off from the generic math nodes.
|
||||
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
|
||||
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
|
||||
/// Counts the number of characters in a string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
@@ -975,7 +977,7 @@ fn read_string(ctx: impl Ctx + ExtractVarArgs) -> Item<String> {
|
||||
|
||||
/// Converts a value to a JSON string representation.
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, i64, DVec2, DAffine2)] value: Item<T>) -> Item<String> {
|
||||
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, u32, u64, DVec2, DAffine2)] value: Item<T>) -> Item<String> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let result = serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::SignedInteger;
|
||||
use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
|
||||
|
||||
/// Checks whether the string contains a match for the given regular expression pattern. Optionally restricts the match to only the start and/or end of the string.
|
||||
@@ -102,7 +103,7 @@ fn regex_find(
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
|
||||
match_index: Item<i64>,
|
||||
match_index: Item<SignedInteger>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
@@ -135,14 +136,15 @@ fn regex_find(
|
||||
// Collect all matches since we need to support negative indexing
|
||||
let matches: Vec<_> = regex.captures_iter(string).filter_map(|c| c.ok()).collect();
|
||||
|
||||
let match_index = match_index as i32;
|
||||
let resolved_index = if match_index < 0 {
|
||||
let from_end = match_index.unsigned_abs();
|
||||
if from_end > matches.len() as u64 {
|
||||
let from_end = (-match_index) as usize;
|
||||
if from_end > matches.len() {
|
||||
return List::new();
|
||||
}
|
||||
matches.len() - from_end as usize
|
||||
matches.len() - from_end
|
||||
} else {
|
||||
match_index.min(matches.len() as i64) as usize
|
||||
match_index as usize
|
||||
};
|
||||
|
||||
let Some(captures) = matches.get(resolved_index) else {
|
||||
@@ -154,8 +156,8 @@ fn regex_find(
|
||||
.map(|i| {
|
||||
let captured = captures.get(i);
|
||||
let text = captured.map_or(String::new(), |m| m.as_str().to_string());
|
||||
let start = captured.map_or(0_i64, |m| m.start() as i64);
|
||||
let end = captured.map_or(0_i64, |m| m.end() as i64);
|
||||
let start = captured.map_or(0_u64, |m| m.start() as u64);
|
||||
let end = captured.map_or(0_u64, |m| m.end() as u64);
|
||||
let name = capture_names.get(i).cloned().flatten().unwrap_or_default();
|
||||
Item::new_from_element(text)
|
||||
.with_attribute(ATTR_START, start)
|
||||
@@ -206,8 +208,8 @@ fn regex_find_all(
|
||||
.filter_map(|m| m.ok())
|
||||
.map(|m| {
|
||||
Item::new_from_element(m.as_str().to_string())
|
||||
.with_attribute(ATTR_START, m.start() as i64)
|
||||
.with_attribute(ATTR_END, m.end() as i64)
|
||||
.with_attribute(ATTR_START, m.start() as u64)
|
||||
.with_attribute(ATTR_END, m.end() as u64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -43,8 +43,8 @@ pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> List<Vecto
|
||||
line_height_ratio: item.attribute_cloned_or(ATTR_LINE_HEIGHT, defaults.line_height_ratio),
|
||||
letter_spacing: item.attribute_cloned_or(ATTR_LETTER_SPACING, defaults.letter_spacing),
|
||||
letter_tilt: item.attribute_cloned_or(ATTR_LETTER_TILT, defaults.letter_tilt),
|
||||
max_width: item.attribute::<f64>(ATTR_MAX_WIDTH).copied().filter(|width| *width > 0.),
|
||||
max_height: item.attribute::<f64>(ATTR_MAX_HEIGHT).copied().filter(|height| *height > 0.),
|
||||
max_width: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, defaults.max_width),
|
||||
max_height: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, defaults.max_height),
|
||||
align: item.attribute_cloned_or(ATTR_TEXT_ALIGN, defaults.align),
|
||||
};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use graphic_types::Vector;
|
||||
use vector_types::vector::VectorExt;
|
||||
use vector_types::vector::algorithms::shapes;
|
||||
use vector_types::vector::misc::BezierHandles;
|
||||
use vector_types::vector::misc::{ArcType, BoxCorners, GridType};
|
||||
use vector_types::vector::misc::{ArcType, AsU64, BoxCorners, GridType};
|
||||
use vector_types::vector::misc::{HandleId, SpiralType};
|
||||
use vector_types::vector::{PointId, SegmentId};
|
||||
|
||||
@@ -157,28 +157,30 @@ fn box_corners(
|
||||
|
||||
/// Generates an regular polygon shape like a triangle, square, pentagon, hexagon, heptagon, octagon, or any higher n-gon.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn regular_polygon(
|
||||
fn regular_polygon<T: AsU64>(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(6)]
|
||||
#[hard(3..)]
|
||||
sides: Item<i64>,
|
||||
#[implementations(u32, u64, f64)]
|
||||
sides: Item<T>,
|
||||
#[unit(" px")]
|
||||
#[default(50)]
|
||||
radius: Item<f64>,
|
||||
) -> Item<Vector> {
|
||||
let points = *sides.element() as u64;
|
||||
let points = sides.element().as_u64();
|
||||
Item::new_from_element(Vector::from_bezpath(shapes::regular_polygon_bezpath(DVec2::ZERO, points, *radius.element())))
|
||||
}
|
||||
|
||||
/// Generates an n-pointed star shape with inner and outer points at chosen radii from the center.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn star(
|
||||
fn star<T: AsU64>(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(5)]
|
||||
#[hard(2..)]
|
||||
sides: Item<i64>,
|
||||
#[implementations(u32, u64, f64)]
|
||||
sides: Item<T>,
|
||||
#[unit(" px")]
|
||||
#[default(50)]
|
||||
radius_1: Item<f64>,
|
||||
@@ -186,7 +188,7 @@ fn star(
|
||||
#[default(25)]
|
||||
radius_2: Item<f64>,
|
||||
) -> Item<Vector> {
|
||||
let points = *sides.element() as u64;
|
||||
let points = sides.element().as_u64();
|
||||
Item::new_from_element(Vector::from_bezpath(shapes::star_polygon_bezpath(DVec2::ZERO, points, *radius_1.element(), *radius_2.element())))
|
||||
}
|
||||
|
||||
@@ -306,17 +308,12 @@ fn grid<T: GridSpacing>(
|
||||
#[default(10)]
|
||||
#[implementations(f64, DVec2)]
|
||||
spacing: Item<T>,
|
||||
#[default(10)]
|
||||
#[hard(0..)]
|
||||
columns: Item<i64>,
|
||||
#[default(10)]
|
||||
#[hard(0..)]
|
||||
rows: Item<i64>,
|
||||
#[default(10)] columns: Item<u32>,
|
||||
#[default(10)] rows: Item<u32>,
|
||||
#[default(30., 30.)] angles: Item<DVec2>,
|
||||
#[default(true)] connect_cells: Item<bool>,
|
||||
) -> Item<Vector> {
|
||||
let (grid_type, columns, rows, angles, connect_cells) = (grid_type.into_element(), *columns.element(), *rows.element(), *angles.element(), *connect_cells.element());
|
||||
let (columns, rows) = (columns.max(0) as u32, rows.max(0) as u32);
|
||||
|
||||
let (x_spacing, y_spacing) = spacing.element().as_dvec2().into();
|
||||
let (angle_a, angle_b) = angles.into();
|
||||
@@ -404,11 +401,11 @@ mod tests {
|
||||
#[test]
|
||||
fn isometric_grid_test() {
|
||||
// Doesn't crash with weird angles
|
||||
grid((), (), item(GridType::Isometric), item(0.), item(5_i64), item(5_i64), item((0., 0.).into()), item(true));
|
||||
grid((), (), item(GridType::Isometric), item(90.), item(5_i64), item(5_i64), item((90., 90.).into()), item(true));
|
||||
grid((), (), item(GridType::Isometric), item(0.), item(5_u32), item(5_u32), item((0., 0.).into()), item(true));
|
||||
grid((), (), item(GridType::Isometric), item(90.), item(5_u32), item(5_u32), item((90., 90.).into()), item(true));
|
||||
|
||||
// Works properly
|
||||
let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_i64), item(5_i64), item((30., 30.).into()), item(true));
|
||||
let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_u32), item(5_u32), item((30., 30.).into()), item(true));
|
||||
assert_eq!(grid.element().point_domain.ids().len(), 5 * 5);
|
||||
assert_eq!(grid.element().segment_iter().count(), 4 * 5 + 4 * 9);
|
||||
for (_, segment, _, _) in grid.element().segment_iter() {
|
||||
@@ -420,7 +417,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn skew_isometric_grid_test() {
|
||||
let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_i64), item(5_i64), item((40., 30.).into()), item(true));
|
||||
let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_u32), item(5_u32), item((40., 30.).into()), item(true));
|
||||
assert_eq!(grid.element().point_domain.ids().len(), 5 * 5);
|
||||
assert_eq!(grid.element().segment_iter().count(), 4 * 5 + 4 * 9);
|
||||
for (_, segment, _, _) in grid.element().segment_iter() {
|
||||
@@ -434,7 +431,7 @@ mod tests {
|
||||
#[test]
|
||||
fn grid_disconnected_cells_test() {
|
||||
// A 3x3 rectangular grid has a 2x2 arrangement of cells, each its own closed quad subpath.
|
||||
let grid = grid((), (), item(GridType::Rectangular), item(10.), item(3_i64), item(3_i64), item((30., 30.).into()), item(false));
|
||||
let grid = grid((), (), item(GridType::Rectangular), item(10.), item(3_u32), item(3_u32), item((30., 30.).into()), item(false));
|
||||
let vector = grid.element();
|
||||
assert_eq!(vector.stroke_manipulator_groups().filter(|(_, closed)| *closed).count(), 4);
|
||||
assert_eq!(vector.point_domain.ids().len(), 4 * 4);
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user