mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
360
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0426a01e82 | ||
|
|
02f9cf3e6b | ||
|
|
33f7257e47 | ||
|
|
2921f44e5c | ||
|
|
1e91511f93 | ||
|
|
daf0231c0c | ||
|
|
92adc524ca | ||
|
|
9f0e0ebc96 | ||
|
|
a911bcc165 | ||
|
|
5bedfa4d11 | ||
|
|
e52af0cee0 | ||
|
|
fbdba0e545 | ||
|
|
6cdab6b95d | ||
|
|
e92faf763d | ||
|
|
305c36fb25 | ||
|
|
fc9e69a7a7 | ||
|
|
c9525d76c4 | ||
|
|
451922c217 | ||
|
|
92ea594a2a | ||
|
|
9d3abe385f | ||
|
|
96521333d6 | ||
|
|
d80651e85c | ||
|
|
a16a4c6354 | ||
|
|
d294d75198 | ||
|
|
8f7d3936f8 | ||
|
|
6961687172 | ||
|
|
38d479bdfa | ||
|
|
14660bdb64 | ||
|
|
b362452ff2 | ||
|
|
30573e6eb6 | ||
|
|
9ac039074d | ||
|
|
fdde760259 | ||
|
|
1be90ebb4a | ||
|
|
8fa250a9f9 | ||
|
|
0b70b18338 | ||
|
|
40efbc3261 | ||
|
|
39ce55ab61 | ||
|
|
3e1a9a1acf | ||
|
|
ab93e1f071 | ||
|
|
aa50c42930 | ||
|
|
c73976f407 | ||
|
|
cac1c47b86 | ||
|
|
1426f6401f | ||
|
|
6b951c1806 | ||
|
|
1f860aae6a | ||
|
|
e415714b04 | ||
|
|
a6016b2c03 | ||
|
|
c12f8f1115 | ||
|
|
4e7d72d4b8 | ||
|
|
41d42fe794 | ||
|
|
21dfe04bf8 | ||
|
|
0f26893ec1 | ||
|
|
0cd428f1b1 | ||
|
|
39ed962e16 | ||
|
|
6a5417ed3d | ||
|
|
29052a58db | ||
|
|
84d11b9285 | ||
|
|
5a6192bbd6 | ||
|
|
ca831c00db | ||
|
|
fe8ca88752 | ||
|
|
8fd2529e27 | ||
|
|
641fcc88c6 | ||
|
|
78e35eb6ea | ||
|
|
3302a3b0b8 | ||
|
|
41d295f140 | ||
|
|
a955d6b458 | ||
|
|
97bc10e4c3 | ||
|
|
3af6834d3c | ||
|
|
277641d27e | ||
|
|
f3e945c5d8 | ||
|
|
aef750153b | ||
|
|
f4d37524c8 | ||
|
|
e5b910f840 | ||
|
|
25f49e8750 | ||
|
|
1ef7c9c2c2 | ||
|
|
f34ec257e7 | ||
|
|
1e5b2c7f62 | ||
|
|
c6b669fc88 | ||
|
|
d814b610da | ||
|
|
5181c74205 | ||
|
|
4cb711e3f8 | ||
|
|
e8aea0728a | ||
|
|
6f809fda73 | ||
|
|
ba84e2a968 | ||
|
|
72387d17ad | ||
|
|
048a4c4b70 | ||
|
|
b262195549 | ||
|
|
68a2fb2be3 | ||
|
|
50911a6a25 | ||
|
|
79f3571b02 | ||
|
|
34ea9c59fd | ||
|
|
92ec2069ad | ||
|
|
20e70e7bc9 | ||
|
|
084f14e973 | ||
|
|
694d3d34b3 | ||
|
|
ed457093b1 | ||
|
|
7d44f6ec9e | ||
|
|
54c140e4f3 | ||
|
|
5987c449b2 | ||
|
|
c7605d12a6 | ||
|
|
d9533de9ea | ||
|
|
bc33e14c35 | ||
|
|
2b06d27729 | ||
|
|
b685ca77f2 | ||
|
|
e5b1fad675 | ||
|
|
eb11eec5bb | ||
|
|
182c2a1554 | ||
|
|
913d7093ea | ||
|
|
938fc1783a | ||
|
|
d452ac0de1 | ||
|
|
95bbeb6634 | ||
|
|
5176bfd331 | ||
|
|
db761cf8ed | ||
|
|
34e03038df | ||
|
|
bb3643541d | ||
|
|
ff99f3605c | ||
|
|
9cf037e992 | ||
|
|
888cdf17b0 | ||
|
|
9aef511891 | ||
|
|
0d88e8be9f | ||
|
|
56d38b3f61 | ||
|
|
a6c56c8655 | ||
|
|
2c84bb478f | ||
|
|
9cdaf06ca9 | ||
|
|
027218f16c | ||
|
|
f1ccb74625 | ||
|
|
cb5fabc6ad | ||
|
|
2448157af8 | ||
|
|
d718cdb225 | ||
|
|
dcc9059041 | ||
|
|
d70eae205d | ||
|
|
ed6922d7eb | ||
|
|
abb099a1c3 | ||
|
|
a4d01bfd11 | ||
|
|
d38c767312 | ||
|
|
aba941e81d | ||
|
|
8c67ad508f | ||
|
|
9ca897963f | ||
|
|
2575b94e8f | ||
|
|
b03e4fb215 | ||
|
|
c0eb2ee4ff | ||
|
|
faa5c9d3db | ||
|
|
bedb0d4159 | ||
|
|
94b9d279a2 | ||
|
|
7c4b029d76 | ||
|
|
9ba3c16e79 | ||
|
|
511b4da9f5 | ||
|
|
2c15dc838e | ||
|
|
73b2ef1d58 | ||
|
|
9d2031f7d0 | ||
|
|
7b609ea781 | ||
|
|
5e918af371 | ||
|
|
6e9cac3b32 | ||
|
|
893cbfe450 | ||
|
|
e40ee486a9 | ||
|
|
58182bc2d3 | ||
|
|
3fb8b10f80 | ||
|
|
6fe533a875 | ||
|
|
feea006fc3 | ||
|
|
73897111d0 | ||
|
|
e76dcb15aa | ||
|
|
538959ea90 | ||
|
|
c33f8ae75b | ||
|
|
3126a5b278 | ||
|
|
5f6c18893e | ||
|
|
cdc6f11d92 | ||
|
|
c4b22c03b9 | ||
|
|
6ab9d0360a | ||
|
|
01da817f61 | ||
|
|
040bd71f82 | ||
|
|
f2b0f7c533 | ||
|
|
a2918887f6 | ||
|
|
7b993c5de6 | ||
|
|
3da7f6cea3 | ||
|
|
7569bdb9cb | ||
|
|
4e8a44650e | ||
|
|
b4346fd47d | ||
|
|
e9a18a6437 | ||
|
|
77b0be5c15 | ||
|
|
4bceae26f2 | ||
|
|
c0f50d41d7 | ||
|
|
0b2aa3798a | ||
|
|
13cd718c90 | ||
|
|
39c7ba39cf | ||
|
|
6635e0aeff | ||
|
|
98dabd7ff5 | ||
|
|
a244cc13d0 | ||
|
|
fb71ea426d | ||
|
|
217f32eb88 | ||
|
|
7fb36123e9 | ||
|
|
46220ac268 | ||
|
|
887dbaca2c | ||
|
|
44369cb12b | ||
|
|
56c772de4c | ||
|
|
93e34d00e5 | ||
|
|
46f048b07c | ||
|
|
4b130b4319 | ||
|
|
da0f70bb5f | ||
|
|
5821816228 | ||
|
|
8eaa541c8c | ||
|
|
e4adf16eba | ||
|
|
a8d257e7d6 | ||
|
|
49c592013c | ||
|
|
80db9c13c8 | ||
|
|
cf87796072 | ||
|
|
8859e6b1a0 | ||
|
|
1f23991a72 | ||
|
|
2be252d7b4 | ||
|
|
2c1acbdc62 | ||
|
|
61e751f278 | ||
|
|
cdd62ed269 | ||
|
|
f12094ced6 | ||
|
|
b5c4aa4598 | ||
|
|
da8ae2be43 | ||
|
|
157c011953 | ||
|
|
ae6807f8e3 | ||
|
|
17ba74485a | ||
|
|
1f2eef5f8f | ||
|
|
1b6513b954 | ||
|
|
74fddff589 | ||
|
|
7e24f810c6 | ||
|
|
306cf1110f | ||
|
|
b610eede20 | ||
|
|
21f671555a | ||
|
|
951059aa3a | ||
|
|
e68254eff3 | ||
|
|
61cf619f4b | ||
|
|
7914a09d4b | ||
|
|
95e2cbca15 | ||
|
|
724bb0fc17 | ||
|
|
fb171cd5ac | ||
|
|
cb46be0430 | ||
|
|
7ffc9b9e3b | ||
|
|
58a65c69e9 | ||
|
|
d1d50ec469 | ||
|
|
e25e32ee8a | ||
|
|
d560a39856 | ||
|
|
00e08359a3 | ||
|
|
116ce622d4 | ||
|
|
082fb5d959 | ||
|
|
043f28cc23 | ||
|
|
b7413dd22c | ||
|
|
586737247e | ||
|
|
055b7f0055 | ||
|
|
4a042bade2 | ||
|
|
3aa018a15c | ||
|
|
8508dc6c9d | ||
|
|
fbba0cd037 | ||
|
|
ae7c51a964 | ||
|
|
0c49026c9a | ||
|
|
bc29166d4c | ||
|
|
0f3e3f7337 | ||
|
|
a03db0ac6c | ||
|
|
932ed8653e | ||
|
|
5ab3f067fe | ||
|
|
3df028cb18 | ||
|
|
e423dd96de | ||
|
|
bef58bf395 | ||
|
|
131abf5883 | ||
|
|
3859bd713e | ||
|
|
ac40f1838f | ||
|
|
9055a5f3d5 | ||
|
|
d32caeab52 | ||
|
|
15f4aa8f98 | ||
|
|
99ce2ea565 | ||
|
|
87200f3c2a | ||
|
|
214632c5ec | ||
|
|
64fb4eda61 | ||
|
|
f9e30c4c77 | ||
|
|
bfa48439c8 | ||
|
|
a717403db8 | ||
|
|
fdf13f91cb | ||
|
|
65e0969721 | ||
|
|
8f265e7660 | ||
|
|
98e6b97072 | ||
|
|
a3e9074955 | ||
|
|
04afada5b3 | ||
|
|
3e183fbd28 | ||
|
|
849d6a17be | ||
|
|
20ba069fe0 | ||
|
|
c82093f153 | ||
|
|
010785d8db | ||
|
|
69774d445c | ||
|
|
b42c632474 | ||
|
|
f195e363a5 | ||
|
|
40f99152ce | ||
|
|
3b1170b148 | ||
|
|
3a20091d3a | ||
|
|
e5206c3b50 | ||
|
|
fbc736e1cc | ||
|
|
d7da2ba9e7 | ||
|
|
a5784c8f0b | ||
|
|
83fbaca6f2 | ||
|
|
b6f73b0691 | ||
|
|
557f8020bb | ||
|
|
fb94d99807 | ||
|
|
264601c5f7 | ||
|
|
5db7e1816a | ||
|
|
5b02edfd9a | ||
|
|
7c0a4073e9 | ||
|
|
275100eab0 | ||
|
|
42cd2a4303 | ||
|
|
e4f81fc947 | ||
|
|
492cf18cb0 | ||
|
|
05630bab6e | ||
|
|
a465948ad4 | ||
|
|
63cf0151e2 | ||
|
|
9c7a633d5b | ||
|
|
166241b0e8 | ||
|
|
ea49f3c2fc | ||
|
|
100f81c307 | ||
|
|
886ff03ef2 | ||
|
|
7a1d1f3238 | ||
|
|
612afb7ebb | ||
|
|
daf3f25d21 | ||
|
|
a2de2a9c09 | ||
|
|
98be2b8c79 | ||
|
|
83fda4f08c | ||
|
|
20c6ba19d3 | ||
|
|
7eeb7d84cd | ||
|
|
7ddc66adbe | ||
|
|
c20a243fc2 | ||
|
|
3eecc31bfd | ||
|
|
7099f056dc | ||
|
|
9680d34abf | ||
|
|
592b2fbe32 | ||
|
|
60f80682c5 | ||
|
|
9fc4fcc7a0 | ||
|
|
7915800d73 | ||
|
|
c91be74a55 | ||
|
|
abe2a565d1 | ||
|
|
6154e4d219 | ||
|
|
62b7ccf40c | ||
|
|
9b45af854a | ||
|
|
562e6602eb | ||
|
|
8fb18012cf | ||
|
|
2b3161773f | ||
|
|
167d733f02 | ||
|
|
ee499be31f | ||
|
|
d385f3c69b | ||
|
|
e372f78b7e | ||
|
|
8686b2c891 | ||
|
|
e3aa32bc83 | ||
|
|
77d439ec35 | ||
|
|
c30054579f | ||
|
|
81a319430b | ||
|
|
1fb6fcb447 | ||
|
|
32d244e700 | ||
|
|
0877f9d50e | ||
|
|
14c1dd0397 | ||
|
|
daf7b3e7b9 | ||
|
|
bdf53070f2 | ||
|
|
0d0ec96709 | ||
|
|
6feaf4ec9d | ||
|
|
5541769dc5 | ||
|
|
1fccb112cb | ||
|
|
eb50be844b | ||
|
|
0f0f62c2e9 | ||
|
|
f5b1fee85f | ||
|
|
6f8c4b2adb |
No files matched your search
Generated
+8
-8
@@ -2008,6 +2008,7 @@ dependencies = [
|
|||||||
"graphene-hash",
|
"graphene-hash",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"gungraun",
|
"gungraun",
|
||||||
|
"interpreted-executor",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"log",
|
"log",
|
||||||
"mmap-io",
|
"mmap-io",
|
||||||
@@ -2038,6 +2039,7 @@ dependencies = [
|
|||||||
"core-types",
|
"core-types",
|
||||||
"dyn-any",
|
"dyn-any",
|
||||||
"glam",
|
"glam",
|
||||||
|
"graphene-hash",
|
||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"log",
|
"log",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
@@ -2312,9 +2314,9 @@ dependencies = [
|
|||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphene-std",
|
"graphene-std",
|
||||||
"graphite-editor",
|
"graphite-editor",
|
||||||
|
"graphite-wasm-wrapper",
|
||||||
"image",
|
"image",
|
||||||
"keyboard-types",
|
"keyboard-types",
|
||||||
"ron",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.18",
|
||||||
@@ -2374,6 +2376,7 @@ dependencies = [
|
|||||||
name = "graphite-proc-macros"
|
name = "graphite-proc-macros"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"convert_case",
|
||||||
"graphite-editor",
|
"graphite-editor",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -2385,17 +2388,17 @@ dependencies = [
|
|||||||
name = "graphite-wasm-wrapper"
|
name = "graphite-wasm-wrapper"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphene-std",
|
"graphene-std",
|
||||||
"graphite-editor",
|
"graphite-editor",
|
||||||
|
"graphite-proc-macros",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"log",
|
"log",
|
||||||
"node-macro",
|
|
||||||
"ron",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde-wasm-bindgen",
|
"serde-wasm-bindgen",
|
||||||
|
"serde_bytes",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"tsify",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"wasm-bindgen-futures",
|
"wasm-bindgen-futures",
|
||||||
"web-sys",
|
"web-sys",
|
||||||
@@ -2934,6 +2937,7 @@ dependencies = [
|
|||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphene-core",
|
"graphene-core",
|
||||||
"graphene-std",
|
"graphene-std",
|
||||||
|
"graphic-types",
|
||||||
"gungraun",
|
"gungraun",
|
||||||
"log",
|
"log",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
@@ -4878,15 +4882,11 @@ dependencies = [
|
|||||||
"core-types",
|
"core-types",
|
||||||
"dyn-any",
|
"dyn-any",
|
||||||
"glam",
|
"glam",
|
||||||
"graphene-core",
|
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"kurbo",
|
|
||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"serde",
|
"serde",
|
||||||
"tokio",
|
|
||||||
"vector-nodes",
|
|
||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
Generated
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"contextLine truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.2050787Line truncated
|
||||||
Generated
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"impleLine truncated
|
||||||
Generated
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":"","sources":[]}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"ValueLine truncated
|
||||||
Generated
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphiLine truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[2,{"inputs":Line truncated
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":Line truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":Line truncated
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0Line truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segLine truncated
|
||||||
Generated
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"StrinLine truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implemeLine truncated
|
||||||
Generated
+1
-1
@@ -1 +1 @@
|
|||||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
|
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodesLine truncated
|
||||||
+6
-2
@@ -14,13 +14,12 @@ use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEv
|
|||||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||||
use winit::window::WindowId;
|
use winit::window::WindowId;
|
||||||
|
|
||||||
use graphite_desktop_ui::{UiCommand, UiInstance};
|
|
||||||
|
|
||||||
use crate::dirs;
|
use crate::dirs;
|
||||||
use crate::event::{AppEvent, AppEventScheduler};
|
use crate::event::{AppEvent, AppEventScheduler};
|
||||||
use crate::persist;
|
use crate::persist;
|
||||||
use crate::preferences;
|
use crate::preferences;
|
||||||
use crate::render::{RenderError, RenderState};
|
use crate::render::{RenderError, RenderState};
|
||||||
|
use crate::ui::{UiCommand, UiInstance};
|
||||||
use crate::window::Window;
|
use crate::window::Window;
|
||||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
|
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
|
||||||
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||||
@@ -98,6 +97,11 @@ impl App {
|
|||||||
});
|
});
|
||||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
||||||
|
|
||||||
|
let completion_render_sender = start_render_sender.clone();
|
||||||
|
DesktopWrapper::set_completion_notifier(move || {
|
||||||
|
let _ = completion_render_sender.try_send(());
|
||||||
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
render_state: None,
|
render_state: None,
|
||||||
wgpu_context,
|
wgpu_context,
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
|
use crate::ui::Cursor;
|
||||||
use crate::wrapper::NodeGraphExecutionResult;
|
use crate::wrapper::NodeGraphExecutionResult;
|
||||||
use crate::wrapper::messages::DesktopWrapperMessage;
|
use crate::wrapper::messages::DesktopWrapperMessage;
|
||||||
|
|
||||||
pub(crate) enum AppEvent {
|
pub(crate) enum AppEvent {
|
||||||
UiUpdate(wgpu::Texture),
|
UiUpdate(wgpu::Texture),
|
||||||
CursorChange(graphite_desktop_ui::Cursor),
|
CursorChange(Cursor),
|
||||||
WebCommunicationInitialized,
|
WebCommunicationInitialized,
|
||||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||||
|
|||||||
+3
-2
@@ -3,12 +3,13 @@ use crate::cli::Cli;
|
|||||||
use crate::consts::APP_LOCK_FILE_NAME;
|
use crate::consts::APP_LOCK_FILE_NAME;
|
||||||
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
|
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use graphite_desktop_ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
|
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::process::ExitCode;
|
use std::process::ExitCode;
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
|
||||||
use winit::event_loop::EventLoop;
|
use winit::event_loop::EventLoop;
|
||||||
|
|
||||||
|
pub(crate) use graphite_desktop_ui as ui;
|
||||||
pub(crate) use graphite_desktop_wrapper as wrapper;
|
pub(crate) use graphite_desktop_wrapper as wrapper;
|
||||||
|
|
||||||
mod app;
|
mod app;
|
||||||
@@ -69,7 +70,7 @@ pub fn start() -> ExitCode {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
dirs::clear_dir(&graphite_desktop_ui::temp_dir_root());
|
dirs::clear_dir(&ui::temp_dir_root());
|
||||||
|
|
||||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||||
dirs::delete_old_cef_browser_directory();
|
dirs::delete_old_cef_browser_directory();
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ impl RenderState {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||||
match result {
|
match result {
|
||||||
Ok(texture) => {
|
Ok(texture) => {
|
||||||
self.overlays_texture = Some(texture.into());
|
self.overlays_texture = Some(texture.into());
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use crate::consts::APP_NAME;
|
use crate::consts::APP_NAME;
|
||||||
use crate::event::AppEventScheduler;
|
use crate::event::AppEventScheduler;
|
||||||
|
use crate::ui::Cursor;
|
||||||
use crate::wrapper::messages::MenuItem;
|
use crate::wrapper::messages::MenuItem;
|
||||||
use crate::wrapper::{WgpuInstance, WgpuSurface};
|
use crate::wrapper::{WgpuInstance, WgpuSurface};
|
||||||
use graphite_desktop_ui::Cursor;
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use winit::cursor::{CustomCursor, CustomCursorSource};
|
use winit::cursor::{CustomCursor, CustomCursorSource};
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
graphite-editor = { workspace = true }
|
graphite-editor = { workspace = true }
|
||||||
|
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
|
||||||
graphene-std = { workspace = true }
|
graphene-std = { workspace = true }
|
||||||
graph-craft = { workspace = true }
|
graph-craft = { workspace = true }
|
||||||
wgpu-executor = { workspace = true }
|
wgpu-executor = { workspace = true }
|
||||||
@@ -22,7 +23,6 @@ wgpu = { workspace = true }
|
|||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
dirs = { workspace = true }
|
dirs = { workspace = true }
|
||||||
ron = { workspace = true}
|
|
||||||
vello = { workspace = true }
|
vello = { workspace = true }
|
||||||
image = { workspace = true }
|
image = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
use graph_craft::application_io::PlatformApplicationIo;
|
use graph_craft::application_io::PlatformApplicationIo;
|
||||||
use graph_craft::application_io::resource::ResourceStorage;
|
use graph_craft::application_io::resource::ResourceStorage;
|
||||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||||
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake};
|
use graphite_editor::messages::frontend::FrontendMessage;
|
||||||
|
use graphite_editor::messages::prelude::Wake;
|
||||||
|
|
||||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -50,6 +52,10 @@ impl DesktopWrapper {
|
|||||||
executor.execute()
|
executor.execute()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
|
||||||
|
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||||
match result {
|
match result {
|
||||||
@@ -65,21 +71,10 @@ pub enum NodeGraphExecutionResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
|
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
|
||||||
if let Ok(string) = std::str::from_utf8(data) {
|
let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
|
||||||
if let Ok(message) = ron::de::from_str::<Message>(string) {
|
|
||||||
Some(DesktopWrapperMessage::FromWeb(message.into()))
|
Some(DesktopWrapperMessage::FromWeb(message.into()))
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
|
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
|
||||||
if let Ok(serialized) = ron::ser::to_string(&messages) {
|
graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
|
||||||
Some(serialized.into_bytes())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
pub mod node {
|
pub mod node {
|
||||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||||
pub const CONTEXT_FEATURES: &str = "context_features";
|
|
||||||
pub const VISIBLE: &str = "visible";
|
pub const VISIBLE: &str = "visible";
|
||||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use core_types::Context;
|
use core_types::Context;
|
||||||
use core_types::context::ContextDependencies;
|
|
||||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||||
use graph_craft::concrete;
|
use graph_craft::concrete;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
@@ -390,9 +389,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
|
|||||||
attributes
|
attributes
|
||||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||||
attributes
|
|
||||||
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
|
|
||||||
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
|
|
||||||
attributes
|
attributes
|
||||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||||
sources.sort_by(|(a, _), (b, _)| a.cmp(b));
|
sources.sort_by_key(|(a, _)| *a);
|
||||||
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
||||||
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
||||||
if later_key != kept_key {
|
if later_key != kept_key {
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
|
|||||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
compiler
|
||||||
|
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
|
||||||
|
.map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,11 +248,6 @@ fn test_nested_network_flattening() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_metadata_preservation() {
|
fn test_metadata_preservation() {
|
||||||
// Create a network with nodes that have non-default metadata
|
// Create a network with nodes that have non-default metadata
|
||||||
let context_features = ContextDependencies {
|
|
||||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let network = NodeNetwork {
|
let network = NodeNetwork {
|
||||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||||
nodes: [
|
nodes: [
|
||||||
@@ -260,7 +257,6 @@ fn test_metadata_preservation() {
|
|||||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||||
call_argument: concrete!(String),
|
call_argument: concrete!(String),
|
||||||
context_features,
|
|
||||||
visible: false, // Non-default value
|
visible: false, // Non-default value
|
||||||
skip_deduplication: true, // Non-default value
|
skip_deduplication: true, // Non-default value
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -294,8 +290,12 @@ fn test_metadata_preservation() {
|
|||||||
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
||||||
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
||||||
|
|
||||||
// Verify context_features is preserved
|
// Verify context_features is not stored
|
||||||
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
|
assert_eq!(
|
||||||
|
conv_node_0.context_features,
|
||||||
|
ContextDependencies::default(),
|
||||||
|
"context_features should resolve at compile, not round-trip"
|
||||||
|
);
|
||||||
|
|
||||||
// Verify visible is preserved
|
// Verify visible is preserved
|
||||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||||
|
|||||||
@@ -310,8 +310,8 @@ fn convert_node(
|
|||||||
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
||||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||||
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
|
|
||||||
// Regenerated during compilation; not stored.
|
// Regenerated during compilation; not stored.
|
||||||
|
context_features: Default::default(),
|
||||||
original_location: Default::default(),
|
original_location: Default::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use super::IconName;
|
use super::IconName;
|
||||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
|
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
|
||||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||||
@@ -14,7 +14,6 @@ use crate::messages::prelude::*;
|
|||||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::raster::Image;
|
|
||||||
use graphene_std::vector::style::FillChoiceUI;
|
use graphene_std::vector::style::FillChoiceUI;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
@@ -235,7 +234,7 @@ pub enum FrontendMessage {
|
|||||||
svg: String,
|
svg: String,
|
||||||
},
|
},
|
||||||
UpdateImageData {
|
UpdateImageData {
|
||||||
image_data: Vec<(u64, Image<SRGBA8>)>,
|
image_data: Vec<RasterizedImage>,
|
||||||
},
|
},
|
||||||
UpdateDocumentLayerDetails {
|
UpdateDocumentLayerDetails {
|
||||||
data: LayerPanelEntry,
|
data: LayerPanelEntry,
|
||||||
|
|||||||
@@ -82,3 +82,12 @@ pub struct EyedropperPreviewImage {
|
|||||||
pub width: u32,
|
pub width: u32,
|
||||||
pub height: u32,
|
pub height: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||||
|
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct RasterizedImage {
|
||||||
|
pub id: u64,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub pixels: serde_bytes::ByteBuf,
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::vector::style::FillChoiceUI;
|
use graphene_std::vector::style::FillChoiceUI;
|
||||||
@@ -291,7 +292,11 @@ impl LayoutMessageHandler {
|
|||||||
responses.add(callback_message);
|
responses.add(callback_message);
|
||||||
}
|
}
|
||||||
WidgetValueAction::Update => {
|
WidgetValueAction::Update => {
|
||||||
let callback_message = (node_type_input.on_update.callback)(&value.into());
|
let Value::String(ref node_type) = value else {
|
||||||
|
error!("NodeCatalog update was not of type: String, found {value:?}");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let callback_message = (node_type_input.on_update.callback)(&DefinitionIdentifier::from_serialized(node_type));
|
||||||
responses.add(callback_message);
|
responses.add(callback_message);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,11 +10,10 @@ use graphene_std::blending::BlendMode;
|
|||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::gradient::GradientStops;
|
use graphene_std::gradient::GradientStops;
|
||||||
use graphene_std::list::List;
|
use graphene_std::list::List;
|
||||||
use graphene_std::memo::IORecord;
|
|
||||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
|
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
|
||||||
use graphene_std::{Artboard, Color, Context, Graphic};
|
use graphene_std::{Artboard, Color, Graphic};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -167,8 +166,8 @@ macro_rules! generate_layout_downcast {
|
|||||||
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
|
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
|
||||||
if false { None }
|
if false { None }
|
||||||
$(
|
$(
|
||||||
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() {
|
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
|
||||||
Some(io.output.layout_with_breadcrumb($data))
|
Some(element.layout_with_breadcrumb($data))
|
||||||
}
|
}
|
||||||
)*
|
)*
|
||||||
else { None }
|
else { None }
|
||||||
@@ -178,8 +177,13 @@ macro_rules! generate_layout_downcast {
|
|||||||
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
||||||
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
||||||
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
|
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
|
||||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<NodeId>>>() {
|
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
|
||||||
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, data));
|
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
|
||||||
|
}
|
||||||
|
// The path's plain value form, produced by `path_of_subgraph` on leveled wires.
|
||||||
|
if let Some(path) = introspected_data.downcast_ref::<Vec<NodeId>>() {
|
||||||
|
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
|
||||||
|
return Some(table_node_id_path_layout_with_breadcrumb(&list, data));
|
||||||
}
|
}
|
||||||
generate_layout_downcast!(introspected_data, data, [
|
generate_layout_downcast!(introspected_data, data, [
|
||||||
List<Artboard>,
|
List<Artboard>,
|
||||||
@@ -308,7 +312,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TableItemLayout for Artboard {
|
impl TableItemLayout for Artboard<'_> {
|
||||||
fn type_name() -> &'static str {
|
fn type_name() -> &'static str {
|
||||||
"Artboard"
|
"Artboard"
|
||||||
}
|
}
|
||||||
@@ -324,7 +328,7 @@ impl TableItemLayout for Artboard {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TableItemLayout for Graphic {
|
impl TableItemLayout for Graphic<'_> {
|
||||||
fn type_name() -> &'static str {
|
fn type_name() -> &'static str {
|
||||||
"Graphic"
|
"Graphic"
|
||||||
}
|
}
|
||||||
@@ -337,6 +341,7 @@ impl TableItemLayout for Graphic {
|
|||||||
Self::Color(list) => list.identifier(),
|
Self::Color(list) => list.identifier(),
|
||||||
Self::Gradient(list) => list.identifier(),
|
Self::Gradient(list) => list.identifier(),
|
||||||
Self::Text(list) => list.identifier(),
|
Self::Text(list) => list.identifier(),
|
||||||
|
Self::Group(_) => "Group".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Don't put a breadcrumb for Graphic
|
// Don't put a breadcrumb for Graphic
|
||||||
@@ -352,6 +357,7 @@ impl TableItemLayout for Graphic {
|
|||||||
Self::Color(list) => list.layout_with_breadcrumb(data),
|
Self::Color(list) => list.layout_with_breadcrumb(data),
|
||||||
Self::Gradient(list) => list.layout_with_breadcrumb(data),
|
Self::Gradient(list) => list.layout_with_breadcrumb(data),
|
||||||
Self::Text(list) => list.layout_with_breadcrumb(data),
|
Self::Text(list) => list.layout_with_breadcrumb(data),
|
||||||
|
Self::Group(_) => Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1010,6 +1016,11 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
|
|||||||
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
|
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
|
||||||
return Some(table_node_id_path_layout_with_breadcrumb(path, data));
|
return Some(table_node_id_path_layout_with_breadcrumb(path, data));
|
||||||
}
|
}
|
||||||
|
// The path's plain value form, the layer-path marker's owned shape.
|
||||||
|
if let Some(path) = any.downcast_ref::<Vec<NodeId>>() {
|
||||||
|
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
|
||||||
|
return Some(table_node_id_path_layout_with_breadcrumb(&list, data));
|
||||||
|
}
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
( $($ty:ty),* $(,)? ) => {
|
( $($ty:ty),* $(,)? ) => {
|
||||||
$(
|
$(
|
||||||
|
|||||||
@@ -248,11 +248,11 @@ pub enum DocumentMessage {
|
|||||||
// `UpdateFillAttributes` and `UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
// `UpdateFillAttributes` and `UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
UpdateFillAttributes {
|
UpdateFillAttributes {
|
||||||
fill_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||||
},
|
},
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
UpdateStrokeAttributes {
|
UpdateStrokeAttributes {
|
||||||
stroke_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||||
},
|
},
|
||||||
Undo,
|
Undo,
|
||||||
UngroupSelectedLayers,
|
UngroupSelectedLayers,
|
||||||
|
|||||||
@@ -457,7 +457,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
|
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
|
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX);
|
||||||
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
|
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
|
||||||
|
|
||||||
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||||
@@ -474,7 +474,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
|
|
||||||
// Skip the rerender on all but the last input so the whole update triggers a single graph run
|
// Skip the rerender on all but the last input so the whole update triggers a single graph run
|
||||||
self.set_input_with_refresh(
|
self.set_input_with_refresh(
|
||||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX),
|
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX),
|
||||||
NodeInput::value(TaggedValue::Gradient(gradient), false),
|
NodeInput::value(TaggedValue::Gradient(gradient), false),
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
@@ -715,7 +715,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::INDEX);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||||
@@ -729,7 +729,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<graphene_std::list::List<f64>>::INDEX);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::INDEX);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ use graphene_std::raster_types::{CPU, Raster};
|
|||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use serde_json::Value;
|
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
pub struct NodePropertiesContext<'a> {
|
pub struct NodePropertiesContext<'a> {
|
||||||
@@ -89,12 +88,8 @@ impl DefinitionIdentifier {
|
|||||||
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
|
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Value> for DefinitionIdentifier {
|
|
||||||
fn from(value: Value) -> Self {
|
|
||||||
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
|
|
||||||
|
|
||||||
|
pub fn from_serialized(s: &str) -> Self {
|
||||||
match s.split_once(':') {
|
match s.split_once(':') {
|
||||||
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
|
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
|
||||||
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
|
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
|
||||||
@@ -164,7 +159,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// Secondary (left) input type coercion
|
// Collection of the content into the layer's group; the wrap keeps
|
||||||
|
// the content level's element type for the legacy boundary.
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::wrap_graphic::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphic::wrap_graphic::IDENTIFIER),
|
||||||
@@ -179,12 +175,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![
|
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
|
||||||
NodeInput::node(NodeId(1), 0),
|
implementation: DocumentNodeImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
|
||||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
|
||||||
NodeInput::node(NodeId(2), 0),
|
|
||||||
],
|
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// The monitor node is used to display a thumbnail in the UI
|
// The monitor node is used to display a thumbnail in the UI
|
||||||
@@ -241,7 +233,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// 3: write_attribute
|
// 3: stamp_layer_path
|
||||||
DocumentNodeMetadata {
|
DocumentNodeMetadata {
|
||||||
persistent_metadata: DocumentNodePersistentMetadata {
|
persistent_metadata: DocumentNodePersistentMetadata {
|
||||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
||||||
@@ -292,7 +284,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
call_argument: generic!(T),
|
call_argument: generic!(T),
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||||
inputs: vec![
|
inputs: vec![
|
||||||
NodeInput::import(concrete!(TaggedValue), 1),
|
NodeInput::node(NodeId(6), 0),
|
||||||
NodeInput::import(concrete!(TaggedValue), 2),
|
NodeInput::import(concrete!(TaggedValue), 2),
|
||||||
NodeInput::import(concrete!(TaggedValue), 3),
|
NodeInput::import(concrete!(TaggedValue), 3),
|
||||||
NodeInput::import(concrete!(TaggedValue), 4),
|
NodeInput::import(concrete!(TaggedValue), 4),
|
||||||
@@ -309,17 +301,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![
|
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||||
NodeInput::node(NodeId(0), 0),
|
implementation: DocumentNodeImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
|
||||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
|
||||||
NodeInput::node(NodeId(1), 0),
|
|
||||||
],
|
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// The monitor node is used to display a thumbnail in the UI.
|
// The monitor node is used to display a thumbnail in the UI.
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
||||||
call_argument: generic!(T),
|
call_argument: generic!(T),
|
||||||
skip_deduplication: true,
|
skip_deduplication: true,
|
||||||
@@ -333,6 +321,27 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
|
// Content coercion into a graphic level, evaluated within the artboard's footprint
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::import(concrete!(TaggedValue), 2)],
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(artboard::translate_footprint::IDENTIFIER),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
// Lifts the artboard element onto a one-lane level so it concatenates with the base stack
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![
|
||||||
|
NodeInput::node(NodeId(2), 0),
|
||||||
|
NodeInput::value(TaggedValue::U32(1), false),
|
||||||
|
NodeInput::value(TaggedValue::Bool(false), false),
|
||||||
|
],
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -400,7 +409,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// 2: write_attribute
|
// 2: stamp_layer_path
|
||||||
DocumentNodeMetadata {
|
DocumentNodeMetadata {
|
||||||
persistent_metadata: DocumentNodePersistentMetadata {
|
persistent_metadata: DocumentNodePersistentMetadata {
|
||||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
||||||
@@ -424,6 +433,30 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
|
// 5: to_graphic
|
||||||
|
DocumentNodeMetadata {
|
||||||
|
persistent_metadata: DocumentNodePersistentMetadata {
|
||||||
|
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-35, -3)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
// 6: translate_footprint
|
||||||
|
DocumentNodeMetadata {
|
||||||
|
persistent_metadata: DocumentNodePersistentMetadata {
|
||||||
|
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-28, -3)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
// 7: repeat (the one-lane lift)
|
||||||
|
DocumentNodeMetadata {
|
||||||
|
persistent_metadata: DocumentNodePersistentMetadata {
|
||||||
|
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-10, -3)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -924,7 +957,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||||
nodes: [
|
nodes: [
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(concrete!(String), 1)],
|
inputs: vec![
|
||||||
|
NodeInput::value(TaggedValue::None, false),
|
||||||
|
NodeInput::import(concrete!(String), 1),
|
||||||
|
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
|
||||||
|
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||||
|
],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
@@ -999,7 +1037,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(concrete!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
|
inputs: vec![
|
||||||
|
NodeInput::value(TaggedValue::None, false),
|
||||||
|
NodeInput::import(generic!(T), 0),
|
||||||
|
NodeInput::import(concrete!(Footprint), 1),
|
||||||
|
NodeInput::node(NodeId(1), 0),
|
||||||
|
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
|
||||||
|
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||||
|
],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
|
|||||||
+5
-6
@@ -29,7 +29,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
|||||||
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
|
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
|
||||||
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||||
let node_registry = NODE_REGISTRY.lock().unwrap();
|
let node_registry = NODE_REGISTRY.lock().unwrap();
|
||||||
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new();
|
let empty_implementations: Vec<RegistryEntry> = Vec::new();
|
||||||
let context_type = concrete!(Context);
|
let context_type = concrete!(Context);
|
||||||
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
|
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
|
||||||
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
|
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
|
||||||
@@ -42,18 +42,17 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
|||||||
fields,
|
fields,
|
||||||
description,
|
description,
|
||||||
properties,
|
properties,
|
||||||
context_features,
|
|
||||||
..
|
..
|
||||||
} = metadata;
|
} = metadata;
|
||||||
|
|
||||||
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
|
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
|
||||||
|
|
||||||
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
|
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||||
|
|
||||||
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
|
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
|
||||||
implementations.iter().map(|(_, io)| &io.call_argument).collect()
|
implementations.iter().map(|entry| &entry.io.call_argument).collect()
|
||||||
} else if let Some(impls) = extended_node_registry.get(id) {
|
} else if let Some(impls) = extended_node_registry.get(id) {
|
||||||
impls.keys().map(|io| &io.call_argument).collect()
|
impls.iter().map(|entry| &entry.io.call_argument).collect()
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
@@ -78,7 +77,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
|||||||
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
|
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
|
||||||
visible: true,
|
visible: true,
|
||||||
skip_deduplication: false,
|
skip_deduplication: false,
|
||||||
context_features: ContextDependencies::from(context_features.as_slice()),
|
context_features: ContextDependencies::default(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||||
|
|||||||
@@ -1769,7 +1769,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
|
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
|
||||||
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
|
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
|
||||||
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
|
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
|
||||||
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::<graphene_std::list::List<Graphic>>::INDEX;
|
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::INDEX;
|
||||||
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
|
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
|
||||||
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
|
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ use graph_craft::application_io::resource::ResourceId;
|
|||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||||
use graph_craft::{Type, concrete};
|
use graph_craft::{Type, concrete};
|
||||||
use graphene_std::Graphic;
|
|
||||||
use graphene_std::NodeInputDecleration;
|
use graphene_std::NodeInputDecleration;
|
||||||
use graphene_std::animation::RealTimeMode;
|
use graphene_std::animation::RealTimeMode;
|
||||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||||
@@ -252,6 +251,10 @@ pub(crate) fn property_from_type(
|
|||||||
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||||
Some(x) if x == TypeId::of::<List<GradientStops>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
Some(x) if x == TypeId::of::<List<GradientStops>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
Some(x) if x == TypeId::of::<List<BrushStroke>>() => brush_strokes_widget(default_info).into(),
|
Some(x) if x == TypeId::of::<List<BrushStroke>>() => brush_strokes_widget(default_info).into(),
|
||||||
|
// Leveled wires type by their element; each element keeps its list form's widget.
|
||||||
|
Some(x) if x == TypeId::of::<Color>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||||
|
Some(x) if x == TypeId::of::<GradientStops>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
|
Some(x) if x == TypeId::of::<BrushStroke>() => brush_strokes_widget(default_info).into(),
|
||||||
// ============
|
// ============
|
||||||
// STRUCT TYPES
|
// STRUCT TYPES
|
||||||
// ============
|
// ============
|
||||||
@@ -323,6 +326,7 @@ pub(crate) fn property_from_type(
|
|||||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||||
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||||
|
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
|
||||||
};
|
};
|
||||||
|
|
||||||
extra_widgets.push(widgets);
|
extra_widgets.push(widgets);
|
||||||
@@ -2167,7 +2171,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
|||||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||||
|
|
||||||
// Corner Radius
|
// Corner Radius
|
||||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::<f64>::INDEX, true, context));
|
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::INDEX, true, context));
|
||||||
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||||
|
|
||||||
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
||||||
@@ -2187,7 +2191,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
|||||||
};
|
};
|
||||||
if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() {
|
if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() {
|
||||||
// Values
|
// Values
|
||||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::<f64>::INDEX) else {
|
let Some(input) = document_node.inputs.get(CornerRadiusInput::INDEX) else {
|
||||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
return vec![];
|
return vec![];
|
||||||
};
|
};
|
||||||
@@ -2215,7 +2219,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
|||||||
.into(),
|
.into(),
|
||||||
NodeGraphMessage::SetInputValue {
|
NodeGraphMessage::SetInputValue {
|
||||||
node_id,
|
node_id,
|
||||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
input_index: CornerRadiusInput::INDEX,
|
||||||
value: TaggedValue::F64(uniform_val),
|
value: TaggedValue::F64(uniform_val),
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
@@ -2235,7 +2239,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
|||||||
.into(),
|
.into(),
|
||||||
NodeGraphMessage::SetInputValue {
|
NodeGraphMessage::SetInputValue {
|
||||||
node_id,
|
node_id,
|
||||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
input_index: CornerRadiusInput::INDEX,
|
||||||
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
@@ -2258,13 +2262,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
|||||||
};
|
};
|
||||||
TextInput::default()
|
TextInput::default()
|
||||||
.value(individual_val.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
.value(individual_val.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||||
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::<f64>::INDEX))
|
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::INDEX))
|
||||||
.widget_instance()
|
.widget_instance()
|
||||||
} else {
|
} else {
|
||||||
NumberInput::default()
|
NumberInput::default()
|
||||||
.value(Some(uniform_val))
|
.value(Some(uniform_val))
|
||||||
.unit(" px")
|
.unit(" px")
|
||||||
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::<f64>::INDEX))
|
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::INDEX))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance()
|
.widget_instance()
|
||||||
};
|
};
|
||||||
@@ -2359,7 +2363,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
|||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>();
|
let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
|
||||||
input_types.sort_by_key(|ty| ty.type_name());
|
input_types.sort_by_key(|ty| ty.type_name());
|
||||||
let input_type = input_types.first().cloned();
|
let input_type = input_types.first().cloned();
|
||||||
|
|
||||||
@@ -2452,13 +2456,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
|||||||
Other,
|
Other,
|
||||||
}
|
}
|
||||||
|
|
||||||
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::INDEX);
|
let connector = InputConnector::node(node_id, FillInput::INDEX);
|
||||||
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
|
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
|
||||||
|
|
||||||
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
|
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
|
||||||
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, context));
|
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::INDEX, false, context));
|
||||||
|
|
||||||
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::<List<Graphic>>::INDEX).is_some_and(|input| input.is_exposed())) {
|
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::INDEX).is_some_and(|input| input.is_exposed())) {
|
||||||
return vec![LayoutGroup::row(widgets_first_row)];
|
return vec![LayoutGroup::row(widgets_first_row)];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2469,7 +2473,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
|||||||
let fill = match input_type.compiled_nested_type() {
|
let fill = match input_type.compiled_nested_type() {
|
||||||
Some(ty) if ty == &concrete!(List<Color>) => {
|
Some(ty) if ty == &concrete!(List<Color>) => {
|
||||||
if let Ok(document_node) = get_document_node(node_id, context) {
|
if let Ok(document_node) = get_document_node(node_id, context) {
|
||||||
let color = match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
|
let color = match document_node.inputs[FillInput::INDEX].as_value() {
|
||||||
Some(&TaggedValue::Color(c)) => c,
|
Some(&TaggedValue::Color(c)) => c,
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
@@ -2520,7 +2524,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
|||||||
let reverse_button = IconButton::new("Reverse", 24)
|
let reverse_button = IconButton::new("Reverse", 24)
|
||||||
.tooltip_label("Reverse Stops")
|
.tooltip_label("Reverse Stops")
|
||||||
.tooltip_description("Reverse the gradient color stops.")
|
.tooltip_description("Reverse the gradient color stops.")
|
||||||
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::<List<Graphic>>::INDEX))
|
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::INDEX))
|
||||||
.widget_instance();
|
.widget_instance();
|
||||||
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||||
widgets_first_row.push(reverse_button);
|
widgets_first_row.push(reverse_button);
|
||||||
@@ -2544,7 +2548,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
|||||||
messages: Box::new([
|
messages: Box::new([
|
||||||
NodeGraphMessage::SetInputValue {
|
NodeGraphMessage::SetInputValue {
|
||||||
node_id,
|
node_id,
|
||||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
input_index: FillInput::INDEX,
|
||||||
value: TaggedValue::Color(color),
|
value: TaggedValue::Color(color),
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
@@ -2561,7 +2565,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
|||||||
messages: Box::new([
|
messages: Box::new([
|
||||||
NodeGraphMessage::SetInputValue {
|
NodeGraphMessage::SetInputValue {
|
||||||
node_id,
|
node_id,
|
||||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
input_index: FillInput::INDEX,
|
||||||
value: TaggedValue::Gradient(gradient.clone()),
|
value: TaggedValue::Gradient(gradient.clone()),
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
@@ -2602,11 +2606,11 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
|||||||
let entries = vec![
|
let entries = vec![
|
||||||
RadioEntryData::new("solid")
|
RadioEntryData::new("solid")
|
||||||
.label("Solid")
|
.label("Solid")
|
||||||
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::<List<Graphic>>::INDEX))
|
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::INDEX))
|
||||||
.on_commit(commit_value),
|
.on_commit(commit_value),
|
||||||
RadioEntryData::new("gradient")
|
RadioEntryData::new("gradient")
|
||||||
.label("Gradient")
|
.label("Gradient")
|
||||||
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::<List<Graphic>>::INDEX))
|
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::INDEX))
|
||||||
.on_commit(commit_value),
|
.on_commit(commit_value),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -2712,14 +2716,14 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
|||||||
_ => &StrokeJoin::Miter,
|
_ => &StrokeJoin::Miter,
|
||||||
};
|
};
|
||||||
|
|
||||||
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::<List<f64>>::INDEX].as_value() {
|
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::INDEX].as_value() {
|
||||||
Some(TaggedValue::F64Array(values)) => values.is_empty(),
|
Some(TaggedValue::F64Array(values)) => values.is_empty(),
|
||||||
_ => true,
|
_ => true,
|
||||||
};
|
};
|
||||||
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
|
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
|
||||||
|
|
||||||
let color = color_widget(
|
let color = color_widget(
|
||||||
ParameterWidgetsInfo::new(node_id, PaintInput::<List<Graphic>>::INDEX, true, context),
|
ParameterWidgetsInfo::new(node_id, PaintInput::INDEX, true, context),
|
||||||
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
||||||
);
|
);
|
||||||
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput::INDEX, true, context), NumberInput::default().unit(" px").min(0.));
|
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput::INDEX, true, context), NumberInput::default().unit(" px").min(0.));
|
||||||
@@ -2739,10 +2743,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
|||||||
.for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput::INDEX, true, context))
|
.for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput::INDEX, true, context))
|
||||||
.property_row();
|
.property_row();
|
||||||
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
||||||
let dash_lengths = array_of_number_widget(
|
let dash_lengths = array_of_number_widget(ParameterWidgetsInfo::new(node_id, DashLengthsInput::INDEX, true, context), TextInput::default().centered(true));
|
||||||
ParameterWidgetsInfo::new(node_id, DashLengthsInput::<List<f64>>::INDEX, true, context),
|
|
||||||
TextInput::default().centered(true),
|
|
||||||
);
|
|
||||||
let number_input = disabled_number_input;
|
let number_input = disabled_number_input;
|
||||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput::INDEX, true, context), number_input);
|
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput::INDEX, true, context), number_input);
|
||||||
|
|
||||||
|
|||||||
@@ -31,11 +31,11 @@ impl FrontendGraphDataType {
|
|||||||
TaggedValue::String(_) => Self::Typography,
|
TaggedValue::String(_) => Self::Typography,
|
||||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||||
n if n == std::any::type_name::<List<Graphic>>() => Self::Graphic,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => Self::Graphic,
|
||||||
n if n == std::any::type_name::<List<Artboard>>() => Self::Artboard,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => Self::Artboard,
|
||||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => Self::Raster,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => Self::Raster,
|
||||||
n if n == std::any::type_name::<List<Vector>>() => Self::Vector,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => Self::Vector,
|
||||||
n if n == std::any::type_name::<List<String>>() => Self::Typography,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => Self::Typography,
|
||||||
_ => Self::General,
|
_ => Self::General,
|
||||||
},
|
},
|
||||||
_ => Self::General,
|
_ => Self::General,
|
||||||
|
|||||||
@@ -20,6 +20,27 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
|||||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Dev tool: writes each demo's migrated re-save into the directory named by `DEMO_OUT`, leaving the checked-in originals untouched.
|
||||||
|
#[test]
|
||||||
|
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
||||||
|
fn migrate_demo_artwork_into_demo_out() {
|
||||||
|
use crate::messages::portfolio::document_migration::{document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades};
|
||||||
|
let out_dir = std::env::var("DEMO_OUT").expect("set DEMO_OUT to the output directory");
|
||||||
|
for entry in std::fs::read_dir("../demo-artwork").unwrap() {
|
||||||
|
let path = entry.unwrap().path();
|
||||||
|
if path.extension().and_then(|extension| extension.to_str()) != Some("graphite") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let content = std::fs::read_to_string(&path).unwrap();
|
||||||
|
let content = document_migration_string_preprocessing(content);
|
||||||
|
let reset = document_migration_reset_node_definition(&content);
|
||||||
|
let mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
|
||||||
|
document_migration_upgrades(&mut document, reset);
|
||||||
|
let out = format!("{out_dir}/{}", path.file_name().unwrap().to_string_lossy());
|
||||||
|
std::fs::write(out, document.serialize_document()).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
|
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
|
||||||
/// iterate every node addressable from the metadata side.
|
/// iterate every node addressable from the metadata side.
|
||||||
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
||||||
|
|||||||
@@ -43,10 +43,10 @@ pub struct DocumentMetadata {
|
|||||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||||
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
||||||
/// information that lives on the list.
|
/// information that lives on the list.
|
||||||
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||||
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
|
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
|
||||||
/// stroke paint information that lives on the list.
|
/// stroke paint information that lives on the list.
|
||||||
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||||
/// Transform from document space to viewport space.
|
/// Transform from document space to viewport space.
|
||||||
pub document_to_viewport: DAffine2,
|
pub document_to_viewport: DAffine2,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ use graph_craft::Type;
|
|||||||
use graph_craft::application_io::resource::ResourceId;
|
use graph_craft::application_io::resource::ResourceId;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||||
use graphene_std::ContextDependencies;
|
|
||||||
use graphene_std::Graphic;
|
use graphene_std::Graphic;
|
||||||
use graphene_std::list::List;
|
use graphene_std::list::List;
|
||||||
use graphene_std::math::quad::Quad;
|
use graphene_std::math::quad::Quad;
|
||||||
@@ -3441,12 +3440,12 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Update the per-layer `ATTR_FILL` snapshot.
|
/// Update the per-layer `ATTR_FILL` snapshot.
|
||||||
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
|
||||||
self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
|
self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the per-layer `ATTR_STROKE` snapshot.
|
/// Update the per-layer `ATTR_STROKE` snapshot.
|
||||||
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
|
||||||
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
|
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4090,18 +4089,6 @@ impl NodeNetworkInterface {
|
|||||||
node.call_argument = call_argument;
|
node.call_argument = call_argument;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_context_features(&mut self, node_id: &NodeId, network_path: &[NodeId], context_features: ContextDependencies) {
|
|
||||||
let Some(network) = self.network_mut(network_path) else {
|
|
||||||
log::error!("Could not get nested network in set_context_features");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let Some(node) = network.nodes.get_mut(node_id) else {
|
|
||||||
log::error!("Could not get node in set_context_features");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
node.context_features = context_features;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Lightweight version of `set_input` for bulk import operations.
|
/// Lightweight version of `set_input` for bulk import operations.
|
||||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||||
|
|||||||
+12
-10
@@ -65,11 +65,11 @@ impl TypeSource {
|
|||||||
TaggedValue::String(_) => FrontendGraphDataType::Typography,
|
TaggedValue::String(_) => FrontendGraphDataType::Typography,
|
||||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||||
n if n == std::any::type_name::<List<Graphic>>() => FrontendGraphDataType::Graphic,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => FrontendGraphDataType::Graphic,
|
||||||
n if n == std::any::type_name::<List<Artboard>>() => FrontendGraphDataType::Artboard,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => FrontendGraphDataType::Artboard,
|
||||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => FrontendGraphDataType::Raster,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => FrontendGraphDataType::Raster,
|
||||||
n if n == std::any::type_name::<List<Vector>>() => FrontendGraphDataType::Vector,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => FrontendGraphDataType::Vector,
|
||||||
n if n == std::any::type_name::<List<String>>() => FrontendGraphDataType::Typography,
|
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => FrontendGraphDataType::Typography,
|
||||||
_ => FrontendGraphDataType::General,
|
_ => FrontendGraphDataType::General,
|
||||||
},
|
},
|
||||||
_ => FrontendGraphDataType::General,
|
_ => FrontendGraphDataType::General,
|
||||||
@@ -253,8 +253,9 @@ impl NodeNetworkInterface {
|
|||||||
};
|
};
|
||||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||||
implementations
|
implementations
|
||||||
.keys()
|
.iter()
|
||||||
.filter_map(|node_io| {
|
.filter_map(|entry| {
|
||||||
|
let node_io = &entry.io;
|
||||||
// Check if this NodeIOTypes implementation is valid for the other inputs
|
// Check if this NodeIOTypes implementation is valid for the other inputs
|
||||||
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
||||||
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
|
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
|
||||||
@@ -293,8 +294,9 @@ impl NodeNetworkInterface {
|
|||||||
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
|
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
|
||||||
|
|
||||||
implementations
|
implementations
|
||||||
.keys()
|
.iter()
|
||||||
.filter_map(|node_io| {
|
.filter_map(|entry| {
|
||||||
|
let node_io = &entry.io;
|
||||||
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
|
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -323,7 +325,7 @@ impl NodeNetworkInterface {
|
|||||||
log::error!("Protonode {render_node:?} not found in registry");
|
log::error!("Protonode {render_node:?} not found in registry");
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
implementations.keys().map(|types| types.inputs[1].clone()).collect()
|
implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1024,6 +1024,12 @@ fn replace_optional_f64_null(input: &str) -> String {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serialized proto identifiers of the pre-flip Merge and Artboard layer internals.
|
||||||
|
/// A document containing any of them predates the leveled-records flip and rebuilds its
|
||||||
|
/// layer definitions through the same reset mechanism as the `SourceNodeIdNode` entry in
|
||||||
|
/// `document_migration_reset_node_definition`.
|
||||||
|
pub const FLIP_RESET_NODE_MARKERS: &[&str] = &["graphic_nodes::graphic::WriteAttributeNode"];
|
||||||
|
|
||||||
pub fn document_migration_reset_node_definition(document_serialized_content: &str) -> bool {
|
pub fn document_migration_reset_node_definition(document_serialized_content: &str) -> bool {
|
||||||
// Upgrade a document being opened to use fresh copies of all nodes
|
// Upgrade a document being opened to use fresh copies of all nodes
|
||||||
if document_serialized_content.contains("node_output_index") {
|
if document_serialized_content.contains("node_output_index") {
|
||||||
@@ -1045,6 +1051,12 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The leveled-records flip replaced the layer internals; documents from before it rebuild
|
||||||
|
// their layer definitions.
|
||||||
|
if FLIP_RESET_NODE_MARKERS.iter().any(|marker| document_serialized_content.contains(marker)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1379,6 +1391,34 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
|
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
|
||||||
let node_definition = resolve_document_node_type(&reference)?;
|
let node_definition = resolve_document_node_type(&reference)?;
|
||||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||||
|
|
||||||
|
// The leveled-records flip moved the Copy to Points content wire ahead of the points wire.
|
||||||
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::copy_to_points::IDENTIFIER) {
|
||||||
|
let mut node_template = node_definition.default_node_template();
|
||||||
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[1].clone(), network_path);
|
||||||
|
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[0].clone(), network_path);
|
||||||
|
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
|
||||||
|
document.network_interface.set_input(&InputConnector::node(*node_id, index), input, network_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The leveled-records flip moved the Repeat on Points content wire ahead of the points wire.
|
||||||
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::repeat::repeat_on_points::IDENTIFIER) {
|
||||||
|
let mut node_template = node_definition.default_node_template();
|
||||||
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[1].clone(), network_path);
|
||||||
|
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[0].clone(), network_path);
|
||||||
|
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
|
||||||
|
document.network_interface.set_input(&InputConnector::node(*node_id, index), input, network_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The leveled-records flip gave Mandelbrot a unit primary input.
|
||||||
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||||
|
let mut node_template = node_definition.default_node_template();
|
||||||
|
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally
|
// Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally
|
||||||
@@ -2401,15 +2441,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add context features to nodes that don't have them (fine-grained context caching migration)
|
|
||||||
if node.context_features == graphene_std::ContextDependencies::default()
|
|
||||||
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
|
|
||||||
&& let Some(node_definition) = resolve_document_node_type(&reference)
|
|
||||||
{
|
|
||||||
let context_features = node_definition.node_template.document_node.context_features;
|
|
||||||
document.network_interface.set_context_features(node_id, network_path, context_features);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the "Scale Type" parameter to the "Decompose Scale" node
|
// Add the "Scale Type" parameter to the "Decompose Scale" node
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
@@ -2572,6 +2603,13 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_flip_reset_markers_keep_the_historical_merge_internals_spelling() {
|
||||||
|
// The node itself is removed; the marker matches its spelling in
|
||||||
|
// documents saved before the flip, which must stay stable.
|
||||||
|
assert_eq!(FLIP_RESET_NODE_MARKERS, &["graphic_nodes::graphic::WriteAttributeNode"]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_no_duplicate_node_replacements() {
|
fn test_no_duplicate_node_replacements() {
|
||||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ use glam::{DAffine2, DVec2};
|
|||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
|
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
|
||||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||||
|
use graphene_std::Color;
|
||||||
use graphene_std::NodeInputDecleration;
|
use graphene_std::NodeInputDecleration;
|
||||||
use graphene_std::list::List;
|
|
||||||
use graphene_std::raster::BlendMode;
|
use graphene_std::raster::BlendMode;
|
||||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||||
use graphene_std::subpath::Subpath;
|
use graphene_std::subpath::Subpath;
|
||||||
@@ -16,7 +16,6 @@ use graphene_std::text::{Font, TypesettingConfig};
|
|||||||
use graphene_std::vector::misc::ManipulatorPointId;
|
use graphene_std::vector::misc::ManipulatorPointId;
|
||||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||||
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
|
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
|
||||||
use graphene_std::{Color, Graphic};
|
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
|
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
|
||||||
@@ -275,14 +274,14 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
|
|||||||
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||||
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
|
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Determine the input connector where the gradient chain enters the layer.
|
/// Determine the input connector where the gradient chain enters the layer.
|
||||||
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
|
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
|
||||||
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
|
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
|
||||||
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
|
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
|
||||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)
|
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX)
|
||||||
} else {
|
} else {
|
||||||
InputConnector::node(layer.to_node(), 1)
|
InputConnector::node(layer.to_node(), 1)
|
||||||
}
|
}
|
||||||
@@ -303,7 +302,7 @@ pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_i
|
|||||||
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||||
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)? else {
|
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)? else {
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
Some(*node_id)
|
Some(*node_id)
|
||||||
@@ -317,7 +316,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
|||||||
.document_network()
|
.document_network()
|
||||||
.nodes
|
.nodes
|
||||||
.get(&fill_node_id)
|
.get(&fill_node_id)
|
||||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX))
|
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::INDEX))
|
||||||
.and_then(|input| input.as_value())
|
.and_then(|input| input.as_value())
|
||||||
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
|
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
|
||||||
}
|
}
|
||||||
@@ -363,7 +362,7 @@ pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
|
|||||||
/// Get the current fill of a layer from the closest "Fill" node.
|
/// Get the current fill of a layer from the closest "Fill" node.
|
||||||
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
|
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
|
||||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||||
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? else {
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
color
|
color
|
||||||
@@ -570,7 +569,7 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
|||||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||||
_ => PaintOrder::default(),
|
_ => PaintOrder::default(),
|
||||||
};
|
};
|
||||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
|
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::INDEX) {
|
||||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||||
_ => Vec::new(),
|
_ => Vec::new(),
|
||||||
};
|
};
|
||||||
@@ -638,7 +637,7 @@ pub struct FillNodeGradient {
|
|||||||
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
|
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
|
||||||
use graphene_std::vector::fill;
|
use graphene_std::vector::fill;
|
||||||
|
|
||||||
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? else {
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
|
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
|
||||||
@@ -665,7 +664,7 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
|||||||
}
|
}
|
||||||
/// Returns the stroke color from a layer's upstream Stroke node.
|
/// Returns the stroke color from a layer's upstream Stroke node.
|
||||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||||
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
let color_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
||||||
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
||||||
}
|
}
|
||||||
@@ -699,7 +698,7 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
|
|||||||
let fill_choice = (|| {
|
let fill_choice = (|| {
|
||||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||||
|
|
||||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? {
|
||||||
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
|
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
|
||||||
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
|
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
|
||||||
_ => None,
|
_ => None,
|
||||||
@@ -825,7 +824,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
|
|||||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||||
for layer in layers {
|
for layer in layers {
|
||||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||||
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
let input_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||||
let value = TaggedValue::Color(color);
|
let value = TaggedValue::Color(color);
|
||||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||||
} else {
|
} else {
|
||||||
@@ -977,6 +976,8 @@ impl<'a> NodeGraphLayer<'a> {
|
|||||||
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
||||||
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
|
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
|
||||||
|
|
||||||
layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<GPU>>))
|
// A leveled wire is typed by its element; depth rides the layout.
|
||||||
|
let compiled = layer_input_type.compiled_nested_type();
|
||||||
|
compiled == Some(&concrete!(Raster<CPU>)) || compiled == Some(&concrete!(Raster<GPU>))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,6 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
|||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graphene_std::NodeInputDecleration;
|
use graphene_std::NodeInputDecleration;
|
||||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||||
use graphene_std::list::List;
|
|
||||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
|
||||||
/// All non-color stroke-related options surfaced in the control bar popover.
|
/// All non-color stroke-related options surfaced in the control bar popover.
|
||||||
@@ -215,7 +214,7 @@ pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, docu
|
|||||||
|
|
||||||
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||||
drawing.dash_lengths = Some(lengths.clone());
|
drawing.dash_lengths = Some(lengths.clone());
|
||||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX, TaggedValue::F64Array(lengths), responses);
|
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::INDEX, TaggedValue::F64Array(lengths), responses);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||||
|
|||||||
@@ -574,12 +574,22 @@ mod test_artboard {
|
|||||||
use graphene_std::Artboard;
|
use graphene_std::Artboard;
|
||||||
use graphene_std::list::List;
|
use graphene_std::list::List;
|
||||||
|
|
||||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
||||||
|
/// occurrence yields one list rather than one element.
|
||||||
|
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard<'_>> {
|
||||||
let instrumented = match editor.eval_graph().await {
|
let instrumented = match editor.eval_graph().await {
|
||||||
Ok(instrumented) => instrumented,
|
Ok(instrumented) => instrumented,
|
||||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||||
};
|
};
|
||||||
instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput<Artboard>>(&editor.runtime).flatten().collect()
|
let mut artboards = List::new();
|
||||||
|
for list in instrumented.grab_all_input_level::<graphene_std::graphic::extend::NewInput<Artboard>, Artboard>(&editor.runtime) {
|
||||||
|
for index in 0..list.len() {
|
||||||
|
if let Some(item) = list.clone_item(index) {
|
||||||
|
artboards.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
artboards
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
|
|||||||
@@ -206,16 +206,19 @@ impl Fsm for FillToolFsmState {
|
|||||||
mod test_fill {
|
mod test_fill {
|
||||||
pub use crate::test_utils::test_prelude::*;
|
pub use crate::test_utils::test_prelude::*;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::list::List;
|
|
||||||
use graphene_std::vector::fill;
|
use graphene_std::vector::fill;
|
||||||
|
|
||||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<Color>> {
|
/// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
|
||||||
|
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
||||||
let instrumented = match editor.eval_graph().await {
|
let instrumented = match editor.eval_graph().await {
|
||||||
Ok(instrumented) => instrumented,
|
Ok(instrumented) => instrumented,
|
||||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||||
};
|
};
|
||||||
|
|
||||||
instrumented.grab_all_input::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
|
instrumented
|
||||||
|
.grab_all_input_level::<fill::FillInput, Color>(&editor.runtime)
|
||||||
|
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -245,8 +248,7 @@ mod test_fill {
|
|||||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
|
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
|
||||||
let fills = get_fills(&mut editor).await;
|
let fills = get_fills(&mut editor).await;
|
||||||
assert_eq!(fills.len(), 1);
|
assert_eq!(fills.len(), 1);
|
||||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::GREEN));
|
||||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -258,7 +260,6 @@ mod test_fill {
|
|||||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
|
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
|
||||||
let fills = get_fills(&mut editor).await;
|
let fills = get_fills(&mut editor).await;
|
||||||
assert_eq!(fills.len(), 1);
|
assert_eq!(fills.len(), 1);
|
||||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::YELLOW));
|
||||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2012,11 +2012,10 @@ mod test_gradient {
|
|||||||
pub use crate::test_utils::test_prelude::*;
|
pub use crate::test_utils::test_prelude::*;
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
use graphene_std::NodeInputDecleration;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::list::List;
|
|
||||||
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
|
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
|
||||||
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
||||||
use graphene_std::{Graphic, NodeInputDecleration};
|
|
||||||
|
|
||||||
use super::gradient_space_transform;
|
use super::gradient_space_transform;
|
||||||
|
|
||||||
@@ -2058,7 +2057,7 @@ mod test_gradient {
|
|||||||
let fill_node_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface)?;
|
let fill_node_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface)?;
|
||||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||||
|
|
||||||
let stops = match fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
let stops = match fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? {
|
||||||
TaggedValue::Gradient(stops) => stops.clone(),
|
TaggedValue::Gradient(stops) => stops.clone(),
|
||||||
_ => return None,
|
_ => return None,
|
||||||
};
|
};
|
||||||
@@ -2176,7 +2175,7 @@ mod test_gradient {
|
|||||||
editor
|
editor
|
||||||
.handle_message(NodeGraphMessage::CreateWire {
|
.handle_message(NodeGraphMessage::CreateWire {
|
||||||
output_connector: OutputConnector::node(gradient_node_id, 0),
|
output_connector: OutputConnector::node(gradient_node_id, 0),
|
||||||
input_connector: InputConnector::node(fill_node_id, fill::FillInput::<List<Graphic>>::INDEX),
|
input_connector: InputConnector::node(fill_node_id, fill::FillInput::INDEX),
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage};
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
@@ -10,12 +10,11 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
|
|||||||
use graphene_std::bounds::RenderBoundingBox;
|
use graphene_std::bounds::RenderBoundingBox;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::list::List;
|
use graphene_std::list::List;
|
||||||
use graphene_std::memo::IORecord;
|
|
||||||
use graphene_std::raster::{CPU, Raster};
|
use graphene_std::raster::{CPU, Raster};
|
||||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::vector::{Vector, graphic_types};
|
use graphene_std::vector::{Vector, graphic_types};
|
||||||
use graphene_std::{ATTR_TRANSFORM, Context, Graphic, NodeInputDecleration};
|
use graphene_std::{ATTR_TRANSFORM, Graphic, NodeInputDecleration};
|
||||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -26,7 +25,7 @@ pub use runtime_io::NodeRuntimeIO;
|
|||||||
mod runtime;
|
mod runtime;
|
||||||
pub use runtime::*;
|
pub use runtime::*;
|
||||||
|
|
||||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct ExecutionRequest {
|
pub struct ExecutionRequest {
|
||||||
execution_id: u64,
|
execution_id: u64,
|
||||||
render_config: RenderConfig,
|
render_config: RenderConfig,
|
||||||
@@ -59,6 +58,9 @@ pub struct NodeGraphExecutor {
|
|||||||
runtime_io: NodeRuntimeIO,
|
runtime_io: NodeRuntimeIO,
|
||||||
current_execution_id: u64,
|
current_execution_id: u64,
|
||||||
futures: VecDeque<(u64, ExecutionContext)>,
|
futures: VecDeque<(u64, ExecutionContext)>,
|
||||||
|
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
|
||||||
|
/// (sent after an async source completion) finds its context again.
|
||||||
|
last_execution_context: Option<(u64, ExecutionContext)>,
|
||||||
node_graph_hash: u64,
|
node_graph_hash: u64,
|
||||||
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
||||||
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
|
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
|
||||||
@@ -108,6 +110,7 @@ impl NodeGraphExecutor {
|
|||||||
let node_executor = Self {
|
let node_executor = Self {
|
||||||
futures: Default::default(),
|
futures: Default::default(),
|
||||||
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
|
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
|
||||||
|
last_execution_context: None,
|
||||||
node_graph_hash: 0,
|
node_graph_hash: 0,
|
||||||
current_execution_id: 0,
|
current_execution_id: 0,
|
||||||
previous_node_to_inspect: Vec::new(),
|
previous_node_to_inspect: Vec::new(),
|
||||||
@@ -375,10 +378,22 @@ impl NodeGraphExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else {
|
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
||||||
panic!("InvalidGenerationId")
|
let (_, execution_context) = self.futures.pop_front().expect("front was just matched");
|
||||||
|
self.last_execution_context = Some((execution_id, execution_context.clone()));
|
||||||
|
execution_context
|
||||||
|
} else {
|
||||||
|
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
|
||||||
|
match &self.last_execution_context {
|
||||||
|
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
|
||||||
|
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
execution_context.clone()
|
||||||
|
}
|
||||||
|
_ => panic!("InvalidGenerationId"),
|
||||||
|
}
|
||||||
};
|
};
|
||||||
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
|
|
||||||
|
|
||||||
// TODO: Eventually remove this document upgrade code
|
// TODO: Eventually remove this document upgrade code
|
||||||
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
|
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
|
||||||
@@ -660,19 +675,15 @@ impl NodeGraphExecutor {
|
|||||||
|
|
||||||
match render_output.data {
|
match render_output.data {
|
||||||
RenderOutputType::Svg { svg, image_data } => {
|
RenderOutputType::Svg { svg, image_data } => {
|
||||||
// Convert each linear-light `Image<Color>` into the JS-boundary `Image<SRGBA8>` form (gamma byte channels) before dispatching.
|
// Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
|
||||||
|
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
|
||||||
let image_data = image_data
|
let image_data = image_data
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(id, image)| {
|
.map(|(id, image)| RasterizedImage {
|
||||||
(
|
|
||||||
id,
|
id,
|
||||||
graphene_std::raster::Image {
|
|
||||||
width: image.width,
|
width: image.width,
|
||||||
height: image.height,
|
height: image.height,
|
||||||
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(),
|
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
|
||||||
base64_string: image.base64_string,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
responses.add(FrontendMessage::UpdateImageData { image_data });
|
responses.add(FrontendMessage::UpdateImageData { image_data });
|
||||||
@@ -888,18 +899,9 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Eventually remove this document upgrade code
|
// TODO: Eventually remove this document upgrade code
|
||||||
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
|
/// Extract a monitor node's captured output element.
|
||||||
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
|
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
|
||||||
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() {
|
data.downcast_ref::<T>().cloned()
|
||||||
return Some(io.output.clone());
|
|
||||||
}
|
|
||||||
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
|
|
||||||
return Some(io.output.clone());
|
|
||||||
}
|
|
||||||
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
|
|
||||||
return Some(io.output.clone());
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Re-export for usage by tests in other modules
|
// Re-export for usage by tests in other modules
|
||||||
@@ -915,9 +917,7 @@ mod test {
|
|||||||
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
|
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
|
||||||
use graph_craft::ProtoNodeIdentifier;
|
use graph_craft::ProtoNodeIdentifier;
|
||||||
use graph_craft::document::NodeNetwork;
|
use graph_craft::document::NodeNetwork;
|
||||||
use graphene_std::Context;
|
|
||||||
use graphene_std::NodeInputDecleration;
|
use graphene_std::NodeInputDecleration;
|
||||||
use graphene_std::memo::IORecord;
|
|
||||||
use test_prelude::LayerNodeIdentifier;
|
use test_prelude::LayerNodeIdentifier;
|
||||||
|
|
||||||
/// Stores all of the monitor nodes that have been attached to a graph
|
/// Stores all of the monitor nodes that have been attached to a graph
|
||||||
@@ -978,31 +978,25 @@ mod test {
|
|||||||
where
|
where
|
||||||
Input::Result: Send + Sync + Clone + 'static,
|
Input::Result: Send + Sync + Clone + 'static,
|
||||||
{
|
{
|
||||||
// This is quite inflexible since it only allows the footprint as inputs.
|
let element = dynamic.downcast_ref::<Input::Result>().cloned();
|
||||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() {
|
if element.is_none() {
|
||||||
Some(x.output.clone())
|
|
||||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Input::Result>>() {
|
|
||||||
Some(x.output.clone())
|
|
||||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Input::Result>>() {
|
|
||||||
Some(x.output.clone())
|
|
||||||
} else {
|
|
||||||
warn!("cannot downcast type for introspection");
|
warn!("cannot downcast type for introspection");
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
element
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Grab all of the values of the input every time it occurs in the graph.
|
/// Grab all of the values of a LEVELED input, which introspects as its
|
||||||
pub fn grab_all_input<'a, Input: NodeInputDecleration + 'a>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Input::Result> + 'a
|
/// whole legacy list rather than as one element. `T` is the introspected
|
||||||
where
|
/// element type, which differs from the declared one where a conversion
|
||||||
Input::Result: Send + Sync + Clone + 'static,
|
/// sits downstream of the monitor.
|
||||||
{
|
pub fn grab_all_input_level<'a, Input: NodeInputDecleration + 'a, T: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = List<T>> + 'a {
|
||||||
self.protonodes_by_name
|
self.protonodes_by_name
|
||||||
.get(&Input::identifier())
|
.get(&Input::identifier())
|
||||||
.map_or([].as_slice(), |x| x.as_slice())
|
.map_or([].as_slice(), |x| x.as_slice())
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|inputs| inputs.get(Input::INDEX))
|
.filter_map(|inputs| inputs.get(Input::INDEX))
|
||||||
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
|
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
|
||||||
.filter_map(Instrumented::downcast::<Input>) // Some might not resolve (e.g. generics that don't work properly)
|
.filter_map(|dynamic| dynamic.downcast_ref::<List<T>>().cloned())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
|
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||||
|
|||||||
@@ -3,25 +3,24 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
|||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
use graph_craft::application_io::resource::ResourceRegistry;
|
use graph_craft::application_io::resource::ResourceRegistry;
|
||||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||||
use graph_craft::concrete;
|
|
||||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||||
use graph_craft::document::{NodeId, NodeNetwork};
|
use graph_craft::document::{NodeId, NodeNetwork};
|
||||||
use graph_craft::graphene_compiler::Compiler;
|
use graph_craft::graphene_compiler::Compiler;
|
||||||
use graph_craft::proto::GraphErrors;
|
use graph_craft::proto::GraphErrors;
|
||||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
||||||
use graphene_std::bounds::RenderBoundingBox;
|
use graphene_std::bounds::RenderBoundingBox;
|
||||||
use graphene_std::list::List;
|
use graphene_std::core_types::gpoll::GPoll;
|
||||||
use graphene_std::memo::IORecord;
|
use graphene_std::ops::ConvertAsync;
|
||||||
use graphene_std::ops::Convert;
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||||
use graphene_std::raster_types::Raster;
|
use graphene_std::raster_types::Raster;
|
||||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
|
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
|
||||||
|
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||||
use graphene_std::transform::RenderQuality;
|
use graphene_std::transform::RenderQuality;
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::vector::style::RenderMode;
|
use graphene_std::vector::style::RenderMode;
|
||||||
use graphene_std::{Artboard, Context, Graphic};
|
use graphene_std::{Artboard, Graphic};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||||
use interpreted_executor::util::wrap_network_in_scope;
|
use interpreted_executor::util::wrap_network_in_scope;
|
||||||
use spin::Mutex;
|
use spin::Mutex;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -40,6 +39,9 @@ pub struct NodeRuntime {
|
|||||||
editor_preferences: EditorPreferences,
|
editor_preferences: EditorPreferences,
|
||||||
old_graph: Option<NodeNetwork>,
|
old_graph: Option<NodeNetwork>,
|
||||||
update_thumbnails: bool,
|
update_thumbnails: bool,
|
||||||
|
graph_runtime: Arc<DynGraphRuntime>,
|
||||||
|
/// The last plain render request, replayed when an async source completion marks the graph dirty.
|
||||||
|
last_render: Option<ExecutionRequest>,
|
||||||
|
|
||||||
editor_api: Arc<PlatformEditorApi>,
|
editor_api: Arc<PlatformEditorApi>,
|
||||||
resources: ResourceRegistry,
|
resources: ResourceRegistry,
|
||||||
@@ -119,20 +121,88 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
|
|||||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||||
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
|
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
|
||||||
|
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||||
|
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
impl TokioSpawner {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
impl Default for TokioSpawner {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
impl Spawner for TokioSpawner {
|
||||||
|
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||||
|
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||||
|
let _guard = runtime.enter();
|
||||||
|
if poll_once(&mut task) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
runtime.spawn(task);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
|
||||||
|
/// [`NodeRuntime`] from one, so shut down in the background instead.
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
impl Drop for TokioSpawner {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(runtime) = self.0.take() {
|
||||||
|
runtime.shutdown_background();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
pub struct WasmSpawner;
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
impl Spawner for WasmSpawner {
|
||||||
|
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||||
|
if poll_once(&mut task) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
wasm_bindgen_futures::spawn_local(task);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl NodeRuntime {
|
impl NodeRuntime {
|
||||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
// The box is a trait object, so `Box::default()` cannot name the concrete spawner.
|
||||||
|
#[allow(clippy::box_default)]
|
||||||
|
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
||||||
|
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
executor.set_runtime(Arc::clone(&graph_runtime));
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
executor: DynamicExecutor::default(),
|
executor,
|
||||||
receiver,
|
receiver,
|
||||||
sender: InternalNodeGraphUpdateSender(sender.clone()),
|
sender: InternalNodeGraphUpdateSender(sender.clone()),
|
||||||
editor_preferences: EditorPreferences::default(),
|
editor_preferences: EditorPreferences::default(),
|
||||||
old_graph: None,
|
old_graph: None,
|
||||||
resources: ResourceRegistry::default(),
|
resources: ResourceRegistry::default(),
|
||||||
update_thumbnails: true,
|
update_thumbnails: true,
|
||||||
|
graph_runtime: Arc::clone(&graph_runtime),
|
||||||
|
last_render: None,
|
||||||
|
|
||||||
editor_api: PlatformEditorApi {
|
editor_api: PlatformEditorApi {
|
||||||
editor_preferences: Box::new(EditorPreferences::default()),
|
editor_preferences: Box::new(EditorPreferences::default()),
|
||||||
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
|
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
|
||||||
|
runtime: RuntimeHandle(graph_runtime),
|
||||||
|
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
application_io: None,
|
application_io: None,
|
||||||
@@ -157,6 +227,11 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn take_dirty(&self) -> bool {
|
||||||
|
self.executor.take_dirty()
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn run(&mut self) -> Option<Texture> {
|
pub async fn run(&mut self) -> Option<Texture> {
|
||||||
let mut preferences = None;
|
let mut preferences = None;
|
||||||
let mut graph = None;
|
let mut graph = None;
|
||||||
@@ -173,6 +248,9 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let for_export = execution_request.render_config.for_export;
|
let for_export = execution_request.render_config.for_export;
|
||||||
|
if !for_export {
|
||||||
|
self.last_render = Some(execution_request.clone());
|
||||||
|
}
|
||||||
|
|
||||||
execution = Some(request);
|
execution = Some(request);
|
||||||
|
|
||||||
@@ -193,6 +271,10 @@ impl NodeRuntime {
|
|||||||
eyedropper.render_config.pointer = execution.render_config.pointer;
|
eyedropper.render_config.pointer = execution.render_config.pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.executor.take_dirty() && execution.is_none() {
|
||||||
|
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
|
||||||
|
}
|
||||||
|
|
||||||
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
|
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
|
||||||
|
|
||||||
for request in requests {
|
for request in requests {
|
||||||
@@ -203,11 +285,12 @@ impl NodeRuntime {
|
|||||||
application_io: self.editor_api.application_io.clone(),
|
application_io: self.editor_api.application_io.clone(),
|
||||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||||
editor_preferences: Box::new(preferences),
|
editor_preferences: Box::new(preferences),
|
||||||
|
runtime: self.editor_api.runtime.clone(),
|
||||||
}
|
}
|
||||||
.into();
|
.into();
|
||||||
if let Some(graph) = self.old_graph.clone() {
|
if let Some(graph) = self.old_graph.clone() {
|
||||||
// We ignore this result as compilation errors should have been reported in an earlier iteration
|
// We ignore this result as compilation errors should have been reported in an earlier iteration
|
||||||
let _ = self.update_network(graph).await;
|
let _ = self.update_network(graph);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||||
@@ -222,7 +305,7 @@ impl NodeRuntime {
|
|||||||
self.resources = resources;
|
self.resources = resources;
|
||||||
|
|
||||||
self.node_graph_errors.clear();
|
self.node_graph_errors.clear();
|
||||||
let result = self.update_network(network).await;
|
let result = self.update_network(network);
|
||||||
let node_graph_errors = self.node_graph_errors.clone();
|
let node_graph_errors = self.node_graph_errors.clone();
|
||||||
|
|
||||||
self.update_thumbnails = true;
|
self.update_thumbnails = true;
|
||||||
@@ -237,7 +320,7 @@ impl NodeRuntime {
|
|||||||
render_config.export_format = ExportFormat::Svg;
|
render_config.export_format = ExportFormat::Svg;
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = self.execute_network(render_config).await;
|
let result = self.execute_network(render_config);
|
||||||
let mut responses = VecDeque::new();
|
let mut responses = VecDeque::new();
|
||||||
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
|
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
|
||||||
if !render_config.for_eyedropper {
|
if !render_config.for_eyedropper {
|
||||||
@@ -258,10 +341,10 @@ impl NodeRuntime {
|
|||||||
.application_io
|
.application_io
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.gpu_executor()
|
.gpu_executor_arc()
|
||||||
.expect("GPU executor should be available when we receive a texture");
|
.expect("GPU executor should be available when we receive a texture");
|
||||||
|
|
||||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
|
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
|
||||||
|
|
||||||
let (data, width, height) = raster_cpu.to_flat_u8();
|
let (data, width, height) = raster_cpu.to_flat_u8();
|
||||||
|
|
||||||
@@ -282,10 +365,10 @@ impl NodeRuntime {
|
|||||||
.application_io
|
.application_io
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.gpu_executor()
|
.gpu_executor_arc()
|
||||||
.expect("GPU executor should be available when we receive a texture");
|
.expect("GPU executor should be available when we receive a texture");
|
||||||
|
|
||||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
|
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
|
||||||
|
|
||||||
self.sender.send_eyedropper_preview(raster_cpu);
|
self.sender.send_eyedropper_preview(raster_cpu);
|
||||||
continue;
|
continue;
|
||||||
@@ -345,7 +428,7 @@ impl NodeRuntime {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
|
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
|
||||||
|
|
||||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||||
@@ -356,7 +439,7 @@ impl NodeRuntime {
|
|||||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||||
|
|
||||||
let c = Compiler {};
|
let c = Compiler {};
|
||||||
let proto_network = match c.compile_single(scoped_network) {
|
let proto_network = match c.compile_single(scoped_network, &interpreted_executor::node_registry::NODE_REGISTRY) {
|
||||||
Ok(network) => network,
|
Ok(network) => network,
|
||||||
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
|
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
|
||||||
};
|
};
|
||||||
@@ -368,20 +451,24 @@ impl NodeRuntime {
|
|||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||||
self.executor.update(proto_network).await.map_err(|(types, e)| {
|
self.executor.update(proto_network).map_err(|(types, e)| {
|
||||||
self.node_graph_errors.clone_from(&e);
|
self.node_graph_errors.clone_from(&e);
|
||||||
(types, format!("{e:?}"))
|
(types, format!("{e:?}"))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
|
fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
|
||||||
use graph_craft::graphene_compiler::Executor;
|
use graph_craft::graphene_compiler::Executor;
|
||||||
|
|
||||||
match self.executor.input_type() {
|
match (&self.executor).execute(render_config).map_err(|e| e.to_string())? {
|
||||||
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()),
|
GPoll::Final(value) | GPoll::Partial(value) => Ok(value),
|
||||||
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
|
GPoll::Fallback(boxed) => {
|
||||||
Some(t) => Err(format!("Invalid input type {t:?}")),
|
let (value, error) = *boxed;
|
||||||
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
|
error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
GPoll::Pending => Err("Node graph evaluation is pending".to_string()),
|
||||||
|
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,44 +493,63 @@ impl NodeRuntime {
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Extract the monitor node's stored `Graphic` data
|
// Read the monitored run directly, inside the introspection window
|
||||||
let Ok(introspected_data) = self.executor.introspect(monitor_node_path) else {
|
let thumbnail_renders = &mut self.thumbnail_renders;
|
||||||
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
let vector_modify = &mut self.vector_modify;
|
||||||
#[cfg(debug_assertions)]
|
let result = self.executor.introspect_with(monitor_node_path, |layout, batch, _arena| {
|
||||||
warn!("Failed to introspect monitor node {}", self.executor.introspect(monitor_node_path).unwrap_err());
|
use graphene_std::core_types::record::{Group, GroupItem, RunView};
|
||||||
continue;
|
let type_id = layout.element.type_id;
|
||||||
};
|
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||||
|
if type_id == std::any::TypeId::of::<Graphic>() {
|
||||||
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
|
||||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() {
|
|
||||||
if update_thumbnails {
|
if update_thumbnails {
|
||||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
// SAFETY: the batch is resident for the read.
|
||||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
let item = unsafe { GroupItem::from_resident(batch) };
|
||||||
|
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
|
||||||
|
let group = Graphic::Group(Group { row: None, content: item });
|
||||||
|
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &group, bounds, responses)
|
||||||
}
|
}
|
||||||
|
Some(())
|
||||||
}
|
}
|
||||||
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
|
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
|
||||||
// clips content to those rectangles so anything outside isn't visible
|
// clips content to those rectangles so anything outside isn't visible
|
||||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Artboard>>>() {
|
else if type_id == std::any::TypeId::of::<Artboard>() {
|
||||||
if update_thumbnails {
|
if update_thumbnails {
|
||||||
let bounds = artboard_clip_bounds(&io.output);
|
// SAFETY: the batch is resident for the read.
|
||||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
let item = unsafe { GroupItem::from_resident(batch) };
|
||||||
|
let run = RunView::<Artboard>::new(&item)?;
|
||||||
|
let bounds = artboard_clip_bounds(&run);
|
||||||
|
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
|
||||||
}
|
}
|
||||||
|
Some(())
|
||||||
}
|
}
|
||||||
// Vector list: vector modifications
|
// Vector run: vector modifications
|
||||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Vector>>>() {
|
else if type_id == std::any::TypeId::of::<Vector>() {
|
||||||
// Insert the vector modify
|
// SAFETY: the batch is resident for the read.
|
||||||
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
|
let item = unsafe { GroupItem::from_resident(batch) };
|
||||||
|
let run = RunView::<Vector>::new(&item)?;
|
||||||
|
use graphene_std::core_types::lane::LaneSource;
|
||||||
|
vector_modify.insert(parent_network_node_id, run.element(0).cloned().unwrap_or_default());
|
||||||
|
Some(())
|
||||||
}
|
}
|
||||||
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
||||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() {
|
else if type_id == std::any::TypeId::of::<String>() {
|
||||||
if update_thumbnails {
|
if update_thumbnails {
|
||||||
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
// SAFETY: the batch is resident for the read.
|
||||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
let item = unsafe { GroupItem::from_resident(batch) };
|
||||||
|
let run = RunView::<String>::new(&item)?;
|
||||||
|
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
|
||||||
|
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
|
||||||
}
|
}
|
||||||
|
Some(())
|
||||||
|
} else {
|
||||||
|
log::warn!("Failed to read monitor node output {parent_network_node_id:?}");
|
||||||
|
Some(())
|
||||||
}
|
}
|
||||||
// Other
|
});
|
||||||
else {
|
if let Err(_error) = result {
|
||||||
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
|
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
warn!("Failed to introspect monitor node {}", _error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -511,11 +617,12 @@ impl NodeRuntime {
|
|||||||
|
|
||||||
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
|
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
|
||||||
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
|
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
|
||||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
fn artboard_clip_bounds<'a, S: graphene_std::core_types::lane::LaneSource<Element = Artboard<'a>>>(artboards: &S) -> RenderBoundingBox {
|
||||||
|
use graphene_std::core_types::attribute::{Dimensions, Location};
|
||||||
let mut combined: Option<[DVec2; 2]> = None;
|
let mut combined: Option<[DVec2; 2]> = None;
|
||||||
for index in 0..artboards.len() {
|
for index in 0..artboards.lane_count() {
|
||||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
let location: DVec2 = artboards.attr::<Location>(index);
|
||||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
let dimensions: DVec2 = artboards.attr::<Dimensions>(index);
|
||||||
let bounds = [location, location + dimensions];
|
let bounds = [location, location + dimensions];
|
||||||
combined = Some(match combined {
|
combined = Some(match combined {
|
||||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||||
@@ -544,14 +651,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
|||||||
[center - half, center + half]
|
[center - half, center + half]
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
|
||||||
let runtime = NODE_RUNTIME.lock();
|
|
||||||
if let Some(ref mut runtime) = runtime.as_ref() {
|
|
||||||
return runtime.executor.introspect(path);
|
|
||||||
}
|
|
||||||
Err(IntrospectError::RuntimeNotReady)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run_node_graph() -> (bool, Option<Texture>) {
|
pub async fn run_node_graph() -> (bool, Option<Texture>) {
|
||||||
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
|
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
|
||||||
if let Some(ref mut runtime) = runtime.as_mut() {
|
if let Some(ref mut runtime) = runtime.as_mut() {
|
||||||
@@ -571,12 +670,20 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
|
||||||
|
let node_runtime = NODE_RUNTIME.lock();
|
||||||
|
if let Some(node_runtime) = &*node_runtime {
|
||||||
|
node_runtime.graph_runtime.set_notifier(notifier);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl NodeRuntime {
|
impl NodeRuntime {
|
||||||
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
|
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
|
||||||
self.editor_api = PlatformEditorApi {
|
self.editor_api = PlatformEditorApi {
|
||||||
application_io: Some(application_io.into()),
|
application_io: Some(application_io.into()),
|
||||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||||
editor_preferences: Box::new(self.editor_preferences.clone()),
|
editor_preferences: Box::new(self.editor_preferences.clone()),
|
||||||
|
runtime: self.editor_api.runtime.clone(),
|
||||||
}
|
}
|
||||||
.into();
|
.into();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,27 @@ impl EditorTestUtils {
|
|||||||
}
|
}
|
||||||
runtime.run().await;
|
runtime.run().await;
|
||||||
|
|
||||||
|
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
|
||||||
|
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
|
||||||
|
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
|
||||||
|
// dispatched, or the editor's type map desyncs permanently.
|
||||||
|
while runtime.take_dirty() {
|
||||||
|
let mut superseded_messages = VecDeque::new();
|
||||||
|
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
|
||||||
|
for message in superseded_messages {
|
||||||
|
editor.handle_message(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||||
|
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||||
|
let document = documents.get_mut(&document_id).unwrap();
|
||||||
|
|
||||||
|
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||||
|
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
|
||||||
|
}
|
||||||
|
runtime.run().await;
|
||||||
|
}
|
||||||
|
|
||||||
let mut messages = VecDeque::new();
|
let mut messages = VecDeque::new();
|
||||||
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
|
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
|
||||||
return Err(format!("Graph should render\n\n{e}"));
|
return Err(format!("Graph should render\n\n{e}"));
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
wrapper/pkg/
|
wrapper/pkg/
|
||||||
|
wrapper/pkg-native/
|
||||||
public/build/
|
public/build/
|
||||||
dist/
|
dist/
|
||||||
@@ -29,6 +29,7 @@ export default defineConfig([
|
|||||||
"**/node_modules/",
|
"**/node_modules/",
|
||||||
"**/dist/",
|
"**/dist/",
|
||||||
"**/pkg/",
|
"**/pkg/",
|
||||||
|
"**/pkg-native/",
|
||||||
"wasm/pkg/",
|
"wasm/pkg/",
|
||||||
// Don't ignore JS and TS dotfiles in this folder
|
// Don't ignore JS and TS dotfiles in this folder
|
||||||
"!**/.*.js",
|
"!**/.*.js",
|
||||||
|
|||||||
@@ -23,7 +23,10 @@ export default defineConfig(({ mode }) => {
|
|||||||
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
|
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
|
||||||
define: { __WASM_PART_COUNT__: "1" },
|
define: { __WASM_PART_COUNT__: "1" },
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: [{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") }],
|
alias: [
|
||||||
|
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
|
||||||
|
{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
port: 8080,
|
port: 8080,
|
||||||
|
|||||||
+15
-11
@@ -11,33 +11,37 @@ repository = "https://github.com/GraphiteEditor/Graphite"
|
|||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["gpu", "shader-nodes"]
|
default = ["gpu", "shader-nodes", "web"]
|
||||||
gpu = ["editor/gpu"]
|
web = ["editor", "editor?/wasm"]
|
||||||
shader-nodes = ["graphene-std/shader-nodes", "gpu"]
|
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:wgpu"]
|
||||||
native = ["node-macro/disable-registration"]
|
gpu = ["editor?/gpu"]
|
||||||
|
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
|
||||||
|
native = []
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
crate-type = ["cdylib", "rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
editor = { path = "../../editor", package = "graphite-editor", features = ["gpu", "wasm"] }
|
editor = { path = "../../editor", package = "graphite-editor", optional = true }
|
||||||
graphene-std = { workspace = true }
|
graphite-proc-macros = { workspace = true }
|
||||||
|
graphene-std = { workspace = true, optional = true }
|
||||||
|
|
||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
bytemuck = { workspace = true }
|
graph-craft = { workspace = true, optional = true }
|
||||||
graph-craft = { workspace = true }
|
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
wasm-bindgen = { workspace = true }
|
wasm-bindgen = { workspace = true }
|
||||||
serde-wasm-bindgen = { workspace = true }
|
serde-wasm-bindgen = { workspace = true }
|
||||||
js-sys = { workspace = true }
|
js-sys = { workspace = true }
|
||||||
wasm-bindgen-futures = { workspace = true }
|
wasm-bindgen-futures = { workspace = true }
|
||||||
wgpu = { workspace = true }
|
wgpu = { workspace = true, optional = true }
|
||||||
web-sys = { workspace = true }
|
web-sys = { workspace = true }
|
||||||
ron = { workspace = true }
|
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
node-macro = { workspace = true }
|
tsify = { workspace = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
serde_bytes = { workspace = true }
|
||||||
|
|
||||||
[lints.rust]
|
[lints.rust]
|
||||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||||
|
|||||||
@@ -0,0 +1,690 @@
|
|||||||
|
//! Commands that JS can call on the editor. Each function maps its arguments to a `Message`. On web the generated
|
||||||
|
//! stub dispatches it directly, on native the arguments are sent as an `EditorCommand` and the same body runs in
|
||||||
|
//! the editor process.
|
||||||
|
|
||||||
|
#![allow(clippy::too_many_arguments)]
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
use crate::editor_wrapper::EditorWrapper;
|
||||||
|
use graphite_proc_macros::editor_commands;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tsify::Tsify;
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
|
#[editor_commands]
|
||||||
|
mod editor_commands {
|
||||||
|
use crate::helpers::translate_key;
|
||||||
|
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||||
|
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||||
|
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
||||||
|
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
|
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
|
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||||
|
use editor::messages::portfolio::utility_types::PanelGroupId;
|
||||||
|
use editor::messages::prelude::*;
|
||||||
|
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
|
||||||
|
use graph_craft::document::NodeId;
|
||||||
|
use graphene_std::raster::color::Color;
|
||||||
|
use graphene_std::vector::style::FillChoice;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
|
||||||
|
fn resend_all_layouts() -> Message {
|
||||||
|
LayoutMessage::ResendAllLayouts.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// First message of a session, sent once the frontend is ready
|
||||||
|
fn init_portfolio() -> Message {
|
||||||
|
PortfolioMessage::Init.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-frame tick: advances the animation clock and broadcasts the animation frame event
|
||||||
|
fn animation_frame(timestamp: u64) -> Message {
|
||||||
|
Message::Batched {
|
||||||
|
messages: Box::new([
|
||||||
|
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
|
||||||
|
AnimationMessage::IncrementFrameCounter.into(),
|
||||||
|
// Used by auto-panning, but this could possibly be refactored in the future, see:
|
||||||
|
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
|
||||||
|
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auto_save_all_documents() -> Message {
|
||||||
|
PortfolioMessage::AutoSaveAllDocuments.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_primary_import() -> Message {
|
||||||
|
Message::Batched {
|
||||||
|
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryImport.into()]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_secondary_import() -> Message {
|
||||||
|
Message::Batched {
|
||||||
|
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryImport.into()]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_primary_export() -> Message {
|
||||||
|
Message::Batched {
|
||||||
|
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryExport.into()]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_secondary_export() -> Message {
|
||||||
|
Message::Batched {
|
||||||
|
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryExport.into()]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start Pointer Lock
|
||||||
|
fn app_window_pointer_lock() -> Message {
|
||||||
|
AppWindowMessage::PointerLock.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Minimizes the application window to the taskbar or dock
|
||||||
|
fn app_window_minimize() -> Message {
|
||||||
|
AppWindowMessage::Minimize.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggles minimizing or restoring down the application window
|
||||||
|
fn app_window_maximize() -> Message {
|
||||||
|
AppWindowMessage::Maximize.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn app_window_fullscreen() -> Message {
|
||||||
|
AppWindowMessage::Fullscreen.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes the application window
|
||||||
|
fn app_window_close() -> Message {
|
||||||
|
AppWindowMessage::Close.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drag the application window
|
||||||
|
fn app_window_drag() -> Message {
|
||||||
|
AppWindowMessage::Drag.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Displays a dialog with an error message
|
||||||
|
fn error_dialog(title: String, description: String) -> Message {
|
||||||
|
DialogMessage::DisplayDialogError { title, description }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
||||||
|
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
|
||||||
|
let widget_id = WidgetId(widget_id);
|
||||||
|
let update = LayoutMessage::WidgetValueUpdate {
|
||||||
|
layout_target,
|
||||||
|
widget_id,
|
||||||
|
value: value.cast(),
|
||||||
|
};
|
||||||
|
if resend_widget {
|
||||||
|
Message::Batched {
|
||||||
|
messages: Box::new([update.into(), LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into()]),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
update.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commit the value of a given UI widget to the history
|
||||||
|
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
|
||||||
|
LayoutMessage::WidgetValueCommit {
|
||||||
|
layout_target,
|
||||||
|
widget_id: WidgetId(widget_id),
|
||||||
|
value: value.cast(),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the value of a given UI widget, and commit it to the history
|
||||||
|
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
|
||||||
|
let widget_id = WidgetId(widget_id);
|
||||||
|
let mut messages: Vec<Message> = vec![
|
||||||
|
LayoutMessage::WidgetValueCommit {
|
||||||
|
layout_target,
|
||||||
|
widget_id,
|
||||||
|
value: value.cast(),
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
LayoutMessage::WidgetValueUpdate {
|
||||||
|
layout_target,
|
||||||
|
widget_id,
|
||||||
|
value: value.cast(),
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
];
|
||||||
|
if resend_widget {
|
||||||
|
messages.push(LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into());
|
||||||
|
}
|
||||||
|
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
|
||||||
|
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
|
||||||
|
messages.push(DocumentMessage::EndTransaction.into());
|
||||||
|
Message::Batched { messages: messages.into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
|
||||||
|
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
|
||||||
|
let widget_id = WidgetId(widget_id);
|
||||||
|
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
|
||||||
|
fn end_transaction() -> Message {
|
||||||
|
DocumentMessage::EndTransaction.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_preferences(preferences: Option<String>) -> Message {
|
||||||
|
let Some(preferences) = preferences else { return Message::NoOp };
|
||||||
|
let Ok(preferences) = serde_json::from_str(&preferences) else {
|
||||||
|
log::error!("Failed to deserialize preferences");
|
||||||
|
return Message::NoOp;
|
||||||
|
};
|
||||||
|
PreferencesMessage::Load { preferences }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_document_content(document_id: u64, document: String) -> Message {
|
||||||
|
PersistentStateMessage::LoadDocument {
|
||||||
|
document_id: DocumentId(document_id),
|
||||||
|
document,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select_document(document_id: u64) -> Message {
|
||||||
|
PortfolioMessage::SelectDocument { document_id: DocumentId(document_id) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename the currently active document.
|
||||||
|
fn rename_document(new_name: String) -> Message {
|
||||||
|
PortfolioMessage::RenameDocument { new_name }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_document_dialog() -> Message {
|
||||||
|
DialogMessage::RequestNewDocumentDialog.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_file(path: String, content: Vec<u8>) -> Message {
|
||||||
|
PortfolioMessage::OpenFile { path: PathBuf::from(path), content }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn import_file(path: String, content: Vec<u8>) -> Message {
|
||||||
|
PortfolioMessage::ImportFile { path: PathBuf::from(path), content }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trigger_auto_save(document_id: u64) -> Message {
|
||||||
|
PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reorder_document(document_id: u64, new_index: usize) -> Message {
|
||||||
|
PortfolioMessage::ReorderDocument {
|
||||||
|
document_id: DocumentId(document_id),
|
||||||
|
new_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reorder_panel_group_tab(group: u64, old_index: usize, new_index: usize) -> Message {
|
||||||
|
PortfolioMessage::ReorderPanelGroupTab {
|
||||||
|
group: PanelGroupId(group),
|
||||||
|
old_index,
|
||||||
|
new_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_all_panel_tabs(source_group: u64, target_group: u64, insert_index: usize) -> Message {
|
||||||
|
PortfolioMessage::MoveAllPanelTabs {
|
||||||
|
source_group: PanelGroupId(source_group),
|
||||||
|
target_group: PanelGroupId(target_group),
|
||||||
|
insert_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_panel_tab(source_group: u64, target_group: u64, insert_index: usize) -> Message {
|
||||||
|
PortfolioMessage::MovePanelTab {
|
||||||
|
source_group: PanelGroupId(source_group),
|
||||||
|
target_group: PanelGroupId(target_group),
|
||||||
|
insert_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_panel_group_active_tab(group: u64, tab_index: usize) -> Message {
|
||||||
|
PortfolioMessage::SetPanelGroupActiveTab {
|
||||||
|
group: PanelGroupId(group),
|
||||||
|
tab_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
|
||||||
|
PortfolioMessage::SplitPanelGroup {
|
||||||
|
target_group: PanelGroupId(target_group),
|
||||||
|
direction,
|
||||||
|
tabs,
|
||||||
|
active_tab_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_panel_group_sizes(split_path: Vec<u32>, sizes: Vec<f64>) -> Message {
|
||||||
|
let split_path = split_path.into_iter().map(|i| i as usize).collect();
|
||||||
|
PortfolioMessage::SetPanelGroupSizes { split_path, sizes }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_document_with_confirmation(document_id: u64) -> Message {
|
||||||
|
PortfolioMessage::CloseDocumentWithConfirmation { document_id: DocumentId(document_id) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_about_graphite_dialog_with_localized_commit_date(localized_commit_date: String, localized_commit_year: String) -> Message {
|
||||||
|
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
|
||||||
|
localized_commit_date,
|
||||||
|
localized_commit_year,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_licenses_third_party_dialog_with_license_text(license_text: String) -> Message {
|
||||||
|
DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send new viewport info to the backend
|
||||||
|
fn update_viewport(x: f64, y: f64, width: f64, height: f64, scale: f64) -> Message {
|
||||||
|
ViewportMessage::Update { x, y, width, height, scale }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mouse movement within the screenspace bounds of the viewport
|
||||||
|
fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||||
|
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mouse scrolling within the screenspace bounds of the viewport
|
||||||
|
fn on_wheel_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) -> Message {
|
||||||
|
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||||
|
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A mouse button depressed within screenspace the bounds of the viewport
|
||||||
|
fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||||
|
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A mouse button released
|
||||||
|
fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||||
|
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mouse shaken
|
||||||
|
fn on_mouse_shake(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||||
|
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mouse double clicked
|
||||||
|
fn on_double_click(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||||
|
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A keyboard button depressed within screenspace the bounds of the viewport
|
||||||
|
fn on_key_down(name: String, modifiers: u8, key_repeat: bool) -> Message {
|
||||||
|
let key = translate_key(&name);
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
|
||||||
|
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A keyboard button released
|
||||||
|
fn on_key_up(name: String, modifiers: u8, key_repeat: bool) -> Message {
|
||||||
|
let key = translate_key(&name);
|
||||||
|
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||||
|
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
|
||||||
|
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A text box was committed
|
||||||
|
fn on_change_text(new_text: String, is_left_or_right_click: bool) -> Message {
|
||||||
|
TextToolMessage::TextChange { new_text, is_left_or_right_click }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dialog got dismissed
|
||||||
|
fn on_dialog_dismiss() -> Message {
|
||||||
|
DialogMessage::Dismiss.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A text box was changed
|
||||||
|
fn update_bounds(new_text: String) -> Message {
|
||||||
|
TextToolMessage::UpdateBounds { new_text }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
|
||||||
|
fn update_primary_color(color: SRGBA8) -> Message {
|
||||||
|
ToolMessage::SelectWorkingColor {
|
||||||
|
color: Color::from(color),
|
||||||
|
primary: true,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
|
||||||
|
fn update_secondary_color(color: SRGBA8) -> Message {
|
||||||
|
ToolMessage::SelectWorkingColor {
|
||||||
|
color: Color::from(color),
|
||||||
|
primary: false,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
|
||||||
|
fn open_color_picker(initial_value: FillChoiceUI, allow_none: bool, disabled: bool) -> Message {
|
||||||
|
ColorPickerMessage::Open {
|
||||||
|
initial_value: FillChoice::from(&initial_value),
|
||||||
|
allow_none,
|
||||||
|
disabled,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tell the Rust color picker handler that the popover is closing.
|
||||||
|
fn close_color_picker() -> Message {
|
||||||
|
ColorPickerMessage::Close.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
|
||||||
|
fn update_gradient_stop_color(color: SRGBA8) -> Message {
|
||||||
|
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a new undo transaction for gradient stop color editing
|
||||||
|
fn start_gradient_stop_color_transaction() -> Message {
|
||||||
|
GradientToolMessage::StartTransactionForColorStop.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
|
||||||
|
fn commit_gradient_stop_color_transaction() -> Message {
|
||||||
|
GradientToolMessage::CommitTransactionForColorStop.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close the gradient stop color picker and commit any pending transaction
|
||||||
|
fn close_gradient_stop_color_picker() -> Message {
|
||||||
|
GradientToolMessage::CloseStopColorPicker.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
|
||||||
|
fn clip_layer(id: u64) -> Message {
|
||||||
|
DocumentMessage::ClipLayer { id: NodeId(id) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
|
||||||
|
fn select_layer(id: u64, ctrl: bool, shift: bool) -> Message {
|
||||||
|
DocumentMessage::SelectLayer { id: NodeId(id), ctrl, shift }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deselect all layers
|
||||||
|
fn deselect_all_layers() -> Message {
|
||||||
|
DocumentMessage::DeselectAllLayers.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Move a layer to within a folder and placed down at the given index.
|
||||||
|
/// If the folder is `None`, it is inserted into the document root.
|
||||||
|
/// If the insert index is `None`, it is inserted at the start of the folder.
|
||||||
|
fn move_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
|
||||||
|
let insert_parent_id = insert_parent_id.map(NodeId);
|
||||||
|
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
|
||||||
|
|
||||||
|
DocumentMessage::MoveSelectedLayersTo {
|
||||||
|
parent,
|
||||||
|
insert_index: insert_index.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reorder a draggable Properties panel section to the given index among its peers.
|
||||||
|
fn reorder_properties_section(node_id: u64, insert_index: usize) -> Message {
|
||||||
|
DocumentMessage::ReorderPropertiesSection {
|
||||||
|
node_id: NodeId(node_id),
|
||||||
|
insert_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
|
||||||
|
/// If the folder is `None`, they are inserted into the document root.
|
||||||
|
/// If the insert index is `None`, they are inserted at the start of the folder.
|
||||||
|
fn duplicate_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
|
||||||
|
DocumentMessage::DuplicateSelectedLayersTo {
|
||||||
|
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
|
||||||
|
insert_index: insert_index.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the name for the layer
|
||||||
|
fn set_layer_name(id: u64, name: String) -> Message {
|
||||||
|
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
|
||||||
|
NodeGraphMessage::SetDisplayName {
|
||||||
|
node_id: layer.to_node(),
|
||||||
|
network_path: Vec::new(),
|
||||||
|
alias: name,
|
||||||
|
skip_adding_history_step: false,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Translates document (in viewport coords)
|
||||||
|
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
|
||||||
|
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pan_canvas_abort(x_not_y_axis: bool) -> Message {
|
||||||
|
NavigationMessage::CanvasPanAbort { x_not_y_axis }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Translates document (in viewport coords)
|
||||||
|
fn pan_canvas(delta_x: f64, delta_y: f64) -> Message {
|
||||||
|
NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Translates document (in viewport coords)
|
||||||
|
fn pan_canvas_by_fraction(delta_x: f64, delta_y: f64) -> Message {
|
||||||
|
NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merge the selected nodes into a subnetwork
|
||||||
|
fn merge_selected_nodes() -> Message {
|
||||||
|
NodeGraphMessage::MergeSelectedNodes.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle lock state of all selected layers
|
||||||
|
fn toggle_selected_locked() -> Message {
|
||||||
|
NodeGraphMessage::ToggleSelectedLocked.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new document node in the node graph
|
||||||
|
fn create_node(node_type: String, x: i32, y: i32) -> Message {
|
||||||
|
let id = NodeId::new();
|
||||||
|
NodeGraphMessage::CreateNodeFromContextMenu {
|
||||||
|
node_id: Some(id),
|
||||||
|
node_type: DefinitionIdentifier::from_serialized(&node_type),
|
||||||
|
xy: Some((x / 24, y / 24)),
|
||||||
|
add_transaction: true,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Respond to selection read
|
||||||
|
fn read_selection(content: Option<String>, cut: bool) -> Message {
|
||||||
|
ClipboardMessage::ReadSelection { content, cut }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paste from a serialized JSON representation
|
||||||
|
fn paste_text(data: String) -> Message {
|
||||||
|
ClipboardMessage::ReadClipboard {
|
||||||
|
content: ClipboardContentRaw::Text(data),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pastes an image
|
||||||
|
fn paste_image(
|
||||||
|
name: Option<String>,
|
||||||
|
image_data: Vec<u8>,
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
mouse_x: Option<f64>,
|
||||||
|
mouse_y: Option<f64>,
|
||||||
|
insert_parent_id: Option<u64>,
|
||||||
|
insert_index: Option<usize>,
|
||||||
|
) -> Message {
|
||||||
|
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
||||||
|
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
|
||||||
|
|
||||||
|
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
||||||
|
let insert_parent_id = NodeId(insert_parent_id);
|
||||||
|
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
||||||
|
Some((parent, insert_index))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
PortfolioMessage::InsertImage {
|
||||||
|
name,
|
||||||
|
image,
|
||||||
|
mouse,
|
||||||
|
parent_and_insert_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pastes an SVG given its string representation
|
||||||
|
fn paste_svg(name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
|
||||||
|
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
||||||
|
|
||||||
|
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
||||||
|
let insert_parent_id = NodeId(insert_parent_id);
|
||||||
|
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
||||||
|
Some((parent, insert_index))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
PortfolioMessage::InsertSvg {
|
||||||
|
name,
|
||||||
|
svg,
|
||||||
|
mouse,
|
||||||
|
parent_and_insert_index,
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle visibility of a layer or node given its node ID
|
||||||
|
fn toggle_node_visibility_layer_panel(id: u64) -> Message {
|
||||||
|
NodeGraphMessage::ToggleVisibility {
|
||||||
|
node_id: NodeId(id),
|
||||||
|
network_path: Vec::new(),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pin or unpin a node given its node ID
|
||||||
|
fn set_node_pinned(id: u64, pinned: bool) -> Message {
|
||||||
|
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collapse or expand a node's section in the Properties panel
|
||||||
|
fn toggle_node_properties_section_expanded(id: u64) -> Message {
|
||||||
|
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete a layer or node given its node ID
|
||||||
|
fn delete_node(id: u64) -> Message {
|
||||||
|
DocumentMessage::DeleteNode { node_id: NodeId(id) }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle lock state of a layer from the layer list
|
||||||
|
fn toggle_layer_lock(node_id: u64) -> Message {
|
||||||
|
NodeGraphMessage::ToggleLocked {
|
||||||
|
node_id: NodeId(node_id),
|
||||||
|
network_path: Vec::new(),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle expansions state of a layer from the layer list
|
||||||
|
fn toggle_layer_expansion(tree_path: Vec<u64>, recursive: bool) -> Message {
|
||||||
|
let tree_path = tree_path.into_iter().map(NodeId).collect();
|
||||||
|
DocumentMessage::ToggleLayerExpansion { tree_path, recursive }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the active panel to the most recently clicked panel
|
||||||
|
fn set_active_panel(panel: String) -> Message {
|
||||||
|
DocumentMessage::SetActivePanel { active_panel: panel.into() }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle display type for a layer
|
||||||
|
fn set_to_node_or_layer(id: u64, is_layer: bool) -> Message {
|
||||||
|
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the name of an import or export
|
||||||
|
fn set_import_name(index: usize, name: String) -> Message {
|
||||||
|
NodeGraphMessage::SetImportExportName {
|
||||||
|
name,
|
||||||
|
index: ImportOrExport::Import(index),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the name of an export
|
||||||
|
fn set_export_name(index: usize, name: String) -> Message {
|
||||||
|
NodeGraphMessage::SetImportExportName {
|
||||||
|
name,
|
||||||
|
index: ImportOrExport::Export(index),
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
|
||||||
|
#[tsify(from_wasm_abi)]
|
||||||
|
pub struct Any(#[tsify(type = "any")] serde_json::Value);
|
||||||
|
impl Any {
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
pub(crate) fn cast<T: for<'de> Deserialize<'de>>(&self) -> T {
|
||||||
|
serde_json::from_value(self.0.clone()).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! editor_proxy_types {
|
||||||
|
($($name:ident = $real:ty;)*) => {
|
||||||
|
$(
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
pub type $name = $real;
|
||||||
|
#[cfg(not(feature = "editor"))]
|
||||||
|
pub type $name = Any;
|
||||||
|
)*
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
editor_proxy_types! {
|
||||||
|
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||||
|
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
|
||||||
|
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
|
||||||
|
SRGBA8 = graphene_std::color::SRGBA8;
|
||||||
|
FillChoiceUI = graphene_std::vector::style::FillChoiceUI;
|
||||||
|
}
|
||||||
@@ -1,44 +1,33 @@
|
|||||||
#![allow(clippy::too_many_arguments)]
|
//! JS-facing editor handle. Owns the callback that delivers `FrontendMessage`s to JS; on web `dispatch` runs
|
||||||
//
|
//! messages through the in-process editor, on native `send` forwards them as `EditorCommand`s.
|
||||||
// This file is where functions are defined to be called directly from JS.
|
|
||||||
// It serves as a thin wrapper over the editor backend API that relies
|
|
||||||
// on the dispatcher messaging system and more complex Rust data types.
|
|
||||||
//
|
|
||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
use crate::EDITOR;
|
use crate::EDITOR;
|
||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
use crate::helpers::poll_node_graph_evaluation;
|
use crate::MESSAGE_BUFFER;
|
||||||
use crate::helpers::{auto_save_all_documents, calculate_hash, render_image_data_to_canvases, request_animation_frame, set_timeout, translate_key, wrapper};
|
#[cfg(all(feature = "native", target_family = "wasm"))]
|
||||||
use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER};
|
use crate::editor_commands::EditorCommand;
|
||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
|
use crate::helpers::poll_node_graph_evaluation;
|
||||||
|
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
|
||||||
|
use crate::helpers::wrapper;
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
use crate::helpers::{calculate_hash, render_image_data_to_canvases};
|
||||||
|
use crate::helpers::{request_animation_frame, set_timeout};
|
||||||
|
use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY};
|
||||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||||
use editor::application::{Editor, Environment, Host, Platform};
|
use editor::application::{Editor, Environment, Host, Platform};
|
||||||
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION};
|
#[cfg(feature = "editor")]
|
||||||
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
|
||||||
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
|
||||||
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
|
||||||
use editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
|
||||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
|
||||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
|
||||||
use editor::messages::portfolio::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
|
||||||
use editor::messages::prelude::*;
|
use editor::messages::prelude::*;
|
||||||
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
|
#[cfg(feature = "editor")]
|
||||||
use graph_craft::document::NodeId;
|
|
||||||
use graphene_std::color::SRGBA8;
|
|
||||||
use graphene_std::graphene_hash::CacheHashWrapper;
|
|
||||||
use graphene_std::raster::color::Color;
|
|
||||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_wasm_bindgen::{self, from_value};
|
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
|
pub(crate) static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
/// This struct is, via wasm-bindgen, used by JS to interact with the editor backend. It does this by calling functions, which are `impl`ed
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct EditorWrapper {
|
pub struct EditorWrapper {
|
||||||
@@ -46,13 +35,7 @@ pub struct EditorWrapper {
|
|||||||
frontend_message_handler_callback: js_sys::Function,
|
frontend_message_handler_callback: js_sys::Function,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Defined separately from the `impl` block below since this `impl` block lacks the `#[wasm_bindgen]` attribute.
|
|
||||||
// Quirks in wasm-bindgen prevent functions in `#[wasm_bindgen]` `impl` blocks from being made publicly accessible from Rust.
|
|
||||||
impl EditorWrapper {
|
impl EditorWrapper {
|
||||||
pub fn send_frontend_message_to_js_rust_proxy(&self, message: FrontendMessage) {
|
|
||||||
self.send_frontend_message_to_js(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(feature = "native", target_family = "wasm"))]
|
#[cfg(any(feature = "native", target_family = "wasm"))]
|
||||||
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
|
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
|
||||||
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
|
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
|
||||||
@@ -69,10 +52,6 @@ impl EditorWrapper {
|
|||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
impl EditorWrapper {
|
impl EditorWrapper {
|
||||||
// ========================
|
|
||||||
// Editor wrapper machinery
|
|
||||||
// ========================
|
|
||||||
|
|
||||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||||
pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
|
pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
|
||||||
use graph_craft::application_io::PlatformApplicationIo;
|
use graph_craft::application_io::PlatformApplicationIo;
|
||||||
@@ -115,7 +94,6 @@ impl EditorWrapper {
|
|||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
|
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
|
||||||
// Process no further messages after a crash to avoid spamming the console
|
// Process no further messages after a crash to avoid spamming the console
|
||||||
use crate::MESSAGE_BUFFER;
|
|
||||||
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -137,24 +115,15 @@ impl EditorWrapper {
|
|||||||
self.send_frontend_message_to_js(message);
|
self.send_frontend_message_to_js(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[cfg(feature = "native")]
|
|
||||||
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
|
|
||||||
let message: Message = message.into();
|
|
||||||
let Ok(serialized_message) = ron::to_string(&message) else {
|
|
||||||
log::error!("Failed to serialize message");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
crate::native_communication::send_message_to_cef(serialized_message)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sends a FrontendMessage to JavaScript
|
#[cfg(feature = "editor")]
|
||||||
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
|
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
|
||||||
if let FrontendMessage::UpdateImageData { ref image_data } = message {
|
if let FrontendMessage::UpdateImageData { ref image_data } = message {
|
||||||
let new_hash = calculate_hash(&CacheHashWrapper(image_data));
|
let new_hash = calculate_hash(image_data);
|
||||||
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
|
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
|
||||||
|
|
||||||
if new_hash != prev_hash {
|
if new_hash != prev_hash {
|
||||||
render_image_data_to_canvases(image_data.as_slice());
|
render_image_data_to_canvases(image_data.iter());
|
||||||
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
|
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -172,16 +141,31 @@ impl EditorWrapper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================
|
pub(crate) fn forward_serialized_frontend_message_to_js(&self, name: &str, data: crate::wasm_value::WasmValue) {
|
||||||
// Functions for calling the editor in Rust from JS
|
let js_return_value = self.frontend_message_handler_callback.call2(&JsValue::null(), &JsValue::from(name), &data.into());
|
||||||
// ================================================
|
|
||||||
|
|
||||||
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
|
if let Err(error) = js_return_value {
|
||||||
#[wasm_bindgen(js_name = resendAllLayouts)]
|
error!("While handling FrontendMessage {name:?}, JavaScript threw an error:\n{error:?}")
|
||||||
pub fn resend_all_layouts(&self) {
|
}
|
||||||
self.dispatch(LayoutMessage::ResendAllLayouts);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(all(feature = "native", target_family = "wasm"))]
|
||||||
|
pub(crate) fn send(&self, command: EditorCommand) {
|
||||||
|
// Process no further commands after a crash to avoid spamming the console
|
||||||
|
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(serialized) = serde_json::to_string(&command) else {
|
||||||
|
log::error!("Failed to serialize editor command");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
crate::native_communication::send_message_to_cef(serialized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
impl EditorWrapper {
|
||||||
#[wasm_bindgen(js_name = initAfterFrontendReady)]
|
#[wasm_bindgen(js_name = initAfterFrontendReady)]
|
||||||
pub fn init_after_frontend_ready(&self) {
|
pub fn init_after_frontend_ready(&self) {
|
||||||
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice
|
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice
|
||||||
@@ -192,7 +176,8 @@ impl EditorWrapper {
|
|||||||
#[cfg(feature = "native")]
|
#[cfg(feature = "native")]
|
||||||
crate::native_communication::initialize_native_communication();
|
crate::native_communication::initialize_native_communication();
|
||||||
|
|
||||||
self.dispatch(PortfolioMessage::Init);
|
#[cfg(target_family = "wasm")]
|
||||||
|
self.init_portfolio();
|
||||||
|
|
||||||
// Poll node graph evaluation on `requestAnimationFrame`
|
// Poll node graph evaluation on `requestAnimationFrame`
|
||||||
{
|
{
|
||||||
@@ -203,25 +188,19 @@ impl EditorWrapper {
|
|||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
|
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
|
||||||
|
|
||||||
if !EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
|
||||||
wrapper(|wrapper| {
|
wrapper(|wrapper| {
|
||||||
// Process all messages that have been queued up
|
// On web, flush the messages that queued up while the editor was locked before this frame's tick
|
||||||
let mut messages = MESSAGE_BUFFER.take();
|
#[cfg(not(feature = "native"))]
|
||||||
messages.push(
|
{
|
||||||
InputPreprocessorMessage::CurrentTime {
|
let messages = MESSAGE_BUFFER.take();
|
||||||
timestamp: js_sys::Date::now() as u64,
|
if !messages.is_empty() {
|
||||||
}
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
messages.push(AnimationMessage::IncrementFrameCounter.into());
|
|
||||||
|
|
||||||
// Used by auto-panning, but this could possibly be refactored in the future, see:
|
|
||||||
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
|
|
||||||
messages.push(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into());
|
|
||||||
|
|
||||||
wrapper.dispatch(Message::Batched { messages: messages.into() });
|
wrapper.dispatch(Message::Batched { messages: messages.into() });
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
wrapper.animation_frame(js_sys::Date::now() as u64);
|
||||||
|
});
|
||||||
|
|
||||||
// Schedule ourself for another requestAnimationFrame callback
|
// Schedule ourself for another requestAnimationFrame callback
|
||||||
request_animation_frame(f.borrow().as_ref().unwrap());
|
request_animation_frame(f.borrow().as_ref().unwrap());
|
||||||
@@ -230,94 +209,25 @@ impl EditorWrapper {
|
|||||||
request_animation_frame(g.borrow().as_ref().unwrap());
|
request_animation_frame(g.borrow().as_ref().unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||||
|
|
||||||
// Auto save all documents on `setTimeout`
|
// Auto save all documents on `setTimeout`
|
||||||
{
|
{
|
||||||
let f = std::rc::Rc::new(RefCell::new(None));
|
let f = std::rc::Rc::new(RefCell::new(None));
|
||||||
let g = f.clone();
|
let g = f.clone();
|
||||||
|
|
||||||
*g.borrow_mut() = Some(Closure::new(move || {
|
*g.borrow_mut() = Some(Closure::new(move || {
|
||||||
auto_save_all_documents();
|
#[cfg(target_family = "wasm")]
|
||||||
|
wrapper(|wrapper| wrapper.auto_save_all_documents());
|
||||||
|
|
||||||
// Schedule ourself for another setTimeout callback
|
// Schedule ourself for another setTimeout callback
|
||||||
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
|
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
|
||||||
}));
|
}));
|
||||||
|
|
||||||
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
|
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = addPrimaryImport)]
|
|
||||||
pub fn add_primary_import(&self) {
|
|
||||||
self.dispatch(DocumentMessage::AddTransaction);
|
|
||||||
self.dispatch(NodeGraphMessage::AddPrimaryImport);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = addSecondaryImport)]
|
|
||||||
pub fn add_secondary_import(&self) {
|
|
||||||
self.dispatch(DocumentMessage::AddTransaction);
|
|
||||||
self.dispatch(NodeGraphMessage::AddSecondaryImport);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = addPrimaryExport)]
|
|
||||||
pub fn add_primary_export(&self) {
|
|
||||||
self.dispatch(DocumentMessage::AddTransaction);
|
|
||||||
self.dispatch(NodeGraphMessage::AddPrimaryExport);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = addSecondaryExport)]
|
|
||||||
pub fn add_secondary_export(&self) {
|
|
||||||
self.dispatch(DocumentMessage::AddTransaction);
|
|
||||||
self.dispatch(NodeGraphMessage::AddSecondaryExport);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Start Pointer Lock
|
|
||||||
#[wasm_bindgen(js_name = appWindowPointerLock)]
|
|
||||||
pub fn app_window_pointer_lock(&self) {
|
|
||||||
let message = AppWindowMessage::PointerLock;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Minimizes the application window to the taskbar or dock
|
|
||||||
#[wasm_bindgen(js_name = appWindowMinimize)]
|
|
||||||
pub fn app_window_minimize(&self) {
|
|
||||||
let message = AppWindowMessage::Minimize;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggles minimizing or restoring down the application window
|
|
||||||
#[wasm_bindgen(js_name = appWindowMaximize)]
|
|
||||||
pub fn app_window_maximize(&self) {
|
|
||||||
let message = AppWindowMessage::Maximize;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = appWindowFullscreen)]
|
|
||||||
pub fn app_window_fullscreen(&self) {
|
|
||||||
let message = AppWindowMessage::Fullscreen;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Closes the application window
|
|
||||||
#[wasm_bindgen(js_name = appWindowClose)]
|
|
||||||
pub fn app_window_close(&self) {
|
|
||||||
let message = AppWindowMessage::Close;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drag the application window
|
|
||||||
#[wasm_bindgen(js_name = appWindowDrag)]
|
|
||||||
pub fn app_window_start_drag(&self) {
|
|
||||||
let message = AppWindowMessage::Drag;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Displays a dialog with an error message
|
|
||||||
#[wasm_bindgen(js_name = errorDialog)]
|
|
||||||
pub fn error_dialog(&self, title: String, description: String) {
|
|
||||||
let message = DialogMessage::DisplayDialogError { title, description };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answer whether or not the editor has crashed
|
/// Answer whether or not the editor has crashed
|
||||||
#[wasm_bindgen(js_name = hasCrashed)]
|
#[wasm_bindgen(js_name = hasCrashed)]
|
||||||
pub fn has_crashed(&self) -> bool {
|
pub fn has_crashed(&self) -> bool {
|
||||||
@@ -330,676 +240,25 @@ impl EditorWrapper {
|
|||||||
cfg!(debug_assertions)
|
cfg!(debug_assertions)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the constant `FILE_EXTENSION`
|
|
||||||
#[wasm_bindgen(js_name = fileExtension)]
|
#[wasm_bindgen(js_name = fileExtension)]
|
||||||
pub fn file_extension(&self) -> String {
|
pub fn file_extension(&self) -> String {
|
||||||
FILE_EXTENSION.into()
|
"graphite".into()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the constant `GDD_FILE_EXTENSION`
|
|
||||||
#[wasm_bindgen(js_name = gddFileExtension)]
|
#[wasm_bindgen(js_name = gddFileExtension)]
|
||||||
pub fn gdd_file_extension(&self) -> String {
|
pub fn gdd_file_extension(&self) -> String {
|
||||||
GDD_FILE_EXTENSION.into()
|
"gdd".into()
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
|
||||||
#[wasm_bindgen(js_name = widgetValueUpdate)]
|
|
||||||
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
|
||||||
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Commit the value of a given UI widget to the history
|
|
||||||
#[wasm_bindgen(js_name = widgetValueCommit)]
|
|
||||||
pub fn widget_value_commit(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
|
||||||
self.widget_value_commit_helper(layout_target, widget_id, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the value of a given UI widget, and commit it to the history
|
|
||||||
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
|
|
||||||
pub fn widget_value_commit_and_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
|
||||||
self.widget_value_commit_helper(layout_target, widget_id, value.clone())?;
|
|
||||||
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
|
|
||||||
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
|
|
||||||
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
|
|
||||||
self.dispatch(DocumentMessage::EndTransaction);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
|
|
||||||
#[wasm_bindgen(js_name = widgetValueDragDrop)]
|
|
||||||
pub fn widget_value_drag_drop(&self, layout_target: LayoutTarget, widget_id: u64) {
|
|
||||||
let widget_id = WidgetId(widget_id);
|
|
||||||
self.dispatch(LayoutMessage::WidgetValueDragDrop { layout_target, widget_id });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
|
|
||||||
#[wasm_bindgen(js_name = endTransaction)]
|
|
||||||
pub fn end_transaction(&self) {
|
|
||||||
self.dispatch(DocumentMessage::EndTransaction);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn widget_value_update_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
|
||||||
let widget_id = WidgetId(widget_id);
|
|
||||||
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not update UI: {e}")))?;
|
|
||||||
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
|
|
||||||
self.dispatch(message);
|
|
||||||
if resend_widget {
|
|
||||||
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
|
|
||||||
self.dispatch(resend_message);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn widget_value_commit_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
|
||||||
let widget_id = WidgetId(widget_id);
|
|
||||||
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not commit UI: {e}")))?;
|
|
||||||
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
|
|
||||||
self.dispatch(message);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = loadPreferences)]
|
|
||||||
pub fn load_preferences(&self, preferences: Option<String>) {
|
|
||||||
if let Some(preferences) = preferences {
|
|
||||||
let Ok(preferences) = serde_json::from_str(&preferences) else {
|
|
||||||
log::error!("Failed to deserialize preferences");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let message = PreferencesMessage::Load { preferences };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
|
||||||
|
#[cfg(all(feature = "web", not(feature = "native")))]
|
||||||
#[wasm_bindgen(js_name = loadPersistedState)]
|
#[wasm_bindgen(js_name = loadPersistedState)]
|
||||||
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
|
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
|
||||||
self.dispatch(PersistentStateMessage::LoadState { state });
|
self.dispatch(PersistentStateMessage::LoadState { state });
|
||||||
}
|
}
|
||||||
|
#[cfg(feature = "native")]
|
||||||
#[wasm_bindgen(js_name = loadDocumentContent)]
|
#[wasm_bindgen(js_name = loadPersistedState)]
|
||||||
pub fn load_document_content(&self, document_id: u64, document: String) {
|
pub fn load_persisted_state(&self, _state: JsValue) {
|
||||||
let message = PersistentStateMessage::LoadDocument {
|
log::error!("loadPersistedState is unavailable on desktop; persistence is handled natively");
|
||||||
document_id: DocumentId(document_id),
|
|
||||||
document,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = selectDocument)]
|
|
||||||
pub fn select_document(&self, document_id: u64) {
|
|
||||||
let document_id = DocumentId(document_id);
|
|
||||||
let message = PortfolioMessage::SelectDocument { document_id };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Rename the currently active document.
|
|
||||||
#[wasm_bindgen(js_name = renameDocument)]
|
|
||||||
pub fn rename_document(&self, new_name: String) {
|
|
||||||
let message = PortfolioMessage::RenameDocument { new_name };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = newDocumentDialog)]
|
|
||||||
pub fn new_document_dialog(&self) {
|
|
||||||
let message = DialogMessage::RequestNewDocumentDialog;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = openFile)]
|
|
||||||
pub fn open_file(&self, path: String, content: Vec<u8>) {
|
|
||||||
let message = PortfolioMessage::OpenFile { path: PathBuf::from(path), content };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = importFile)]
|
|
||||||
pub fn import_file(&self, path: String, content: Vec<u8>) {
|
|
||||||
let message = PortfolioMessage::ImportFile { path: PathBuf::from(path), content };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = triggerAutoSave)]
|
|
||||||
pub fn trigger_auto_save(&self, document_id: u64) {
|
|
||||||
let document_id = DocumentId(document_id);
|
|
||||||
let message = PortfolioMessage::AutoSaveDocument { document_id };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = reorderDocument)]
|
|
||||||
pub fn reorder_document(&self, document_id: u64, new_index: usize) {
|
|
||||||
let document_id = DocumentId(document_id);
|
|
||||||
let message = PortfolioMessage::ReorderDocument { document_id, new_index };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = reorderPanelGroupTab)]
|
|
||||||
pub fn reorder_panel_group_tab(&self, group: u64, old_index: usize, new_index: usize) {
|
|
||||||
let message = PortfolioMessage::ReorderPanelGroupTab {
|
|
||||||
group: PanelGroupId(group),
|
|
||||||
old_index,
|
|
||||||
new_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = moveAllPanelTabs)]
|
|
||||||
pub fn move_all_panel_tabs(&self, source_group: u64, target_group: u64, insert_index: usize) {
|
|
||||||
let message = PortfolioMessage::MoveAllPanelTabs {
|
|
||||||
source_group: PanelGroupId(source_group),
|
|
||||||
target_group: PanelGroupId(target_group),
|
|
||||||
insert_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = movePanelTab)]
|
|
||||||
pub fn move_panel_tab(&self, source_group: u64, target_group: u64, insert_index: usize) {
|
|
||||||
let message = PortfolioMessage::MovePanelTab {
|
|
||||||
source_group: PanelGroupId(source_group),
|
|
||||||
target_group: PanelGroupId(target_group),
|
|
||||||
insert_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = setPanelGroupActiveTab)]
|
|
||||||
pub fn set_panel_group_active_tab(&self, group: u64, tab_index: usize) {
|
|
||||||
let message = PortfolioMessage::SetPanelGroupActiveTab {
|
|
||||||
group: PanelGroupId(group),
|
|
||||||
tab_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = splitPanelGroup)]
|
|
||||||
pub fn split_panel_group(&self, target_group: u64, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) {
|
|
||||||
let message = PortfolioMessage::SplitPanelGroup {
|
|
||||||
target_group: PanelGroupId(target_group),
|
|
||||||
direction,
|
|
||||||
tabs,
|
|
||||||
active_tab_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = setPanelGroupSizes)]
|
|
||||||
pub fn set_panel_group_sizes(&self, split_path: Vec<u32>, sizes: Vec<f64>) {
|
|
||||||
let split_path = split_path.into_iter().map(|i| i as usize).collect();
|
|
||||||
let message = PortfolioMessage::SetPanelGroupSizes { split_path, sizes };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = closeDocumentWithConfirmation)]
|
|
||||||
pub fn close_document_with_confirmation(&self, document_id: u64) {
|
|
||||||
let document_id = DocumentId(document_id);
|
|
||||||
let message = PortfolioMessage::CloseDocumentWithConfirmation { document_id };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = requestAboutGraphiteDialogWithLocalizedCommitDate)]
|
|
||||||
pub fn request_about_graphite_dialog_with_localized_commit_date(&self, localized_commit_date: String, localized_commit_year: String) {
|
|
||||||
let message = DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
|
|
||||||
localized_commit_date,
|
|
||||||
localized_commit_year,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = requestLicensesThirdPartyDialogWithLicenseText)]
|
|
||||||
pub fn request_licenses_third_party_dialog_with_license_text(&self, license_text: String) {
|
|
||||||
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send new viewport info to the backend
|
|
||||||
#[wasm_bindgen(js_name = updateViewport)]
|
|
||||||
pub fn update_viewport(&self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
|
|
||||||
let message = ViewportMessage::Update { x, y, width, height, scale };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mouse movement within the screenspace bounds of the viewport
|
|
||||||
#[wasm_bindgen(js_name = onMouseMove)]
|
|
||||||
pub fn on_mouse_move(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
|
||||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
|
||||||
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mouse scrolling within the screenspace bounds of the viewport
|
|
||||||
#[wasm_bindgen(js_name = onWheelScroll)]
|
|
||||||
pub fn on_wheel_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) {
|
|
||||||
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
|
||||||
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
|
|
||||||
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A mouse button depressed within screenspace the bounds of the viewport
|
|
||||||
#[wasm_bindgen(js_name = onMouseDown)]
|
|
||||||
pub fn on_mouse_down(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
|
||||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
|
||||||
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A mouse button released
|
|
||||||
#[wasm_bindgen(js_name = onMouseUp)]
|
|
||||||
pub fn on_mouse_up(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
|
||||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
|
||||||
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mouse shaken
|
|
||||||
#[wasm_bindgen(js_name = onMouseShake)]
|
|
||||||
pub fn on_mouse_shake(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
|
||||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
|
||||||
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mouse double clicked
|
|
||||||
#[wasm_bindgen(js_name = onDoubleClick)]
|
|
||||||
pub fn on_double_click(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
|
||||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
|
||||||
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A keyboard button depressed within screenspace the bounds of the viewport
|
|
||||||
#[wasm_bindgen(js_name = onKeyDown)]
|
|
||||||
pub fn on_key_down(&self, name: String, modifiers: u8, key_repeat: bool) {
|
|
||||||
let key = translate_key(&name);
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A keyboard button released
|
|
||||||
#[wasm_bindgen(js_name = onKeyUp)]
|
|
||||||
pub fn on_key_up(&self, name: String, modifiers: u8, key_repeat: bool) {
|
|
||||||
let key = translate_key(&name);
|
|
||||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
|
||||||
|
|
||||||
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
|
|
||||||
|
|
||||||
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A text box was committed
|
|
||||||
#[wasm_bindgen(js_name = onChangeText)]
|
|
||||||
pub fn on_change_text(&self, new_text: String, is_left_or_right_click: bool) -> Result<(), JsValue> {
|
|
||||||
let message = TextToolMessage::TextChange { new_text, is_left_or_right_click };
|
|
||||||
self.dispatch(message);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dialog got dismissed
|
|
||||||
#[wasm_bindgen(js_name = onDialogDismiss)]
|
|
||||||
pub fn on_dialog_dismiss(&self) {
|
|
||||||
let message = DialogMessage::Dismiss;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A text box was changed
|
|
||||||
#[wasm_bindgen(js_name = updateBounds)]
|
|
||||||
pub fn update_bounds(&self, new_text: String) -> Result<(), JsValue> {
|
|
||||||
let message = TextToolMessage::UpdateBounds { new_text };
|
|
||||||
self.dispatch(message);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
|
|
||||||
#[wasm_bindgen(js_name = updatePrimaryColor)]
|
|
||||||
pub fn update_primary_color(&self, color: SRGBA8) {
|
|
||||||
self.dispatch(ToolMessage::SelectWorkingColor {
|
|
||||||
color: Color::from(color),
|
|
||||||
primary: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
|
|
||||||
#[wasm_bindgen(js_name = updateSecondaryColor)]
|
|
||||||
pub fn update_secondary_color(&self, color: SRGBA8) {
|
|
||||||
self.dispatch(ToolMessage::SelectWorkingColor {
|
|
||||||
color: Color::from(color),
|
|
||||||
primary: false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
|
|
||||||
#[wasm_bindgen(js_name = openColorPicker)]
|
|
||||||
pub fn open_color_picker(&self, initial_value: FillChoiceUI, allow_none: bool, disabled: bool) {
|
|
||||||
let initial_value = FillChoice::from(&initial_value);
|
|
||||||
self.dispatch(ColorPickerMessage::Open { initial_value, allow_none, disabled });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tell the Rust color picker handler that the popover is closing.
|
|
||||||
#[wasm_bindgen(js_name = closeColorPicker)]
|
|
||||||
pub fn close_color_picker(&self) {
|
|
||||||
self.dispatch(ColorPickerMessage::Close);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
|
|
||||||
#[wasm_bindgen(js_name = updateGradientStopColor)]
|
|
||||||
pub fn update_gradient_stop_color(&self, color: SRGBA8) {
|
|
||||||
self.dispatch(GradientToolMessage::UpdateStopColor { color: Color::from(color) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Start a new undo transaction for gradient stop color editing
|
|
||||||
#[wasm_bindgen(js_name = startGradientStopColorTransaction)]
|
|
||||||
pub fn start_gradient_stop_color_transaction(&self) {
|
|
||||||
self.dispatch(GradientToolMessage::StartTransactionForColorStop);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
|
|
||||||
#[wasm_bindgen(js_name = commitGradientStopColorTransaction)]
|
|
||||||
pub fn commit_gradient_stop_color_transaction(&self) {
|
|
||||||
self.dispatch(GradientToolMessage::CommitTransactionForColorStop);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close the gradient stop color picker and commit any pending transaction
|
|
||||||
#[wasm_bindgen(js_name = closeGradientStopColorPicker)]
|
|
||||||
pub fn close_gradient_stop_color_picker(&self) {
|
|
||||||
self.dispatch(GradientToolMessage::CloseStopColorPicker);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
|
|
||||||
#[wasm_bindgen(js_name = clipLayer)]
|
|
||||||
pub fn clip_layer(&self, id: u64) {
|
|
||||||
let id = NodeId(id);
|
|
||||||
let message = DocumentMessage::ClipLayer { id };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
|
|
||||||
#[wasm_bindgen(js_name = selectLayer)]
|
|
||||||
pub fn select_layer(&self, id: u64, ctrl: bool, shift: bool) {
|
|
||||||
let id = NodeId(id);
|
|
||||||
let message = DocumentMessage::SelectLayer { id, ctrl, shift };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Deselect all layers
|
|
||||||
#[wasm_bindgen(js_name = deselectAllLayers)]
|
|
||||||
pub fn deselect_all_layers(&self) {
|
|
||||||
let message = DocumentMessage::DeselectAllLayers;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Move a layer to within a folder and placed down at the given index.
|
|
||||||
/// If the folder is `None`, it is inserted into the document root.
|
|
||||||
/// If the insert index is `None`, it is inserted at the start of the folder.
|
|
||||||
#[wasm_bindgen(js_name = moveLayerInTree)]
|
|
||||||
pub fn move_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
|
|
||||||
let insert_parent_id = insert_parent_id.map(NodeId);
|
|
||||||
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
|
|
||||||
|
|
||||||
let message = DocumentMessage::MoveSelectedLayersTo {
|
|
||||||
parent,
|
|
||||||
insert_index: insert_index.unwrap_or_default(),
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reorder a draggable Properties panel section to the given index among its peers.
|
|
||||||
#[wasm_bindgen(js_name = reorderPropertiesSection)]
|
|
||||||
pub fn reorder_properties_section(&self, node_id: u64, insert_index: usize) {
|
|
||||||
self.dispatch(DocumentMessage::ReorderPropertiesSection {
|
|
||||||
node_id: NodeId(node_id),
|
|
||||||
insert_index,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
|
|
||||||
/// If the folder is `None`, they are inserted into the document root.
|
|
||||||
/// If the insert index is `None`, they are inserted at the start of the folder.
|
|
||||||
#[wasm_bindgen(js_name = duplicateLayerInTree)]
|
|
||||||
pub fn duplicate_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
|
|
||||||
let message = DocumentMessage::DuplicateSelectedLayersTo {
|
|
||||||
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
|
|
||||||
insert_index: insert_index.unwrap_or_default(),
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the name for the layer
|
|
||||||
#[wasm_bindgen(js_name = setLayerName)]
|
|
||||||
pub fn set_layer_name(&self, id: u64, name: String) {
|
|
||||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
|
|
||||||
let message = NodeGraphMessage::SetDisplayName {
|
|
||||||
node_id: layer.to_node(),
|
|
||||||
network_path: Vec::new(),
|
|
||||||
alias: name,
|
|
||||||
skip_adding_history_step: false,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Translates document (in viewport coords)
|
|
||||||
#[wasm_bindgen(js_name = panCanvasAbortPrepare)]
|
|
||||||
pub fn pan_canvas_abort_prepare(&self, x_not_y_axis: bool) {
|
|
||||||
let message = NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = panCanvasAbort)]
|
|
||||||
pub fn pan_canvas_abort(&self, x_not_y_axis: bool) {
|
|
||||||
let message = NavigationMessage::CanvasPanAbort { x_not_y_axis };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Translates document (in viewport coords)
|
|
||||||
#[wasm_bindgen(js_name = panCanvas)]
|
|
||||||
pub fn pan_canvas(&self, delta_x: f64, delta_y: f64) {
|
|
||||||
let message = NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Translates document (in viewport coords)
|
|
||||||
#[wasm_bindgen(js_name = panCanvasByFraction)]
|
|
||||||
pub fn pan_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
|
|
||||||
let message = NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Merge the selected nodes into a subnetwork
|
|
||||||
#[wasm_bindgen(js_name = mergeSelectedNodes)]
|
|
||||||
pub fn merge_nodes(&self) {
|
|
||||||
let message = NodeGraphMessage::MergeSelectedNodes;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggle lock state of all selected layers
|
|
||||||
#[wasm_bindgen(js_name = toggleSelectedLocked)]
|
|
||||||
pub fn toggle_selected_locked(&self) {
|
|
||||||
let message = NodeGraphMessage::ToggleSelectedLocked;
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a new document node in the node graph
|
|
||||||
#[wasm_bindgen(js_name = createNode)]
|
|
||||||
pub fn create_node(&self, node_type: JsValue, x: i32, y: i32) {
|
|
||||||
let value: serde_json::Value = serde_wasm_bindgen::from_value(node_type).unwrap();
|
|
||||||
|
|
||||||
let id = NodeId::new();
|
|
||||||
let message = NodeGraphMessage::CreateNodeFromContextMenu {
|
|
||||||
node_id: Some(id),
|
|
||||||
node_type: value.into(),
|
|
||||||
xy: Some((x / 24, y / 24)),
|
|
||||||
add_transaction: true,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Respond to selection read
|
|
||||||
#[wasm_bindgen(js_name = readSelection)]
|
|
||||||
pub fn read_selection(&self, content: Option<String>, cut: bool) {
|
|
||||||
let message = ClipboardMessage::ReadSelection { content, cut };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Paste from a serialized JSON representation
|
|
||||||
#[wasm_bindgen(js_name = pasteText)]
|
|
||||||
pub fn paste_text(&self, data: String) {
|
|
||||||
let message = ClipboardMessage::ReadClipboard {
|
|
||||||
content: ClipboardContentRaw::Text(data),
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pastes an image
|
|
||||||
#[wasm_bindgen(js_name = pasteImage)]
|
|
||||||
pub fn paste_image(
|
|
||||||
&self,
|
|
||||||
name: Option<String>,
|
|
||||||
image_data: Vec<u8>,
|
|
||||||
width: u32,
|
|
||||||
height: u32,
|
|
||||||
mouse_x: Option<f64>,
|
|
||||||
mouse_y: Option<f64>,
|
|
||||||
insert_parent_id: Option<u64>,
|
|
||||||
insert_index: Option<usize>,
|
|
||||||
) {
|
|
||||||
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
|
||||||
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
|
|
||||||
|
|
||||||
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
|
||||||
let insert_parent_id = NodeId(insert_parent_id);
|
|
||||||
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
|
||||||
Some((parent, insert_index))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let message = PortfolioMessage::InsertImage {
|
|
||||||
name,
|
|
||||||
image,
|
|
||||||
mouse,
|
|
||||||
parent_and_insert_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pastes an SVG given its string representation
|
|
||||||
#[wasm_bindgen(js_name = pasteSvg)]
|
|
||||||
pub fn paste_svg(&self, name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
|
|
||||||
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
|
||||||
|
|
||||||
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
|
||||||
let insert_parent_id = NodeId(insert_parent_id);
|
|
||||||
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
|
||||||
Some((parent, insert_index))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let message = PortfolioMessage::InsertSvg {
|
|
||||||
name,
|
|
||||||
svg,
|
|
||||||
mouse,
|
|
||||||
parent_and_insert_index,
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggle visibility of a layer or node given its node ID
|
|
||||||
#[wasm_bindgen(js_name = toggleNodeVisibilityLayerPanel)]
|
|
||||||
pub fn toggle_node_visibility_layer(&self, id: u64) {
|
|
||||||
let node_id = NodeId(id);
|
|
||||||
let message = NodeGraphMessage::ToggleVisibility { node_id, network_path: Vec::new() };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pin or unpin a node given its node ID
|
|
||||||
#[wasm_bindgen(js_name = setNodePinned)]
|
|
||||||
pub fn set_node_pinned(&self, id: u64, pinned: bool) {
|
|
||||||
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Collapse or expand a node's section in the Properties panel
|
|
||||||
#[wasm_bindgen(js_name = toggleNodePropertiesSectionExpanded)]
|
|
||||||
pub fn toggle_node_properties_section_expanded(&self, id: u64) {
|
|
||||||
self.dispatch(DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Delete a layer or node given its node ID
|
|
||||||
#[wasm_bindgen(js_name = deleteNode)]
|
|
||||||
pub fn delete_node(&self, id: u64) {
|
|
||||||
self.dispatch(DocumentMessage::DeleteNode { node_id: NodeId(id) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggle lock state of a layer from the layer list
|
|
||||||
#[wasm_bindgen(js_name = toggleLayerLock)]
|
|
||||||
pub fn toggle_layer_lock(&self, node_id: u64) {
|
|
||||||
let message = NodeGraphMessage::ToggleLocked {
|
|
||||||
node_id: NodeId(node_id),
|
|
||||||
network_path: Vec::new(),
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggle expansions state of a layer from the layer list
|
|
||||||
#[wasm_bindgen(js_name = toggleLayerExpansion)]
|
|
||||||
pub fn toggle_layer_expansion(&self, tree_path: &[u64], recursive: bool) {
|
|
||||||
let tree_path = tree_path.iter().map(|&id| NodeId(id)).collect();
|
|
||||||
let message = DocumentMessage::ToggleLayerExpansion { tree_path, recursive };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the active panel to the most recently clicked panel
|
|
||||||
#[wasm_bindgen(js_name = setActivePanel)]
|
|
||||||
pub fn set_active_panel(&self, panel: String) {
|
|
||||||
let message = DocumentMessage::SetActivePanel { active_panel: panel.into() };
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Toggle display type for a layer
|
|
||||||
#[wasm_bindgen(js_name = setToNodeOrLayer)]
|
|
||||||
pub fn set_to_node_or_layer(&self, id: u64, is_layer: bool) {
|
|
||||||
self.dispatch(DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the name of an import or export
|
|
||||||
#[wasm_bindgen(js_name = setImportName)]
|
|
||||||
pub fn set_import_name(&self, index: usize, name: String) {
|
|
||||||
let message = NodeGraphMessage::SetImportExportName {
|
|
||||||
name,
|
|
||||||
index: ImportOrExport::Import(index),
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the name of an export
|
|
||||||
#[wasm_bindgen(js_name = setExportName)]
|
|
||||||
pub fn set_export_name(&self, index: usize, name: String) {
|
|
||||||
let message = NodeGraphMessage::SetImportExportName {
|
|
||||||
name,
|
|
||||||
index: ImportOrExport::Export(index),
|
|
||||||
};
|
|
||||||
self.dispatch(message);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,18 @@
|
|||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
use crate::EDITOR;
|
use crate::EDITOR;
|
||||||
|
#[cfg(not(feature = "native"))]
|
||||||
|
use crate::EDITOR_HAS_CRASHED;
|
||||||
|
use crate::EDITOR_WRAPPER;
|
||||||
use crate::editor_wrapper::EditorWrapper;
|
use crate::editor_wrapper::EditorWrapper;
|
||||||
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER};
|
use crate::native_communication::RasterizedImage;
|
||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
use editor::application::Editor;
|
use editor::application::Editor;
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
use editor::messages::input_mapper::utility_types::input_keyboard::Key;
|
use editor::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||||
|
#[cfg(not(feature = "native"))]
|
||||||
use editor::messages::prelude::*;
|
use editor::messages::prelude::*;
|
||||||
use graphene_std::color::SRGBA8;
|
|
||||||
use graphene_std::raster::Image;
|
|
||||||
use js_sys::{Object, Reflect};
|
use js_sys::{Object, Reflect};
|
||||||
|
#[cfg(not(feature = "native"))]
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use wasm_bindgen::JsCast;
|
use wasm_bindgen::JsCast;
|
||||||
@@ -119,18 +123,8 @@ pub(crate) fn async_wake_callback() -> Wake {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn auto_save_all_documents() {
|
/// Blits each rasterized image to a canvas registered on `window.imageCanvases`
|
||||||
// Process no further messages after a crash to avoid spamming the console
|
pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<Item = &'a RasterizedImage>) {
|
||||||
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
wrapper(|wrapper| {
|
|
||||||
wrapper.dispatch(PortfolioMessage::AutoSaveAllDocuments);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)]) {
|
|
||||||
let window = match window() {
|
let window = match window() {
|
||||||
Some(window) => window,
|
Some(window) => window,
|
||||||
None => {
|
None => {
|
||||||
@@ -155,11 +149,13 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
|
|||||||
};
|
};
|
||||||
let canvases_obj = Object::from(canvases_obj);
|
let canvases_obj = Object::from(canvases_obj);
|
||||||
|
|
||||||
for (placeholder_id, image) in image_data.iter() {
|
for image in image_data {
|
||||||
|
let (placeholder_id, width, height) = (image.id, image.width, image.height);
|
||||||
|
let pixels = image.pixels.as_slice();
|
||||||
let canvas_name = placeholder_id.to_string();
|
let canvas_name = placeholder_id.to_string();
|
||||||
let js_key = JsValue::from_str(&canvas_name);
|
let js_key = JsValue::from_str(&canvas_name);
|
||||||
|
|
||||||
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || image.width == 0 || image.height == 0 {
|
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || width == 0 || height == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,8 +165,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
|
|||||||
.dyn_into::<HtmlCanvasElement>()
|
.dyn_into::<HtmlCanvasElement>()
|
||||||
.expect("Failed to cast element to HtmlCanvasElement");
|
.expect("Failed to cast element to HtmlCanvasElement");
|
||||||
|
|
||||||
canvas.set_width(image.width);
|
canvas.set_width(width);
|
||||||
canvas.set_height(image.height);
|
canvas.set_height(height);
|
||||||
|
|
||||||
let context: CanvasRenderingContext2d = canvas
|
let context: CanvasRenderingContext2d = canvas
|
||||||
.get_context("2d")
|
.get_context("2d")
|
||||||
@@ -178,10 +174,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
|
|||||||
.expect("2d context was not found")
|
.expect("2d context was not found")
|
||||||
.dyn_into::<CanvasRenderingContext2d>()
|
.dyn_into::<CanvasRenderingContext2d>()
|
||||||
.expect("Failed to cast context to CanvasRenderingContext2d");
|
.expect("Failed to cast context to CanvasRenderingContext2d");
|
||||||
// `SRGBA8` is `#[repr(C)]` of four `u8`s, so the data buffer is already the byte format the canvas expects
|
let clamped_pixels = wasm_bindgen::Clamped(pixels);
|
||||||
let u8_data: &[u8] = bytemuck::cast_slice(&image.data);
|
match ImageData::new_with_u8_clamped_array_and_sh(clamped_pixels, width, height) {
|
||||||
let clamped_u8_data = wasm_bindgen::Clamped(u8_data);
|
|
||||||
match ImageData::new_with_u8_clamped_array_and_sh(clamped_u8_data, image.width, image.height) {
|
|
||||||
Ok(image_data_obj) => {
|
Ok(image_data_obj) => {
|
||||||
if context.put_image_data(&image_data_obj, 0, 0).is_err() {
|
if context.put_image_data(&image_data_obj, 0, 0).is_err() {
|
||||||
error!("Failed to put image data on canvas for id: {placeholder_id}");
|
error!("Failed to put image data on canvas for id: {placeholder_id}");
|
||||||
@@ -209,6 +203,7 @@ pub(crate) fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Translate a keyboard key from its JS name to its Rust `Key` enum
|
/// Translate a keyboard key from its JS name to its Rust `Key` enum
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
pub(crate) fn translate_key(name: &str) -> Key {
|
pub(crate) fn translate_key(name: &str) -> Key {
|
||||||
use Key::*;
|
use Key::*;
|
||||||
|
|
||||||
|
|||||||
+46
-16
@@ -4,11 +4,18 @@
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate log;
|
extern crate log;
|
||||||
|
|
||||||
|
pub mod editor_commands;
|
||||||
pub mod editor_wrapper;
|
pub mod editor_wrapper;
|
||||||
pub mod helpers;
|
pub mod helpers;
|
||||||
pub mod native_communication;
|
pub mod native_communication;
|
||||||
|
mod wasm_value;
|
||||||
|
|
||||||
|
#[cfg(any(feature = "native", not(target_family = "wasm")))]
|
||||||
|
pub use editor_commands::EditorCommand;
|
||||||
|
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
use crate::helpers::wrapper;
|
use crate::helpers::wrapper;
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
use editor::messages::prelude::*;
|
use editor::messages::prelude::*;
|
||||||
use std::panic;
|
use std::panic;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
@@ -24,6 +31,7 @@ pub static LOGGER: WasmLog = WasmLog;
|
|||||||
thread_local! {
|
thread_local! {
|
||||||
#[cfg(not(feature = "native"))]
|
#[cfg(not(feature = "native"))]
|
||||||
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
|
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
|
||||||
|
#[cfg(not(feature = "native"))]
|
||||||
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
|
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||||
pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) };
|
pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) };
|
||||||
pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) };
|
pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) };
|
||||||
@@ -43,6 +51,10 @@ pub fn init_graphite() {
|
|||||||
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies
|
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies
|
||||||
pub fn panic_hook(info: &panic::PanicHookInfo) {
|
pub fn panic_hook(info: &panic::PanicHookInfo) {
|
||||||
let info = info.to_string();
|
let info = info.to_string();
|
||||||
|
|
||||||
|
// Node graph panics can only originate here when the node graph runs inside this wasm module
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
{
|
||||||
let backtrace = Error::new("stack").stack().to_string();
|
let backtrace = Error::new("stack").stack().to_string();
|
||||||
if backtrace.contains("DynAnyNode") {
|
if backtrace.contains("DynAnyNode") {
|
||||||
log::error!("Node graph evaluation panicked {info}");
|
log::error!("Node graph evaluation panicked {info}");
|
||||||
@@ -64,14 +76,15 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
|
|||||||
/text>"#
|
/text>"#
|
||||||
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
|
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
|
||||||
.to_string();
|
.to_string();
|
||||||
wrapper.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error });
|
wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
} else {
|
|
||||||
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
|
||||||
|
|
||||||
log::error!("{info}");
|
log::error!("{info}");
|
||||||
|
|
||||||
@@ -82,30 +95,20 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> {
|
fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> {
|
||||||
let message = FrontendMessage::DisplayDialogPanic { panic_info };
|
let message = PanicDialogMessage::DisplayDialogPanic { panic_info: panic_info.clone() };
|
||||||
let message_type = message.to_discriminant().local_name();
|
|
||||||
let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else {
|
let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else {
|
||||||
log::error!("Failed to serialize crash dialog panic message");
|
log::error!("Failed to serialize crash dialog panic message");
|
||||||
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
|
|
||||||
unreachable!("Message variant changed unexpectedly")
|
|
||||||
};
|
|
||||||
return Err(panic_info);
|
return Err(panic_info);
|
||||||
};
|
};
|
||||||
|
|
||||||
PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| {
|
PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| {
|
||||||
let callback_ref = callback.borrow();
|
let callback_ref = callback.borrow();
|
||||||
let Some(callback) = callback_ref.as_ref() else {
|
let Some(callback) = callback_ref.as_ref() else {
|
||||||
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
|
|
||||||
unreachable!("Message variant changed unexpectedly")
|
|
||||||
};
|
|
||||||
return Err(panic_info);
|
return Err(panic_info);
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from(message_type), &message_data) {
|
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from("DisplayDialogPanic"), &message_data) {
|
||||||
log::error!("Failed to send crash dialog panic message to JS: {:?}", error);
|
log::error!("Failed to send crash dialog panic message to JS: {error:?}");
|
||||||
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
|
|
||||||
unreachable!("Message variant changed unexpectedly")
|
|
||||||
};
|
|
||||||
return Err(panic_info);
|
return Err(panic_info);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,3 +204,30 @@ impl log::Log for WasmLog {
|
|||||||
|
|
||||||
fn flush(&self) {}
|
fn flush(&self) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
use editor::messages::prelude::FrontendMessage as PanicDialogMessage;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "editor"))]
|
||||||
|
use PanicDialogMessageCopy as PanicDialogMessage;
|
||||||
|
|
||||||
|
#[cfg(any(not(feature = "editor"), test))]
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
enum PanicDialogMessageCopy {
|
||||||
|
DisplayDialogPanic {
|
||||||
|
#[serde(rename = "panicInfo")]
|
||||||
|
panic_info: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "editor"))]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn panic_dialog_copy_matches_editor_shape() {
|
||||||
|
let copy = serde_json::to_value(PanicDialogMessageCopy::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
|
||||||
|
let real = serde_json::to_value(FrontendMessage::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
|
||||||
|
assert_eq!(copy, real);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +1,77 @@
|
|||||||
use crate::editor_wrapper::EditorWrapper;
|
//! Messaging with the native process. Serialized `FrontendMessage`s come in and are forwarded to JS,
|
||||||
use crate::helpers::wrapper;
|
//! `EditorCommand`s go back out. Encoding and decoding both live here so the wire format stays in one place.
|
||||||
use editor::messages::prelude::FrontendMessage;
|
|
||||||
|
use crate::editor_wrapper::{EditorWrapper, IMAGE_DATA_HASH};
|
||||||
|
use crate::helpers::{calculate_hash, render_image_data_to_canvases, wrapper};
|
||||||
|
use crate::wasm_value::WasmValue;
|
||||||
use js_sys::{ArrayBuffer, Uint8Array};
|
use js_sys::{ArrayBuffer, Uint8Array};
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
#[wasm_bindgen(js_name = "receiveNativeMessage")]
|
#[wasm_bindgen(js_name = "receiveNativeMessage")]
|
||||||
pub fn receive_native_message(buffer: ArrayBuffer) {
|
pub fn receive_native_message(buffer: ArrayBuffer) {
|
||||||
let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
|
let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
|
||||||
match ron::from_str::<Vec<FrontendMessage>>(str::from_utf8(buffer.as_slice()).unwrap()) {
|
match serde_json::from_slice::<Vec<(String, String)>>(&buffer) {
|
||||||
Ok(messages) => {
|
Ok(messages) => {
|
||||||
let callback = move |wrapper: &mut EditorWrapper| {
|
wrapper(move |wrapper: &mut EditorWrapper| {
|
||||||
for message in messages {
|
for (name, data) in messages {
|
||||||
wrapper.send_frontend_message_to_js_rust_proxy(message);
|
match name.as_str() {
|
||||||
|
"UpdateImageData" => {
|
||||||
|
let new_hash = calculate_hash(&data);
|
||||||
|
if IMAGE_DATA_HASH.swap(new_hash, Ordering::Relaxed) == new_hash {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
wrapper(callback);
|
match serde_json::from_str::<Vec<RasterizedImage>>(&data) {
|
||||||
|
Ok(image_data) => render_image_data_to_canvases(image_data.iter()),
|
||||||
|
Err(e) => error!("Failed to deserialize image data: {e:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => match serde_json::from_str::<WasmValue>(&data) {
|
||||||
|
Ok(value) => wrapper.forward_serialized_frontend_message_to_js(&name, value),
|
||||||
|
Err(e) => log::error!("Failed to deserialize frontend message {name}: {e:?}"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
|
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
pub fn encode_frontend_messages(messages: Vec<editor::messages::prelude::FrontendMessage>) -> Option<Vec<u8>> {
|
||||||
|
use editor::messages::prelude::FrontendMessage;
|
||||||
|
use editor::utility_traits::{AsMessage, ToDiscriminant};
|
||||||
|
|
||||||
|
let messages: Vec<(String, String)> = messages
|
||||||
|
.into_iter()
|
||||||
|
.map(|message| {
|
||||||
|
let name = message.to_discriminant().local_name();
|
||||||
|
let data = match message {
|
||||||
|
FrontendMessage::UpdateImageData { image_data } => serde_json::to_string(&image_data).inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}")).ok()?,
|
||||||
|
message => crate::wasm_value::encode(&message)
|
||||||
|
.inspect_err(|e| log::error!("Failed to serialize FrontendMessage {name}: {e}"))
|
||||||
|
.ok()?,
|
||||||
|
};
|
||||||
|
Some((name, data))
|
||||||
|
})
|
||||||
|
.collect::<Option<_>>()?;
|
||||||
|
|
||||||
|
serde_json::to_vec(&messages).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
|
||||||
|
pub fn decode_editor_command(data: &[u8]) -> Option<editor::messages::prelude::Message> {
|
||||||
|
match serde_json::from_slice::<crate::EditorCommand>(data) {
|
||||||
|
Ok(command) => Some(command.into()),
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to deserialize editor command: {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn initialize_native_communication() {
|
pub fn initialize_native_communication() {
|
||||||
let global = js_sys::global();
|
let global = js_sys::global();
|
||||||
|
|
||||||
@@ -44,3 +96,38 @@ pub fn send_message_to_cef(message: String) {
|
|||||||
// Call it with argument
|
// Call it with argument
|
||||||
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
|
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
pub(crate) use editor::messages::frontend::utility_types::RasterizedImage;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "editor"))]
|
||||||
|
pub(crate) use RasterizedImageCopy as RasterizedImage;
|
||||||
|
|
||||||
|
#[cfg(any(not(feature = "editor"), test))]
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub(crate) struct RasterizedImageCopy {
|
||||||
|
pub(crate) id: u64,
|
||||||
|
pub(crate) width: u32,
|
||||||
|
pub(crate) height: u32,
|
||||||
|
pub(crate) pixels: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "editor"))]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rasterized_image_copy_matches_editor_shape() {
|
||||||
|
let editor_image = RasterizedImage {
|
||||||
|
id: 7,
|
||||||
|
width: 2,
|
||||||
|
height: 1,
|
||||||
|
pixels: serde_bytes::ByteBuf::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
|
||||||
|
};
|
||||||
|
let json = serde_json::to_string(&vec![editor_image]).unwrap();
|
||||||
|
let decoded: Vec<RasterizedImageCopy> = serde_json::from_str(&json).unwrap();
|
||||||
|
assert_eq!(decoded[0].id, 7);
|
||||||
|
assert_eq!((decoded[0].width, decoded[0].height), (2, 1));
|
||||||
|
assert_eq!(decoded[0].pixels, [1, 2, 3, 4, 5, 6, 7, 8]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,448 @@
|
|||||||
|
//! Serializable stand-in for `JsValue`, used to send `FrontendMessage`s from the native editor process to JS.
|
||||||
|
//! Keeps the types JSON can't represent (`BigInt`, `Uint8Array`, `Map`, `undefined`, `NaN`) so the wasm side
|
||||||
|
//! can reconstruct the same `JsValue`s that `serde_wasm_bindgen` produces on web.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
use serde_json::Error;
|
||||||
|
use wasm_bindgen::JsValue;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub(crate) enum WasmValue {
|
||||||
|
Undefined,
|
||||||
|
Bool(bool),
|
||||||
|
Number(f64),
|
||||||
|
NonFinite(NonFinite),
|
||||||
|
Int(i64),
|
||||||
|
UInt(u64),
|
||||||
|
String(String),
|
||||||
|
Bytes(Vec<u8>),
|
||||||
|
Seq(Vec<WasmValue>),
|
||||||
|
Object(Vec<(String, WasmValue)>),
|
||||||
|
Map(Vec<(WasmValue, WasmValue)>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) enum NonFinite {
|
||||||
|
Nan,
|
||||||
|
PositiveInfinity,
|
||||||
|
NegativeInfinity,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<NonFinite> for f64 {
|
||||||
|
fn from(value: NonFinite) -> Self {
|
||||||
|
match value {
|
||||||
|
NonFinite::Nan => f64::NAN,
|
||||||
|
NonFinite::PositiveInfinity => f64::INFINITY,
|
||||||
|
NonFinite::NegativeInfinity => f64::NEG_INFINITY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<WasmValue> for JsValue {
|
||||||
|
fn from(value: WasmValue) -> Self {
|
||||||
|
match value {
|
||||||
|
WasmValue::Undefined => JsValue::UNDEFINED,
|
||||||
|
WasmValue::Bool(value) => JsValue::from_bool(value),
|
||||||
|
WasmValue::Number(value) => JsValue::from_f64(value),
|
||||||
|
WasmValue::NonFinite(value) => JsValue::from_f64(value.into()),
|
||||||
|
WasmValue::Int(value) => JsValue::from(value),
|
||||||
|
WasmValue::UInt(value) => JsValue::from(value),
|
||||||
|
WasmValue::String(value) => JsValue::from_str(&value),
|
||||||
|
WasmValue::Bytes(bytes) => js_sys::Uint8Array::from(bytes.as_slice()).into(),
|
||||||
|
WasmValue::Seq(values) => {
|
||||||
|
let array = js_sys::Array::new();
|
||||||
|
for value in values {
|
||||||
|
array.push(&value.into());
|
||||||
|
}
|
||||||
|
array.into()
|
||||||
|
}
|
||||||
|
WasmValue::Object(fields) => {
|
||||||
|
let object = js_sys::Object::new();
|
||||||
|
for (key, value) in fields {
|
||||||
|
let _ = js_sys::Reflect::set(&object, &JsValue::from_str(&key), &value.into());
|
||||||
|
}
|
||||||
|
object.into()
|
||||||
|
}
|
||||||
|
WasmValue::Map(entries) => {
|
||||||
|
let map = js_sys::Map::new();
|
||||||
|
for (key, value) in entries {
|
||||||
|
map.set(&key.into(), &value.into());
|
||||||
|
}
|
||||||
|
map.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
pub(crate) fn encode<T: Serialize + ?Sized>(value: &T) -> Result<String, serde_json::Error> {
|
||||||
|
serde_json::to_string(&ser::to_value(value)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "editor")]
|
||||||
|
mod ser {
|
||||||
|
use super::*;
|
||||||
|
use serde::ser::{self, Error as _};
|
||||||
|
|
||||||
|
pub(super) fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<WasmValue, Error> {
|
||||||
|
value.serialize(ValueSerializer)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ValueSerializer;
|
||||||
|
|
||||||
|
impl ser::Serializer for ValueSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
type SerializeSeq = SeqSerializer;
|
||||||
|
type SerializeTuple = SeqSerializer;
|
||||||
|
type SerializeTupleStruct = SeqSerializer;
|
||||||
|
type SerializeTupleVariant = VariantSeqSerializer;
|
||||||
|
type SerializeMap = MapSerializer;
|
||||||
|
type SerializeStruct = ObjectSerializer;
|
||||||
|
type SerializeStructVariant = VariantObjectSerializer;
|
||||||
|
|
||||||
|
fn serialize_bool(self, v: bool) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Bool(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i8(self, v: i8) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Number(v as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i16(self, v: i16) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Number(v as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i32(self, v: i32) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Number(v as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i64(self, v: i64) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Int(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i128(self, v: i128) -> Result<WasmValue, Error> {
|
||||||
|
if let Ok(v) = i64::try_from(v) {
|
||||||
|
Ok(WasmValue::Int(v))
|
||||||
|
} else {
|
||||||
|
u64::try_from(v)
|
||||||
|
.map(WasmValue::UInt)
|
||||||
|
.map_err(|_| Error::custom(format!("i128 value {v} exceeds the wire BigInt range")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u8(self, v: u8) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Number(v as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u16(self, v: u16) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Number(v as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u32(self, v: u32) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Number(v as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u64(self, v: u64) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::UInt(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u128(self, v: u128) -> Result<WasmValue, Error> {
|
||||||
|
u64::try_from(v)
|
||||||
|
.map(WasmValue::UInt)
|
||||||
|
.map_err(|_| Error::custom(format!("u128 value {v} exceeds the wire BigInt range")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_f32(self, v: f32) -> Result<WasmValue, Error> {
|
||||||
|
self.serialize_f64(v as f64)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_f64(self, v: f64) -> Result<WasmValue, Error> {
|
||||||
|
Ok(if v.is_finite() {
|
||||||
|
WasmValue::Number(v)
|
||||||
|
} else if v.is_nan() {
|
||||||
|
WasmValue::NonFinite(NonFinite::Nan)
|
||||||
|
} else if v > 0. {
|
||||||
|
WasmValue::NonFinite(NonFinite::PositiveInfinity)
|
||||||
|
} else {
|
||||||
|
WasmValue::NonFinite(NonFinite::NegativeInfinity)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_char(self, v: char) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::String(v.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_str(self, v: &str) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::String(v.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_bytes(self, v: &[u8]) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Bytes(v.to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_none(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<WasmValue, Error> {
|
||||||
|
value.serialize(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit_struct(self, _name: &'static str) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::String(variant.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_newtype_struct<T: Serialize + ?Sized>(self, _name: &'static str, value: &T) -> Result<WasmValue, Error> {
|
||||||
|
value.serialize(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_newtype_variant<T: Serialize + ?Sized>(self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Object(vec![(variant.to_string(), value.serialize(ValueSerializer)?)]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_seq(self, len: Option<usize>) -> Result<SeqSerializer, Error> {
|
||||||
|
Ok(SeqSerializer(Vec::with_capacity(len.unwrap_or_default())))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple(self, len: usize) -> Result<SeqSerializer, Error> {
|
||||||
|
self.serialize_seq(Some(len))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqSerializer, Error> {
|
||||||
|
self.serialize_seq(Some(len))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantSeqSerializer, Error> {
|
||||||
|
Ok(VariantSeqSerializer {
|
||||||
|
variant,
|
||||||
|
elements: Vec::with_capacity(len),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_map(self, len: Option<usize>) -> Result<MapSerializer, Error> {
|
||||||
|
Ok(MapSerializer {
|
||||||
|
entries: Vec::with_capacity(len.unwrap_or_default()),
|
||||||
|
pending_key: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<ObjectSerializer, Error> {
|
||||||
|
Ok(ObjectSerializer(Vec::with_capacity(len)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantObjectSerializer, Error> {
|
||||||
|
Ok(VariantObjectSerializer {
|
||||||
|
variant,
|
||||||
|
fields: Vec::with_capacity(len),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SeqSerializer(Vec<WasmValue>);
|
||||||
|
|
||||||
|
impl ser::SerializeSeq for SeqSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||||
|
self.0.push(value.serialize(ValueSerializer)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Seq(self.0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ser::SerializeTuple for SeqSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||||
|
ser::SerializeSeq::serialize_element(self, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
ser::SerializeSeq::end(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ser::SerializeTupleStruct for SeqSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||||
|
ser::SerializeSeq::serialize_element(self, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
ser::SerializeSeq::end(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VariantSeqSerializer {
|
||||||
|
variant: &'static str,
|
||||||
|
elements: Vec<WasmValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ser::SerializeTupleVariant for VariantSeqSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||||
|
self.elements.push(value.serialize(ValueSerializer)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Seq(self.elements))]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MapSerializer {
|
||||||
|
entries: Vec<(WasmValue, WasmValue)>,
|
||||||
|
pending_key: Option<WasmValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ser::SerializeMap for MapSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {
|
||||||
|
self.pending_key = Some(key.serialize(ValueSerializer)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||||
|
let key = self.pending_key.take().ok_or_else(|| Error::custom("Map value serialized without a key"))?;
|
||||||
|
self.entries.push((key, value.serialize(ValueSerializer)?));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Map(self.entries))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ObjectSerializer(Vec<(String, WasmValue)>);
|
||||||
|
|
||||||
|
impl ser::SerializeStruct for ObjectSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
|
||||||
|
self.0.push((key.to_string(), value.serialize(ValueSerializer)?));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Object(self.0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VariantObjectSerializer {
|
||||||
|
variant: &'static str,
|
||||||
|
fields: Vec<(String, WasmValue)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ser::SerializeStructVariant for VariantObjectSerializer {
|
||||||
|
type Ok = WasmValue;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
|
||||||
|
self.fields.push((key.to_string(), value.serialize(ValueSerializer)?));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<WasmValue, Error> {
|
||||||
|
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Object(self.fields))]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::wasm_value::encode;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
enum TestMessage {
|
||||||
|
UnitVariant,
|
||||||
|
StructVariant {
|
||||||
|
#[serde(rename = "nodeId")]
|
||||||
|
node_id: u64,
|
||||||
|
width: u32,
|
||||||
|
scale: f64,
|
||||||
|
min: f64,
|
||||||
|
max: f64,
|
||||||
|
label: Option<String>,
|
||||||
|
widths: std::collections::BTreeMap<u64, u32>,
|
||||||
|
flags: Vec<bool>,
|
||||||
|
bytes: serde_bytes::ByteBuf,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mirrors_serde_wasm_bindgen_representations() {
|
||||||
|
assert_eq!(to_value(&TestMessage::UnitVariant).unwrap(), WasmValue::String("unitVariant".into()));
|
||||||
|
|
||||||
|
let message = TestMessage::StructVariant {
|
||||||
|
node_id: u64::MAX,
|
||||||
|
width: 8,
|
||||||
|
scale: f64::NAN,
|
||||||
|
min: f64::NEG_INFINITY,
|
||||||
|
max: f64::INFINITY,
|
||||||
|
label: None,
|
||||||
|
widths: [(42, 7)].into(),
|
||||||
|
flags: vec![true, false],
|
||||||
|
bytes: serde_bytes::ByteBuf::from(vec![0, 255]),
|
||||||
|
};
|
||||||
|
let expected = WasmValue::Object(vec![(
|
||||||
|
"structVariant".into(),
|
||||||
|
WasmValue::Object(vec![
|
||||||
|
("nodeId".into(), WasmValue::UInt(u64::MAX)),
|
||||||
|
("width".into(), WasmValue::Number(8.)),
|
||||||
|
("scale".into(), WasmValue::NonFinite(NonFinite::Nan)),
|
||||||
|
("min".into(), WasmValue::NonFinite(NonFinite::NegativeInfinity)),
|
||||||
|
("max".into(), WasmValue::NonFinite(NonFinite::PositiveInfinity)),
|
||||||
|
("label".into(), WasmValue::Undefined),
|
||||||
|
("widths".into(), WasmValue::Map(vec![(WasmValue::UInt(42), WasmValue::Number(7.))])),
|
||||||
|
("flags".into(), WasmValue::Seq(vec![WasmValue::Bool(true), WasmValue::Bool(false)])),
|
||||||
|
("bytes".into(), WasmValue::Bytes(vec![0, 255])),
|
||||||
|
]),
|
||||||
|
)]);
|
||||||
|
assert_eq!(to_value(&message).unwrap(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_decode_roundtrip() {
|
||||||
|
let message = TestMessage::StructVariant {
|
||||||
|
node_id: 1,
|
||||||
|
width: 2,
|
||||||
|
scale: f64::NAN,
|
||||||
|
min: f64::NEG_INFINITY,
|
||||||
|
max: 1.5,
|
||||||
|
label: Some("hi".into()),
|
||||||
|
widths: [(3, 4)].into(),
|
||||||
|
flags: vec![true],
|
||||||
|
bytes: serde_bytes::ByteBuf::from(vec![9]),
|
||||||
|
};
|
||||||
|
|
||||||
|
let json: &str = &encode(&message).unwrap();
|
||||||
|
let decoded: WasmValue = serde_json::from_str(json).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(decoded, to_value(&message).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ extern crate proc_macro;
|
|||||||
use proc_macro::TokenStream;
|
use proc_macro::TokenStream;
|
||||||
use proc_macro2::Span;
|
use proc_macro2::Span;
|
||||||
use quote::quote;
|
use quote::quote;
|
||||||
use syn::{DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound, parse_macro_input};
|
use syn::{DeriveInput, GenericParam, Lifetime, TypeParamBound, parse_macro_input};
|
||||||
|
|
||||||
/// Derives an implementation for the [`DynAny`] trait.
|
/// Derives an implementation for the [`DynAny`] trait.
|
||||||
///
|
///
|
||||||
@@ -40,37 +40,45 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream {
|
|||||||
let struct_name = &ast.ident;
|
let struct_name = &ast.ident;
|
||||||
let generics = &ast.generics;
|
let generics = &ast.generics;
|
||||||
|
|
||||||
let static_params = replace_lifetimes(generics, "'static");
|
let static_params = generic_arguments(generics, "'static");
|
||||||
let dyn_params = replace_lifetimes(generics, "'dyn_any");
|
let dyn_params = generic_arguments(generics, "'dyn_any");
|
||||||
|
|
||||||
let old_params = &generics.params.iter().collect::<Vec<_>>();
|
let impl_params = generics.params.iter().map(|param| match param {
|
||||||
|
GenericParam::Type(t) => {
|
||||||
|
let mut t = t.clone();
|
||||||
|
t.bounds.push(TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())));
|
||||||
|
quote! {#t}
|
||||||
|
}
|
||||||
|
param => quote! {#param},
|
||||||
|
});
|
||||||
quote! {
|
quote! {
|
||||||
unsafe impl<'dyn_any, #(#old_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
|
unsafe impl<'dyn_any, #(#impl_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
|
||||||
type Static = #struct_name <#(#static_params,)*>;
|
type Static = #struct_name <#(#static_params,)*>;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
|
/// The struct's generic parameters as argument tokens: bare idents for type
|
||||||
|
/// and const parameters (bounds are illegal in argument position), the
|
||||||
|
/// replacement for lifetimes.
|
||||||
|
fn generic_arguments(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
|
||||||
generics
|
generics
|
||||||
.params
|
.params
|
||||||
.iter()
|
.iter()
|
||||||
.map(|param| {
|
.map(|param| match param {
|
||||||
let param = match param {
|
GenericParam::Lifetime(_) => {
|
||||||
GenericParam::Lifetime(_) => GenericParam::Lifetime(LifetimeParam::new(Lifetime::new(replacement, Span::call_site()))),
|
let lifetime = Lifetime::new(replacement, Span::call_site());
|
||||||
|
quote! {#lifetime}
|
||||||
|
}
|
||||||
GenericParam::Type(t) => {
|
GenericParam::Type(t) => {
|
||||||
let mut t = t.clone();
|
let ident = &t.ident;
|
||||||
t.bounds.iter_mut().for_each(|bond| {
|
quote! {#ident}
|
||||||
if let TypeParamBound::Lifetime(t) = bond {
|
|
||||||
*t = Lifetime::new(replacement, Span::call_site())
|
|
||||||
}
|
}
|
||||||
});
|
GenericParam::Const(c) => {
|
||||||
GenericParam::Type(t.clone())
|
let ident = &c.ident;
|
||||||
|
quote! {#ident}
|
||||||
}
|
}
|
||||||
c => c.clone(),
|
|
||||||
};
|
|
||||||
quote! {#param}
|
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
}
|
}
|
||||||
@@ -74,6 +74,7 @@ mmap-io = { workspace = true }
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
graph-craft = { workspace = true, features = ["loading"] }
|
graph-craft = { workspace = true, features = ["loading"] }
|
||||||
|
interpreted-executor = { workspace = true }
|
||||||
pretty_assertions = { workspace = true }
|
pretty_assertions = { workspace = true }
|
||||||
criterion = { workspace = true }
|
criterion = { workspace = true }
|
||||||
gungraun = { workspace = true }
|
gungraun = { workspace = true }
|
||||||
|
|||||||
@@ -6,10 +6,13 @@ use graph_craft::util::DEMO_ART;
|
|||||||
fn compile_to_proto(c: &mut Criterion) {
|
fn compile_to_proto(c: &mut Criterion) {
|
||||||
use graph_craft::util::{compile, load_from_name};
|
use graph_craft::util::{compile, load_from_name};
|
||||||
let mut c = c.benchmark_group("Compile Network cold");
|
let mut c = c.benchmark_group("Compile Network cold");
|
||||||
|
let registry = &interpreted_executor::node_registry::NODE_REGISTRY;
|
||||||
|
|
||||||
for name in DEMO_ART {
|
for name in DEMO_ART {
|
||||||
let network = load_from_name(name);
|
let network = load_from_name(name);
|
||||||
c.bench_function(name, |b| b.iter_batched(|| network.clone(), |network| compile(black_box(network)), criterion::BatchSize::SmallInput));
|
c.bench_function(name, |b| {
|
||||||
|
b.iter_batched(|| network.clone(), |network| compile(black_box(network), registry), criterion::BatchSize::SmallInput)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use gungraun::prelude::*;
|
|||||||
#[library_benchmark]
|
#[library_benchmark]
|
||||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
|
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
|
||||||
pub fn compile_to_proto(_input: NodeNetwork) {
|
pub fn compile_to_proto(_input: NodeNetwork) {
|
||||||
std::hint::black_box(compile(_input));
|
std::hint::black_box(compile(_input, &interpreted_executor::node_registry::NODE_REGISTRY));
|
||||||
}
|
}
|
||||||
|
|
||||||
library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto);
|
library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto);
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ pub use graphene_application_io::ApplicationIo;
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct PlatformApplicationIo {
|
pub struct PlatformApplicationIo {
|
||||||
#[cfg(feature = "wgpu")]
|
#[cfg(feature = "wgpu")]
|
||||||
gpu_executor: Option<WgpuExecutor>,
|
gpu_executor: Option<std::sync::Arc<WgpuExecutor>>,
|
||||||
resources: Option<Box<dyn resource::LoadResource>>,
|
resources: Option<Box<dyn resource::LoadResource>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ impl PlatformApplicationIo {
|
|||||||
|
|
||||||
Self {
|
Self {
|
||||||
#[cfg(feature = "wgpu")]
|
#[cfg(feature = "wgpu")]
|
||||||
gpu_executor: executor,
|
gpu_executor: executor.map(std::sync::Arc::new),
|
||||||
resources: None,
|
resources: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,7 +39,7 @@ impl PlatformApplicationIo {
|
|||||||
set_wgpu_available(wgpu_available);
|
set_wgpu_available(wgpu_available);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
gpu_executor: executor,
|
gpu_executor: executor.map(std::sync::Arc::new),
|
||||||
resources: None,
|
resources: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,12 @@ impl ApplicationIo for PlatformApplicationIo {
|
|||||||
|
|
||||||
#[cfg(feature = "wgpu")]
|
#[cfg(feature = "wgpu")]
|
||||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||||
self.gpu_executor.as_ref()
|
self.gpu_executor.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "wgpu")]
|
||||||
|
fn gpu_executor_arc(&self) -> Option<std::sync::Arc<Self::Executor>> {
|
||||||
|
self.gpu_executor.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ pub use core_types::uuid::generate_uuid;
|
|||||||
use core_types::{Context, ContextDependencies, Cow, MemoHash, ProtoNodeIdentifier, Type};
|
use core_types::{Context, ContextDependencies, Cow, MemoHash, ProtoNodeIdentifier, Type};
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::IVec2;
|
use glam::IVec2;
|
||||||
use log::Metadata;
|
|
||||||
use rustc_hash::FxHashMap;
|
use rustc_hash::FxHashMap;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
@@ -58,7 +57,8 @@ pub struct DocumentNode {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub skip_deduplication: bool,
|
pub skip_deduplication: bool,
|
||||||
/// List of Extract and Inject annotations for the Context.
|
/// List of Extract and Inject annotations for the Context.
|
||||||
#[serde(default)]
|
/// Resolved from the registry at compile time; only code-built wrapper nodes carry a declaration here.
|
||||||
|
#[serde(skip)]
|
||||||
pub context_features: ContextDependencies,
|
pub context_features: ContextDependencies,
|
||||||
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
@@ -167,6 +167,8 @@ impl DocumentNode {
|
|||||||
original_location: self.original_location,
|
original_location: self.original_location,
|
||||||
skip_deduplication: self.skip_deduplication,
|
skip_deduplication: self.skip_deduplication,
|
||||||
context_features: self.context_features,
|
context_features: self.context_features,
|
||||||
|
lane_invariant_inputs: 0,
|
||||||
|
resolved: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,12 +217,14 @@ impl InlineRust {
|
|||||||
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum DocumentNodeMetadata {
|
pub enum DocumentNodeMetadata {
|
||||||
DocumentNodePath,
|
DocumentNodePath,
|
||||||
|
SourceId,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DocumentNodeMetadata {
|
impl DocumentNodeMetadata {
|
||||||
pub fn ty(&self) -> Type {
|
pub fn ty(&self) -> Type {
|
||||||
match self {
|
match self {
|
||||||
DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>),
|
DocumentNodeMetadata::DocumentNodePath => concrete!(Vec<NodeId>),
|
||||||
|
DocumentNodeMetadata::SourceId => concrete!(u64),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -273,7 +277,7 @@ impl NodeInput {
|
|||||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||||
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
|
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
|
||||||
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
|
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
|
||||||
NodeInput::Reflection(_) => concrete!(Metadata),
|
NodeInput::Reflection(metadata) => metadata.ty(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -879,7 +883,7 @@ impl NodeNetwork {
|
|||||||
|
|
||||||
// Replace value inputs with dedicated value nodes
|
// Replace value inputs with dedicated value nodes
|
||||||
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
|
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
|
||||||
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id);
|
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id, Some(&mut node.context_features));
|
||||||
}
|
}
|
||||||
|
|
||||||
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
|
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
|
||||||
@@ -898,6 +902,7 @@ impl NodeNetwork {
|
|||||||
gen_id,
|
gen_id,
|
||||||
map_ids,
|
map_ids,
|
||||||
id,
|
id,
|
||||||
|
None,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
|
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
|
||||||
@@ -978,6 +983,12 @@ impl NodeNetwork {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn source_id_for_path(path: &[NodeId]) -> u64 {
|
||||||
|
let mut hasher = graphene_hash::FxHasher64::new();
|
||||||
|
path.hash(&mut hasher);
|
||||||
|
hasher.finish()
|
||||||
|
}
|
||||||
|
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
fn replace_value_inputs_with_nodes(
|
fn replace_value_inputs_with_nodes(
|
||||||
inputs: &mut [NodeInput],
|
inputs: &mut [NodeInput],
|
||||||
@@ -986,6 +997,7 @@ impl NodeNetwork {
|
|||||||
gen_id: impl Fn() -> NodeId + Copy,
|
gen_id: impl Fn() -> NodeId + Copy,
|
||||||
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
|
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
|
mut context_features: Option<&mut ContextDependencies>,
|
||||||
) {
|
) {
|
||||||
// Replace value exports and imports with value nodes, added inside the nested network
|
// Replace value exports and imports with value nodes, added inside the nested network
|
||||||
for export in inputs {
|
for export in inputs {
|
||||||
@@ -996,6 +1008,13 @@ impl NodeNetwork {
|
|||||||
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
|
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
|
||||||
NodeInput::Reflection(reflect) => match reflect {
|
NodeInput::Reflection(reflect) => match reflect {
|
||||||
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
|
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
|
||||||
|
DocumentNodeMetadata::SourceId => {
|
||||||
|
let source_id = Self::source_id_for_path(path);
|
||||||
|
if let Some(context_features) = context_features.as_deref_mut() {
|
||||||
|
context_features.add_sources(&[source_id]);
|
||||||
|
}
|
||||||
|
(TaggedValue::U64(source_id).into(), false)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
previous_export => {
|
previous_export => {
|
||||||
*export = previous_export;
|
*export = previous_export;
|
||||||
@@ -1146,6 +1165,7 @@ impl NodeNetwork {
|
|||||||
inputs: Vec::new(),
|
inputs: Vec::new(),
|
||||||
output: node_id,
|
output: node_id,
|
||||||
nodes,
|
nodes,
|
||||||
|
..Default::default()
|
||||||
}]
|
}]
|
||||||
.into_iter();
|
.into_iter();
|
||||||
}
|
}
|
||||||
@@ -1162,6 +1182,7 @@ impl NodeNetwork {
|
|||||||
// inputs: self.imports.clone(),
|
// inputs: self.imports.clone(),
|
||||||
output: node_id,
|
output: node_id,
|
||||||
nodes: nodes.clone(),
|
nodes: nodes.clone(),
|
||||||
|
..Default::default()
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -1208,7 +1229,9 @@ fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> R
|
|||||||
Old(Option<Type>),
|
Old(Option<Type>),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Eventually remove this migration document upgrade code
|
||||||
Ok(match CallArg::deserialize(deserializer)? {
|
Ok(match CallArg::deserialize(deserializer)? {
|
||||||
|
CallArg::New(Type::Concrete(descriptor)) if descriptor.name.ends_with("OwnedContextImpl>>") => concrete!(Context),
|
||||||
CallArg::New(ty) => ty,
|
CallArg::New(ty) => ty,
|
||||||
CallArg::Old(ty) => ty.unwrap_or_default(),
|
CallArg::Old(ty) => ty.unwrap_or_default(),
|
||||||
})
|
})
|
||||||
@@ -1424,6 +1447,7 @@ mod test {
|
|||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect(),
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
};
|
};
|
||||||
let network = flat_network();
|
let network = flat_network();
|
||||||
let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>();
|
let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>();
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
use super::DocumentNode;
|
use super::DocumentNode;
|
||||||
use crate::application_io::PlatformEditorApi;
|
use crate::application_io::PlatformEditorApi;
|
||||||
use crate::application_io::resource::Resource;
|
use crate::application_io::resource::Resource;
|
||||||
use crate::proto::{Any as DAny, FutureAny};
|
use crate::proto::Any as DAny;
|
||||||
use brush_nodes::brush_stroke::BrushStroke;
|
use brush_nodes::brush_stroke::BrushStroke;
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
|
use core_types::context::Context;
|
||||||
|
use core_types::gpoll::GPoll;
|
||||||
use core_types::list::List;
|
use core_types::list::List;
|
||||||
|
use core_types::registry::SourceHandle;
|
||||||
use core_types::transform::Footprint;
|
use core_types::transform::Footprint;
|
||||||
use core_types::uuid::NodeId;
|
use core_types::uuid::NodeId;
|
||||||
use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor};
|
use core_types::value::{leveled_record_value_source, record_value_source};
|
||||||
|
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
pub use dyn_any::StaticType;
|
pub use dyn_any::StaticType;
|
||||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||||
@@ -19,7 +23,6 @@ use graphic_types::{Artboard, Graphic, Vector};
|
|||||||
use rendering::RenderMetadata;
|
use rendering::RenderMetadata;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::marker::PhantomData;
|
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
pub use std::sync::Arc;
|
pub use std::sync::Arc;
|
||||||
use text_nodes::Font;
|
use text_nodes::Font;
|
||||||
@@ -90,7 +93,7 @@ macro_rules! tagged_value {
|
|||||||
DocumentNode(DocumentNode),
|
DocumentNode(DocumentNode),
|
||||||
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
|
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
ContextFeatures(ContextFeatures),
|
ContextModification(ContextModification),
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
EditorApi(Arc<PlatformEditorApi>),
|
EditorApi(Arc<PlatformEditorApi>),
|
||||||
/// Only used by the `resource` node, should never be serialized
|
/// Only used by the `resource` node, should never be serialized
|
||||||
@@ -120,7 +123,7 @@ macro_rules! tagged_value {
|
|||||||
// =======================
|
// =======================
|
||||||
Self::NodeIdPath(path) => path.hash(state),
|
Self::NodeIdPath(path) => path.hash(state),
|
||||||
Self::DocumentNode(node) => node.cache_hash(state),
|
Self::DocumentNode(node) => node.cache_hash(state),
|
||||||
Self::ContextFeatures(features) => features.cache_hash(state),
|
Self::ContextModification(modification) => modification.cache_hash(state),
|
||||||
Self::RenderOutput(x) => x.cache_hash(state),
|
Self::RenderOutput(x) => x.cache_hash(state),
|
||||||
Self::EditorApi(x) => x.cache_hash(state),
|
Self::EditorApi(x) => x.cache_hash(state),
|
||||||
Self::ResourceHash(x) => x.cache_hash(state),
|
Self::ResourceHash(x) => x.cache_hash(state),
|
||||||
@@ -143,7 +146,7 @@ macro_rules! tagged_value {
|
|||||||
let name = td.name.as_ref();
|
let name = td.name.as_ref();
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); }
|
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Box::new(<$type_default>::default()); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
for_each_type_default!(check);
|
for_each_type_default!(check);
|
||||||
@@ -170,12 +173,9 @@ macro_rules! tagged_value {
|
|||||||
// NON-SERIALIZED VARIANTS
|
// NON-SERIALIZED VARIANTS
|
||||||
// =======================
|
// =======================
|
||||||
Self::RenderOutput(x) => Box::new(x),
|
Self::RenderOutput(x) => Box::new(x),
|
||||||
Self::NodeIdPath(path) => {
|
Self::NodeIdPath(path) => Box::new(path),
|
||||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
|
||||||
Box::new(list)
|
|
||||||
}
|
|
||||||
Self::DocumentNode(node) => Box::new(node),
|
Self::DocumentNode(node) => Box::new(node),
|
||||||
Self::ContextFeatures(features) => Box::new(features),
|
Self::ContextModification(modification) => Box::new(modification),
|
||||||
Self::EditorApi(x) => Box::new(x),
|
Self::EditorApi(x) => Box::new(x),
|
||||||
Self::ResourceHash(x) => Box::new(x),
|
Self::ResourceHash(x) => Box::new(x),
|
||||||
}
|
}
|
||||||
@@ -193,7 +193,7 @@ macro_rules! tagged_value {
|
|||||||
let name = td.name.as_ref();
|
let name = td.name.as_ref();
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); }
|
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Arc::new(<$type_default>::default()); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
for_each_type_default!(check);
|
for_each_type_default!(check);
|
||||||
@@ -220,12 +220,9 @@ macro_rules! tagged_value {
|
|||||||
// NON-SERIALIZED VARIANTS
|
// NON-SERIALIZED VARIANTS
|
||||||
// =======================
|
// =======================
|
||||||
Self::RenderOutput(x) => Arc::new(x),
|
Self::RenderOutput(x) => Arc::new(x),
|
||||||
Self::NodeIdPath(path) => {
|
Self::NodeIdPath(path) => Arc::new(path),
|
||||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
|
||||||
Arc::new(list)
|
|
||||||
}
|
|
||||||
Self::DocumentNode(node) => Arc::new(node),
|
Self::DocumentNode(node) => Arc::new(node),
|
||||||
Self::ContextFeatures(features) => Arc::new(features),
|
Self::ContextModification(modification) => Arc::new(modification),
|
||||||
Self::EditorApi(x) => Arc::new(x),
|
Self::EditorApi(x) => Arc::new(x),
|
||||||
Self::ResourceHash(x) => Arc::new(x),
|
Self::ResourceHash(x) => Arc::new(x),
|
||||||
}
|
}
|
||||||
@@ -238,11 +235,21 @@ macro_rules! tagged_value {
|
|||||||
// MANUAL VARIANTS
|
// MANUAL VARIANTS
|
||||||
// ===============
|
// ===============
|
||||||
Self::None => concrete!(()),
|
Self::None => concrete!(()),
|
||||||
Self::TypeDefault(td) => Type::Concrete(td.clone()),
|
// The list-typed defaults type by their element: depth is not a
|
||||||
Self::F64Array(_) => concrete!(List<f64>),
|
// `Type` axis, it rides the layout proven at wiring.
|
||||||
Self::Color(_) => concrete!(List<Color>),
|
Self::TypeDefault(td) => {
|
||||||
Self::Gradient(_) => concrete!(List<GradientStops>),
|
let name = td.name.as_ref();
|
||||||
Self::BrushStrokes(_) => concrete!(List<BrushStroke>),
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return concrete!(Graphic); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return concrete!(Artboard); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) { return concrete!(Raster<CPU>); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return concrete!(Vector); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<String>>()) { return concrete!(String); }
|
||||||
|
Type::Concrete(td.clone())
|
||||||
|
}
|
||||||
|
Self::F64Array(_) => concrete!(f64),
|
||||||
|
Self::Color(_) => concrete!(Color),
|
||||||
|
Self::Gradient(_) => concrete!(GradientStops),
|
||||||
|
Self::BrushStrokes(_) => concrete!(BrushStroke),
|
||||||
// =======================
|
// =======================
|
||||||
// AUTO-GENERATED VARIANTS
|
// AUTO-GENERATED VARIANTS
|
||||||
// =======================
|
// =======================
|
||||||
@@ -251,14 +258,133 @@ macro_rules! tagged_value {
|
|||||||
// NON-SERIALIZED VARIANTS
|
// NON-SERIALIZED VARIANTS
|
||||||
// =======================
|
// =======================
|
||||||
Self::RenderOutput(_) => concrete!(RenderOutput),
|
Self::RenderOutput(_) => concrete!(RenderOutput),
|
||||||
Self::NodeIdPath(_) => concrete!(List<NodeId>),
|
Self::NodeIdPath(_) => concrete!(Vec<NodeId>),
|
||||||
Self::DocumentNode(_) => concrete!(DocumentNode),
|
Self::DocumentNode(_) => concrete!(DocumentNode),
|
||||||
Self::ContextFeatures(_) => concrete!(ContextFeatures),
|
Self::ContextModification(_) => concrete!(ContextModification),
|
||||||
Self::EditorApi(_) => concrete!(&PlatformEditorApi),
|
Self::EditorApi(_) => concrete!(Arc<PlatformEditorApi>),
|
||||||
Self::ResourceHash(_) => concrete!(ResourceHash),
|
Self::ResourceHash(_) => concrete!(ResourceHash),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The record layout of this value's source: leveled for the list-carrying
|
||||||
|
/// variants, element-only at rank 0 otherwise. `None` for a
|
||||||
|
/// [`Self::TypeDefault`] whose named type is outside `for_each_type_default!`.
|
||||||
|
pub fn value_layout(&self) -> Option<core_types::record::Layout> {
|
||||||
|
fn leveled<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>() -> Option<core_types::record::Layout>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
Some(core_types::record::Layout::default().with_writes(1, core_types::record::element_write_hashed::<T>(), &[]))
|
||||||
|
}
|
||||||
|
fn scalar<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Option<core_types::record::Layout>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
Some(core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[]))
|
||||||
|
}
|
||||||
|
match self {
|
||||||
|
Self::None => scalar::<()>(),
|
||||||
|
Self::TypeDefault(td) => {
|
||||||
|
let name = td.name.as_ref();
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return leveled::<Graphic>(); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return leveled::<Artboard>(); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) { return leveled::<Raster<CPU>>(); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return leveled::<Vector>(); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<String>>()) { return leveled::<String>(); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return scalar::<DocumentNode>(); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return scalar::<Resource>(); }
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Self::F64Array(_) => leveled::<f64>(),
|
||||||
|
Self::Color(_) => leveled::<Color>(),
|
||||||
|
Self::Gradient(_) => leveled::<GradientStops>(),
|
||||||
|
Self::BrushStrokes(_) => leveled::<BrushStroke>(),
|
||||||
|
$( Self::$identifier(_) => scalar::<$ty>(), )*
|
||||||
|
Self::RenderOutput(_) => scalar::<RenderOutput>(),
|
||||||
|
Self::NodeIdPath(_) => scalar::<Vec<NodeId>>(),
|
||||||
|
Self::DocumentNode(_) => scalar::<DocumentNode>(),
|
||||||
|
Self::ContextModification(_) => scalar::<ContextModification>(),
|
||||||
|
Self::EditorApi(_) => scalar::<Arc<PlatformEditorApi>>(),
|
||||||
|
Self::ResourceHash(_) => scalar::<ResourceHash>(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value source typed by [`Self::ty`].
|
||||||
|
pub fn to_edge(self) -> Result<SourceHandle, String> {
|
||||||
|
match self {
|
||||||
|
// ===============
|
||||||
|
// MANUAL VARIANTS
|
||||||
|
// ===============
|
||||||
|
Self::None => Ok(record_value_source(())),
|
||||||
|
Self::TypeDefault(td) => {
|
||||||
|
let name = td.name.as_ref();
|
||||||
|
// The list-typed defaults serve an empty level; the rest construct
|
||||||
|
// their default directly, mirroring `to_dynany`'s recursion guard.
|
||||||
|
macro_rules! check_level {
|
||||||
|
($list:ty, $element:ty) => {
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<$list>()) {
|
||||||
|
return Ok(leveled_record_value_source(Vec::<$element>::new()));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
check_level!(List<Graphic>, Graphic);
|
||||||
|
check_level!(List<Artboard>, Artboard);
|
||||||
|
check_level!(List<Raster<CPU>>, Raster<CPU>);
|
||||||
|
// One default lane rather than an empty level: an unwired path input
|
||||||
|
// starts from a blank vector, as the legacy path modify synthesized itself.
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_source(vec![Vector::default()])); }
|
||||||
|
check_level!(List<String>, String);
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_source(DocumentNode::default())); }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_source(Resource::default())); }
|
||||||
|
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||||
|
}
|
||||||
|
Self::F64Array(values) => Ok(leveled_record_value_source(values)),
|
||||||
|
Self::Color(color) => Ok(leveled_record_value_source(color.into_iter().collect::<Vec<_>>())),
|
||||||
|
Self::Gradient(stops) => Ok(leveled_record_value_source(vec![stops])),
|
||||||
|
Self::BrushStrokes(strokes) => Ok(leveled_record_value_source(strokes)),
|
||||||
|
// =======================
|
||||||
|
// AUTO-GENERATED VARIANTS
|
||||||
|
// =======================
|
||||||
|
$( Self::$identifier(x) => Ok(record_value_source(x)), )*
|
||||||
|
// =======================
|
||||||
|
// NON-SERIALIZED VARIANTS
|
||||||
|
// =======================
|
||||||
|
Self::RenderOutput(x) => Ok(record_value_source(x)),
|
||||||
|
Self::NodeIdPath(path) => Ok(record_value_source(path)),
|
||||||
|
Self::DocumentNode(node) => Ok(record_value_source(node)),
|
||||||
|
Self::ContextModification(modification) => Ok(record_value_source(modification)),
|
||||||
|
Self::EditorApi(x) => Ok(record_value_source(x)),
|
||||||
|
Self::ResourceHash(x) => Ok(record_value_source(x)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates a typed source and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||||
|
pub fn from_edge<'f>(handle: SourceHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||||
|
let ty = handle.ty().clone();
|
||||||
|
// =======================
|
||||||
|
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||||
|
// =======================
|
||||||
|
if ty == core_types::registry::record_source_type::<()>() {
|
||||||
|
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
||||||
|
return Ok(core_types::record::serve_input(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||||
|
}
|
||||||
|
$(
|
||||||
|
if ty == core_types::registry::record_source_type::<$ty>() {
|
||||||
|
let layout = handle.layout().clone();
|
||||||
|
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
||||||
|
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||||
|
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||||
|
}
|
||||||
|
)*
|
||||||
|
if ty == core_types::registry::record_source_type::<RenderOutput>() {
|
||||||
|
let layout = handle.layout().clone();
|
||||||
|
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
||||||
|
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||||
|
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
|
||||||
|
}
|
||||||
|
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Attempts to downcast the dynamic type to a tagged value
|
/// Attempts to downcast the dynamic type to a tagged value
|
||||||
pub fn try_from_any(input: Box<dyn DynAny<'a> + 'a>) -> Result<Self, String> {
|
pub fn try_from_any(input: Box<dyn DynAny<'a> + 'a>) -> Result<Self, String> {
|
||||||
use dyn_any::downcast;
|
use dyn_any::downcast;
|
||||||
@@ -309,21 +435,31 @@ macro_rules! tagged_value {
|
|||||||
pub fn from_type(input: &Type) -> Option<Self> {
|
pub fn from_type(input: &Type) -> Option<Self> {
|
||||||
match input {
|
match input {
|
||||||
Type::Generic(_) => None,
|
Type::Generic(_) => None,
|
||||||
|
Type::Record(inner) => Self::from_type(inner),
|
||||||
Type::Concrete(concrete_type) => {
|
Type::Concrete(concrete_type) => {
|
||||||
let name = concrete_type.name.as_ref();
|
let name = concrete_type.name.as_ref();
|
||||||
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
|
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
|
||||||
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
|
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
|
||||||
if name == std::any::type_name::<()>() { return Some(TaggedValue::None) }
|
if name == core_types::normalize_type_name(std::any::type_name::<()>()) { return Some(TaggedValue::None) }
|
||||||
// List-wrapped types need a single-item default with the element's default, not an empty list
|
// List-wrapped types need a single-item default with the element's default, not an empty list
|
||||||
if name == std::any::type_name::<List<Color>>() { return Some(TaggedValue::Color(Some(Color::default()))) }
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Color>>()) { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||||
if name == std::any::type_name::<List<GradientStops>>() { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
if name == core_types::normalize_type_name(std::any::type_name::<List<GradientStops>>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||||
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
|
$( if name == core_types::normalize_type_name(std::any::type_name::<$ty>()) { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||||
if name == std::any::type_name::<List<f64>>() { return Some(TaggedValue::F64Array(Vec::new())) }
|
if name == core_types::normalize_type_name(std::any::type_name::<List<f64>>()) { return Some(TaggedValue::F64Array(Vec::new())) }
|
||||||
if name == std::any::type_name::<List<BrushStroke>>() { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
if name == core_types::normalize_type_name(std::any::type_name::<List<BrushStroke>>()) { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||||
|
// Leveled inputs type by their element; each element name maps to the
|
||||||
|
// same tagged default as its legacy list form.
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Color>()) { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<GradientStops>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<BrushStroke>()) { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Graphic>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>))) }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Artboard>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>))) }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Raster<CPU>>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))) }
|
||||||
|
if name == core_types::normalize_type_name(std::any::type_name::<Vector>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))) }
|
||||||
// Types whose `TaggedValue` variant has been removed. They route through `TypeDefault` instead, with `to_dynany`/`to_any` constructing the actual default at execution time.
|
// Types whose `TaggedValue` variant has been removed. They route through `TypeDefault` instead, with `to_dynany`/`to_any` constructing the actual default at execution time.
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
|
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
for_each_type_default!(check);
|
for_each_type_default!(check);
|
||||||
@@ -359,7 +495,7 @@ macro_rules! tagged_value {
|
|||||||
Self::RenderOutput(_) => "RenderOutput".to_string(),
|
Self::RenderOutput(_) => "RenderOutput".to_string(),
|
||||||
Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"),
|
Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"),
|
||||||
Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
|
Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
|
||||||
Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"),
|
Self::ContextModification(modification) => format!("ContextModification({modification:?})"),
|
||||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||||
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
||||||
}
|
}
|
||||||
@@ -569,6 +705,8 @@ impl TaggedValue {
|
|||||||
|
|
||||||
match ty {
|
match ty {
|
||||||
Type::Generic(_) => None,
|
Type::Generic(_) => None,
|
||||||
|
// A leveled input's default is its element's default, as in `from_type`.
|
||||||
|
Type::Record(inner) => TaggedValue::from_primitive_string(string, inner),
|
||||||
Type::Concrete(concrete_type) => {
|
Type::Concrete(concrete_type) => {
|
||||||
let ty = concrete_type.id?;
|
let ty = concrete_type.id?;
|
||||||
use std::any::TypeId;
|
use std::any::TypeId;
|
||||||
@@ -684,39 +822,6 @@ impl Display for TaggedValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct UpcastNode {
|
|
||||||
value: MemoHash<TaggedValue>,
|
|
||||||
}
|
|
||||||
impl<'input> Node<'input, DAny<'input>> for UpcastNode {
|
|
||||||
type Output = FutureAny<'input>;
|
|
||||||
|
|
||||||
fn eval(&'input self, _: DAny<'input>) -> Self::Output {
|
|
||||||
let memo_clone = MemoHash::clone(&self.value);
|
|
||||||
Box::pin(async move { memo_clone.into_inner().as_ref().clone().to_dynany() })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl UpcastNode {
|
|
||||||
pub fn new(value: MemoHash<TaggedValue>) -> Self {
|
|
||||||
Self { value }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Default, Debug, Clone, Copy)]
|
|
||||||
pub struct UpcastAsRefNode<T: AsRef<U> + Sync + Send, U: Sync + Send>(pub T, PhantomData<U>);
|
|
||||||
|
|
||||||
impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<'i, DAny<'i>> for UpcastAsRefNode<T, U> {
|
|
||||||
type Output = FutureAny<'i>;
|
|
||||||
#[inline(always)]
|
|
||||||
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
|
|
||||||
Box::pin(async move { Box::new(self.0.as_ref()) as DAny<'i> })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: AsRef<U> + Sync + Send, U: Sync + Send> UpcastAsRefNode<T, U> {
|
|
||||||
pub const fn new(value: T) -> UpcastAsRefNode<T, U> {
|
|
||||||
UpcastAsRefNode(value, PhantomData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct RenderOutput {
|
pub struct RenderOutput {
|
||||||
pub data: RenderOutputType,
|
pub data: RenderOutputType,
|
||||||
@@ -794,7 +899,7 @@ mod typedefault_dispatch {
|
|||||||
DynAny::type_id(&*dyn_value),
|
DynAny::type_id(&*dyn_value),
|
||||||
expected_type_id,
|
expected_type_id,
|
||||||
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — `for_each_type_default!` lists this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
|
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — `for_each_type_default!` lists this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
|
||||||
std::any::type_name::<$type_default>(),
|
core_types::normalize_type_name(std::any::type_name::<$type_default>()),
|
||||||
);
|
);
|
||||||
|
|
||||||
let arc_value = TaggedValue::TypeDefault(descriptor).to_any();
|
let arc_value = TaggedValue::TypeDefault(descriptor).to_any();
|
||||||
@@ -802,10 +907,69 @@ mod typedefault_dispatch {
|
|||||||
(*arc_value).type_id(),
|
(*arc_value).type_id(),
|
||||||
expected_type_id,
|
expected_type_id,
|
||||||
"`to_any(TypeDefault({0}))` did not produce a `{0}` — same recursion hazard as above for the `to_any` path.",
|
"`to_any(TypeDefault({0}))` did not produce a `{0}` — same recursion hazard as above for the `to_any` path.",
|
||||||
std::any::type_name::<$type_default>(),
|
core_types::normalize_type_name(std::any::type_name::<$type_default>()),
|
||||||
);
|
);
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
for_each_type_default!(check);
|
for_each_type_default!(check);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod leveled_edges {
|
||||||
|
use super::*;
|
||||||
|
use core_types::descriptor;
|
||||||
|
use core_types::registry::record_source_type;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn list_variants_produce_leveled_edges_typed_by_element() {
|
||||||
|
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
|
||||||
|
assert_eq!(edge.ty(), &record_source_type::<f64>());
|
||||||
|
assert_eq!(edge.layout().depth, 1);
|
||||||
|
|
||||||
|
let edge = TaggedValue::Color(Some(Color::default())).to_edge().unwrap();
|
||||||
|
assert_eq!(edge.ty(), &record_source_type::<Color>());
|
||||||
|
assert_eq!(edge.layout().depth, 1);
|
||||||
|
|
||||||
|
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
||||||
|
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
|
||||||
|
assert_eq!(edge.layout().depth, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scalar_variants_keep_their_rank_zero_edges() {
|
||||||
|
let edge = TaggedValue::Bool(true).to_edge().unwrap();
|
||||||
|
assert_eq!(edge.ty(), &record_source_type::<bool>());
|
||||||
|
assert_eq!(edge.layout().depth, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_value_layout_matches_the_edge_layout() {
|
||||||
|
for value in [
|
||||||
|
TaggedValue::F64Array(vec![1.]),
|
||||||
|
TaggedValue::Bool(true),
|
||||||
|
TaggedValue::TypeDefault(descriptor!(List<Vector>)),
|
||||||
|
TaggedValue::Gradient(Default::default()),
|
||||||
|
] {
|
||||||
|
let layout = value.value_layout().unwrap();
|
||||||
|
let edge = value.to_edge().unwrap();
|
||||||
|
assert_eq!(&layout, edge.layout());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod record_defaults {
|
||||||
|
use super::*;
|
||||||
|
use core_types::registry::record_source_type;
|
||||||
|
|
||||||
|
// The registry can present a record row first (wasm registration order),
|
||||||
|
// so primitive defaults must parse through the record wrapping.
|
||||||
|
#[test]
|
||||||
|
fn primitive_defaults_parse_through_record_wires() {
|
||||||
|
let leveled = core_types::registry::record_type::<f64>();
|
||||||
|
assert_eq!(TaggedValue::from_primitive_string("2.", &leveled), Some(TaggedValue::F64(2.)));
|
||||||
|
assert_eq!(TaggedValue::from_primitive_string("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||||
|
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
use crate::document::NodeNetwork;
|
use crate::document::NodeNetwork;
|
||||||
use crate::proto::{LocalFuture, ProtoNetwork};
|
use crate::proto::{ProtoNetwork, Registry};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
pub struct Compiler {}
|
pub struct Compiler {}
|
||||||
|
|
||||||
impl Compiler {
|
impl Compiler {
|
||||||
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
|
pub fn compile<'r>(&self, mut network: NodeNetwork, registry: &'r Registry) -> impl Iterator<Item = Result<ProtoNetwork, String>> + 'r {
|
||||||
network.resolve_scope_inputs();
|
network.resolve_scope_inputs();
|
||||||
network.generate_node_paths(&[]);
|
network.generate_node_paths(&[]);
|
||||||
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
|
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||||
@@ -19,13 +19,15 @@ impl Compiler {
|
|||||||
|
|
||||||
proto_networks.map(move |mut proto_network| {
|
proto_networks.map(move |mut proto_network| {
|
||||||
proto_network.insert_context_nullification_nodes()?;
|
proto_network.insert_context_nullification_nodes()?;
|
||||||
|
let _ = proto_network.resolve_types(registry);
|
||||||
|
proto_network.compute_layouts();
|
||||||
proto_network.generate_stable_node_ids();
|
proto_network.generate_stable_node_ids();
|
||||||
Ok(proto_network)
|
Ok(proto_network)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
pub fn compile_single(&self, network: NodeNetwork) -> Result<ProtoNetwork, String> {
|
pub fn compile_single(&self, network: NodeNetwork, registry: &Registry) -> Result<ProtoNetwork, String> {
|
||||||
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||||
let Some(proto_network) = self.compile(network).next() else {
|
let Some(proto_network) = self.compile(network, registry).next() else {
|
||||||
return Err("Failed to convert graph into proto graph".to_string());
|
return Err("Failed to convert graph into proto graph".to_string());
|
||||||
};
|
};
|
||||||
proto_network
|
proto_network
|
||||||
@@ -33,5 +35,5 @@ impl Compiler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub trait Executor<I, O> {
|
pub trait Executor<I, O> {
|
||||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<O, Box<dyn Error>>>;
|
fn execute(&self, input: I) -> Result<O, Box<dyn Error>>;
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,9 @@ pub struct ProtoNetwork {
|
|||||||
pub output: NodeId,
|
pub output: NodeId,
|
||||||
/// A list of nodes stored in a Vec to allow for sorting.
|
/// A list of nodes stored in a Vec to allow for sorting.
|
||||||
pub nodes: Vec<(NodeId, ProtoNode)>,
|
pub nodes: Vec<(NodeId, ProtoNode)>,
|
||||||
|
/// Peak record-stack bytes for an evaluation, folded from the resolved layouts by [`compute_layouts`](ProtoNetwork::compute_layouts).
|
||||||
|
#[serde(default)]
|
||||||
|
pub stack_need: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl core::fmt::Display for ProtoNetwork {
|
impl core::fmt::Display for ProtoNetwork {
|
||||||
@@ -124,6 +127,20 @@ impl ConstructionArgs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub(crate) struct Resolved {
|
||||||
|
pub io: Option<NodeIOTypes>,
|
||||||
|
pub layout_meta: Option<core_types::record::LayoutMeta>,
|
||||||
|
pub layout: Option<core_types::record::RecordLayout>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Resolved {
|
||||||
|
fn eq(&self, _: &Self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Eq for Resolved {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
/// A proto node is an intermediate step between the `DocumentNode` and the boxed struct that actually runs the node (found in the [`BorrowTree`]).
|
/// A proto node is an intermediate step between the `DocumentNode` and the boxed struct that actually runs the node (found in the [`BorrowTree`]).
|
||||||
/// At different stages in the compilation process, this struct will be transformed into a reduced (more restricted) form acting as a subset of its original form, but that restricted form is still valid in the earlier stage in the compilation process before it was transformed.
|
/// At different stages in the compilation process, this struct will be transformed into a reduced (more restricted) form acting as a subset of its original form, but that restricted form is still valid in the earlier stage in the compilation process before it was transformed.
|
||||||
@@ -134,6 +151,12 @@ pub struct ProtoNode {
|
|||||||
pub original_location: OriginalLocation,
|
pub original_location: OriginalLocation,
|
||||||
pub skip_deduplication: bool,
|
pub skip_deduplication: bool,
|
||||||
pub(crate) context_features: ContextDependencies,
|
pub(crate) context_features: ContextDependencies,
|
||||||
|
/// Bit `i` marks input `i` as invariant under the innermost index. Inputs at
|
||||||
|
/// position 32 and above never set a bit, so they read as varying.
|
||||||
|
#[serde(skip)]
|
||||||
|
pub(crate) lane_invariant_inputs: u32,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub(crate) resolved: Resolved,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ProtoNode {
|
impl Default for ProtoNode {
|
||||||
@@ -145,6 +168,8 @@ impl Default for ProtoNode {
|
|||||||
original_location: OriginalLocation::default(),
|
original_location: OriginalLocation::default(),
|
||||||
skip_deduplication: false,
|
skip_deduplication: false,
|
||||||
context_features: Default::default(),
|
context_features: Default::default(),
|
||||||
|
lane_invariant_inputs: 0,
|
||||||
|
resolved: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -185,6 +210,8 @@ impl ProtoNode {
|
|||||||
},
|
},
|
||||||
skip_deduplication: false,
|
skip_deduplication: false,
|
||||||
context_features: Default::default(),
|
context_features: Default::default(),
|
||||||
|
lane_invariant_inputs: 0,
|
||||||
|
resolved: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,6 +229,10 @@ impl ProtoNode {
|
|||||||
_ => panic!("tried to unwrap nodes from non node construction args \n node: {self:#?}"),
|
_ => panic!("tried to unwrap nodes from non node construction args \n node: {self:#?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn resolved_layout(&self) -> Option<&core_types::record::RecordLayout> {
|
||||||
|
self.resolved.layout.as_ref()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
@@ -227,6 +258,7 @@ impl ProtoNetwork {
|
|||||||
inputs: vec![node_id],
|
inputs: vec![node_id],
|
||||||
output: node_id,
|
output: node_id,
|
||||||
nodes: vec![(node_id, proto_node.clone())],
|
nodes: vec![(node_id, proto_node.clone())],
|
||||||
|
..Default::default()
|
||||||
};
|
};
|
||||||
(proto_network, node_id, proto_node)
|
(proto_network, node_id, proto_node)
|
||||||
}
|
}
|
||||||
@@ -258,6 +290,11 @@ impl ProtoNetwork {
|
|||||||
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
|
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
|
||||||
self.nodes[index].0 = sni;
|
self.nodes[index].0 = sni;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Equal nodes hash to one id; the copies must go, or a pass that
|
||||||
|
// rewrites one of them (like adapter splicing) leaves the others stale.
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
self.nodes.retain(|(id, _)| seen.insert(*id));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Remove
|
// TODO: Remove
|
||||||
@@ -294,6 +331,115 @@ impl ProtoNetwork {
|
|||||||
(inwards_edges, id_map)
|
(inwards_edges, id_map)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn source_ids(&self) -> Vec<SourceId> {
|
||||||
|
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve_types(&mut self, registry: &Registry) -> Result<(), String> {
|
||||||
|
self.reorder_ids()?;
|
||||||
|
for index in 0..self.nodes.len() {
|
||||||
|
let resolved = {
|
||||||
|
let node = &self.nodes[index].1;
|
||||||
|
match &node.construction_args {
|
||||||
|
ConstructionArgs::Value(value) => Resolved {
|
||||||
|
io: Some(NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(value.ty())), vec![])),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
let inputs: Vec<Type> = match &node.construction_args {
|
||||||
|
ConstructionArgs::Nodes(nodes) => nodes
|
||||||
|
.iter()
|
||||||
|
.map(|input| {
|
||||||
|
self.nodes[input.0 as usize]
|
||||||
|
.1
|
||||||
|
.resolved
|
||||||
|
.io
|
||||||
|
.as_ref()
|
||||||
|
.map(|io| io.ty())
|
||||||
|
.ok_or_else(|| format!("input {input:?} of {} is not yet typed", node.identifier.as_str()))
|
||||||
|
})
|
||||||
|
.collect::<Result<_, _>>()?,
|
||||||
|
ConstructionArgs::Inline(inline) => vec![inline.ty.clone()],
|
||||||
|
ConstructionArgs::Value(_) => unreachable!(),
|
||||||
|
};
|
||||||
|
let impls = registry.get(&node.identifier).ok_or_else(|| format!("no implementations for {}", node.identifier.as_str()))?;
|
||||||
|
let (io, entry) = resolve_entry(node, &inputs, impls).map_err(|errors| format!("{errors:?}"))?;
|
||||||
|
Resolved {
|
||||||
|
io: Some(io),
|
||||||
|
layout_meta: entry.layout_meta.clone(),
|
||||||
|
layout: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.nodes[index].1.resolved = resolved;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn compute_layouts(&mut self) {
|
||||||
|
for index in 0..self.nodes.len() {
|
||||||
|
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
|
||||||
|
let layout = {
|
||||||
|
let node = &self.nodes[index].1;
|
||||||
|
match &node.construction_args {
|
||||||
|
ConstructionArgs::Value(value) => value.value_layout().map(|layout| core_types::record::RecordLayout {
|
||||||
|
frame_bytes: layout.frame_bytes(),
|
||||||
|
plan: Vec::new(),
|
||||||
|
lane_invariant,
|
||||||
|
layout,
|
||||||
|
}),
|
||||||
|
ConstructionArgs::Nodes(inputs) => node.resolved.layout_meta.as_ref().and_then(|meta| {
|
||||||
|
let input_layouts: Vec<Option<&core_types::record::Layout>> = inputs
|
||||||
|
.iter()
|
||||||
|
.map(|input| self.nodes[input.0 as usize].1.resolved.layout.as_ref().map(|resolved| &resolved.layout))
|
||||||
|
.collect();
|
||||||
|
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| core_types::record::RecordLayout {
|
||||||
|
lane_invariant,
|
||||||
|
..meta.resolve(&input_layouts)
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
ConstructionArgs::Inline(_) => None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Set GRAPHENE_LAYOUT_DEBUG to dump each node's resolved record depth.
|
||||||
|
if let Some(resolved) = &layout
|
||||||
|
&& std::env::var("GRAPHENE_LAYOUT_DEBUG").is_ok()
|
||||||
|
{
|
||||||
|
eprintln!("layout {} depth {}", self.nodes[index].1.identifier, resolved.layout.depth);
|
||||||
|
}
|
||||||
|
self.nodes[index].1.resolved.layout = layout;
|
||||||
|
}
|
||||||
|
self.stack_need = self.fold_stack_peak();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Peak record-stack bytes for evaluating [`output`](Self::output)'s cone. A node holds its
|
||||||
|
/// inputs' frames until it returns, so its need is its own frame plus every input's frame plus
|
||||||
|
/// the deepest input's peak. Memoized over shared cones. Runs while node IDs are still indices.
|
||||||
|
fn fold_stack_peak(&self) -> usize {
|
||||||
|
fn peak(index: usize, network: &ProtoNetwork, memo: &mut [Option<usize>]) -> usize {
|
||||||
|
if let Some(cached) = memo[index] {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
let frame = |i: usize| network.nodes[i].1.resolved.layout.as_ref().map_or(0, |resolved| resolved.frame_bytes);
|
||||||
|
let mut held = 0;
|
||||||
|
let mut deepest = 0;
|
||||||
|
if let ConstructionArgs::Nodes(inputs) = &network.nodes[index].1.construction_args {
|
||||||
|
for input in inputs {
|
||||||
|
let child = input.0 as usize;
|
||||||
|
let child_frame = frame(child);
|
||||||
|
held += child_frame;
|
||||||
|
deepest = deepest.max(peak(child, network, memo).saturating_sub(child_frame));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let need = frame(index) + held + deepest;
|
||||||
|
memo[index] = Some(need);
|
||||||
|
need
|
||||||
|
}
|
||||||
|
let mut memo = vec![None; self.nodes.len()];
|
||||||
|
peak(self.output.0 as usize, self, &mut memo)
|
||||||
|
}
|
||||||
|
|
||||||
/// Inserts context nullification nodes to optimize caching.
|
/// Inserts context nullification nodes to optimize caching.
|
||||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||||
@@ -308,7 +454,7 @@ impl ProtoNetwork {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId {
|
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
|
||||||
let (_, node) = &self.nodes[node_id.0 as usize];
|
let (_, node) = &self.nodes[node_id.0 as usize];
|
||||||
let mut path = node.original_location.path.clone();
|
let mut path = node.original_location.path.clone();
|
||||||
|
|
||||||
@@ -324,7 +470,7 @@ impl ProtoNetwork {
|
|||||||
ProtoNode {
|
ProtoNode {
|
||||||
construction_args: ConstructionArgs::Nodes(vec![node_id]),
|
construction_args: ConstructionArgs::Nodes(vec![node_id]),
|
||||||
call_argument: concrete!(Context),
|
call_argument: concrete!(Context),
|
||||||
identifier: graphene_core::memo::memoize::IDENTIFIER,
|
identifier: graphene_core::memo::frame_memo::IDENTIFIER,
|
||||||
original_location: OriginalLocation {
|
original_location: OriginalLocation {
|
||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -338,7 +484,7 @@ impl ProtoNetwork {
|
|||||||
self.nodes.push((
|
self.nodes.push((
|
||||||
nullification_value_node_id,
|
nullification_value_node_id,
|
||||||
ProtoNode {
|
ProtoNode {
|
||||||
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))),
|
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextModification(context_deps))),
|
||||||
call_argument: concrete!(Context),
|
call_argument: concrete!(Context),
|
||||||
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
|
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
|
||||||
original_location: OriginalLocation {
|
original_location: OriginalLocation {
|
||||||
@@ -365,39 +511,90 @@ impl ProtoNetwork {
|
|||||||
nullification_node_id
|
nullification_node_id
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option<NodeId>) {
|
/// The node's declared dependencies and per-input pushed levels, both read
|
||||||
|
/// from the registry since they follow the node's signature. A node with no
|
||||||
|
/// registry entry declares nothing and pushes nothing.
|
||||||
|
fn registry_dependencies(&self, node_index: usize) -> (ContextDependencies, Vec<u8>) {
|
||||||
|
let identifier = &self.nodes[node_index].1.identifier;
|
||||||
|
let metadata = core_types::registry::NODE_METADATA.lock().unwrap();
|
||||||
|
match metadata.get(identifier) {
|
||||||
|
Some(entry) => (
|
||||||
|
ContextDependencies::from(entry.context_features.as_slice()),
|
||||||
|
entry.fields.iter().map(|field| field.pushed_levels).collect(),
|
||||||
|
),
|
||||||
|
None => (ContextDependencies::default(), Vec::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
|
||||||
let mut branch_dependencies = Vec::new();
|
let mut branch_dependencies = Vec::new();
|
||||||
let mut combined_deps = ContextFeatures::default();
|
let mut combined_deps = ContextModification::default();
|
||||||
let node_index = id.0 as usize;
|
let node_index = id.0 as usize;
|
||||||
|
|
||||||
let context_features = self.nodes[node_index].1.context_features;
|
let (registry_deps, pushed_levels) = self.registry_dependencies(node_index);
|
||||||
|
let (extract, inject, own_deps) = {
|
||||||
|
let carried = &self.nodes[node_index].1.context_features;
|
||||||
|
// A code-built wrapper node declares dependencies its signature cannot
|
||||||
|
// express; everything else resolves from the registry. Sources are
|
||||||
|
// input wiring, not declarations, so they merge either way.
|
||||||
|
let mut dependencies = match carried.extract.is_empty() && carried.inject.is_empty() {
|
||||||
|
false => carried.clone(),
|
||||||
|
true => registry_deps,
|
||||||
|
};
|
||||||
|
dependencies.add_sources(carried.sources());
|
||||||
|
let index_levels = match dependencies.extract.contains(core_types::context::ContextFeatures::INDEX) {
|
||||||
|
// A hand-declared `INDEX` names no level and addresses the innermost.
|
||||||
|
true if dependencies.index_levels.is_empty() => core_types::context::IndexLevels::innermost(),
|
||||||
|
true => dependencies.index_levels,
|
||||||
|
false => core_types::context::IndexLevels::empty(),
|
||||||
|
};
|
||||||
|
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources()).with_index_levels(index_levels);
|
||||||
|
(dependencies.extract, dependencies.inject, own_deps)
|
||||||
|
};
|
||||||
|
|
||||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||||
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
||||||
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
|
ConstructionArgs::Value(value) => {
|
||||||
|
let mut deps = own_deps;
|
||||||
|
// A leveled value serves its lanes by the innermost index.
|
||||||
|
if value.value_layout().is_some_and(|layout| layout.depth > 0) {
|
||||||
|
deps |= core_types::context::ContextFeatures::INDEX;
|
||||||
|
deps.index_levels |= core_types::context::IndexLevels::innermost();
|
||||||
|
}
|
||||||
|
return (deps, Some(id));
|
||||||
|
}
|
||||||
ConstructionArgs::Nodes(items) => items.clone(),
|
ConstructionArgs::Nodes(items) => items.clone(),
|
||||||
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
|
ConstructionArgs::Inline(_) => return (own_deps, Some(id)),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Compute the dependencies for each branch and combine all of them
|
// Compute the dependencies for each branch and combine all of them
|
||||||
for &node in &inputs {
|
let mut lane_invariant_inputs = 0u32;
|
||||||
|
for (input, &node) in inputs.iter().enumerate() {
|
||||||
let branch = self.find_context_dependencies(node);
|
let branch = self.find_context_dependencies(node);
|
||||||
|
|
||||||
branch_dependencies.push(branch);
|
let reads_innermost = branch.0.features.contains(core_types::context::ContextFeatures::INDEX) && branch.0.index_levels.contains_level(0);
|
||||||
combined_deps |= branch.0;
|
if !reads_innermost && input < 32 {
|
||||||
|
lane_invariant_inputs |= 1 << input;
|
||||||
}
|
}
|
||||||
let mut new_deps = combined_deps;
|
|
||||||
|
let mut lifted = branch.0.clone();
|
||||||
|
lifted.index_levels = lifted.index_levels.lifted(0, pushed_levels.get(input).copied().unwrap_or(0));
|
||||||
|
combined_deps |= &lifted;
|
||||||
|
branch_dependencies.push(branch);
|
||||||
|
}
|
||||||
|
self.nodes[node_index].1.lane_invariant_inputs = lane_invariant_inputs;
|
||||||
|
let mut new_deps = combined_deps.clone();
|
||||||
|
|
||||||
// Remove requirements which this node provides
|
// Remove requirements which this node provides
|
||||||
new_deps &= !context_features.inject;
|
new_deps &= !inject;
|
||||||
// Add requirements we have
|
// Add requirements we have
|
||||||
new_deps |= context_features.extract;
|
new_deps |= own_deps;
|
||||||
|
|
||||||
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
|
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
|
||||||
let we_introduce_new_deps = !combined_deps.contains(new_deps);
|
let we_introduce_new_deps = !combined_deps.contains(&new_deps);
|
||||||
|
|
||||||
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
|
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
|
||||||
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
|
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
|
||||||
if let Some(new_id) = new_id {
|
if let Some(new_id) = new_id {
|
||||||
*child_node = new_id;
|
*child_node = new_id;
|
||||||
} else if we_introduce_new_deps || deps != combined_deps {
|
} else if we_introduce_new_deps || deps != combined_deps {
|
||||||
@@ -407,18 +604,21 @@ impl ProtoNetwork {
|
|||||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||||
|
|
||||||
// Which dependencies do we supply (and don't need ourselves)?
|
// Which dependencies do we supply (and don't need ourselves)?
|
||||||
let net_injections = context_features.inject.difference(context_features.extract);
|
// TODO: a shrinking index-level mask does not count as supplying a
|
||||||
|
// dependency, so a fold that consumes its subtree's only level inserts
|
||||||
|
// no boundary here.
|
||||||
|
let net_injections = inject.difference(extract);
|
||||||
|
|
||||||
// Which dependencies still need to be met after this node?
|
// Which dependencies still need to be met after this node?
|
||||||
let remaining_deps_from_children = combined_deps.difference(net_injections);
|
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
|
||||||
|
|
||||||
// Do we satisfy any existing dependencies?
|
// Do we satisfy any existing dependencies?
|
||||||
let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty();
|
let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
|
||||||
|
|
||||||
let mut new_id = None;
|
let mut new_id = None;
|
||||||
if we_supply_existing_deps {
|
if we_supply_existing_deps {
|
||||||
// Our set of context dependencies has shrunk so we can add a cache node after the current node
|
// Our set of context dependencies has shrunk so we can add a cache node after the current node
|
||||||
new_id = Some(self.insert_context_nullification_node(id, new_deps));
|
new_id = Some(self.insert_context_nullification_node(id, new_deps.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
(new_deps, new_id)
|
(new_deps, new_id)
|
||||||
@@ -545,6 +745,7 @@ pub enum GraphErrorType {
|
|||||||
},
|
},
|
||||||
NoImplementations,
|
NoImplementations,
|
||||||
NoConstructor,
|
NoConstructor,
|
||||||
|
ConstructionFailed(String),
|
||||||
/// The `inputs` represents a formatted list of input indices corresponding to their types.
|
/// The `inputs` represents a formatted list of input indices corresponding to their types.
|
||||||
/// Each element in `error_inputs` represents a valid `NodeIOTypes` implementation.
|
/// Each element in `error_inputs` represents a valid `NodeIOTypes` implementation.
|
||||||
/// The inner Vec stores the inputs which need to be changed and what type each needs to be changed to.
|
/// The inner Vec stores the inputs which need to be changed and what type each needs to be changed to.
|
||||||
@@ -565,6 +766,7 @@ impl Debug for GraphErrorType {
|
|||||||
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
|
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
|
||||||
GraphErrorType::NoImplementations => write!(f, "No implementations found"),
|
GraphErrorType::NoImplementations => write!(f, "No implementations found"),
|
||||||
GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
|
GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
|
||||||
|
GraphErrorType::ConstructionFailed(error) => write!(f, "Construction failed: {error}"),
|
||||||
GraphErrorType::InvalidImplementations { inputs, error_inputs } => {
|
GraphErrorType::InvalidImplementations { inputs, error_inputs } => {
|
||||||
let format_error = |(index, (found, expected)): &(usize, (Type, Type))| {
|
let format_error = |(index, (found, expected)): &(usize, (Type, Type))| {
|
||||||
let index = index + 1;
|
let index = index + 1;
|
||||||
@@ -628,28 +830,34 @@ impl Debug for GraphError {
|
|||||||
}
|
}
|
||||||
pub type GraphErrors = Vec<GraphError>;
|
pub type GraphErrors = Vec<GraphError>;
|
||||||
|
|
||||||
|
pub type Registry = HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>;
|
||||||
|
|
||||||
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
|
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
|
||||||
#[derive(Default, Clone, dyn_any::DynAny)]
|
#[derive(Default, Clone, dyn_any::DynAny)]
|
||||||
pub struct TypingContext {
|
pub struct TypingContext {
|
||||||
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>>,
|
lookup: Cow<'static, Registry>,
|
||||||
inferred: HashMap<NodeId, NodeIOTypes>,
|
inferred: HashMap<NodeId, NodeIOTypes>,
|
||||||
constructor: HashMap<NodeId, NodeConstructor>,
|
constructor: HashMap<NodeId, NodeConstructor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TypingContext {
|
impl TypingContext {
|
||||||
/// Creates a new `TypingContext` with the given lookup table.
|
/// Creates a new `TypingContext` with the given lookup table.
|
||||||
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>) -> Self {
|
pub fn new(lookup: &'static Registry) -> Self {
|
||||||
Self {
|
Self {
|
||||||
lookup: Cow::Borrowed(lookup),
|
lookup: Cow::Borrowed(lookup),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn registry(&self) -> &Registry {
|
||||||
|
&self.lookup
|
||||||
|
}
|
||||||
|
|
||||||
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
|
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
|
||||||
/// and store them in the `inferred` field. The proto network has to be topologically sorted
|
/// and store them in the `inferred` field. The proto network has to be topologically sorted
|
||||||
/// and contain fully resolved stable node ids.
|
/// and contain fully resolved stable node ids.
|
||||||
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
|
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
|
||||||
for (id, node) in network.nodes.iter() {
|
for (id, node) in &network.nodes {
|
||||||
self.infer(*id, node)?;
|
self.infer(*id, node)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -679,10 +887,10 @@ impl TypingContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let inputs = match node.construction_args {
|
let inputs = match node.construction_args {
|
||||||
// If the node has a value input we can infer the return type from it
|
// A value node is a native record source, so it types as a record
|
||||||
|
// of its value.
|
||||||
ConstructionArgs::Value(ref v) => {
|
ConstructionArgs::Value(ref v) => {
|
||||||
// TODO: This should return a reference to the value
|
let types = NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(v.ty())), vec![]);
|
||||||
let types = NodeIOTypes::new(concrete!(Context), Type::Future(Box::new(v.ty())), vec![]);
|
|
||||||
self.inferred.insert(node_id, types.clone());
|
self.inferred.insert(node_id, types.clone());
|
||||||
return Ok(types);
|
return Ok(types);
|
||||||
}
|
}
|
||||||
@@ -700,65 +908,49 @@ impl TypingContext {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Get the node input type from the proto node declaration
|
// Get the node input type from the proto node declaration
|
||||||
let call_argument = &node.call_argument;
|
|
||||||
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
|
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
|
||||||
|
let (node_io, entry) = resolve_entry(node, &inputs, impls)?;
|
||||||
|
if std::env::var("GRAPHENE_TYPE_DEBUG").is_ok() {
|
||||||
|
eprintln!("type {} {} -> {}", node_id, node.identifier, node_io.ty());
|
||||||
|
}
|
||||||
|
self.inferred.insert(node_id, node_io.clone());
|
||||||
|
self.constructor.insert(node_id, entry.constructor);
|
||||||
|
Ok(node_io)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Selects the single registry entry matching the node's resolved input types,
|
||||||
|
/// substituting generics. Stateless and stable-id-free.
|
||||||
|
fn resolve_entry<'a>(node: &ProtoNode, inputs: &[Type], impls: &'a [RegistryEntry]) -> Result<(NodeIOTypes, &'a RegistryEntry), GraphErrors> {
|
||||||
|
let call_argument = &node.call_argument;
|
||||||
|
let candidates: Vec<(NodeIOTypes, &RegistryEntry)> = impls.iter().map(|entry| (entry.io.clone(), entry)).collect();
|
||||||
|
|
||||||
if let Some(index) = inputs.iter().position(|p| {
|
if let Some(index) = inputs.iter().position(|p| {
|
||||||
matches!(p,
|
matches!(p,
|
||||||
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
|
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
|
||||||
}) {
|
}) {
|
||||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
|
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs: inputs.to_vec() })]);
|
||||||
}
|
|
||||||
|
|
||||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
|
||||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
|
||||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
|
||||||
match (from, to) {
|
|
||||||
// Direct comparison of two concrete types.
|
|
||||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
|
||||||
// Check inner type for futures
|
|
||||||
(Type::Future(type1), Type::Future(type2)) => valid_type(type1, type2),
|
|
||||||
// Direct comparison of two function types.
|
|
||||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
|
||||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
|
||||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
|
||||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
|
||||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
|
||||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
|
||||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
|
||||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
|
||||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
|
||||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
|
||||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
|
||||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
|
||||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
|
||||||
// TODO: Add proper generic counting which is not based on the name
|
|
||||||
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
|
||||||
// Reject unknown type relationships.
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of all implementations that match the input types
|
// List of all implementations that match the input types
|
||||||
let valid_output_types = impls
|
let valid_output_types = candidates
|
||||||
.keys()
|
.iter()
|
||||||
.filter(|node_io| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
// Attempt to substitute generic types with concrete types and save the list of results
|
// Attempt to substitute generic types with concrete types and save the list of results
|
||||||
let substitution_results = valid_output_types
|
let substitution_results = valid_output_types
|
||||||
.iter()
|
.iter()
|
||||||
.map(|node_io| {
|
.map(|(node_io, entry)| {
|
||||||
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
||||||
.iter()
|
.iter()
|
||||||
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
|
.map(|generic| check_generic(node_io, call_argument, inputs, generic).map(|x| (generic.to_string(), x)))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
generics_lookup.map(|generics_lookup| {
|
generics_lookup.map(|generics_lookup| {
|
||||||
let orig_node_io = (*node_io).clone();
|
let mut new_node_io = node_io.clone();
|
||||||
let mut new_node_io = orig_node_io.clone();
|
|
||||||
replace_generics(&mut new_node_io, &generics_lookup);
|
replace_generics(&mut new_node_io, &generics_lookup);
|
||||||
(new_node_io, orig_node_io)
|
(new_node_io, *entry)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -771,11 +963,11 @@ impl TypingContext {
|
|||||||
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
||||||
let mut best_errors = usize::MAX;
|
let mut best_errors = usize::MAX;
|
||||||
let mut error_inputs = Vec::new();
|
let mut error_inputs = Vec::new();
|
||||||
for node_io in impls.keys() {
|
for (node_io, _) in &candidates {
|
||||||
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
||||||
let current_errors = [call_argument]
|
let current_errors = [call_argument]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(&inputs)
|
.chain(inputs)
|
||||||
.cloned()
|
.cloned()
|
||||||
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
|
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -792,7 +984,7 @@ impl TypingContext {
|
|||||||
}
|
}
|
||||||
let inputs = [call_argument]
|
let inputs = [call_argument]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(&inputs)
|
.chain(inputs)
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter_map(|(i, t)| {
|
.filter_map(|(i, t)| {
|
||||||
if i == 0 {
|
if i == 0 {
|
||||||
@@ -806,40 +998,57 @@ impl TypingContext {
|
|||||||
.join("\n");
|
.join("\n");
|
||||||
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
||||||
}
|
}
|
||||||
[(node_io, org_nio)] => {
|
[(node_io, entry)] => Ok((node_io.clone(), *entry)),
|
||||||
let node_io = node_io.clone();
|
|
||||||
|
|
||||||
// Save the inferred type
|
|
||||||
self.inferred.insert(node_id, node_io.clone());
|
|
||||||
self.constructor.insert(node_id, impls[org_nio]);
|
|
||||||
Ok(node_io)
|
|
||||||
}
|
|
||||||
// If two types are available and one of them accepts () an input, always choose that one
|
// If two types are available and one of them accepts () an input, always choose that one
|
||||||
[first, second] => {
|
[first, second] => {
|
||||||
if first.0.call_argument != second.0.call_argument {
|
if first.0.call_argument != second.0.call_argument {
|
||||||
for (node_io, orig_nio) in [first, second] {
|
for (node_io, entry) in [first, second] {
|
||||||
if node_io.call_argument != concrete!(()) {
|
if node_io.call_argument != concrete!(()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
return Ok((node_io.clone(), *entry));
|
||||||
// Save the inferred type
|
|
||||||
self.inferred.insert(node_id, node_io.clone());
|
|
||||||
self.constructor.insert(node_id, impls[orig_nio]);
|
|
||||||
return Ok(node_io.clone());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||||
let valid = valid_output_types.into_iter().cloned().collect();
|
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => {
|
_ => {
|
||||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||||
let valid = valid_output_types.into_iter().cloned().collect();
|
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||||
|
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||||
|
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||||
|
match (from, to) {
|
||||||
|
// Direct comparison of two concrete types.
|
||||||
|
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||||
|
// Direct comparison of two function types.
|
||||||
|
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||||
|
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||||
|
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||||
|
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||||
|
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||||
|
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||||
|
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||||
|
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||||
|
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||||
|
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||||
|
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||||
|
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||||
|
// A record input is substitutable exactly when the elements are.
|
||||||
|
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
||||||
|
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||||
|
// TODO: Add proper generic counting which is not based on the name
|
||||||
|
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
||||||
|
// Reject unknown type relationships.
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a list of all generic types used in the node
|
/// Returns a list of all generic types used in the node
|
||||||
@@ -860,10 +1069,17 @@ fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
|
|||||||
|
|
||||||
/// Checks if a generic type can be substituted with a concrete type and returns the concrete type
|
/// Checks if a generic type can be substituted with a concrete type and returns the concrete type
|
||||||
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
|
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
|
||||||
|
fn record_element(ty: Option<&Type>) -> Option<&Type> {
|
||||||
|
match ty {
|
||||||
|
Some(Type::Record(inner)) => Some(inner.as_ref()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
let inputs = [(Some(&types.call_argument), Some(input))]
|
let inputs = [(Some(&types.call_argument), Some(input))]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
|
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
|
||||||
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())));
|
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())))
|
||||||
|
.chain(types.inputs.iter().map(|x| record_element(x.fn_output())).zip(parameters.iter().map(|x| record_element(x.fn_output()))));
|
||||||
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
|
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
|
||||||
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
|
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
|
||||||
let out_ty = outputs
|
let out_ty = outputs
|
||||||
@@ -893,6 +1109,34 @@ mod test {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stack_peak_folds_a_diamond_chain() {
|
||||||
|
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs; every frame is one byte.
|
||||||
|
let node = |index: u64| {
|
||||||
|
let args = if index == 0 {
|
||||||
|
ConstructionArgs::Value(value::TaggedValue::U32(0).into())
|
||||||
|
} else {
|
||||||
|
ConstructionArgs::Nodes(vec![NodeId(index - 1), NodeId(index - 1)])
|
||||||
|
};
|
||||||
|
ProtoNode {
|
||||||
|
construction_args: args,
|
||||||
|
resolved: Resolved {
|
||||||
|
layout: Some(core_types::record::RecordLayout { frame_bytes: 1, ..Default::default() }),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut network = ProtoNetwork {
|
||||||
|
output: NodeId(3),
|
||||||
|
nodes: (0..4).map(|index| (NodeId(index), node(index))).collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(network.fold_stack_peak(), 7);
|
||||||
|
network.output = NodeId(0);
|
||||||
|
assert_eq!(network.fold_stack_peak(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn topological_sort() {
|
fn topological_sort() {
|
||||||
let construction_network = test_network();
|
let construction_network = test_network();
|
||||||
@@ -955,6 +1199,81 @@ mod test {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn retain_filter_placement_on_source_free_branch() {
|
||||||
|
let mut network = source_branch_network(vec![1], vec![]);
|
||||||
|
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||||
|
|
||||||
|
let filters = nullification_filters(&network);
|
||||||
|
assert_eq!(filters.len(), 1, "only the source-free branch gets a filter");
|
||||||
|
let (filter_id, wrapped, retained) = &filters[0];
|
||||||
|
assert_eq!(wrapped, "source_b");
|
||||||
|
assert!(retained.is_empty(), "the source-free branch retains no sources");
|
||||||
|
|
||||||
|
let (source_a_id, _) = find_node(&network, "source_a");
|
||||||
|
let (_, join) = find_node(&network, "join");
|
||||||
|
let ConstructionArgs::Nodes(join_args) = &join.construction_args else {
|
||||||
|
panic!("join args must be nodes")
|
||||||
|
};
|
||||||
|
assert_eq!(join_args, &vec![source_a_id, *filter_id], "the source branch stays direct, the filter replaces the source-free branch");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn diverging_source_sets_filter_each_branch() {
|
||||||
|
let mut network = source_branch_network(vec![1], vec![2]);
|
||||||
|
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||||
|
|
||||||
|
let mut filters = nullification_filters(&network);
|
||||||
|
filters.sort_by(|(_, a, _), (_, b, _)| a.cmp(b));
|
||||||
|
let summary: Vec<_> = filters.iter().map(|(_, wrapped, retained)| (wrapped.as_str(), retained.as_slice())).collect();
|
||||||
|
assert_eq!(
|
||||||
|
summary,
|
||||||
|
vec![("source_a", &[1u64][..]), ("source_b", &[2u64][..])],
|
||||||
|
"each diverging branch is filtered down to its own source set"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matching_source_sets_insert_no_filter() {
|
||||||
|
let mut network = source_branch_network(vec![1], vec![1]);
|
||||||
|
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||||
|
|
||||||
|
assert!(nullification_filters(&network).is_empty(), "equal branch source sets need no filter");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_node<'a>(network: &'a ProtoNetwork, name: &str) -> (NodeId, &'a ProtoNode) {
|
||||||
|
network
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.find(|(_, node)| node.identifier.as_str() == name)
|
||||||
|
.map(|(id, node)| (*id, node))
|
||||||
|
.unwrap_or_else(|| panic!("node {name} not found"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn nullification_filters(network: &ProtoNetwork) -> Vec<(NodeId, String, Vec<SourceId>)> {
|
||||||
|
let node = |id: NodeId| &network.nodes[id.0 as usize].1;
|
||||||
|
network
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, candidate)| candidate.identifier.as_str() == graphene_core::context_modification::context_modification::IDENTIFIER.as_str())
|
||||||
|
.map(|(id, candidate)| {
|
||||||
|
let ConstructionArgs::Nodes(args) = &candidate.construction_args else {
|
||||||
|
panic!("filter args must be nodes")
|
||||||
|
};
|
||||||
|
let ConstructionArgs::Nodes(memoized) = &node(args[0]).construction_args else {
|
||||||
|
panic!("filter memoize args must be nodes")
|
||||||
|
};
|
||||||
|
let ConstructionArgs::Value(value) = &node(args[1]).construction_args else {
|
||||||
|
panic!("filter payload must be a value")
|
||||||
|
};
|
||||||
|
let value::TaggedValue::ContextModification(modification) = &**value else {
|
||||||
|
panic!("filter payload must be a context modification")
|
||||||
|
};
|
||||||
|
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
fn test_network() -> ProtoNetwork {
|
fn test_network() -> ProtoNetwork {
|
||||||
ProtoNetwork {
|
ProtoNetwork {
|
||||||
inputs: vec![NodeId(10)],
|
inputs: vec![NodeId(10)],
|
||||||
@@ -1008,6 +1327,46 @@ mod test {
|
|||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect(),
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn source_branch_network(branch_a_sources: Vec<SourceId>, branch_b_sources: Vec<SourceId>) -> ProtoNetwork {
|
||||||
|
let branch = |name: &str, sources: Vec<SourceId>| ProtoNode {
|
||||||
|
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
|
||||||
|
call_argument: concrete!(()),
|
||||||
|
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
|
||||||
|
context_features: ContextDependencies::from_sources(&sources),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
ProtoNetwork {
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(3),
|
||||||
|
nodes: [
|
||||||
|
(
|
||||||
|
NodeId(0),
|
||||||
|
ProtoNode {
|
||||||
|
identifier: ProtoNodeIdentifier::new("value"),
|
||||||
|
call_argument: concrete!(()),
|
||||||
|
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(2).into()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(NodeId(1), branch("source_a", branch_a_sources)),
|
||||||
|
(NodeId(2), branch("source_b", branch_b_sources)),
|
||||||
|
(
|
||||||
|
NodeId(3),
|
||||||
|
ProtoNode {
|
||||||
|
identifier: ProtoNodeIdentifier::new("join"),
|
||||||
|
call_argument: concrete!(()),
|
||||||
|
construction_args: ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1037,6 +1396,7 @@ mod test {
|
|||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect(),
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::document::NodeNetwork;
|
use crate::document::NodeNetwork;
|
||||||
use crate::graphene_compiler::Compiler;
|
use crate::graphene_compiler::Compiler;
|
||||||
use crate::proto::ProtoNetwork;
|
use crate::proto::{ProtoNetwork, Registry};
|
||||||
|
|
||||||
pub fn load_network(document_string: &str) -> NodeNetwork {
|
pub fn load_network(document_string: &str) -> NodeNetwork {
|
||||||
let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document");
|
let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document");
|
||||||
@@ -8,9 +8,9 @@ pub fn load_network(document_string: &str) -> NodeNetwork {
|
|||||||
serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document")
|
serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn compile(network: NodeNetwork) -> ProtoNetwork {
|
pub fn compile(network: NodeNetwork, registry: &Registry) -> ProtoNetwork {
|
||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
compiler.compile_single(network).unwrap()
|
compiler.compile_single(network, registry).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_from_name(name: &str) -> NodeNetwork {
|
pub fn load_from_name(name: &str) -> NodeNetwork {
|
||||||
|
|||||||
@@ -1,15 +1,40 @@
|
|||||||
|
use futures::executor::block_on;
|
||||||
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
|
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
|
||||||
use graph_craft::graphene_compiler::Executor;
|
use graph_craft::graphene_compiler::Executor;
|
||||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||||
use graphene_std::core_types::ops::Convert;
|
use graphene_std::core_types::gpoll::GPoll;
|
||||||
|
use graphene_std::core_types::ops::ConvertAsync;
|
||||||
use graphene_std::core_types::transform::Footprint;
|
use graphene_std::core_types::transform::Footprint;
|
||||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::mpsc::Receiver;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
|
fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
|
||||||
|
loop {
|
||||||
|
while completion.try_recv().is_ok() {}
|
||||||
|
match executor.execute(render_config)? {
|
||||||
|
GPoll::Final(value) => return Ok(value),
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (value, error) = *boxed;
|
||||||
|
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||||
|
return Ok(value);
|
||||||
|
}
|
||||||
|
GPoll::Partial(_) | GPoll::Pending => {
|
||||||
|
completion
|
||||||
|
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
|
||||||
|
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
|
||||||
|
}
|
||||||
|
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum FileType {
|
pub enum FileType {
|
||||||
Svg,
|
Svg,
|
||||||
@@ -28,14 +53,16 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn export_document(
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn export_document(
|
||||||
executor: &DynamicExecutor,
|
executor: &DynamicExecutor,
|
||||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
wgpu_executor: wgpu_executor::WgpuExecutorHandle,
|
||||||
output_path: PathBuf,
|
output_path: PathBuf,
|
||||||
file_type: FileType,
|
file_type: FileType,
|
||||||
scale: f64,
|
scale: f64,
|
||||||
(width, height): (Option<u32>, Option<u32>),
|
(width, height): (Option<u32>, Option<u32>),
|
||||||
transparent: bool,
|
transparent: bool,
|
||||||
|
completion: &Receiver<()>,
|
||||||
) -> Result<(), Box<dyn Error>> {
|
) -> Result<(), Box<dyn Error>> {
|
||||||
// Determine export format based on file type
|
// Determine export format based on file type
|
||||||
let export_format = match file_type {
|
let export_format = match file_type {
|
||||||
@@ -57,7 +84,7 @@ pub async fn export_document(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Execute the graph
|
// Execute the graph
|
||||||
let result = executor.execute(render_config).await?;
|
let result = execute_until_final(executor, render_config, completion)?;
|
||||||
|
|
||||||
// Handle the result based on output type
|
// Handle the result based on output type
|
||||||
match result {
|
match result {
|
||||||
@@ -70,7 +97,7 @@ pub async fn export_document(
|
|||||||
RenderOutputType::Texture(texture) => {
|
RenderOutputType::Texture(texture) => {
|
||||||
// Convert GPU texture to CPU buffer
|
// Convert GPU texture to CPU buffer
|
||||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||||
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await;
|
let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
|
||||||
let (data, width, height) = cpu_raster.to_flat_u8();
|
let (data, width, height) = cpu_raster.to_flat_u8();
|
||||||
|
|
||||||
// Encode and write raster image
|
// Encode and write raster image
|
||||||
@@ -149,13 +176,14 @@ impl AnimationParams {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Export an animated GIF by rendering multiple frames at different animation times
|
/// Export an animated GIF by rendering multiple frames at different animation times
|
||||||
pub async fn export_gif(
|
pub fn export_gif(
|
||||||
executor: &DynamicExecutor,
|
executor: &DynamicExecutor,
|
||||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
wgpu_executor: wgpu_executor::WgpuExecutorHandle,
|
||||||
output_path: PathBuf,
|
output_path: PathBuf,
|
||||||
scale: f64,
|
scale: f64,
|
||||||
(width, height): (Option<u32>, Option<u32>),
|
(width, height): (Option<u32>, Option<u32>),
|
||||||
animation: AnimationParams,
|
animation: AnimationParams,
|
||||||
|
completion: &Receiver<()>,
|
||||||
) -> Result<(), Box<dyn Error>> {
|
) -> Result<(), Box<dyn Error>> {
|
||||||
use image::codecs::gif::{GifEncoder, Repeat};
|
use image::codecs::gif::{GifEncoder, Repeat};
|
||||||
use image::{Frame, RgbaImage};
|
use image::{Frame, RgbaImage};
|
||||||
@@ -195,14 +223,14 @@ pub async fn export_gif(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Execute the graph for this frame
|
// Execute the graph for this frame
|
||||||
let result = executor.execute(render_config).await?;
|
let result = execute_until_final(executor, render_config, completion)?;
|
||||||
|
|
||||||
// Extract RGBA data from result
|
// Extract RGBA data from result
|
||||||
let (data, img_width, img_height) = match result {
|
let (data, img_width, img_height) = match result {
|
||||||
TaggedValue::RenderOutput(output) => match output.data {
|
TaggedValue::RenderOutput(output) => match output.data {
|
||||||
RenderOutputType::Texture(texture) => {
|
RenderOutputType::Texture(texture) => {
|
||||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||||
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await;
|
let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
|
||||||
cpu_raster.to_flat_u8()
|
cpu_raster.to_flat_u8()
|
||||||
}
|
}
|
||||||
RenderOutputType::Buffer { data, width, height } => (data, width, height),
|
RenderOutputType::Buffer { data, width, height } => (data, width, height),
|
||||||
|
|||||||
@@ -7,13 +7,13 @@ use document_format::{GddV1, GddV1Layout};
|
|||||||
use fern::colors::{Color, ColoredLevelConfig};
|
use fern::colors::{Color, ColoredLevelConfig};
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
use graph_craft::application_io::EditorPreferences;
|
use graph_craft::application_io::EditorPreferences;
|
||||||
use graph_craft::application_io::resource::ResourceRegistry;
|
|
||||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||||
use graph_craft::document::*;
|
use graph_craft::document::*;
|
||||||
use graph_craft::graphene_compiler::Compiler;
|
use graph_craft::graphene_compiler::Compiler;
|
||||||
use graph_craft::proto::ProtoNetwork;
|
use graph_craft::proto::ProtoNetwork;
|
||||||
use graph_craft::util::load_network;
|
use graph_craft::util::load_network;
|
||||||
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
|
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
|
||||||
|
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
use interpreted_executor::util::wrap_network_in_scope;
|
use interpreted_executor::util::wrap_network_in_scope;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
@@ -28,6 +28,35 @@ impl NodeGraphUpdateSender for UpdateLogger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||||
|
|
||||||
|
impl TokioSpawner {
|
||||||
|
fn new() -> Result<Self, std::io::Error> {
|
||||||
|
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spawner for TokioSpawner {
|
||||||
|
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||||
|
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||||
|
let _guard = runtime.enter();
|
||||||
|
if poll_once(&mut task) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
runtime.spawn(task);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
|
||||||
|
impl Drop for TokioSpawner {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(runtime) = self.0.take() {
|
||||||
|
runtime.shutdown_background();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Parser)]
|
#[derive(Debug, Parser)]
|
||||||
#[clap(name = "graphene-cli", version)]
|
#[clap(name = "graphene-cli", version)]
|
||||||
pub struct App {
|
pub struct App {
|
||||||
@@ -101,8 +130,7 @@ struct GlobalOpts {
|
|||||||
verbose: u8,
|
verbose: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
async fn main() -> Result<(), Box<dyn Error>> {
|
|
||||||
let app = App::parse();
|
let app = App::parse();
|
||||||
|
|
||||||
let log_level = app.global_opts.verbose;
|
let log_level = app.global_opts.verbose;
|
||||||
@@ -130,9 +158,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let gdd = if is_gdd {
|
let gdd = if is_gdd {
|
||||||
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
||||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||||
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)
|
let gdd = block_on(document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)).map_err(|error| format!("Failed to open document: {error}"))?;
|
||||||
.await
|
|
||||||
.map_err(|error| format!("Failed to open document: {error}"))?;
|
|
||||||
Some(gdd)
|
Some(gdd)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -140,7 +166,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
if let Command::ExtractLegacyDoc { ref document } = app.command {
|
if let Command::ExtractLegacyDoc { ref document } = app.command {
|
||||||
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
|
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
|
||||||
let Some(legacy_doc) = gdd.read_legacy_document().await else {
|
let Some(legacy_doc) = block_on(gdd.read_legacy_document()) else {
|
||||||
return Err("gdd file did not contain a legacy .graphite document".into());
|
return Err("gdd file did not contain a legacy .graphite document".into());
|
||||||
};
|
};
|
||||||
let mut new_path = document.clone();
|
let mut new_path = document.clone();
|
||||||
@@ -153,7 +179,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
|
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
|
||||||
let node_network = match &gdd {
|
let node_network = match &gdd {
|
||||||
Some(gdd) => {
|
Some(gdd) => {
|
||||||
let declarations = gdd.declarations(gdd).await;
|
let declarations = block_on(gdd.declarations(gdd));
|
||||||
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
|
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||||
node_network
|
node_network
|
||||||
}
|
}
|
||||||
@@ -164,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
log::info!("Creating GPU context");
|
log::info!("Creating GPU context");
|
||||||
let mut application_io = PlatformApplicationIo::new().await;
|
let mut application_io = block_on(PlatformApplicationIo::new());
|
||||||
if let Some(gdd) = &gdd {
|
if let Some(gdd) = &gdd {
|
||||||
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
||||||
}
|
}
|
||||||
@@ -176,16 +202,22 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let application_io_for_api = application_io_arc.clone();
|
let application_io_for_api = application_io_arc.clone();
|
||||||
|
|
||||||
// Get reference to wgpu executor and clone device handle
|
// Get reference to wgpu executor and clone device handle
|
||||||
let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap();
|
let wgpu_executor_ref = wgpu_executor::WgpuExecutorHandle(application_io_arc.gpu_executor_arc().unwrap());
|
||||||
let device = wgpu_executor_ref.context().device.clone();
|
let device = wgpu_executor_ref.context().device.clone();
|
||||||
|
|
||||||
let preferences = EditorPreferences {
|
let preferences = EditorPreferences {
|
||||||
max_render_region_size: EditorPreferences::default().max_render_region_size,
|
max_render_region_size: EditorPreferences::default().max_render_region_size,
|
||||||
};
|
};
|
||||||
|
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
|
||||||
|
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
|
||||||
|
graph_runtime.set_notifier(Arc::new(move || {
|
||||||
|
let _ = completion_sender.send(());
|
||||||
|
}));
|
||||||
let editor_api = Arc::new(PlatformEditorApi {
|
let editor_api = Arc::new(PlatformEditorApi {
|
||||||
application_io: Some(application_io_for_api),
|
application_io: Some(application_io_for_api),
|
||||||
node_graph_message_sender: Box::new(UpdateLogger {}),
|
node_graph_message_sender: Box::new(UpdateLogger {}),
|
||||||
editor_preferences: Box::new(preferences),
|
editor_preferences: Box::new(preferences),
|
||||||
|
runtime: RuntimeHandle(graph_runtime.clone()),
|
||||||
});
|
});
|
||||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
|
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
|
||||||
|
|
||||||
@@ -218,7 +250,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let file_type = export::detect_file_type(&output)?;
|
let file_type = export::detect_file_type(&output)?;
|
||||||
|
|
||||||
// Create executor
|
// Create executor
|
||||||
let executor = create_executor(proto_graph)?;
|
let executor = create_executor(proto_graph, graph_runtime)?;
|
||||||
|
|
||||||
if fps <= 0. {
|
if fps <= 0. {
|
||||||
return Err("Fps number must be positive".into());
|
return Err("Fps number must be positive".into());
|
||||||
@@ -227,9 +259,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
// Perform export based on file type
|
// Perform export based on file type
|
||||||
if file_type == export::FileType::Gif {
|
if file_type == export::FileType::Gif {
|
||||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||||
export::export_gif(&executor, wgpu_executor_ref, output, scale, (width, height), animation).await?;
|
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
|
||||||
} else {
|
} else {
|
||||||
export::export_document(&executor, wgpu_executor_ref, output, file_type, scale, (width, height), transparent).await?;
|
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => unreachable!("All other commands should be handled before this match statement is run"),
|
_ => unreachable!("All other commands should be handled before this match statement is run"),
|
||||||
@@ -282,10 +314,11 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
|
|||||||
}
|
}
|
||||||
|
|
||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
compiler.compile_single(network).map_err(|x| x.into())
|
compiler.compile_single(network, &interpreted_executor::node_registry::NODE_REGISTRY).map_err(|x| x.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||||
let executor = block_on(DynamicExecutor::new(proto_network)).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
let mut executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
||||||
|
executor.set_runtime(runtime);
|
||||||
Ok(executor)
|
Ok(executor)
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,7 @@ wasm = ["graphene-std/wasm"]
|
|||||||
graphene-std = { workspace = true }
|
graphene-std = { workspace = true }
|
||||||
graph-craft = { workspace = true }
|
graph-craft = { workspace = true }
|
||||||
graphene-core = { workspace = true }
|
graphene-core = { workspace = true }
|
||||||
|
graphic-types = { workspace = true }
|
||||||
wgpu-executor = { workspace = true }
|
wgpu-executor = { workspace = true }
|
||||||
core-types = { workspace = true }
|
core-types = { workspace = true }
|
||||||
dyn-any = { workspace = true }
|
dyn-any = { workspace = true }
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use criterion::BenchmarkGroup;
|
use criterion::BenchmarkGroup;
|
||||||
use criterion::measurement::Measurement;
|
use criterion::measurement::Measurement;
|
||||||
use futures::executor::block_on;
|
|
||||||
use graph_craft::proto::ProtoNetwork;
|
use graph_craft::proto::ProtoNetwork;
|
||||||
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
||||||
use graphene_std::application_io::EditorApi;
|
use graphene_std::application_io::EditorApi;
|
||||||
@@ -13,11 +12,13 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
|||||||
let mut network = wrap_network_in_scope(network, editor_api);
|
let mut network = wrap_network_in_scope(network, editor_api);
|
||||||
let preprocessor = preprocessor::Preprocessor::new();
|
let preprocessor = preprocessor::Preprocessor::new();
|
||||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||||
let proto_network = compile(network);
|
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||||
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
|
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
|
||||||
(executor, proto_network)
|
(executor, proto_network)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Some benches in this module's include set drive the demos themselves.
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
|
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
|
||||||
where
|
where
|
||||||
F: Fn(&str, &mut BenchmarkGroup<M>),
|
F: Fn(&str, &mut BenchmarkGroup<M>),
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ mod benchmark_util;
|
|||||||
|
|
||||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||||
use criterion::{Criterion, criterion_group, criterion_main};
|
use criterion::{Criterion, criterion_group, criterion_main};
|
||||||
|
use graph_craft::graphene_compiler::Executor;
|
||||||
use graphene_std::application_io::RenderConfig;
|
use graphene_std::application_io::RenderConfig;
|
||||||
|
|
||||||
fn subsequent_evaluations(c: &mut Criterion) {
|
fn subsequent_evaluations(c: &mut Criterion) {
|
||||||
@@ -9,9 +10,7 @@ fn subsequent_evaluations(c: &mut Criterion) {
|
|||||||
let context = RenderConfig::default();
|
let context = RenderConfig::default();
|
||||||
bench_for_each_demo(&mut group, |name, g| {
|
bench_for_each_demo(&mut group, |name, g| {
|
||||||
let (executor, _) = setup_network(name);
|
let (executor, _) = setup_network(name);
|
||||||
g.bench_function(name, |b| {
|
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
|
||||||
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
group.finish();
|
group.finish();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
mod benchmark_util;
|
mod benchmark_util;
|
||||||
|
|
||||||
use benchmark_util::setup_network;
|
use benchmark_util::setup_network;
|
||||||
|
use graph_craft::graphene_compiler::Executor;
|
||||||
use graphene_std::application_io::RenderConfig;
|
use graphene_std::application_io::RenderConfig;
|
||||||
use gungraun::prelude::*;
|
use gungraun::prelude::*;
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
@@ -11,16 +12,16 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
|||||||
|
|
||||||
// Warm up the cache by running once
|
// Warm up the cache by running once
|
||||||
let context = RenderConfig::default();
|
let context = RenderConfig::default();
|
||||||
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
|
let _ = Executor::execute(&&executor, context);
|
||||||
|
|
||||||
executor
|
executor
|
||||||
}
|
}
|
||||||
|
|
||||||
#[library_benchmark]
|
#[library_benchmark]
|
||||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||||
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
||||||
let context = RenderConfig::default();
|
let context = RenderConfig::default();
|
||||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||||
|
|
||||||
// Return the executor so its teardown happens outside the measured section
|
// Return the executor so its teardown happens outside the measured section
|
||||||
executor
|
executor
|
||||||
|
|||||||
@@ -8,15 +8,12 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
|||||||
|
|
||||||
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||||
let network = load_from_name(name);
|
let network = load_from_name(name);
|
||||||
let proto_network = compile(network);
|
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||||
let empty = ProtoNetwork::default();
|
|
||||||
|
|
||||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
|
||||||
|
|
||||||
c.bench_function(name, |b| {
|
c.bench_function(name, |b| {
|
||||||
b.iter_batched(
|
b.iter_batched(
|
||||||
|| (executor.clone(), proto_network.clone()),
|
|| (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|
||||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||||
criterion::BatchSize::SmallInput,
|
criterion::BatchSize::SmallInput,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@@ -31,12 +28,12 @@ fn update_executor_demo(c: &mut Criterion) {
|
|||||||
|
|
||||||
fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||||
let network = load_from_name(name);
|
let network = load_from_name(name);
|
||||||
let proto_network = compile(network);
|
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||||
|
|
||||||
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap();
|
let executor = DynamicExecutor::new(proto_network).unwrap();
|
||||||
let footprint = Footprint::default();
|
let footprint = Footprint::default();
|
||||||
|
|
||||||
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint))));
|
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
|
||||||
}
|
}
|
||||||
fn run_once_demo(c: &mut Criterion) {
|
fn run_once_demo(c: &mut Criterion) {
|
||||||
let mut g = c.benchmark_group("Run Once no render");
|
let mut g = c.benchmark_group("Run Once no render");
|
||||||
|
|||||||
@@ -2,17 +2,20 @@ mod benchmark_util;
|
|||||||
|
|
||||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||||
use criterion::{Criterion, criterion_group, criterion_main};
|
use criterion::{Criterion, criterion_group, criterion_main};
|
||||||
|
use graph_craft::graphene_compiler::Executor;
|
||||||
use graphene_std::application_io::RenderConfig;
|
use graphene_std::application_io::RenderConfig;
|
||||||
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
|
|
||||||
fn run_once(c: &mut Criterion) {
|
fn run_once(c: &mut Criterion) {
|
||||||
let mut group = c.benchmark_group("Run Once");
|
let mut group = c.benchmark_group("Run Once");
|
||||||
let context = RenderConfig::default();
|
let context = RenderConfig::default();
|
||||||
bench_for_each_demo(&mut group, |name, g| {
|
bench_for_each_demo(&mut group, |name, g| {
|
||||||
|
let (_, network) = setup_network(name);
|
||||||
g.bench_function(name, |b| {
|
g.bench_function(name, |b| {
|
||||||
b.iter_batched(
|
b.iter_batched_ref(
|
||||||
|| setup_network(name),
|
|| DynamicExecutor::new(network.clone()).unwrap(),
|
||||||
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
|
|executor| Executor::execute(&&*executor, std::hint::black_box(context)).unwrap(),
|
||||||
criterion::BatchSize::SmallInput,
|
criterion::BatchSize::LargeInput,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
mod benchmark_util;
|
mod benchmark_util;
|
||||||
|
|
||||||
use benchmark_util::setup_network;
|
use benchmark_util::setup_network;
|
||||||
|
use graph_craft::graphene_compiler::Executor;
|
||||||
use graphene_std::application_io;
|
use graphene_std::application_io;
|
||||||
use gungraun::prelude::*;
|
use gungraun::prelude::*;
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
@@ -12,13 +13,13 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[library_benchmark]
|
#[library_benchmark]
|
||||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||||
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
|
pub fn run_once(executor: DynamicExecutor) -> (DynamicExecutor, core_types::gpoll::GPoll<graph_craft::document::value::TaggedValue>) {
|
||||||
let context = application_io::RenderConfig::default();
|
let context = application_io::RenderConfig::default();
|
||||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
let result = black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||||
|
|
||||||
// Return the executor so its teardown happens outside the measured section
|
// Return the executor and result so their teardown happens outside the measured section
|
||||||
executor
|
(executor, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
library_benchmark_group!(name = run_once_group; benchmarks = run_once);
|
library_benchmark_group!(name = run_once_group; benchmarks = run_once);
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ fn update_executor(c: &mut Criterion) {
|
|||||||
let mut group = c.benchmark_group("Update Executor");
|
let mut group = c.benchmark_group("Update Executor");
|
||||||
bench_for_each_demo(&mut group, |name, g| {
|
bench_for_each_demo(&mut group, |name, g| {
|
||||||
g.bench_function(name, |b| {
|
g.bench_function(name, |b| {
|
||||||
b.iter_batched(
|
b.iter_batched_ref(
|
||||||
|| {
|
|| {
|
||||||
let (_, proto_network) = setup_network(name);
|
let (_, proto_network) = setup_network(name);
|
||||||
let empty = ProtoNetwork::default();
|
let empty = ProtoNetwork::default();
|
||||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
let executor = DynamicExecutor::new(empty).unwrap();
|
||||||
(executor, proto_network)
|
(executor, proto_network)
|
||||||
},
|
},
|
||||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
|(executor, network)| executor.update(std::hint::black_box(std::mem::take(network))),
|
||||||
criterion::BatchSize::SmallInput,
|
criterion::BatchSize::SmallInput,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use std::hint::black_box;
|
|||||||
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||||
let (_, proto_network) = setup_network(name);
|
let (_, proto_network) = setup_network(name);
|
||||||
let empty = ProtoNetwork::default();
|
let empty = ProtoNetwork::default();
|
||||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
let executor = DynamicExecutor::new(empty).unwrap();
|
||||||
(executor, proto_network)
|
(executor, proto_network)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
|||||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
||||||
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
||||||
let (mut executor, network) = setup;
|
let (mut executor, network) = setup;
|
||||||
let _ = black_box(futures::executor::block_on(executor.update(black_box(network))));
|
let _ = black_box(executor.update(black_box(network)));
|
||||||
|
|
||||||
// Return the executor so its teardown happens outside the measured section
|
// Return the executor so its teardown happens outside the measured section
|
||||||
executor
|
executor
|
||||||
|
|||||||
@@ -1,17 +1,46 @@
|
|||||||
use crate::node_registry;
|
use crate::node_registry;
|
||||||
use dyn_any::StaticType;
|
use core_types::arena::Arena;
|
||||||
|
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
||||||
|
use core_types::gpoll::GPoll;
|
||||||
|
use core_types::registry::SourceHandle;
|
||||||
|
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||||
use graph_craft::Type;
|
use graph_craft::Type;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode};
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::graphene_compiler::Executor;
|
use graph_craft::graphene_compiler::Executor;
|
||||||
use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext};
|
use graph_craft::proto::{ConstructionArgs, GraphError, ProtoNetwork, ProtoNode, TypingContext};
|
||||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::sync::Arc;
|
use std::sync::{Arc, Mutex, PoisonError};
|
||||||
|
|
||||||
|
const ARENA_CAPACITY: usize = 1 << 27;
|
||||||
|
|
||||||
|
const PERSISTENT_CAPACITY: usize = 1 << 26;
|
||||||
|
|
||||||
|
/// The heap the persistent region's parked payloads may own before a flush.
|
||||||
|
/// Occupancy cannot stand in for it: a park costs one pointer in the region
|
||||||
|
/// and owns its content outside it, so the two diverge by orders of magnitude.
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
const PERSISTENT_HEAP_BUDGET: usize = 1 << 29;
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
const PERSISTENT_HEAP_BUDGET: usize = 1 << 28;
|
||||||
|
|
||||||
|
/// The share of a budget that triggers a flush at the next boundary, chosen so
|
||||||
|
/// the region is emptied before a promote is refused mid-evaluation.
|
||||||
|
fn over_budget(used: usize, budget: usize) -> bool {
|
||||||
|
used >= budget / 8 * 7
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_arena(capacity: usize) -> Arena {
|
||||||
|
Arena::new(capacity).unwrap_or_else(|| {
|
||||||
|
log::error!("arena generations exhausted; continuing without frame caching");
|
||||||
|
Arena::parked()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
|
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct DynamicExecutor {
|
pub struct DynamicExecutor {
|
||||||
output: NodeId,
|
output: NodeId,
|
||||||
/// Stores all of the dynamic node structs.
|
/// Stores all of the dynamic node structs.
|
||||||
@@ -20,6 +49,19 @@ pub struct DynamicExecutor {
|
|||||||
typing_context: TypingContext,
|
typing_context: TypingContext,
|
||||||
// This allows us to keep the nodes around for one more frame which is used for introspection
|
// This allows us to keep the nodes around for one more frame which is used for introspection
|
||||||
orphaned_nodes: HashSet<NodeId>,
|
orphaned_nodes: HashSet<NodeId>,
|
||||||
|
arena: Mutex<Arena>,
|
||||||
|
/// The region memo levels are promoted into: reset only between
|
||||||
|
/// evaluations, and only once a promote has been refused.
|
||||||
|
persistent: Mutex<Arena>,
|
||||||
|
/// The record frame space, grow-only across evaluations and lent to the
|
||||||
|
/// root by `&mut`.
|
||||||
|
frames: Mutex<core_types::record::FrameArena>,
|
||||||
|
runtime: Arc<DynGraphRuntime>,
|
||||||
|
live_sources: Vec<core_types::SourceId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn noop_runtime() -> Arc<DynGraphRuntime> {
|
||||||
|
Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>))
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for DynamicExecutor {
|
impl Default for DynamicExecutor {
|
||||||
@@ -29,6 +71,11 @@ impl Default for DynamicExecutor {
|
|||||||
tree: Default::default(),
|
tree: Default::default(),
|
||||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||||
orphaned_nodes: HashSet::new(),
|
orphaned_nodes: HashSet::new(),
|
||||||
|
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
|
||||||
|
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
|
||||||
|
frames: Mutex::new(core_types::record::FrameArena::new()),
|
||||||
|
runtime: noop_runtime(),
|
||||||
|
live_sources: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,25 +95,42 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl DynamicExecutor {
|
impl DynamicExecutor {
|
||||||
pub async fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||||
typing_context.update(&proto_network)?;
|
typing_context.update(&mut proto_network)?;
|
||||||
let output = proto_network.output;
|
let output = proto_network.output;
|
||||||
let tree = BorrowTree::new(proto_network, &typing_context).await?;
|
let sources = proto_network.source_ids();
|
||||||
|
let tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||||
|
let runtime = noop_runtime();
|
||||||
|
runtime.retain_sources(&sources);
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
tree,
|
tree,
|
||||||
output,
|
output,
|
||||||
typing_context,
|
typing_context,
|
||||||
orphaned_nodes: HashSet::new(),
|
orphaned_nodes: HashSet::new(),
|
||||||
|
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
|
||||||
|
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
|
||||||
|
frames: Mutex::new(core_types::record::FrameArena::new()),
|
||||||
|
runtime,
|
||||||
|
live_sources: sources,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_runtime(&mut self, runtime: Arc<DynGraphRuntime>) {
|
||||||
|
runtime.retain_sources(&self.live_sources);
|
||||||
|
self.runtime = runtime;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take_dirty(&self) -> bool {
|
||||||
|
self.runtime.take_dirty()
|
||||||
|
}
|
||||||
|
|
||||||
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
|
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
|
||||||
#[cfg_attr(debug_assertions, inline(never))]
|
#[cfg_attr(debug_assertions, inline(never))]
|
||||||
pub async fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
self.output = proto_network.output;
|
self.output = proto_network.output;
|
||||||
self.typing_context.update(&proto_network).map_err(|e| {
|
self.typing_context.update(&mut proto_network).map_err(|e| {
|
||||||
// If there is an error then get types that have been resolved before the error
|
// If there is an error then get types that have been resolved before the error
|
||||||
let add = proto_network
|
let add = proto_network
|
||||||
.nodes
|
.nodes
|
||||||
@@ -87,11 +151,10 @@ impl DynamicExecutor {
|
|||||||
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let (add, orphaned) = self
|
let sources = proto_network.source_ids();
|
||||||
.tree
|
let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||||
.update(proto_network, &self.typing_context)
|
self.runtime.retain_sources(&sources);
|
||||||
.await
|
self.live_sources = sources;
|
||||||
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
|
||||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
||||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
||||||
for node_id in old_to_remove {
|
for node_id in old_to_remove {
|
||||||
@@ -107,9 +170,73 @@ impl DynamicExecutor {
|
|||||||
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
|
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
/// Calls the `Node::serialize` for that specific node. A monitor serializes
|
||||||
|
/// its stored context snapshot, and this entry recreates the monitored
|
||||||
|
/// value from it as the legacy value the editor's downcasts expect: a
|
||||||
|
/// rank-0 input yields its element and a leveled input its legacy list.
|
||||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||||
self.tree.introspect(node_path)
|
let result = self.tree.introspect(node_path)?;
|
||||||
|
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
|
||||||
|
return self
|
||||||
|
.introspect_with(node_path, graphic_types::boundary::batch_to_legacy)
|
||||||
|
.map(Arc::from);
|
||||||
|
}
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-evaluates the monitored input at `node_path` with its stored context
|
||||||
|
/// snapshot and hands the resulting resident batch to `read`, inside the
|
||||||
|
/// introspection window. The monitor stores only the context; the value is
|
||||||
|
/// recreated against current source data, so a read right after an
|
||||||
|
/// execution serves out of the warm memo entries.
|
||||||
|
pub fn introspect_with<R>(&self, node_path: &[NodeId], read: impl FnOnce(&core_types::record::Layout, core_types::node::RecordBatch<'_>, &Arena) -> Option<R>) -> Result<R, IntrospectError> {
|
||||||
|
let serialized = self.tree.introspect(node_path)?;
|
||||||
|
let Some(snapshot) = serialized.downcast_ref::<core_types::context::CtxSnapshot>() else {
|
||||||
|
return Err(IntrospectError::NoData);
|
||||||
|
};
|
||||||
|
let edge = self
|
||||||
|
.tree
|
||||||
|
.get_by_path(node_path)
|
||||||
|
.and_then(SourceHandle::record_source)
|
||||||
|
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||||
|
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
buffer.reserve(self.tree.stack_need());
|
||||||
|
let frames = buffer.frames();
|
||||||
|
let generations = self.runtime.snapshot();
|
||||||
|
let scope = EvalScope::new(snapshot.try_real_time(), snapshot.try_animation_time(), snapshot.try_pointer_position(), &generations, &arena).with_persistent(&persistent);
|
||||||
|
let Some(ctx) = snapshot.rehydrate(&scope) else {
|
||||||
|
return Err(IntrospectError::NoData);
|
||||||
|
};
|
||||||
|
let layout = core_types::node::Node::<ContextImpl>::layout(&edge);
|
||||||
|
// The batch borrows the frames the read closure is handed, so the read
|
||||||
|
// cannot outlive the scope that owns them.
|
||||||
|
let frames = frames.scope();
|
||||||
|
let result = if layout.depth > 0 {
|
||||||
|
match core_types::record::materialize_level(&edge, &ctx, &arena, &frames) {
|
||||||
|
core_types::record::LevelStatus::Batch(batch, _) => read(layout, batch, &arena),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match core_types::record::serve_input(&edge, &ctx, &frames) {
|
||||||
|
GPoll::Final(value) | GPoll::Partial(value) => {
|
||||||
|
let rec = layout.rec(&value);
|
||||||
|
// SAFETY: the serve produced one live record of the input's layout.
|
||||||
|
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
|
||||||
|
read(layout, batch, &arena)
|
||||||
|
}
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (value, _) = *boxed;
|
||||||
|
let rec = layout.rec(&value);
|
||||||
|
// SAFETY: as for the final arm.
|
||||||
|
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
|
||||||
|
read(layout, batch, &arena)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
result.ok_or(IntrospectError::NoData)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn input_type(&self) -> Option<Type> {
|
pub fn input_type(&self) -> Option<Type> {
|
||||||
@@ -135,27 +262,75 @@ impl DynamicExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<I> Executor<I, TaggedValue> for &DynamicExecutor
|
impl<I> Executor<I, GPoll<TaggedValue>> for &DynamicExecutor
|
||||||
where
|
where
|
||||||
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
|
I: VarArg + Send + Sync + std::panic::RefUnwindSafe,
|
||||||
{
|
{
|
||||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> {
|
fn execute(&self, input: I) -> Result<GPoll<TaggedValue>, Box<dyn Error>> {
|
||||||
Box::pin(async move {
|
let Some(handle) = self.tree.get(self.output) else {
|
||||||
use futures::FutureExt;
|
return Err("Output node not found in executor".into());
|
||||||
|
};
|
||||||
|
let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
// The region is flushed whole between evaluations and the memos
|
||||||
|
// re-promote: on a refusal, which leaves no room for the next promote,
|
||||||
|
// and ahead of one where either the region itself or the heap its
|
||||||
|
// parked payloads own is close to full.
|
||||||
|
if persistent.exhausted() || over_budget(persistent.occupancy(), persistent.capacity()) || over_budget(persistent.retained_heap(), PERSISTENT_HEAP_BUDGET) {
|
||||||
|
persistent.reset();
|
||||||
|
}
|
||||||
|
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
buffer.reserve(self.tree.stack_need());
|
||||||
|
let result = eval_root(&mut arena, &persistent, &mut buffer, &self.runtime, &input, |ctx, frames| {
|
||||||
|
match TaggedValue::from_edge(handle.duplicate(), ctx, frames) {
|
||||||
|
Ok(poll) => poll.map(Ok),
|
||||||
|
Err(error) => GPoll::Final(Err(error)),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
match result {
|
||||||
|
GPoll::Final(value) => Ok(GPoll::Final(value?)),
|
||||||
|
GPoll::Partial(value) => Ok(GPoll::Partial(value?)),
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (value, error) = *boxed;
|
||||||
|
Ok(GPoll::Fallback(Box::new((value?, error))))
|
||||||
|
}
|
||||||
|
GPoll::Pending => Ok(GPoll::Pending),
|
||||||
|
GPoll::Error(error) => Ok(GPoll::Error(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// One evaluation over the arena and the frame buffer, which the caller sized
|
||||||
|
/// to the graph's frame need: both are the evaluation's lifetime, so a record
|
||||||
|
/// served anywhere in the cone lives exactly as long as the arena it may
|
||||||
|
/// reference. The persistent region is borrowed shared for the same span, so
|
||||||
|
/// no flush can land while a value promoted into it is readable.
|
||||||
|
pub fn eval_root<S, T>(
|
||||||
|
arena: &mut Arena,
|
||||||
|
persistent: &Arena,
|
||||||
|
buffer: &mut core_types::record::FrameArena,
|
||||||
|
runtime: &GraphRuntime<S>,
|
||||||
|
call_argument: DynSlot,
|
||||||
|
eval: impl for<'e> FnOnce(&ContextImpl<'e>, &core_types::record::Frames<'e>) -> GPoll<T>,
|
||||||
|
) -> GPoll<T> {
|
||||||
|
arena.reset();
|
||||||
|
let generations = runtime.snapshot();
|
||||||
|
let scope = EvalScope::new(None, None, None, &generations, arena).with_persistent(persistent);
|
||||||
|
let root = ContextImpl::root(&scope);
|
||||||
|
let link = VarArgLink {
|
||||||
|
args: VarArgSlots::Single(call_argument),
|
||||||
|
outer: None,
|
||||||
|
};
|
||||||
|
let ctx = root.with_varargs(&link);
|
||||||
|
let frames = buffer.frames();
|
||||||
|
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx, &frames))) {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(_) => {
|
||||||
|
arena.reset();
|
||||||
|
GPoll::panicked()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let result = self.tree.eval_tagged_value(self.output, input);
|
|
||||||
let wrapped_result = std::panic::AssertUnwindSafe(result).catch_unwind().await;
|
|
||||||
|
|
||||||
match wrapped_result {
|
|
||||||
Ok(result) => result.map_err(|e| e.into()),
|
|
||||||
Err(e) => {
|
|
||||||
Box::leak(e);
|
|
||||||
Err("Node graph execution panicked".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub struct InputMapping {}
|
pub struct InputMapping {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
@@ -188,85 +363,76 @@ impl std::fmt::Display for IntrospectError {
|
|||||||
///
|
///
|
||||||
/// # Fields
|
/// # Fields
|
||||||
///
|
///
|
||||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`] and [`Path`].
|
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SourceHandle`] and [`Path`].
|
||||||
/// This stores the actual node instances and their associated paths.
|
/// This stores the actual node instances and their associated paths.
|
||||||
///
|
///
|
||||||
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
||||||
/// This maps document paths to node IDs and their associated type information.
|
/// This maps document paths to node IDs and their associated type information.
|
||||||
///
|
///
|
||||||
/// A store of the dynamically typed nodes and also the source map.
|
/// A store of the dynamically typed nodes and also the source map.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default)]
|
||||||
pub struct BorrowTree {
|
pub struct BorrowTree {
|
||||||
/// A hashmap of node IDs and dynamically typed nodes.
|
/// A hashmap of node IDs and dynamically typed nodes.
|
||||||
nodes: HashMap<NodeId, (SharedNodeContainer, Path)>,
|
nodes: HashMap<NodeId, (SourceHandle, Path)>,
|
||||||
/// A hashmap from the document path to the proto node ID.
|
/// A hashmap from the document path to the proto node ID.
|
||||||
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
||||||
|
/// The record-stack reserve, folded from the graph at construction.
|
||||||
|
stack_need: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BorrowTree {
|
impl BorrowTree {
|
||||||
pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||||
let mut nodes = BorrowTree::default();
|
let mut nodes = BorrowTree::default();
|
||||||
|
let stack_need = proto_network.stack_need;
|
||||||
for (id, node) in proto_network.nodes {
|
for (id, node) in proto_network.nodes {
|
||||||
nodes.push_node(id, node, typing_context).await?
|
nodes.push_node(id, node, typing_context)?
|
||||||
}
|
}
|
||||||
|
nodes.stack_need = stack_need;
|
||||||
Ok(nodes)
|
Ok(nodes)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pushes new nodes into the tree and return orphaned nodes
|
/// Pushes new nodes into the tree and return orphaned nodes
|
||||||
pub async fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||||
|
let stack_need = proto_network.stack_need;
|
||||||
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
|
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
|
||||||
let mut new_nodes: Vec<_> = Vec::new();
|
let mut new_nodes: Vec<_> = Vec::new();
|
||||||
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
||||||
for (id, node) in proto_network.nodes {
|
for (id, node) in proto_network.nodes {
|
||||||
if !self.nodes.contains_key(&id) {
|
if !self.nodes.contains_key(&id) {
|
||||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||||
self.push_node(id, node, typing_context).await?;
|
self.push_node(id, node, typing_context)?;
|
||||||
} else if self.update_source_map(id, typing_context, &node) {
|
} else if self.update_source_map(id, typing_context, &node) {
|
||||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||||
}
|
}
|
||||||
old_nodes.remove(&id);
|
old_nodes.remove(&id);
|
||||||
}
|
}
|
||||||
|
self.stack_need = stack_need;
|
||||||
Ok((new_nodes, old_nodes))
|
Ok((new_nodes, old_nodes))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> {
|
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SourceHandle> {
|
||||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect()
|
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path) {
|
fn store_node(&mut self, node: SourceHandle, id: NodeId, path: Path) {
|
||||||
self.nodes.insert(id, (node, path));
|
self.nodes.insert(id, (node, path));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
/// Calls the `Node::serialize` for that specific node, returning for example the captured context snapshot for a monitor node. The node path must match the document node path.
|
||||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||||
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||||
node.serialize().ok_or(IntrospectError::NoData)
|
node.serialize().ok_or(IntrospectError::NoData)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> {
|
pub fn get(&self, id: NodeId) -> Option<SourceHandle> {
|
||||||
self.nodes.get(&id).map(|(node, _)| node.clone())
|
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate the output node of the [`BorrowTree`].
|
/// The edge handle for the node at a document path.
|
||||||
pub async fn eval<'i, I, O>(&'i self, id: NodeId, input: I) -> Option<O>
|
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<SourceHandle> {
|
||||||
where
|
let (id, _) = self.source_map.get(node_path)?;
|
||||||
I: StaticType + 'i + Send + Sync,
|
self.get(*id)
|
||||||
O: StaticType + 'i,
|
|
||||||
{
|
|
||||||
let (node, _path) = self.nodes.get(&id).cloned()?;
|
|
||||||
let output = node.eval(Box::new(input));
|
|
||||||
dyn_any::downcast::<O>(output.await).ok().map(|o| *o)
|
|
||||||
}
|
|
||||||
/// Evaluate the output node of the [`BorrowTree`] and cast it to a tagged value.
|
|
||||||
/// This ensures that no borrowed data can escape the node graph.
|
|
||||||
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
|
|
||||||
where
|
|
||||||
I: StaticType + 'static + Send + Sync,
|
|
||||||
{
|
|
||||||
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
|
|
||||||
let output = node.eval(Box::new(input));
|
|
||||||
TaggedValue::try_from_any(output.await)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes a node from the [`BorrowTree`] and returns its associated path.
|
/// Removes a node from the [`BorrowTree`] and returns its associated path.
|
||||||
@@ -293,10 +459,10 @@ impl BorrowTree {
|
|||||||
/// use interpreted_executor::node_registry;
|
/// use interpreted_executor::node_registry;
|
||||||
///
|
///
|
||||||
///
|
///
|
||||||
/// async fn example() -> Result<(), GraphErrors> {
|
/// fn example() -> Result<(), GraphErrors> {
|
||||||
/// let (proto_network, node_id, proto_node) = ProtoNetwork::example();
|
/// let (proto_network, node_id, proto_node) = ProtoNetwork::example();
|
||||||
/// let typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
/// let typing_context = TypingContext::default();
|
||||||
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context).await?;
|
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||||
///
|
///
|
||||||
/// // Assert that the node exists in the BorrowTree
|
/// // Assert that the node exists in the BorrowTree
|
||||||
/// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal");
|
/// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal");
|
||||||
@@ -393,30 +559,26 @@ impl BorrowTree {
|
|||||||
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
||||||
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
||||||
/// - Returns an error if no constructor is found for the given node ID.
|
/// - Returns an error if no constructor is found for the given node ID.
|
||||||
async fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||||
self.update_source_map(id, typing_context, &proto_node);
|
self.update_source_map(id, typing_context, &proto_node);
|
||||||
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
||||||
|
|
||||||
match &proto_node.construction_args {
|
match &proto_node.construction_args {
|
||||||
ConstructionArgs::Value(value) => {
|
ConstructionArgs::Value(value) => {
|
||||||
let node = if let TaggedValue::EditorApi(api) = &**value {
|
let node = (**value)
|
||||||
let editor_api = UpcastAsRefNode::new(api.clone());
|
.clone()
|
||||||
let node = Box::new(editor_api) as TypeErasedBox<'_>;
|
.to_edge()
|
||||||
NodeContainer::new(node)
|
.map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(error))])?;
|
||||||
} else {
|
|
||||||
let upcasted = UpcastNode::new(value.to_owned());
|
|
||||||
let node = Box::new(upcasted) as TypeErasedBox<'_>;
|
|
||||||
NodeContainer::new(node)
|
|
||||||
};
|
|
||||||
self.store_node(node, id, path.into());
|
self.store_node(node, id, path.into());
|
||||||
}
|
}
|
||||||
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
|
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
|
||||||
ConstructionArgs::Nodes(ids) => {
|
ConstructionArgs::Nodes(ids) => {
|
||||||
let ids = ids.to_vec();
|
let construction_nodes = self.node_deps(ids);
|
||||||
let construction_nodes = self.node_deps(&ids);
|
|
||||||
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
||||||
let node = constructor(construction_nodes).await;
|
let mut node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
|
||||||
let node = NodeContainer::new(node);
|
if let Some(layout) = proto_node.resolved_layout() {
|
||||||
|
node.set_layout(layout.clone());
|
||||||
|
}
|
||||||
self.store_node(node, id, path.into());
|
self.store_node(node, id, path.into());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -427,22 +589,309 @@ impl BorrowTree {
|
|||||||
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
||||||
&self.source_map
|
&self.source_map
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The record-stack reserve of an evaluation, folded from the resolved layouts by the layout pass.
|
||||||
|
pub fn stack_need(&self) -> usize {
|
||||||
|
self.stack_need
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use core_types::arena::ArenaCell;
|
||||||
|
use core_types::context::{ExtractFootprint, ExtractVarArgs};
|
||||||
|
use core_types::runtime::{SourceFuture, Spawner};
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
|
||||||
|
struct InertSpawner;
|
||||||
|
|
||||||
|
impl Spawner for InertSpawner {
|
||||||
|
fn spawn(&self, _task: SourceFuture) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_flush_trigger_fires_on_occupancy_and_on_retained_heap() {
|
||||||
|
assert!(!over_budget(0, 1 << 10));
|
||||||
|
assert!(!over_budget(1 << 10 >> 1, 1 << 10), "half full stays");
|
||||||
|
assert!(over_budget(1 << 10 >> 3 << 3, 1 << 10), "a full region flushes");
|
||||||
|
assert!(over_budget((1 << 10) / 8 * 7, 1 << 10), "seven eighths is the trigger");
|
||||||
|
|
||||||
|
let arena = Arena::new(1024).unwrap();
|
||||||
|
assert!(!over_budget(arena.retained_heap(), PERSISTENT_HEAP_BUDGET), "an empty region is under every budget");
|
||||||
|
let owned = vec![0u8; 4096];
|
||||||
|
let length = owned.len();
|
||||||
|
arena.alloc_sized(owned, length).unwrap();
|
||||||
|
assert_eq!(arena.retained_heap(), length);
|
||||||
|
assert!(over_budget(arena.retained_heap(), 4096), "the heap hint alone can trigger a flush");
|
||||||
|
assert!(
|
||||||
|
!over_budget(arena.occupancy(), arena.capacity()),
|
||||||
|
"occupancy stays low while the retained heap is large, which is why the trigger reads both"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
|
||||||
|
let mut arena = Arena::new(64).unwrap();
|
||||||
|
let persistent = Arena::new(64).unwrap();
|
||||||
|
let mut buffer = core_types::record::FrameArena::new();
|
||||||
|
let runtime = GraphRuntime::new(InertSpawner);
|
||||||
|
let argument = 21.5f64;
|
||||||
|
let result = eval_root(&mut arena, &persistent, &mut buffer, &runtime, &argument, |ctx, _frames| {
|
||||||
|
assert!(ctx.try_footprint().is_none(), "the bare root carries no axes");
|
||||||
|
GPoll::Final(ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.))
|
||||||
|
});
|
||||||
|
assert_eq!(result, GPoll::Final(21.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn eval_root_resets_the_arena_at_eval_start() {
|
||||||
|
let mut arena = Arena::new(64).unwrap();
|
||||||
|
let persistent = Arena::new(64).unwrap();
|
||||||
|
let mut buffer = core_types::record::FrameArena::new();
|
||||||
|
let runtime = GraphRuntime::new(InertSpawner);
|
||||||
|
let cell = ArenaCell::new();
|
||||||
|
eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
|
||||||
|
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
|
||||||
|
cell.store(weak);
|
||||||
|
GPoll::Final(())
|
||||||
|
});
|
||||||
|
assert!(cell.load(&arena).is_some(), "the introspection window spans until the next eval");
|
||||||
|
eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
|
||||||
|
assert!(cell.load(ctx.scope().arena()).is_none(), "the reset at eval start reclaims the previous frame");
|
||||||
|
GPoll::Final(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
|
||||||
|
let mut arena = Arena::new(64).unwrap();
|
||||||
|
let persistent = Arena::new(64).unwrap();
|
||||||
|
let mut buffer = core_types::record::FrameArena::new();
|
||||||
|
let runtime = GraphRuntime::new(InertSpawner);
|
||||||
|
let cell = ArenaCell::new();
|
||||||
|
let result: GPoll<()> = eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
|
||||||
|
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
|
||||||
|
cell.store(weak);
|
||||||
|
panic!("mid-eval");
|
||||||
|
});
|
||||||
|
assert_eq!(result, GPoll::panicked());
|
||||||
|
assert!(cell.load(&arena).is_none(), "reset-on-panic leaves no stale records");
|
||||||
|
assert_eq!(eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |_, _| GPoll::Final(7u32)), GPoll::Final(7));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn push_node_sync() {
|
fn push_node_sync() {
|
||||||
let mut tree = BorrowTree::default();
|
let mut tree = BorrowTree::default();
|
||||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
|
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
|
||||||
let context = TypingContext::default();
|
let context = TypingContext::default();
|
||||||
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
|
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
|
||||||
futures::executor::block_on(future).unwrap();
|
let handle = tree.get(NodeId(0)).unwrap();
|
||||||
let _node = tree.get(NodeId(0)).unwrap();
|
let layout = handle.layout().clone();
|
||||||
let result = futures::executor::block_on(tree.eval(NodeId(0), ()));
|
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||||
assert_eq!(result, Some(2u32));
|
|
||||||
|
let arena = Arena::new(64).unwrap();
|
||||||
|
let generations = [];
|
||||||
|
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||||
|
let ctx = ContextImpl::root(&scope);
|
||||||
|
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||||
|
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||||
|
panic!("expected a final record");
|
||||||
|
};
|
||||||
|
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_executor(mut network: ProtoNetwork) -> DynamicExecutor {
|
||||||
|
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
|
||||||
|
network.compute_layouts();
|
||||||
|
DynamicExecutor::new(network).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
|
||||||
|
let mut node = ProtoNode::default();
|
||||||
|
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
|
||||||
|
node.call_argument = core_types::concrete!(core_types::context::Context);
|
||||||
|
node.construction_args = ConstructionArgs::Nodes(args);
|
||||||
|
node
|
||||||
|
}
|
||||||
|
|
||||||
|
fn string_value(value: &str) -> ProtoNode {
|
||||||
|
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(1),
|
||||||
|
nodes: vec![
|
||||||
|
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![7.]).into()), vec![])),
|
||||||
|
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
let arena = Arena::new(1 << 20).unwrap();
|
||||||
|
let generations = [];
|
||||||
|
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||||
|
let ctx = ContextImpl::root(&scope);
|
||||||
|
let handle = executor.tree().get(NodeId(1)).unwrap();
|
||||||
|
let layout = handle.layout().clone();
|
||||||
|
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
|
||||||
|
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||||
|
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||||
|
panic!("the flipped clone must evaluate over record wires, got a non-final poll");
|
||||||
|
};
|
||||||
|
assert_eq!(unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }, 7.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_palette_folds_its_record_wire_to_a_color_level() {
|
||||||
|
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(2),
|
||||||
|
nodes: vec![
|
||||||
|
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
|
||||||
|
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
|
||||||
|
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
let arena = Arena::new(1 << 12).unwrap();
|
||||||
|
let generations = [];
|
||||||
|
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||||
|
let ctx = ContextImpl::root(&scope);
|
||||||
|
let edge = executor.tree().get(NodeId(2)).unwrap().downcast_record::<graphene_std::raster::color::Color>().unwrap();
|
||||||
|
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||||
|
let result = core_types::record::serve_input(&edge, &ctx, &frames);
|
||||||
|
// The empty raster level folds to an empty palette: past-end at lane 0.
|
||||||
|
assert!(
|
||||||
|
matches!(&result, GPoll::Error(error) if error.kind == core_types::gpoll::ErrorKind::PastEnd),
|
||||||
|
"the empty palette level must serve the past-end signal at lane 0"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_value_edge_is_a_record_wire_end_to_end() {
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(0),
|
||||||
|
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![]))],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
let value = executor.tree().get(NodeId(0)).unwrap();
|
||||||
|
assert_eq!(value.ty(), &core_types::registry::record_source_type::<f64>());
|
||||||
|
assert_eq!(value.layout().depth, 0);
|
||||||
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_record_monitor_row_forwards_and_introspects_through_the_executor() {
|
||||||
|
let mut monitor = proto_node("graphene_core::memo::MonitorNode", vec![NodeId(0)]);
|
||||||
|
monitor.original_location.path = Some(vec![NodeId(9)]);
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(1),
|
||||||
|
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])), (NodeId(1), monitor)],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||||
|
let element = executor.introspect(&[NodeId(9)]).unwrap();
|
||||||
|
let element = element.downcast_ref::<f64>().expect("a record capture materializes to its element");
|
||||||
|
assert_eq!(*element, 7.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_memoize_row_wires_generically_and_replays_over_record_wires() {
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(1),
|
||||||
|
nodes: vec![
|
||||||
|
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(String::from("cached")).into()), vec![])),
|
||||||
|
(NodeId(1), proto_node("graphene_core::memo::MemoizeNode", vec![NodeId(0)])),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
|
||||||
|
assert_eq!(
|
||||||
|
(&executor).execute(()).unwrap(),
|
||||||
|
GPoll::Final(TaggedValue::String(String::from("cached"))),
|
||||||
|
"the second execution replays the deep copy against a reset arena"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modification_value() -> ProtoNode {
|
||||||
|
let modification = core_types::ContextModification::from_sources(core_types::context::ContextFeatures::all(), &[]);
|
||||||
|
ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(modification).into()), vec![])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_context_modification_row_wires_over_a_value_wire() {
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(2),
|
||||||
|
nodes: vec![
|
||||||
|
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||||
|
(NodeId(1), modification_value()),
|
||||||
|
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nested_context_modifications_forward_the_layout() {
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(4),
|
||||||
|
nodes: vec![
|
||||||
|
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||||
|
(NodeId(1), modification_value()),
|
||||||
|
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
|
||||||
|
(NodeId(3), modification_value()),
|
||||||
|
(NodeId(4), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(2), NodeId(3)])),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stacked_frame_memos_replay_over_record_wires() {
|
||||||
|
let network = ProtoNetwork {
|
||||||
|
stack_need: 0,
|
||||||
|
inputs: vec![],
|
||||||
|
output: NodeId(2),
|
||||||
|
nodes: vec![
|
||||||
|
(NodeId(0), string_value("memoized")),
|
||||||
|
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
|
||||||
|
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let executor = build_executor(network);
|
||||||
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
|
||||||
|
assert_eq!(
|
||||||
|
(&executor).execute(()).unwrap(),
|
||||||
|
GPoll::Final(TaggedValue::String("memoized".to_string())),
|
||||||
|
"the frame memo must replay across evaluations"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,6 @@ pub mod util;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use core_types::*;
|
use core_types::*;
|
||||||
use futures::executor::block_on;
|
|
||||||
use graphene_core::ops::passthrough;
|
use graphene_core::ops::passthrough;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -45,8 +44,8 @@ mod tests {
|
|||||||
use graph_craft::graphene_compiler::Compiler;
|
use graph_craft::graphene_compiler::Compiler;
|
||||||
|
|
||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
let protograph = compiler.compile_single(network).expect("Graph should be generated");
|
let protograph = compiler.compile_single(network, &crate::node_registry::NODE_REGISTRY).expect("Graph should be generated");
|
||||||
|
|
||||||
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,34 +1,25 @@
|
|||||||
use dyn_any::StaticType;
|
|
||||||
use glam::{DAffine2, DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::application_io::PlatformEditorApi;
|
|
||||||
use graph_craft::document::DocumentNode;
|
use graphene_std::list::List;
|
||||||
use graph_craft::document::value::RenderOutput;
|
|
||||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
|
||||||
use graphene_std::any::DynAnyNode;
|
|
||||||
use graphene_std::application_io::Texture;
|
|
||||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
|
||||||
use graphene_std::gradient::GradientStops;
|
|
||||||
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
use graphene_std::platform_application_io::canvas_utils::CanvasHandle;
|
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
use graphene_std::raster::GPU;
|
use graphene_std::raster::GPU;
|
||||||
use graphene_std::raster::color::Color;
|
|
||||||
use graphene_std::raster::*;
|
#[cfg(feature = "gpu")]
|
||||||
|
use graphene_std::SourceId;
|
||||||
use graphene_std::raster::{CPU, Raster};
|
use graphene_std::raster::{CPU, Raster};
|
||||||
use graphene_std::render_node::RenderIntermediate;
|
use graphene_std::registry::{ConstructionError, SourceHandle, NodeIOTypes, RegistryEntry};
|
||||||
use graphene_std::transform::Footprint;
|
#[cfg(feature = "gpu")]
|
||||||
use graphene_std::uuid::NodeId;
|
use graphene_std::runtime::RuntimeHandle;
|
||||||
|
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type_fut, future};
|
use graphene_std::{Context, Graphic, ProtoNodeIdentifier, concrete};
|
||||||
use node_registry_macros::{async_node, convert_node, into_node};
|
use node_registry_macros::{convert_node, into_node};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
use wgpu_executor::WgpuExecutor;
|
use wgpu_executor::WgpuExecutorHandle;
|
||||||
|
|
||||||
// TODO: turn into hashmap
|
fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
|
let mut node_types: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||||
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
|
||||||
// ==========
|
// ==========
|
||||||
// INTO NODES
|
// INTO NODES
|
||||||
// ==========
|
// ==========
|
||||||
@@ -40,60 +31,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
convert_node!(from: List<Raster<CPU>>, to: List<Graphic>),
|
convert_node!(from: List<Raster<CPU>>, to: List<Graphic>),
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
convert_node!(from: List<Raster<GPU>>, to: List<Graphic>),
|
convert_node!(from: List<Raster<GPU>>, to: List<Graphic>),
|
||||||
// Type-erased attribute conversions for the `Attach Attribute` node, so it monomorphizes only over the destination `List` type.
|
|
||||||
convert_node!(from: List<Artboard>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<Graphic>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<Vector>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<Raster<CPU>>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<Color>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<GradientStops>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<f64>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<bool>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<String>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<DAffine2>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<BlendMode>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: AttributeDyn),
|
|
||||||
convert_node!(from: List<Artboard>, to: ListDyn),
|
|
||||||
convert_node!(from: List<Graphic>, to: ListDyn),
|
|
||||||
convert_node!(from: List<Vector>, to: ListDyn),
|
|
||||||
convert_node!(from: List<Raster<CPU>>, to: ListDyn),
|
|
||||||
#[cfg(feature = "gpu")]
|
|
||||||
convert_node!(from: List<Raster<GPU>>, to: ListDyn),
|
|
||||||
convert_node!(from: List<Color>, to: ListDyn),
|
|
||||||
convert_node!(from: List<GradientStops>, to: ListDyn),
|
|
||||||
convert_node!(from: List<f64>, to: ListDyn),
|
|
||||||
convert_node!(from: List<bool>, to: ListDyn),
|
|
||||||
convert_node!(from: List<String>, to: ListDyn),
|
|
||||||
convert_node!(from: List<u8>, to: ListDyn),
|
|
||||||
convert_node!(from: List<NodeId>, to: ListDyn),
|
|
||||||
convert_node!(from: List<DAffine2>, to: ListDyn),
|
|
||||||
convert_node!(from: List<BlendMode>, to: ListDyn),
|
|
||||||
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: ListDyn),
|
|
||||||
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: ListDyn),
|
|
||||||
// Type-erased attribute value conversions for the `Write Attribute` node, so it monomorphizes only over the destination `List` type.
|
|
||||||
convert_node!(from: f64, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: u32, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: u64, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: bool, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: String, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: DVec2, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: DAffine2, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: Color, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: BlendMode, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: graphene_std::vector::style::GradientType, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: graphene_std::vector::style::GradientSpreadMethod, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<String>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<NodeId>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<Color>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<GradientStops>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<Vector>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<Raster<CPU>>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn),
|
|
||||||
convert_node!(from: List<Graphic>, to: AttributeValueDyn),
|
|
||||||
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
|
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
|
||||||
#[cfg(feature = "gpu")]
|
|
||||||
into_node!(from: &PlatformEditorApi, to: &WgpuExecutor),
|
|
||||||
convert_node!(from: DVec2, to: DVec2),
|
convert_node!(from: DVec2, to: DVec2),
|
||||||
convert_node!(from: List<Vector>, to: List<Vector>),
|
convert_node!(from: List<Vector>, to: List<Vector>),
|
||||||
convert_node!(from: DVec2, to: List<Vector>),
|
convert_node!(from: DVec2, to: List<Vector>),
|
||||||
@@ -103,194 +41,110 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
convert_node!(from: IVec2, to: String),
|
convert_node!(from: IVec2, to: String),
|
||||||
convert_node!(from: DAffine2, to: String),
|
convert_node!(from: DAffine2, to: String),
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
|
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle),
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
|
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
|
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
|
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle, async),
|
||||||
// =============
|
// =============
|
||||||
// MONITOR NODES
|
// MONITOR NODES
|
||||||
// =============
|
// =============
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ()]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
|
||||||
#[cfg(feature = "gpu")]
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientStops>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Image<Color>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => String]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => IVec2]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DVec2]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DAffine2]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => bool]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => f64]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u32]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u64]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => BlendMode]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Texture]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<f64>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<NodeId>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u8>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeDyn]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Graphic]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DocumentNode]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::LuminanceCalculation]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlue]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlueAlpha]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::NoiseType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::FractalType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularDistanceFunction]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularReturnType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::DomainWarpType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RelativeAbsolute]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::SelectiveColorChoice]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
|
|
||||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
|
|
||||||
// Context nullification
|
|
||||||
#[cfg(feature = "gpu")]
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextFeatures]),
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>, Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextFeatures]),
|
|
||||||
// ==========
|
// ==========
|
||||||
// MEMO NODES
|
// MEMO NODES
|
||||||
// ==========
|
// ==========
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<NodeId>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<u8>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => CanvasHandle]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f64]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f32]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u32]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u64]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DVec2]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => String]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Footprint]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi]),
|
|
||||||
#[cfg(feature = "gpu")]
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<Color>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Graphic]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextFeatures]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlue]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlueAlpha]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::NoiseType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::FractalType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularDistanceFunction]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularReturnType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::DomainWarpType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RelativeAbsolute]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::SelectiveColorChoice]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
|
|
||||||
];
|
];
|
||||||
|
// The transform's value-typed rows, served by `transform_value` under the
|
||||||
|
// leveled transform's identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::transform_nodes::transform_nodes::transform_value_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::transform_nodes::transform_nodes::transform::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The graphic-lane fill and stroke rows, served under their identifiers.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::vector::fill_graphic_leveled_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::vector::fill::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::vector::stroke_graphic_leveled_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::vector::stroke::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The boolean operation's plain vector rows, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::path_bool_nodes::boolean_operation_vector_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The path flattening's plain vector rows, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::vector::flatten_path_vector_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::vector::flatten_path::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The solidify's plain vector rows, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::vector::solidify_stroke_vector_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::vector::solidify_stroke::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The color assignment's graphic-lane rows, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::vector::assign_colors_graphic_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::vector::assign_colors::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The mirror's plain vector rows, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::graphic::mirror_vector_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::graphic::mirror::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The morph's plain vector rows, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::vector::morph_vector_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::vector::morph::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// Element-wise coercion into `Graphic` for single-typed leveled inputs,
|
||||||
|
// served by the hidden elementwise rows.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::graphic::to_graphic_element_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (ProtoNodeIdentifier::new("graphene_core::ops::IntoNode<Graphic>"), entry)),
|
||||||
|
);
|
||||||
|
// The typed-level collapse rows of To Graphic, served under its identifier.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::graphic::to_graphic_typed_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The unit row of To Graphic: an unconnected content input renders as nothing.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::graphic::to_graphic_unit_entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||||
|
);
|
||||||
|
// The transitional level bridge: a leveled input materializes into the legacy
|
||||||
|
// list an unconverted consumer expects. The rows are keyed under the legacy
|
||||||
|
// convert identifiers and die with the last legacy consumer.
|
||||||
|
node_types.extend(
|
||||||
|
graphene_std::graphic::level_to_list_entries()
|
||||||
|
.into_iter()
|
||||||
|
.zip([
|
||||||
|
"List<Graphic>",
|
||||||
|
"List<Vector>",
|
||||||
|
"List<Raster<CPU>>",
|
||||||
|
"List<Raster<GPU>>",
|
||||||
|
"List<Color>",
|
||||||
|
"List<GradientStops>",
|
||||||
|
"List<String>",
|
||||||
|
])
|
||||||
|
.map(|(entry, target)| (ProtoNodeIdentifier::with_owned_string(format!("graphene_core::ops::ConvertNode<{target}>")), entry)),
|
||||||
|
);
|
||||||
// =============
|
// =============
|
||||||
// CONVERT NODES
|
// CONVERT NODES
|
||||||
// =============
|
// =============
|
||||||
@@ -317,15 +171,21 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
.flatten(),
|
.flatten(),
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
let mut map: HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> = HashMap::new();
|
||||||
|
let insert = |map: &mut HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>, id: ProtoNodeIdentifier, entry: RegistryEntry| {
|
||||||
|
let rows = map.entry(id).or_default();
|
||||||
|
if !rows.iter().any(|row| row.io == entry.io) {
|
||||||
|
rows.push(entry);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
for (id, entry) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
|
for (id, entries) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
|
||||||
for (constructor, types) in entry.iter() {
|
for entry in entries {
|
||||||
map.entry(id.clone()).or_default().insert(types.clone(), *constructor);
|
insert(&mut map, id.clone(), entry.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (id, node_constructor, types) in node_types.into_iter() {
|
for (id, entry) in node_types.into_iter() {
|
||||||
// TODO: this is a hack to remove the newline from the node new_name
|
// TODO: this is a hack to remove the newline from the node new_name
|
||||||
// This occurs for the ChannelMixerNode presumably because of the long name.
|
// This occurs for the ChannelMixerNode presumably because of the long name.
|
||||||
// This might be caused by the stringify! macro
|
// This might be caused by the stringify! macro
|
||||||
@@ -338,77 +198,44 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
new_name = path.to_string();
|
new_name = path.to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
map.entry(ProtoNodeIdentifier::with_owned_string(new_name)).or_default().insert(types.clone(), node_constructor);
|
insert(&mut map, ProtoNodeIdentifier::with_owned_string(new_name), entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||||
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>> = once_cell::sync::Lazy::new(|| node_registry());
|
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = once_cell::sync::Lazy::new(node_registry);
|
||||||
|
|
||||||
mod node_registry_macros {
|
mod node_registry_macros {
|
||||||
macro_rules! async_node {
|
|
||||||
// TODO: we currently need to annotate the type here because the compiler would otherwise (correctly)
|
|
||||||
// TODO: assign a Pin<Box<dyn Future<Output=T>>> type to the node, which is not what we want for now.
|
|
||||||
//
|
|
||||||
// This `params` variant of the macro wraps the normal `fn_params` variant and is used as a shorthand for writing `T` instead of `() => T`
|
|
||||||
($path:ty, input: $input:ty, params: [$($type:ty),*]) => {
|
|
||||||
async_node!($path, input: $input, fn_params: [ $(() => $type),*])
|
|
||||||
};
|
|
||||||
($path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
|
|
||||||
(
|
|
||||||
ProtoNodeIdentifier::new(stringify!($path)),
|
|
||||||
|mut args| {
|
|
||||||
Box::pin(async move {
|
|
||||||
args.reverse();
|
|
||||||
let node = <$path>::new($(graphene_std::any::downcast_node::<$arg, $type>(args.pop().expect("Not enough arguments provided to construct node"))),*);
|
|
||||||
let any: DynAnyNode<$input, _, _> = graphene_std::any::DynAnyNode::new(node);
|
|
||||||
Box::new(any) as TypeErasedBox
|
|
||||||
})
|
|
||||||
},
|
|
||||||
{
|
|
||||||
let node = <$path>::new($(
|
|
||||||
graphene_std::any::PanicNode::<$arg, core::pin::Pin<Box<dyn core::future::Future<Output = $type> + Send>>>::new()
|
|
||||||
),*);
|
|
||||||
let params = vec![$(fn_type_fut!($arg, $type)),*];
|
|
||||||
let mut node_io = NodeIO::<'_, $input>::to_async_node_io(&node, params);
|
|
||||||
node_io.call_argument = concrete!(<$input as StaticType>::Static);
|
|
||||||
node_io
|
|
||||||
},
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! into_node {
|
macro_rules! into_node {
|
||||||
(from: $from:ty, to: $to:ty) => {
|
(from: $from:ty, to: $to:ty) => {
|
||||||
(
|
(
|
||||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|
||||||
|mut args| {
|
RegistryEntry {
|
||||||
Box::pin(async move {
|
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||||
let node = graphene_std::ops::IntoNode::new(
|
io: NodeIOTypes::new(
|
||||||
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
|
concrete!(Context),
|
||||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
|
core_types::registry::record_type::<$to>(),
|
||||||
);
|
vec![core_types::registry::record_source_type::<$from>()],
|
||||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
),
|
||||||
Box::new(any) as TypeErasedBox
|
constructor: |inputs| {
|
||||||
})
|
if inputs.len() != 1 {
|
||||||
|
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
|
||||||
|
}
|
||||||
|
let mut inputs = inputs.into_iter();
|
||||||
|
let handle = inputs.next().unwrap();
|
||||||
|
let layout = handle.layout().clone();
|
||||||
|
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
|
||||||
|
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||||
},
|
},
|
||||||
{
|
|
||||||
let node = graphene_std::ops::IntoNode::new(
|
|
||||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
|
||||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
|
|
||||||
);
|
|
||||||
let params = vec![fn_type_fut!(Context, $from)];
|
|
||||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
|
||||||
node_io
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
macro_rules! convert_node {
|
macro_rules! convert_node {
|
||||||
(from: $from:ty, to: numbers) => {{
|
(from: $from:ty, to: numbers) => {{
|
||||||
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||||
convert_node!(from: $from, to: f32),
|
convert_node!(from: $from, to: f32),
|
||||||
convert_node!(from: $from, to: f64),
|
convert_node!(from: $from, to: f64),
|
||||||
convert_node!(from: $from, to: i8),
|
convert_node!(from: $from, to: i8),
|
||||||
@@ -427,7 +254,7 @@ mod node_registry_macros {
|
|||||||
x
|
x
|
||||||
}};
|
}};
|
||||||
(from: numbers, to: $to:ty) => {{
|
(from: numbers, to: $to:ty) => {{
|
||||||
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||||
convert_node!(from: f32, to: $to),
|
convert_node!(from: f32, to: $to),
|
||||||
convert_node!(from: f64, to: $to),
|
convert_node!(from: f64, to: $to),
|
||||||
convert_node!(from: i8, to: $to),
|
convert_node!(from: i8, to: $to),
|
||||||
@@ -448,37 +275,113 @@ mod node_registry_macros {
|
|||||||
(from: $from:ty, to: $to:ty) => {
|
(from: $from:ty, to: $to:ty) => {
|
||||||
convert_node!(from: $from, to: $to, converter: ())
|
convert_node!(from: $from, to: $to, converter: ())
|
||||||
};
|
};
|
||||||
|
(from: $from:ty, to: $to:ty, converter: $convert:ty, async) => {
|
||||||
|
(
|
||||||
|
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||||
|
RegistryEntry {
|
||||||
|
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||||
|
io: NodeIOTypes::new(
|
||||||
|
concrete!(Context),
|
||||||
|
core_types::registry::record_type::<$to>(),
|
||||||
|
vec![
|
||||||
|
core_types::registry::record_source_type::<$from>(),
|
||||||
|
core_types::registry::record_source_type::<$convert>(),
|
||||||
|
core_types::registry::record_source_type::<RuntimeHandle>(),
|
||||||
|
core_types::registry::record_source_type::<SourceId>(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
constructor: |inputs| {
|
||||||
|
if inputs.len() != 4 {
|
||||||
|
return Err(ConstructionError::Arity { expected: 4, got: inputs.len() });
|
||||||
|
}
|
||||||
|
let mut inputs = inputs.into_iter();
|
||||||
|
let mut claim = || {
|
||||||
|
let handle = inputs.next().unwrap();
|
||||||
|
let layout = handle.layout().clone();
|
||||||
|
Ok::<_, ConstructionError>((handle, layout))
|
||||||
|
};
|
||||||
|
let (value, value_layout) = claim()?;
|
||||||
|
let (converter, converter_layout) = claim()?;
|
||||||
|
let (runtime, runtime_layout) = claim()?;
|
||||||
|
let (source, source_layout) = claim()?;
|
||||||
|
let node = graphene_std::ops::ConvertAsyncNode::<$to, _, _, _, _, $from, $convert>::new(
|
||||||
|
value.downcast_record::<$from>()?,
|
||||||
|
converter.downcast_record::<$convert>()?,
|
||||||
|
runtime.downcast_record::<RuntimeHandle>()?,
|
||||||
|
source.downcast_record::<SourceId>()?,
|
||||||
|
&value_layout,
|
||||||
|
&converter_layout,
|
||||||
|
&runtime_layout,
|
||||||
|
&source_layout,
|
||||||
|
);
|
||||||
|
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
};
|
||||||
(from: $from:ty, to: $to:ty, converter: $convert:ty) => {
|
(from: $from:ty, to: $to:ty, converter: $convert:ty) => {
|
||||||
(
|
(
|
||||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||||
|mut args| {
|
RegistryEntry {
|
||||||
Box::pin(async move {
|
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||||
let mut args = args.drain(..);
|
io: NodeIOTypes::new(
|
||||||
let node = graphene_std::ops::ConvertNode::new(
|
concrete!(Context),
|
||||||
graphene_std::any::downcast_node::<Context, $from>(args.next().expect("Convert node did not get first argument")),
|
core_types::registry::record_type::<$to>(),
|
||||||
graphene_std::any::downcast_node::<Context, $convert>(args.next().expect("Convert node did not get converter argument")),
|
vec![core_types::registry::record_source_type::<$from>(), core_types::registry::record_source_type::<$convert>()],
|
||||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
),
|
||||||
|
constructor: |inputs| {
|
||||||
|
if inputs.len() != 2 {
|
||||||
|
return Err(ConstructionError::Arity { expected: 2, got: inputs.len() });
|
||||||
|
}
|
||||||
|
let mut inputs = inputs.into_iter();
|
||||||
|
let value = inputs.next().unwrap();
|
||||||
|
let value_layout = value.layout().clone();
|
||||||
|
let converter = inputs.next().unwrap();
|
||||||
|
let converter_layout = converter.layout().clone();
|
||||||
|
let node = graphene_std::ops::ConvertNode::<$to, _, _, $from, $convert>::new(
|
||||||
|
value.downcast_record::<$from>()?,
|
||||||
|
converter.downcast_record::<$convert>()?,
|
||||||
|
&value_layout,
|
||||||
|
&converter_layout,
|
||||||
);
|
);
|
||||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||||
Box::new(any) as TypeErasedBox
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
{
|
|
||||||
let node = graphene_std::ops::ConvertNode::new(
|
|
||||||
|
|
||||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
|
||||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $convert> + Send>>>::new(),
|
|
||||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
|
||||||
);
|
|
||||||
let params = vec![fn_type_fut!(Context, $from), fn_type_fut!(Context, $convert)];
|
|
||||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
|
||||||
node_io
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) use async_node;
|
|
||||||
pub(crate) use convert_node;
|
pub(crate) use convert_node;
|
||||||
pub(crate) use into_node;
|
pub(crate) use into_node;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use graphene_std::Type;
|
||||||
|
|
||||||
|
fn is_record_edge(ty: &Type) -> bool {
|
||||||
|
match ty {
|
||||||
|
Type::Fn(_, output) => matches!(&**output, Type::Record(_)),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One input kind: every row consumes and produces records. A plain
|
||||||
|
/// io type here would need a bridge adapter, and those are gone.
|
||||||
|
#[test]
|
||||||
|
fn every_registry_row_is_record_typed() {
|
||||||
|
let mut plain: Vec<String> = Vec::new();
|
||||||
|
for (id, entries) in NODE_REGISTRY.iter() {
|
||||||
|
for entry in entries {
|
||||||
|
let plain_output = !matches!(entry.io.return_value, Type::Record(_));
|
||||||
|
let plain_inputs: Vec<usize> = entry.io.inputs.iter().enumerate().filter(|(_, ty)| !is_record_edge(ty)).map(|(index, _)| index).collect();
|
||||||
|
if plain_output || !plain_inputs.is_empty() {
|
||||||
|
plain.push(format!("{} plain_output={plain_output} plain_inputs={plain_inputs:?}", id.as_str()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
plain.sort();
|
||||||
|
assert!(plain.is_empty(), "plain io remains in the registry:\n{}", plain.join("\n"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,21 +29,15 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
|||||||
DocumentNode {
|
DocumentNode {
|
||||||
call_argument: concrete!(Context),
|
call_argument: concrete!(Context),
|
||||||
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate_leveled::IDENTIFIER),
|
||||||
context_features: graphene_std::ContextDependencies {
|
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
|
||||||
extract: ContextFeatures::VARARGS,
|
|
||||||
inject: ContextFeatures::INDEX,
|
|
||||||
},
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
call_argument: concrete!(Context),
|
call_argument: concrete!(Context),
|
||||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
|
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||||
context_features: graphene_std::ContextDependencies {
|
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
|
||||||
inject: ContextFeatures::empty(),
|
|
||||||
},
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
@@ -54,20 +48,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
|||||||
NodeInput::node(NodeId(1), 0),
|
NodeInput::node(NodeId(1), 0),
|
||||||
],
|
],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||||
context_features: graphene_std::ContextDependencies {
|
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
|
||||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
|
||||||
inject: ContextFeatures::VARARGS,
|
|
||||||
},
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
call_argument: concrete!(Context),
|
call_argument: concrete!(Context),
|
||||||
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
|
||||||
context_features: graphene_std::ContextDependencies {
|
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
|
||||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
|
||||||
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
|
||||||
},
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
@@ -77,21 +65,18 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
|||||||
NodeInput::node(NodeId(3), 0),
|
NodeInput::node(NodeId(3), 0),
|
||||||
],
|
],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
|
||||||
context_features: graphene_std::ContextDependencies {
|
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
|
||||||
inject: ContextFeatures::empty(),
|
|
||||||
},
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
call_argument: concrete!(graphene_std::application_io::RenderConfig),
|
call_argument: concrete!(Context),
|
||||||
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
||||||
context_features: graphene_std::ContextDependencies {
|
|
||||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||||
extract: ContextFeatures::INDEX,
|
context_features: graphene_std::ContextDependencies::new(
|
||||||
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
ContextFeatures::INDEX | ContextFeatures::VARARGS,
|
||||||
},
|
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||||
|
),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
@@ -114,7 +99,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(&PlatformEditorApi)))];
|
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(std::sync::Arc<PlatformEditorApi>)))];
|
||||||
|
|
||||||
NodeNetwork {
|
NodeNetwork {
|
||||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
|
|||||||
# Local dependencies
|
# Local dependencies
|
||||||
dyn-any = { workspace = true }
|
dyn-any = { workspace = true }
|
||||||
core-types = { workspace = true }
|
core-types = { workspace = true }
|
||||||
|
graphene-hash = { workspace = true }
|
||||||
vector-types = { workspace = true }
|
vector-types = { workspace = true }
|
||||||
text-nodes = { workspace = true }
|
text-nodes = { workspace = true }
|
||||||
graphene-resource = { workspace = true }
|
graphene-resource = { workspace = true }
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ pub trait ApplicationIo {
|
|||||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
fn gpu_executor_arc(&self) -> Option<Arc<Self::Executor>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>;
|
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,6 +34,10 @@ impl<T: ApplicationIo> ApplicationIo for &T {
|
|||||||
(**self).gpu_executor()
|
(**self).gpu_executor()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn gpu_executor_arc(&self) -> Option<Arc<T::Executor>> {
|
||||||
|
(**self).gpu_executor_arc()
|
||||||
|
}
|
||||||
|
|
||||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
||||||
(**self).load_resource(hash)
|
(**self).load_resource(hash)
|
||||||
}
|
}
|
||||||
@@ -54,7 +61,7 @@ pub trait GetEditorPreferences {
|
|||||||
fn max_render_region_area(&self) -> u32;
|
fn max_render_region_area(&self) -> u32;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
|
||||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub enum ExportFormat {
|
pub enum ExportFormat {
|
||||||
#[default]
|
#[default]
|
||||||
@@ -62,14 +69,14 @@ pub enum ExportFormat {
|
|||||||
Raster,
|
Raster,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub struct TimingInformation {
|
pub struct TimingInformation {
|
||||||
pub time: f64,
|
pub time: f64,
|
||||||
pub animation_time: Duration,
|
pub animation_time: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub struct RenderConfig {
|
pub struct RenderConfig {
|
||||||
pub viewport: Footprint,
|
pub viewport: Footprint,
|
||||||
@@ -105,6 +112,7 @@ pub struct EditorApi<Io> {
|
|||||||
pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>,
|
pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>,
|
||||||
/// Editor preferences made available to the graph through the `PlatformEditorApi`.
|
/// Editor preferences made available to the graph through the `PlatformEditorApi`.
|
||||||
pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>,
|
pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>,
|
||||||
|
pub runtime: core_types::runtime::RuntimeHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io> Eq for EditorApi<Io> {}
|
impl<Io> Eq for EditorApi<Io> {}
|
||||||
@@ -115,6 +123,7 @@ impl<Io: Default> Default for EditorApi<Io> {
|
|||||||
application_io: None,
|
application_io: None,
|
||||||
node_graph_message_sender: Box::new(Logger),
|
node_graph_message_sender: Box::new(Logger),
|
||||||
editor_preferences: Box::new(DummyPreferences),
|
editor_preferences: Box::new(DummyPreferences),
|
||||||
|
runtime: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,785 @@
|
|||||||
|
use std::any::TypeId;
|
||||||
|
use std::cell::UnsafeCell;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::mem::MaybeUninit;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
|
||||||
|
/// addressable and generations run out after ~3 days of 60fps resets.
|
||||||
|
const OFFSET_BITS: u32 = 40;
|
||||||
|
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
|
||||||
|
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
|
||||||
|
|
||||||
|
/// Out of the encodable range, so no handle, including `NULL`, matches it.
|
||||||
|
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
|
||||||
|
|
||||||
|
pub struct Arena {
|
||||||
|
generation: AtomicU64,
|
||||||
|
offset: AtomicUsize,
|
||||||
|
buf: Box<[UnsafeCell<MaybeUninit<u8>>]>,
|
||||||
|
drops: Mutex<Vec<DropEntry>>,
|
||||||
|
/// Set by a refused reservation and cleared by [`Arena::reset`], so a region
|
||||||
|
/// no evaluation resets can be seen to need one.
|
||||||
|
exhausted: AtomicBool,
|
||||||
|
/// Heap the parked payloads keep alive, which occupancy does not measure:
|
||||||
|
/// a park costs one pointer in the arena and owns its content outside it.
|
||||||
|
retained_heap: AtomicUsize,
|
||||||
|
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
|
||||||
|
/// the header's address in the receiving arena and the moved type's key, so
|
||||||
|
/// a payload two records share is moved once and a mistyped sharer is
|
||||||
|
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
|
||||||
|
/// generation.
|
||||||
|
forwarded: Mutex<HashMap<usize, (usize, TypeId)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Arena {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Arena").field("generation", &self.generation).field("size", &self.buf.len()).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct DropEntry {
|
||||||
|
offset: usize,
|
||||||
|
/// The parked payload's static-type key, `None` where the park was
|
||||||
|
/// allocated without one and so never moves.
|
||||||
|
type_of: Option<TypeId>,
|
||||||
|
drop_fn: unsafe fn(*mut u8),
|
||||||
|
/// The park glue's estimate of the heap this payload owns, 0 where the
|
||||||
|
/// glue cannot measure it, so the counter is a lower bound.
|
||||||
|
retained: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The glue a tombstoned entry carries: its payload was moved to another arena,
|
||||||
|
/// which now owns the obligation.
|
||||||
|
unsafe fn inert(_: *mut u8) {}
|
||||||
|
|
||||||
|
/// The entry parking `offset`, `None` where the arena holds no obligation for
|
||||||
|
/// it. Entries are pushed in reserve order, which is offset order, so the
|
||||||
|
/// search is exact; the scan covers a push order that concurrency interleaved.
|
||||||
|
fn entry_at(entries: &[DropEntry], offset: usize) -> Option<usize> {
|
||||||
|
let probe = entries.partition_point(|entry| entry.offset < offset);
|
||||||
|
match entries.get(probe).is_some_and(|entry| entry.offset == offset) {
|
||||||
|
true => Some(probe),
|
||||||
|
false => entries.iter().rposition(|entry| entry.offset == offset),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
|
||||||
|
// only by its allocating caller before publication, and cross-thread hand-off is
|
||||||
|
// ordered by the Release/Acquire pair on the published handle word. Payloads are
|
||||||
|
// `Send + Sync` by the bound on every allocating method.
|
||||||
|
unsafe impl Sync for Arena {}
|
||||||
|
unsafe impl Send for Arena {}
|
||||||
|
|
||||||
|
impl std::panic::UnwindSafe for Arena {}
|
||||||
|
impl std::panic::RefUnwindSafe for Arena {}
|
||||||
|
|
||||||
|
/// Shared by all arenas, so a foreign handle misses like a stale one.
|
||||||
|
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||||
|
|
||||||
|
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
|
||||||
|
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
|
||||||
|
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
|
||||||
|
fn next_generation() -> Option<u64> {
|
||||||
|
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||||
|
(generation <= GENERATION_MASK).then_some(generation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewinds the shared generation counter so previously issued values are reused.
|
||||||
|
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
|
||||||
|
/// check, which is a debugging aid rather than a guarantee.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
///
|
||||||
|
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
|
||||||
|
/// every [`Arena`] is not sufficient, since nodes also hold handles in
|
||||||
|
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
|
||||||
|
/// concurrently either, since the live check and the rewind are separate steps.
|
||||||
|
pub unsafe fn reset_generation_counter() -> bool {
|
||||||
|
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
NEXT_GENERATION.store(1, Ordering::Release);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Arena {
|
||||||
|
pub fn new(capacity: usize) -> Option<Self> {
|
||||||
|
let generation = next_generation()?;
|
||||||
|
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
|
||||||
|
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||||
|
Some(Self {
|
||||||
|
generation: AtomicU64::new(generation),
|
||||||
|
offset: AtomicUsize::new(0),
|
||||||
|
buf,
|
||||||
|
drops: Mutex::new(Vec::new()),
|
||||||
|
exhausted: AtomicBool::new(false),
|
||||||
|
retained_heap: AtomicUsize::new(0),
|
||||||
|
forwarded: Mutex::new(HashMap::new()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An arena that refuses every allocation and resolves no handle, so a caller that
|
||||||
|
/// cannot fail can degrade instead of propagating exhaustion.
|
||||||
|
pub fn parked() -> Self {
|
||||||
|
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||||
|
Self {
|
||||||
|
generation: AtomicU64::new(PARKED_GENERATION),
|
||||||
|
offset: AtomicUsize::new(0),
|
||||||
|
buf: Box::new([]),
|
||||||
|
drops: Mutex::new(Vec::new()),
|
||||||
|
exhausted: AtomicBool::new(false),
|
||||||
|
retained_heap: AtomicUsize::new(0),
|
||||||
|
forwarded: Mutex::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a reservation has been refused since the last [`Arena::reset`].
|
||||||
|
pub fn exhausted(&self) -> bool {
|
||||||
|
self.exhausted.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generation(&self) -> u64 {
|
||||||
|
self.generation.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes handed out since the last [`Arena::reset`], including alignment
|
||||||
|
/// padding, so a caller can flush at a boundary before a refusal.
|
||||||
|
pub fn occupancy(&self) -> usize {
|
||||||
|
self.offset.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn capacity(&self) -> usize {
|
||||||
|
self.buf.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The heap the parked payloads own, summed from the park glue's hints.
|
||||||
|
/// A lower bound: glue that cannot measure its payload contributes 0.
|
||||||
|
pub fn retained_heap(&self) -> usize {
|
||||||
|
self.retained_heap.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `ptr` addresses this arena's backbone, which is the provenance
|
||||||
|
/// question a promote asks of every parked reference.
|
||||||
|
pub fn contains(&self, ptr: *const u8) -> bool {
|
||||||
|
let base = self.base() as usize;
|
||||||
|
(ptr as usize).wrapping_sub(base) < self.buf.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base(&self) -> *mut u8 {
|
||||||
|
self.buf.as_ptr() as *mut u8
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reserve(&self, size: usize, align: usize) -> Option<usize> {
|
||||||
|
debug_assert!(align.is_power_of_two());
|
||||||
|
let base = self.base() as usize;
|
||||||
|
let mut start = 0;
|
||||||
|
let reserved = self
|
||||||
|
.offset
|
||||||
|
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
|
||||||
|
// Alignment is computed on the absolute address; the backbone
|
||||||
|
// allocation itself has no alignment guarantee.
|
||||||
|
let addr = (base.checked_add(current)?.checked_add(align - 1)?) & !(align - 1);
|
||||||
|
start = addr - base;
|
||||||
|
let end = start.checked_add(size)?;
|
||||||
|
(end <= self.buf.len()).then_some(end)
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
{
|
||||||
|
static ARENA_TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||||
|
if *ARENA_TRACE.get_or_init(|| std::env::var_os("GRAPHENE_ARENA_DEBUG").is_some()) {
|
||||||
|
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||||
|
let count = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||||
|
if reserved.is_none() {
|
||||||
|
eprintln!("arena> EXHAUSTED after {count} allocations, wanted {size} bytes\n{}", std::backtrace::Backtrace::force_capture());
|
||||||
|
} else if count.is_multiple_of(20000) {
|
||||||
|
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reserved.is_none() {
|
||||||
|
self.exhausted.store(true, Ordering::Relaxed);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(start)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
|
||||||
|
self.alloc_sized(value, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
|
||||||
|
/// which the region's own occupancy cannot see.
|
||||||
|
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
|
||||||
|
self.alloc_stamped(value, retained, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Arena::alloc_sized`] stamping the park's static-type key, which is what
|
||||||
|
/// [`Arena::move_park`] matches on, so only a park allocated here can move.
|
||||||
|
pub fn alloc_sized_keyed<T: Send + Sync + dyn_any::StaticTypeSized>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
|
||||||
|
self.alloc_stamped(value, retained, Some(TypeId::of::<T::Static>()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Arena::alloc_sized_keyed`] for park glue already holding the element's
|
||||||
|
/// static form, which projects the key from the element type instead of
|
||||||
|
/// from the value's own. Crate-private: a wrong key mistypes a move.
|
||||||
|
pub(crate) fn alloc_sized_as<T: Send + Sync>(&self, value: T, retained: usize, type_of: TypeId) -> Option<(&T, ArenaWeak<T>)> {
|
||||||
|
self.alloc_stamped(value, retained, Some(type_of))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alloc_stamped<T: Send + Sync>(&self, value: T, retained: usize, type_of: Option<TypeId>) -> Option<(&T, ArenaWeak<T>)> {
|
||||||
|
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
|
||||||
|
// Built before the write so an unencodable offset drops `value` here
|
||||||
|
// rather than stranding it in the arena without drop glue.
|
||||||
|
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||||
|
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||||
|
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||||
|
unsafe { ptr.write(value) };
|
||||||
|
if std::mem::needs_drop::<T>() {
|
||||||
|
unsafe fn glue<T>(p: *mut u8) {
|
||||||
|
unsafe { p.cast::<T>().drop_in_place() }
|
||||||
|
}
|
||||||
|
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
|
||||||
|
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
|
||||||
|
Some((unsafe { &*ptr }, weak))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the payload at `src` out of this arena and into `dst`: the header's
|
||||||
|
/// own bytes are copied, its drop obligation is pushed onto `dst` with the
|
||||||
|
/// `retained` hint, and the entry here is tombstoned in place, its glue
|
||||||
|
/// swapped for [`inert`] so the reset costs nothing per entry to honour it.
|
||||||
|
/// The heap the payload owns is neither copied nor freed; ownership travels
|
||||||
|
/// with the obligation and is discharged by `dst`'s flush.
|
||||||
|
///
|
||||||
|
/// THE MOVE'S OWNERSHIP CONTRACT: the source header keeps its bytes and
|
||||||
|
/// stays readable to this generation's remaining sharers, but it owns
|
||||||
|
/// nothing, so no read of it may outlive `dst`'s flush. A payload moved
|
||||||
|
/// once is not moved again: its recorded destination is returned, so a
|
||||||
|
/// fan-out sharer's second move reaches the one header and the obligation
|
||||||
|
/// is never duplicated.
|
||||||
|
///
|
||||||
|
/// `dst` is credited `retained`, which is what a clone of the payload would
|
||||||
|
/// have credited it, and this arena is debited what its own park recorded,
|
||||||
|
/// so neither counter reads worse than it did before the move.
|
||||||
|
///
|
||||||
|
/// The move republishes the payload at `T::Static`, which is the key both
|
||||||
|
/// [`Arena::alloc_sized_keyed`] and this stamp, so a park and its move
|
||||||
|
/// project the type exactly once each and agree by construction.
|
||||||
|
///
|
||||||
|
/// `None` where `src` is not this arena's park keyed to `T::Static`, where
|
||||||
|
/// the type is zero-sized (whose parks share an offset and so cannot be
|
||||||
|
/// told apart), or where `dst` refused the header.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `src` must address a live `T`, and `T` must own all of its content: the
|
||||||
|
/// moved header may reference no storage of this arena, which is also what
|
||||||
|
/// lets the payload be republished at `T::Static`. The key settles the
|
||||||
|
/// type, so the caller owes no size or identity argument beyond those two.
|
||||||
|
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T::Static>
|
||||||
|
where
|
||||||
|
T::Static: Send + Sync,
|
||||||
|
{
|
||||||
|
(size_of::<T::Static>() != 0).then_some(())?;
|
||||||
|
let offset = (src as usize).checked_sub(self.base() as usize)?;
|
||||||
|
(offset < self.buf.len()).then_some(())?;
|
||||||
|
let type_of = TypeId::of::<T::Static>();
|
||||||
|
let mut forwarded = self.forwarded.lock().unwrap();
|
||||||
|
if let Some(&(moved, moved_type)) = forwarded.get(&offset) {
|
||||||
|
(moved_type == type_of).then_some(())?;
|
||||||
|
return Some(moved as *const T::Static);
|
||||||
|
}
|
||||||
|
let mut entries = self.drops.lock().unwrap();
|
||||||
|
let entry = entry_at(&entries, offset)?;
|
||||||
|
(entries[entry].type_of == Some(type_of)).then_some(())?;
|
||||||
|
let slot = dst.alloc_scratch::<T::Static>(1)?;
|
||||||
|
let target = slot.as_mut_ptr().cast::<T::Static>();
|
||||||
|
// SAFETY: the caller's contract on `src`, into a freshly reserved,
|
||||||
|
// aligned, unaliased slot of the same type.
|
||||||
|
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T::Static>(), target, 1) };
|
||||||
|
let parked = std::mem::replace(&mut entries[entry].retained, 0);
|
||||||
|
entries[entry].drop_fn = inert;
|
||||||
|
drop(entries);
|
||||||
|
unsafe fn glue<T>(p: *mut u8) {
|
||||||
|
unsafe { p.cast::<T>().drop_in_place() }
|
||||||
|
}
|
||||||
|
dst.drops.lock().unwrap().push(DropEntry {
|
||||||
|
offset: target as usize - dst.base() as usize,
|
||||||
|
type_of: Some(type_of),
|
||||||
|
drop_fn: glue::<T::Static>,
|
||||||
|
retained,
|
||||||
|
});
|
||||||
|
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||||
|
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
|
||||||
|
forwarded.insert(offset, (target as usize, type_of));
|
||||||
|
Some(target.cast_const())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
|
||||||
|
let buf = self.alloc_scratch::<T>(src.len())?;
|
||||||
|
for (slot, &value) in buf.iter_mut().zip(src) {
|
||||||
|
slot.write(value);
|
||||||
|
}
|
||||||
|
// SAFETY: every lane written above from `src`.
|
||||||
|
Some(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<T>(), src.len()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not drop-tracked: callers must either consume every written lane or
|
||||||
|
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
|
||||||
|
#[allow(clippy::mut_from_ref)]
|
||||||
|
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||||
|
let size = size_of::<T>().checked_mul(len)?;
|
||||||
|
let offset = self.reserve(size, align_of::<T>())?;
|
||||||
|
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||||
|
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
|
||||||
|
// `&mut self`, so the slice cannot outlive the generation.
|
||||||
|
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The generation-checked handle for a region this arena holds, `None` for
|
||||||
|
/// a pointer from anywhere else. The handle keeps the region's provenance,
|
||||||
|
/// so a cache stores one where it would otherwise launder an address.
|
||||||
|
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
|
||||||
|
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
|
||||||
|
(offset < self.buf.len()).then_some(())?;
|
||||||
|
ArenaWeak::new(self.generation(), offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
|
||||||
|
/// where every handle misses and further allocation is refused.
|
||||||
|
///
|
||||||
|
/// A park [`Arena::move_park`] handed to another arena carries [`inert`]
|
||||||
|
/// glue and a zeroed hint, so it costs the loop nothing beyond the call it
|
||||||
|
/// would have made anyway.
|
||||||
|
pub fn reset(&mut self) -> bool {
|
||||||
|
let base = self.base();
|
||||||
|
let entries = std::mem::take(self.drops.get_mut().unwrap());
|
||||||
|
self.forwarded.get_mut().unwrap().clear();
|
||||||
|
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||||
|
for entry in entries.into_iter().rev() {
|
||||||
|
// SAFETY: registered at alloc time; insert-only means the region was
|
||||||
|
// never overwritten within this generation.
|
||||||
|
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||||
|
// Decremented as each payload's heap is freed, so an unwinding reset
|
||||||
|
// leaves the counter matching what is still parked.
|
||||||
|
let retained = self.retained_heap.get_mut();
|
||||||
|
*retained = retained.saturating_sub(entry.retained);
|
||||||
|
}
|
||||||
|
*self.offset.get_mut() = 0;
|
||||||
|
*self.exhausted.get_mut() = false;
|
||||||
|
let Some(generation) = next_generation() else { return false };
|
||||||
|
self.generation.store(generation, Ordering::Release);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Arena {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.reset();
|
||||||
|
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ArenaWeak<T> {
|
||||||
|
word: u64,
|
||||||
|
_marker: PhantomData<fn() -> T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Clone for ArenaWeak<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> Copy for ArenaWeak<T> {}
|
||||||
|
|
||||||
|
impl<T> ArenaWeak<T> {
|
||||||
|
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
|
||||||
|
|
||||||
|
/// `None` once either field leaves its encodable range, so an oversized or parked
|
||||||
|
/// arena refuses to hand out a handle rather than truncating it to a live address.
|
||||||
|
fn new(generation: u64, offset: usize) -> Option<Self> {
|
||||||
|
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
|
||||||
|
(generation <= GENERATION_MASK).then_some(Self {
|
||||||
|
word: (generation << OFFSET_BITS) | offset,
|
||||||
|
_marker: PhantomData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
|
||||||
|
let generation = self.word >> OFFSET_BITS;
|
||||||
|
if generation != arena.generation() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let offset = (self.word & OFFSET_MASK) as usize;
|
||||||
|
// SAFETY: same generation means the entry was fully written before its
|
||||||
|
// word was published (Release) and cannot move or be overwritten within
|
||||||
|
// a generation (insert-only); the Acquire load that produced this word
|
||||||
|
// ordered the payload writes.
|
||||||
|
Some(unsafe { &*arena.base().add(offset).cast::<T>() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ArenaCell<T> {
|
||||||
|
word: AtomicU64,
|
||||||
|
_marker: PhantomData<fn() -> T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Clone for ArenaCell<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
word: AtomicU64::new(self.word.load(Ordering::Acquire)),
|
||||||
|
_marker: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> std::fmt::Debug for ArenaCell<T> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("ArenaCell").field("word", &self.word.load(Ordering::Relaxed)).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Default for ArenaCell<T> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
word: AtomicU64::new(0),
|
||||||
|
_marker: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> ArenaCell<T> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load<'e>(&self, arena: &'e Arena) -> Option<&'e T> {
|
||||||
|
let weak = ArenaWeak::<T> {
|
||||||
|
word: self.word.load(Ordering::Acquire),
|
||||||
|
_marker: PhantomData,
|
||||||
|
};
|
||||||
|
weak.upgrade(arena)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn store(&self, weak: ArenaWeak<T>) {
|
||||||
|
self.word.store(weak.word, Ordering::Release);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::PoisonError;
|
||||||
|
use std::sync::atomic::AtomicU32;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn alloc_upgrade_reset_miss() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
let cell = ArenaCell::new();
|
||||||
|
let (value, weak) = arena.alloc(41u32).unwrap();
|
||||||
|
assert_eq!(*value, 41);
|
||||||
|
cell.store(weak);
|
||||||
|
assert_eq!(cell.load(&arena), Some(&41));
|
||||||
|
arena.reset();
|
||||||
|
assert_eq!(cell.load(&arena), None, "stale handle must miss");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn capacity_survives_reset() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
|
||||||
|
for _ in 0..10 {
|
||||||
|
for _ in 0..16 {
|
||||||
|
assert!(arena.alloc(0u32).is_some());
|
||||||
|
}
|
||||||
|
assert!(arena.alloc(0u32).is_none(), "exhausted within generation");
|
||||||
|
arena.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn panics_leave_the_arena_coherent() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
|
||||||
|
assert_ref_unwind_safe::<Arena>();
|
||||||
|
|
||||||
|
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||||
|
struct Probe(#[allow(dead_code)] String);
|
||||||
|
impl Drop for Probe {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
let cell = ArenaCell::new();
|
||||||
|
let result = std::panic::catch_unwind(|| {
|
||||||
|
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
|
||||||
|
cell.store(weak);
|
||||||
|
panic!("mid-eval");
|
||||||
|
});
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(cell.load(&arena).is_some(), "the generation is still live after the caught panic");
|
||||||
|
arena.reset();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "reset reclaims pre-panic allocations");
|
||||||
|
assert!(cell.load(&arena).is_none(), "the bump kills stale handles");
|
||||||
|
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_panicking_destructor_leaves_no_resolvable_handle() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
struct Bomb;
|
||||||
|
impl Drop for Bomb {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
panic!("payload destructor");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
let cell = ArenaCell::new();
|
||||||
|
let (_, weak) = arena.alloc(Bomb).unwrap();
|
||||||
|
cell.store(weak);
|
||||||
|
|
||||||
|
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
|
||||||
|
assert!(unwound.is_err(), "the panic must propagate out of reset");
|
||||||
|
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
|
||||||
|
/// is never observed by a concurrently constructing test.
|
||||||
|
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
let (_, weak) = arena.alloc(41u32).unwrap();
|
||||||
|
|
||||||
|
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
|
||||||
|
assert!(!arena.reset(), "an exhausted counter must report failure");
|
||||||
|
NEXT_GENERATION.store(restore, Ordering::Relaxed);
|
||||||
|
|
||||||
|
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
|
||||||
|
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
|
||||||
|
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_generation_counter_rewinds_only_without_live_arenas() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let arena = Arena::new(64).unwrap();
|
||||||
|
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
|
||||||
|
drop(arena);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn handles_do_not_upgrade_against_a_foreign_arena() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let first = Arena::new(1024).unwrap();
|
||||||
|
let second = Arena::new(1024).unwrap();
|
||||||
|
let (_, weak) = first.alloc(41u32).unwrap();
|
||||||
|
assert_eq!(weak.upgrade(&first), Some(&41));
|
||||||
|
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
|
||||||
|
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reset_drops_dependents_before_their_dependencies() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
|
||||||
|
struct Probe(u32);
|
||||||
|
impl Drop for Probe {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
ORDER.lock().unwrap().push(self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
for id in 0..3 {
|
||||||
|
arena.alloc(Probe(id)).unwrap();
|
||||||
|
}
|
||||||
|
arena.reset();
|
||||||
|
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sized_parks_account_for_their_retained_heap() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
assert_eq!(arena.retained_heap(), 0);
|
||||||
|
|
||||||
|
let owned = String::from("retained by the park");
|
||||||
|
let length = owned.len();
|
||||||
|
arena.alloc_sized(owned, length).unwrap();
|
||||||
|
assert_eq!(arena.retained_heap(), length, "the park's hint reaches the counter");
|
||||||
|
|
||||||
|
arena.alloc(String::from("unmeasured")).unwrap();
|
||||||
|
assert_eq!(arena.retained_heap(), length, "an unmeasured park contributes nothing");
|
||||||
|
|
||||||
|
arena.reset();
|
||||||
|
assert_eq!(arena.retained_heap(), 0, "the flush frees every parked payload");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_moved_park_carries_its_heap_and_its_obligation() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut transient = Arena::new(1024).unwrap();
|
||||||
|
let mut persistent = Arena::new(1024).unwrap();
|
||||||
|
|
||||||
|
let owned = String::from("moved, never cloned");
|
||||||
|
let length = owned.len();
|
||||||
|
let heap = owned.as_ptr();
|
||||||
|
let (parked, _) = transient.alloc_sized_keyed(owned, length).unwrap();
|
||||||
|
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||||
|
|
||||||
|
let moved = unsafe { transient.move_park::<String>(src, &persistent, length) }.unwrap();
|
||||||
|
assert_eq!(unsafe { &*moved }.as_ptr(), heap, "the move copies the header and leaves the heap where it was");
|
||||||
|
assert!(persistent.contains(moved.cast()), "the header lands in the receiving arena");
|
||||||
|
assert_eq!(transient.retained_heap(), 0, "the parking arena gives the hint up");
|
||||||
|
assert_eq!(persistent.retained_heap(), length, "and the receiving arena takes it");
|
||||||
|
|
||||||
|
transient.reset();
|
||||||
|
assert_eq!(unsafe { &*moved }, "moved, never cloned", "the parking arena's reset leaves a moved payload alone");
|
||||||
|
persistent.reset();
|
||||||
|
assert_eq!(persistent.retained_heap(), 0, "the receiving flush frees it");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_park_two_records_share_moves_once_and_frees_once() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||||
|
struct Probe(#[allow(dead_code)] String);
|
||||||
|
unsafe impl dyn_any::StaticType for Probe {
|
||||||
|
type Static = Probe;
|
||||||
|
}
|
||||||
|
impl Drop for Probe {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DROPS.store(0, Ordering::Relaxed);
|
||||||
|
let mut transient = Arena::new(1024).unwrap();
|
||||||
|
let mut persistent = Arena::new(1024).unwrap();
|
||||||
|
|
||||||
|
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
|
||||||
|
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||||
|
let first = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
|
||||||
|
let second = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
|
||||||
|
assert_eq!(first, second, "the second move forwards to the header the first wrote");
|
||||||
|
assert_eq!(persistent.retained_heap(), 21, "the hint transfers once, not once per sharer");
|
||||||
|
|
||||||
|
transient.reset();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 0, "a tombstoned entry is skipped by its arena's reset");
|
||||||
|
persistent.reset();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "the flush that owns the obligation frees it exactly once");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_move_refuses_a_mistyped_park_and_its_forwarding() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
struct Owner(#[allow(dead_code)] String);
|
||||||
|
unsafe impl dyn_any::StaticType for Owner {
|
||||||
|
type Static = Owner;
|
||||||
|
}
|
||||||
|
/// Owner's layout exactly, so only the type key tells the two apart.
|
||||||
|
struct Twin(#[allow(dead_code)] String);
|
||||||
|
unsafe impl dyn_any::StaticType for Twin {
|
||||||
|
type Static = Twin;
|
||||||
|
}
|
||||||
|
let mut transient = Arena::new(1024).unwrap();
|
||||||
|
let mut persistent = Arena::new(1024).unwrap();
|
||||||
|
|
||||||
|
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
|
||||||
|
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||||
|
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "a park of another type of the same size is refused");
|
||||||
|
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
|
||||||
|
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
|
||||||
|
|
||||||
|
let (unkeyed, _) = transient.alloc(Owner(String::from("an unkeyed park"))).unwrap();
|
||||||
|
let src = std::ptr::from_ref(unkeyed).cast::<u8>();
|
||||||
|
assert!(unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.is_none(), "a park allocated without a key never moves");
|
||||||
|
|
||||||
|
transient.reset();
|
||||||
|
persistent.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_forwarding_map_lives_one_generation() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||||
|
struct Probe(#[allow(dead_code)] String);
|
||||||
|
unsafe impl dyn_any::StaticType for Probe {
|
||||||
|
type Static = Probe;
|
||||||
|
}
|
||||||
|
impl Drop for Probe {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DROPS.store(0, Ordering::Relaxed);
|
||||||
|
let mut transient = Arena::new(1024).unwrap();
|
||||||
|
let mut persistent = Arena::new(1024).unwrap();
|
||||||
|
|
||||||
|
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("first generation")), 16).unwrap();
|
||||||
|
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||||
|
unsafe { transient.move_park::<Probe>(src, &persistent, 16) }.unwrap();
|
||||||
|
assert_eq!(transient.forwarded.lock().unwrap().len(), 1, "the move tombstoned the entry it left");
|
||||||
|
|
||||||
|
transient.reset();
|
||||||
|
assert!(transient.forwarded.lock().unwrap().is_empty(), "the tombstone set is empty after the reset");
|
||||||
|
|
||||||
|
transient.alloc_sized(Probe(String::from("second generation")), 16).unwrap();
|
||||||
|
transient.reset();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "a fresh park at a tombstoned offset drops normally");
|
||||||
|
persistent.reset();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn occupancy_tracks_the_bump_and_clears_on_reset() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
assert_eq!(arena.occupancy(), 0);
|
||||||
|
assert_eq!(arena.capacity(), 1024);
|
||||||
|
arena.alloc(0u64).unwrap();
|
||||||
|
assert_eq!(arena.occupancy(), 8);
|
||||||
|
arena.reset();
|
||||||
|
assert_eq!(arena.occupancy(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn containment_answers_only_for_this_arena() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
let first = Arena::new(1024).unwrap();
|
||||||
|
let second = Arena::new(1024).unwrap();
|
||||||
|
let (value, _) = first.alloc(41u32).unwrap();
|
||||||
|
let ptr = std::ptr::from_ref(value).cast::<u8>();
|
||||||
|
assert!(first.contains(ptr));
|
||||||
|
assert!(!second.contains(ptr));
|
||||||
|
assert!(!first.contains(std::ptr::null()));
|
||||||
|
let heap = Box::new(7u32);
|
||||||
|
assert!(!first.contains(std::ptr::from_ref(&*heap).cast::<u8>()), "heap the arena does not back is outside it");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drop_glue_runs_on_reset() {
|
||||||
|
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
|
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||||
|
struct Probe(#[allow(dead_code)] String);
|
||||||
|
impl Drop for Probe {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut arena = Arena::new(1024).unwrap();
|
||||||
|
arena.alloc(Probe("owns heap".into())).unwrap();
|
||||||
|
arena.alloc(Probe("me too".into())).unwrap();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
|
||||||
|
arena.reset();
|
||||||
|
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,498 @@
|
|||||||
|
//! Attribute markers and their census. A marker declares an attribute name
|
||||||
|
//! once, fixing its value type and its name-specific default; the census
|
||||||
|
//! collects every declaration so name resolution, defaults, and diagnostics
|
||||||
|
//! run at graph compile time. One name belongs to one marker, so a name can
|
||||||
|
//! never mean two different types.
|
||||||
|
//!
|
||||||
|
//! Values are `Copy` and pack directly into record fields. Data with drop
|
||||||
|
//! glue rides the arena instead: the marker declares a reference value
|
||||||
|
//! (`&str`), the writing kernel parks the payload in the arena, and the
|
||||||
|
//! record field carries the eval-lifetime reference.
|
||||||
|
|
||||||
|
use crate::list::AnyAttributeValue;
|
||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use std::any::TypeId;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::collections::hash_map::Entry;
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::sync::{LazyLock, Mutex};
|
||||||
|
|
||||||
|
/// Declares an attribute name: one marker per name, fixing the value type and
|
||||||
|
/// the name-specific default. Declare markers through the [`attribute!`]
|
||||||
|
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
|
||||||
|
pub trait Attribute: 'static {
|
||||||
|
/// The name as it appears in documents and diagnostics.
|
||||||
|
const NAME: &'static str;
|
||||||
|
/// The value type every read and write of this name shares. The lifetime
|
||||||
|
/// is the evaluation the value flows in; non-reference values ignore it.
|
||||||
|
/// The value outlives that evaluation, so its `'static` instantiation is
|
||||||
|
/// the one the census registers and layouts stamp their type id from.
|
||||||
|
type Value<'e>: Copy + Default + std::fmt::Debug + 'e;
|
||||||
|
/// The name-specific default, filled where an item lacks the attribute.
|
||||||
|
/// Producing a value for any `'e` from no inputs, reference defaults can
|
||||||
|
/// only point at `'static` data, which is what lets the census fill them
|
||||||
|
/// as plain bytes.
|
||||||
|
fn default<'e>() -> Self::Value<'e> {
|
||||||
|
Default::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Borrows the value out of legacy list storage, whose stored form is the
|
||||||
|
/// owned clone [`Self::read_erased`] produces. `None` where the column is
|
||||||
|
/// absent or holds another type.
|
||||||
|
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>>;
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `ptr` must point at a live field of this marker's value type.
|
||||||
|
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
|
||||||
|
|
||||||
|
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
||||||
|
/// field storage; `None` for plain values, which ride the byte copy.
|
||||||
|
const REPARK: Option<crate::list::ReparkFn> = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
||||||
|
/// (yielding the declared default where the attribute is absent upstream), an
|
||||||
|
/// `Attr<A>` in the return tuple is a write, and the same marker on both
|
||||||
|
/// sides is a modify.
|
||||||
|
pub struct Attr<'e, A: Attribute>(pub A::Value<'e>);
|
||||||
|
|
||||||
|
impl<'e, A: Attribute> Deref for Attr<'e, A> {
|
||||||
|
type Target = A::Value<'e>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &A::Value<'e> {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'e, A: Attribute> Clone for Attr<'e, A> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'e, A: Attribute> Copy for Attr<'e, A> {}
|
||||||
|
|
||||||
|
impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_tuple(A::NAME).field(&self.0).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An attribute write that outlives the evaluation producing it: an async
|
||||||
|
/// source's slot persists across generations, so a reference value cannot
|
||||||
|
/// cross as itself. The value crosses deep-copied through the field glue and
|
||||||
|
/// parks into the serving arena at every lift, which is why the copy is paid
|
||||||
|
/// once per invocation rather than once per evaluation.
|
||||||
|
pub struct OwnedAttr<A: Attribute>(Box<dyn AnyAttributeValue>, PhantomData<fn() -> A>);
|
||||||
|
|
||||||
|
impl<A: Attribute> OwnedAttr<A> {
|
||||||
|
/// Deep-copies `value` out of the evaluation that produced it.
|
||||||
|
pub fn new(value: A::Value<'_>) -> Self {
|
||||||
|
// SAFETY: the read addresses a live local of the marker's value type.
|
||||||
|
let erased = unsafe { A::read_erased((&raw const value).cast()) };
|
||||||
|
OwnedAttr(crate::record::deepen_field_value(erased), PhantomData)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parks the copy into `arena` for one evaluation; `None` reports arena
|
||||||
|
/// exhaustion.
|
||||||
|
pub fn park<'e>(&self, arena: &'e crate::arena::Arena) -> Option<A::Value<'e>> {
|
||||||
|
let resident = crate::record::replay_field_value(&*self.0, arena)?;
|
||||||
|
let mut value = A::default();
|
||||||
|
// SAFETY: the slot is a live field of the marker's value type, and the
|
||||||
|
// stored value is the copy `new` took at that same type.
|
||||||
|
unsafe { write_stored::<A>(resident.as_deref().unwrap_or(&*self.0), (&raw mut value).cast(), arena) }?;
|
||||||
|
Some(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Attribute> Clone for OwnedAttr<A> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
OwnedAttr(self.0.clone(), PhantomData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Attribute> std::fmt::Debug for OwnedAttr<A> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_tuple(A::NAME).field(&self.0.display_string()).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A deletion of `A` in a node's return tuple: the name leaves the output
|
||||||
|
/// layout, so downstream reads yield the declared default again. Functionally
|
||||||
|
/// a write of the default; the value carries nothing.
|
||||||
|
pub struct RemoveAttr<A: Attribute>(PhantomData<A>);
|
||||||
|
|
||||||
|
impl<A: Attribute> RemoveAttr<A> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
RemoveAttr(PhantomData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Attribute> Default for RemoveAttr<A> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A census row: what is known about one declared attribute name.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct AttributeInfo {
|
||||||
|
pub name: &'static str,
|
||||||
|
pub value_type: TypeId,
|
||||||
|
pub value_type_name: &'static str,
|
||||||
|
pub default: fn() -> Box<dyn AnyAttributeValue>,
|
||||||
|
pub size: usize,
|
||||||
|
pub align: usize,
|
||||||
|
/// Writes the declared default's bytes into a `size`-long slice.
|
||||||
|
pub write_default_bytes: fn(&mut [u8]),
|
||||||
|
/// The marker's field form at the given level, for layouts built at runtime.
|
||||||
|
pub field_write_at: fn(u8) -> crate::record::FieldWrite,
|
||||||
|
/// Writes a legacy stored value into a field of this marker, parking
|
||||||
|
/// droppable payloads. A wrong-typed stored value leaves the field
|
||||||
|
/// untouched; `None` reports arena exhaustion.
|
||||||
|
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||||
|
assert_eq!(out.len(), size_of::<A::Value<'static>>());
|
||||||
|
let value: A::Value<'static> = A::default();
|
||||||
|
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
|
||||||
|
where
|
||||||
|
A::Value<'static>: graphene_hash::CacheHash + PartialEq,
|
||||||
|
{
|
||||||
|
crate::record::FieldWrite::of::<A>(level)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||||
|
if A::from_stored(stored.as_any()).is_none() {
|
||||||
|
// A wrong-typed stored value reads as absent, so the field keeps its default.
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
|
match A::REPARK {
|
||||||
|
Some(repark) => unsafe { repark(stored, dst, arena) },
|
||||||
|
None => {
|
||||||
|
let value = A::from_stored(stored.as_any()).expect("checked above");
|
||||||
|
// SAFETY: a marker without re-park glue stores a plain value, so the bytes carry no borrowed data.
|
||||||
|
unsafe { dst.cast::<A::Value<'_>>().write(value) };
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All declared attribute names, keyed by name.
|
||||||
|
pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInfo>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
|
/// Registers `A` into the census. Called by the [`attribute!`] expansion at
|
||||||
|
/// startup (ctor natively, a `__node_registry_attribute_*` export on wasm).
|
||||||
|
/// Re-registration at the same value type is idempotent; a second marker
|
||||||
|
/// claiming the name at a different value type panics.
|
||||||
|
pub fn register<A: Attribute>()
|
||||||
|
where
|
||||||
|
A::Value<'static>: AnyAttributeValue + graphene_hash::CacheHash + PartialEq,
|
||||||
|
{
|
||||||
|
let info = AttributeInfo {
|
||||||
|
name: A::NAME,
|
||||||
|
value_type: TypeId::of::<A::Value<'static>>(),
|
||||||
|
value_type_name: std::any::type_name::<A::Value<'static>>(),
|
||||||
|
default: || Box::new(A::default()),
|
||||||
|
size: size_of::<A::Value<'static>>(),
|
||||||
|
align: align_of::<A::Value<'static>>(),
|
||||||
|
write_default_bytes: write_default_bytes::<A>,
|
||||||
|
field_write_at: field_write_at::<A>,
|
||||||
|
write_stored: write_stored::<A>,
|
||||||
|
};
|
||||||
|
let conflict = match ATTRIBUTE_REGISTRY.lock().unwrap().entry(A::NAME) {
|
||||||
|
Entry::Vacant(vacant) => {
|
||||||
|
vacant.insert(info);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Entry::Occupied(occupied) => (occupied.get().value_type != info.value_type).then(|| occupied.get().value_type_name),
|
||||||
|
};
|
||||||
|
if let Some(existing) = conflict {
|
||||||
|
panic!("attribute `{}` is declared at two value types: {existing} and {}", A::NAME, info.value_type_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks up a declared name.
|
||||||
|
pub fn info(name: &str) -> Option<AttributeInfo> {
|
||||||
|
ATTRIBUTE_REGISTRY.lock().unwrap().get(name).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name-specific default for `name`, if the name is declared.
|
||||||
|
pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||||
|
info(name).map(|info| (info.default)())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Declares attribute markers: for each entry, the marker struct, its
|
||||||
|
/// [`Attribute`] impl, and the census registration.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// core_types::attribute! {
|
||||||
|
/// /// How visible the content is.
|
||||||
|
/// pub Opacity("opacity"): f64 = 1.;
|
||||||
|
/// /// The item's label, parked in the arena by the writer.
|
||||||
|
/// pub Label("label"): &str;
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// The trailing `= expr` is the name-specific default; without it the value
|
||||||
|
/// type's `Default` applies. A `&T` value carries the eval lifetime, so its
|
||||||
|
/// default must be `'static` data. An `Option<&T>` value is an optional
|
||||||
|
/// parked reference whose default is `None`, for attributes whose absence
|
||||||
|
/// means something a present value cannot.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! attribute {
|
||||||
|
() => {};
|
||||||
|
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): Option<&$value:ty>; $($rest:tt)*) => {
|
||||||
|
$(#[$meta])*
|
||||||
|
$vis struct $marker;
|
||||||
|
|
||||||
|
impl $crate::attribute::Attribute for $marker {
|
||||||
|
const NAME: &'static str = $name;
|
||||||
|
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||||
|
|
||||||
|
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||||
|
stored
|
||||||
|
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
|
||||||
|
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||||
|
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
|
||||||
|
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||||
|
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
|
||||||
|
value.as_any().downcast_ref().expect("an optional reference attribute replays its owned clone");
|
||||||
|
let parked = match owned {
|
||||||
|
::core::option::Option::Some(owned) => {
|
||||||
|
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||||
|
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
|
||||||
|
}
|
||||||
|
::core::option::Option::None => ::core::option::Option::None,
|
||||||
|
};
|
||||||
|
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
|
||||||
|
::core::option::Option::Some(())
|
||||||
|
}
|
||||||
|
::core::option::Option::Some(repark)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::attribute!(@register $marker);
|
||||||
|
$crate::attribute!($($rest)*);
|
||||||
|
};
|
||||||
|
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): &$value:ty $(= $default:expr)?; $($rest:tt)*) => {
|
||||||
|
$(#[$meta])*
|
||||||
|
$vis struct $marker;
|
||||||
|
|
||||||
|
impl $crate::attribute::Attribute for $marker {
|
||||||
|
const NAME: &'static str = $name;
|
||||||
|
type Value<'e> = &'e $value;
|
||||||
|
$(
|
||||||
|
fn default<'e>() -> Self::Value<'e> {
|
||||||
|
$default
|
||||||
|
}
|
||||||
|
)?
|
||||||
|
|
||||||
|
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||||
|
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||||
|
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
|
||||||
|
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||||
|
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference attribute replays its owned clone");
|
||||||
|
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||||
|
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
|
||||||
|
::core::option::Option::Some(())
|
||||||
|
}
|
||||||
|
::core::option::Option::Some(repark)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::attribute!(@register $marker);
|
||||||
|
$crate::attribute!($($rest)*);
|
||||||
|
};
|
||||||
|
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): $value:ty $(= $default:expr)?; $($rest:tt)*) => {
|
||||||
|
$(#[$meta])*
|
||||||
|
$vis struct $marker;
|
||||||
|
|
||||||
|
impl $crate::attribute::Attribute for $marker {
|
||||||
|
const NAME: &'static str = $name;
|
||||||
|
type Value<'e> = $value;
|
||||||
|
$(
|
||||||
|
fn default<'e>() -> Self::Value<'e> {
|
||||||
|
$default
|
||||||
|
}
|
||||||
|
)?
|
||||||
|
|
||||||
|
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||||
|
stored.downcast_ref::<$value>().copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||||
|
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::attribute!(@register $marker);
|
||||||
|
$crate::attribute!($($rest)*);
|
||||||
|
};
|
||||||
|
(@register $marker:ident) => {
|
||||||
|
const _: () = {
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
#[$crate::ctor::ctor]
|
||||||
|
fn register() {
|
||||||
|
$crate::attribute::register::<$marker>();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
#[unsafe(export_name = concat!("__node_registry_attribute_", stringify!($marker)))]
|
||||||
|
extern "C" fn register() {
|
||||||
|
$crate::attribute::register::<$marker>();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
attribute! {
|
||||||
|
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||||
|
pub Transform("transform"): DAffine2;
|
||||||
|
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||||
|
pub BlendMode("blend_mode"): crate::blending::BlendMode;
|
||||||
|
/// Item's opacity multiplier, composed multiplicatively through nested groups.
|
||||||
|
/// Affects content clipped to the item.
|
||||||
|
pub Opacity("opacity"): f64 = 1.;
|
||||||
|
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
|
||||||
|
pub OpacityFill("opacity_fill"): f64 = 1.;
|
||||||
|
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||||
|
pub ClippingMask("clipping_mask"): bool;
|
||||||
|
/// The document node path of the editor layer owning the item.
|
||||||
|
/// Editor tools read it to route clicks and selection back to the originating layer.
|
||||||
|
pub EditorLayerPath("editor:layer_path"): &[crate::uuid::NodeId];
|
||||||
|
/// Maps the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' node's
|
||||||
|
/// text frame in this item's local space. Each item carries the frame relative to its own
|
||||||
|
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
|
||||||
|
/// position its drag cage.
|
||||||
|
pub EditorTextFrame("editor:text_frame"): DAffine2;
|
||||||
|
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
|
||||||
|
pub Start("start"): u64;
|
||||||
|
/// Byte offset where a regex match ends ('Regex Find All' and 'Regex Capture' text nodes).
|
||||||
|
pub End("end"): u64;
|
||||||
|
/// A regex named-capture-group's name, or empty for unnamed groups.
|
||||||
|
pub Name("name"): &str;
|
||||||
|
/// A JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||||
|
pub Type("type"): &str;
|
||||||
|
/// Artboard's top-left corner in document coordinates.
|
||||||
|
pub Location("location"): DVec2;
|
||||||
|
/// Artboard's width and height.
|
||||||
|
pub Dimensions("dimensions"): DVec2;
|
||||||
|
/// Artboard's background fill.
|
||||||
|
pub Background("background"): crate::Color;
|
||||||
|
/// Whether an artboard clips content to its bounds.
|
||||||
|
pub Clip("clip"): bool;
|
||||||
|
/// Text item's font size in document-space units.
|
||||||
|
pub FontSize("font_size"): f64 = 24.;
|
||||||
|
/// Text item's line height as a ratio of the font size.
|
||||||
|
pub LineHeight("line_height"): f64 = 1.2;
|
||||||
|
/// Text item's extra spacing between letters in document-space units.
|
||||||
|
pub LetterSpacing("letter_spacing"): f64;
|
||||||
|
/// Text item's maximum line-wrap width in document-space units.
|
||||||
|
pub MaxWidth("max_width"): Option<f64>;
|
||||||
|
/// Text item's maximum block height in document-space units, past which lines are not drawn.
|
||||||
|
pub MaxHeight("max_height"): Option<f64>;
|
||||||
|
/// Text item's faux-italic letter tilt angle in degrees.
|
||||||
|
pub LetterTilt("letter_tilt"): f64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn census_carries_declared_names() {
|
||||||
|
let row = info("opacity").unwrap();
|
||||||
|
assert_eq!(row.value_type, TypeId::of::<f64>());
|
||||||
|
assert_eq!(info("transform").unwrap().value_type, TypeId::of::<DAffine2>());
|
||||||
|
assert_eq!(info("max_width").unwrap().value_type, TypeId::of::<Option<f64>>());
|
||||||
|
assert_eq!(info("background").unwrap().value_type, TypeId::of::<crate::Color>());
|
||||||
|
assert!(info("never_declared").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn name_specific_default_overrides_the_type_default() {
|
||||||
|
assert_eq!(<Opacity as Attribute>::default(), 1.);
|
||||||
|
assert_eq!(<Name as Attribute>::default(), "");
|
||||||
|
assert_eq!(<FontSize as Attribute>::default(), 24.);
|
||||||
|
assert_eq!(<LineHeight as Attribute>::default(), 1.2);
|
||||||
|
assert_eq!(<MaxWidth as Attribute>::default(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn erased_default_downcasts_to_the_declared_type() {
|
||||||
|
let value = default_value("opacity_fill").unwrap();
|
||||||
|
assert_eq!(*value.as_any().downcast_ref::<f64>().unwrap(), 1.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reference_values_register_at_the_static_instantiation() {
|
||||||
|
let row = info("name").unwrap();
|
||||||
|
assert_eq!(row.value_type, TypeId::of::<&'static str>());
|
||||||
|
assert_eq!(row.size, size_of::<&str>());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_owned_reference_crossing_parks_into_the_serving_arena() {
|
||||||
|
let owned = OwnedAttr::<Name>::new("crossing");
|
||||||
|
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||||
|
assert_eq!(owned.park(&arena).unwrap(), "crossing");
|
||||||
|
assert_eq!(owned.clone().park(&arena).unwrap(), "crossing", "the crossing parks again on every evaluation");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_owned_plain_crossing_rides_its_bytes() {
|
||||||
|
let arena = crate::arena::Arena::new(64).unwrap();
|
||||||
|
assert_eq!(OwnedAttr::<Opacity>::new(0.25).park(&arena).unwrap(), 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_exhausted_arena_refuses_an_owned_reference_crossing() {
|
||||||
|
let owned = OwnedAttr::<Name>::new("too long for this arena");
|
||||||
|
let arena = crate::arena::Arena::new(8).unwrap();
|
||||||
|
assert!(owned.park(&arena).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reregistration_at_the_same_type_is_idempotent() {
|
||||||
|
register::<Opacity>();
|
||||||
|
register::<Opacity>();
|
||||||
|
assert_eq!(info("opacity").unwrap().value_type, TypeId::of::<f64>());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "two value types")]
|
||||||
|
fn a_second_marker_at_a_different_type_panics() {
|
||||||
|
struct Conflict;
|
||||||
|
impl Attribute for Conflict {
|
||||||
|
const NAME: &'static str = "opacity";
|
||||||
|
type Value<'e> = bool;
|
||||||
|
|
||||||
|
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
|
||||||
|
stored.downcast_ref::<bool>().copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
|
||||||
|
Box::new(unsafe { ptr.cast::<bool>().read() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
register::<Conflict>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::Color;
|
use crate::Color;
|
||||||
|
use crate::lane::{LaneColumn, LaneSource};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
|
|
||||||
#[derive(Clone, Copy, Default, Debug, PartialEq)]
|
#[derive(Clone, Copy, Default, Debug, PartialEq)]
|
||||||
@@ -51,3 +52,62 @@ impl BoundingBox for Color {
|
|||||||
RenderBoundingBox::Infinite
|
RenderBoundingBox::Infinite
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Combined bounding box of a lane source's elements, composing each lane's
|
||||||
|
/// transform attribute with the given transform.
|
||||||
|
pub fn lane_bounding_box<S: LaneSource>(source: &S, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox
|
||||||
|
where
|
||||||
|
S::Element: BoundingBox,
|
||||||
|
{
|
||||||
|
let mut combined_bounds = None;
|
||||||
|
|
||||||
|
let transforms = source.column::<crate::attribute::Transform>();
|
||||||
|
for lane in 0..source.lane_count() {
|
||||||
|
let Some(element) = source.element(lane) else { continue };
|
||||||
|
let lane_transform: DAffine2 = transforms.get(lane);
|
||||||
|
match element.bounding_box(transform * lane_transform, include_stroke) {
|
||||||
|
RenderBoundingBox::None => continue,
|
||||||
|
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
|
||||||
|
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
||||||
|
Some(existing) => combined_bounds = Some(crate::math::quad::Quad::combine_bounds(existing, bounds)),
|
||||||
|
None => combined_bounds = Some(bounds),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match combined_bounds {
|
||||||
|
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||||
|
None => RenderBoundingBox::None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// As [`lane_bounding_box`], but `Infinite` lanes are skipped (rather than
|
||||||
|
/// propagating outward) so a finite sibling in a mixed group dictates the
|
||||||
|
/// framing.
|
||||||
|
pub fn lane_thumbnail_bounding_box<S: LaneSource>(source: &S, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox
|
||||||
|
where
|
||||||
|
S::Element: BoundingBox,
|
||||||
|
{
|
||||||
|
let mut combined_bounds = None;
|
||||||
|
let mut any_infinite = false;
|
||||||
|
|
||||||
|
let transforms = source.column::<crate::attribute::Transform>();
|
||||||
|
for lane in 0..source.lane_count() {
|
||||||
|
let Some(element) = source.element(lane) else { continue };
|
||||||
|
let lane_transform: DAffine2 = transforms.get(lane);
|
||||||
|
match element.thumbnail_bounding_box(transform * lane_transform, include_stroke) {
|
||||||
|
RenderBoundingBox::None => continue,
|
||||||
|
RenderBoundingBox::Infinite => any_infinite = true,
|
||||||
|
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
||||||
|
Some(existing) => combined_bounds = Some(crate::math::quad::Quad::combine_bounds(existing, bounds)),
|
||||||
|
None => combined_bounds = Some(bounds),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match (combined_bounds, any_infinite) {
|
||||||
|
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||||
|
(None, true) => RenderBoundingBox::Infinite,
|
||||||
|
(None, false) => RenderBoundingBox::None,
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
|||||||
|
//! The typed surface handed to an `extent(fn)` helper: the node's inputs in
|
||||||
|
//! declaration order, then the queried level. Values read without unsafe or
|
||||||
|
//! internal fields, upstream extents query per level, and the one blessed
|
||||||
|
//! context modification is per-copy derived promotion. Anything beyond this
|
||||||
|
//! vocabulary uses `extent_raw(fn)`, which keeps the full node/ctx/level form.
|
||||||
|
|
||||||
|
use crate::gpoll::{Extent, GPoll};
|
||||||
|
|
||||||
|
/// A wired value input; `get` evaluates the input and yields the typed element.
|
||||||
|
pub struct ValueIn<'a, T> {
|
||||||
|
read: &'a dyn Fn() -> GPoll<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T> ValueIn<'a, T> {
|
||||||
|
pub fn new(read: &'a dyn Fn() -> GPoll<T>) -> Self {
|
||||||
|
Self { read }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self) -> GPoll<T> {
|
||||||
|
(self.read)()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An upstream input's extents. For derived (per-copy) content the query runs
|
||||||
|
/// at the given copy's promoted context; `at` queries copy 0, the uniform
|
||||||
|
/// default. For ordinary inputs the copy is ignored.
|
||||||
|
pub struct ExtentIn<'a> {
|
||||||
|
query: &'a dyn Fn(u64, u8) -> GPoll<Extent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> ExtentIn<'a> {
|
||||||
|
pub fn new(query: &'a dyn Fn(u64, u8) -> GPoll<Extent>) -> Self {
|
||||||
|
Self { query }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn at(&self, level: LevelIn) -> GPoll<Extent> {
|
||||||
|
(self.query)(0, level.level)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn at_copy(&self, copy: u64, level: LevelIn) -> GPoll<Extent> {
|
||||||
|
(self.query)(copy, level.level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A ranked (`IList`) input materialized whole: `get` drives the batch and
|
||||||
|
/// yields the level as a [`List`](crate::node::List), for extents that depend
|
||||||
|
/// on the input's data rather than its counts alone. `total` answers the
|
||||||
|
/// subject's flat count without materializing, so count-shaped extents stay
|
||||||
|
/// cheap: a materializing extent inside another's subject multiplies, and
|
||||||
|
/// nested emitters turn that into a blowup.
|
||||||
|
pub struct ListIn<'a, T> {
|
||||||
|
get: &'a dyn Fn() -> GPoll<crate::node::List<'a, T>>,
|
||||||
|
total: &'a dyn Fn() -> GPoll<crate::gpoll::Extent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T> ListIn<'a, T> {
|
||||||
|
pub fn new(get: &'a dyn Fn() -> GPoll<crate::node::List<'a, T>>, total: &'a dyn Fn() -> GPoll<crate::gpoll::Extent>) -> Self {
|
||||||
|
Self { get, total }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self) -> GPoll<crate::node::List<'a, T>> {
|
||||||
|
(self.get)()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The subject input's total flat extent as a plain query.
|
||||||
|
pub fn total(&self) -> GPoll<crate::gpoll::Extent> {
|
||||||
|
(self.total)()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The queried absolute level (innermost `0`), paired with the node's depth.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct LevelIn {
|
||||||
|
pub level: u8,
|
||||||
|
pub depth: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LevelIn {
|
||||||
|
pub fn new(level: u8, depth: u8) -> Self {
|
||||||
|
Self { level, depth }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the query targets the node's own pushed (outermost) level.
|
||||||
|
pub fn pushed(&self) -> bool {
|
||||||
|
self.level + 1 == self.depth
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the query targets the topmost level; `pushed` under the name a
|
||||||
|
/// non-creator (concat, remap) reads naturally.
|
||||||
|
pub fn top(&self) -> bool {
|
||||||
|
self.pushed()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
use crate::Node;
|
|
||||||
use std::marker::PhantomData;
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct FnNode<T: Fn(I) -> O, I, O>(T, PhantomData<(I, O)>);
|
|
||||||
|
|
||||||
impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode<T, I, O> {
|
|
||||||
type Output = O;
|
|
||||||
fn eval(&'i self, input: I) -> Self::Output {
|
|
||||||
self.0(input)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Fn(I) -> O, I, O> FnNode<T, I, O> {
|
|
||||||
pub fn new(f: T) -> Self {
|
|
||||||
FnNode(f, PhantomData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum ErrorKind {
|
||||||
|
Node(&'static str),
|
||||||
|
ArenaExhausted,
|
||||||
|
Panic,
|
||||||
|
/// A lane past the end of a lower-bound (`Extent::AtLeast`) level: the
|
||||||
|
/// end-of-data signal for draining consumers, an error for everyone else.
|
||||||
|
PastEnd,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq<&str> for ErrorKind {
|
||||||
|
fn eq(&self, other: &&str) -> bool {
|
||||||
|
matches!(self, ErrorKind::Node(kind) if kind == other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct GraphError {
|
||||||
|
pub kind: ErrorKind,
|
||||||
|
pub trace: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphError {
|
||||||
|
pub fn new(kind: &'static str) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: ErrorKind::Node(kind),
|
||||||
|
trace: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn traced(mut self, input_index: usize) -> Self {
|
||||||
|
self.trace.push(input_index);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn past_end() -> Self {
|
||||||
|
Self {
|
||||||
|
kind: ErrorKind::PastEnd,
|
||||||
|
trace: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum GPoll<T> {
|
||||||
|
Pending,
|
||||||
|
Final(T),
|
||||||
|
Partial(T),
|
||||||
|
Fallback(Box<(T, GraphError)>),
|
||||||
|
Error(Box<GraphError>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> GPoll<T> {
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> GPoll<U> {
|
||||||
|
match self {
|
||||||
|
GPoll::Pending => GPoll::Pending,
|
||||||
|
GPoll::Final(value) => GPoll::Final(f(value)),
|
||||||
|
GPoll::Partial(value) => GPoll::Partial(f(value)),
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (value, e) = *boxed;
|
||||||
|
GPoll::Fallback(Box::new((f(value), e)))
|
||||||
|
}
|
||||||
|
GPoll::Error(e) => GPoll::Error(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn and_then<U>(self, f: impl FnOnce(T) -> GPoll<U>) -> GPoll<U> {
|
||||||
|
match self {
|
||||||
|
GPoll::Pending => GPoll::Pending,
|
||||||
|
GPoll::Final(value) => f(value),
|
||||||
|
GPoll::Partial(value) => match f(value) {
|
||||||
|
GPoll::Final(result) => GPoll::Partial(result),
|
||||||
|
other => other,
|
||||||
|
},
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (value, e) = *boxed;
|
||||||
|
match f(value) {
|
||||||
|
GPoll::Pending => GPoll::Pending,
|
||||||
|
GPoll::Final(result) | GPoll::Partial(result) => GPoll::Fallback(Box::new((result, e))),
|
||||||
|
GPoll::Fallback(inner) => {
|
||||||
|
let (result, _) = *inner;
|
||||||
|
GPoll::Fallback(Box::new((result, e)))
|
||||||
|
}
|
||||||
|
GPoll::Error(inner) => GPoll::Error(inner),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
GPoll::Error(e) => GPoll::Error(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn zip<U>(self, other: GPoll<U>) -> GPoll<(T, U)> {
|
||||||
|
match (self, other) {
|
||||||
|
(GPoll::Error(e), _) | (_, GPoll::Error(e)) => GPoll::Error(e),
|
||||||
|
(GPoll::Pending, _) | (_, GPoll::Pending) => GPoll::Pending,
|
||||||
|
(GPoll::Final(a), GPoll::Final(b)) => GPoll::Final((a, b)),
|
||||||
|
(GPoll::Fallback(boxed), GPoll::Final(b) | GPoll::Partial(b)) => {
|
||||||
|
let (a, e) = *boxed;
|
||||||
|
GPoll::Fallback(Box::new(((a, b), e)))
|
||||||
|
}
|
||||||
|
(GPoll::Final(a) | GPoll::Partial(a), GPoll::Fallback(boxed)) => {
|
||||||
|
let (b, e) = *boxed;
|
||||||
|
GPoll::Fallback(Box::new(((a, b), e)))
|
||||||
|
}
|
||||||
|
(GPoll::Fallback(first), GPoll::Fallback(second)) => {
|
||||||
|
let (a, e) = *first;
|
||||||
|
let (b, _) = *second;
|
||||||
|
GPoll::Fallback(Box::new(((a, b), e)))
|
||||||
|
}
|
||||||
|
(GPoll::Partial(a), GPoll::Final(b) | GPoll::Partial(b)) | (GPoll::Final(a), GPoll::Partial(b)) => GPoll::Partial((a, b)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn trace(self, input: usize) -> Self {
|
||||||
|
match self {
|
||||||
|
GPoll::Fallback(mut boxed) => {
|
||||||
|
boxed.1.trace.push(input);
|
||||||
|
GPoll::Fallback(boxed)
|
||||||
|
}
|
||||||
|
GPoll::Error(mut e) => {
|
||||||
|
e.trace.push(input);
|
||||||
|
GPoll::Error(e)
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fallback(value: T, kind: &'static str) -> Self {
|
||||||
|
GPoll::Fallback(Box::new((value, GraphError::new(kind))))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn error(kind: &'static str) -> Self {
|
||||||
|
GPoll::Error(Box::new(GraphError::new(kind)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn arena_exhausted() -> Self {
|
||||||
|
GPoll::Error(Box::new(GraphError {
|
||||||
|
kind: ErrorKind::ArenaExhausted,
|
||||||
|
trace: Vec::new(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn panicked() -> Self {
|
||||||
|
GPoll::Error(Box::new(GraphError {
|
||||||
|
kind: ErrorKind::Panic,
|
||||||
|
trace: Vec::new(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn past_end() -> Self {
|
||||||
|
GPoll::Error(Box::new(GraphError::past_end()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Interrupt {
|
||||||
|
Pending,
|
||||||
|
Error(Box<GraphError>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<GraphError> for Interrupt {
|
||||||
|
fn from(error: GraphError) -> Self {
|
||||||
|
Interrupt::Error(Box::new(error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<Interrupt> for GPoll<T> {
|
||||||
|
fn from(interrupt: Interrupt) -> Self {
|
||||||
|
match interrupt {
|
||||||
|
Interrupt::Pending => GPoll::Pending,
|
||||||
|
Interrupt::Error(e) => GPoll::Error(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Extent {
|
||||||
|
Free,
|
||||||
|
Exactly(usize),
|
||||||
|
/// A sound lower bound; the true count is discoverable only by draining.
|
||||||
|
AtLeast(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Extent {
|
||||||
|
pub fn meet(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||||
|
a.zip(b).and_then(|(a, b)| match (a, b) {
|
||||||
|
(Extent::Free, other) | (other, Extent::Free) => GPoll::Final(other),
|
||||||
|
(Extent::Exactly(n), Extent::Exactly(m)) if n == m => GPoll::Final(Extent::Exactly(n)),
|
||||||
|
(Extent::AtLeast(a), Extent::AtLeast(b)) => GPoll::Final(Extent::AtLeast(a.max(b))),
|
||||||
|
(Extent::AtLeast(bound), Extent::Exactly(n)) | (Extent::Exactly(n), Extent::AtLeast(bound)) if n >= bound => GPoll::Final(Extent::Exactly(n)),
|
||||||
|
(Extent::AtLeast(_), Extent::Exactly(n)) | (Extent::Exactly(n), Extent::AtLeast(_)) => GPoll::fallback(Extent::Exactly(n), "extent mismatch"),
|
||||||
|
(Extent::Exactly(n), Extent::Exactly(m)) => GPoll::fallback(Extent::Exactly(n.min(m)), "extent mismatch"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The product of two extents, used to compose nested-level counts; an
|
||||||
|
/// unbounded operand leaves the product unbounded, a lower-bound operand
|
||||||
|
/// keeps the product a lower bound.
|
||||||
|
pub fn mul(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||||
|
a.zip(b).map(|(a, b)| match (a, b) {
|
||||||
|
(Extent::Free, _) | (_, Extent::Free) => Extent::Free,
|
||||||
|
(Extent::Exactly(n), Extent::Exactly(m)) => Extent::Exactly(n * m),
|
||||||
|
(Extent::AtLeast(n) | Extent::Exactly(n), Extent::AtLeast(m) | Extent::Exactly(m)) => Extent::AtLeast(n * m),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sum of two extents, used to concatenate a level; a free operand
|
||||||
|
/// counts as one lane, so a scalar input joins a concat as a single item,
|
||||||
|
/// and a lower-bound operand keeps the sum a lower bound.
|
||||||
|
pub fn sum(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||||
|
let lanes = |extent| match extent {
|
||||||
|
Extent::Exactly(count) | Extent::AtLeast(count) => count,
|
||||||
|
Extent::Free => 1,
|
||||||
|
};
|
||||||
|
a.zip(b).map(|(a, b)| match (a, b) {
|
||||||
|
(Extent::AtLeast(_), _) | (_, Extent::AtLeast(_)) => Extent::AtLeast(lanes(a) + lanes(b)),
|
||||||
|
_ => Extent::Exactly(lanes(a) + lanes(b)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A query over a node's nesting levels: one level, the product below or above
|
||||||
|
/// it, or the whole domain. The composite [`Node::extent`](crate::node::Node::extent)
|
||||||
|
/// derives these from the per-level [`extent_at`](crate::node::Node::extent_at).
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum Level {
|
||||||
|
At(u8),
|
||||||
|
Below(u8),
|
||||||
|
Above(u8),
|
||||||
|
Total,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Finality {
|
||||||
|
AllFinal,
|
||||||
|
Partial,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Finality {
|
||||||
|
pub fn meet(self, other: Finality) -> Finality {
|
||||||
|
match (self, other) {
|
||||||
|
(Finality::AllFinal, Finality::AllFinal) => Finality::AllFinal,
|
||||||
|
_ => Finality::Partial,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn free_is_the_meet_identity() {
|
||||||
|
let meet = Extent::meet(GPoll::Final(Extent::Free), GPoll::Final(Extent::Exactly(4)));
|
||||||
|
assert_eq!(meet, GPoll::Final(Extent::Exactly(4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extent_mismatch_truncates_and_reports() {
|
||||||
|
let meet = Extent::meet(GPoll::Final(Extent::Exactly(3)), GPoll::Final(Extent::Exactly(5)));
|
||||||
|
let GPoll::Fallback(boxed) = meet else {
|
||||||
|
panic!("expected fallback, got {meet:?}");
|
||||||
|
};
|
||||||
|
assert_eq!(boxed.0, Extent::Exactly(3));
|
||||||
|
assert!(boxed.1.kind == "extent mismatch");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn error_dominates_pending_in_zip() {
|
||||||
|
let zipped = GPoll::<u32>::error("boom").zip(GPoll::<u32>::Pending);
|
||||||
|
assert!(matches!(zipped, GPoll::Error(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trace_builds_root_to_source_path() {
|
||||||
|
let poll = GPoll::<u32>::error("boom").trace(2).trace(0);
|
||||||
|
let GPoll::Error(e) = poll else { unreachable!() };
|
||||||
|
assert_eq!(e.trace, vec![2, 0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn interrupt_round_trips_to_gpoll() {
|
||||||
|
assert_eq!(GPoll::<u32>::from(Interrupt::Pending), GPoll::Pending);
|
||||||
|
let interrupt = Interrupt::from(GraphError::new("boom"));
|
||||||
|
assert!(matches!(GPoll::<u32>::from(interrupt), GPoll::Error(e) if e.kind == "boom"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
//! The read surface over a source of lanes, so readers name census markers
|
||||||
|
//! instead of a storage shape.
|
||||||
|
|
||||||
|
use crate::attribute::Attribute;
|
||||||
|
|
||||||
|
/// One marker's column on a source, resolved once so lane reads skip the key
|
||||||
|
/// lookup.
|
||||||
|
pub trait LaneColumn<'a, A: Attribute> {
|
||||||
|
/// The lane's value, `None` where the source carries no such column.
|
||||||
|
fn try_get(&self, lane: usize) -> Option<A::Value<'a>>;
|
||||||
|
|
||||||
|
/// The lane's value, falling back to the marker's census default.
|
||||||
|
fn get(&self, lane: usize) -> A::Value<'a> {
|
||||||
|
self.try_get(lane).unwrap_or_else(A::default)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A source of lanes carrying an element and census attributes.
|
||||||
|
pub trait LaneSource {
|
||||||
|
type Element;
|
||||||
|
type Column<'a, A: Attribute>: LaneColumn<'a, A>
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
|
||||||
|
fn lane_count(&self) -> usize;
|
||||||
|
|
||||||
|
fn element(&self, lane: usize) -> Option<&Self::Element>;
|
||||||
|
|
||||||
|
fn column<A: Attribute>(&self) -> Self::Column<'_, A>;
|
||||||
|
|
||||||
|
fn attr<A: Attribute>(&self, lane: usize) -> A::Value<'_> {
|
||||||
|
self.column::<A>().get(lane)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Distinguishes an absent column from one holding the census default.
|
||||||
|
fn try_attr<A: Attribute>(&self, lane: usize) -> Option<A::Value<'_>> {
|
||||||
|
self.column::<A>().try_get(lane)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bare element as a one-lane source: no columns, so every marker reads its
|
||||||
|
/// census default. The read surface for a de-tabled leaf, whose attributes
|
||||||
|
/// ride the containing lane.
|
||||||
|
pub struct Single<'a, T>(pub &'a T);
|
||||||
|
|
||||||
|
/// The column of a [`Single`]: always absent, so reads fall to the census
|
||||||
|
/// default.
|
||||||
|
pub struct NoColumn;
|
||||||
|
|
||||||
|
impl<'a, A: Attribute> LaneColumn<'a, A> for NoColumn {
|
||||||
|
fn try_get(&self, _lane: usize) -> Option<A::Value<'a>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> LaneSource for Single<'_, T> {
|
||||||
|
type Element = T;
|
||||||
|
type Column<'a, A: Attribute>
|
||||||
|
= NoColumn
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
|
||||||
|
fn lane_count(&self) -> usize {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn element(&self, lane: usize) -> Option<&T> {
|
||||||
|
(lane == 0).then_some(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column<A: Attribute>(&self) -> NoColumn {
|
||||||
|
NoColumn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: crate::bounds::BoundingBox> crate::bounds::BoundingBox for Single<'_, T> {
|
||||||
|
fn bounding_box(&self, transform: glam::DAffine2, include_stroke: bool) -> crate::bounds::RenderBoundingBox {
|
||||||
|
self.0.bounding_box(transform, include_stroke)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thumbnail_bounding_box(&self, transform: glam::DAffine2, include_stroke: bool) -> crate::bounds::RenderBoundingBox {
|
||||||
|
self.0.thumbnail_bounding_box(transform, include_stroke)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One lane of a source re-based as a one-lane source of a leaf element: the
|
||||||
|
/// de-tabled leaf read with its containing lane's attributes.
|
||||||
|
pub struct LeafLane<'a, S, T> {
|
||||||
|
source: &'a S,
|
||||||
|
index: usize,
|
||||||
|
element: &'a T,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, S, T> LeafLane<'a, S, T> {
|
||||||
|
pub fn new(source: &'a S, index: usize, element: &'a T) -> Self {
|
||||||
|
Self { source, index, element }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LaneColumnAt<'a, S: LaneSource + 'a, A: Attribute> {
|
||||||
|
inner: S::Column<'a, A>,
|
||||||
|
index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for LaneColumnAt<'a, S, A> {
|
||||||
|
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||||
|
(lane == 0).then(|| self.inner.try_get(self.index)).flatten()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S: LaneSource, T> LaneSource for LeafLane<'_, S, T> {
|
||||||
|
type Element = T;
|
||||||
|
type Column<'a, A: Attribute>
|
||||||
|
= LaneColumnAt<'a, S, A>
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
|
||||||
|
fn lane_count(&self) -> usize {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn element(&self, lane: usize) -> Option<&T> {
|
||||||
|
(lane == 0).then_some(self.element)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column<A: Attribute>(&self) -> LaneColumnAt<'_, S, A> {
|
||||||
|
LaneColumnAt {
|
||||||
|
inner: self.source.column::<A>(),
|
||||||
|
index: self.index,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::LaneSource;
|
||||||
|
use crate::attribute::{EditorLayerPath, Opacity, Transform};
|
||||||
|
use crate::list::List;
|
||||||
|
use crate::uuid::NodeId;
|
||||||
|
use glam::DAffine2;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_plain_marker_reads_what_the_legacy_column_stores() {
|
||||||
|
let mut list = List::new_from_element(1u32);
|
||||||
|
let transform = DAffine2::from_translation((3., 4.).into());
|
||||||
|
list.set_attribute(crate::ATTR_TRANSFORM, 0, transform);
|
||||||
|
|
||||||
|
assert_eq!(list.attr::<Transform>(0), transform);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_absent_marker_reads_its_census_default_not_the_value_default() {
|
||||||
|
let list = List::new_from_element(1u32);
|
||||||
|
|
||||||
|
// `Opacity` declares `= 1.`, so the census default must win over `f64::default()`.
|
||||||
|
assert_eq!(list.attr::<Opacity>(0), 1.);
|
||||||
|
assert_eq!(list.attr::<Transform>(0), DAffine2::IDENTITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_reference_marker_borrows_the_stored_owned_form() {
|
||||||
|
let mut list = List::new_from_element(1u32);
|
||||||
|
let path = vec![NodeId(7), NodeId(9)];
|
||||||
|
list.set_attribute(crate::ATTR_EDITOR_LAYER_PATH, 0, path.clone());
|
||||||
|
|
||||||
|
assert_eq!(list.attr::<EditorLayerPath>(0), path.as_slice());
|
||||||
|
assert!(List::new_from_element(1u32).attr::<EditorLayerPath>(0).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_column_of_the_wrong_stored_type_reads_as_absent() {
|
||||||
|
let mut list = List::new_from_element(1u32);
|
||||||
|
list.set_attribute(crate::ATTR_OPACITY, 0, "not an f64".to_string());
|
||||||
|
|
||||||
|
assert_eq!(list.attr::<Opacity>(0), 1.);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,23 @@
|
|||||||
extern crate log;
|
extern crate log;
|
||||||
|
|
||||||
|
pub mod arena;
|
||||||
|
pub mod attribute;
|
||||||
pub mod bounds;
|
pub mod bounds;
|
||||||
pub mod consts;
|
pub mod consts;
|
||||||
pub mod context;
|
pub mod context;
|
||||||
pub mod generic;
|
pub mod extent;
|
||||||
|
pub mod gpoll;
|
||||||
|
pub mod lane;
|
||||||
pub mod list;
|
pub mod list;
|
||||||
pub mod math;
|
pub mod math;
|
||||||
pub mod memo;
|
pub mod memo;
|
||||||
pub mod misc;
|
pub mod misc;
|
||||||
|
pub mod node;
|
||||||
pub mod ops;
|
pub mod ops;
|
||||||
|
pub mod record;
|
||||||
pub mod registry;
|
pub mod registry;
|
||||||
pub mod render_complexity;
|
pub mod render_complexity;
|
||||||
|
pub mod runtime;
|
||||||
pub mod transform;
|
pub mod transform;
|
||||||
pub mod uuid;
|
pub mod uuid;
|
||||||
pub mod value;
|
pub mod value;
|
||||||
@@ -24,9 +31,8 @@ pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
|
|||||||
pub use graphene_hash;
|
pub use graphene_hash;
|
||||||
pub use graphene_hash::CacheHash;
|
pub use graphene_hash::CacheHash;
|
||||||
pub use list::{
|
pub use list::{
|
||||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_TEXT_FRAME, ATTR_END, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT,
|
||||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TRANSFORM, ATTR_TYPE,
|
||||||
ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
|
||||||
};
|
};
|
||||||
pub use memo::MemoHash;
|
pub use memo::MemoHash;
|
||||||
pub use no_std_types::AsU32;
|
pub use no_std_types::AsU32;
|
||||||
@@ -34,113 +40,15 @@ pub use no_std_types::blending;
|
|||||||
pub use no_std_types::choice_type;
|
pub use no_std_types::choice_type;
|
||||||
pub use no_std_types::color;
|
pub use no_std_types::color;
|
||||||
pub use no_std_types::shaders;
|
pub use no_std_types::shaders;
|
||||||
|
pub use node::Node;
|
||||||
pub use num_traits;
|
pub use num_traits;
|
||||||
use std::any::TypeId;
|
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
|
||||||
#[cfg(feature = "wasm")]
|
#[cfg(feature = "wasm")]
|
||||||
pub use tsify;
|
pub use tsify;
|
||||||
pub use types::Cow;
|
pub use types::Cow;
|
||||||
|
|
||||||
// pub trait Node: for<'n> NodeIO<'n> {
|
|
||||||
/// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct.
|
|
||||||
/// See `node-graph/README.md` for information on how to define a new node.
|
|
||||||
pub trait Node<'i, Input> {
|
|
||||||
type Output: 'i;
|
|
||||||
/// Evaluates the node with the single specified input.
|
|
||||||
fn eval(&'i self, input: Input) -> Self::Output;
|
|
||||||
/// Resets the node, e.g. the LetNode's cache is set to None.
|
|
||||||
fn reset(&self) {}
|
|
||||||
/// Returns the name of the node for diagnostic purposes.
|
|
||||||
fn node_name(&self) -> &'static str {
|
|
||||||
std::any::type_name::<Self>()
|
|
||||||
}
|
|
||||||
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
|
|
||||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
|
||||||
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mod types;
|
mod types;
|
||||||
pub use types::*;
|
pub use types::*;
|
||||||
|
|
||||||
pub trait NodeIO<'i, Input>: Node<'i, Input>
|
|
||||||
where
|
|
||||||
Self::Output: 'i + StaticTypeSized,
|
|
||||||
Input: StaticTypeSized,
|
|
||||||
{
|
|
||||||
fn input_type(&self) -> TypeId {
|
|
||||||
TypeId::of::<Input::Static>()
|
|
||||||
}
|
|
||||||
fn input_type_name(&self) -> &'static str {
|
|
||||||
std::any::type_name::<Input>()
|
|
||||||
}
|
|
||||||
fn output_type(&self) -> TypeId {
|
|
||||||
TypeId::of::<<Self::Output as StaticTypeSized>::Static>()
|
|
||||||
}
|
|
||||||
fn output_type_name(&self) -> &'static str {
|
|
||||||
std::any::type_name::<Self::Output>()
|
|
||||||
}
|
|
||||||
fn to_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes {
|
|
||||||
NodeIOTypes {
|
|
||||||
call_argument: concrete!(<Input as StaticTypeSized>::Static),
|
|
||||||
return_value: concrete!(<Self::Output as StaticTypeSized>::Static),
|
|
||||||
inputs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn to_async_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes
|
|
||||||
where
|
|
||||||
<Self::Output as Future>::Output: StaticTypeSized,
|
|
||||||
Self::Output: Future,
|
|
||||||
{
|
|
||||||
NodeIOTypes {
|
|
||||||
call_argument: concrete!(<Input as StaticTypeSized>::Static),
|
|
||||||
return_value: future!(<<Self::Output as Future>::Output as StaticTypeSized>::Static),
|
|
||||||
inputs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N
|
|
||||||
where
|
|
||||||
N::Output: 'i + StaticTypeSized,
|
|
||||||
I: StaticTypeSized,
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N {
|
|
||||||
type Output = N::Output;
|
|
||||||
fn eval(&'i self, input: I) -> N::Output {
|
|
||||||
(*self).eval(input)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box<N> {
|
|
||||||
type Output = O;
|
|
||||||
fn eval(&'i self, input: I) -> O {
|
|
||||||
(**self).eval(input)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc<N> {
|
|
||||||
type Output = O;
|
|
||||||
fn eval(&'i self, input: I) -> O {
|
|
||||||
(**self).eval(input)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'i, I, O: 'i> Node<'i, I> for Pin<Box<dyn Node<'i, I, Output = O> + 'i>> {
|
|
||||||
type Output = O;
|
|
||||||
fn eval(&'i self, input: I) -> O {
|
|
||||||
(**self).eval(input)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> {
|
|
||||||
type Output = O;
|
|
||||||
fn eval(&'i self, input: I) -> O {
|
|
||||||
(**self).eval(input)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
|
pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
|
||||||
fn get_input(&'a self, index: usize) -> Option<&'a T>;
|
fn get_input(&'a self, index: usize) -> Option<&'a T>;
|
||||||
fn set_input(&'a mut self, index: usize, value: T);
|
fn set_input(&'a mut self, index: usize, value: T);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use crate::attribute::Attribute as _;
|
||||||
use crate::bounds::{BoundingBox, RenderBoundingBox};
|
use crate::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
use crate::math::quad::Quad;
|
|
||||||
use crate::transform::ApplyTransform;
|
use crate::transform::ApplyTransform;
|
||||||
use dyn_any::{StaticType, StaticTypeSized};
|
use dyn_any::{StaticType, StaticTypeSized};
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
@@ -9,86 +9,42 @@ use std::fmt::Debug;
|
|||||||
// =================================================
|
// =================================================
|
||||||
// Standard attribute keys used across the data flow
|
// Standard attribute keys used across the data flow
|
||||||
// =================================================
|
// =================================================
|
||||||
|
// Each name is declared once by its marker, which documents the attribute and
|
||||||
|
// fixes its value type. The constants re-export the markers' names for the
|
||||||
|
// string-keyed legacy readers and writers. Markers whose value types live
|
||||||
|
// below core-types are declared in their types' crates (vector-types, the
|
||||||
|
// text nodes, graphic-types), each with its own name constants.
|
||||||
|
|
||||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
pub const ATTR_TRANSFORM: &str = crate::attribute::Transform::NAME;
|
||||||
pub const ATTR_TRANSFORM: &str = "transform";
|
pub const ATTR_BLEND_MODE: &str = crate::attribute::BlendMode::NAME;
|
||||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
pub const ATTR_OPACITY: &str = crate::attribute::Opacity::NAME;
|
||||||
pub const ATTR_BLEND_MODE: &str = "blend_mode";
|
pub const ATTR_OPACITY_FILL: &str = crate::attribute::OpacityFill::NAME;
|
||||||
/// Item's opacity multiplier (`f64`, implicit default `1.`).
|
pub const ATTR_CLIPPING_MASK: &str = crate::attribute::ClippingMask::NAME;
|
||||||
/// Composed multiplicatively through nested groups. Affects content clipped to the item.
|
pub const ATTR_EDITOR_LAYER_PATH: &str = crate::attribute::EditorLayerPath::NAME;
|
||||||
pub const ATTR_OPACITY: &str = "opacity";
|
pub const ATTR_EDITOR_TEXT_FRAME: &str = crate::attribute::EditorTextFrame::NAME;
|
||||||
/// Item's fill opacity multiplier (`f64`, implicit default `1.`).
|
pub const ATTR_START: &str = crate::attribute::Start::NAME;
|
||||||
/// Like opacity but does not affect content clipped to the item.
|
pub const ATTR_END: &str = crate::attribute::End::NAME;
|
||||||
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
|
pub const ATTR_NAME: &str = crate::attribute::Name::NAME;
|
||||||
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
|
pub const ATTR_TYPE: &str = crate::attribute::Type::NAME;
|
||||||
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
|
pub const ATTR_LOCATION: &str = crate::attribute::Location::NAME;
|
||||||
/// `List<NodeId>` path from the root network to the layer node owning this item.
|
pub const ATTR_DIMENSIONS: &str = crate::attribute::Dimensions::NAME;
|
||||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
pub const ATTR_BACKGROUND: &str = crate::attribute::Background::NAME;
|
||||||
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
|
pub const ATTR_CLIP: &str = crate::attribute::Clip::NAME;
|
||||||
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
|
pub const ATTR_FONT_SIZE: &str = crate::attribute::FontSize::NAME;
|
||||||
/// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for
|
pub const ATTR_LINE_HEIGHT: &str = crate::attribute::LineHeight::NAME;
|
||||||
/// the original child layers after their content has been collapsed.
|
pub const ATTR_LETTER_SPACING: &str = crate::attribute::LetterSpacing::NAME;
|
||||||
pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers";
|
pub const ATTR_MAX_WIDTH: &str = crate::attribute::MaxWidth::NAME;
|
||||||
/// Optional `Vector` that overrides the item's own geometry for click-target generation.
|
pub const ATTR_MAX_HEIGHT: &str = crate::attribute::MaxHeight::NAME;
|
||||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
pub const ATTR_LETTER_TILT: &str = crate::attribute::LetterTilt::NAME;
|
||||||
/// by clicking anywhere within their bounds, not just the filled letterform.
|
|
||||||
pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
|
||||||
/// `DAffine2` mapping the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text'
|
|
||||||
/// node's text frame in this item's local space. Each item carries the frame relative to its own
|
|
||||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
|
||||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
|
||||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
|
||||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
|
||||||
pub const ATTR_START: &str = "start";
|
|
||||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
|
||||||
pub const ATTR_END: &str = "end";
|
|
||||||
/// `String` for a regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
|
|
||||||
pub const ATTR_NAME: &str = "name";
|
|
||||||
/// `String` for a JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
|
||||||
pub const ATTR_TYPE: &str = "type";
|
|
||||||
/// Artboard's `DVec2` top-left corner in document coordinates.
|
|
||||||
pub const ATTR_LOCATION: &str = "location";
|
|
||||||
/// Artboard's `DVec2` width and height.
|
|
||||||
pub const ATTR_DIMENSIONS: &str = "dimensions";
|
|
||||||
/// Artboard's `Color` background fill.
|
|
||||||
pub const ATTR_BACKGROUND: &str = "background";
|
|
||||||
/// `bool` for whether an artboard clips content to its bounds.
|
|
||||||
pub const ATTR_CLIP: &str = "clip";
|
|
||||||
/// Gradient's `GradientSpreadMethod` (`Pad`, `Reflect`, or `Repeat`).
|
|
||||||
pub const ATTR_SPREAD_METHOD: &str = "spread_method";
|
|
||||||
/// Gradient's `GradientType` (`Linear` or `Radial`).
|
|
||||||
pub const ATTR_GRADIENT_TYPE: &str = "gradient_type";
|
|
||||||
/// Vector graphics object's filled area paint, of type List<T> where T is any graphic type.
|
|
||||||
pub const ATTR_FILL: &str = "fill";
|
|
||||||
/// Vector graphics object's stroke paint, of type List<T> where T is any graphic type.
|
|
||||||
pub const ATTR_STROKE: &str = "stroke";
|
|
||||||
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
|
|
||||||
pub const ATTR_FONT_SIZE: &str = "font_size";
|
|
||||||
/// Text item's font, as a `Resource` of the loaded font file.
|
|
||||||
pub const ATTR_FONT: &str = "font";
|
|
||||||
/// Text item's line height as a ratio of the font size (`f64`, implicit default `1.2`).
|
|
||||||
pub const ATTR_LINE_HEIGHT: &str = "line_height";
|
|
||||||
/// Text item's extra spacing between letters in document-space units (`f64`, implicit default `0.`).
|
|
||||||
pub const ATTR_LETTER_SPACING: &str = "letter_spacing";
|
|
||||||
/// Text item's maximum line-wrap width in document-space units (`Option<f64>`, implicit default `None`).
|
|
||||||
pub const ATTR_MAX_WIDTH: &str = "max_width";
|
|
||||||
/// Text item's maximum block height in document-space units, past which lines are not drawn (`Option<f64>`, implicit default `None`).
|
|
||||||
pub const ATTR_MAX_HEIGHT: &str = "max_height";
|
|
||||||
/// Text item's faux-italic letter tilt angle in degrees (`f64`, implicit default `0.`).
|
|
||||||
pub const ATTR_LETTER_TILT: &str = "letter_tilt";
|
|
||||||
/// Text item's `TextAlign` horizontal alignment of lines within the block.
|
|
||||||
pub const ATTR_TEXT_ALIGN: &str = "text_align";
|
|
||||||
|
|
||||||
// ===========================
|
// ===========================
|
||||||
// Implicit attribute defaults
|
// Implicit attribute defaults
|
||||||
// ===========================
|
// ===========================
|
||||||
|
|
||||||
/// Overrides the type's default value for certain attributes.
|
/// The census-declared default for `key`; a mismatched value type degrades
|
||||||
|
/// to the column type's own default in `push_repeated`.
|
||||||
fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||||
match key {
|
crate::attribute::ATTRIBUTE_REGISTRY.lock().unwrap().get(key).map(|info| (info.default)())
|
||||||
ATTR_OPACITY | ATTR_OPACITY_FILL => Some(Box::new(1_f64)),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
|
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
|
||||||
@@ -129,6 +85,12 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
|
|||||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Re-parks an owned attribute value into fresh field storage; `None` reports arena exhaustion.
|
||||||
|
pub type ReparkFn = unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>;
|
||||||
|
|
||||||
|
/// Replays an owned attribute value into a serving arena; `Some(None)` is unchanged, `None` reports arena exhaustion.
|
||||||
|
pub type FieldReplayFn = fn(&dyn AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn AnyAttributeValue>>>;
|
||||||
|
|
||||||
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
|
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
|
||||||
/// Clones this value into a new boxed trait object.
|
/// Clones this value into a new boxed trait object.
|
||||||
fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
|
fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
|
||||||
@@ -381,20 +343,6 @@ impl AttributeDyn {
|
|||||||
self.0.len() == 0
|
self.0.len() == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds a new attribute matching `target_len` items, taking values from this attribute (wrapping if shorter, truncating if longer).
|
|
||||||
pub fn cloned_to_length(&self, key: &str, target_len: usize) -> Box<dyn AnyAttribute> {
|
|
||||||
let mut result = self.0.new_with_defaults(0);
|
|
||||||
let source_len = self.0.len();
|
|
||||||
if source_len == 0 {
|
|
||||||
pad_with_implicit_default(key, &mut result, target_len);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
for i in 0..target_len {
|
|
||||||
let value = self.0.clone_value(i % source_len).expect("source_len > 0");
|
|
||||||
result.push(value);
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clone for AttributeDyn {
|
impl Clone for AttributeDyn {
|
||||||
@@ -646,6 +594,11 @@ impl ItemAttributeValues {
|
|||||||
self.0.iter().map(|(key, _)| key.as_str())
|
self.0.iter().map(|(key, _)| key.as_str())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns an iterator over the stored (key, value) pairs, in insertion order.
|
||||||
|
pub fn iter(&self) -> impl Iterator<Item = (&str, &dyn AnyAttributeValue)> {
|
||||||
|
self.0.iter().map(|(key, value)| (key.as_str(), &**value))
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns a debug-formatted string representation of the attribute value for the given key, if it exists.
|
/// Returns a debug-formatted string representation of the attribute value for the given key, if it exists.
|
||||||
/// The `overrides` function can provide custom formatting for specific type.
|
/// The `overrides` function can provide custom formatting for specific type.
|
||||||
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||||
@@ -781,6 +734,11 @@ impl Attributes {
|
|||||||
.find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<T>() } else { None })
|
.find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<T>() } else { None })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The whole column for the given key, resolved once for repeated lane reads.
|
||||||
|
fn column(&self, key: &str) -> Option<&dyn AnyAttribute> {
|
||||||
|
self.attributes.iter().find_map(|(k, attribute)| (k == key).then_some(&**attribute))
|
||||||
|
}
|
||||||
|
|
||||||
/// Removes the entire attribute for the given key, if present.
|
/// Removes the entire attribute for the given key, if present.
|
||||||
fn remove_attribute(&mut self, key: &str) {
|
fn remove_attribute(&mut self, key: &str) {
|
||||||
if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) {
|
if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) {
|
||||||
@@ -818,13 +776,6 @@ impl Attributes {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets a mutable reference to the value at the given index, creating the attribute if it doesn't exist or has the wrong type.
|
|
||||||
fn get_or_insert_default_value<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str, index: usize) -> &mut T {
|
|
||||||
let attribute_position = self.find_or_create_attribute::<T>(key);
|
|
||||||
let attribute = (*self.attributes[attribute_position].1).as_any_mut().downcast_mut::<Attribute<T>>().unwrap();
|
|
||||||
&mut attribute.0[index]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the value at the given index in the attribute for the given key.
|
/// Sets the value at the given index in the attribute for the given key.
|
||||||
/// Creates the attribute with defaults if it doesn't exist.
|
/// Creates the attribute with defaults if it doesn't exist.
|
||||||
fn set_value<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, index: usize, value: T) {
|
fn set_value<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, index: usize, value: T) {
|
||||||
@@ -1065,14 +1016,6 @@ impl<T> List<T> {
|
|||||||
self.attributes.set_value(key, index, value);
|
self.attributes.set_value(key, index, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replaces (or adds) an attribute from a type-erased source. The source is wrapped or truncated to match this list's item count.
|
|
||||||
pub fn set_attribute_dyn(&mut self, key: impl Into<String>, source: AttributeDyn) {
|
|
||||||
let key = key.into();
|
|
||||||
self.attributes.attributes.retain(|(k, _)| k != &key);
|
|
||||||
let new_attribute = source.cloned_to_length(&key, self.element.len());
|
|
||||||
self.attributes.attributes.push((key, new_attribute));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
|
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
|
||||||
/// Falls back to default if the value's type doesn't match an existing attribute.
|
/// Falls back to default if the value's type doesn't match an existing attribute.
|
||||||
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
|
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
|
||||||
@@ -1092,12 +1035,6 @@ impl<T> List<T> {
|
|||||||
self.attributes.remove_attribute(key);
|
self.attributes.remove_attribute(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the given closure on a mutable reference to the attribute value at the given item index,
|
|
||||||
/// creating the attribute with defaults if it doesn't exist, and returns the closure's result.
|
|
||||||
pub fn with_attribute_mut_or_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static, R, F: FnOnce(&mut U) -> R>(&mut self, key: &str, index: usize, f: F) -> R {
|
|
||||||
f(self.attributes.get_or_insert_default_value::<U>(key, index))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a debug-formatted display string for the attribute at the given item index and key.
|
/// Returns a debug-formatted display string for the attribute at the given item index and key.
|
||||||
pub fn attribute_display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
pub fn attribute_display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||||
self.attributes.display_value(key, index, overrides)
|
self.attributes.display_value(key, index, overrides)
|
||||||
@@ -1143,48 +1080,12 @@ impl<T> List<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: BoundingBox> BoundingBox for List<T> {
|
impl<T: BoundingBox> BoundingBox for List<T> {
|
||||||
/// Computes the combined bounding box of all items, composing each item's transform attribute with the given transform.
|
|
||||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||||
let mut combined_bounds = None;
|
crate::bounds::lane_bounding_box(self, transform, include_stroke)
|
||||||
|
|
||||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
|
||||||
match element.bounding_box(transform * item_transform, include_stroke) {
|
|
||||||
RenderBoundingBox::None => continue,
|
|
||||||
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
|
|
||||||
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
|
||||||
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
|
|
||||||
None => combined_bounds = Some(bounds),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match combined_bounds {
|
|
||||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
|
||||||
None => RenderBoundingBox::None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||||
// `Infinite` items are skipped here (rather than propagating outward as in `bounding_box`) so a finite sibling in a mixed group dictates the framing
|
crate::bounds::lane_thumbnail_bounding_box(self, transform, include_stroke)
|
||||||
let mut combined_bounds = None;
|
|
||||||
let mut any_infinite = false;
|
|
||||||
|
|
||||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
|
||||||
match element.thumbnail_bounding_box(transform * item_transform, include_stroke) {
|
|
||||||
RenderBoundingBox::None => continue,
|
|
||||||
RenderBoundingBox::Infinite => any_infinite = true,
|
|
||||||
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
|
|
||||||
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
|
|
||||||
None => combined_bounds = Some(bounds),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match (combined_bounds, any_infinite) {
|
|
||||||
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
|
||||||
(None, true) => RenderBoundingBox::Infinite,
|
|
||||||
(None, false) => RenderBoundingBox::None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1211,6 +1112,41 @@ impl<T> Default for List<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A marker's column on a [`List`], absent when the list carries no such key.
|
||||||
|
pub struct ListColumn<'a, A: crate::attribute::Attribute> {
|
||||||
|
stored: Option<&'a dyn AnyAttribute>,
|
||||||
|
marker: std::marker::PhantomData<A>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, A: crate::attribute::Attribute> crate::lane::LaneColumn<'a, A> for ListColumn<'a, A> {
|
||||||
|
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||||
|
self.stored.and_then(|column| column.get_any(lane)).and_then(A::from_stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> crate::lane::LaneSource for List<T> {
|
||||||
|
type Element = T;
|
||||||
|
type Column<'a, A: crate::attribute::Attribute>
|
||||||
|
= ListColumn<'a, A>
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
|
||||||
|
fn lane_count(&self) -> usize {
|
||||||
|
List::len(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn element(&self, lane: usize) -> Option<&T> {
|
||||||
|
List::element(self, lane)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column<A: crate::attribute::Attribute>(&self) -> ListColumn<'_, A> {
|
||||||
|
ListColumn {
|
||||||
|
stored: self.attributes.column(A::NAME),
|
||||||
|
marker: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<T: CacheHash> CacheHash for List<T> {
|
impl<T: CacheHash> CacheHash for List<T> {
|
||||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||||
self.element.cache_hash(state);
|
self.element.cache_hash(state);
|
||||||
|
|||||||
@@ -0,0 +1,685 @@
|
|||||||
|
use crate::context::InjectIndex;
|
||||||
|
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt, Level};
|
||||||
|
use std::cell::Cell;
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::mem::MaybeUninit;
|
||||||
|
use std::ops::{Deref, Range};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum BatchStatus<'a> {
|
||||||
|
/// Producer-resident lanes, shared: read-only for the caller. The extent
|
||||||
|
/// is the producer's knowledge of the level's total after serving the
|
||||||
|
/// range: a sound lower bound, or exact; a batch shorter than the
|
||||||
|
/// requested range carries `Exactly` and marks the end of the data.
|
||||||
|
Lent(RecordBatch<'a>, Finality, Extent),
|
||||||
|
/// The caller's scratch, filled: the caller is the exclusive owner and may
|
||||||
|
/// mutate the lanes or reclaim the buffer for in-place reuse. The extent
|
||||||
|
/// hint is as for `Lent`.
|
||||||
|
Filled(RecordBatchMut<'a>, Finality, Extent),
|
||||||
|
/// No batch implementation behind this input; a driver answers with the
|
||||||
|
/// per-lane serve and copy-out loop ([`crate::record::fill_frames`]).
|
||||||
|
Unbatched,
|
||||||
|
Pending,
|
||||||
|
Error(GraphError),
|
||||||
|
NeedBuffer,
|
||||||
|
InvalidRange,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Interrupt> for BatchStatus<'_> {
|
||||||
|
fn from(interrupt: Interrupt) -> Self {
|
||||||
|
match interrupt {
|
||||||
|
Interrupt::Pending => BatchStatus::Pending,
|
||||||
|
Interrupt::Error(error) => BatchStatus::Error(*error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A shared view over a batch of records in one flat frame buffer: lane `i`
|
||||||
|
/// starts at `frames + i * stride` with `stride = layout.lane_stride()`.
|
||||||
|
/// Frame bytes carry no drop glue (droppable elements ride parked,
|
||||||
|
/// arena-owned), so the view has no drop obligation; `'a` covers the frames
|
||||||
|
/// and the layout.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct RecordBatch<'a> {
|
||||||
|
frames: *const u8,
|
||||||
|
stride: usize,
|
||||||
|
len: usize,
|
||||||
|
layout: &'a crate::record::Layout,
|
||||||
|
_lifetime: PhantomData<&'a [u8]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> RecordBatch<'a> {
|
||||||
|
/// # Safety
|
||||||
|
/// `frames` must hold `len` initialized records of `layout`, packed at
|
||||||
|
/// `layout.lane_stride()` stride and valid for `'a`.
|
||||||
|
pub unsafe fn new(frames: *const u8, len: usize, layout: &'a crate::record::Layout) -> Self {
|
||||||
|
Self {
|
||||||
|
frames,
|
||||||
|
stride: layout.lane_stride(),
|
||||||
|
len,
|
||||||
|
layout,
|
||||||
|
_lifetime: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.len
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.len == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||||
|
self.layout
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn frames_ptr(&self) -> *const u8 {
|
||||||
|
self.frames
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, lane: usize) -> RecordLane<'a> {
|
||||||
|
assert!(lane < self.len, "lane {lane} out of bounds for a batch of {}", self.len);
|
||||||
|
RecordLane {
|
||||||
|
// SAFETY: in-bounds by the assert against the constructor's contract.
|
||||||
|
rec: unsafe { crate::record::Rec::new(self.frames.add(lane * self.stride)) },
|
||||||
|
layout: self.layout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'a>)) {
|
||||||
|
for lane in 0..self.len {
|
||||||
|
f(lane, self.get(lane));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The exclusive view over caller-owned frames (the `Filled` status): while it
|
||||||
|
/// lives, the borrow of the caller's scratch guarantees nobody else can read
|
||||||
|
/// the lanes, so mutating them or reclaiming the buffer is sound.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RecordBatchMut<'a> {
|
||||||
|
scratch: &'a mut [MaybeUninit<u64>],
|
||||||
|
len: usize,
|
||||||
|
layout: &'a crate::record::Layout,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> RecordBatchMut<'a> {
|
||||||
|
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
|
||||||
|
/// which is what makes the initialized prefix a fact rather than a contract.
|
||||||
|
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
|
||||||
|
debug_assert!(len * layout.lane_stride() <= scratch.len() * 8);
|
||||||
|
Self { scratch, len, layout }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.len
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.len == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||||
|
self.layout
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the lanes without giving up exclusivity.
|
||||||
|
pub fn share(&self) -> RecordBatch<'_> {
|
||||||
|
// SAFETY: the constructor's contract, narrowed to the reborrow's scope.
|
||||||
|
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gives up exclusivity for the batch's whole lifetime.
|
||||||
|
pub fn into_shared(self) -> RecordBatch<'a> {
|
||||||
|
// SAFETY: the constructor's contract; the exclusive borrow is consumed.
|
||||||
|
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One lane's record: its pointer paired with the batch's layout.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct RecordLane<'a> {
|
||||||
|
rec: crate::record::Rec<'a>,
|
||||||
|
layout: &'a crate::record::Layout,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> RecordLane<'a> {
|
||||||
|
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||||
|
self.layout
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rec(&self) -> crate::record::Rec<'a> {
|
||||||
|
self.rec
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The element at offset 0.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `U` must be the record's element type, proven at the consumer's wiring.
|
||||||
|
pub unsafe fn element<U: Copy>(&self) -> U {
|
||||||
|
unsafe { self.rec.element::<U>() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attribute `A` through a token, `None` where the token was minted against
|
||||||
|
/// another layout than this lane's.
|
||||||
|
pub fn try_attr_at<A: crate::attribute::Attribute>(&self, field: crate::record::FieldOffset<A>) -> Option<A::Value<'a>> {
|
||||||
|
let offset = field.resolve(self.layout)?;
|
||||||
|
// SAFETY: resolving against this lane's own layout pins the offset and
|
||||||
|
// the field's value type, and the batch's contract makes the lane a live
|
||||||
|
// record of that layout.
|
||||||
|
Some(unsafe { self.rec.read::<A::Value<'a>>(offset) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attribute `A` through a token, or its census default where the token is
|
||||||
|
/// absent or names another layout.
|
||||||
|
pub fn attr_at<A: crate::attribute::Attribute>(&self, field: Option<crate::record::FieldOffset<A>>) -> A::Value<'a> {
|
||||||
|
field.and_then(|field| self.try_attr_at(field)).unwrap_or_else(A::default)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attribute `A` at the record's top level, or its census default when the
|
||||||
|
/// layout does not carry it. Mints a token per call; lane loops hoist the
|
||||||
|
/// mint instead.
|
||||||
|
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'a> {
|
||||||
|
self.attr_at(crate::record::FieldOffset::<A>::of(self.layout, 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One lane of a materialized level, element-typed. In a kernel's element
|
||||||
|
/// position the output frame is copied from this lane.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Lane<'a, T> {
|
||||||
|
lane: RecordLane<'a>,
|
||||||
|
_element: PhantomData<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// A view regardless of `T`: copying a lane copies no record.
|
||||||
|
impl<T> Clone for Lane<'_, T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Copy for Lane<'_, T> {}
|
||||||
|
|
||||||
|
impl<'a, T> Deref for Lane<'a, T> {
|
||||||
|
type Target = RecordLane<'a>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &RecordLane<'a> {
|
||||||
|
&self.lane
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A materialized nesting level handed to a folding kernel: a thin element-typed
|
||||||
|
/// view over the [`RecordBatch`] the level was collected into.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct List<'a, T> {
|
||||||
|
batch: RecordBatch<'a>,
|
||||||
|
_element: PhantomData<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// A shared view regardless of `T`: copying the list copies no elements.
|
||||||
|
impl<T> Clone for List<'_, T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Copy for List<'_, T> {}
|
||||||
|
|
||||||
|
impl<'a, T> List<'a, T> {
|
||||||
|
/// # Safety
|
||||||
|
/// `T` must be the batch's record element type, proven at the consumer's
|
||||||
|
/// wiring, and the batch's frames must stay valid for the evaluation:
|
||||||
|
/// arena-resident batches qualify, caller stack scratch does not.
|
||||||
|
pub unsafe fn new(batch: RecordBatch<'a>) -> Self {
|
||||||
|
Self { batch, _element: PhantomData }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The level as a group item over the same frames, without copying.
|
||||||
|
/// Panics where a parked element or field lacks content glue.
|
||||||
|
pub fn as_group_item(&self) -> crate::record::GroupItem<'a> {
|
||||||
|
// SAFETY: `List::new` established the frames stay valid for the
|
||||||
|
// evaluation.
|
||||||
|
unsafe { crate::record::GroupItem::from_resident(self.batch) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.batch.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.batch.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn batch(&self) -> RecordBatch<'a> {
|
||||||
|
self.batch
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, index: usize) -> T
|
||||||
|
where
|
||||||
|
T: Copy,
|
||||||
|
{
|
||||||
|
// SAFETY: `List::new` established that `T` is the batch's element type.
|
||||||
|
unsafe { self.batch.get(index).element::<T>() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Borrows lane `index`'s element, through the park for droppable types.
|
||||||
|
pub fn element_ref(&self, index: usize) -> &T {
|
||||||
|
// SAFETY: `List::new` established that `T` is the batch's element type,
|
||||||
|
// and the borrow lives within the batch's own lifetime.
|
||||||
|
unsafe { crate::record::borrow_element::<T>(self.batch.get(index).rec()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lane `index`'s record, for attribute reads beside the element.
|
||||||
|
pub fn lane(&self, index: usize) -> Lane<'a, T> {
|
||||||
|
Lane {
|
||||||
|
lane: self.batch.get(index),
|
||||||
|
_element: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn iter(&self) -> impl Iterator<Item = T> + '_
|
||||||
|
where
|
||||||
|
T: Copy,
|
||||||
|
{
|
||||||
|
(0..self.len()).map(move |index| self.get(index))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: Copy> IntoIterator for List<'a, T> {
|
||||||
|
type Item = T;
|
||||||
|
type IntoIter = ListIter<'a, T>;
|
||||||
|
|
||||||
|
fn into_iter(self) -> ListIter<'a, T> {
|
||||||
|
ListIter { list: self, position: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ListIter<'a, T> {
|
||||||
|
list: List<'a, T>,
|
||||||
|
position: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Copy> Iterator for ListIter<'_, T> {
|
||||||
|
type Item = T;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<T> {
|
||||||
|
(self.position < self.list.len()).then(|| {
|
||||||
|
let value = self.list.get(self.position);
|
||||||
|
self.position += 1;
|
||||||
|
value
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Node<Input> {
|
||||||
|
/// Serves the node's record through the caller's claim: the writes land
|
||||||
|
/// in the claim and the returned proof is mintable only by its closing
|
||||||
|
/// methods, so the served record is of the claimed layout by
|
||||||
|
/// construction. The caller claims the frame at [`Node::layout`] out of
|
||||||
|
/// its own frame space, and the claim carries what is left, so the node
|
||||||
|
/// takes exactly its own frame out of the caller's free space.
|
||||||
|
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>;
|
||||||
|
|
||||||
|
/// The count of items at one absolute nesting level (innermost `0`). The
|
||||||
|
/// leveled primitive a structure node overrides to report a pushed level's
|
||||||
|
/// size; the scalar base is one item at every level. Uncertainty rides the
|
||||||
|
/// `GPoll` status axis.
|
||||||
|
fn extent_at<'e>(&self, _input: &Input, _level: u8, _frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
GPoll::Final(Extent::Exactly(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The composite domain query derived from [`extent_at`](Node::extent_at):
|
||||||
|
/// one level, the product of the levels below or above it, or the whole
|
||||||
|
/// domain's flat count. Consumers query this; nodes only write `extent_at`.
|
||||||
|
fn extent<'e>(&self, input: &Input, at: Level, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
let product =
|
||||||
|
|range: core::ops::Range<u8>, frames: &crate::record::Frames<'e>| range.fold(GPoll::Final(Extent::Exactly(1)), |acc, level| Extent::mul(acc, self.extent_at(input, level, frames)));
|
||||||
|
match at {
|
||||||
|
Level::At(level) => self.extent_at(input, level, frames),
|
||||||
|
Level::Below(level) => product(0..level, frames),
|
||||||
|
Level::Above(level) => product((level + 1)..self.depth(), frames),
|
||||||
|
Level::Total => product(0..self.depth(), frames),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node's domain depth (number of nesting levels; `0` = scalar), baked
|
||||||
|
/// into the record layout at wiring.
|
||||||
|
fn depth(&self) -> u8 {
|
||||||
|
self.layout().depth
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Introspection access to node-resident records; `None` for ordinary nodes.
|
||||||
|
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The record layout of this node's output; the shared empty layout for
|
||||||
|
/// element-only producers. Consumers read their carrier's layout through
|
||||||
|
/// this at wiring, and the wiring layer derives the root buffer's sizing from
|
||||||
|
/// the same layouts, in the dynamic executor and exported source alike.
|
||||||
|
fn layout(&self) -> &crate::record::Layout {
|
||||||
|
crate::record::empty_layout()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs this node's resolved record layout; a no-op unless it produces records.
|
||||||
|
fn set_layout(&mut self, _layout: crate::record::RecordLayout) {}
|
||||||
|
|
||||||
|
/// Batched evaluation of `range` into caller-provided frame storage of
|
||||||
|
/// `range.len() * layout.lane_stride()` bytes; see [`BatchStatus`]. The
|
||||||
|
/// default advertises no support and drivers fall back to per-lane serves
|
||||||
|
/// with copy-out ([`crate::record::fill_frames`]); overrides exist to beat
|
||||||
|
/// that loop (resident lanes, direct fills, fewer erased calls), never for
|
||||||
|
/// correctness.
|
||||||
|
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||||
|
where
|
||||||
|
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
let _ = (input, range, scratch, frames);
|
||||||
|
BatchStatus::Unbatched
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Input, N> Node<Input> for &N
|
||||||
|
where
|
||||||
|
N: Node<Input> + ?Sized,
|
||||||
|
{
|
||||||
|
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).serve(input, slot)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).extent_at(input, level, frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||||
|
(**self).serialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(&self) -> &crate::record::Layout {
|
||||||
|
(**self).layout()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||||
|
where
|
||||||
|
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).eval_batch(input, range, scratch, frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Input, N> Node<Input> for Box<N>
|
||||||
|
where
|
||||||
|
N: Node<Input> + ?Sized,
|
||||||
|
{
|
||||||
|
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).serve(input, slot)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).extent_at(input, level, frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||||
|
(**self).serialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(&self) -> &crate::record::Layout {
|
||||||
|
(**self).layout()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||||
|
where
|
||||||
|
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).eval_batch(input, range, scratch, frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Input, N> Node<Input> for std::sync::Arc<N>
|
||||||
|
where
|
||||||
|
N: Node<Input> + ?Sized,
|
||||||
|
{
|
||||||
|
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).serve(input, slot)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).extent_at(input, level, frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||||
|
(**self).serialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(&self) -> &crate::record::Layout {
|
||||||
|
(**self).layout()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
|
||||||
|
where
|
||||||
|
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
(**self).eval_batch(input, range, scratch, frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct StatusCell {
|
||||||
|
finality: Cell<Finality>,
|
||||||
|
error: Cell<Option<GraphError>>,
|
||||||
|
no_partial: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for StatusCell {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StatusCell {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
finality: Cell::new(Finality::AllFinal),
|
||||||
|
error: Cell::new(None),
|
||||||
|
no_partial: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn no_partial() -> Self {
|
||||||
|
Self { no_partial: true, ..Self::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claims the input's own frame out of `frames`, serves through it, and
|
||||||
|
/// folds the poll's status into the cell. The claim is the caller's, so
|
||||||
|
/// the input's frame is claimed exactly once per evaluation.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn eval_input<'e, Input, N: Node<Input> + ?Sized>(&self, input_index: usize, node: &N, input: &Input, frames: &crate::record::Frames<'e>) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||||
|
where
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
let slot = frames.claim(node.layout());
|
||||||
|
match node.serve(input, slot) {
|
||||||
|
GPoll::Final(served) => Ok(served.value()),
|
||||||
|
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
|
||||||
|
GPoll::Partial(served) => {
|
||||||
|
self.finality.set(Finality::Partial);
|
||||||
|
Ok(served.value())
|
||||||
|
}
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (served, error) = *boxed;
|
||||||
|
let first = self.error.take();
|
||||||
|
self.error.set(first.or(Some(error.traced(input_index))));
|
||||||
|
Ok(served.value())
|
||||||
|
}
|
||||||
|
GPoll::Pending => Err(Interrupt::Pending),
|
||||||
|
GPoll::Error(mut error) => {
|
||||||
|
error.trace.push(input_index);
|
||||||
|
Err(Interrupt::Error(error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new cell holding a copy of the accumulated status; the error stays in
|
||||||
|
/// place, cloned rather than taken.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn snapshot(&self) -> StatusCell {
|
||||||
|
let error = self.error.take();
|
||||||
|
self.error.set(error.clone());
|
||||||
|
StatusCell {
|
||||||
|
finality: Cell::new(self.finality.get()),
|
||||||
|
error: Cell::new(error),
|
||||||
|
no_partial: self.no_partial,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn finish<T>(self, value: T) -> GPoll<T> {
|
||||||
|
match (self.error.take(), self.finality.get()) {
|
||||||
|
(Some(error), _) => GPoll::Fallback(Box::new((value, error))),
|
||||||
|
(None, Finality::AllFinal) => GPoll::Final(value),
|
||||||
|
(None, Finality::Partial) => GPoll::Partial(value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
|
||||||
|
match poll {
|
||||||
|
GPoll::Final(value) => self.finish(value),
|
||||||
|
GPoll::Partial(_) if self.no_partial => GPoll::Pending,
|
||||||
|
GPoll::Partial(value) => match self.finish(value) {
|
||||||
|
GPoll::Final(value) => GPoll::Partial(value),
|
||||||
|
other => other,
|
||||||
|
},
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (value, error) = *boxed;
|
||||||
|
let first = self.error.take().unwrap_or(error);
|
||||||
|
GPoll::Fallback(Box::new((value, first)))
|
||||||
|
}
|
||||||
|
interrupted => interrupted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct LazyInput<'a, 'f, N> {
|
||||||
|
node: &'a N,
|
||||||
|
cell: &'a StatusCell,
|
||||||
|
input_index: usize,
|
||||||
|
frames: &'a crate::record::Frames<'f>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'f, N> LazyInput<'a, 'f, N> {
|
||||||
|
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize, frames: &'a crate::record::Frames<'f>) -> Self {
|
||||||
|
Self { node, cell, input_index, frames }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn eval<'e, Input>(&self, ctx: &Input) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||||
|
where
|
||||||
|
N: crate::record::DerivedRecordInput<'e, Input>,
|
||||||
|
'f: 'e,
|
||||||
|
{
|
||||||
|
self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The input's composite extent, for kernels that split or shift indices
|
||||||
|
/// over their sources.
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn extent<'e, Input>(&self, ctx: &Input, at: Level) -> GPoll<Extent>
|
||||||
|
where
|
||||||
|
N: Node<Input>,
|
||||||
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
'f: 'e,
|
||||||
|
{
|
||||||
|
self.node.extent(ctx, at, self.frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
use crate::arena::Arena;
|
||||||
|
use crate::context::ExtractArena;
|
||||||
|
use crate::record::{LiftedSource, serve_input};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
struct TestInput<'a> {
|
||||||
|
index: u64,
|
||||||
|
arena: &'a Arena,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InjectIndex for TestInput<'_> {
|
||||||
|
fn set_index(&mut self, index: u64) {
|
||||||
|
self.index = index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> ExtractArena for TestInput<'a> {
|
||||||
|
type ArenaRef = &'a Arena;
|
||||||
|
|
||||||
|
fn arena(&self) -> &'a Arena {
|
||||||
|
self.arena
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn double<'a>() -> LiftedSource<u64, impl Fn(&TestInput<'a>) -> GPoll<u64>> {
|
||||||
|
LiftedSource::new(|input: &TestInput<'a>| GPoll::Final(input.index * 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_advertises_no_batch_support() {
|
||||||
|
let frames = crate::record::test_frames(1 << 16);
|
||||||
|
let arena = Arena::new(1024).unwrap();
|
||||||
|
let input = TestInput { index: 0, arena: &arena };
|
||||||
|
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||||
|
let node = double();
|
||||||
|
assert!(matches!(node.eval_batch(&input, 2..6, Some(&mut scratch), &frames), BatchStatus::Unbatched));
|
||||||
|
assert!(matches!(node.eval_batch(&input, 2..6, None, &frames), BatchStatus::Unbatched));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trait_is_object_safe_across_erased_edges() {
|
||||||
|
let arena = Arena::new(1024).unwrap();
|
||||||
|
let input = TestInput { index: 21, arena: &arena };
|
||||||
|
let node = double();
|
||||||
|
let layout = Node::<TestInput>::layout(&node).clone();
|
||||||
|
let erased: Box<dyn Node<TestInput>> = Box::new(node);
|
||||||
|
let frames = crate::record::test_frames(1 << 12);
|
||||||
|
let GPoll::Final(value) = serve_input(&*erased, &input, &frames) else {
|
||||||
|
panic!("the erased edge must serve a final record");
|
||||||
|
};
|
||||||
|
// SAFETY: the record was served at `layout`, whose element is the output.
|
||||||
|
assert_eq!(unsafe { crate::record::read_element::<u64>(layout.rec(&value)) }, 42);
|
||||||
|
assert!(matches!(erased.eval_batch(&input, 0..2, None, &frames), BatchStatus::Unbatched));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,56 +1,26 @@
|
|||||||
use crate::Node;
|
|
||||||
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||||
use crate::transform::Footprint;
|
use crate::transform::Footprint;
|
||||||
use glam::DVec2;
|
use glam::DVec2;
|
||||||
use graphene_hash::CacheHash;
|
use graphene_hash::CacheHash;
|
||||||
use std::future::Future;
|
|
||||||
use std::marker::PhantomData;
|
|
||||||
|
|
||||||
// Type
|
|
||||||
// TODO: Document this
|
|
||||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
|
||||||
pub struct TypeNode<N: for<'a> Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>);
|
|
||||||
impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode<N, I, O>
|
|
||||||
where
|
|
||||||
N: for<'n> Node<'n, I, Output = O>,
|
|
||||||
{
|
|
||||||
type Output = O;
|
|
||||||
fn eval(&'i self, input: I) -> Self::Output {
|
|
||||||
self.0.eval(input)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reset(&self) {
|
|
||||||
self.0.reset();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
|
||||||
self.0.serialize()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode<N, I, <N as Node<'i, I>>::Output> {
|
|
||||||
pub fn new(node: N) -> Self {
|
|
||||||
Self(node, PhantomData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode<N, I, <N as Node<'i, I>>::Output> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Self(self.0.clone(), self.1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Node<'i, I>>::Output> {}
|
|
||||||
|
|
||||||
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
|
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
|
||||||
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
|
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
|
||||||
pub trait Convert<T, C>: Sized {
|
pub trait Convert<T, C>: Sized {
|
||||||
/// Converts this type into the (usually inferred) output type.
|
/// Converts this type into the (usually inferred) output type.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
fn convert(self, footprint: Footprint, converter: C) -> T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The asynchronous counterpart of [`Convert`]; a conversion pair implements exactly one of the two traits.
|
||||||
|
pub trait ConvertAsync<T, C>: Sized {
|
||||||
|
#[must_use]
|
||||||
|
fn convert(self, footprint: Footprint, converter: C) -> crate::runtime::SourceFuture<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||||
/// Converts this type into a `String` using its `ToString` implementation.
|
/// Converts this type into a `String` using its `ToString` implementation.
|
||||||
#[inline]
|
#[inline]
|
||||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||||
self.to_string()
|
self.to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,7 +30,7 @@ pub trait ListConvert<U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> List<U> {
|
fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||||
let list: List<U> = self
|
let list: List<U> = self
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|row| {
|
.map(|row| {
|
||||||
@@ -74,9 +44,9 @@ impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
|||||||
|
|
||||||
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
|
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
|
||||||
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
|
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
|
||||||
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
|
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph sources to the dyn input.
|
||||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
|
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||||
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
||||||
AttributeDyn(Box::new(Attribute(values)))
|
AttributeDyn(Box::new(Attribute(values)))
|
||||||
}
|
}
|
||||||
@@ -84,9 +54,9 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
|
|||||||
|
|
||||||
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
|
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
|
||||||
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
|
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
|
||||||
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
|
/// alone, with the compiler-inserted convert handling each concrete value type at the input level.
|
||||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
|
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||||
AttributeValueDyn(Box::new(self))
|
AttributeValueDyn(Box::new(self))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,13 +65,13 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
|
|||||||
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
|
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
|
||||||
/// instead of monomorphizing over every possible carrier list type.
|
/// instead of monomorphizing over every possible carrier list type.
|
||||||
impl<T: Send> Convert<ListDyn, ()> for List<T> {
|
impl<T: Send> Convert<ListDyn, ()> for List<T> {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||||
self.into()
|
self.into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Convert<DVec2, ()> for DVec2 {
|
impl Convert<DVec2, ()> for DVec2 {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -115,7 +85,7 @@ pub trait FromAnchorPosition {
|
|||||||
|
|
||||||
// Converts a position into a vector path composed of a single anchor point
|
// Converts a position into a vector path composed of a single anchor point
|
||||||
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> List<T> {
|
fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||||
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
|
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,7 +94,7 @@ impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
|||||||
macro_rules! impl_convert {
|
macro_rules! impl_convert {
|
||||||
($from:ty, $to:ty) => {
|
($from:ty, $to:ty) => {
|
||||||
impl Convert<$to, ()> for $from {
|
impl Convert<$to, ()> for $from {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
fn convert(self, _: Footprint, _: ()) -> $to {
|
||||||
self as $to
|
self as $to
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -146,7 +116,7 @@ macro_rules! impl_convert {
|
|||||||
impl_convert!(usize, $to);
|
impl_convert!(usize, $to);
|
||||||
|
|
||||||
impl Convert<DVec2, ()> for $to {
|
impl Convert<DVec2, ()> for $to {
|
||||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||||
DVec2::splat(self as f64)
|
DVec2::splat(self as f64)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,272 @@
|
|||||||
|
//! Raw typed access to a record at a wiring-proven layout.
|
||||||
|
|
||||||
|
use super::layout::element_parked;
|
||||||
|
use crate::attribute;
|
||||||
|
use crate::gpoll::GPoll;
|
||||||
|
|
||||||
|
/// A view of one record: a pointer whose layout is proven at wiring, borrowing
|
||||||
|
/// the storage it points into for `'r`.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Rec<'r>(pub(in crate::record) *const u8, pub(in crate::record) std::marker::PhantomData<&'r u8>);
|
||||||
|
|
||||||
|
impl<'r> Rec<'r> {
|
||||||
|
/// # Safety
|
||||||
|
/// `ptr` must point to a live record of the layout the consumer resolved
|
||||||
|
/// at wiring, valid for `'r` and until the owning slot is next written.
|
||||||
|
pub unsafe fn new(ptr: *const u8) -> Self {
|
||||||
|
Rec(ptr, std::marker::PhantomData)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `offset` must be a field offset of the record's layout and `T` the
|
||||||
|
/// field's type; both are proven at wiring. The record's base is aligned
|
||||||
|
/// to its layout, so field reads are aligned.
|
||||||
|
pub unsafe fn read<T: Copy>(self, offset: usize) -> T {
|
||||||
|
unsafe { self.0.add(offset).cast::<T>().read() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `T` must be the record's element type; the element sits at offset 0.
|
||||||
|
pub unsafe fn element<T: Copy>(self) -> T {
|
||||||
|
unsafe { self.read(0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ptr(self) -> *const u8 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An opaque record value: every non-empty record spills to a claimed frame
|
||||||
|
/// and the value carries its pointer, while an empty record carries nothing.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct RecordValue<'e> {
|
||||||
|
pub(in crate::record) ptr: *const u8,
|
||||||
|
_lifetime: std::marker::PhantomData<&'e ()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for RecordValue<'_> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("RecordValue(..)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAFETY: `element_write` requires the element `Send + Sync` and attribute payloads
|
||||||
|
// are `Copy` or arena-backed, so the record bytes behind the pointer are thread-safe;
|
||||||
|
// `'e` ties the pointer's validity to the shared arena and record-stack discipline.
|
||||||
|
unsafe impl Send for RecordValue<'_> {}
|
||||||
|
// SAFETY: as `Send`.
|
||||||
|
unsafe impl Sync for RecordValue<'_> {}
|
||||||
|
|
||||||
|
impl<'e> RecordValue<'e> {
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn zeroed() -> Self {
|
||||||
|
RecordValue {
|
||||||
|
ptr: std::ptr::null(),
|
||||||
|
_lifetime: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The inline storage under construction; writes land in the value itself.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn as_mut_ptr(&mut self) -> *mut u8 {
|
||||||
|
(&raw mut *self).cast()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn spilled(rec: Rec<'_>) -> Self {
|
||||||
|
RecordValue {
|
||||||
|
ptr: rec.ptr(),
|
||||||
|
_lifetime: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebinds the eval lifetime, lengthening a derived scope's record back
|
||||||
|
/// onto the outer evaluation's. Sound only because the record's bytes live
|
||||||
|
/// in the outer caller's slot region: a derived context shortens the
|
||||||
|
/// caller's frame space rather than owning any, so the frame the record
|
||||||
|
/// sits in outlives the derivation, exactly as it outlives the arena
|
||||||
|
/// borrow the derived context carries.
|
||||||
|
pub(in crate::record) fn rebind<'a>(self) -> RecordValue<'a> {
|
||||||
|
RecordValue {
|
||||||
|
ptr: self.ptr,
|
||||||
|
_lifetime: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a declared attribute out of a record at a wiring-resolved offset,
|
||||||
|
/// falling back to the marker's census default where the layout does not carry
|
||||||
|
/// the name.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `rec` must be a live record of the layout `offset` was resolved against,
|
||||||
|
/// and `offset`, where present, must be that layout's offset for `A` at the
|
||||||
|
/// read's level. The census admits one value type per attribute name and
|
||||||
|
/// panics on a conflicting declaration, so that field's bytes are a value of
|
||||||
|
/// `A::Value`, differing from the read type only in `'e`, which must not
|
||||||
|
/// outlive the evaluation a parked payload is arena-resident for.
|
||||||
|
pub unsafe fn read_at<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<usize>) -> attribute::Attr<'e, A> {
|
||||||
|
attribute::Attr(match offset {
|
||||||
|
// SAFETY: the caller's contract.
|
||||||
|
Some(offset) => unsafe { rec.read::<A::Value<'e>>(offset) },
|
||||||
|
None => A::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The read-less [`DerivedLazyInput`] glue: the token alone.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `rec` must be a spilled record's frame.
|
||||||
|
pub unsafe fn token_only<'e>(rec: Rec<'_>, _reads: &[Option<usize>]) -> RecordValue<'e> {
|
||||||
|
RecordValue::spilled(rec)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `offset` must be a field offset of the layout of the record under
|
||||||
|
/// construction at `dst` and `T` the field's type; both are proven at wiring.
|
||||||
|
pub unsafe fn write_field<T>(dst: *mut u8, offset: usize, value: T) {
|
||||||
|
unsafe { dst.add(offset).cast::<T>().write(value) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// The record's element must be a `T` in the form [`element_parked`] picks,
|
||||||
|
/// and the borrow is only valid while the record is.
|
||||||
|
pub unsafe fn borrow_element<'e, T>(rec: Rec<'_>) -> &'e T {
|
||||||
|
match element_parked::<T>() {
|
||||||
|
true => unsafe { rec.element::<&T>() },
|
||||||
|
false => unsafe { &*rec.ptr().cast::<T>() },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// The record's element must be a `T` in the form [`element_parked`] picks.
|
||||||
|
pub unsafe fn read_element<T: Clone>(rec: Rec<'_>) -> T {
|
||||||
|
unsafe { borrow_element::<T>(rec) }.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `dst` must be fresh element storage of a record whose element is `T`.
|
||||||
|
/// `None` reports arena exhaustion for a parked element.
|
||||||
|
pub unsafe fn write_element<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
|
||||||
|
unsafe { write_element_sized(dst, value, arena, 0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`write_element`] with the park glue's estimate of the heap `value` owns.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// As [`write_element`].
|
||||||
|
pub unsafe fn write_element_sized<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
|
||||||
|
// SAFETY: the caller's contract; `T::Static` is the element type's own key.
|
||||||
|
unsafe { write_element_keyed(dst, value, arena, retained, std::any::TypeId::of::<T::Static>()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`write_element_sized`] for replay glue already holding the element's
|
||||||
|
/// static form, whose key the element type it replays into supplies.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// As [`write_element`], and `type_of` must be that element type's key, since
|
||||||
|
/// a park carrying it is what [`Promotion::move_park`] moves at.
|
||||||
|
pub(in crate::record) unsafe fn write_element_keyed<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize, type_of: std::any::TypeId) -> Option<()> {
|
||||||
|
match element_parked::<T>() {
|
||||||
|
true => {
|
||||||
|
let (parked, _) = arena.alloc_sized_as(value, retained, type_of)?;
|
||||||
|
unsafe { dst.cast::<&T>().write(parked) };
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
false => {
|
||||||
|
unsafe { dst.cast::<T>().write(value) };
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finishes a carried record frame: the element lands beside the fields
|
||||||
|
/// already carried into `dst`, and inline frames copy out of the scratch
|
||||||
|
/// bytes. Arena exhaustion of a parked element reports as an error poll.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `dst` must be the claimed frame (or inline scratch when `frame_bytes` is
|
||||||
|
/// 0) of a record whose element is `T` and whose frame size is `frame_bytes`,
|
||||||
|
/// with every carried field already written.
|
||||||
|
pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::StaticTypeSized>(
|
||||||
|
poll: GPoll<T>,
|
||||||
|
dst: *mut u8,
|
||||||
|
frame_bytes: usize,
|
||||||
|
arena: &'e crate::arena::Arena,
|
||||||
|
) -> GPoll<RecordValue<'e>> {
|
||||||
|
let build = |element: T| {
|
||||||
|
let written = unsafe { write_element(dst, element, arena) };
|
||||||
|
written.map(|()| match frame_bytes {
|
||||||
|
0 => unsafe { dst.cast::<RecordValue>().read() },
|
||||||
|
_ => RecordValue::spilled(unsafe { Rec::new(dst.cast_const()) }),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let exhausted = || {
|
||||||
|
GPoll::Error(Box::new(crate::gpoll::GraphError {
|
||||||
|
kind: crate::gpoll::ErrorKind::ArenaExhausted,
|
||||||
|
trace: Vec::new(),
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
match poll {
|
||||||
|
GPoll::Final(element) => build(element).map_or_else(exhausted, GPoll::Final),
|
||||||
|
GPoll::Partial(element) => build(element).map_or_else(exhausted, GPoll::Partial),
|
||||||
|
GPoll::Fallback(boxed) => {
|
||||||
|
let (element, error) = *boxed;
|
||||||
|
build(element).map_or_else(exhausted, |value| GPoll::Fallback(Box::new((value, error))))
|
||||||
|
}
|
||||||
|
GPoll::Pending => GPoll::Pending,
|
||||||
|
GPoll::Error(error) => GPoll::Error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `src` must be a record of the plan's source layout and `dst` a buffer of
|
||||||
|
/// the plan's target layout; both are proven at wiring.
|
||||||
|
pub unsafe fn apply_plan(src: Rec<'_>, dst: *mut u8, plan: &[(usize, usize, usize)]) {
|
||||||
|
for &(from, to, size) in plan {
|
||||||
|
unsafe { std::ptr::copy_nonoverlapping(src.ptr().add(from), dst.add(to), size) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value with its lifetimes substituted by `'static`, for erased storage
|
||||||
|
/// whose reads re-bind a live lifetime.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// The erased value's borrows must not be used past their real lifetimes: the
|
||||||
|
/// stored form may only be read through a surface that re-binds a lifetime no
|
||||||
|
/// longer than the borrows' own, or after deep glue replaced every borrow with
|
||||||
|
/// owned content.
|
||||||
|
pub unsafe fn erase_static<T: dyn_any::StaticTypeSized>(value: T) -> T::Static {
|
||||||
|
let value = std::mem::ManuallyDrop::new(value);
|
||||||
|
// SAFETY: `Static` is `Self` with lifetimes substituted, layout-identical
|
||||||
|
// by `StaticTypeSized`'s contract.
|
||||||
|
unsafe { std::ptr::read((&raw const value).cast::<T::Static>()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn elements_write_and_read_in_their_picked_form() {
|
||||||
|
let arena = crate::arena::Arena::new(256).unwrap();
|
||||||
|
|
||||||
|
let mut inline = [0u64; 2];
|
||||||
|
unsafe { write_element(inline.as_mut_ptr().cast(), 4.5f64, &arena) }.unwrap();
|
||||||
|
let rec = unsafe { Rec::new(inline.as_ptr().cast()) };
|
||||||
|
assert_eq!(unsafe { *borrow_element::<f64>(rec) }, 4.5);
|
||||||
|
assert_eq!(unsafe { read_element::<f64>(rec) }, 4.5);
|
||||||
|
|
||||||
|
let mut parked = [0u64; 2];
|
||||||
|
unsafe { write_element(parked.as_mut_ptr().cast(), String::from("moved once"), &arena) }.unwrap();
|
||||||
|
let rec = unsafe { Rec::new(parked.as_ptr().cast()) };
|
||||||
|
assert_eq!(unsafe { borrow_element::<String>(rec) }.as_str(), "moved once");
|
||||||
|
assert_eq!(unsafe { read_element::<String>(rec) }, "moved once");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn record_values_are_one_word() {
|
||||||
|
assert_eq!(size_of::<RecordValue>(), 8);
|
||||||
|
assert_eq!(align_of::<RecordValue>(), 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
//! The evaluation's record frame storage.
|
||||||
|
|
||||||
|
use super::access::RecordValue;
|
||||||
|
use super::layout::Layout;
|
||||||
|
use super::serve::{FrameClaim, SlotRun};
|
||||||
|
|
||||||
|
/// The evaluation's record frame space: a grow-only buffer the executor owns
|
||||||
|
/// and lends by `&mut`, sized by the wiring-derived frame need, so exhaustion
|
||||||
|
/// is an accounting failure the debug assertion catches rather than a hot-path
|
||||||
|
/// branch. Frame bytes carry no drop glue, so growth and reuse are plain
|
||||||
|
/// buffer operations.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct FrameArena {
|
||||||
|
buf: Vec<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FrameArena {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { buf: Vec::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Grows the buffer to hold `bytes`, the root's wiring-derived frame need.
|
||||||
|
/// Grow-only, so repeated evaluations reuse one allocation.
|
||||||
|
pub fn reserve(&mut self, bytes: usize) {
|
||||||
|
let words = bytes.div_ceil(8).max(1);
|
||||||
|
if self.buf.len() < words {
|
||||||
|
self.buf.resize(words, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole buffer as free space, for one evaluation.
|
||||||
|
pub fn frames(&mut self) -> Frames<'_> {
|
||||||
|
let base = self.buf.as_mut_ptr().cast::<u8>();
|
||||||
|
Frames {
|
||||||
|
base: std::cell::Cell::new(base),
|
||||||
|
words: std::cell::Cell::new(self.buf.len()),
|
||||||
|
bounds: (base as usize, self.buf.len() * 8),
|
||||||
|
_lifetime: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The free frame space at one point of an evaluation. [`Self::claim`] splits
|
||||||
|
/// a node's own frame off the front and the claim carries the remainder, so a
|
||||||
|
/// node's inputs claim beyond its frame, one after another, and the space they
|
||||||
|
/// used is free again once the claim dies: the release is the claim's
|
||||||
|
/// lifetime, not a rewind contract. The cursor is shared through `&self` so
|
||||||
|
/// the lazy inputs a kernel holds claim beyond each other rather than over each
|
||||||
|
/// other. Covariant in `'e`, so a claim minted at the evaluation shortens onto
|
||||||
|
/// a derived context's arena lifetime.
|
||||||
|
pub struct Frames<'e> {
|
||||||
|
base: std::cell::Cell<*mut u8>,
|
||||||
|
words: std::cell::Cell<usize>,
|
||||||
|
/// The whole buffer as (address, bytes), which stays fixed while claims
|
||||||
|
/// advance the cursor, so a promote can range-check a reference against it.
|
||||||
|
bounds: (usize, usize),
|
||||||
|
_lifetime: std::marker::PhantomData<&'e ()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Frames<'_> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Frames").field("free_words", &self.words.get()).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'e> Frames<'e> {
|
||||||
|
/// An independent cursor over the same free space: claims made through it
|
||||||
|
/// are free again when it dies, so a repeated evaluation reuses one region.
|
||||||
|
/// Two live cursors hand out the same region, so only one may be claimed
|
||||||
|
/// from at a time.
|
||||||
|
pub fn reborrow(&self) -> Frames<'e> {
|
||||||
|
Frames {
|
||||||
|
base: std::cell::Cell::new(self.base.get()),
|
||||||
|
words: std::cell::Cell::new(self.words.get()),
|
||||||
|
bounds: self.bounds,
|
||||||
|
_lifetime: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole frame buffer as (address, bytes), the range a promote treats
|
||||||
|
/// as evaluation-lived.
|
||||||
|
pub fn bounds(&self) -> (usize, usize) {
|
||||||
|
self.bounds
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs claims against this space and gives it back on the guard's drop, so
|
||||||
|
/// a loop that evaluates a subtree per iteration reuses the same region.
|
||||||
|
pub fn scope(&self) -> FrameScope<'_, 'e> {
|
||||||
|
FrameScope {
|
||||||
|
frames: self,
|
||||||
|
base: self.base.get(),
|
||||||
|
words: self.words.get(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The words still free, the observable the frame accounting asserts on.
|
||||||
|
pub fn free_words(&self) -> usize {
|
||||||
|
self.words.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claims `layout`'s frame at the front of the free space; the claim
|
||||||
|
/// carries the remainder, and an inline layout's record builds in the
|
||||||
|
/// claim itself.
|
||||||
|
pub fn claim<'l>(&self, layout: &'l Layout) -> FrameClaim<'e, 'l> {
|
||||||
|
let frame = match layout.frame_bytes() {
|
||||||
|
0 => None,
|
||||||
|
bytes => Some(self.split(bytes)),
|
||||||
|
};
|
||||||
|
FrameClaim {
|
||||||
|
layout,
|
||||||
|
inline: RecordValue::zeroed(),
|
||||||
|
frame,
|
||||||
|
free: self.reborrow(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits `bytes` (rounded to word alignment) off the front.
|
||||||
|
fn split(&self, bytes: usize) -> *mut u8 {
|
||||||
|
let words = bytes.div_ceil(8);
|
||||||
|
debug_assert!(words <= self.words.get(), "record frame space exhausted: the root buffer must cover the graph's frame need");
|
||||||
|
let frame = self.base.get();
|
||||||
|
// SAFETY: the buffer covers the wiring-derived need, so the advanced
|
||||||
|
// cursor stays within it.
|
||||||
|
self.base.set(unsafe { frame.add(words * 8) });
|
||||||
|
self.words.set(self.words.get() - words);
|
||||||
|
frame
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A run of same-layout slots over caller scratch: lanes serve in place,
|
||||||
|
/// each backed by its own region of the slab, and the collected proofs
|
||||||
|
/// certify the filled prefix. `None` where the scratch cannot hold `len`
|
||||||
|
/// lanes.
|
||||||
|
pub fn run<'a>(&self, scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
|
||||||
|
SlotRun::new(scratch, len, layout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Frames::scope`]. A forgotten guard leaks its region until the frame
|
||||||
|
/// space itself dies, rather than releasing it.
|
||||||
|
pub struct FrameScope<'s, 'e> {
|
||||||
|
frames: &'s Frames<'e>,
|
||||||
|
base: *mut u8,
|
||||||
|
words: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'e> std::ops::Deref for FrameScope<'_, 'e> {
|
||||||
|
type Target = Frames<'e>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Frames<'e> {
|
||||||
|
self.frames
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for FrameScope<'_, '_> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.frames.base.set(self.base);
|
||||||
|
self.frames.words.set(self.words);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::record::layout::element_write;
|
||||||
|
use crate::record::test_support::f64_field;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_scope_releases_and_reuses_its_frames() {
|
||||||
|
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||||
|
let mut frame_arena = FrameArena::new();
|
||||||
|
frame_arena.reserve(1 << 10);
|
||||||
|
let frames = frame_arena.frames();
|
||||||
|
let free = frames.free_words();
|
||||||
|
let mut addresses = Vec::new();
|
||||||
|
for _ in 0..3 {
|
||||||
|
let scope = frames.scope();
|
||||||
|
let mut claim = scope.claim(&layout);
|
||||||
|
addresses.push(claim.dst() as usize);
|
||||||
|
drop(scope);
|
||||||
|
assert_eq!(frames.free_words(), free, "the scope returns its claims");
|
||||||
|
}
|
||||||
|
assert!(addresses.windows(2).all(|pair| pair[0] == pair[1]), "each claim reuses the same region");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,518 @@
|
|||||||
|
//! Consumer-side bindings onto a record input, and the drivers they run.
|
||||||
|
|
||||||
|
use super::access::{Rec, RecordValue, read_element};
|
||||||
|
use super::frames::Frames;
|
||||||
|
use super::layout::Layout;
|
||||||
|
use super::serve::{FrameClaim, Served, serve_input};
|
||||||
|
use crate::gpoll::GPoll;
|
||||||
|
use crate::node::Node;
|
||||||
|
|
||||||
|
/// A record input evaluable at a derived context, yielding the record at that
|
||||||
|
/// context's lifetime. The lifetime is a trait parameter because a bound like
|
||||||
|
/// `for<'d> Node<Derived<'d, C>>` cannot also say the derived context's arena
|
||||||
|
/// is at `'d`: the equality binding `ExtractArena<ArenaRef = &'d Arena>` is an
|
||||||
|
/// unconstrained position under a higher rank.
|
||||||
|
pub trait DerivedRecordInput<'derived, C> {
|
||||||
|
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt>;
|
||||||
|
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'derived, C, N> DerivedRecordInput<'derived, C> for N
|
||||||
|
where
|
||||||
|
N: Node<C>,
|
||||||
|
C: crate::context::ExtractArena<ArenaRef = &'derived crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt> {
|
||||||
|
cell.eval_input(input_index, self, ctx, frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent> {
|
||||||
|
self.extent_at(ctx, level, frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fills caller scratch with one frame per lane of `range`: the input serves
|
||||||
|
/// into the lane's own region of the slab, and the lane's own frame space is
|
||||||
|
/// free again at the next lane, so the frame peak stays at one lane's need and
|
||||||
|
/// every lane's bytes are distinct.
|
||||||
|
pub fn fill_frames<'a, 'e, C, N>(node: &'a N, input: &C, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
|
||||||
|
where
|
||||||
|
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
N: Node<C>,
|
||||||
|
{
|
||||||
|
use crate::node::BatchStatus;
|
||||||
|
let Some(scratch) = scratch else {
|
||||||
|
return BatchStatus::NeedBuffer;
|
||||||
|
};
|
||||||
|
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||||
|
return BatchStatus::InvalidRange;
|
||||||
|
};
|
||||||
|
let Some(mut run) = frames.run(scratch, len, node.layout()) else {
|
||||||
|
return BatchStatus::InvalidRange;
|
||||||
|
};
|
||||||
|
let mut local = *input;
|
||||||
|
let mut finality = crate::gpoll::Finality::AllFinal;
|
||||||
|
let mut hint = crate::gpoll::Extent::AtLeast(range.end as usize);
|
||||||
|
for lane in 0..len {
|
||||||
|
local.set_index(range.start + lane as u64);
|
||||||
|
let lane_frames = frames.scope();
|
||||||
|
let slot = run.slot(lane, &lane_frames);
|
||||||
|
let served = match node.serve(&local, slot) {
|
||||||
|
GPoll::Final(served) => served,
|
||||||
|
GPoll::Partial(served) => {
|
||||||
|
finality = crate::gpoll::Finality::Partial;
|
||||||
|
served
|
||||||
|
}
|
||||||
|
GPoll::Pending => return BatchStatus::Pending,
|
||||||
|
GPoll::Fallback(boxed) => return BatchStatus::Error(boxed.1),
|
||||||
|
// A lane past a lower-bound level ends the data: the fill comes
|
||||||
|
// back short and the hint turns exact.
|
||||||
|
GPoll::Error(error) if error.kind == crate::gpoll::ErrorKind::PastEnd => {
|
||||||
|
hint = crate::gpoll::Extent::Exactly(range.start as usize + lane);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
GPoll::Error(error) => return BatchStatus::Error(*error),
|
||||||
|
};
|
||||||
|
run.served(lane, &served);
|
||||||
|
}
|
||||||
|
BatchStatus::Filled(run.finish(), finality, hint)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The driver a consumer runs on a record input: a resident batch returns with
|
||||||
|
/// no allocation, a node's own batch impl gets `n * frame_bytes` of arena
|
||||||
|
/// scratch, and an unbatched input falls back to the [`fill_frames`] loop.
|
||||||
|
pub fn materialize_batch<'a, 'e, C, N>(node: &'a N, input: &'a C, range: std::ops::Range<u64>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
|
||||||
|
where
|
||||||
|
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
N: Node<C>,
|
||||||
|
{
|
||||||
|
use crate::node::BatchStatus;
|
||||||
|
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||||
|
return BatchStatus::InvalidRange;
|
||||||
|
};
|
||||||
|
let words = len * node.layout().lane_stride() / 8;
|
||||||
|
let exhausted = || {
|
||||||
|
BatchStatus::Error(crate::gpoll::GraphError {
|
||||||
|
kind: crate::gpoll::ErrorKind::ArenaExhausted,
|
||||||
|
trace: Vec::new(),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
match node.eval_batch(input, range.clone(), None, frames) {
|
||||||
|
BatchStatus::Unbatched => match arena.alloc_scratch::<u64>(words) {
|
||||||
|
Some(scratch) => fill_frames(node, input, range, Some(scratch), frames),
|
||||||
|
None => exhausted(),
|
||||||
|
},
|
||||||
|
BatchStatus::NeedBuffer => match arena.alloc_scratch::<u64>(words) {
|
||||||
|
Some(scratch) => node.eval_batch(input, range, Some(scratch), frames),
|
||||||
|
None => exhausted(),
|
||||||
|
},
|
||||||
|
status => status,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The outcome of materializing a leveled input's whole flat span.
|
||||||
|
pub enum LevelStatus<'a> {
|
||||||
|
Batch(crate::node::RecordBatch<'a>, crate::gpoll::Finality),
|
||||||
|
Pending,
|
||||||
|
Error(crate::gpoll::GraphError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates a leveled input's whole flat span into one batch: an exact total
|
||||||
|
/// fills once, a lower bound drains by guess-and-double until a short fill,
|
||||||
|
/// each reply's hint seeding the next guess. The boundary consumers' driver;
|
||||||
|
/// reducers inline the same protocol with their span offsets.
|
||||||
|
pub fn materialize_level<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'a>
|
||||||
|
where
|
||||||
|
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
N: Node<C>,
|
||||||
|
{
|
||||||
|
use crate::gpoll::{Extent, GraphError, Level};
|
||||||
|
use crate::node::BatchStatus;
|
||||||
|
let sized = match node.extent(input, Level::Total, frames) {
|
||||||
|
GPoll::Final(Extent::Exactly(count)) => Ok(count),
|
||||||
|
GPoll::Final(Extent::AtLeast(bound)) => Err(bound),
|
||||||
|
GPoll::Pending => return LevelStatus::Pending,
|
||||||
|
_ => return LevelStatus::Error(GraphError::new("materialize over a non-exact extent")),
|
||||||
|
};
|
||||||
|
match sized {
|
||||||
|
Ok(count) => match materialize_batch(node, input, 0..count as u64, arena, frames) {
|
||||||
|
BatchStatus::Lent(batch, finality, _) => LevelStatus::Batch(batch, finality),
|
||||||
|
BatchStatus::Filled(batch, finality, _) => LevelStatus::Batch(batch.into_shared(), finality),
|
||||||
|
BatchStatus::Pending => LevelStatus::Pending,
|
||||||
|
BatchStatus::Error(error) => LevelStatus::Error(error),
|
||||||
|
_ => LevelStatus::Error(GraphError::new("materialize batch failed")),
|
||||||
|
},
|
||||||
|
Err(bound) => {
|
||||||
|
let mut guess = bound.max(16);
|
||||||
|
loop {
|
||||||
|
let (batch, finality, hint) = match materialize_batch(node, input, 0..guess as u64, arena, frames) {
|
||||||
|
BatchStatus::Lent(batch, finality, hint) => (batch, finality, hint),
|
||||||
|
BatchStatus::Filled(batch, finality, hint) => (batch.into_shared(), finality, hint),
|
||||||
|
BatchStatus::Pending => return LevelStatus::Pending,
|
||||||
|
BatchStatus::Error(error) => return LevelStatus::Error(error),
|
||||||
|
_ => return LevelStatus::Error(GraphError::new("materialize batch failed")),
|
||||||
|
};
|
||||||
|
let filled = batch.len();
|
||||||
|
if filled < guess {
|
||||||
|
break LevelStatus::Batch(batch, finality);
|
||||||
|
}
|
||||||
|
match hint {
|
||||||
|
Extent::Exactly(total) if total <= filled => break LevelStatus::Batch(batch, finality),
|
||||||
|
Extent::Exactly(total) => guess = total,
|
||||||
|
Extent::AtLeast(more) => guess = (guess * 2).max(more),
|
||||||
|
Extent::Free => guess *= 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The raw lazy record input handed to a record-opaque kernel: the input plus
|
||||||
|
/// its wiring-proven layout, the pairing the kernel's unsafe record
|
||||||
|
/// operations rely on. The kernel must only pair the layout with values this
|
||||||
|
/// input produced.
|
||||||
|
pub struct RecordInput<'a, 'e, N> {
|
||||||
|
node: &'a N,
|
||||||
|
layout: &'a Layout,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, N> RecordInput<'a, 'e, N> {
|
||||||
|
pub fn new(node: &'a N, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
|
||||||
|
Self { node, layout, frames }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(&self) -> &Layout {
|
||||||
|
self.layout
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves the input through the kernel's own claim: the kernel's output
|
||||||
|
/// layout is the input's, so the claim it was handed is the input's frame.
|
||||||
|
pub fn serve<'l, C>(&self, ctx: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||||
|
where
|
||||||
|
N: Node<C>,
|
||||||
|
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
self.node.serve(ctx, slot)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`materialize_level`] over the input: the input's whole flat span as one
|
||||||
|
/// batch.
|
||||||
|
pub fn materialize_level<'b, C>(&'b self, ctx: &'b C, arena: &'b crate::arena::Arena) -> LevelStatus<'b>
|
||||||
|
where
|
||||||
|
N: Node<C>,
|
||||||
|
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
materialize_level(self.node, ctx, arena, self.frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// `rec` must be a record of the layout the offsets were resolved against
|
||||||
|
/// and `El` its element type; both are proven at wiring.
|
||||||
|
unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El {
|
||||||
|
unsafe { read_element::<El>(rec) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The raw lazy input handed to a poll kernel whose input rides records while
|
||||||
|
/// the kernel consumes the plain element.
|
||||||
|
pub struct ElementInput<'a, 'e, Out, N> {
|
||||||
|
node: &'a N,
|
||||||
|
layout: &'a Layout,
|
||||||
|
reads: &'a [Option<usize>],
|
||||||
|
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, El: Clone, N> ElementInput<'a, 'e, El, N> {
|
||||||
|
pub fn new(node: &'a N, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
|
||||||
|
Self {
|
||||||
|
node,
|
||||||
|
layout,
|
||||||
|
reads: &[],
|
||||||
|
read: element_only::<El>,
|
||||||
|
frames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, Out, N> ElementInput<'a, 'e, Out, N> {
|
||||||
|
/// `read` must be sound against the layout the offsets in `reads` were
|
||||||
|
/// resolved from; the macro proves both at wiring.
|
||||||
|
pub fn with_reads(node: &'a N, layout: &'a Layout, reads: &'a [Option<usize>], read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out, frames: &'a Frames<'e>) -> Self {
|
||||||
|
Self { node, layout, reads, read, frames }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The input's element at `ctx`, read out of a record claimed beyond the
|
||||||
|
/// kernel's own frame; the claim dies with the call, so the record is free
|
||||||
|
/// again at the next one.
|
||||||
|
pub fn eval<'d, C>(&self, ctx: &C) -> GPoll<Out>
|
||||||
|
where
|
||||||
|
N: DerivedRecordInput<'d, C>,
|
||||||
|
'e: 'd,
|
||||||
|
{
|
||||||
|
let cell = crate::node::StatusCell::new();
|
||||||
|
let scope = self.frames.scope();
|
||||||
|
match self.node.eval_derived(&cell, 0, ctx, &scope) {
|
||||||
|
// SAFETY: the read copies out by value against the input's own layout.
|
||||||
|
Ok(value) => cell.finish(unsafe { (self.read)(self.layout.rec(&value), self.reads) }),
|
||||||
|
Err(interrupt) => interrupt.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lazy input handed to a kernel whose input rides a record while
|
||||||
|
/// the kernel consumes the plain element, or the element beside its declared
|
||||||
|
/// attribute reads.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct ElementLazyInput<'a, 'e, Out, N> {
|
||||||
|
node: &'a N,
|
||||||
|
cell: &'a crate::node::StatusCell,
|
||||||
|
input_index: usize,
|
||||||
|
layout: &'a Layout,
|
||||||
|
reads: &'a [Option<usize>],
|
||||||
|
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, El: Clone, N> ElementLazyInput<'a, 'e, El, N> {
|
||||||
|
pub fn new(node: &'a N, cell: &'a crate::node::StatusCell, input_index: usize, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
|
||||||
|
Self {
|
||||||
|
node,
|
||||||
|
cell,
|
||||||
|
input_index,
|
||||||
|
layout,
|
||||||
|
reads: &[],
|
||||||
|
read: element_only::<El>,
|
||||||
|
frames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, Out, N> ElementLazyInput<'a, 'e, Out, N> {
|
||||||
|
/// `read` must be sound against the layout the offsets in `reads` were
|
||||||
|
/// resolved from; the macro proves both at wiring.
|
||||||
|
pub fn with_reads(
|
||||||
|
node: &'a N,
|
||||||
|
cell: &'a crate::node::StatusCell,
|
||||||
|
input_index: usize,
|
||||||
|
layout: &'a Layout,
|
||||||
|
reads: &'a [Option<usize>],
|
||||||
|
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
node,
|
||||||
|
cell,
|
||||||
|
input_index,
|
||||||
|
layout,
|
||||||
|
reads,
|
||||||
|
read,
|
||||||
|
frames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The read copies the element and declared attributes out by value, so
|
||||||
|
/// the record's claim dies with the call.
|
||||||
|
pub fn eval<'d, C>(&self, ctx: &C) -> Result<Out, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
N: DerivedRecordInput<'d, C>,
|
||||||
|
'e: 'd,
|
||||||
|
{
|
||||||
|
let scope = self.frames.scope();
|
||||||
|
let value = self.node.eval_derived(self.cell, self.input_index, ctx, &scope)?;
|
||||||
|
// SAFETY: the reads are the input's own layout's, resolved at wiring.
|
||||||
|
Ok(unsafe { (self.read)(self.layout.rec(&value), self.reads) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lazy record input handed to a kernel that evaluates its inputs under
|
||||||
|
/// derived contexts: evaluating rebinds the record to the kernel's routing
|
||||||
|
/// lifetime, so the value escapes the derivation scope.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct RecordLazyInput<'a, 'e, N> {
|
||||||
|
node: &'a N,
|
||||||
|
cell: &'a crate::node::StatusCell,
|
||||||
|
input_index: usize,
|
||||||
|
inner_levels: u8,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, N> RecordLazyInput<'a, 'e, N> {
|
||||||
|
pub fn new(node: &'a N, cell: &'a crate::node::StatusCell, input_index: usize, inner_levels: u8, frames: &'a Frames<'e>) -> Self {
|
||||||
|
Self {
|
||||||
|
node,
|
||||||
|
cell,
|
||||||
|
input_index,
|
||||||
|
inner_levels,
|
||||||
|
frames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eval<'d, C>(&self, ctx: &C) -> Result<RecordValue<'e>, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
N: DerivedRecordInput<'d, C>,
|
||||||
|
'e: 'd,
|
||||||
|
{
|
||||||
|
Ok(self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)?.rebind())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flat lane count of one copy: the product of the input's inner-level
|
||||||
|
/// extents, queried uniform across copies (at copy 0). The dividend of a
|
||||||
|
/// structure node's decompose-and-promote.
|
||||||
|
pub fn inner_extent<B>(&self, ctx: &B) -> Result<u64, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
B: crate::context::DeriveCtx,
|
||||||
|
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||||
|
{
|
||||||
|
inner_extent_of(self.node, ctx, 0, self.inner_levels, self.input_index, self.frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flat lane count of the copy at `copy`, for inputs whose inner
|
||||||
|
/// extents vary per copy.
|
||||||
|
pub fn inner_extent_at<B>(&self, ctx: &B, copy: u64) -> Result<u64, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
B: crate::context::DeriveCtx,
|
||||||
|
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||||
|
{
|
||||||
|
inner_extent_of(self.node, ctx, copy, self.inner_levels, self.input_index, self.frames)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`RecordLazyInput::inner_extent`].
|
||||||
|
fn inner_extent_of<B, N>(node: &N, ctx: &B, copy: u64, levels: u8, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
B: crate::context::DeriveCtx,
|
||||||
|
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||||
|
{
|
||||||
|
let mut frame = crate::context::IndexLink { index: 0, outer: None };
|
||||||
|
let derived = ctx.push_level(&mut frame, copy, 0);
|
||||||
|
let mut inner: u64 = 1;
|
||||||
|
for level in 0..levels {
|
||||||
|
match node.extent_at_derived(&derived, level, frames) {
|
||||||
|
GPoll::Final(crate::gpoll::Extent::Exactly(count)) => inner *= count as u64,
|
||||||
|
GPoll::Final(crate::gpoll::Extent::AtLeast(_)) => return probed_inner(node, ctx, copy, input_index, frames),
|
||||||
|
GPoll::Pending => return Err(crate::gpoll::Interrupt::Pending),
|
||||||
|
_ => return Err(crate::gpoll::GraphError::new("structure decomposition over a non-exact extent").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flat lane count of one copy of a lower-bound input, probed by
|
||||||
|
/// evaluating lanes to the past-end signal. The probed records are
|
||||||
|
/// discarded, and their statuses land in a scratch cell.
|
||||||
|
fn probed_inner<B, N>(node: &N, ctx: &B, copy: u64, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
B: crate::context::DeriveCtx,
|
||||||
|
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||||
|
{
|
||||||
|
let cell = crate::node::StatusCell::new();
|
||||||
|
let mut count: u64 = 0;
|
||||||
|
loop {
|
||||||
|
// The probed record is discarded, so the probe's claim is free again
|
||||||
|
// at the next iteration.
|
||||||
|
let probe_frames = frames.scope();
|
||||||
|
let mut frame = crate::context::IndexLink { index: 0, outer: None };
|
||||||
|
let probe = ctx.push_level(&mut frame, copy, count);
|
||||||
|
let result = node.eval_derived(&cell, input_index, &probe, &probe_frames);
|
||||||
|
match result {
|
||||||
|
Ok(_) => count += 1,
|
||||||
|
Err(crate::gpoll::Interrupt::Error(error)) if error.kind == crate::gpoll::ErrorKind::PastEnd => return Ok(count),
|
||||||
|
Err(interrupt) => return Err(interrupt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The derive-routing carrier beside its declared attribute reads: evaluating
|
||||||
|
/// at a derived context yields the opaque row token and the read values in one
|
||||||
|
/// step, so the kernel drives the per-copy eval while reads stay resolved
|
||||||
|
/// against the source's wired layout.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct DerivedLazyInput<'a, 'e, Out, N> {
|
||||||
|
node: &'a N,
|
||||||
|
cell: &'a crate::node::StatusCell,
|
||||||
|
input_index: usize,
|
||||||
|
inner_levels: u8,
|
||||||
|
reads: &'a [Option<usize>],
|
||||||
|
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'e, Out, N> DerivedLazyInput<'a, 'e, Out, N> {
|
||||||
|
/// `read` must be sound against the layout the offsets in `reads` were
|
||||||
|
/// resolved from; the macro proves both at wiring.
|
||||||
|
pub fn new(
|
||||||
|
node: &'a N,
|
||||||
|
cell: &'a crate::node::StatusCell,
|
||||||
|
input_index: usize,
|
||||||
|
inner_levels: u8,
|
||||||
|
reads: &'a [Option<usize>],
|
||||||
|
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||||
|
frames: &'a Frames<'e>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
node,
|
||||||
|
cell,
|
||||||
|
input_index,
|
||||||
|
inner_levels,
|
||||||
|
reads,
|
||||||
|
read,
|
||||||
|
frames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flat lane count of one copy; see [`RecordLazyInput::inner_extent`].
|
||||||
|
pub fn inner_extent<B>(&self, ctx: &B) -> Result<u64, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
B: crate::context::DeriveCtx,
|
||||||
|
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||||
|
{
|
||||||
|
inner_extent_of(self.node, ctx, 0, self.inner_levels, self.input_index, self.frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eval<'d, C>(&self, ctx: &C) -> Result<Out, crate::gpoll::Interrupt>
|
||||||
|
where
|
||||||
|
N: DerivedRecordInput<'d, C>,
|
||||||
|
'e: 'd,
|
||||||
|
{
|
||||||
|
let value: RecordValue<'e> = self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)?.rebind();
|
||||||
|
// SAFETY: declared reads imply a non-empty layout, so the record is
|
||||||
|
// spilled and its pointer is the frame the offsets index into.
|
||||||
|
Ok(unsafe { (self.read)(Rec::new(value.ptr), self.reads) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plain probe over a record input, cloning the element out of the parked
|
||||||
|
/// reference when it carries drop glue. Registry constructors wrap a record
|
||||||
|
/// input in one to feed a node's plain value input, keeping the input kind
|
||||||
|
/// uniform.
|
||||||
|
pub struct RecordExtract<El, N> {
|
||||||
|
edge: N,
|
||||||
|
layout: Layout,
|
||||||
|
_marker: std::marker::PhantomData<fn() -> El>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<El, N> RecordExtract<El, N> {
|
||||||
|
pub fn new(edge: N, layout: &Layout) -> Self {
|
||||||
|
Self {
|
||||||
|
edge,
|
||||||
|
layout: layout.clone(),
|
||||||
|
_marker: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<El: Clone + 'static, N> RecordExtract<El, N> {
|
||||||
|
/// The input's element, copied out of its record.
|
||||||
|
pub fn eval<'e, C>(&self, input: &C, frames: &Frames<'e>) -> GPoll<El>
|
||||||
|
where
|
||||||
|
N: Node<C>,
|
||||||
|
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
|
{
|
||||||
|
// The element copies out by value, so the input's claim dies with
|
||||||
|
// the scope.
|
||||||
|
let scope = frames.scope();
|
||||||
|
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,692 @@
|
|||||||
|
//! Wiring-time shape facts: the layout a record takes and the writes it folds from.
|
||||||
|
|
||||||
|
use super::access::{Rec, RecordValue, borrow_element, erase_static, read_element, write_element_keyed};
|
||||||
|
use super::owned::deep_element_glue;
|
||||||
|
use super::promote::{Promotion, retained_measure};
|
||||||
|
use crate::attribute;
|
||||||
|
|
||||||
|
/// A field write declared at wiring, carrying the marker's erased-read glue
|
||||||
|
/// so introspection and persistence never consult the census at runtime.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct FieldWrite {
|
||||||
|
pub name: &'static str,
|
||||||
|
pub level: u8,
|
||||||
|
pub size: usize,
|
||||||
|
pub align: usize,
|
||||||
|
pub type_id: std::any::TypeId,
|
||||||
|
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||||
|
pub repark: Option<crate::list::ReparkFn>,
|
||||||
|
/// Hashes the field's content. `None` means the stored bytes are the
|
||||||
|
/// content, which holds for every unparked value.
|
||||||
|
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||||
|
/// Compares two fields' content. `None` as for `content_hash`.
|
||||||
|
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FieldWrite {
|
||||||
|
pub fn of<A: crate::attribute::Attribute>(level: u8) -> Self
|
||||||
|
where
|
||||||
|
A::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
|
||||||
|
{
|
||||||
|
unsafe fn content_hash<V: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||||
|
let mut state = state;
|
||||||
|
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
|
||||||
|
}
|
||||||
|
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||||
|
unsafe { *a.cast::<V>() == *b.cast::<V>() }
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
name: A::NAME,
|
||||||
|
level,
|
||||||
|
size: size_of::<A::Value<'static>>(),
|
||||||
|
align: align_of::<A::Value<'static>>(),
|
||||||
|
type_id: std::any::TypeId::of::<A::Value<'static>>(),
|
||||||
|
read_erased: A::read_erased,
|
||||||
|
repark: A::REPARK,
|
||||||
|
content_hash: Some(content_hash::<A::Value<'static>>),
|
||||||
|
content_eq: Some(content_eq::<A::Value<'static>>),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One field of a [`Layout`]: a (name, level) key resolved to an offset.
|
||||||
|
/// Levels are numbered innermost-out; only level 0 exists at rank 0.
|
||||||
|
/// Equality is structural over the field's identity, its value type
|
||||||
|
/// included; only the glue pointers are excluded, since fn-pointer identity
|
||||||
|
/// is not guaranteed across codegen units and layout equality drives
|
||||||
|
/// identity forwarding.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct FieldDesc {
|
||||||
|
pub name: &'static str,
|
||||||
|
pub level: u8,
|
||||||
|
pub offset: usize,
|
||||||
|
pub size: usize,
|
||||||
|
pub align: usize,
|
||||||
|
pub type_id: std::any::TypeId,
|
||||||
|
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||||
|
pub repark: Option<crate::list::ReparkFn>,
|
||||||
|
/// Hashes the field's content. `None` means the stored bytes are the
|
||||||
|
/// content, which holds for every unparked value.
|
||||||
|
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||||
|
/// Compares two fields' content. `None` as for `content_hash`.
|
||||||
|
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for FieldDesc {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
(self.name, self.level, self.offset, self.size, self.align, self.type_id) == (other.name, other.level, other.offset, other.size, other.align, other.type_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FieldDesc {
|
||||||
|
/// The write this field re-declares when a layout's fields fold into
|
||||||
|
/// another layout.
|
||||||
|
pub fn as_write(&self) -> FieldWrite {
|
||||||
|
FieldWrite {
|
||||||
|
name: self.name,
|
||||||
|
level: self.level,
|
||||||
|
size: self.size,
|
||||||
|
align: self.align,
|
||||||
|
type_id: self.type_id,
|
||||||
|
read_erased: self.read_erased,
|
||||||
|
repark: self.repark,
|
||||||
|
content_hash: self.content_hash,
|
||||||
|
content_eq: self.content_eq,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for FieldDesc {}
|
||||||
|
|
||||||
|
/// The element slot of a layout: its dimensions plus erased glue bound where
|
||||||
|
/// the element type is statically known, so generic consumers read or
|
||||||
|
/// deep-copy the element without it. Equality is structural over the
|
||||||
|
/// element's identity, its type included; glue pointers are excluded for the
|
||||||
|
/// same reason as [`FieldDesc`]'s.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct ElementWrite {
|
||||||
|
pub size: usize,
|
||||||
|
pub align: usize,
|
||||||
|
pub parked: bool,
|
||||||
|
pub type_id: std::any::TypeId,
|
||||||
|
pub clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
|
||||||
|
pub repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||||
|
/// Moves a parked payload's header into the persistent region rather than
|
||||||
|
/// cloning the heap it owns, returning the new header. `None` declines,
|
||||||
|
/// which leaves the caller its clone path.
|
||||||
|
pub park_move: unsafe fn(*const u8, &Promotion<'_>) -> Option<*const u8>,
|
||||||
|
/// Hashes the element's content. `None` means the stored bytes are the
|
||||||
|
/// content, which holds for every unparked element.
|
||||||
|
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||||
|
/// Compares two elements' content. `None` as for `content_hash`.
|
||||||
|
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for ElementWrite {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
(self.size, self.align, self.parked, self.type_id) == (other.size, other.align, other.parked, other.type_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for ElementWrite {}
|
||||||
|
|
||||||
|
impl Default for ElementWrite {
|
||||||
|
fn default() -> Self {
|
||||||
|
unsafe fn clone_out(_ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||||
|
Box::new(())
|
||||||
|
}
|
||||||
|
unsafe fn repark(_value: &(dyn std::any::Any + Send + Sync), _dst: *mut u8, _arena: &crate::arena::Arena) -> Option<()> {
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
unsafe fn park_move(_parked: *const u8, _promotion: &Promotion<'_>) -> Option<*const u8> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
size: 0,
|
||||||
|
align: 0,
|
||||||
|
parked: false,
|
||||||
|
type_id: std::any::TypeId::of::<()>(),
|
||||||
|
clone_out,
|
||||||
|
repark,
|
||||||
|
park_move,
|
||||||
|
content_hash: None,
|
||||||
|
content_eq: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A record layout: the element at offset 0, then the written attributes in
|
||||||
|
/// canonical order (descending alignment, then size, then name, then level).
|
||||||
|
/// Layouts are derived data, a pure function of the upstream write set.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct Layout {
|
||||||
|
pub depth: u8,
|
||||||
|
pub element: ElementWrite,
|
||||||
|
pub fields: Vec<FieldDesc>,
|
||||||
|
pub size: usize,
|
||||||
|
pub align: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Layout {
|
||||||
|
pub fn offset_of(&self, name: &str, level: u8) -> Option<usize> {
|
||||||
|
self.fields.iter().find(|field| field.name == name && field.level == level).map(|field| field.offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn frame_bytes(&self) -> usize {
|
||||||
|
self.size.next_multiple_of(8)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One batch lane's stride: a spilled record's frame, or the value itself
|
||||||
|
/// for records this layout keeps inline (`size == 0`), whose payload rides
|
||||||
|
/// in the `RecordValue`'s own storage exactly as [`Layout::rec`] resolves.
|
||||||
|
pub fn lane_stride(&self) -> usize {
|
||||||
|
match self.size == 0 {
|
||||||
|
true => size_of::<RecordValue<'static>>(),
|
||||||
|
false => self.frame_bytes(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a value of this layout, which must be its wiring-proven one,
|
||||||
|
/// to its record bytes. An empty record carries nothing and resolves to the
|
||||||
|
/// value's own storage; every other record spills and rides the pointer.
|
||||||
|
pub fn rec<'v>(&self, value: &'v RecordValue<'_>) -> Rec<'v> {
|
||||||
|
match self.size == 0 {
|
||||||
|
true => Rec((&raw const *value).cast(), std::marker::PhantomData),
|
||||||
|
false => Rec(value.ptr, std::marker::PhantomData),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The union of this layout's fields and `writes` over `element` at
|
||||||
|
/// `depth`, in canonical order. A (name, level) written at a different
|
||||||
|
/// size is a type conflict and panics; the census keeps declared names to
|
||||||
|
/// one type, so this only fires on wiring bugs.
|
||||||
|
pub fn with_writes(&self, depth: u8, element: ElementWrite, writes: &[FieldWrite]) -> Layout {
|
||||||
|
let mut merged: Vec<FieldWrite> = self.fields.iter().map(FieldDesc::as_write).collect();
|
||||||
|
for &write in writes {
|
||||||
|
match merged.iter().find(|field| field.name == write.name && field.level == write.level) {
|
||||||
|
Some(existing) => assert_eq!(existing.type_id, write.type_id, "attribute `{}` written at two different types", write.name),
|
||||||
|
None => merged.push(write),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
merged.sort_by(|a, b| b.align.cmp(&a.align).then(b.size.cmp(&a.size)).then(a.name.cmp(b.name)).then(a.level.cmp(&b.level)));
|
||||||
|
let mut offset = element.size;
|
||||||
|
let mut align = element.align.max(1);
|
||||||
|
let fields = merged
|
||||||
|
.into_iter()
|
||||||
|
.map(|write| {
|
||||||
|
offset = offset.next_multiple_of(write.align.max(1));
|
||||||
|
align = align.max(write.align);
|
||||||
|
let desc = FieldDesc {
|
||||||
|
name: write.name,
|
||||||
|
level: write.level,
|
||||||
|
offset,
|
||||||
|
size: write.size,
|
||||||
|
align: write.align,
|
||||||
|
type_id: write.type_id,
|
||||||
|
read_erased: write.read_erased,
|
||||||
|
repark: write.repark,
|
||||||
|
content_hash: write.content_hash,
|
||||||
|
content_eq: write.content_eq,
|
||||||
|
};
|
||||||
|
offset += write.size;
|
||||||
|
desc
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Layout {
|
||||||
|
depth,
|
||||||
|
element,
|
||||||
|
fields,
|
||||||
|
size: offset,
|
||||||
|
align,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This layout minus the named fields, offsets recomputed. Removing an
|
||||||
|
/// absent name is a no-op: downstream reads yield the default either way.
|
||||||
|
pub fn without(&self, removes: &[(&str, u8)]) -> Layout {
|
||||||
|
let retained: Vec<FieldWrite> = self.fields.iter().filter(|field| !removes.contains(&(field.name, field.level))).map(FieldDesc::as_write).collect();
|
||||||
|
Layout::default().with_writes(self.depth, self.element, &retained)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The union of several layouts over the same element and depth.
|
||||||
|
pub fn union(layouts: &[&Layout]) -> Layout {
|
||||||
|
let first = layouts.first().expect("a union needs at least one layout");
|
||||||
|
// A shallower source joins the union lifted: a scalar concatenates as
|
||||||
|
// one lane, its fields sitting at the innermost level like any lane's.
|
||||||
|
let depth = layouts.iter().map(|layout| layout.depth).max().unwrap_or(first.depth);
|
||||||
|
let mut union = Layout::default().with_writes(depth, first.element, &[]);
|
||||||
|
for layout in layouts {
|
||||||
|
assert_eq!(union.element, layout.element, "union layouts must share the element");
|
||||||
|
let writes: Vec<FieldWrite> = layout.fields.iter().map(FieldDesc::as_write).collect();
|
||||||
|
union = union.with_writes(union.depth, union.element, &writes);
|
||||||
|
}
|
||||||
|
union
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A field handle minted once against a layout: the marker's (name, level)
|
||||||
|
/// resolved to a field index and offset, with the marker-to-type proof taken
|
||||||
|
/// there. Resolving it against a layout re-checks that one index instead of
|
||||||
|
/// scanning names, so a token paired with any other layout resolves to
|
||||||
|
/// nothing rather than to the wrong bytes.
|
||||||
|
pub struct FieldOffset<A: attribute::Attribute> {
|
||||||
|
index: usize,
|
||||||
|
offset: usize,
|
||||||
|
level: u8,
|
||||||
|
marker: std::marker::PhantomData<fn() -> A>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: attribute::Attribute> Clone for FieldOffset<A> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: attribute::Attribute> Copy for FieldOffset<A> {}
|
||||||
|
|
||||||
|
impl<A: attribute::Attribute> std::fmt::Debug for FieldOffset<A> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("FieldOffset").field("name", &A::NAME).field("offset", &self.offset).field("level", &self.level).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: attribute::Attribute> FieldOffset<A> {
|
||||||
|
/// The marker's field at `level`, `None` where the layout does not carry
|
||||||
|
/// it. Panics where the layout declares the name at another value type,
|
||||||
|
/// which the census forbids.
|
||||||
|
pub fn of(layout: &Layout, level: u8) -> Option<Self> {
|
||||||
|
let (index, field) = layout.fields.iter().enumerate().find(|(_, field)| field.name == A::NAME && field.level == level)?;
|
||||||
|
assert_eq!(field.type_id, std::any::TypeId::of::<A::Value<'static>>(), "attribute `{}` is declared at another value type", A::NAME);
|
||||||
|
Some(Self {
|
||||||
|
index,
|
||||||
|
offset: field.offset,
|
||||||
|
level,
|
||||||
|
marker: std::marker::PhantomData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn offset(self) -> usize {
|
||||||
|
self.offset
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The offset this token names in `layout`, `None` unless `layout` is the
|
||||||
|
/// one it was minted against. The field's value type is re-checked, so a
|
||||||
|
/// resolved offset carries the marker-to-type proof into `layout`.
|
||||||
|
pub fn resolve(self, layout: &Layout) -> Option<usize> {
|
||||||
|
let field = layout.fields.get(self.index)?;
|
||||||
|
let same = field.offset == self.offset && field.level == self.level && field.name == A::NAME && field.type_id == std::any::TypeId::of::<A::Value<'static>>();
|
||||||
|
same.then_some(self.offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stand-in fed to a kernel's unbounded `element: T` parameter. The type
|
||||||
|
/// system forces the kernel to route it to the element position of its return
|
||||||
|
/// tuple, so the passthrough is explicit in the signature while the lowering
|
||||||
|
/// carries the element bytes untyped through the copy plan.
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct ElToken;
|
||||||
|
|
||||||
|
/// The shared empty layout: `depth` 0, no element, no fields, so `frame_bytes`
|
||||||
|
/// is 0. The `Node::layout` default returns it for element-only and test nodes,
|
||||||
|
/// which carry no record.
|
||||||
|
pub fn empty_layout() -> &'static Layout {
|
||||||
|
static EMPTY: std::sync::OnceLock<Layout> = std::sync::OnceLock::new();
|
||||||
|
EMPTY.get_or_init(Layout::default)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A record node's output layout with the frame size and carrier copy plan derived from it.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct RecordLayout {
|
||||||
|
pub layout: Layout,
|
||||||
|
pub frame_bytes: usize,
|
||||||
|
pub plan: Vec<(usize, usize, usize)>,
|
||||||
|
/// Inputs whose value cannot change with the innermost index, as a bitmask
|
||||||
|
/// over input positions. Empty is the safe default: an uninstalled layout
|
||||||
|
/// rebinds every input per lane.
|
||||||
|
pub lane_invariant: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Declarative record-io metadata for a node type, emitted by the macro into
|
||||||
|
/// its registry entry so the compiler can fold each input's layout without
|
||||||
|
/// running the node's constructor. [`fold`](LayoutMeta::fold) reproduces the
|
||||||
|
/// layout the constructor derives at wiring today; the compiler layout pass
|
||||||
|
/// calls it over the proto graph instead.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct LayoutMeta {
|
||||||
|
/// Input indices whose layouts union to form the base: `[]` writes a fresh
|
||||||
|
/// record, `[i]` derives from a single carrier, `[i, j, ..]` unions routing
|
||||||
|
/// sources.
|
||||||
|
pub sources: Vec<u8>,
|
||||||
|
/// Attributes read from each input. Unused by [`fold`](LayoutMeta::fold);
|
||||||
|
/// recorded for later compiler analysis (read-offset resolution, per-name
|
||||||
|
/// cache dependencies, residency).
|
||||||
|
pub reads: Vec<InputReads>,
|
||||||
|
/// The output element: a concrete write, or carried through from the base.
|
||||||
|
pub element: ElementSpec,
|
||||||
|
/// The attributes the node writes at its acting level.
|
||||||
|
pub writes: Vec<FieldWrite>,
|
||||||
|
/// The attributes removed from the base layout, as `(name, level)`.
|
||||||
|
pub removes: Vec<(&'static str, u8)>,
|
||||||
|
/// The depth change the node applies: `0` for elementwise and flip nodes,
|
||||||
|
/// `+1` for a creator, `-1` for a reducer.
|
||||||
|
pub level_delta: i8,
|
||||||
|
/// The materialized subject a reducer folds, as `(input, levels)`. The fold
|
||||||
|
/// consumes the whole subject input, so only the node's own levels remain.
|
||||||
|
pub folded: Option<(u8, u8)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The attributes a node reads from one input, recorded on [`LayoutMeta`] for
|
||||||
|
/// later compiler analysis. A read and a write of an attribute carry the same
|
||||||
|
/// [`FieldWrite`] descriptor; the direction is the position on the node.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct InputReads {
|
||||||
|
pub input: u8,
|
||||||
|
pub reads: Vec<FieldWrite>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a node's output element comes from, for [`LayoutMeta`].
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum ElementSpec {
|
||||||
|
/// The node writes this concrete element.
|
||||||
|
Concrete(ElementWrite),
|
||||||
|
/// The node carries the carrier's element through unchanged.
|
||||||
|
Carried,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LayoutMeta {
|
||||||
|
/// Keeps input 0's layout but replaces its element.
|
||||||
|
pub fn retype(element: ElementWrite) -> Self {
|
||||||
|
Self {
|
||||||
|
sources: vec![0],
|
||||||
|
reads: Vec::new(),
|
||||||
|
element: ElementSpec::Concrete(element),
|
||||||
|
writes: Vec::new(),
|
||||||
|
removes: Vec::new(),
|
||||||
|
level_delta: 0,
|
||||||
|
folded: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Folds the node's output layout from its inputs', reproducing what the
|
||||||
|
/// node's constructor derives at wiring. `inputs` is indexed by proto-input
|
||||||
|
/// position; [`sources`](LayoutMeta::sources) selects the base layouts, which
|
||||||
|
/// union (empty writes a fresh record).
|
||||||
|
pub fn fold(&self, inputs: &[Option<&Layout>]) -> Layout {
|
||||||
|
let sources: Vec<&Layout> = self.sources.iter().map(|&i| inputs[i as usize].expect("layout fold source input has no layout")).collect();
|
||||||
|
let base = match sources.as_slice() {
|
||||||
|
[] => Layout::default(),
|
||||||
|
sources => Layout::union(sources),
|
||||||
|
}
|
||||||
|
.without(&self.removes);
|
||||||
|
let depth = match self.folded {
|
||||||
|
// A fold consumes the whole subject input (a deeper input folds its
|
||||||
|
// total flat span), so only the node's own levels remain.
|
||||||
|
Some(_) => self.level_delta.max(0) as u8,
|
||||||
|
None => (base.depth as i8 + self.level_delta).max(0) as u8,
|
||||||
|
};
|
||||||
|
let element = match &self.element {
|
||||||
|
ElementSpec::Concrete(element) => *element,
|
||||||
|
ElementSpec::Carried => base.element,
|
||||||
|
};
|
||||||
|
base.with_writes(depth, element, &self.writes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`fold`](LayoutMeta::fold) with the frame size and carrier copy plan derived from it.
|
||||||
|
pub fn resolve(&self, inputs: &[Option<&Layout>]) -> RecordLayout {
|
||||||
|
let layout = self.fold(inputs);
|
||||||
|
let frame_bytes = layout.frame_bytes();
|
||||||
|
let plan = match self.sources.first() {
|
||||||
|
Some(&source) if self.level_delta >= 0 => {
|
||||||
|
let from = inputs[source as usize].expect("layout resolve source input has no layout");
|
||||||
|
let carry_element = matches!(self.element, ElementSpec::Carried);
|
||||||
|
let removes: Vec<(&str, u8)> = self.removes.clone();
|
||||||
|
copy_plan(from, &layout, carry_element, &removes)
|
||||||
|
}
|
||||||
|
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
|
||||||
|
_ => Vec::new(),
|
||||||
|
};
|
||||||
|
RecordLayout {
|
||||||
|
layout,
|
||||||
|
frame_bytes,
|
||||||
|
plan,
|
||||||
|
lane_invariant: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Field-by-field carry from `from`'s layout into `to`'s, computed at
|
||||||
|
/// wiring. The element copy is included when `carry_element` holds, which is
|
||||||
|
/// exactly when the node does not write a concrete element itself. `removes`
|
||||||
|
/// names the fields the node deletes, which are exactly the ones allowed to
|
||||||
|
/// be absent from `to`.
|
||||||
|
pub fn copy_plan(from: &Layout, to: &Layout, carry_element: bool, removes: &[(&str, u8)]) -> Vec<(usize, usize, usize)> {
|
||||||
|
let mut plan = Vec::new();
|
||||||
|
if carry_element {
|
||||||
|
assert_eq!(from.element.size, to.element.size, "a carried element must keep its size");
|
||||||
|
if from.element.size > 0 {
|
||||||
|
plan.push((0, 0, from.element.size));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for field in &from.fields {
|
||||||
|
if removes.contains(&(field.name, field.level)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let target = to.offset_of(field.name, field.level).expect("carried field missing from the output layout");
|
||||||
|
plan.push((field.offset, target, field.size));
|
||||||
|
}
|
||||||
|
plan
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether elements of `T` move once into the arena and ride as references:
|
||||||
|
/// records byte-copy their contents and never run drop glue, so a type is
|
||||||
|
/// byte-carried exactly when it has none.
|
||||||
|
pub const fn element_parked<T>() -> bool {
|
||||||
|
std::mem::needs_drop::<T>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The element (size, align) a record input of `T` carries.
|
||||||
|
pub fn element_dims<T>() -> (usize, usize) {
|
||||||
|
match element_parked::<T>() {
|
||||||
|
true => (size_of::<*const u8>(), align_of::<*const u8>()),
|
||||||
|
false => (size_of::<T>(), align_of::<T>()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The element slot a record input of `T` carries, its erased glue bound at
|
||||||
|
/// the statically-known type.
|
||||||
|
pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> ElementWrite
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
unsafe fn clone_out<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||||
|
return unsafe { (deep.clone_out)(ptr) };
|
||||||
|
}
|
||||||
|
// SAFETY: a lifetime-carrying element type registers deep glue, so
|
||||||
|
// this shallow path only erases borrow-free values.
|
||||||
|
Box::new(unsafe { erase_static(read_element::<T>(Rec::new(ptr))) })
|
||||||
|
}
|
||||||
|
unsafe fn repark<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &crate::arena::Arena) -> Option<()>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||||
|
return unsafe { (deep.repark)(value, dst, arena) };
|
||||||
|
}
|
||||||
|
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
|
||||||
|
let value = value.downcast_ref::<T::Static>().expect("an element replays at its own type");
|
||||||
|
// SAFETY: the caller's contract, keyed as this element's own parks are.
|
||||||
|
unsafe { write_element_keyed(dst, value.clone(), arena, retained, std::any::TypeId::of::<T::Static>()) }
|
||||||
|
}
|
||||||
|
/// Declines for a type carrying deep glue, whose value may hold interiors
|
||||||
|
/// the evaluation's arena owns and which a moved header may not reference.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `parked` must address a live payload of `T`.
|
||||||
|
unsafe fn park_move<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(parked: *const u8, promotion: &Promotion<'_>) -> Option<*const u8>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
deep_element_glue(std::any::TypeId::of::<T::Static>()).is_none().then_some(())?;
|
||||||
|
// SAFETY: the caller's contract, at the type the park was written with.
|
||||||
|
let value: &(dyn std::any::Any + Send + Sync) = unsafe { &*parked.cast::<T::Static>() };
|
||||||
|
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
|
||||||
|
// SAFETY: as above, and the decline above establishes that the payload
|
||||||
|
// owns all of its content.
|
||||||
|
unsafe { promotion.move_park::<T>(parked, retained) }.map(<*const T::Static>::cast)
|
||||||
|
}
|
||||||
|
let (size, align) = element_dims::<T>();
|
||||||
|
ElementWrite {
|
||||||
|
size,
|
||||||
|
align,
|
||||||
|
parked: element_parked::<T>(),
|
||||||
|
type_id: std::any::TypeId::of::<T::Static>(),
|
||||||
|
clone_out: clone_out::<T>,
|
||||||
|
repark: repark::<T>,
|
||||||
|
park_move: park_move::<T>,
|
||||||
|
content_hash: None,
|
||||||
|
content_eq: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`element_write`] plus the content hashing and equality glue, for element
|
||||||
|
/// types that support them.
|
||||||
|
pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash + PartialEq + dyn_any::StaticTypeSized>() -> ElementWrite
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
unsafe fn content_hash<T: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||||
|
let mut state = state;
|
||||||
|
unsafe { borrow_element::<T>(Rec::new(ptr)) }.cache_hash(&mut state);
|
||||||
|
}
|
||||||
|
unsafe fn content_eq<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||||
|
unsafe { borrow_element::<T>(Rec::new(a)) == borrow_element::<T>(Rec::new(b)) }
|
||||||
|
}
|
||||||
|
ElementWrite {
|
||||||
|
content_hash: Some(content_hash::<T>),
|
||||||
|
content_eq: Some(content_eq::<T>),
|
||||||
|
..element_write::<T>()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Selects [`element_write_hashed`] when the element type supports the
|
||||||
|
/// content glue and [`element_write`] otherwise, by autoref method
|
||||||
|
/// resolution: call `(&ElementWritePick::<T>(..)).element_write()` with both
|
||||||
|
/// traits in scope.
|
||||||
|
pub struct ElementWritePick<T>(pub std::marker::PhantomData<T>);
|
||||||
|
|
||||||
|
pub trait ElementWritePickHashed {
|
||||||
|
fn element_write(&self) -> ElementWrite;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Clone + Send + Sync + graphene_hash::CacheHash + PartialEq + dyn_any::StaticTypeSized> ElementWritePickHashed for ElementWritePick<T>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
fn element_write(&self) -> ElementWrite {
|
||||||
|
element_write_hashed::<T>()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait ElementWritePickPlain {
|
||||||
|
fn element_write(&self) -> ElementWrite;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Clone + Send + Sync + dyn_any::StaticTypeSized> ElementWritePickPlain for &ElementWritePick<T>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
fn element_write(&self) -> ElementWrite {
|
||||||
|
element_write::<T>()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::record::test_support::{f64_field, sized_field};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn canonical_order_and_offsets() {
|
||||||
|
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("tint", 4, 4), f64_field("opacity"), sized_field("flag", 1, 1)]);
|
||||||
|
assert_eq!(layout.offset_of("opacity", 0), Some(8));
|
||||||
|
assert_eq!(layout.offset_of("tint", 0), Some(16));
|
||||||
|
assert_eq!(layout.offset_of("flag", 0), Some(20));
|
||||||
|
assert_eq!(layout.size, 21);
|
||||||
|
assert_eq!(layout.align, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "two different types")]
|
||||||
|
fn type_conflicts_panic() {
|
||||||
|
let mut conflicting = sized_field("opacity", 8, 8);
|
||||||
|
conflicting.type_id = std::any::TypeId::of::<u64>();
|
||||||
|
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||||
|
layout.with_writes(0, element_write::<f64>(), &[conflicting]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_token_resolves_only_in_the_layout_it_was_minted_against() {
|
||||||
|
use crate::attribute::{Attribute, Opacity, Transform};
|
||||||
|
|
||||||
|
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Opacity>(0)]);
|
||||||
|
let token = FieldOffset::<Opacity>::of(&layout, 0).expect("the layout carries the marker");
|
||||||
|
assert_eq!(token.resolve(&layout), layout.offset_of(Opacity::NAME, 0));
|
||||||
|
|
||||||
|
let shifted = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)]);
|
||||||
|
assert_eq!(FieldOffset::<Opacity>::of(&shifted, 0).and_then(|token| token.resolve(&layout)), None);
|
||||||
|
assert!(FieldOffset::<Opacity>::of(&Layout::default(), 0).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn union_is_order_independent() {
|
||||||
|
let a = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||||
|
let b = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("length")]);
|
||||||
|
assert_eq!(Layout::union(&[&a, &b]), Layout::union(&[&b, &a]));
|
||||||
|
assert!(Layout::union(&[&a, &b]).offset_of("length", 0).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_element_write_pick_selects_the_content_glue_by_type() {
|
||||||
|
use super::{ElementWritePickHashed as _, ElementWritePickPlain as _};
|
||||||
|
|
||||||
|
#[derive(Clone, dyn_any::DynAny)]
|
||||||
|
struct Opaque;
|
||||||
|
|
||||||
|
let hashed = ElementWritePick::<String>(std::marker::PhantomData).element_write();
|
||||||
|
assert!(hashed.content_hash.is_some() && hashed.content_eq.is_some());
|
||||||
|
let plain = (&ElementWritePick::<Opaque>(std::marker::PhantomData)).element_write();
|
||||||
|
assert!(plain.content_hash.is_none() && plain.content_eq.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn elements_ride_as_bytes_exactly_without_drop_glue() {
|
||||||
|
assert!(!element_parked::<f64>());
|
||||||
|
assert!(!element_parked::<[f64; 4]>());
|
||||||
|
assert!(element_parked::<String>());
|
||||||
|
assert!(element_parked::<std::sync::Arc<str>>());
|
||||||
|
assert_eq!(element_dims::<[f64; 4]>(), (32, 8));
|
||||||
|
assert_eq!(element_dims::<String>(), (8, 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layouts_resolve_spilled_values() {
|
||||||
|
let small = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||||
|
assert_eq!(small.frame_bytes(), 16);
|
||||||
|
let backing = [4f64, 0.5];
|
||||||
|
let value = RecordValue::spilled(unsafe { Rec::new(backing.as_ptr().cast()) });
|
||||||
|
assert_eq!(unsafe { small.rec(&value).element::<f64>() }, 4.);
|
||||||
|
assert_eq!(unsafe { small.rec(&value).read::<f64>(small.offset_of("opacity", 0).unwrap()) }, 0.5);
|
||||||
|
|
||||||
|
let spilled = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity"), f64_field("length")]);
|
||||||
|
assert_eq!(spilled.frame_bytes(), 24);
|
||||||
|
let record = [1f64, 2., 3.];
|
||||||
|
let value = RecordValue::spilled(unsafe { Rec::new(record.as_ptr().cast()) });
|
||||||
|
assert_eq!(unsafe { spilled.rec(&value).element::<f64>() }, 1.);
|
||||||
|
assert_eq!(unsafe { spilled.rec(&value).read::<f64>(spilled.offset_of("length", 0).unwrap()) }, 2.);
|
||||||
|
assert_eq!(unsafe { spilled.rec(&value).read::<f64>(spilled.offset_of("opacity", 0).unwrap()) }, 3.);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
//! The packed-record tier at rank 0. A record is the element at offset 0
|
||||||
|
//! plus one field per written attribute; its [`Layout`] is computed at
|
||||||
|
//! wiring from the upstream write set and never serialized. Records of
|
||||||
|
//! inline layouts live in the [`RecordValue`] itself; larger ones live as
|
||||||
|
//! per-lane views on the evaluation's [`Frames`], which the root owns and
|
||||||
|
//! every node claims its own frame out of. Kernels route them as opaque
|
||||||
|
//! [`RecordValue`]s that carry
|
||||||
|
//! their provenance. Only generated or wiring code touches offsets, so a
|
||||||
|
//! safe kernel cannot misalign a field.
|
||||||
|
|
||||||
|
mod access;
|
||||||
|
mod frames;
|
||||||
|
mod input;
|
||||||
|
mod layout;
|
||||||
|
mod owned;
|
||||||
|
mod promote;
|
||||||
|
mod route;
|
||||||
|
mod run;
|
||||||
|
mod serve;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test_support;
|
||||||
|
mod testkit;
|
||||||
|
|
||||||
|
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_element, token_only, write_element, write_element_sized, write_field};
|
||||||
|
pub use frames::{FrameArena, FrameScope, Frames};
|
||||||
|
pub use input::{DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_frames, materialize_batch, materialize_level};
|
||||||
|
pub use layout::{
|
||||||
|
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, RecordLayout, copy_plan,
|
||||||
|
element_dims, element_parked, element_write, element_write_hashed, empty_layout,
|
||||||
|
};
|
||||||
|
pub use owned::{OwnedRecord, deepen_field_value, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||||
|
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
|
||||||
|
pub use route::{RecordSource, SourcePlan};
|
||||||
|
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
|
||||||
|
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
|
||||||
|
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
//! The owned crossing: deep copies that outlive the evaluation their content borrowed.
|
||||||
|
|
||||||
|
use super::access::Rec;
|
||||||
|
use super::layout::Layout;
|
||||||
|
use super::serve::FrameClaim;
|
||||||
|
|
||||||
|
/// Deep-copy overrides for element types whose plain clone borrows the
|
||||||
|
/// evaluation's arena (a `Graphic` holding a group interior). The generic
|
||||||
|
/// element glue consults this registry, so every layout carrying such an
|
||||||
|
/// element deep-copies at memo and capture seams regardless of which
|
||||||
|
/// constructor built the glue. The clone-out must produce a value of the
|
||||||
|
/// element's own type that owns all of its content; the re-park restores that
|
||||||
|
/// value's arena-resident form before parking it.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub(in crate::record) struct DeepElementGlue {
|
||||||
|
pub(in crate::record) clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
|
||||||
|
pub(in crate::record) repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static DEEP_ELEMENT_CLONES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepElementGlue>>> = std::sync::LazyLock::new(Default::default);
|
||||||
|
|
||||||
|
/// Registers the deep copy-out and re-park pair for elements of `T`. Called
|
||||||
|
/// at startup from the crate that owns the type.
|
||||||
|
pub fn register_deep_element_clone<T: dyn_any::StaticTypeSized>(
|
||||||
|
clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
|
||||||
|
repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||||
|
) {
|
||||||
|
DEEP_ELEMENT_CLONES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), DeepElementGlue { clone_out, repark });
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<DeepElementGlue> {
|
||||||
|
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deep-copy overrides for field values whose content borrows the
|
||||||
|
/// evaluation's arena (a graphic list holding native groups), keyed by the
|
||||||
|
/// field's owned value form. Consulted at the persistence seams only:
|
||||||
|
/// `read_erased` itself stays shallow, since introspection reads captures in
|
||||||
|
/// generation. Both halves decline when the value already owns all of its
|
||||||
|
/// content, so group-free values pay no extra clone: `copy_out` returns
|
||||||
|
/// `None` for unchanged, `replay` returns `Some(None)` for unchanged and
|
||||||
|
/// `None` for arena exhaustion.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub(in crate::record) struct DeepFieldGlue {
|
||||||
|
pub(in crate::record) copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
||||||
|
pub(in crate::record) replay: crate::list::FieldReplayFn,
|
||||||
|
}
|
||||||
|
|
||||||
|
static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepFieldGlue>>> = std::sync::LazyLock::new(Default::default);
|
||||||
|
|
||||||
|
/// Registers the deep copy-out and replay pair for field values of `T`.
|
||||||
|
/// Called at startup from the crate that owns the type.
|
||||||
|
pub fn register_deep_field_value<T: 'static>(
|
||||||
|
copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
||||||
|
replay: crate::list::FieldReplayFn,
|
||||||
|
) {
|
||||||
|
DEEP_FIELD_VALUES.lock().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::record) fn deep_field_glue(type_id: std::any::TypeId) -> Option<DeepFieldGlue> {
|
||||||
|
DEEP_FIELD_VALUES.lock().unwrap().get(&type_id).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The copy-out half over an erased field value: the owned form a value takes
|
||||||
|
/// when it crosses out of the evaluation whose arena its content borrows. A
|
||||||
|
/// value with no registered glue already owns everything and passes through.
|
||||||
|
pub fn deepen_field_value(value: Box<dyn crate::list::AnyAttributeValue>) -> Box<dyn crate::list::AnyAttributeValue> {
|
||||||
|
match deep_field_glue(value.as_any().type_id()) {
|
||||||
|
Some(glue) => (glue.copy_out)(&*value).unwrap_or(value),
|
||||||
|
None => value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The replay half over an erased field value: `Some(None)` where the value
|
||||||
|
/// already owns its content, `None` on arena exhaustion.
|
||||||
|
pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>> {
|
||||||
|
match deep_field_glue(value.as_any().type_id()) {
|
||||||
|
Some(glue) => (glue.replay)(value, arena),
|
||||||
|
None => Some(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A record deep-copied out of its evaluation: the packed bytes plus owned
|
||||||
|
/// clones of every parked payload, replayable into a later evaluation's
|
||||||
|
/// storage through the layout's erased glue. The layout stays with the
|
||||||
|
/// holder, which proved it at wiring.
|
||||||
|
pub struct OwnedRecord {
|
||||||
|
pub(in crate::record) bytes: Box<[u8]>,
|
||||||
|
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
|
||||||
|
fields: Vec<(usize, Box<dyn crate::list::AnyAttributeValue>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for OwnedRecord {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("OwnedRecord(..)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OwnedRecord {
|
||||||
|
/// # Safety
|
||||||
|
/// `rec` must be a live record of `layout`.
|
||||||
|
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
|
||||||
|
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(rec.ptr(), layout.size) }.into();
|
||||||
|
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
|
||||||
|
let fields = layout
|
||||||
|
.fields
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, field)| field.repark.is_some())
|
||||||
|
.map(|(index, field)| (index, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
|
||||||
|
.collect();
|
||||||
|
OwnedRecord { bytes, element, fields }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replays the copy into a caller's claim, re-parking droppable payloads
|
||||||
|
/// against `arena`; the claim's layout is the one the copy was taken at,
|
||||||
|
/// and `None` reports arena exhaustion.
|
||||||
|
pub fn replay_into(&self, slot: &mut FrameClaim<'_, '_>, arena: &crate::arena::Arena) -> Option<()> {
|
||||||
|
let layout = slot.layout;
|
||||||
|
self.write_into(layout, slot.dst(), arena)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_into(&self, layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||||
|
unsafe { std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), dst, self.bytes.len()) };
|
||||||
|
if let Some(element) = &self.element {
|
||||||
|
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
|
||||||
|
}
|
||||||
|
for (index, value) in &self.fields {
|
||||||
|
let field = &layout.fields[*index];
|
||||||
|
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||||
|
let resident = replay_field_value(&**value, arena)?;
|
||||||
|
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
|
||||||
|
}
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::record::access::{read_element, write_element, write_field};
|
||||||
|
use crate::record::frames::FrameArena;
|
||||||
|
use crate::record::layout::{FieldWrite, element_write};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn owned_records_replay_re_parked_payloads_after_the_source_dies() {
|
||||||
|
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
|
||||||
|
let mut buffer = vec![0u64; layout.size.div_ceil(8)];
|
||||||
|
let base: *mut u8 = buffer.as_mut_ptr().cast();
|
||||||
|
|
||||||
|
let copy = {
|
||||||
|
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||||
|
unsafe { write_element(base, String::from("element"), &arena) }.unwrap();
|
||||||
|
let (name, _) = arena.alloc(String::from("field")).unwrap();
|
||||||
|
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
|
||||||
|
unsafe { OwnedRecord::copy_out(&layout, Rec::new(base)) }
|
||||||
|
};
|
||||||
|
buffer.fill(u64::MAX);
|
||||||
|
|
||||||
|
let replay_arena = crate::arena::Arena::new(1024).unwrap();
|
||||||
|
let mut frame_arena = FrameArena::new();
|
||||||
|
frame_arena.reserve(layout.frame_bytes());
|
||||||
|
let frames = frame_arena.frames();
|
||||||
|
let mut slot = frames.claim(&layout);
|
||||||
|
copy.replay_into(&mut slot, &replay_arena).unwrap();
|
||||||
|
// SAFETY: the replay completes the record in the claimed frame.
|
||||||
|
let value = unsafe { slot.finish() };
|
||||||
|
let rec = layout.rec(&value);
|
||||||
|
assert_eq!(unsafe { read_element::<String>(rec) }, "element");
|
||||||
|
assert_eq!(unsafe { rec.read::<&str>(layout.offset_of("name", 0).unwrap()) }, "field");
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user