Compare commits

...
Author SHA1 Message Date
Oliver Davies 986759597b Added text as instances and contains nodes 2025-05-06 02:14:23 -07:00
Oliver Davies 914360551f Tweaks, crash fixes and a few new nodes 2025-04-28 18:46:22 -07:00
Sidharth-Singh10andKeavon Chambers 0c3cae2ba5 Add Spline tool tests for drawing within a transformed artboard (#2575)
* Add Spline tool tests for drawing within a transformed artboard

* Refactor spline tool test to use click_tool and add draw_spline helper method

* refactor asserting point positions

* Fix decimal fomat

---------

Co-authored-by: Keavon Chambers <[email protected]>
2025-04-25 14:01:48 +00:00
Keavon Chambers d445bffe31 Add donation callouts in-app and on the site 2025-04-25 00:13:24 -07:00
Rahat 2dee47a6ee Add Spline tool test for drawing with PTZ applied to the canvas view (#2573)
* Adding tests for spline PTZ

* Some refactoring

* Feedback applied from James

* Unnecessary changes

* refactor with current merged pr

* Code refactoring based on guidelines

* cli failing
2025-04-24 20:39:33 +01:00
Keavon Chambers e60a9c36d8 Update the website roadmap 2025-04-24 06:11:37 -07:00
Keavon Chambers 471ef87801 Add reference point input to the Mirror node 2025-04-24 05:33:20 -07:00
0SlowPoke0andKeavon Chambers d39308c048 Add Path tool feature for angle locking upon pressing Ctrl while dragging handle over anchor (#2612)
* almost_fixed

* fix need to refactor

* fixed issed need to refactor

* refactor-done fixed issue

* move function to common_functionality

---------

Co-authored-by: Keavon Chambers <[email protected]>
2025-04-23 20:39:14 -07:00
MateoandKeavon Chambers 3d37ef79ac Add shape fill overlays when closing a path (Pen tool) or filling it (Fill tool) (#2521)
* Make the Pen tool show a path being closed by drawing a filled overlay when hovering the endpoint

* Add to_css to color.rs

* Check before unwrapping layer

* Close if in the right place

* Fix typo

* Format code

* Support discontinuous paths for closing preview

* Code review

* Denser fill lines

* Fill tool preview with strip lines only and revert pen shape-closing opacity

* Small adjustments to fill preview

* Fix line width of fill preview

* Use a pattern to preview the fill tool and fix canvas clearing

* Update pattern

* Simplify code

* Format code

* Use secondary color to preview fill if shift is pressed

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
2025-04-23 18:33:08 -07:00
0SlowPoke0andKeavon Chambers a4a0e110d7 Improve Pen tool behavior to less aggressively delete single-point layers (#2605)
* add single-anchor-place

* clippy_changes

---------

Co-authored-by: Keavon Chambers <[email protected]>
2025-04-23 11:45:51 +00:00
Keavon Chambers ac9fb2b02d Improve instancing nodes (make them output group data, add 'Instance Repeat', fix Flatten Vector Elements click targets, and more) (#2610)
* Improve instancing nodes (make them output group data, add 'Instance Repeat', fix Flatten Vector Elements click targets, and more)

* Fix test?

* Fix more tests?

* Fix moar test??

* Clean up instance method naming
2025-04-22 17:55:57 -07:00
a29802de36 Refactor the Solidify Stroke node implementation to use the Kurbo API (#2608)
* impl append_bezpath method to push a kurbo bezier path to vector data.

* refactor stroke_bezier_paths method and StrokePathIter iterator implementation

* refactor

* impl VectorData method to get strokes iterator of kurbo bezpath

* impl solidify stroke node

* refactor

* use StrokeOptLevel::Optimized for generation stroke fill

* add miter limit and dashes

* fix naming

---------

Co-authored-by: indierusty <[email protected]>
Co-authored-by: Keavon Chambers <[email protected]>
2025-04-22 08:32:58 +00:00
Keavon Chambers 5e0e11b4c1 Update the UI colors of the node graph data types 2025-04-20 17:37:21 -07:00
James Lindsay 704dad4f76 Fix angle logic in the Grid node to allow slanted isometric grids (#2602)
* Fix angles

* Fix hardcoded index

* More information on monitor nodes
2025-04-20 14:16:27 -07:00
80 changed files with 3129 additions and 1051 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0,"lambda":false}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0,"lambda":false}},{"Node":{"node_id":1250460246919467000,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[13690529431936890000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0,"lambda":false}},{"Node":{"node_id":13897409604737649000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"U32":5},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}},{"Network":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":1}},{"Network":{"import_type":{"Concrete":{"name":"u32","alias":null}},"import_index":2}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::vector::PoissonDiskPointsNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::transform::BoundlessFootprintNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::transform::FreezeRealTimeNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MemoNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[8226419277180271000,{"inputs":[{"Node":{"node_id":14061026919898233000,"output_index":0,"lambda":false}},{"Node":{"node_id":11448859343137378000,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_iLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0,"lambda":false}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0,"lambda":false}},{"Node":{"node_id":1250460246919467000,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"OptionalColor":{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[17021405646895729000,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":1.0,"green":0.31764707,"blue":0.15686275,"alpha":1.0}],[0.5,{"red":1.0,"green":0.5686275,"blue":0.25490198,"alpha":1.0}],[1.0,{"red":1.0,"green":0.7294118,"blue":0.16078432,"alpha":1.0}]]},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::ops::GradientValueNode"}},"visible":true,"skip_deduplication":false}],[8366826746721323000,{"inputs":[{"Node":{"node_id":11348516716977914000,"output_index":0,"lambda":false}},{"Node":{"node_id":16084834641749443000,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Concrete":{"name":"graphene_core::instances::Instances<graphene_core::vector::vector_data::VectorData>","alias":null}},"import_index":0}},{"Network":{"import_type":{"Concrete":{"name":"graphene_core::vectoLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0,"lambda":false}}],"nodes":[[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0,"lambda":false}},{"Node":{"node_id":2181148486404191200,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"line_cap":"Butt","line_join":"Miter","line_join_miter_limit":4.0,"transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"opacity":1.0,"blend_mode":"Normal"}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[13,[153.77777777777777,-1.3333333333333712]],[28,[39.111111111111086,-58.22222222222226]],[15,[111.11111111111114,-60.888888888888914]],[26,[22.66666666666663,-81.33333333333337]],[16,[159.5555555555555,-75.55555555555557]],[11,[136.88888888888886,39.111111111111086]],[14,[183.11111111111103,-19.111111111111143]],[3,[45.77777777777777,145.33333333333331]],[33,[-78.22222222222223,75.55555555555554]],[1,[-103.55555555555554,126.66666666666664]],[5,[66.22222222222223,152.88888888888886]],[9,[156.4444444444444,97.33333333333331]],[34,[-5.333333333333371,99.11111111111109]],[20,[128.4444444444444,-142.22222222222223]],[22,[71.11111111111109,-201.7777777777778]],[18,[145.77777777777777,-97.7777777777778]],[17,[123.99999999999994,-84.00000000000003]],[21,[76.0,-202.22222222222223]],[24,[57.77777777777777,-129.33333333333334]],[2,[-67.55555555555554,158.22222222222217]],[25,[0.8888888888888573,-94.66666666666669]],[31,[-53.33333333333337,13.777777777777771]],[30,[-9.333333333333371,0.0]],[6,[123.99999999999994,148.4444444444444]],[32,[9.333333333333314,38.66666666666663]],[19,[90.66666666666664,-129.33333333333334]],[12,[199.5555555555555,10.666666666666629]],[23,[19.555555555555543,-139.55555555555557]],[10,[216.4444444444444,72.4444444444444]],[4,[18.66666666666663,157.77777777777771]],[7,[229.33333333333331,152.4444444444444]],[27,[-11.111111111111144,-72.00000000000003]],[29,[-32.888888888888914,-14.666666666666686]],[8,[252.4444444444444,124.88888888888886]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[25,25],[2,2],[11,11],[26,26],[13,13],[19,19],[32,32],[17,17],[5,5],[7,7],[22,22],[18,18],[29,29],[27,27],[33,33],[28,28],[9,9],[16,16],[14,14],[10,10],[12,12],[8,8],[30,30],[4,4],[21,21],[3,3],[31,31],[1,1],[20,20],[24,24],[15,15],[6,6],[23,23],[34,34]],"end_point":[[6,7],[17,18],[11,12],[3,4],[21,22],[33,34],[29,30],[27,28],[32,33],[25,26],[30,31],[22,23],[31,32],[7,8],[2,3],[20,21],[14,15],[1,2],[13,14],[15,16],[26,27],[8,9],[4,5],[16,17],[10,11],[34,1],[12,13],[18,19],[24,25],[9,10],[19,20],[28,29],[23,24],[5,6]],"handle_primary":[[20,[0.0,0.0]],[6,[0.0,0.0]],[22,[0.0,0.0]],[1,[0.0,0.0]],[5,[0.0,0.0]],[11,[0.0,0.0]],[32,[0.0,0.0]],[14,[0.0,0.0]],[33,[0.0,0.0]],[24,[0.0,0.0]],[7,[24.88888888888891,-15.111111111111086]],[27,[0.0,0.0]],[12,[0.0,0.0]],[15,[0.0,0.0]],[21,[0.0,0.0]],[4,[0.0,0.0]],[28,[0.0,0.0]],[18,[0.0,0.0]],[3,[0.0,0.0]],[9,[0.0,0.0]],[26,[0.0,0.0]],[30,[0.0,0.0]],[19,[0.0,0.0]],[31,[0.0,0.0]],[29,[Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0,"lambda":false}}],"nodes":[[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0,"lambda":false}},{"Node":{"node_id":2181148486404191200,"output_index":0,"lambda":false}}],"manual_composition":null,"implementation":{"Network":{"exports":[{"Node":{"node_id":3,"output_index":0,"lambda":false}}],"nodes":[[0,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":1}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToElementNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0,"lambda":false}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Reflection":"DocumentNodePath"}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::LayerNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0,"lambda":false}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Network":{"import_type":{"Generic":"T"},"import_index":0}}],"manual_composition":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic_element::ToGroupNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"VectorData":{"instance":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"line_cap":"Butt","line_join":"Miter","line_join_miter_limit":4.0,"transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_graphic_group":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"opacity":1.0,"blend_mode":"Normal"}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[21,[76.0,-202.22222222222223]],[5,[66.22222222222223,152.88888888888886]],[11,[136.88888888888886,39.111111111111086]],[24,[57.77777777777777,-129.33333333333334]],[30,[-9.333333333333371,0.0]],[23,[19.555555555555543,-139.55555555555557]],[33,[-78.22222222222223,75.55555555555554]],[2,[-67.55555555555554,158.22222222222217]],[6,[123.99999999999994,148.4444444444444]],[9,[156.4444444444444,97.33333333333331]],[34,[-5.333333333333371,99.11111111111109]],[25,[0.8888888888888573,-94.66666666666669]],[12,[199.5555555555555,10.666666666666629]],[27,[-11.111111111111144,-72.00000000000003]],[1,[-103.55555555555554,126.66666666666664]],[19,[90.66666666666664,-129.33333333333334]],[4,[18.66666666666663,157.77777777777771]],[31,[-53.33333333333337,13.777777777777771]],[32,[9.333333333333314,38.66666666666663]],[8,[252.4444444444444,124.88888888888886]],[28,[39.111111111111086,-58.22222222222226]],[17,[123.99999999999994,-84.00000000000003]],[15,[111.11111111111114,-60.888888888888914]],[7,[229.33333333333331,152.4444444444444]],[13,[153.77777777777777,-1.3333333333333712]],[22,[71.11111111111109,-201.7777777777778]],[16,[159.5555555555555,-75.55555555555557]],[26,[22.66666666666663,-81.33333333333337]],[3,[45.77777777777777,145.33333333333331]],[14,[183.11111111111103,-19.111111111111143]],[20,[128.4444444444444,-142.22222222222223]],[18,[145.77777777777777,-97.7777777777778]],[10,[216.4444444444444,72.4444444444444]],[29,[-32.888888888888914,-14.666666666666686]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[12,12],[21,21],[13,13],[9,9],[18,18],[2,2],[27,27],[25,25],[32,32],[5,5],[4,4],[8,8],[31,31],[10,10],[24,24],[3,3],[11,11],[6,6],[33,33],[30,30],[28,28],[20,20],[23,23],[26,26],[7,7],[15,15],[34,34],[16,16],[29,29],[14,14],[22,22],[19,19],[17,17],[1,1]],"end_point":[[5,6],[6,7],[18,19],[11,12],[23,24],[29,30],[31,32],[13,14],[27,28],[9,10],[19,20],[30,31],[10,11],[12,13],[17,18],[20,21],[2,3],[22,23],[24,25],[26,27],[21,22],[14,15],[7,8],[32,33],[3,4],[1,2],[4,5],[34,1],[33,34],[25,26],[15,16],[8,9],[16,17],[28,29]],"handle_primary":[[23,[0.0,0.0]],[6,[0.0,0.0]],[12,[0.0,0.0]],[33,[0.0,0.0]],[16,[0.0,0.0]],[14,[0.0,0.0]],[19,[0.0,0.0]],[34,[0.0,0.0]],[4,[0.0,0.0]],[17,[0.0,0.0]],[9,[0.0,0.0]],[29,[0.0,0.0]],[3,[0.0,0.0]],[8,[0.0,0.0]],[25,[0.0,0.0]],[26,[0.0,0.0]],[2,[30.66666666666663,2.6666666666666856]],[28,[0.0,0.0]],[22,[0.0,0.0]],[21,[0.0,0.0]],[11,[0.0,0.0]],[24,[0.0,0.0]],[27,[0.0,0.0]],[1,[0.0,0.0]],[32,[0Line truncated
+6 -1
View File
@@ -30,7 +30,9 @@ ron = ["dep:ron"]
# Local dependencies
graphite-proc-macros = { path = "../proc-macros" }
graph-craft = { path = "../node-graph/graph-craft" }
interpreted-executor = { path = "../node-graph/interpreted-executor", features = ["serde"] }
interpreted-executor = { path = "../node-graph/interpreted-executor", features = [
"serde",
] }
graphene-core = { path = "../node-graph/gcore" }
graphene-std = { path = "../node-graph/gstd", features = ["serde"] }
@@ -58,6 +60,9 @@ web-sys = { workspace = true, features = [
"Element",
"HtmlCanvasElement",
"CanvasRenderingContext2d",
"CanvasPattern",
"OffscreenCanvas",
"OffscreenCanvasRenderingContext2d",
"TextMetrics",
] }
@@ -20,8 +20,9 @@ impl DialogLayoutHolder for AboutGraphiteDialog {
fn layout_column_2(&self) -> Layout {
let links = [
("Website", "Website", "https://graphite.rs"),
("Heart", "Donate", "https://graphite.rs/donate/"),
("Volunteer", "Volunteer", "https://graphite.rs/volunteer/"),
("GraphiteLogo", "Website", "https://graphite.rs"),
("Credits", "Credits", "https://github.com/GraphiteEditor/Graphite/graphs/contributors"),
];
let mut widgets = links
@@ -282,6 +282,7 @@ pub fn input_mappings() -> Mapping {
entry!(KeyDown(Enter); action_dispatch=SplineToolMessage::Confirm),
//
// FillToolMessage
entry!(PointerMove; refresh_keys=[Shift], action_dispatch=FillToolMessage::PointerMove),
entry!(KeyDown(MouseLeft); action_dispatch=FillToolMessage::FillPrimaryColor),
entry!(KeyDown(MouseLeft); modifiers=[Shift], action_dispatch=FillToolMessage::FillSecondaryColor),
entry!(KeyUp(MouseLeft); action_dispatch=FillToolMessage::PointerUp),
@@ -276,13 +276,13 @@ impl LayoutMessageHandler {
responses.add(callback_message);
}
Widget::PivotInput(pivot_input) => {
Widget::ReferencePointInput(reference_point_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (pivot_input.on_commit.callback)(&()),
WidgetValueAction::Commit => (reference_point_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let update_value = value.as_str().expect("PivotInput update was not of type: u64");
pivot_input.position = update_value.into();
(pivot_input.on_update.callback)(pivot_input)
let update_value = value.as_str().expect("ReferencePointInput update was not of type: u64");
reference_point_input.value = update_value.into();
(reference_point_input.on_update.callback)(reference_point_input)
}
};
@@ -373,7 +373,7 @@ impl LayoutGroup {
Widget::TextInput(x) => &mut x.tooltip,
Widget::TextLabel(x) => &mut x.tooltip,
Widget::BreadcrumbTrailButtons(x) => &mut x.tooltip,
Widget::InvisibleStandinInput(_) | Widget::PivotInput(_) | Widget::RadioInput(_) | Widget::Separator(_) | Widget::WorkingColorsInput(_) | Widget::NodeCatalog(_) => continue,
Widget::InvisibleStandinInput(_) | Widget::ReferencePointInput(_) | Widget::RadioInput(_) | Widget::Separator(_) | Widget::WorkingColorsInput(_) | Widget::NodeCatalog(_) => continue,
};
if val.is_empty() {
val.clone_from(&tooltip);
@@ -546,7 +546,7 @@ pub enum Widget {
NodeCatalog(NodeCatalog),
NumberInput(NumberInput),
ParameterExposeButton(ParameterExposeButton),
PivotInput(PivotInput),
ReferencePointInput(ReferencePointInput),
PopoverButton(PopoverButton),
RadioInput(RadioInput),
Separator(Separator),
@@ -621,7 +621,7 @@ impl DiffUpdate {
| Widget::CurveInput(_)
| Widget::InvisibleStandinInput(_)
| Widget::NodeCatalog(_)
| Widget::PivotInput(_)
| Widget::ReferencePointInput(_)
| Widget::RadioInput(_)
| Widget::Separator(_)
| Widget::TextAreaInput(_)
@@ -1,9 +1,9 @@
use crate::messages::input_mapper::utility_types::misc::ActionKeys;
use crate::messages::layout::utility_types::widget_prelude::*;
use derivative::*;
use glam::DVec2;
use graphene_core::Color;
use graphene_core::raster::curve::Curve;
use graphene_std::transform::ReferencePoint;
use graphite_proc_macros::WidgetBuilder;
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
@@ -411,100 +411,18 @@ pub struct CurveInput {
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct PivotInput {
pub struct ReferencePointInput {
#[widget_builder(constructor)]
pub position: PivotPosition,
pub value: ReferencePoint,
pub disabled: bool,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<PivotInput>,
pub on_update: WidgetCallback<ReferencePointInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
#[derive(Clone, Copy, serde::Serialize, serde::Deserialize, Debug, Default, PartialEq, Eq, specta::Type)]
pub enum PivotPosition {
#[default]
None,
TopLeft,
TopCenter,
TopRight,
CenterLeft,
Center,
CenterRight,
BottomLeft,
BottomCenter,
BottomRight,
}
impl From<&str> for PivotPosition {
fn from(input: &str) -> Self {
match input {
"None" => PivotPosition::None,
"TopLeft" => PivotPosition::TopLeft,
"TopCenter" => PivotPosition::TopCenter,
"TopRight" => PivotPosition::TopRight,
"CenterLeft" => PivotPosition::CenterLeft,
"Center" => PivotPosition::Center,
"CenterRight" => PivotPosition::CenterRight,
"BottomLeft" => PivotPosition::BottomLeft,
"BottomCenter" => PivotPosition::BottomCenter,
"BottomRight" => PivotPosition::BottomRight,
_ => panic!("Failed parsing unrecognized PivotPosition enum value '{input}'"),
}
}
}
impl From<PivotPosition> for Option<DVec2> {
fn from(input: PivotPosition) -> Self {
match input {
PivotPosition::None => None,
PivotPosition::TopLeft => Some(DVec2::new(0., 0.)),
PivotPosition::TopCenter => Some(DVec2::new(0.5, 0.)),
PivotPosition::TopRight => Some(DVec2::new(1., 0.)),
PivotPosition::CenterLeft => Some(DVec2::new(0., 0.5)),
PivotPosition::Center => Some(DVec2::new(0.5, 0.5)),
PivotPosition::CenterRight => Some(DVec2::new(1., 0.5)),
PivotPosition::BottomLeft => Some(DVec2::new(0., 1.)),
PivotPosition::BottomCenter => Some(DVec2::new(0.5, 1.)),
PivotPosition::BottomRight => Some(DVec2::new(1., 1.)),
}
}
}
impl From<DVec2> for PivotPosition {
fn from(input: DVec2) -> Self {
const TOLERANCE: f64 = 1e-5_f64;
if input.y.abs() < TOLERANCE {
if input.x.abs() < TOLERANCE {
return PivotPosition::TopLeft;
} else if (input.x - 0.5).abs() < TOLERANCE {
return PivotPosition::TopCenter;
} else if (input.x - 1.).abs() < TOLERANCE {
return PivotPosition::TopRight;
}
} else if (input.y - 0.5).abs() < TOLERANCE {
if input.x.abs() < TOLERANCE {
return PivotPosition::CenterLeft;
} else if (input.x - 0.5).abs() < TOLERANCE {
return PivotPosition::Center;
} else if (input.x - 1.).abs() < TOLERANCE {
return PivotPosition::CenterRight;
}
} else if (input.y - 1.).abs() < TOLERANCE {
if input.x.abs() < TOLERANCE {
return PivotPosition::BottomLeft;
} else if (input.x - 0.5).abs() < TOLERANCE {
return PivotPosition::BottomCenter;
} else if (input.x - 1.).abs() < TOLERANCE {
return PivotPosition::BottomRight;
}
}
PivotPosition::None
}
}
@@ -2800,7 +2800,7 @@ mod document_message_handler_tests {
let document = editor.active_document();
for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
if (bbox[0].x - min_x).abs() < 1.0 && (bbox[0].y - min_y).abs() < 1.0 {
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
return Some(layer);
}
}
@@ -2814,8 +2814,8 @@ mod document_message_handler_tests {
parent.children(document.metadata()).position(|child| child == layer)
}
let layer_middle = get_layer_by_bounds(&mut editor, 50.0, 50.0).await.unwrap();
let layer_top = get_layer_by_bounds(&mut editor, 100.0, 100.0).await.unwrap();
let layer_middle = get_layer_by_bounds(&mut editor, 50., 50.).await.unwrap();
let layer_top = get_layer_by_bounds(&mut editor, 100., 100.).await.unwrap();
let initial_index_top = get_layer_index(&mut editor, layer_top).await.unwrap();
let initial_index_middle = get_layer_index(&mut editor, layer_middle).await.unwrap();
@@ -2915,7 +2915,7 @@ mod document_message_handler_tests {
// Applying transform to folder1 (translation)
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![folder1.to_node()] }).await;
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(100.0, 50.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(100., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -2927,7 +2927,7 @@ mod document_message_handler_tests {
// Applying different transform to folder2 (translation)
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![folder2.to_node()] }).await;
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(200.0, 100.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(200., 100., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -2946,7 +2946,7 @@ mod document_message_handler_tests {
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: folder1, insert_index: 0 }).await;
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(50.0, 25.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(50., 25., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -2967,10 +2967,10 @@ mod document_message_handler_tests {
let rect_bbox_after = document.metadata().bounding_box_viewport(rect_layer).unwrap();
// Verifing the rectangle maintains approximately the same position in viewport space
let before_center = (rect_bbox_before[0] + rect_bbox_before[1]) / 2.0;
let after_center = (rect_bbox_after[0] + rect_bbox_after[1]) / 2.0;
let before_center = (rect_bbox_before[0] + rect_bbox_before[1]) / 2.;
let after_center = (rect_bbox_after[0] + rect_bbox_after[1]) / 2.;
let distance = before_center.distance(after_center);
assert!(distance < 1.0, "Rectangle should maintain its viewport position after moving between transformed groups");
assert!(distance < 1., "Rectangle should maintain its viewport position after moving between transformed groups");
}
}
@@ -15,7 +15,7 @@ use graph_craft::document::value::*;
use graph_craft::document::*;
use graphene_core::raster::brush_cache::BrushCache;
use graphene_core::raster::image::ImageFrameTable;
use graphene_core::raster::{Color, RedGreenBlue, RedGreenBlueAlpha};
use graphene_core::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlue, RedGreenBlueAlpha};
use graphene_core::text::{Font, TypesettingConfig};
use graphene_core::transform::Footprint;
use graphene_core::vector::VectorDataTable;
@@ -128,6 +128,87 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
description: Cow::Borrowed("Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes."),
properties: Some("identity_properties"),
},
DocumentNodeDefinition {
identifier: "Cache",
category: "General",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
DocumentNode {
inputs: vec![NodeInput::network(generic!(T), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::memo::MemoNode")),
manual_composition: Some(generic!(T)),
..Default::default()
},
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::transform::FreezeRealTimeNode")),
manual_composition: Some(generic!(T)),
..Default::default()
},
DocumentNode {
inputs: vec![NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::transform::BoundlessFootprintNode")),
manual_composition: Some(generic!(T)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, true)],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
network_metadata: Some(NodeNetworkMetadata {
persistent_metadata: NodeNetworkPersistentMetadata {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Memoize".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Freeze Real Time".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Boundless Footprint".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
},
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
},
..Default::default()
}),
input_properties: vec![("Data", "TODO").into()],
output_names: vec!["Data".to_string()],
..Default::default()
},
},
description: Cow::Borrowed("TODO"),
properties: None,
},
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
identifier: "Monitor",
@@ -716,6 +797,87 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
description: Cow::Borrowed("Rasterizes the given vector data"),
properties: None,
},
DocumentNodeDefinition {
identifier: "Noise Pattern",
category: "Raster",
node_template: NodeTemplate {
document_node: DocumentNode {
manual_composition: Some(concrete!(Context)),
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_std::raster::NoisePatternNode")),
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::Bool(true), false),
NodeInput::value(TaggedValue::U32(0), false),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::NoiseType(NoiseType::default()), false),
NodeInput::value(TaggedValue::DomainWarpType(DomainWarpType::default()), false),
NodeInput::value(TaggedValue::F64(100.), false),
NodeInput::value(TaggedValue::FractalType(FractalType::default()), false),
NodeInput::value(TaggedValue::U32(3), false),
NodeInput::value(TaggedValue::F64(2.), false),
NodeInput::value(TaggedValue::F64(0.5), false),
NodeInput::value(TaggedValue::F64(0.), false), // 0-1 range
NodeInput::value(TaggedValue::F64(2.), false),
NodeInput::value(TaggedValue::CellularDistanceFunction(CellularDistanceFunction::default()), false),
NodeInput::value(TaggedValue::CellularReturnType(CellularReturnType::default()), false),
NodeInput::value(TaggedValue::F64(1.), false),
],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
input_properties: vec![
("Spacer", "TODO").into(),
("Clip", "TODO").into(),
("Seed", "TODO").into(),
PropertiesRow::with_override("Scale", "TODO", WidgetOverride::Custom("noise_properties_scale".to_string())),
PropertiesRow::with_override("Noise Type", "TODO", WidgetOverride::Custom("noise_properties_noise_type".to_string())),
PropertiesRow::with_override("Domain Warp Type", "TODO", WidgetOverride::Custom("noise_properties_domain_warp_type".to_string())),
PropertiesRow::with_override("Domain Warp Amplitude", "TODO", WidgetOverride::Custom("noise_properties_domain_warp_amplitude".to_string())),
PropertiesRow::with_override("Fractal Type", "TODO", WidgetOverride::Custom("noise_properties_fractal_type".to_string())),
PropertiesRow::with_override("Fractal Octaves", "TODO", WidgetOverride::Custom("noise_properties_fractal_octaves".to_string())),
PropertiesRow::with_override("Fractal Lacunarity", "TODO", WidgetOverride::Custom("noise_properties_fractal_lacunarity".to_string())),
PropertiesRow::with_override("Fractal Gain", "TODO", WidgetOverride::Custom("noise_properties_fractal_gain".to_string())),
PropertiesRow::with_override("Fractal Weighted Strength", "TODO", WidgetOverride::Custom("noise_properties_fractal_weighted_strength".to_string())),
PropertiesRow::with_override("Fractal Ping Pong Strength", "TODO", WidgetOverride::Custom("noise_properties_ping_pong_strength".to_string())),
PropertiesRow::with_override("Cellular Distance Function", "TODO", WidgetOverride::Custom("noise_properties_cellular_distance_function".to_string())),
PropertiesRow::with_override("Cellular Return Type", "TODO", WidgetOverride::Custom("noise_properties_cellular_return_type".to_string())),
PropertiesRow::with_override("Cellular Jitter", "TODO", WidgetOverride::Custom("noise_properties_cellular_jitter".to_string())),
],
output_names: vec!["Image".to_string()],
network_metadata: Some(NodeNetworkMetadata {
persistent_metadata: NodeNetworkPersistentMetadata {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Noise Pattern".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Cull".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
},
..Default::default()
}),
..Default::default()
},
},
description: Cow::Borrowed("Generates different noise patterns."),
properties: None,
},
// TODO: This needs to work with resolution-aware (raster with footprint, post-Cull node) data.
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
@@ -2100,6 +2262,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().character_spacing), false),
NodeInput::value(TaggedValue::OptionalF64(TypesettingConfig::default().max_width), false),
NodeInput::value(TaggedValue::OptionalF64(TypesettingConfig::default().max_height), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
..Default::default()
},
@@ -2153,6 +2316,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
..Default::default()
}),
),
PropertiesRow::with_override("Instances", "TODO", WidgetOverride::Custom("instances".to_string())),
],
output_names: vec!["Vector".to_string()],
..Default::default()
@@ -3559,7 +3723,7 @@ impl DocumentNodeDefinition {
};
nested_node_metadata.persistent_metadata.input_properties.resize_with(input_length, PropertiesRow::default);
//Recurse over all sub nodes if the current node is a network implementation
// Recurse over all sub-nodes if the current node is a network implementation
let mut current_path = path.clone();
current_path.push(current_node);
let DocumentNodeImplementation::Network(template_network) = &node_template.document_node.implementation else {
@@ -17,17 +17,18 @@ use graphene_core::raster::{
SelectiveColorChoice,
};
use graphene_core::text::Font;
use graphene_core::vector::generator_nodes::grid;
use graphene_core::vector::misc::CentroidType;
use graphene_core::vector::style::{GradientType, LineCap, LineJoin};
use graphene_std::animation::RealTimeMode;
use graphene_std::application_io::TextureFrameTable;
use graphene_std::ops::XY;
use graphene_std::transform::Footprint;
use graphene_std::transform::{Footprint, ReferencePoint};
use graphene_std::vector::VectorDataTable;
use graphene_std::vector::misc::ArcType;
use graphene_std::vector::misc::{BooleanOperation, GridType};
use graphene_std::vector::style::{Fill, FillChoice, FillType, GradientStops};
use graphene_std::{GraphicGroupTable, RasterFrame};
use graphene_std::{GraphicGroupTable, NodeInputDecleration, RasterFrame};
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
let widget = TextLabel::new(text).widget_holder();
@@ -53,7 +54,11 @@ pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphData
ParameterExposeButton::new()
.exposed(exposed)
.data_type(data_type)
.tooltip("Expose this parameter as a node input in the graph")
.tooltip(if exposed {
"Stop exposing this parameter as a node input in the graph"
} else {
"Expose this parameter as a node input in the graph"
})
.on_update(move |_parameter| {
Message::Batched(Box::new([
NodeGraphMessage::ExposeInput {
@@ -173,6 +178,7 @@ pub(crate) fn property_from_type(
Some(x) if x == TypeId::of::<VectorDataTable>() => vector_data_widget(default_info).into(),
Some(x) if x == TypeId::of::<RasterFrame>() || x == TypeId::of::<ImageFrameTable<Color>>() || x == TypeId::of::<TextureFrameTable>() => raster_widget(default_info).into(),
Some(x) if x == TypeId::of::<GraphicGroupTable>() => group_widget(default_info).into(),
Some(x) if x == TypeId::of::<ReferencePoint>() => reference_point_widget(default_info, false).into(),
Some(x) if x == TypeId::of::<Footprint>() => footprint_widget(default_info, &mut extra_widgets),
Some(x) if x == TypeId::of::<BlendMode>() => blend_mode_widget(default_info),
Some(x) if x == TypeId::of::<RealTimeMode>() => real_time_mode_widget(default_info),
@@ -286,6 +292,27 @@ pub fn bool_widget(parameter_widgets_info: ParameterWidgetsInfo, checkbox_input:
widgets
}
pub fn reference_point_widget(parameter_widgets_info: ParameterWidgetsInfo, disabled: bool) -> Vec<WidgetHolder> {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
let mut widgets = start_widgets(parameter_widgets_info, FrontendGraphDataType::General);
let Some(input) = document_node.inputs.get(index) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(&TaggedValue::ReferencePoint(reference_point)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_holder(),
ReferencePointInput::new(reference_point)
.on_update(update_value(move |x: &ReferencePointInput| TaggedValue::ReferencePoint(x.value), node_id, index))
.disabled(disabled)
.widget_holder(),
])
}
widgets
}
pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
@@ -1621,11 +1648,11 @@ pub(crate) fn _gpu_map_properties(parameter_widgets_info: ParameterWidgetsInfo)
}
pub(crate) fn grid_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
let grid_type_index = 1;
let spacing_index = 2;
let angles_index = 3;
let rows_index = 4;
let columns_index = 5;
let grid_type_index = grid::GridTypeInput::INDEX;
let spacing_index = grid::SpacingInput::<f64>::INDEX;
let angles_index = grid::AnglesInput::INDEX;
let rows_index = grid::RowsInput::INDEX;
let columns_index = grid::ColumnsInput::INDEX;
let document_node = match get_document_node(node_id, context) {
Ok(document_node) => document_node,
@@ -47,7 +47,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageData<'_>> for OverlaysMessag
let [a, b, c, d, e, f] = DAffine2::from_scale(DVec2::splat(device_pixel_ratio)).to_cols_array();
let _ = context.set_transform(a, b, c, d, e, f);
context.clear_rect(0., 0., ipp.viewport_bounds.size().x, ipp.viewport_bounds.size().y);
context.clear_rect(0., 0., canvas.width().into(), canvas.height().into());
let _ = context.reset_transform();
if overlays_visible {
@@ -8,10 +8,12 @@ use bezier_rs::{Bezier, Subpath};
use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, TAU};
use glam::{DAffine2, DVec2};
use graphene_core::Color;
use graphene_core::renderer::Quad;
use graphene_std::vector::{PointId, SegmentId, VectorData};
use std::collections::HashMap;
use wasm_bindgen::JsValue;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{OffscreenCanvas, OffscreenCanvasRenderingContext2d};
pub type OverlayProvider = fn(OverlayContext) -> Message;
@@ -447,6 +449,7 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}
/// Used by the Pen and Path tools to outline the path of the shape.
pub fn outline_vector(&mut self, vector_data: &VectorData, transform: DAffine2) {
self.start_dpi_aware_transform();
@@ -465,6 +468,7 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}
/// Used by the Pen tool in order to show how the bezier curve would look like.
pub fn outline_bezier(&mut self, bezier: Bezier, transform: DAffine2) {
self.start_dpi_aware_transform();
@@ -493,7 +497,7 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}
pub fn outline(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
@@ -540,10 +544,63 @@ impl OverlayContext {
}
}
self.end_dpi_aware_transform();
}
/// Used by the Select tool to outline a path selected or hovered.
pub fn outline(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
self.push_path(subpaths, transform);
self.render_context.set_stroke_style_str(COLOR_OVERLAY_BLUE);
self.render_context.stroke();
}
self.end_dpi_aware_transform();
/// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed.
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.push_path(subpaths, transform);
self.render_context.set_fill_style_str(color);
self.render_context.fill();
}
/// Fills the area inside the path with a pattern. Assumes `color` is in gamma space.
/// Used by the fill tool to show the area to be filled.
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &Color) {
const PATTERN_WIDTH: usize = 4;
const PATTERN_HEIGHT: usize = 4;
let pattern_canvas = OffscreenCanvas::new(PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
let pattern_context: OffscreenCanvasRenderingContext2d = pattern_canvas
.get_context("2d")
.ok()
.flatten()
.expect("Failed to get canvas context")
.dyn_into()
.expect("Context should be a canvas 2d context");
// 4x4 pixels, 4 components (RGBA) per pixel
let mut data = [0_u8; 4 * PATTERN_WIDTH * PATTERN_HEIGHT];
// ┌▄▄┬──┬──┬──┐
// ├▀▀┼──┼──┼──┤
// ├──┼──┼▄▄┼──┤
// ├──┼──┼▀▀┼──┤
// └──┴──┴──┴──┘
let pixels = [(0, 0), (2, 2)];
for &(x, y) in &pixels {
let index = (x + y * PATTERN_WIDTH as usize) * 4;
data[index..index + 4].copy_from_slice(&color.to_rgba8_srgb());
}
let image_data = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&mut data), PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
pattern_context.put_image_data(&image_data, 0., 0.).unwrap();
let pattern = self.render_context.create_pattern_with_offscreen_canvas(&pattern_canvas, "repeat").unwrap().unwrap();
self.push_path(subpaths, transform);
self.render_context.set_fill_style_canvas_pattern(&pattern);
self.render_context.fill();
}
pub fn get_width(&self, text: &str) -> f64 {
@@ -1141,7 +1141,7 @@ impl NodeNetworkInterface {
pub fn input_description<'a>(&'a self, node_id: NodeId, index: usize, network_path: &[NodeId]) -> Option<&'a str> {
let Some(input_row) = self.input_properties_row(&node_id, index, network_path) else {
log::error!("Could not get node_metadata in input_description");
log::error!("Could not get input_row in input_description");
return None;
};
let description = input_row.input_description.as_str();
@@ -1162,7 +1162,7 @@ impl NodeNetworkInterface {
pub fn input_metadata(&self, node_id: &NodeId, index: usize, field: &str, network_path: &[NodeId]) -> Option<&Value> {
let Some(input_row) = self.input_properties_row(node_id, index, network_path) else {
log::error!("Could not get node_metadata in get_input_metadata");
log::error!("Could not get input_row in get_input_metadata");
return None;
};
input_row.input_data.get(field)
@@ -3781,6 +3781,7 @@ impl NodeNetworkInterface {
self.unload_stack_dependents(network_path);
}
// TODO: Eventually remove this document upgrade code
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts
pub fn replace_implementation(&mut self, node_id: &NodeId, network_path: &[NodeId], implementation: DocumentNodeImplementation) {
let Some(network) = self.network_mut(network_path) else {
@@ -585,18 +585,29 @@ impl LayoutHolder for MenuBarMessageHandler {
action: MenuBarEntry::create_action(|_| DialogMessage::RequestAboutGraphiteDialog.into()),
..MenuBarEntry::default()
}],
vec![MenuBarEntry {
label: "User Manual".into(),
icon: Some("UserManual".into()),
action: MenuBarEntry::create_action(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.rs/learn/".into(),
}
.into()
}),
..MenuBarEntry::default()
}],
vec![
MenuBarEntry {
label: "Donate to Graphite".into(),
icon: Some("Heart".into()),
action: MenuBarEntry::create_action(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.rs/donate/".into(),
}
.into()
}),
..MenuBarEntry::default()
},
MenuBarEntry {
label: "User Manual".into(),
icon: Some("UserManual".into()),
action: MenuBarEntry::create_action(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.rs/learn/".into(),
}
.into()
}),
..MenuBarEntry::default()
},
MenuBarEntry {
label: "Report a Bug".into(),
icon: Some("Bug".into()),
@@ -828,6 +828,34 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::Bool(true), false), network_path);
}
// Upgrade the Mirror node to add the `reference_point` input and change `offset` from `DVec2` to `f64`
if reference == "Mirror" && inputs_count == 4 {
let node_definition = resolve_document_node_type(reference).unwrap();
let new_node_template = node_definition.default_node_template();
let document_node = new_node_template.document_node;
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
document
.network_interface
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
let Some(&TaggedValue::DVec2(old_offset)) = old_inputs[1].as_value() else { return };
let old_offset = if old_offset.x.abs() > old_offset.y.abs() { old_offset.x } else { old_offset.y };
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(
&InputConnector::node(*node_id, 1),
NodeInput::value(TaggedValue::ReferencePoint(graphene_std::transform::ReferencePoint::Center), false),
network_path,
);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::F64(old_offset), false), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 3), old_inputs[2].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[3].clone(), network_path);
}
// Upgrade artboard name being passed as hidden value input to "To Artboard"
if reference == "Artboard" && upgrade_from_before_returning_nested_click_targets {
let label = document.network_interface.display_name(node_id, network_path);
@@ -862,6 +890,21 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageData<'_>> for PortfolioMes
document.network_interface.set_input(&InputConnector::node(*node_id, i + 1), input.clone(), network_path);
}
}
if reference == "Instance on Points" && inputs_count == 2 {
let node_definition = resolve_document_node_type(reference).unwrap();
let new_node_template = node_definition.default_node_template();
let document_node = new_node_template.document_node;
document.network_interface.replace_implementation(node_id, network_path, document_node.implementation.clone());
document
.network_interface
.replace_implementation_metadata(node_id, network_path, new_node_template.persistent_node_metadata);
let old_inputs = document.network_interface.replace_inputs(node_id, document_node.inputs.clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
}
}
// TODO: Eventually remove this document upgrade code
@@ -258,7 +258,7 @@ impl<T: InstanceLayout> InstanceLayout for Instances<T> {
}
let mut rows = self
.instances()
.instance_ref_iter()
.enumerate()
.map(|(index, instance)| {
vec![
@@ -2,11 +2,11 @@
use super::graph_modification_utils;
use crate::consts::PIVOT_DIAMETER;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2};
use graphene_std::transform::ReferencePoint;
use std::collections::VecDeque;
#[derive(Clone, Debug)]
@@ -18,7 +18,7 @@ pub struct Pivot {
/// The viewspace pivot position (if applicable)
pivot: Option<DVec2>,
/// The old pivot position in the GUI, used to reduce refreshes of the document bar
old_pivot_position: PivotPosition,
old_pivot_position: ReferencePoint,
}
impl Default for Pivot {
@@ -27,7 +27,7 @@ impl Default for Pivot {
normalized_pivot: DVec2::splat(0.5),
transform_from_normalized: Default::default(),
pivot: Default::default(),
old_pivot_position: PivotPosition::Center,
old_pivot_position: ReferencePoint::Center,
}
}
}
@@ -96,7 +96,7 @@ impl Pivot {
should_refresh
}
pub fn to_pivot_position(&self) -> PivotPosition {
pub fn to_pivot_position(&self) -> ReferencePoint {
self.normalized_pivot.into()
}
@@ -729,7 +729,9 @@ impl ShapeState {
let length = transform.transform_vector2(unselected_position - anchor).length();
let position = transform.inverse().transform_vector2(direction * length);
let modification_type = unselected_handle.set_relative_position(position);
responses.add(GraphOperationMessage::Vector { layer, modification_type });
if (anchor - selected_position).length() > 1e-6 {
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
}
// If both handles are selected, average the angles of the handles
else {
@@ -775,6 +777,7 @@ impl ShapeState {
in_viewport_space: bool,
was_alt_dragging: bool,
opposite_handle_position: Option<DVec2>,
skip_opposite_handle: bool,
responses: &mut VecDeque<Message>,
) {
for (&layer, state) in &self.selected_shape_state {
@@ -816,6 +819,11 @@ impl ShapeState {
responses.add(GraphOperationMessage::Vector { layer, modification_type });
let Some(other) = vector_data.other_colinear_handle(handle) else { continue };
if skip_opposite_handle {
continue;
}
if state.is_selected(other.to_manipulator_point()) {
// If two colinear handles are being dragged at the same time but not the anchor, it is necessary to break the colinear state.
let handles = [handle, other];
@@ -4,7 +4,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils::get_t
use glam::DVec2;
use graphene_core::renderer::Quad;
use graphene_core::text::{FontCache, load_face};
use graphene_std::vector::PointId;
use graphene_std::vector::{ManipulatorPointId, PointId, SegmentId, VectorData};
/// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable.
pub fn should_extend(
@@ -66,3 +66,30 @@ pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageH
Quad::from_box([DVec2::ZERO, far])
}
pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector_data: &VectorData, pen_tool: bool) -> Option<f64> {
let is_start = |point: PointId, segment: SegmentId| vector_data.segment_start_from_id(segment) == Some(point);
let anchor_position = vector_data.point_domain.position_from_id(anchor)?;
let end_handle = ManipulatorPointId::EndHandle(segment).get_position(vector_data);
let start_handle = ManipulatorPointId::PrimaryHandle(segment).get_position(vector_data);
let start_point = if is_start(anchor, segment) {
vector_data.segment_end_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
} else {
vector_data.segment_start_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
};
let required_handle = if is_start(anchor, segment) {
start_handle
.filter(|&handle| pen_tool && handle != anchor_position)
.or(end_handle.filter(|&handle| Some(handle) != start_point))
.or(start_point)
} else {
end_handle
.filter(|&handle| pen_tool && handle != anchor_position)
.or(start_handle.filter(|&handle| Some(handle) != start_point))
.or(start_point)
};
required_handle.map(|handle| -(handle - anchor_position).angle_to(DVec2::X))
}
@@ -218,7 +218,7 @@ impl MessageHandler<ToolMessage, ToolMessageData<'_>> for ToolMessageHandler {
let document_data = &mut self.tool_state.document_tool_data;
document_data.primary_color = color;
self.tool_state.document_tool_data.update_working_colors(responses); // TODO: Make this an event
document_data.update_working_colors(responses); // TODO: Make this an event
}
ToolMessage::SelectRandomPrimaryColor => {
// Select a random primary color (rgba) based on an UUID
@@ -1,18 +1,23 @@
use super::tool_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use graphene_core::vector::style::Fill;
#[derive(Default)]
pub struct FillTool {
fsm_state: FillToolFsmState,
}
#[impl_message(Message, ToolMessage, Fill)]
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
#[derive(PartialEq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum FillToolMessage {
// Standard messages
Abort,
WorkingColorChanged,
Overlays(OverlayContext),
// Tool-specific messages
PointerMove,
PointerUp,
FillPrimaryColor,
FillSecondaryColor,
@@ -45,8 +50,10 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionHandlerData<'a>> for FillToo
FillToolFsmState::Ready => actions!(FillToolMessageDiscriminant;
FillPrimaryColor,
FillSecondaryColor,
PointerMove,
),
FillToolFsmState::Filling => actions!(FillToolMessageDiscriminant;
PointerMove,
PointerUp,
Abort,
),
@@ -58,6 +65,8 @@ impl ToolTransition for FillTool {
fn event_to_message_map(&self) -> EventToMessageMap {
EventToMessageMap {
tool_abort: Some(FillToolMessage::Abort.into()),
working_color_changed: Some(FillToolMessage::WorkingColorChanged.into()),
overlay_provider: Some(|overlay_context| FillToolMessage::Overlays(overlay_context).into()),
..Default::default()
}
}
@@ -82,6 +91,23 @@ impl Fsm for FillToolFsmState {
let ToolMessage::Fill(event) = event else { return self };
match (self, event) {
(_, FillToolMessage::Overlays(mut overlay_context)) => {
// Choose the working color to preview
let use_secondary = input.keyboard.get(Key::Shift as usize);
let preview_color = if use_secondary { global_tool_data.secondary_color } else { global_tool_data.primary_color };
// Get the layer the user is hovering over
if let Some(layer) = document.click(input) {
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &preview_color);
}
self
}
(_, FillToolMessage::PointerMove | FillToolMessage::WorkingColorChanged) => {
// Generate the hover outline
responses.add(OverlaysMessage::Draw);
self
}
(FillToolFsmState::Ready, color_event) => {
let Some(layer_identifier) = document.click(input) else {
return self;
@@ -462,8 +462,8 @@ mod test_line_tool {
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
match (start_input, end_input) {
(start_input, end_input) => {
assert!((start_input - DVec2::ZERO).length() < 1.0, "Start point should be near (0,0)");
assert!((end_input - DVec2::new(100.0, 100.0)).length() < 1.0, "End point should be near (100,100)");
assert!((start_input - DVec2::ZERO).length() < 1., "Start point should be near (0,0)");
assert!((end_input - DVec2::new(100., 100.)).length() < 1., "End point should be near (100,100)");
}
}
}
@@ -473,9 +473,13 @@ mod test_line_tool {
async fn test_line_tool_with_transformed_viewport() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 2.0 }).await;
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(100.0, 50.0) }).await;
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 30.0_f64.to_radians() }).await;
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 2. }).await;
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(100., 50.) }).await;
editor
.handle_message(NavigationMessage::CanvasTiltSet {
angle_radians: (30. as f64).to_radians(),
})
.await;
editor.drag_tool(ToolType::Line, 0., 0., 100., 100., ModifierKeys::empty()).await;
if let Some((start_input, end_input)) = get_line_node_inputs(&mut editor).await {
let document = editor.active_document();
@@ -483,16 +487,16 @@ mod test_line_tool {
let viewport_to_document = document_to_viewport.inverse();
let expected_start = viewport_to_document.transform_point2(DVec2::ZERO);
let expected_end = viewport_to_document.transform_point2(DVec2::new(100.0, 100.0));
let expected_end = viewport_to_document.transform_point2(DVec2::new(100., 100.));
assert!(
(start_input - expected_start).length() < 1.0,
(start_input - expected_start).length() < 1.,
"Start point should match expected document coordinates. Got {:?}, expected {:?}",
start_input,
expected_start
);
assert!(
(end_input - expected_end).length() < 1.0,
(end_input - expected_end).length() < 1.,
"End point should match expected document coordinates. Got {:?}, expected {:?}",
end_input,
expected_end
@@ -519,7 +523,7 @@ mod test_line_tool {
let updated_line_vec = updated_end - updated_start;
let updated_angle = updated_line_vec.angle_to(DVec2::X);
assert!((original_angle - updated_angle).abs() < 0.1, "Line angle should be locked when Ctrl is kept pressed");
assert!((updated_start - updated_end).length() > 1.0, "Line should be able to change length when Ctrl is kept pressed");
assert!((updated_start - updated_end).length() > 1., "Line should be able to change length when Ctrl is kept pressed");
}
}
}
@@ -538,8 +542,8 @@ mod test_line_tool {
(start_input, end_input) => {
let expected_start = DVec2::new(0., 100.);
let expected_end = DVec2::new(200., 100.);
assert!((start_input - expected_start).length() < 1.0, "start point should be near (0,100)");
assert!((end_input - expected_end).length() < 1.0, "end point should be near (200,100)");
assert!((start_input - expected_start).length() < 1., "start point should be near (0,100)");
assert!((end_input - expected_end).length() < 1., "end point should be near (200,100)");
}
}
}
@@ -556,9 +560,9 @@ mod test_line_tool {
let line_vec = end_input - start_input;
let angle_radians = line_vec.angle_to(DVec2::X);
let angle_degrees = angle_radians.to_degrees();
let nearest_angle = (angle_degrees / 15.0).round() * 15.0;
let nearest_angle = (angle_degrees / 15.).round() * 15.;
assert!((angle_degrees - nearest_angle).abs() < 1.0, "Angle should snap to the nearest 15 degrees");
assert!((angle_degrees - nearest_angle).abs() < 1., "Angle should snap to the nearest 15 degrees");
}
}
}
@@ -15,6 +15,7 @@ use crate::messages::tool::common_functionality::shape_editor::{
ClosestSegment, ManipulatorAngle, OpposingHandleLengths, SelectedPointsInfo, SelectionChange, SelectionShape, SelectionShapeType, ShapeState,
};
use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager};
use crate::messages::tool::common_functionality::utility_functions::calculate_segment_angle;
use graphene_core::renderer::Quad;
use graphene_core::vector::{ManipulatorPointId, PointId, VectorModificationType};
use graphene_std::vector::{HandleId, NoHashBuilder, SegmentId, VectorData};
@@ -380,6 +381,8 @@ struct PathToolData {
snapping_axis: Option<Axis>,
alt_clicked_on_anchor: bool,
alt_dragging_from_anchor: bool,
angle_locked: bool,
temporary_colinear_handles: bool,
}
impl PathToolData {
@@ -727,11 +730,38 @@ impl PathToolData {
Some((handle_position_document, anchor_position_document, handle_id))
}
fn calculate_handle_angle(&mut self, handle_vector: DVec2, handle_id: ManipulatorPointId, lock_angle: bool, snap_angle: bool) -> f64 {
#[allow(clippy::too_many_arguments)]
fn calculate_handle_angle(
&mut self,
shape_editor: &mut ShapeState,
document: &DocumentMessageHandler,
responses: &mut VecDeque<Message>,
relative_vector: DVec2,
handle_vector: DVec2,
handle_id: ManipulatorPointId,
lock_angle: bool,
snap_angle: bool,
) -> f64 {
let current_angle = -handle_vector.angle_to(DVec2::X);
if let Some(vector_data) = shape_editor
.selected_shape_state
.iter()
.next()
.and_then(|(layer, _)| document.network_interface.compute_modified_vector(*layer))
{
if relative_vector.length() < 25. && lock_angle && !self.angle_locked {
if let Some(angle) = calculate_lock_angle(self, shape_editor, responses, document, &vector_data, handle_id) {
self.angle = angle;
return angle;
}
}
}
// When the angle is locked we use the old angle
if self.current_selected_handle_id == Some(handle_id) && lock_angle {
self.angle_locked = true;
return self.angle;
}
@@ -785,7 +815,7 @@ impl PathToolData {
let drag_start = self.drag_start_pos;
let opposite_delta = drag_start - current_mouse;
shape_editor.move_selected_points(None, document, opposite_delta, false, true, false, None, responses);
shape_editor.move_selected_points(None, document, opposite_delta, false, true, false, None, false, responses);
// Calculate the projected delta and shift the points along that delta
let delta = current_mouse - drag_start;
@@ -797,7 +827,7 @@ impl PathToolData {
_ => DVec2::new(delta.x, 0.),
};
shape_editor.move_selected_points(None, document, projected_delta, false, true, false, None, responses);
shape_editor.move_selected_points(None, document, projected_delta, false, true, false, None, false, responses);
}
fn stop_snap_along_axis(&mut self, shape_editor: &mut ShapeState, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) {
@@ -813,12 +843,12 @@ impl PathToolData {
_ => DVec2::new(opposite_delta.x, 0.),
};
shape_editor.move_selected_points(None, document, opposite_projected_delta, false, true, false, None, responses);
shape_editor.move_selected_points(None, document, opposite_projected_delta, false, true, false, None, false, responses);
// Calculate what actually would have been the original delta for the point, and apply that
let delta = current_mouse - drag_start;
shape_editor.move_selected_points(None, document, delta, false, true, false, None, responses);
shape_editor.move_selected_points(None, document, delta, false, true, false, None, false, responses);
self.snapping_axis = None;
}
@@ -872,7 +902,7 @@ impl PathToolData {
let snapped_delta = if let Some((handle_pos, anchor_pos, handle_id)) = self.try_get_selected_handle_and_anchor(shape_editor, document) {
let cursor_pos = handle_pos + raw_delta;
let handle_angle = self.calculate_handle_angle(cursor_pos - anchor_pos, handle_id, lock_angle, snap_angle);
let handle_angle = self.calculate_handle_angle(shape_editor, document, responses, handle_pos - anchor_pos, cursor_pos - anchor_pos, handle_id, lock_angle, snap_angle);
let constrained_direction = DVec2::new(handle_angle.cos(), handle_angle.sin());
let projected_length = (cursor_pos - anchor_pos).dot(constrained_direction);
@@ -931,7 +961,14 @@ impl PathToolData {
self.alt_dragging_from_anchor = false;
self.alt_clicked_on_anchor = false;
}
shape_editor.move_selected_points(handle_lengths, document, snapped_delta, equidistant, true, was_alt_dragging, opposite, responses);
let mut skip_opposite = false;
if self.temporary_colinear_handles && !lock_angle {
shape_editor.disable_colinear_handles_state_on_selected(&document.network_interface, responses);
self.temporary_colinear_handles = false;
skip_opposite = true;
}
shape_editor.move_selected_points(handle_lengths, document, snapped_delta, equidistant, true, was_alt_dragging, opposite, skip_opposite, responses);
self.previous_mouse_position += document_to_viewport.inverse().transform_vector2(snapped_delta);
} else {
let Some(axis) = self.snapping_axis else { return };
@@ -940,7 +977,7 @@ impl PathToolData {
Axis::Y => DVec2::new(0., unsnapped_delta.y),
_ => DVec2::new(unsnapped_delta.x, 0.),
};
shape_editor.move_selected_points(handle_lengths, document, projected_delta, equidistant, true, false, opposite, responses);
shape_editor.move_selected_points(handle_lengths, document, projected_delta, equidistant, true, false, opposite, false, responses);
self.previous_mouse_position += document_to_viewport.inverse().transform_vector2(unsnapped_delta);
}
@@ -1030,7 +1067,7 @@ impl Fsm for PathToolFsmState {
match self {
Self::Drawing { selection_shape } => {
let mut fill_color = graphene_std::Color::from_rgb_str(crate::consts::COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
let mut fill_color = graphene_std::Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
.unwrap()
.with_alpha(0.05)
.to_rgba_hex_srgb();
@@ -1238,6 +1275,10 @@ impl Fsm for PathToolFsmState {
let lock_angle_state = input.keyboard.get(lock_angle as usize);
let snap_angle_state = input.keyboard.get(snap_angle as usize);
if !lock_angle_state {
tool_data.angle_locked = false;
}
if !tool_data.update_colinear(equidistant_state, toggle_colinear_state, tool_action_data.shape_editor, tool_action_data.document, responses) {
tool_data.drag(
equidistant_state,
@@ -1412,6 +1453,10 @@ impl Fsm for PathToolFsmState {
}
}
if tool_data.temporary_colinear_handles {
tool_data.temporary_colinear_handles = false;
}
if tool_data.handle_drag_toggle && drag_occurred {
shape_editor.deselect_all_points();
shape_editor.select_points_by_manipulator_id(&tool_data.saved_points_before_handle_drag);
@@ -1511,6 +1556,7 @@ impl Fsm for PathToolFsmState {
false,
false,
tool_data.opposite_handle_position,
false,
responses,
);
@@ -1749,3 +1795,52 @@ fn get_selection_status(network_interface: &NodeNetworkInterface, shape_state: &
SelectionStatus::None
}
fn calculate_lock_angle(
tool_data: &mut PathToolData,
shape_state: &mut ShapeState,
responses: &mut VecDeque<Message>,
document: &DocumentMessageHandler,
vector_data: &VectorData,
handle_id: ManipulatorPointId,
) -> Option<f64> {
let anchor = handle_id.get_anchor(vector_data)?;
let anchor_position = vector_data.point_domain.position_from_id(anchor);
let current_segment = handle_id.get_segment();
let points_connected = vector_data.connected_count(anchor);
let (anchor_position, segment) = anchor_position.zip(current_segment)?;
if points_connected == 1 {
calculate_segment_angle(anchor, segment, vector_data, false)
} else {
let opposite_handle = handle_id
.get_handle_pair(vector_data)
.iter()
.flatten()
.find(|&h| h.to_manipulator_point() != handle_id)
.copied()
.map(|h| h.to_manipulator_point());
let opposite_handle_position = opposite_handle.and_then(|h| h.get_position(vector_data)).filter(|pos| (pos - anchor_position).length() > 1e-6);
if let Some(opposite_pos) = opposite_handle_position {
if !vector_data.colinear_manipulators.iter().flatten().map(|h| h.to_manipulator_point()).any(|h| h == handle_id) {
shape_state.convert_selected_manipulators_to_colinear_handles(responses, document);
tool_data.temporary_colinear_handles = true;
}
Some(-(opposite_pos - anchor_position).angle_to(DVec2::X))
} else {
let angle_1 = vector_data
.adjacent_segment(&handle_id)
.and_then(|(_, adjacent_segment)| calculate_segment_angle(anchor, adjacent_segment, vector_data, false));
let angle_2 = calculate_segment_angle(anchor, segment, vector_data, false);
match (angle_1, angle_2) {
(Some(angle_1), Some(angle_2)) => Some((angle_1 + angle_2) / 2.0),
(Some(angle_1), None) => Some(angle_1),
(None, Some(angle_2)) => Some(angle_2),
(None, None) => None,
}
}
}
}
@@ -1,5 +1,5 @@
use super::tool_prelude::*;
use crate::consts::{DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE};
use crate::consts::{COLOR_OVERLAY_BLUE, DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE};
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
@@ -10,12 +10,12 @@ use crate::messages::tool::common_functionality::color_selector::{ToolColorOptio
use crate::messages::tool::common_functionality::graph_modification_utils::{self, merge_layers};
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
use crate::messages::tool::common_functionality::utility_functions::{closest_point, should_extend};
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, closest_point, should_extend};
use bezier_rs::{Bezier, BezierHandles};
use graph_craft::document::NodeId;
use graphene_core::Color;
use graphene_core::vector::{PointId, VectorModificationType};
use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, VectorData};
use graphene_std::vector::{HandleId, ManipulatorPointId, NoHashBuilder, SegmentId, StrokeId, VectorData};
#[derive(Default)]
pub struct PenTool {
@@ -608,7 +608,9 @@ impl PenToolData {
// Get close path
let mut end = None;
let layer = self.current_layer?;
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
let layer = selected_layers.next().filter(|_| selected_layers.next().is_none()).or(self.current_layer)?;
let vector_data = document.network_interface.compute_modified_vector(layer)?;
let start = self.latest_point()?.id;
let transform = document.metadata().document_to_viewport * transform;
@@ -1029,7 +1031,9 @@ impl PenToolData {
let relative = if self.path_closed { None } else { self.latest_point().map(|point| point.pos) };
self.next_point = self.compute_snapped_angle(snap_data, transform, false, mouse, relative, true);
let layer = self.current_layer?;
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
let layer = selected_layers.next().filter(|_| selected_layers.next().is_none()).or(self.current_layer)?;
let vector_data = document.network_interface.compute_modified_vector(layer)?;
let transform = document.metadata().document_to_viewport * transform;
for point in vector_data.extendable_points(preferences.vector_meshes) {
@@ -1291,31 +1295,8 @@ impl PenToolData {
match (self.handle_type, self.path_closed) {
(TargetHandle::FuturePreviewOutHandle, _) | (TargetHandle::PreviewInHandle, true) => {
let is_start = |point: PointId, segment: SegmentId| vector_data.segment_start_from_id(segment) == Some(point);
let end_handle = ManipulatorPointId::EndHandle(segment).get_position(vector_data);
let start_handle = ManipulatorPointId::PrimaryHandle(segment).get_position(vector_data);
let start_point = if is_start(anchor, segment) {
vector_data.segment_end_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
} else {
vector_data.segment_start_from_id(segment).and_then(|id| vector_data.point_domain.position_from_id(id))
};
let required_handle = if is_start(anchor, segment) {
start_handle
.filter(|&handle| handle != anchor_position)
.or(end_handle.filter(|&handle| Some(handle) != start_point))
.or(start_point)
} else {
end_handle
.filter(|&handle| handle != anchor_position)
.or(start_handle.filter(|&handle| Some(handle) != start_point))
.or(start_point)
};
if let Some(required_handle) = required_handle {
self.angle = -(required_handle - anchor_position).angle_to(DVec2::X);
if let Some(required_handle) = calculate_segment_angle(anchor, segment, vector_data, true) {
self.angle = required_handle;
self.handle_mode = HandleMode::ColinearEquidistant;
}
}
@@ -1328,8 +1309,6 @@ impl PenToolData {
self.handle_mode = HandleMode::ColinearEquidistant;
}
}
// Closure to check if a point is the start or end of a segment
}
fn add_point_layer_position(&mut self, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>, layer: LayerNodeIdentifier, viewport: DVec2) {
@@ -1363,8 +1342,10 @@ impl Fsm for PenToolFsmState {
preferences,
..
} = tool_action_data;
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
let layer = selected_layers.next().filter(|_| selected_layers.next().is_none()).or(tool_data.current_layer);
let layer = tool_data.current_layer;
let mut transform = layer.map(|layer| document.metadata().transform_to_document(layer)).unwrap_or_default();
if !transform.inverse().is_finite() {
@@ -1608,6 +1589,54 @@ impl Fsm for PenToolFsmState {
overlay_context.manipulator_anchor(next_anchor, false, None);
}
// Display a filled overlay of the shape if the new point closes the path
if let Some(latest_point) = tool_data.latest_point() {
let handle_start = latest_point.handle_start;
let handle_end = tool_data.handle_end.unwrap_or(tool_data.next_handle_start);
let next_point = tool_data.next_point;
let start = latest_point.id;
if let Some(layer) = layer {
let mut vector_data = document.network_interface.compute_modified_vector(layer).unwrap();
let closest_point = vector_data.extendable_points(preferences.vector_meshes).filter(|&id| id != start).find(|&id| {
vector_data.point_domain.position_from_id(id).map_or(false, |pos| {
let dist_sq = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point));
dist_sq < crate::consts::SNAP_POINT_TOLERANCE.powi(2)
})
});
// We have the point. Join the 2 vertices and check if any path is closed.
if let Some(end) = closest_point {
let segment_id = SegmentId::generate();
vector_data.push(segment_id, start, end, BezierHandles::Cubic { handle_start, handle_end }, StrokeId::ZERO);
let grouped_segments = vector_data.auto_join_paths();
let closed_paths = grouped_segments.iter().filter(|path| path.is_closed() && path.contains(segment_id));
let subpaths: Vec<_> = closed_paths
.filter_map(|path| {
let segments = path.edges.iter().filter_map(|edge| {
vector_data
.segment_domain
.iter()
.find(|(id, _, _, _)| id == &edge.id)
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
});
vector_data.subpath_from_segments_ignore_discontinuities(segments)
})
.collect();
let mut fill_color = graphene_std::Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
.unwrap()
.with_alpha(0.05)
.to_rgba_hex_srgb();
fill_color.insert(0, '#');
overlay_context.fill_path(subpaths.iter(), transform, fill_color.as_str());
}
}
}
// Draw the overlays that visualize current snapping
tool_data.snap_manager.draw_overlays(SnapData::new(document, input), &mut overlay_context);
@@ -1666,7 +1695,13 @@ impl Fsm for PenToolFsmState {
.descendants(document.metadata())
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]));
if let Some((other_layer, _, _)) = should_extend(document, viewport, crate::consts::SNAP_POINT_TOLERANCE, layers, preferences) {
if let Some(current_layer) = tool_data.current_layer.filter(|layer| *layer != other_layer) {
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
if let Some(current_layer) = selected_layers
.next()
.filter(|current_layer| selected_layers.next().is_none() && *current_layer != other_layer)
.or(tool_data.current_layer.filter(|layer| *layer != other_layer))
{
merge_layers(document, current_layer, other_layer, responses);
}
}
@@ -1947,17 +1982,6 @@ impl Fsm for PenToolFsmState {
PenToolFsmState::Ready
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::Confirm) => {
if let Some((vector_data, layer)) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)).zip(layer) {
let single_point_in_layer = vector_data.point_domain.ids().len() == 1;
if single_point_in_layer {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: vec![layer.to_node()],
delete_children: true,
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
responses.add(DocumentMessage::EndTransaction);
tool_data.cleanup(responses);
tool_data.cleanup_target_selections(shape_editor, layer, document, responses);
@@ -1965,8 +1989,8 @@ impl Fsm for PenToolFsmState {
PenToolFsmState::Ready
}
(PenToolFsmState::DraggingHandle(..), PenToolMessage::Abort) => {
responses.add(DocumentMessage::AbortTransaction);
if tool_data.handle_end.is_none() {
responses.add(DocumentMessage::AbortTransaction);
tool_data.cleanup(responses);
tool_data.cleanup_target_selections(shape_editor, layer, document, responses);
@@ -1977,7 +2001,7 @@ impl Fsm for PenToolFsmState {
.unwrap_or(PenToolFsmState::Ready)
}
}
(_, PenToolMessage::Abort) => {
(PenToolFsmState::PlacingAnchor, PenToolMessage::Abort) => {
let should_delete_layer = if let Some(vector_data) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)) {
vector_data.point_domain.ids().len() == 1
} else {
@@ -1999,6 +2023,7 @@ impl Fsm for PenToolFsmState {
PenToolFsmState::Ready
}
(_, PenToolMessage::Abort) => PenToolFsmState::Ready,
(PenToolFsmState::DraggingHandle(..) | PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => {
if tool_data.point_index > 0 {
tool_data.point_index -= 1;
@@ -2,8 +2,8 @@
use super::tool_prelude::*;
use crate::consts::{
COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COMPASS_ROSE_HOVER_RING_DIAMETER, DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD, RESIZE_HANDLE_SIZE, ROTATE_INCREMENT, SELECTION_DRAG_ANGLE,
SELECTION_TOLERANCE,
COLOR_OVERLAY_BLUE, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COMPASS_ROSE_HOVER_RING_DIAMETER, DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD, RESIZE_HANDLE_SIZE, ROTATE_INCREMENT,
SELECTION_DRAG_ANGLE, SELECTION_TOLERANCE,
};
use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
@@ -28,6 +28,7 @@ use glam::DMat2;
use graph_craft::document::NodeId;
use graphene_core::renderer::Quad;
use graphene_std::renderer::Rect;
use graphene_std::transform::ReferencePoint;
use graphene_std::vector::misc::BooleanOperation;
use std::fmt;
@@ -96,7 +97,7 @@ pub enum SelectToolMessage {
PointerOutsideViewport(SelectToolPointerKeys),
SelectOptions(SelectOptionsUpdate),
SetPivot {
position: PivotPosition,
position: ReferencePoint,
},
}
@@ -129,9 +130,9 @@ impl SelectTool {
.widget_holder()
}
fn pivot_widget(&self, disabled: bool) -> WidgetHolder {
PivotInput::new(self.tool_data.pivot.to_pivot_position())
.on_update(|pivot_input: &PivotInput| SelectToolMessage::SetPivot { position: pivot_input.position }.into())
fn pivot_reference_point_widget(&self, disabled: bool) -> WidgetHolder {
ReferencePointInput::new(self.tool_data.pivot.to_pivot_position())
.on_update(|pivot_input: &ReferencePointInput| SelectToolMessage::SetPivot { position: pivot_input.value }.into())
.disabled(disabled)
.widget_holder()
}
@@ -204,7 +205,7 @@ impl LayoutHolder for SelectTool {
// Pivot
widgets.push(Separator::new(SeparatorType::Unrelated).widget_holder());
widgets.push(self.pivot_widget(self.tool_data.selected_layers_count == 0));
widgets.push(self.pivot_reference_point_widget(self.tool_data.selected_layers_count == 0));
// Align
let disabled = self.tool_data.selected_layers_count < 2;
@@ -759,7 +760,7 @@ impl Fsm for SelectToolFsmState {
}
// Update the selection box
let mut fill_color = graphene_std::Color::from_rgb_str(crate::consts::COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
let mut fill_color = graphene_std::Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
.unwrap()
.with_alpha(0.05)
.to_rgba_hex_srgb();
@@ -537,6 +537,7 @@ fn delete_preview(tool_data: &mut SplineToolData, responses: &mut VecDeque<Messa
#[cfg(test)]
mod test_spline_tool {
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::tool::tool_messages::spline_tool::find_spline;
use crate::test_utils::test_prelude::*;
use glam::DAffine2;
@@ -648,4 +649,199 @@ mod test_spline_tool {
assert_point_positions(&extended_vector_data, layer_to_viewport, &all_expected_points, 1e-10);
}
#[tokio::test]
async fn test_spline_with_zoomed_view() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Zooming the viewport
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 2.0 }).await;
// Selecting the spline tool
editor.select_tool(ToolType::Spline).await;
// Adding points by clicking at different positions
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(50.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(100.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(150.0, 100.0), ModifierKeys::empty()).await;
// Finish the spline
editor.handle_message(SplineToolMessage::Confirm).await;
// Evaluate the graph to ensure everything is processed
editor.eval_graph().await;
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
let layer = network_interface
.selected_nodes()
.selected_visible_and_unlocked_layers(network_interface)
.next()
.expect("Should have a selected layer");
let vector_data = network_interface.compute_modified_vector(layer).expect("Should have vector data");
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
// Expected points in viewport coordinates
let expected_points = vec![DVec2::new(50.0, 50.0), DVec2::new(100.0, 50.0), DVec2::new(150.0, 100.0)];
// Assert all points are correctly positioned
assert_point_positions(&vector_data, layer_to_viewport, &expected_points, 1e-10);
}
#[tokio::test]
async fn test_spline_with_panned_view() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let pan_amount = DVec2::new(200.0, 150.0);
editor.handle_message(NavigationMessage::CanvasPan { delta: pan_amount }).await;
editor.select_tool(ToolType::Spline).await;
// Add points by clicking at different positions
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(50.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(100.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(150.0, 100.0), ModifierKeys::empty()).await;
editor.handle_message(SplineToolMessage::Confirm).await;
// Evaluating the graph to ensure everything is processed
editor.eval_graph().await;
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
let layer = network_interface
.selected_nodes()
.selected_visible_and_unlocked_layers(network_interface)
.next()
.expect("Should have a selected layer");
let vector_data = network_interface.compute_modified_vector(layer).expect("Should have vector data");
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
// Expected points in viewport coordinates
let expected_points = vec![DVec2::new(50.0, 50.0), DVec2::new(100.0, 50.0), DVec2::new(150.0, 100.0)];
// Assert all points are correctly positioned
assert_point_positions(&vector_data, layer_to_viewport, &expected_points, 1e-10);
}
#[tokio::test]
async fn test_spline_with_tilted_view() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Tilt/rotate the viewport (45 degrees)
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 45.0_f64.to_radians() }).await;
editor.select_tool(ToolType::Spline).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(50.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(100.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(150.0, 100.0), ModifierKeys::empty()).await;
editor.handle_message(SplineToolMessage::Confirm).await;
// Evaluating the graph to ensure everything is processed
editor.eval_graph().await;
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
let layer = network_interface
.selected_nodes()
.selected_visible_and_unlocked_layers(network_interface)
.next()
.expect("Should have a selected layer");
let vector_data = network_interface.compute_modified_vector(layer).expect("Should have vector data");
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
// Expected points in viewport coordinates
let expected_points = vec![DVec2::new(50.0, 50.0), DVec2::new(100.0, 50.0), DVec2::new(150.0, 100.0)];
// Assert all points are correctly positioned
assert_point_positions(&vector_data, layer_to_viewport, &expected_points, 1e-10);
}
#[tokio::test]
async fn test_spline_with_combined_transformations() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Applying multiple transformations
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 1.5 }).await;
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(100.0, 75.0) }).await;
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 30.0_f64.to_radians() }).await;
editor.select_tool(ToolType::Spline).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(50.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(100.0, 50.0), ModifierKeys::empty()).await;
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(150.0, 100.0), ModifierKeys::empty()).await;
editor.handle_message(SplineToolMessage::Confirm).await;
editor.eval_graph().await;
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
let layer = network_interface
.selected_nodes()
.selected_visible_and_unlocked_layers(network_interface)
.next()
.expect("Should have a selected layer");
let vector_data = network_interface.compute_modified_vector(layer).expect("Should have vector data");
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
// Expected points in viewport coordinates
let expected_points = vec![DVec2::new(50.0, 50.0), DVec2::new(100.0, 50.0), DVec2::new(150.0, 100.0)];
// Assert all points are correctly positioned
assert_point_positions(&vector_data, layer_to_viewport, &expected_points, 1e-10);
}
#[tokio::test]
async fn test_spline_tool_with_transformed_artboard() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Artboard, 0., 0., 500., 500., ModifierKeys::empty()).await;
let document = editor.active_document();
let artboard_layer = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard_layer,
transform: DAffine2::from_scale_angle_translation(DVec2::new(1.5, 1.2), 30_f64.to_radians(), DVec2::new(50., 25.)),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
let spline_points = [DVec2::new(100., 100.), DVec2::new(200., 150.), DVec2::new(300., 100.)];
editor.draw_spline(&spline_points).await;
let document = editor.active_document();
let mut layers = document.metadata().all_layers();
layers.next();
let spline_layer = layers.next().expect("Failed to find the spline layer");
assert!(find_spline(document, spline_layer).is_some(), "Spline node not found in the layer");
let vector_data = document.network_interface.compute_modified_vector(spline_layer).expect("Vector data not found for the spline layer");
// Verify we have the correct number of points and segments
let point_count = vector_data.point_domain.ids().len();
let segment_count = vector_data.segment_domain.ids().len();
assert_eq!(point_count, 3, "Expected 3 points in the spline, found {}", point_count);
assert_eq!(segment_count, 2, "Expected 2 segments in the spline, found {}", segment_count);
let layer_to_viewport = document.metadata().transform_to_viewport(spline_layer);
assert_point_positions(&vector_data, layer_to_viewport, &spline_points, 1e-10);
}
}
@@ -1,7 +1,7 @@
#![allow(clippy::too_many_arguments)]
use super::tool_prelude::*;
use crate::consts::{COLOR_OVERLAY_RED, DRAG_THRESHOLD};
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_RED, DRAG_THRESHOLD};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -456,7 +456,7 @@ impl Fsm for TextToolFsmState {
font_cache,
..
} = transition_data;
let fill_color = graphene_std::Color::from_rgb_str(crate::consts::COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
let fill_color = graphene_std::Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap())
.unwrap()
.with_alpha(0.05)
.to_rgba_hex_srgb();
@@ -745,7 +745,7 @@ mod test_transform_layer {
editor.handle_message(TransformLayerMessage::BeginGrab).await;
let translation = DVec2::new(50.0, 50.0);
let translation = DVec2::new(50., 50.);
editor.move_mouse(translation.x, translation.y, ModifierKeys::empty(), MouseKeys::NONE).await;
editor
@@ -760,7 +760,7 @@ mod test_transform_layer {
let final_transform = get_layer_transform(&mut editor, layer).await.unwrap();
let translation_diff = (final_transform.translation - original_transform.translation).length();
assert!(translation_diff > 10.0, "Transform should have changed after applying transformation. Diff: {}", translation_diff);
assert!(translation_diff > 10., "Transform should have changed after applying transformation. Diff: {}", translation_diff);
}
#[tokio::test]
@@ -774,7 +774,7 @@ mod test_transform_layer {
let original_transform = get_layer_transform(&mut editor, layer).await.expect("Should be able to get the layer transform");
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(50.0, 50.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(50., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -794,7 +794,7 @@ mod test_transform_layer {
// Verify transform is either restored to original OR reset to identity
assert!(
(final_translation - original_translation).length() < 5.0 || final_translation.length() < 0.001,
(final_translation - original_translation).length() < 5. || final_translation.length() < 0.001,
"Transform neither restored to original nor reset to identity. Original: {:?}, Final: {:?}",
original_translation,
final_translation
@@ -814,7 +814,7 @@ mod test_transform_layer {
editor.handle_message(TransformLayerMessage::BeginRotate).await;
editor.move_mouse(150.0, 50.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(150., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
@@ -852,7 +852,7 @@ mod test_transform_layer {
assert!(!after_cancel.translation.y.is_nan(), "Transform is NaN after cancel");
let translation_diff = (after_cancel.translation - original_transform.translation).length();
assert!(translation_diff < 1.0, "Translation component changed too much: {}", translation_diff);
assert!(translation_diff < 1., "Translation component changed too much: {}", translation_diff);
}
#[tokio::test]
@@ -868,7 +868,7 @@ mod test_transform_layer {
editor.handle_message(TransformLayerMessage::BeginScale).await;
editor.move_mouse(150.0, 150.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(150., 150., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
@@ -918,7 +918,7 @@ mod test_transform_layer {
// Also check translation component is similar
let translation_diff = (after_cancel.translation - original_transform.translation).length();
assert!(translation_diff < 1.0, "Translation component changed too much: {}", translation_diff);
assert!(translation_diff < 1., "Translation component changed too much: {}", translation_diff);
}
#[tokio::test]
@@ -932,7 +932,7 @@ mod test_transform_layer {
let original_transform = get_layer_transform(&mut editor, layer).await.unwrap();
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(150.0, 130.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(150., 130., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -941,7 +941,7 @@ mod test_transform_layer {
.await;
let after_grab_transform = get_layer_transform(&mut editor, layer).await.unwrap();
let expected_translation = DVec2::new(50.0, 30.0);
let expected_translation = DVec2::new(50., 30.);
let actual_translation = after_grab_transform.translation - original_transform.translation;
assert!(
(actual_translation - expected_translation).length() < 1e-5,
@@ -952,7 +952,7 @@ mod test_transform_layer {
// 2. Chain to rotation - from current position to create ~45 degree rotation
editor.handle_message(TransformLayerMessage::BeginRotate).await;
editor.move_mouse(190.0, 90.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(190., 90., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -970,7 +970,7 @@ mod test_transform_layer {
// 3. Chain to scaling - scale(area) up by 2x
editor.handle_message(TransformLayerMessage::BeginScale).await;
editor.move_mouse(250.0, 200.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(250., 200., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -982,7 +982,7 @@ mod test_transform_layer {
let before_scale_det = after_rotate_transform.matrix2.determinant();
let after_scale_det = after_scale_transform.matrix2.determinant();
assert!(
after_scale_det >= 2.0 * before_scale_det,
after_scale_det >= 2. * before_scale_det,
"Scale should increase the determinant of the matrix (before: {}, after: {})",
before_scale_det,
after_scale_det
@@ -1005,7 +1005,7 @@ mod test_transform_layer {
let original_transform = get_layer_transform(&mut editor, layer).await.unwrap();
let pan_amount = DVec2::new(200.0, 150.0);
let pan_amount = DVec2::new(200., 150.);
editor.handle_message(NavigationMessage::CanvasPan { delta: pan_amount }).await;
editor.handle_message(TransformLayerMessage::BeginScale).await;
@@ -1017,8 +1017,8 @@ mod test_transform_layer {
let scale_x = final_transform.matrix2.x_axis.length() / original_transform.matrix2.x_axis.length();
let scale_y = final_transform.matrix2.y_axis.length() / original_transform.matrix2.y_axis.length();
assert!((scale_x - 2.0).abs() < 0.1, "Expected scale factor X of 2.0, got: {}", scale_x);
assert!((scale_y - 2.0).abs() < 0.1, "Expected scale factor Y of 2.0, got: {}", scale_y);
assert!((scale_x - 2.).abs() < 0.1, "Expected scale factor X of 2.0, got: {}", scale_x);
assert!((scale_y - 2.).abs() < 0.1, "Expected scale factor Y of 2.0, got: {}", scale_y);
}
#[tokio::test]
@@ -1043,8 +1043,8 @@ mod test_transform_layer {
let scale_x = final_transform.matrix2.x_axis.length() / original_transform.matrix2.x_axis.length();
let scale_y = final_transform.matrix2.y_axis.length() / original_transform.matrix2.y_axis.length();
assert!((scale_x - 2.0).abs() < 0.1, "Expected scale factor X of 2.0, got: {}", scale_x);
assert!((scale_y - 2.0).abs() < 0.1, "Expected scale factor Y of 2.0, got: {}", scale_y);
assert!((scale_x - 2.).abs() < 0.1, "Expected scale factor X of 2.0, got: {}", scale_x);
assert!((scale_y - 2.).abs() < 0.1, "Expected scale factor Y of 2.0, got: {}", scale_y);
}
#[tokio::test]
@@ -1059,7 +1059,11 @@ mod test_transform_layer {
// Rotate the document view (45 degrees)
editor.handle_message(NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu: false }).await;
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 45.0_f64.to_radians() }).await;
editor
.handle_message(NavigationMessage::CanvasTiltSet {
angle_radians: (45. as f64).to_radians(),
})
.await;
editor.handle_message(TransformLayerMessage::BeginRotate).await;
editor.handle_message(TransformLayerMessage::TypeDigit { digit: 9 }).await;
@@ -1073,8 +1077,8 @@ mod test_transform_layer {
let angle_change = (final_angle - original_angle).to_degrees();
// Normalize angle between 0 and 360
let angle_change = ((angle_change % 360.0) + 360.0) % 360.0;
assert!((angle_change - 90.0).abs() < 0.1, "Expected rotation of 90 degrees, got: {}", angle_change);
let angle_change = ((angle_change % 360.) + 360.) % 360.;
assert!((angle_change - 90.).abs() < 0.1, "Expected rotation of 90 degrees, got: {}", angle_change);
}
#[tokio::test]
@@ -1088,14 +1092,14 @@ mod test_transform_layer {
let point_id = PointId::generate();
let modification_type = VectorModificationType::InsertPoint {
id: point_id,
position: DVec2::new(100.0, 100.0),
position: DVec2::new(100., 100.),
};
editor.handle_message(GraphOperationMessage::Vector { layer, modification_type }).await;
editor.handle_message(ToolMessage::ActivateTool { tool_type: ToolType::Select }).await;
// Testing grab operation - just checking that it doesn't crash.
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(150.0, 150.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(150., 150., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -1131,8 +1135,8 @@ mod test_transform_layer {
let scale_y = near_zero_transform.matrix2.y_axis.length();
assert!(scale_x < 0.001, "Scale factor X should be near zero, got: {}", scale_x);
assert!(scale_y < 0.001, "Scale factor Y should be near zero, got: {}", scale_y);
assert!(scale_x > 0.0, "Scale factor X should not be exactly zero");
assert!(scale_y > 0.0, "Scale factor Y should not be exactly zero");
assert!(scale_x > 0., "Scale factor X should not be exactly zero");
assert!(scale_y > 0., "Scale factor Y should not be exactly zero");
editor.handle_message(TransformLayerMessage::BeginScale).await;
editor.handle_message(TransformLayerMessage::TypeDigit { digit: 2 }).await;
@@ -1143,8 +1147,8 @@ mod test_transform_layer {
let new_scale_x = final_transform.matrix2.x_axis.length();
let new_scale_y = final_transform.matrix2.y_axis.length();
assert!(new_scale_x > 0.0, "After rescaling, scale factor X should be non-zero");
assert!(new_scale_y > 0.0, "After rescaling, scale factor Y should be non-zero");
assert!(new_scale_x > 0., "After rescaling, scale factor X should be non-zero");
assert!(new_scale_y > 0., "After rescaling, scale factor Y should be non-zero");
}
#[tokio::test]
@@ -1180,7 +1184,7 @@ mod test_transform_layer {
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layers[0].to_node()] }).await;
let original_transform = get_layer_transform(&mut editor, layers[0]).await.unwrap();
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(50.0, 50.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(50., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -1200,7 +1204,7 @@ mod test_transform_layer {
let original_transform_1 = get_layer_transform(&mut editor, layers[0]).await.unwrap();
let original_transform_2 = get_layer_transform(&mut editor, layers[1]).await.unwrap();
editor.handle_message(TransformLayerMessage::BeginRotate).await;
editor.move_mouse(200.0, 50.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(200., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
@@ -1244,7 +1248,7 @@ mod test_transform_layer {
.await;
let original_child_transform = get_layer_transform(&mut editor, child_layer_id).await.unwrap();
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(30.0, 30.0, ModifierKeys::empty(), MouseKeys::NONE).await;
editor.move_mouse(30., 30., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
+3 -3
View File
@@ -293,9 +293,9 @@ impl NodeRuntime {
Self::process_graphic_element(&mut self.thumbnail_renders, parent_network_node_id, &io.output, responses, update_thumbnails)
// Insert the vector modify if we are dealing with vector data
} else if let Some(record) = introspected_data.downcast_ref::<IORecord<Context, VectorDataTable>>() {
self.vector_modify.insert(parent_network_node_id, record.output.one_instance().instance.clone());
self.vector_modify.insert(parent_network_node_id, record.output.one_instance_ref().instance.clone());
} else {
log::warn!("failed to downcast monitor node output");
log::warn!("failed to downcast monitor node output {parent_network_node_id:?}");
}
}
}
@@ -315,7 +315,7 @@ impl NodeRuntime {
return;
}
let bounds = graphic_element.bounding_box(DAffine2::IDENTITY);
let bounds = graphic_element.bounding_box(DAffine2::IDENTITY, true);
// Render the thumbnail from a `GraphicElement` into an SVG string
let render_params = RenderParams::new(ViewMode::Normal, bounds, true, false, false);
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<path d="M8,15C5.12471,9.753694 0.5,8.795225 0.5,4.736524 C0.5,-0.507473 7.468734,0 8,4.967381 C8.531266,0 15.5,-0.507473 15.5,4.736524 C15.5,8.795225 10.87529,9.753694 8,15z" fill="#dc6a7d" />
</svg>

After

Width:  |  Height:  |  Size: 263 B

+18 -16
View File
@@ -7,7 +7,7 @@
"name": "graphite-web-frontend",
"license": "Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.2.0",
"@rollup/rollup-win32-x64-msvc": "^4.40.1",
"class-transformer": "^0.5.1",
"idb-keyval": "^6.2.1",
"reflect-metadata": "^0.2.2"
@@ -989,15 +989,13 @@
]
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.34.9",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.9.tgz",
"integrity": "sha512-AyleYRPU7+rgkMWbEh71fQlrzRfeP6SyMnRf9XX4fCdDPAJumdSBqYEcWPMzVQ4ScAl7E4oFfK0GUVn77xSwbw==",
"version": "4.40.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.40.1.tgz",
"integrity": "sha512-ECyOuDeH3C1I8jH2MK1RtBJW+YPMvSfT0a5NN0nHfQYnDSJ6tUiZH3gzwVP5/Kfh/+Tt7tpWVF9LXNTnhTJ3kA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
@@ -1050,16 +1048,6 @@
"vite": "^5.0.0"
}
},
"node_modules/@tauri-apps/api": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.2.0.tgz",
"integrity": "sha512-R8epOeZl1eJEl603aUMIGb4RXlhPjpgxbGVEaqY+0G5JG9vzV/clNlzTeqc+NLYXVqXcn8mb4c5b9pJIUDEyAg==",
"license": "Apache-2.0 OR MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
@@ -4668,6 +4656,20 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/rollup/node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.34.9",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.9.tgz",
"integrity": "sha512-AyleYRPU7+rgkMWbEh71fQlrzRfeP6SyMnRf9XX4fCdDPAJumdSBqYEcWPMzVQ4ScAl7E4oFfK0GUVn77xSwbw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
+1
View File
@@ -29,6 +29,7 @@
"wasm:watch-production": "cargo watch --postpone --watch-when-idle --workdir=wasm --shell \"wasm-pack build . --release --target=web -- --color=always\""
},
"dependencies": {
"@rollup/rollup-win32-x64-msvc": "^4.40.1",
"class-transformer": "^0.5.1",
"idb-keyval": "^6.2.1",
"reflect-metadata": "^0.2.2"
+8 -8
View File
@@ -105,18 +105,18 @@
--color-error-red: #d6536e;
--color-error-red-rgb: 214, 83, 110;
--color-data-general: #c5c5c5;
--color-data-general-dim: #767676;
--color-data-general: #cfcfcf;
--color-data-general-dim: #8a8a8a;
--color-data-raster: #e4bb72;
--color-data-raster-dim: #8b7752;
--color-data-vectordata: #65bbe5;
--color-data-vectordata-dim: #4b778c;
--color-data-number: #cbbab4;
--color-data-number-dim: #87736b;
--color-data-group: #6b84e8;
--color-data-group-dim: #4a557b;
--color-data-artboard: #70a898;
--color-data-artboard-dim: #3a6156;
--color-data-group: #66b195;
--color-data-group-dim: #3d725e;
--color-data-artboard: #fbf9eb;
--color-data-artboard-dim: #b9b9a9;
--color-data-number: #c9a699;
--color-data-number-dim: #886b60;
--color-none: white;
--color-none-repeat: no-repeat;
+2 -2
View File
@@ -207,7 +207,7 @@
const LINE_WIDTH = 2;
// Calculate coordinates for input and output connectors
const inX = verticalIn ? inputBounds.x + inputBounds.width / 2 : inputBounds.x + 1;
const inX = verticalIn ? inputBounds.x + inputBounds.width / 2 : inputBounds.x;
const inY = verticalIn ? inputBounds.y + inputBounds.height - VERTICAL_WIRE_OVERLAP_ON_SHAPED_CAP : inputBounds.y + inputBounds.height / 2;
const outX = verticalOut ? outputBounds.x + outputBounds.width / 2 : outputBounds.x + outputBounds.width - 1;
const outY = verticalOut ? outputBounds.y + VERTICAL_WIRE_OVERLAP_ON_SHAPED_CAP : outputBounds.y + outputBounds.height / 2;
@@ -475,7 +475,7 @@
const outConnectorX = (outX - containerBounds.x) / $nodeGraph.transform.scale;
const outConnectorY = (outY - containerBounds.y) / $nodeGraph.transform.scale;
const inX = verticalIn ? inputBounds.x + inputBounds.width / 2 : inputBounds.x + 1;
const inX = verticalIn ? inputBounds.x + inputBounds.width / 2 : inputBounds.x;
const inY = verticalIn ? inputBounds.y + inputBounds.height - VERTICAL_WIRE_OVERLAP_ON_SHAPED_CAP : inputBounds.y + inputBounds.height / 2;
const inConnectorX = (inX - containerBounds.x) / $nodeGraph.transform.scale;
const inConnectorY = (inY - containerBounds.y) / $nodeGraph.transform.scale;
@@ -19,8 +19,8 @@
import DropdownInput from "@graphite/components/widgets/inputs/DropdownInput.svelte";
import FontInput from "@graphite/components/widgets/inputs/FontInput.svelte";
import NumberInput from "@graphite/components/widgets/inputs/NumberInput.svelte";
import PivotInput from "@graphite/components/widgets/inputs/PivotInput.svelte";
import RadioInput from "@graphite/components/widgets/inputs/RadioInput.svelte";
import ReferencePointInput from "@graphite/components/widgets/inputs/ReferencePointInput.svelte";
import TextAreaInput from "@graphite/components/widgets/inputs/TextAreaInput.svelte";
import TextInput from "@graphite/components/widgets/inputs/TextInput.svelte";
import WorkingColorsInput from "@graphite/components/widgets/inputs/WorkingColorsInput.svelte";
@@ -142,9 +142,9 @@
incrementCallbackDecrease={() => widgetValueCommitAndUpdate(index, "Decrement")}
/>
{/if}
{@const pivotInput = narrowWidgetProps(component.props, "PivotInput")}
{#if pivotInput}
<PivotInput {...exclude(pivotInput)} on:position={({ detail }) => widgetValueCommitAndUpdate(index, detail)} />
{@const referencePointInput = narrowWidgetProps(component.props, "ReferencePointInput")}
{#if referencePointInput}
<ReferencePointInput {...exclude(referencePointInput)} on:value={({ detail }) => widgetValueCommitAndUpdate(index, detail)} />
{/if}
{@const popoverButton = narrowWidgetProps(component.props, "PopoverButton")}
{#if popoverButton}
@@ -1,115 +0,0 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { PivotPosition } from "@graphite/messages";
const dispatch = createEventDispatcher<{ position: PivotPosition }>();
export let position: string;
export let disabled = false;
function setPosition(newPosition: PivotPosition) {
dispatch("position", newPosition);
}
</script>
<div class="pivot-input" class:disabled>
<button on:click={() => setPosition("TopLeft")} class="row-1 col-1" class:active={position === "TopLeft"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("TopCenter")} class="row-1 col-2" class:active={position === "TopCenter"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("TopRight")} class="row-1 col-3" class:active={position === "TopRight"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("CenterLeft")} class="row-2 col-1" class:active={position === "CenterLeft"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("Center")} class="row-2 col-2" class:active={position === "Center"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("CenterRight")} class="row-2 col-3" class:active={position === "CenterRight"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("BottomLeft")} class="row-3 col-1" class:active={position === "BottomLeft"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("BottomCenter")} class="row-3 col-2" class:active={position === "BottomCenter"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setPosition("BottomRight")} class="row-3 col-3" class:active={position === "BottomRight"} tabindex="-1" {disabled}><div /></button>
</div>
<style lang="scss" global>
.pivot-input {
position: relative;
flex: 0 0 auto;
width: 24px;
height: 24px;
--pivot-border-color: var(--color-5-dullgray);
--pivot-fill-active: var(--color-e-nearwhite);
button {
position: absolute;
width: 5px;
height: 5px;
margin: 0;
padding: 0;
background: var(--color-1-nearblack);
border: 1px solid var(--pivot-border-color);
&.active {
border-color: transparent;
background: var(--pivot-fill-active);
}
&.col-1::before,
&.col-2::before {
content: "";
pointer-events: none;
width: 2px;
height: 0;
border-top: 1px solid var(--pivot-border-color);
position: absolute;
top: 1px;
right: -3px;
}
&.row-1::after,
&.row-2::after {
content: "";
pointer-events: none;
width: 0;
height: 2px;
border-left: 1px solid var(--pivot-border-color);
position: absolute;
bottom: -3px;
right: 1px;
}
&.row-1 {
top: 3px;
}
&.col-1 {
left: 3px;
}
&.row-2 {
top: 10px;
}
&.col-2 {
left: 10px;
}
&.row-3 {
top: 17px;
}
&.col-3 {
left: 17px;
}
// Click targets that extend 1px beyond the borders of each square
div {
width: 100%;
height: 100%;
padding: 2px;
margin: -2px;
}
}
&:not(.disabled) button:not(.active):hover {
border-color: transparent;
background: var(--color-6-lowergray);
}
&.disabled button {
--pivot-border-color: var(--color-4-dimgray);
--pivot-fill-active: var(--color-8-uppergray);
}
}
</style>
@@ -0,0 +1,115 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ReferencePoint } from "@graphite/messages";
const dispatch = createEventDispatcher<{ value: ReferencePoint }>();
export let value: string;
export let disabled = false;
function setValue(newValue: ReferencePoint) {
dispatch("value", newValue);
}
</script>
<div class="reference-point-input" class:disabled>
<button on:click={() => setValue("TopLeft")} class="row-1 col-1" class:active={value === "TopLeft"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("TopCenter")} class="row-1 col-2" class:active={value === "TopCenter"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("TopRight")} class="row-1 col-3" class:active={value === "TopRight"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("CenterLeft")} class="row-2 col-1" class:active={value === "CenterLeft"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("Center")} class="row-2 col-2" class:active={value === "Center"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("CenterRight")} class="row-2 col-3" class:active={value === "CenterRight"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("BottomLeft")} class="row-3 col-1" class:active={value === "BottomLeft"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("BottomCenter")} class="row-3 col-2" class:active={value === "BottomCenter"} tabindex="-1" {disabled}><div /></button>
<button on:click={() => setValue("BottomRight")} class="row-3 col-3" class:active={value === "BottomRight"} tabindex="-1" {disabled}><div /></button>
</div>
<style lang="scss" global>
.reference-point-input {
position: relative;
flex: 0 0 auto;
width: 24px;
height: 24px;
--reference-point-border-color: var(--color-5-dullgray);
--reference-point-fill-active: var(--color-e-nearwhite);
button {
position: absolute;
width: 5px;
height: 5px;
margin: 0;
padding: 0;
background: var(--color-1-nearblack);
border: 1px solid var(--reference-point-border-color);
&.active {
border-color: transparent;
background: var(--reference-point-fill-active);
}
&.col-1::before,
&.col-2::before {
content: "";
pointer-events: none;
width: 2px;
height: 0;
border-top: 1px solid var(--reference-point-border-color);
position: absolute;
top: 1px;
right: -3px;
}
&.row-1::after,
&.row-2::after {
content: "";
pointer-events: none;
width: 0;
height: 2px;
border-left: 1px solid var(--reference-point-border-color);
position: absolute;
bottom: -3px;
right: 1px;
}
&.row-1 {
top: 3px;
}
&.col-1 {
left: 3px;
}
&.row-2 {
top: 10px;
}
&.col-2 {
left: 10px;
}
&.row-3 {
top: 17px;
}
&.col-3 {
left: 17px;
}
// Click targets that extend 1px beyond the borders of each square
div {
width: 100%;
height: 100%;
padding: 2px;
margin: -2px;
}
}
&:not(.disabled) button:not(.active):hover {
border-color: transparent;
background: var(--color-6-lowergray);
}
&.disabled button {
--reference-point-border-color: var(--color-4-dimgray);
--reference-point-fill-active: var(--color-8-uppergray);
}
}
</style>
@@ -172,6 +172,11 @@
<TextButton label="Open Demo Artwork" icon="Image" flush={true} action={() => editor.handle.demoArtworkDialog()} />
</td>
</tr>
<tr>
<td colspan="2">
<TextButton label="Support the Development Fund" icon="Heart" flush={true} action={() => editor.handle.visitUrl("https://graphite.rs/donate/")} />
</td>
</tr>
</table>
</LayoutRow>
</LayoutCol>
+4 -4
View File
@@ -1350,10 +1350,10 @@ export class TextLabel extends WidgetProps {
tooltip!: string | undefined;
}
export type PivotPosition = "None" | "TopLeft" | "TopCenter" | "TopRight" | "CenterLeft" | "Center" | "CenterRight" | "BottomLeft" | "BottomCenter" | "BottomRight";
export type ReferencePoint = "None" | "TopLeft" | "TopCenter" | "TopRight" | "CenterLeft" | "Center" | "CenterRight" | "BottomLeft" | "BottomCenter" | "BottomRight";
export class PivotInput extends WidgetProps {
position!: PivotPosition;
export class ReferencePointInput extends WidgetProps {
value!: ReferencePoint;
disabled!: boolean;
}
@@ -1373,7 +1373,7 @@ const widgetSubTypes = [
{ value: NodeCatalog, name: "NodeCatalog" },
{ value: NumberInput, name: "NumberInput" },
{ value: ParameterExposeButton, name: "ParameterExposeButton" },
{ value: PivotInput, name: "PivotInput" },
{ value: ReferencePointInput, name: "ReferencePointInput" },
{ value: PopoverButton, name: "PopoverButton" },
{ value: RadioInput, name: "RadioInput" },
{ value: Separator, name: "Separator" },
+2
View File
@@ -137,6 +137,7 @@ import GraphiteLogo from "@graphite-frontend/assets/icon-16px-solid/graphite-log
import HandleVisibilityAll from "@graphite-frontend/assets/icon-16px-solid/handle-visibility-all.svg";
import HandleVisibilityFrontier from "@graphite-frontend/assets/icon-16px-solid/handle-visibility-frontier.svg";
import HandleVisibilitySelected from "@graphite-frontend/assets/icon-16px-solid/handle-visibility-selected.svg";
import Heart from "@graphite-frontend/assets/icon-16px-solid/heart.svg";
import HistoryRedo from "@graphite-frontend/assets/icon-16px-solid/history-redo.svg";
import HistoryUndo from "@graphite-frontend/assets/icon-16px-solid/history-undo.svg";
import IconsGrid from "@graphite-frontend/assets/icon-16px-solid/icons-grid.svg";
@@ -257,6 +258,7 @@ const SOLID_16PX = {
HandleVisibilityAll: { svg: HandleVisibilityAll, size: 16 },
HandleVisibilityFrontier: { svg: HandleVisibilityFrontier, size: 16 },
HandleVisibilitySelected: { svg: HandleVisibilitySelected, size: 16 },
Heart: { svg: Heart, size: 16 },
HistoryRedo: { svg: HistoryRedo, size: 16 },
HistoryUndo: { svg: HistoryUndo, size: 16 },
IconsGrid: { svg: IconsGrid, size: 16 },
+7
View File
@@ -490,6 +490,13 @@ impl EditorHandle {
Ok(())
}
/// Visit the given URL
#[wasm_bindgen(js_name = visitUrl)]
pub fn visit_url(&self, url: String) {
let message = FrontendMessage::TriggerVisitLink { url };
self.dispatch(message);
}
/// Paste layers from a serialized json representation
#[wasm_bindgen(js_name = pasteSerializedData)]
pub fn paste_serialized_data(&self, data: String) {
+2 -2
View File
@@ -77,8 +77,8 @@ impl Bezier {
pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 {
match t {
TValue::Parametric(t) => {
assert!((0.0..=1.).contains(&t));
t
// Clamp the t value to the valid range [0.0, 1.0]
t.clamp(0.0, 1.0)
}
TValue::Euclidean(t) => {
assert!((0.0..=1.).contains(&t));
+2 -1
View File
@@ -212,7 +212,8 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
(segment_index, t)
}
SubpathTValue::GlobalParametric(global_t) => {
assert!((0.0..=1.).contains(&global_t));
// Clamp global_t to the valid range [0, 1] instead of asserting
let global_t = global_t.clamp(0.0, 1.0);
if global_t == 1. {
return (self.len_segments() - 1, 1.);
+42 -48
View File
@@ -1,5 +1,5 @@
use crate::application_io::{ImageTexture, TextureFrameTable};
use crate::instances::Instances;
use crate::instances::{Instance, Instances};
use crate::raster::BlendMode;
use crate::raster::image::{Image, ImageFrameTable};
use crate::transform::TransformMut;
@@ -67,10 +67,12 @@ pub fn migrate_graphic_group<'de, D: serde::Deserializer<'de>>(deserializer: D)
EitherFormat::OldGraphicGroup(old) => {
let mut graphic_group_table = GraphicGroupTable::empty();
for (graphic_element, source_node_id) in old.elements {
let last = graphic_group_table.push(graphic_element);
*last.source_node_id = source_node_id;
*last.transform = old.transform;
*last.alpha_blending = old.alpha_blending;
graphic_group_table.push(Instance {
instance: graphic_element,
transform: old.transform,
alpha_blending: old.alpha_blending,
source_node_id,
});
}
graphic_group_table
}
@@ -78,12 +80,14 @@ pub fn migrate_graphic_group<'de, D: serde::Deserializer<'de>>(deserializer: D)
// Try to deserialize as either table format
if let Ok(old_table) = serde_json::from_value::<OldGraphicGroupTable>(value.clone()) {
let mut graphic_group_table = GraphicGroupTable::empty();
for instance in old_table.instances() {
for instance in old_table.instance_ref_iter() {
for (graphic_element, source_node_id) in &instance.instance.elements {
let new_row = graphic_group_table.push(graphic_element.clone());
*new_row.source_node_id = *source_node_id;
*new_row.transform = *instance.transform;
*new_row.alpha_blending = *instance.alpha_blending;
graphic_group_table.push(Instance {
instance: graphic_element.clone(),
transform: *instance.transform,
alpha_blending: *instance.alpha_blending,
source_node_id: *source_node_id,
});
}
}
graphic_group_table
@@ -276,8 +280,12 @@ pub fn migrate_artboard_group<'de, D: serde::Deserializer<'de>>(deserializer: D)
EitherFormat::ArtboardGroup(artboard_group) => {
let mut table = ArtboardGroupTable::empty();
for (artboard, source_node_id) in artboard_group.artboards {
let pushed = table.push(artboard);
*pushed.source_node_id = source_node_id;
table.push(Instance {
instance: artboard,
transform: DAffine2::IDENTITY,
alpha_blending: AlphaBlending::default(),
source_node_id,
});
}
table
}
@@ -290,38 +298,18 @@ pub type ArtboardGroupTable = Instances<Artboard>;
#[node_macro::node(category(""))]
async fn layer(_: impl Ctx, mut stack: GraphicGroupTable, element: GraphicElement, node_path: Vec<NodeId>) -> GraphicGroupTable {
// Get the penultimate element of the node path, or None if the path is too short
let pushed = stack.push(element);
*pushed.source_node_id = node_path.get(node_path.len().wrapping_sub(2)).copied();
let source_node_id = node_path.get(node_path.len().wrapping_sub(2)).copied();
stack.push(Instance {
instance: element,
transform: DAffine2::IDENTITY,
alpha_blending: AlphaBlending::default(),
source_node_id,
});
stack
}
// // TODO: Once we have nicely working spreadsheet tables, test this and make it nicely user-facing and move it from "Debug" to "General"
// #[node_macro::node(category("Debug"))]
// async fn concatenate<T: Clone>(
// _: impl Ctx,
// #[implementations(
// GraphicGroupTable,
// VectorDataTable,
// ImageFrameTable<Color>,
// TextureFrameTable,
// )]
// from: Instances<T>,
// #[expose]
// #[implementations(
// GraphicGroupTable,
// VectorDataTable,
// ImageFrameTable<Color>,
// TextureFrameTable,
// )]
// mut to: Instances<T>,
// ) -> Instances<T> {
// for instance in from.instances() {
// to.push_instance(instance);
// }
// to
// }
#[node_macro::node(category("Debug"))]
async fn to_element<Data: Into<GraphicElement> + 'n>(
_: impl Ctx,
@@ -354,7 +342,7 @@ async fn to_group<Data: Into<GraphicGroupTable> + 'n>(
async fn flatten_group(_: impl Ctx, group: GraphicGroupTable, fully_flatten: bool) -> GraphicGroupTable {
// TODO: Avoid mutable reference, instead return a new GraphicGroupTable?
fn flatten_group(output_group_table: &mut GraphicGroupTable, current_group_table: GraphicGroupTable, fully_flatten: bool, recursion_depth: usize) {
for current_instance in current_group_table.instances() {
for current_instance in current_group_table.instance_ref_iter() {
let current_element = current_instance.instance.clone();
let reference = *current_instance.source_node_id;
@@ -364,7 +352,7 @@ async fn flatten_group(_: impl Ctx, group: GraphicGroupTable, fully_flatten: boo
// If we're allowed to recurse, flatten any GraphicGroups we encounter
GraphicElement::GraphicGroup(mut current_element) if recurse => {
// Apply the parent group's transform to all child elements
for graphic_element in current_element.instances_mut() {
for graphic_element in current_element.instance_mut_iter() {
*graphic_element.transform = *current_instance.transform * *graphic_element.transform;
}
@@ -372,10 +360,12 @@ async fn flatten_group(_: impl Ctx, group: GraphicGroupTable, fully_flatten: boo
}
// Handle any leaf elements we encounter, which can be either non-GraphicGroup elements or GraphicGroups that we don't want to flatten
_ => {
let pushed = output_group_table.push(current_element);
*pushed.source_node_id = reference;
// Apply the parent group's transform to the leaf element
*pushed.transform = *current_instance.transform * *pushed.transform;
output_group_table.push(Instance {
instance: current_element,
transform: *current_instance.transform,
alpha_blending: *current_instance.alpha_blending,
source_node_id: reference,
});
}
}
}
@@ -427,8 +417,12 @@ async fn append_artboard(_ctx: impl Ctx, mut artboards: ArtboardGroupTable, artb
// This is used to get the ID of the user-facing "Artboard" node (which encapsulates this internal "Append Artboard" node).
let encapsulating_node_id = node_path.get(node_path.len().wrapping_sub(2)).copied();
let pushed = artboards.push(artboard);
*pushed.source_node_id = encapsulating_node_id;
artboards.push(Instance {
instance: artboard,
transform: DAffine2::IDENTITY,
alpha_blending: AlphaBlending::default(),
source_node_id: encapsulating_node_id,
});
artboards
}
@@ -275,7 +275,7 @@ pub trait GraphicElementRendered {
#[cfg(feature = "vello")]
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, _render_params: &RenderParams);
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]>;
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]>;
// The upstream click targets for each layer are collected during the render so that they do not have to be calculated for each click detection
fn add_upstream_click_targets(&self, _click_targets: &mut Vec<ClickTarget>) {}
@@ -299,7 +299,7 @@ pub trait GraphicElementRendered {
impl GraphicElementRendered for GraphicGroupTable {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
render.parent_tag(
"g",
|attributes| {
@@ -325,12 +325,16 @@ impl GraphicElementRendered for GraphicGroupTable {
#[cfg(feature = "vello")]
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let transform = transform * *instance.transform;
let alpha_blending = *instance.alpha_blending;
let mut layer = false;
if let Some(bounds) = self.instances().filter_map(|element| element.instance.bounding_box(transform)).reduce(Quad::combine_bounds) {
if let Some(bounds) = self
.instance_ref_iter()
.filter_map(|element| element.instance.bounding_box(transform, true))
.reduce(Quad::combine_bounds)
{
let blend_mode = match render_params.view_mode {
ViewMode::Outline => peniko::Mix::Normal,
_ => alpha_blending.blend_mode.into(),
@@ -355,14 +359,14 @@ impl GraphicElementRendered for GraphicGroupTable {
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
self.instances()
.filter_map(|element| element.instance.bounding_box(transform * *element.transform))
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]> {
self.instance_ref_iter()
.filter_map(|element| element.instance.bounding_box(transform * *element.transform, include_stroke))
.reduce(Quad::combine_bounds)
}
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
if let Some(element_id) = instance.source_node_id {
let mut footprint = footprint;
footprint.transform *= *instance.transform;
@@ -374,7 +378,7 @@ impl GraphicElementRendered for GraphicGroupTable {
if let Some(graphic_group_id) = element_id {
let mut all_upstream_click_targets = Vec::new();
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let mut new_click_targets = Vec::new();
instance.instance.add_upstream_click_targets(&mut new_click_targets);
@@ -390,7 +394,7 @@ impl GraphicElementRendered for GraphicGroupTable {
}
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let mut new_click_targets = Vec::new();
instance.instance.add_upstream_click_targets(&mut new_click_targets);
@@ -404,11 +408,11 @@ impl GraphicElementRendered for GraphicGroupTable {
}
fn contains_artboard(&self) -> bool {
self.instances().any(|instance| instance.instance.contains_artboard())
self.instance_ref_iter().any(|instance| instance.instance.contains_artboard())
}
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.instance.new_ids_from_hash(*instance.source_node_id);
}
}
@@ -420,7 +424,7 @@ impl GraphicElementRendered for GraphicGroupTable {
impl GraphicElementRendered for VectorDataTable {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let multiplied_transform = render.transform * *instance.transform;
// Only consider strokes with non-zero weight, since default strokes with zero weight would prevent assigning the correct stroke transform
let has_real_stroke = instance.instance.style.stroke().filter(|stroke| stroke.weight() > 0.);
@@ -469,7 +473,7 @@ impl GraphicElementRendered for VectorDataTable {
use vello::kurbo::{Cap, Join};
use vello::peniko;
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let multiplied_transform = parent_transform * *instance.transform;
let has_real_stroke = instance.instance.style.stroke().filter(|stroke| stroke.weight() > 0.);
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform.matrix2.determinant() != 0.);
@@ -613,9 +617,13 @@ impl GraphicElementRendered for VectorDataTable {
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
self.instances()
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]> {
self.instance_ref_iter()
.flat_map(|instance| {
if !include_stroke {
return instance.instance.bounding_box_with_transform(transform * *instance.transform);
}
let stroke_width = instance.instance.style.stroke().map(|s| s.weight()).unwrap_or_default();
let miter_limit = instance.instance.style.stroke().map(|s| s.line_join_miter_limit).unwrap_or(1.);
@@ -633,7 +641,7 @@ impl GraphicElementRendered for VectorDataTable {
fn collect_metadata(&self, metadata: &mut RenderMetadata, mut footprint: Footprint, element_id: Option<NodeId>) {
let instance_transform = self.transform();
for instance in self.instances().map(|instance| instance.instance) {
for instance in self.instance_ref_iter().map(|instance| instance.instance) {
if let Some(element_id) = element_id {
let stroke_width = instance.style.stroke().as_ref().map_or(0., Stroke::weight);
let filled = instance.style.fill() != &Fill::None;
@@ -661,7 +669,7 @@ impl GraphicElementRendered for VectorDataTable {
}
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let stroke_width = instance.instance.style.stroke().as_ref().map_or(0., Stroke::weight);
let filled = instance.instance.style.fill() != &Fill::None;
let fill = |mut subpath: bezier_rs::Subpath<_>| {
@@ -679,7 +687,7 @@ impl GraphicElementRendered for VectorDataTable {
}
fn new_ids_from_hash(&mut self, reference: Option<NodeId>) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.instance.vector_new_ids_from_hash(reference.map(|id| id.0).unwrap_or_default());
}
}
@@ -761,12 +769,15 @@ impl GraphicElementRendered for Artboard {
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]> {
let artboard_bounds = (transform * Quad::from_box([self.location.as_dvec2(), self.location.as_dvec2() + self.dimensions.as_dvec2()])).bounding_box();
if self.clip {
Some(artboard_bounds)
} else {
[self.graphic_group.bounding_box(transform), Some(artboard_bounds)].into_iter().flatten().reduce(Quad::combine_bounds)
[self.graphic_group.bounding_box(transform, include_stroke), Some(artboard_bounds)]
.into_iter()
.flatten()
.reduce(Quad::combine_bounds)
}
}
@@ -796,42 +807,44 @@ impl GraphicElementRendered for Artboard {
impl GraphicElementRendered for ArtboardGroupTable {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
for artboard in self.instances() {
for artboard in self.instance_ref_iter() {
artboard.instance.render_svg(render, render_params);
}
}
#[cfg(feature = "vello")]
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
instance.instance.render_to_vello(scene, transform, context, render_params);
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
self.instances().filter_map(|instance| instance.instance.bounding_box(transform)).reduce(Quad::combine_bounds)
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]> {
self.instance_ref_iter()
.filter_map(|instance| instance.instance.bounding_box(transform, include_stroke))
.reduce(Quad::combine_bounds)
}
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, _element_id: Option<NodeId>) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
instance.instance.collect_metadata(metadata, footprint, *instance.source_node_id);
}
}
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
instance.instance.add_upstream_click_targets(click_targets);
}
}
fn contains_artboard(&self) -> bool {
self.instances().count() > 0
self.instance_ref_iter().count() > 0
}
}
impl GraphicElementRendered for ImageFrameTable<Color> {
fn render_svg(&self, render: &mut SvgRender, _render_params: &RenderParams) {
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let transform = *instance.transform * render.transform;
let image = &instance.instance;
@@ -870,7 +883,7 @@ impl GraphicElementRendered for ImageFrameTable<Color> {
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, _: &mut RenderContext, _render_params: &RenderParams) {
use vello::peniko;
for instance in self.instances() {
for instance in self.instance_ref_iter() {
let image = &instance.instance;
if image.data.is_empty() {
return;
@@ -882,8 +895,8 @@ impl GraphicElementRendered for ImageFrameTable<Color> {
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
self.instances()
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> Option<[DVec2; 2]> {
self.instance_ref_iter()
.flat_map(|instance| {
let transform = transform * *instance.transform;
(transform.matrix2.determinant() != 0.).then(|| (transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box())
@@ -924,7 +937,7 @@ impl GraphicElementRendered for RasterFrame {
let image_transform = transform * self.transform() * DAffine2::from_scale(1. / DVec2::new(image.width as f64, image.height as f64));
let layer = blend_mode != Default::default();
let Some(bounds) = self.bounding_box(transform) else { return };
let Some(bounds) = self.bounding_box(transform, true) else { return };
let blending = vello::peniko::BlendMode::new(blend_mode.blend_mode.into(), vello::peniko::Compose::SrcOver);
if layer {
@@ -939,7 +952,7 @@ impl GraphicElementRendered for RasterFrame {
match self {
RasterFrame::ImageFrame(image) => {
for instance in image.instances() {
for instance in image.instance_ref_iter() {
let image = &instance.instance;
if image.data.is_empty() {
return;
@@ -951,7 +964,7 @@ impl GraphicElementRendered for RasterFrame {
}
}
RasterFrame::TextureFrame(image_texture) => {
for instance in image_texture.instances() {
for instance in image_texture.instance_ref_iter() {
let image =
vello::peniko::Image::new(vec![].into(), peniko::Format::Rgba8, instance.instance.texture.width(), instance.instance.texture.height()).with_extend(peniko::Extend::Repeat);
@@ -964,7 +977,7 @@ impl GraphicElementRendered for RasterFrame {
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> Option<[DVec2; 2]> {
let transform = transform * self.transform();
(transform.matrix2.determinant() != 0.).then(|| (transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box())
}
@@ -1002,11 +1015,11 @@ impl GraphicElementRendered for GraphicElement {
}
}
fn bounding_box(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]> {
match self {
GraphicElement::VectorData(vector_data) => vector_data.bounding_box(transform),
GraphicElement::RasterFrame(raster) => raster.bounding_box(transform),
GraphicElement::GraphicGroup(graphic_group) => graphic_group.bounding_box(transform),
GraphicElement::VectorData(vector_data) => vector_data.bounding_box(transform, include_stroke),
GraphicElement::RasterFrame(raster) => raster.bounding_box(transform, include_stroke),
GraphicElement::GraphicGroup(graphic_group) => graphic_group.bounding_box(transform, include_stroke),
}
}
@@ -1078,7 +1091,7 @@ impl<P: Primitive> GraphicElementRendered for P {
render.parent_tag("text", text_attributes, |render| render.leaf_node(format!("{self}")));
}
fn bounding_box(&self, _transform: DAffine2) -> Option<[DVec2; 2]> {
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> Option<[DVec2; 2]> {
None
}
@@ -1106,7 +1119,7 @@ impl GraphicElementRendered for Option<Color> {
render.parent_tag("text", text_attributes, |render| render.leaf_node(color_info))
}
fn bounding_box(&self, _transform: DAffine2) -> Option<[DVec2; 2]> {
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> Option<[DVec2; 2]> {
None
}
@@ -1130,7 +1143,7 @@ impl GraphicElementRendered for Vec<Color> {
}
}
fn bounding_box(&self, _transform: DAffine2) -> Option<[DVec2; 2]> {
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> Option<[DVec2; 2]> {
None
}
+56 -43
View File
@@ -40,39 +40,15 @@ impl<T> Instances<T> {
}
}
pub fn push(&mut self, instance: T) -> InstanceMut<T> {
self.instance.push(instance);
self.transform.push(DAffine2::IDENTITY);
self.alpha_blending.push(AlphaBlending::default());
self.source_node_id.push(None);
InstanceMut {
instance: self.instance.last_mut().expect("Shouldn't be empty"),
transform: self.transform.last_mut().expect("Shouldn't be empty"),
alpha_blending: self.alpha_blending.last_mut().expect("Shouldn't be empty"),
source_node_id: self.source_node_id.last_mut().expect("Shouldn't be empty"),
}
pub fn push(&mut self, instance: Instance<T>) {
self.instance.push(instance.instance);
self.transform.push(instance.transform);
self.alpha_blending.push(instance.alpha_blending);
self.source_node_id.push(instance.source_node_id);
}
pub fn push_instance(&mut self, instance: Instance<T>) -> InstanceMut<T>
where
T: Clone,
{
self.instance.push(instance.instance.clone());
self.transform.push(*instance.transform);
self.alpha_blending.push(*instance.alpha_blending);
self.source_node_id.push(*instance.source_node_id);
InstanceMut {
instance: self.instance.last_mut().expect("Shouldn't be empty"),
transform: self.transform.last_mut().expect("Shouldn't be empty"),
alpha_blending: self.alpha_blending.last_mut().expect("Shouldn't be empty"),
source_node_id: self.source_node_id.last_mut().expect("Shouldn't be empty"),
}
}
pub fn one_instance(&self) -> Instance<T> {
Instance {
pub fn one_instance_ref(&self) -> InstanceRef<T> {
InstanceRef {
instance: self.instance.first().unwrap_or_else(|| panic!("ONE INSTANCE EXPECTED, FOUND {}", self.instance.len())),
transform: self.transform.first().unwrap_or_else(|| panic!("ONE INSTANCE EXPECTED, FOUND {}", self.instance.len())),
alpha_blending: self.alpha_blending.first().unwrap_or_else(|| panic!("ONE INSTANCE EXPECTED, FOUND {}", self.instance.len())),
@@ -91,12 +67,12 @@ impl<T> Instances<T> {
}
}
pub fn instances(&self) -> impl DoubleEndedIterator<Item = Instance<T>> {
pub fn instance_iter(self) -> impl DoubleEndedIterator<Item = Instance<T>> {
self.instance
.iter()
.zip(self.transform.iter())
.zip(self.alpha_blending.iter())
.zip(self.source_node_id.iter())
.into_iter()
.zip(self.transform)
.zip(self.alpha_blending)
.zip(self.source_node_id)
.map(|(((instance, transform), alpha_blending), source_node_id)| Instance {
instance,
transform,
@@ -105,7 +81,21 @@ impl<T> Instances<T> {
})
}
pub fn instances_mut(&mut self) -> impl DoubleEndedIterator<Item = InstanceMut<T>> {
pub fn instance_ref_iter(&self) -> impl DoubleEndedIterator<Item = InstanceRef<T>> {
self.instance
.iter()
.zip(self.transform.iter())
.zip(self.alpha_blending.iter())
.zip(self.source_node_id.iter())
.map(|(((instance, transform), alpha_blending), source_node_id)| InstanceRef {
instance,
transform,
alpha_blending,
source_node_id,
})
}
pub fn instance_mut_iter(&mut self) -> impl DoubleEndedIterator<Item = InstanceMut<T>> {
self.instance
.iter_mut()
.zip(self.transform.iter_mut())
@@ -119,12 +109,12 @@ impl<T> Instances<T> {
})
}
pub fn get(&self, index: usize) -> Option<Instance<T>> {
pub fn get(&self, index: usize) -> Option<InstanceRef<T>> {
if index >= self.instance.len() {
return None;
}
Some(Instance {
Some(InstanceRef {
instance: &self.instance[index],
transform: &self.transform[index],
alpha_blending: &self.alpha_blending[index],
@@ -199,12 +189,13 @@ fn one_source_node_id_default() -> Vec<Option<NodeId>> {
}
#[derive(Copy, Clone, Debug)]
pub struct Instance<'a, T> {
pub struct InstanceRef<'a, T> {
pub instance: &'a T,
pub transform: &'a DAffine2,
pub alpha_blending: &'a AlphaBlending,
pub source_node_id: &'a Option<NodeId>,
}
#[derive(Debug)]
pub struct InstanceMut<'a, T> {
pub instance: &'a mut T,
@@ -213,10 +204,32 @@ pub struct InstanceMut<'a, T> {
pub source_node_id: &'a mut Option<NodeId>,
}
#[derive(Copy, Clone, Debug)]
pub struct Instance<T> {
pub instance: T,
pub transform: DAffine2,
pub alpha_blending: AlphaBlending,
pub source_node_id: Option<NodeId>,
}
impl<T> Instance<T> {
pub fn to_graphic_element<U>(self) -> Instance<U>
where
T: Into<U>,
{
Instance {
instance: self.instance.into(),
transform: self.transform,
alpha_blending: self.alpha_blending,
source_node_id: self.source_node_id,
}
}
}
// VECTOR DATA TABLE
impl Transform for VectorDataTable {
fn transform(&self) -> DAffine2 {
*self.one_instance().transform
*self.one_instance_ref().transform
}
}
impl TransformMut for VectorDataTable {
@@ -228,7 +241,7 @@ impl TransformMut for VectorDataTable {
// TEXTURE FRAME TABLE
impl Transform for TextureFrameTable {
fn transform(&self) -> DAffine2 {
*self.one_instance().transform
*self.one_instance_ref().transform
}
}
impl TransformMut for TextureFrameTable {
@@ -243,7 +256,7 @@ where
GraphicElement: From<Image<P>>,
{
fn transform(&self) -> DAffine2 {
*self.one_instance().transform
*self.one_instance_ref().transform
}
}
impl<P: Pixel> TransformMut for ImageFrameTable<P>
+24
View File
@@ -365,6 +365,30 @@ fn not_equals<U: core::cmp::PartialEq<T>, T>(
other_value != value
}
/// The less-than operation (<) compares two values and returns true if the first value is less than the second, or false if it is not.
/// If enabled with "Or Equal", the less-than-or-equal operation (<=) will be used instead.
#[node_macro::node(category("Math: Logic"))]
fn less_than<T: core::cmp::PartialOrd<T>>(
_: impl Ctx,
#[implementations(f64, &f64, f32, &f32, u32, &u32)] value: T,
#[implementations(f64, &f64, f32, &f32, u32, &u32)] other_value: T,
or_equal: bool,
) -> bool {
if or_equal { value <= other_value } else { value < other_value }
}
/// The greater-than operation (>) compares two values and returns true if the first value is greater than the second, or false if it is not.
/// If enabled with "Or Equal", the greater-than-or-equal operation (>=) will be used instead.
#[node_macro::node(category("Math: Logic"))]
fn greater_than<T: core::cmp::PartialOrd<T>>(
_: impl Ctx,
#[implementations(f64, &f64, f32, &f32, u32, &u32)] value: T,
#[implementations(f64, &f64, f32, &f32, u32, &u32)] other_value: T,
or_equal: bool,
) -> bool {
if or_equal { value >= other_value } else { value > other_value }
}
/// The logical or operation (||) returns true if either of the two inputs are true, or false if both are false.
#[node_macro::node(category("Math: Logic"))]
fn logical_or(_: impl Ctx, value: bool, other_value: bool) -> bool {
+3 -3
View File
@@ -300,21 +300,21 @@ trait SetBlendMode {
impl SetBlendMode for VectorDataTable {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.alpha_blending.blend_mode = blend_mode;
}
}
}
impl SetBlendMode for GraphicGroupTable {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.alpha_blending.blend_mode = blend_mode;
}
}
}
impl SetBlendMode for ImageFrameTable<Color> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.alpha_blending.blend_mode = blend_mode;
}
}
+6 -6
View File
@@ -598,7 +598,7 @@ impl Blend<Color> for ImageFrameTable<Color> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result = self.clone();
for (over, under) in result.instances_mut().zip(under.instances()) {
for (over, under) in result.instance_mut_iter().zip(under.instance_ref_iter()) {
let data = over.instance.data.iter().zip(under.instance.data.iter()).map(|(a, b)| blend_fn(*a, *b)).collect();
*over.instance = Image {
@@ -731,7 +731,7 @@ where
GraphicElement: From<Image<P>>,
{
fn adjust(&mut self, map_fn: impl Fn(&P) -> P) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
for c in instance.instance.data.iter_mut() {
*c = map_fn(c);
}
@@ -1360,14 +1360,14 @@ impl MultiplyAlpha for Color {
}
impl MultiplyAlpha for VectorDataTable {
fn multiply_alpha(&mut self, factor: f64) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.alpha_blending.opacity *= factor as f32;
}
}
}
impl MultiplyAlpha for GraphicGroupTable {
fn multiply_alpha(&mut self, factor: f64) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.alpha_blending.opacity *= factor as f32;
}
}
@@ -1377,7 +1377,7 @@ where
GraphicElement: From<Image<P>>,
{
fn multiply_alpha(&mut self, factor: f64) {
for instance in self.instances_mut() {
for instance in self.instance_mut_iter() {
instance.alpha_blending.opacity *= factor as f32;
}
}
@@ -1577,7 +1577,7 @@ mod test {
let opacity = 100_f64;
let result = super::color_overlay((), ImageFrameTable::new(image.clone()), overlay_color, BlendMode::Multiply, opacity);
let result = result.instances().next().unwrap().instance;
let result = result.instance_ref_iter().next().unwrap().instance;
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
+6
View File
@@ -54,6 +54,12 @@ impl AxisAlignedBbox {
}
}
impl From<(DVec2, DVec2)> for AxisAlignedBbox {
fn from((start, end): (DVec2, DVec2)) -> Self {
Self { start, end }
}
}
#[cfg_attr(not(target_arch = "spirv"), derive(Debug))]
#[derive(Clone)]
pub struct Bbox {
+1 -1
View File
@@ -31,7 +31,7 @@ struct BrushCacheImpl {
impl BrushCacheImpl {
fn compute_brush_plan(&mut self, mut background: ImageFrameTable<Color>, input: &[BrushStroke]) -> BrushPlan {
// Do background invalidation.
if background.one_instance().instance != self.background.one_instance().instance {
if background.one_instance_ref().instance != self.background.one_instance_ref().instance {
self.background = background.clone();
return BrushPlan {
strokes: input.to_vec(),
+7 -7
View File
@@ -232,7 +232,7 @@ pub fn migrate_image_frame<'de, D: serde::Deserializer<'de>>(deserializer: D) ->
fn from(element: GraphicElement) -> Self {
match element {
GraphicElement::RasterFrame(crate::RasterFrame::ImageFrame(image)) => Self {
image: image.one_instance().instance.clone(),
image: image.one_instance_ref().instance.clone(),
},
_ => panic!("Expected Image, found {:?}", element),
}
@@ -274,7 +274,7 @@ pub fn migrate_image_frame<'de, D: serde::Deserializer<'de>>(deserializer: D) ->
*image_frame_table.one_instance_mut().alpha_blending = alpha_blending;
image_frame_table
}
FormatVersions::ImageFrame(image_frame) => ImageFrameTable::new(image_frame.one_instance().instance.image.clone()),
FormatVersions::ImageFrame(image_frame) => ImageFrameTable::new(image_frame.one_instance_ref().instance.image.clone()),
FormatVersions::ImageFrameTable(image_frame_table) => image_frame_table,
})
}
@@ -315,8 +315,8 @@ where
// TODO: Improve sampling logic
#[inline(always)]
fn sample(&self, pos: DVec2, area: DVec2) -> Option<Self::Pixel> {
let image_transform = self.one_instance().transform;
let image = self.one_instance().instance;
let image_transform = self.one_instance_ref().transform;
let image = self.one_instance_ref().instance;
let image_size = DVec2::new(image.width() as f64, image.height() as f64);
let pos = (DAffine2::from_scale(image_size) * image_transform.inverse()).transform_point2(pos);
@@ -333,19 +333,19 @@ where
type Pixel = P;
fn width(&self) -> u32 {
let image = self.one_instance().instance;
let image = self.one_instance_ref().instance;
image.width()
}
fn height(&self) -> u32 {
let image = self.one_instance().instance;
let image = self.one_instance_ref().instance;
image.height()
}
fn get_pixel(&self, x: u32, y: u32) -> Option<Self::Pixel> {
let image = self.one_instance().instance;
let image = self.one_instance_ref().instance;
image.get_pixel(x, y)
}
+152 -2
View File
@@ -1,6 +1,8 @@
use crate::vector::PointId;
use crate::instances::Instance;
use crate::vector::{PointId, VectorData, VectorDataTable};
use crate::{GraphicElement, GraphicGroupTable};
use bezier_rs::{ManipulatorGroup, Subpath};
use glam::DVec2;
use glam::{DAffine2, DVec2};
use rustybuzz::ttf_parser::{GlyphId, OutlineBuilder};
use rustybuzz::{GlyphBuffer, UnicodeBuffer};
@@ -247,3 +249,151 @@ fn split_words_including_spaces() {
assert_eq!(split_words.next(), Some("."));
assert_eq!(split_words.next(), None);
}
// Builder specifically for generating glyph paths relative to (0,0)
struct GlyphBuilder {
current_subpath: Subpath<PointId>,
other_subpaths: Vec<Subpath<PointId>>,
ascender: f64,
scale: f64,
id: PointId,
}
impl GlyphBuilder {
// Calculates point relative to glyph origin, scaled and adjusted for ascender
fn point(&self, x: f32, y: f32) -> DVec2 {
DVec2::new(x as f64, self.ascender - y as f64) * self.scale
}
// Extracts the generated subpaths and resets the builder state
fn take_subpaths(&mut self) -> Vec<Subpath<PointId>> {
let mut subpaths = std::mem::take(&mut self.other_subpaths);
if !self.current_subpath.is_empty() {
subpaths.push(std::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
}
subpaths
}
}
impl OutlineBuilder for GlyphBuilder {
fn move_to(&mut self, x: f32, y: f32) {
if !self.current_subpath.is_empty() {
self.other_subpaths.push(core::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
}
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_anchor_with_id(self.point(x, y), self.id.next_id()));
}
fn line_to(&mut self, x: f32, y: f32) {
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_anchor_with_id(self.point(x, y), self.id.next_id()));
}
fn quad_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) {
let [handle, anchor] = [self.point(x1, y1), self.point(x2, y2)];
self.current_subpath.last_manipulator_group_mut().unwrap().out_handle = Some(handle);
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_with_id(anchor, None, None, self.id.next_id()));
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
let [handle1, handle2, anchor] = [self.point(x1, y1), self.point(x2, y2), self.point(x3, y3)];
self.current_subpath.last_manipulator_group_mut().unwrap().out_handle = Some(handle1);
self.current_subpath
.push_manipulator_group(ManipulatorGroup::new_with_id(anchor, Some(handle2), None, self.id.next_id()));
}
fn close(&mut self) {
self.current_subpath.set_closed(true);
self.other_subpaths.push(core::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
}
}
/// Converts a string into a graphic group, where each element is a single character glyph as VectorData.
pub fn to_group(str: &str, buzz_face: Option<rustybuzz::Face>, typesetting: TypesettingConfig) -> GraphicGroupTable {
let Some(buzz_face) = buzz_face else { return GraphicGroupTable::empty() };
let space_glyph = buzz_face.glyph_index(' ');
let (scale, line_height, mut buffer) = font_properties(&buzz_face, typesetting.font_size, typesetting.line_height_ratio);
let ascender = (buzz_face.ascender() as f64 / buzz_face.height() as f64) * typesetting.font_size / scale;
let mut result_group = GraphicGroupTable::empty(); // Changed from Instances::empty()
let mut text_cursor = DVec2::ZERO;
let mut point_id_gen = PointId::ZERO; // Use a single generator across all glyphs
for line in str.split('\n') {
for (index, word) in SplitWordsIncludingSpaces::new(line).enumerate() {
push_str(&mut buffer, word);
let glyph_buffer = rustybuzz::shape(&buzz_face, &[], buffer);
// Don't wrap the first word
if index != 0 && wrap_word(typesetting.max_width, &glyph_buffer, scale, typesetting.character_spacing, text_cursor.x, space_glyph) {
text_cursor = DVec2::new(0., text_cursor.y + line_height);
}
for (glyph_position, glyph_info) in glyph_buffer.glyph_positions().iter().zip(glyph_buffer.glyph_infos()) {
let glyph_id = GlyphId(glyph_info.glyph_id as u16);
// Calculate the intended render position for this glyph's origin before advancing the cursor
let current_glyph_offset = DVec2::new(glyph_position.x_offset as f64, glyph_position.y_offset as f64) * scale;
let glyph_render_pos = text_cursor + current_glyph_offset;
// Check for line wrap based on advance width BEFORE rendering the current glyph
if let Some(max_width) = typesetting.max_width {
if space_glyph != Some(glyph_id) && text_cursor.x + (glyph_position.x_advance as f64 * scale * typesetting.character_spacing) >= max_width {
// Move cursor to the next line for the *next* glyph
text_cursor = DVec2::new(0., text_cursor.y + line_height);
// Note: The current glyph still renders based on the glyph_render_pos calculated before the wrap check.
}
}
// Clip when the height is exceeded - stop adding instances
if typesetting.max_height.is_some_and(|max_height| text_cursor.y > max_height - line_height) {
return result_group; // Changed from result_instances
}
// Build the glyph geometry relative to its origin (0,0)
let mut glyph_builder = GlyphBuilder {
current_subpath: Subpath::new(Vec::new(), false),
other_subpaths: Vec::new(),
ascender,
scale,
id: point_id_gen, // Pass the current generator state
};
buzz_face.outline_glyph(glyph_id, &mut glyph_builder);
point_id_gen = glyph_builder.id; // Update the generator state for the next glyph
let glyph_subpaths = glyph_builder.take_subpaths();
// Create an instance only if the glyph has geometry (e.g., not for empty spaces if they have no outline)
if !glyph_subpaths.is_empty() {
// Create VectorData for this single glyph
let glyph_vector_data = VectorData::from_subpaths(glyph_subpaths, true);
// Wrap VectorData in VectorDataTable
let glyph_vector_table = VectorDataTable::new(glyph_vector_data);
// TODO: Consider inheriting style (fill/stroke) if needed in the future.
// Create the transform to position this glyph instance
let glyph_transform = DAffine2::from_translation(glyph_render_pos);
// Add the instance to the results group
result_group.push(Instance {
// Changed from result_instances.push
instance: GraphicElement::VectorData(glyph_vector_table), // Changed instance type
transform: glyph_transform,
alpha_blending: Default::default(), // Use default blending for now
source_node_id: None, // Glyphs don't have a specific source node ID
});
}
// Advance the main text cursor based on the glyph's advance width for the next glyph
text_cursor += DVec2::new(glyph_position.x_advance as f64 * typesetting.character_spacing, glyph_position.y_advance as f64) * scale;
}
buffer = glyph_buffer.clear();
}
// Move cursor down for the next line
text_cursor = DVec2::new(0., text_cursor.y + line_height);
}
result_group // Changed from result_instances
}
+103 -2
View File
@@ -189,7 +189,7 @@ async fn transform<T: 'n + 'static>(
let mut transform_target = transform_target.eval(ctx.into_context()).await;
for data_transform in transform_target.instances_mut() {
for data_transform in transform_target.instance_mut_iter() {
*data_transform.transform = matrix * *data_transform.transform;
}
@@ -202,7 +202,7 @@ fn replace_transform<Data, TransformInput: Transform>(
#[implementations(VectorDataTable, ImageFrameTable<Color>, GraphicGroupTable)] mut data: Instances<Data>,
#[implementations(DAffine2)] transform: TransformInput,
) -> Instances<Data> {
for data_transform in data.instances_mut() {
for data_transform in data.instance_mut_iter() {
*data_transform.transform = transform.transform();
}
data
@@ -242,3 +242,104 @@ async fn freeze_real_time<T: 'n + 'static>(
transform_target.eval(ctx.into_context()).await
}
#[derive(Clone, Copy, Debug, Default, Hash, Eq, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum ReferencePoint {
#[default]
None,
TopLeft,
TopCenter,
TopRight,
CenterLeft,
Center,
CenterRight,
BottomLeft,
BottomCenter,
BottomRight,
}
impl ReferencePoint {
pub fn point_in_bounding_box(&self, bounding_box: AxisAlignedBbox) -> Option<DVec2> {
let size = bounding_box.size();
let offset = match self {
ReferencePoint::None => return None,
ReferencePoint::TopLeft => DVec2::ZERO,
ReferencePoint::TopCenter => DVec2::new(size.x / 2., 0.),
ReferencePoint::TopRight => DVec2::new(size.x, 0.),
ReferencePoint::CenterLeft => DVec2::new(0., size.y / 2.),
ReferencePoint::Center => DVec2::new(size.x / 2., size.y / 2.),
ReferencePoint::CenterRight => DVec2::new(size.x, size.y / 2.),
ReferencePoint::BottomLeft => DVec2::new(0., size.y),
ReferencePoint::BottomCenter => DVec2::new(size.x / 2., size.y),
ReferencePoint::BottomRight => DVec2::new(size.x, size.y),
};
Some(bounding_box.start + offset)
}
}
impl From<&str> for ReferencePoint {
fn from(input: &str) -> Self {
match input {
"None" => ReferencePoint::None,
"TopLeft" => ReferencePoint::TopLeft,
"TopCenter" => ReferencePoint::TopCenter,
"TopRight" => ReferencePoint::TopRight,
"CenterLeft" => ReferencePoint::CenterLeft,
"Center" => ReferencePoint::Center,
"CenterRight" => ReferencePoint::CenterRight,
"BottomLeft" => ReferencePoint::BottomLeft,
"BottomCenter" => ReferencePoint::BottomCenter,
"BottomRight" => ReferencePoint::BottomRight,
_ => panic!("Failed parsing unrecognized ReferencePosition enum value '{input}'"),
}
}
}
impl From<ReferencePoint> for Option<DVec2> {
fn from(input: ReferencePoint) -> Self {
match input {
ReferencePoint::None => None,
ReferencePoint::TopLeft => Some(DVec2::new(0., 0.)),
ReferencePoint::TopCenter => Some(DVec2::new(0.5, 0.)),
ReferencePoint::TopRight => Some(DVec2::new(1., 0.)),
ReferencePoint::CenterLeft => Some(DVec2::new(0., 0.5)),
ReferencePoint::Center => Some(DVec2::new(0.5, 0.5)),
ReferencePoint::CenterRight => Some(DVec2::new(1., 0.5)),
ReferencePoint::BottomLeft => Some(DVec2::new(0., 1.)),
ReferencePoint::BottomCenter => Some(DVec2::new(0.5, 1.)),
ReferencePoint::BottomRight => Some(DVec2::new(1., 1.)),
}
}
}
impl From<DVec2> for ReferencePoint {
fn from(input: DVec2) -> Self {
const TOLERANCE: f64 = 1e-5_f64;
if input.y.abs() < TOLERANCE {
if input.x.abs() < TOLERANCE {
return ReferencePoint::TopLeft;
} else if (input.x - 0.5).abs() < TOLERANCE {
return ReferencePoint::TopCenter;
} else if (input.x - 1.).abs() < TOLERANCE {
return ReferencePoint::TopRight;
}
} else if (input.y - 0.5).abs() < TOLERANCE {
if input.x.abs() < TOLERANCE {
return ReferencePoint::CenterLeft;
} else if (input.x - 0.5).abs() < TOLERANCE {
return ReferencePoint::Center;
} else if (input.x - 1.).abs() < TOLERANCE {
return ReferencePoint::CenterRight;
}
} else if (input.y - 1.).abs() < TOLERANCE {
if input.x.abs() < TOLERANCE {
return ReferencePoint::BottomLeft;
} else if (input.x - 0.5).abs() < TOLERANCE {
return ReferencePoint::BottomCenter;
} else if (input.x - 1.).abs() < TOLERANCE {
return ReferencePoint::BottomRight;
}
}
ReferencePoint::None
}
}
@@ -1,39 +1,74 @@
use crate::instances::Instance;
use crate::vector::{VectorData, VectorDataTable};
use crate::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractIndex, ExtractVarArgs, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use crate::instances::{InstanceRef, Instances};
use crate::raster::Color;
use crate::raster::image::ImageFrameTable;
use crate::transform::TransformMut;
use crate::vector::VectorDataTable;
use crate::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractIndex, ExtractVarArgs, GraphicElement, GraphicGroupTable, OwnedContextImpl};
use glam::DVec2;
#[node_macro::node(name("Instance on Points"), category("Vector: Shape"), path(graphene_core::vector))]
async fn instance_on_points(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
#[node_macro::node(name("Instance on Points"), category("Instancing"), path(graphene_core::vector))]
async fn instance_on_points<T: Into<GraphicElement> + Default + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx,
points: VectorDataTable,
#[implementations(Context -> VectorDataTable)] instance_node: impl Node<'n, Context<'static>, Output = VectorDataTable>,
) -> VectorDataTable {
let mut result = VectorDataTable::empty();
#[implementations(Context -> GraphicGroupTable, Context -> VectorDataTable, Context -> ImageFrameTable<Color>)] instance: impl Node<'n, Context<'static>, Output = Instances<T>>,
reverse: bool,
) -> GraphicGroupTable {
let mut result_table = GraphicGroupTable::empty();
for Instance { instance: points, transform, .. } in points.instances() {
for (index, &point) in points.point_domain.positions().iter().enumerate() {
for InstanceRef { instance: points, transform, .. } in points.instance_ref_iter() {
let mut iteration = async |index, point| {
let transformed_point = transform.transform_point2(point);
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_vararg(Box::new(transformed_point));
let instanced = instance_node.eval(new_ctx.into_context()).await;
let generated_instance = instance.eval(new_ctx.into_context()).await;
for instanced in instanced.instances() {
let instanced = result.push_instance(instanced);
*instanced.transform *= DAffine2::from_translation(transformed_point);
for mut instanced in generated_instance.instance_iter() {
instanced.transform.translate(transformed_point);
result_table.push(instanced.to_graphic_element());
}
};
let range = points.point_domain.positions().iter().enumerate();
if reverse {
for (index, &point) in range.rev() {
iteration(index, point).await;
}
} else {
for (index, &point) in range {
iteration(index, point).await;
}
}
}
// TODO: Remove once we support empty tables, currently this is here to avoid crashing
if result.is_empty() {
return VectorDataTable::new(VectorData::empty());
}
result
result_table
}
#[node_macro::node(category("Attributes"), path(graphene_core::vector))]
#[node_macro::node(category("Instancing"), path(graphene_core::vector))]
async fn instance_repeat<T: Into<GraphicElement> + Default + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
#[implementations(Context -> GraphicGroupTable, Context -> VectorDataTable, Context -> ImageFrameTable<Color>)] instance: impl Node<'n, Context<'static>, Output = Instances<T>>,
#[default(1)] count: u64,
reverse: bool,
) -> GraphicGroupTable {
let count = count.max(1) as usize;
let mut result_table = GraphicGroupTable::empty();
for index in 0..count {
let index = if reverse { count - index - 1 } else { index };
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index);
let generated_instance = instance.eval(new_ctx.into_context()).await;
for instanced in generated_instance.instance_iter() {
result_table.push(instanced.to_graphic_element());
}
}
result_table
}
#[node_macro::node(category("Instancing"), path(graphene_core::vector))]
async fn instance_position(ctx: impl Ctx + ExtractVarArgs) -> DVec2 {
match ctx.vararg(0).map(|dynamic| dynamic.downcast_ref::<DVec2>()) {
Ok(Some(position)) => return *position,
@@ -43,7 +78,7 @@ async fn instance_position(ctx: impl Ctx + ExtractVarArgs) -> DVec2 {
Default::default()
}
#[node_macro::node(category("Attributes"), path(graphene_core::vector))]
#[node_macro::node(category("Instancing"), path(graphene_core::vector))]
async fn instance_index(ctx: impl Ctx + ExtractIndex) -> f64 {
match ctx.try_index() {
Some(index) => return index as f64,
@@ -87,10 +122,17 @@ mod test {
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
let points = VectorDataTable::new(VectorData::from_subpath(Subpath::from_anchors_linear(positions, false)));
let repeated = super::instance_on_points(owned, points, &rect).await;
let repeated = super::instance_on_points(owned, points, &rect, false).await;
assert_eq!(repeated.len(), positions.len());
for (position, instanced) in positions.into_iter().zip(repeated.instances()) {
let bounds = instanced.instance.bounding_box_with_transform(*instanced.transform).unwrap();
for (position, instanced) in positions.into_iter().zip(repeated.instance_ref_iter()) {
let bounds = instanced
.instance
.as_vector_data()
.unwrap()
.one_instance_ref()
.instance
.bounding_box_with_transform(*instanced.transform)
.unwrap();
assert!(position.abs_diff_eq((bounds[0] + bounds[1]) / 2., 1e-10));
assert_eq!((bounds[1] - bounds[0]).x, position.y);
}
+24 -6
View File
@@ -205,9 +205,14 @@ fn grid<T: GridSpacing>(
for x in 0..columns {
// Add current point to the grid with offset for odd columns
let current_index = vector_data.point_domain.ids().len();
vector_data
.point_domain
.push(point_id.next_id(), DVec2::new(spacing.x * x as f64, spacing.y * (y as f64 - (x % 2) as f64 * 0.5)));
let a_angles_eaten = ((x + 1) / 2) as f64;
let b_angles_eaten = (x / 2) as f64;
let offset_y_fraction = b_angles_eaten * tan_b - a_angles_eaten * tan_a;
let position = DVec2::new(spacing.x * x as f64, spacing.y * y as f64 + offset_y_fraction * spacing.x);
vector_data.point_domain.push(point_id.next_id(), position);
// Helper function to connect points with line segments
let mut push_segment = |to_index: Option<usize>| {
@@ -248,9 +253,9 @@ fn isometric_grid_test() {
// Works properly
let grid = grid((), (), GridType::Isometric, 10., (30., 30.).into(), 5, 5);
assert_eq!(grid.one_instance().instance.point_domain.ids().len(), 5 * 5);
assert_eq!(grid.one_instance().instance.segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.one_instance().instance.segment_bezier_iter() {
assert_eq!(grid.one_instance_ref().instance.point_domain.ids().len(), 5 * 5);
assert_eq!(grid.one_instance_ref().instance.segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.one_instance_ref().instance.segment_bezier_iter() {
assert_eq!(bezier.handles, bezier_rs::BezierHandles::Linear);
assert!(
((bezier.start - bezier.end).length() - 10.).abs() < 1e-5,
@@ -259,3 +264,16 @@ fn isometric_grid_test() {
);
}
}
#[test]
fn skew_isometric_grid_test() {
let grid = grid((), (), GridType::Isometric, 10., (40., 30.).into(), 5, 5);
assert_eq!(grid.one_instance_ref().instance.point_domain.ids().len(), 5 * 5);
assert_eq!(grid.one_instance_ref().instance.segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.one_instance_ref().instance.segment_bezier_iter() {
assert_eq!(bezier.handles, bezier_rs::BezierHandles::Linear);
let vector = bezier.start - bezier.end;
let angle = (vector.angle_to(DVec2::X).to_degrees() + 180.) % 180.;
assert!([90., 150., 40.].into_iter().any(|target| (target - angle).abs() < 1e-10), "unexpected angle of {}", angle)
}
}
+10
View File
@@ -1,4 +1,6 @@
use dyn_any::DynAny;
use glam::DVec2;
use kurbo::Point;
/// Represents different ways of calculating the centroid.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash, DynAny, specta::Type)]
@@ -101,3 +103,11 @@ pub enum ArcType {
Closed,
PieSlice,
}
pub fn point_to_dvec2(point: Point) -> DVec2 {
DVec2 { x: point.x, y: point.y }
}
pub fn dvec2_to_point(value: DVec2) -> Point {
Point { x: value.x, y: value.y }
}
+85 -13
View File
@@ -2,11 +2,12 @@ mod attributes;
mod indexed;
mod modification;
use super::misc::point_to_dvec2;
use super::style::{PathStyle, Stroke};
use crate::instances::Instances;
use crate::{AlphaBlending, Color, GraphicGroupTable};
pub use attributes::*;
use bezier_rs::ManipulatorGroup;
use bezier_rs::{BezierHandles, ManipulatorGroup};
use core::borrow::Borrow;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
@@ -176,6 +177,70 @@ impl VectorData {
}
}
/// Appends a Kurbo BezPath to the vector data.
pub fn append_bezpath(&mut self, bezpath: kurbo::BezPath) {
let mut first_point_index = None;
let mut last_point_index = None;
let mut first_segment_id = None;
let mut last_segment_id = None;
let mut point_id = self.point_domain.next_id();
let mut segment_id = self.segment_domain.next_id();
let stroke_id = StrokeId::ZERO;
let fill_id = FillId::ZERO;
for element in bezpath.elements() {
match *element {
kurbo::PathEl::MoveTo(point) => {
let next_point_index = self.point_domain.ids().len();
self.point_domain.push(point_id.next_id(), point_to_dvec2(point));
first_point_index = Some(next_point_index);
last_point_index = Some(next_point_index);
}
kurbo::PathEl::ClosePath => match (first_point_index, last_point_index) {
(Some(first_point_index), Some(last_point_index)) => {
let next_segment_id = segment_id.next_id();
self.segment_domain.push(next_segment_id, first_point_index, last_point_index, BezierHandles::Linear, stroke_id);
let next_region_id = self.region_domain.next_id();
self.region_domain.push(next_region_id, first_segment_id.unwrap()..=next_segment_id, fill_id);
}
_ => {
error!("Empty bezpath cannot be closed.")
}
},
_ => {}
}
let mut append_path_element = |handle: BezierHandles, point: kurbo::Point| {
let next_point_index = self.point_domain.ids().len();
self.point_domain.push(point_id.next_id(), point_to_dvec2(point));
let next_segment_id = segment_id.next_id();
self.segment_domain.push(segment_id.next_id(), last_point_index.unwrap(), next_point_index, handle, stroke_id);
last_point_index = Some(next_point_index);
first_segment_id = Some(first_segment_id.unwrap_or(next_segment_id));
last_segment_id = Some(next_segment_id);
};
match *element {
kurbo::PathEl::LineTo(point) => append_path_element(BezierHandles::Linear, point),
kurbo::PathEl::QuadTo(handle, point) => append_path_element(BezierHandles::Quadratic { handle: point_to_dvec2(handle) }, point),
kurbo::PathEl::CurveTo(handle_start, handle_end, point) => append_path_element(
BezierHandles::Cubic {
handle_start: point_to_dvec2(handle_start),
handle_end: point_to_dvec2(handle_end),
},
point,
),
_ => {}
}
}
}
/// Construct some new vector data from subpaths with an identity transform and black fill.
pub fn from_subpaths(subpaths: impl IntoIterator<Item = impl Borrow<bezier_rs::Subpath<PointId>>>, preserve_id: bool) -> Self {
let mut vector_data = Self::empty();
@@ -368,29 +433,29 @@ impl VectorData {
}
}
pub fn concat(&mut self, other: &Self, transform: DAffine2, node_id: u64) {
let point_map = other
pub fn concat(&mut self, additional: &Self, transform_of_additional: DAffine2, collision_hash_seed: u64) {
let point_map = additional
.point_domain
.ids()
.iter()
.filter(|id| self.point_domain.ids().contains(id))
.map(|&old| (old, old.generate_from_hash(node_id)))
.map(|&old| (old, old.generate_from_hash(collision_hash_seed)))
.collect::<HashMap<_, _>>();
let segment_map = other
let segment_map = additional
.segment_domain
.ids()
.iter()
.filter(|id| self.segment_domain.ids().contains(id))
.map(|&old| (old, old.generate_from_hash(node_id)))
.map(|&old| (old, old.generate_from_hash(collision_hash_seed)))
.collect::<HashMap<_, _>>();
let region_map = other
let region_map = additional
.region_domain
.ids()
.iter()
.filter(|id| self.region_domain.ids().contains(id))
.map(|&old| (old, old.generate_from_hash(node_id)))
.map(|&old| (old, old.generate_from_hash(collision_hash_seed)))
.collect::<HashMap<_, _>>();
let id_map = IdMap {
@@ -400,14 +465,14 @@ impl VectorData {
region_map,
};
self.point_domain.concat(&other.point_domain, transform, &id_map);
self.segment_domain.concat(&other.segment_domain, transform, &id_map);
self.region_domain.concat(&other.region_domain, transform, &id_map);
self.point_domain.concat(&additional.point_domain, transform_of_additional, &id_map);
self.segment_domain.concat(&additional.segment_domain, transform_of_additional, &id_map);
self.region_domain.concat(&additional.region_domain, transform_of_additional, &id_map);
// TODO: properly deal with fills such as gradients
self.style = other.style.clone();
self.style = additional.style.clone();
self.colinear_manipulators.extend(other.colinear_manipulators.iter().copied());
self.colinear_manipulators.extend(additional.colinear_manipulators.iter().copied());
}
}
@@ -496,6 +561,13 @@ impl ManipulatorPointId {
_ => None,
}
}
pub fn get_segment(self) -> Option<SegmentId> {
match self {
ManipulatorPointId::PrimaryHandle(segment) | ManipulatorPointId::EndHandle(segment) => Some(segment),
_ => None,
}
}
}
/// The type of handle found on a bézier curve.
@@ -1,3 +1,4 @@
use crate::vector::misc::dvec2_to_point;
use crate::vector::vector_data::{HandleId, VectorData};
use bezier_rs::BezierHandles;
use core::iter::zip;
@@ -180,6 +181,14 @@ impl PointDomain {
}
}
pub fn len(&self) -> usize {
self.id.len()
}
pub fn is_empty(&self) -> bool {
self.id.is_empty()
}
/// Iterate over point IDs and positions
pub fn iter(&self) -> impl Iterator<Item = (PointId, DVec2)> + '_ {
self.ids().iter().copied().zip(self.positions().iter().copied())
@@ -544,6 +553,94 @@ impl RegionDomain {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HalfEdge {
pub id: SegmentId,
pub start: usize,
pub end: usize,
pub reverse: bool,
}
impl HalfEdge {
pub fn new(id: SegmentId, start: usize, end: usize, reverse: bool) -> Self {
Self { id, start, end, reverse }
}
pub fn reversed(&self) -> Self {
Self {
id: self.id,
start: self.start,
end: self.end,
reverse: !self.reverse,
}
}
pub fn normalize_direction(&self) -> Self {
if self.reverse {
Self {
id: self.id,
start: self.end,
end: self.start,
reverse: false,
}
} else {
*self
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FoundSubpath {
pub edges: Vec<HalfEdge>,
}
impl FoundSubpath {
pub fn new(segments: Vec<HalfEdge>) -> Self {
Self { edges: segments }
}
pub fn endpoints(&self) -> Option<(&HalfEdge, &HalfEdge)> {
match (self.edges.first(), self.edges.last()) {
(Some(first), Some(last)) => Some((first, last)),
_ => None,
}
}
pub fn push(&mut self, segment: HalfEdge) {
self.edges.push(segment);
}
pub fn insert(&mut self, index: usize, segment: HalfEdge) {
self.edges.insert(index, segment);
}
pub fn extend(&mut self, segments: impl IntoIterator<Item = HalfEdge>) {
self.edges.extend(segments);
}
pub fn splice<I>(&mut self, range: std::ops::Range<usize>, replace_with: I)
where
I: IntoIterator<Item = HalfEdge>,
{
self.edges.splice(range, replace_with);
}
pub fn is_closed(&self) -> bool {
match (self.edges.first(), self.edges.last()) {
(Some(first), Some(last)) => first.start == last.end,
_ => false,
}
}
pub fn from_segment(segment: HalfEdge) -> Self {
Self { edges: vec![segment] }
}
pub fn contains(&self, segment_id: SegmentId) -> bool {
self.edges.iter().any(|s| s.id == segment_id)
}
}
impl VectorData {
/// Construct a [`bezier_rs::Bezier`] curve spanning from the resolved position of the start and end points with the specified handles.
fn segment_to_bezier_with_index(&self, start: usize, end: usize, handles: bezier_rs::BezierHandles) -> bezier_rs::Bezier {
@@ -583,6 +680,114 @@ impl VectorData {
.map(to_bezier)
}
pub fn auto_join_paths(&self) -> Vec<FoundSubpath> {
let segments = self.segment_domain.iter().map(|(id, start, end, _)| HalfEdge::new(id, start, end, false));
let mut paths: Vec<FoundSubpath> = Vec::new();
let mut current_path: Option<&mut FoundSubpath> = None;
let mut previous: Option<(usize, usize)> = None;
// First pass. Generates subpaths from continuous segments.
for seg_ref in segments {
let (start, end) = (seg_ref.start, seg_ref.end);
if previous.is_some_and(|(_, prev_end)| start == prev_end) {
if let Some(path) = current_path.as_mut() {
path.push(seg_ref);
}
} else {
paths.push(FoundSubpath::from_segment(seg_ref));
current_path = paths.last_mut();
}
previous = Some((start, end));
}
// Second pass. Try to join paths together.
let mut joined_paths = Vec::new();
loop {
let mut prev_index: Option<usize> = None;
let original_len = paths.len();
for current in paths.into_iter() {
// If there's no previous subpath, start a new one
if prev_index.is_none() {
joined_paths.push(current);
prev_index = Some(joined_paths.len() - 1);
continue;
}
let prev = &mut joined_paths[prev_index.unwrap()];
// Compare segment connections
let (prev_first, prev_last) = prev.endpoints().unwrap();
let (cur_first, cur_last) = current.endpoints().unwrap();
// Join paths if the endpoints connect
if prev_last.end == cur_first.start {
prev.edges.extend(current.edges.into_iter().map(|s| s.normalize_direction()));
} else if prev_first.start == cur_last.end {
prev.edges.splice(0..0, current.edges.into_iter().rev().map(|s| s.normalize_direction()));
} else if prev_last.end == cur_last.end {
prev.edges.extend(current.edges.into_iter().rev().map(|s| s.reversed().normalize_direction()));
} else if prev_first.start == cur_first.start {
prev.edges.splice(0..0, current.edges.into_iter().map(|s| s.reversed().normalize_direction()));
} else {
// If not connected, start a new subpath
joined_paths.push(current);
prev_index = Some(joined_paths.len() - 1);
}
}
// If no paths were joined in this pass, we're done
if joined_paths.len() == original_len {
return joined_paths;
}
// Repeat pass with newly joined paths
paths = joined_paths;
joined_paths = Vec::new();
}
}
/// Construct a [`bezier_rs::Bezier`] curve from an iterator of segments with (handles, start point, end point) independently of discontinuities.
pub fn subpath_from_segments_ignore_discontinuities(&self, segments: impl Iterator<Item = (bezier_rs::BezierHandles, usize, usize)>) -> Option<bezier_rs::Subpath<PointId>> {
let mut first_point = None;
let mut groups = Vec::new();
let mut last: Option<(usize, bezier_rs::BezierHandles)> = None;
for (handle, start, end) in segments {
first_point = Some(first_point.unwrap_or(start));
groups.push(bezier_rs::ManipulatorGroup {
anchor: self.point_domain.positions()[start],
in_handle: last.and_then(|(_, handle)| handle.end()),
out_handle: handle.start(),
id: self.point_domain.ids()[start],
});
last = Some((end, handle));
}
let closed = groups.len() > 1 && last.map(|(point, _)| point) == first_point;
if let Some((end, last_handle)) = last {
if closed {
groups[0].in_handle = last_handle.end();
} else {
groups.push(bezier_rs::ManipulatorGroup {
anchor: self.point_domain.positions()[end],
in_handle: last_handle.end(),
out_handle: None,
id: self.point_domain.ids()[end],
});
}
}
Some(bezier_rs::Subpath::new(groups, closed))
}
/// Construct a [`bezier_rs::Bezier`] curve from an iterator of segments with (handles, start point, end point). Returns None if any ids are invalid or if the segments are not continuous.
fn subpath_from_segments(&self, segments: impl Iterator<Item = (bezier_rs::BezierHandles, usize, usize)>) -> Option<bezier_rs::Subpath<PointId>> {
let mut first_point = None;
@@ -644,8 +849,7 @@ impl VectorData {
})
}
/// Construct a [`bezier_rs::Bezier`] curve for stroke.
pub fn stroke_bezier_paths(&self) -> StrokePathIter<'_> {
fn build_stroke_path_iter(&self) -> StrokePathIter {
let mut points = vec![StrokePathIterPointMetadata::default(); self.point_domain.ids().len()];
for (segment_index, (&start, &end)) in self.segment_domain.start_point.iter().zip(&self.segment_domain.end_point).enumerate() {
points[start].set(StrokePathIterPointSegmentMetadata::new(segment_index, false));
@@ -660,6 +864,44 @@ impl VectorData {
}
}
/// Construct a [`bezier_rs::Bezier`] curve for stroke.
pub fn stroke_bezier_paths(&self) -> impl Iterator<Item = bezier_rs::Subpath<PointId>> {
self.build_stroke_path_iter().map(|(group, closed)| bezier_rs::Subpath::new(group, closed))
}
/// Construct a [`kurbo::BezPath`] curve for stroke.
pub fn stroke_bezpath_iter(&self) -> impl Iterator<Item = kurbo::BezPath> {
self.build_stroke_path_iter().map(|(group, closed)| {
let mut bezpath = kurbo::BezPath::new();
let mut out_handle;
let Some(first) = group.first() else { return bezpath };
bezpath.move_to(dvec2_to_point(first.anchor));
out_handle = first.out_handle;
for manipulator in group.iter().skip(1) {
match (out_handle, manipulator.in_handle) {
(Some(handle_start), Some(handle_end)) => bezpath.curve_to(dvec2_to_point(handle_start), dvec2_to_point(handle_end), dvec2_to_point(manipulator.anchor)),
(None, None) => bezpath.line_to(dvec2_to_point(manipulator.anchor)),
(None, Some(handle)) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(manipulator.anchor)),
(Some(handle), None) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(manipulator.anchor)),
}
out_handle = manipulator.out_handle;
}
if closed {
match (out_handle, first.in_handle) {
(Some(handle_start), Some(handle_end)) => bezpath.curve_to(dvec2_to_point(handle_start), dvec2_to_point(handle_end), dvec2_to_point(first.anchor)),
(None, None) => bezpath.line_to(dvec2_to_point(first.anchor)),
(None, Some(handle)) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(first.anchor)),
(Some(handle), None) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(first.anchor)),
}
bezpath.close_path();
}
bezpath
})
}
/// Construct an iterator [`bezier_rs::ManipulatorGroup`] for stroke.
pub fn manipulator_groups(&self) -> impl Iterator<Item = bezier_rs::ManipulatorGroup<PointId>> + '_ {
self.stroke_bezier_paths().flat_map(|mut path| std::mem::take(path.manipulator_groups_mut()))
@@ -746,7 +988,7 @@ pub struct StrokePathIter<'a> {
}
impl Iterator for StrokePathIter<'_> {
type Item = bezier_rs::Subpath<PointId>;
type Item = (Vec<bezier_rs::ManipulatorGroup<PointId>>, bool);
fn next(&mut self) -> Option<Self::Item> {
let current_start = if let Some((index, _)) = self.points.iter().enumerate().skip(self.skip).find(|(_, val)| val.connected() == 1) {
@@ -805,7 +1047,7 @@ impl Iterator for StrokePathIter<'_> {
}
}
Some(bezier_rs::Subpath::new(groups, closed))
Some((groups, closed))
}
}
@@ -424,7 +424,7 @@ impl core::hash::Hash for VectorModification {
/// A node that applies a procedural modification to some [`VectorData`].
#[node_macro::node(category(""))]
async fn path_modify(_ctx: impl Ctx, mut vector_data: VectorDataTable, modification: Box<VectorModification>) -> VectorDataTable {
let vector_data_transform = *vector_data.one_instance().transform;
let vector_data_transform = *vector_data.one_instance_ref().transform;
let vector_data = vector_data.one_instance_mut().instance;
modification.apply(vector_data);
File diff suppressed because it is too large. Load diff
@@ -7,6 +7,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_core::raster::brush_cache::BrushCache;
use graphene_core::raster::{BlendMode, LuminanceCalculation};
use graphene_core::renderer::RenderMetadata;
use graphene_core::transform::ReferencePoint;
use graphene_core::uuid::NodeId;
use graphene_core::vector::style::Fill;
use graphene_core::{Color, MemoHash, Node, Type};
@@ -233,6 +234,7 @@ tagged_value! {
DocumentNode(DocumentNode),
Curve(graphene_core::raster::curve::Curve),
Footprint(graphene_core::transform::Footprint),
ReferencePoint(graphene_core::transform::ReferencePoint),
Palette(Vec<Color>),
VectorModification(Box<graphene_core::vector::VectorModification>),
CentroidType(graphene_core::vector::misc::CentroidType),
@@ -302,6 +304,32 @@ impl TaggedValue {
None
}
fn to_reference_point(input: &str) -> Option<ReferencePoint> {
let mut choices = input.split("::");
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
if first == "ReferencePoint" {
return Some(match second {
"None" => ReferencePoint::None,
"TopLeft" => ReferencePoint::TopLeft,
"TopCenter" => ReferencePoint::TopCenter,
"TopRight" => ReferencePoint::TopRight,
"CenterLeft" => ReferencePoint::CenterLeft,
"Center" => ReferencePoint::Center,
"CenterRight" => ReferencePoint::CenterRight,
"BottomLeft" => ReferencePoint::BottomLeft,
"BottomCenter" => ReferencePoint::BottomCenter,
"BottomRight" => ReferencePoint::BottomRight,
_ => {
log::error!("Invalid ReferencePoint default type variant: {}", input);
return None;
}
});
}
log::error!("Invalid ReferencePoint default type: {}", input);
None
}
match ty {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
@@ -320,6 +348,7 @@ impl TaggedValue {
x if x == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
x if x == TypeId::of::<Option<Color>>() => to_color(string).map(|color| TaggedValue::OptionalColor(Some(color)))?,
x if x == TypeId::of::<Fill>() => to_color(string).map(|color| TaggedValue::Fill(Fill::solid(color)))?,
x if x == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
_ => return None,
};
Some(ty)
+6 -6
View File
@@ -15,7 +15,7 @@ use graphene_core::{Ctx, GraphicElement, Node};
#[node_macro::node(category("Debug"))]
fn vector_points(_: impl Ctx, vector_data: VectorDataTable) -> Vec<DVec2> {
let vector_data = vector_data.one_instance().instance;
let vector_data = vector_data.one_instance_ref().instance;
vector_data.point_domain.positions().to_vec()
}
@@ -96,8 +96,8 @@ where
return target;
}
let target_width = target.one_instance().instance.width;
let target_height = target.one_instance().instance.height;
let target_width = target.one_instance_ref().instance.width;
let target_height = target.one_instance_ref().instance.height;
let target_size = DVec2::new(target_width as f64, target_height as f64);
let texture_size = DVec2::new(texture.width as f64, texture.height as f64);
@@ -122,7 +122,7 @@ where
let max_y = (blit_area_offset.y + blit_area_dimensions.y).saturating_sub(1);
let max_x = (blit_area_offset.x + blit_area_dimensions.x).saturating_sub(1);
assert!(texture_index(max_x, max_y) < texture.data.len());
assert!(target_index(max_x, max_y) < target.one_instance().instance.data.len());
assert!(target_index(max_x, max_y) < target.one_instance_ref().instance.data.len());
for y in blit_area_offset.y..blit_area_offset.y + blit_area_dimensions.y {
for x in blit_area_offset.x..blit_area_offset.x + blit_area_dimensions.x {
@@ -143,7 +143,7 @@ pub async fn create_brush_texture(brush_style: &BrushStyle) -> Image<Color> {
let blank_texture = empty_image((), transform, Color::TRANSPARENT);
let image = crate::raster::blend_image_closure(stamp, blank_texture, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
image.one_instance().instance.clone()
image.one_instance_ref().instance.clone()
}
macro_rules! inline_blend_funcs {
@@ -220,7 +220,7 @@ async fn brush(_: impl Ctx, image_frame_table: ImageFrameTable<Color>, bounds: I
let mut background_bounds = bbox.to_transform();
// If the bounds are empty (no size on images or det(transform) = 0), keep the target bounds
let bounds_empty = bounds.instances().all(|bounds| bounds.instance.width() == 0 || bounds.instance.height() == 0);
let bounds_empty = bounds.instance_ref_iter().all(|bounds| bounds.instance.width() == 0 || bounds.instance.height() == 0);
if bounds.transform().matrix2.determinant() != 0. && !bounds_empty {
background_bounds = bounds.transform();
}
+2 -2
View File
@@ -9,9 +9,9 @@ use std::cmp::{max, min};
#[node_macro::node(category("Raster"))]
async fn dehaze(_: impl Ctx, image_frame: ImageFrameTable<Color>, strength: Percentage) -> ImageFrameTable<Color> {
let image_frame_transform = image_frame.transform();
let image_frame_alpha_blending = image_frame.one_instance().alpha_blending;
let image_frame_alpha_blending = image_frame.one_instance_ref().alpha_blending;
let image = image_frame.one_instance().instance;
let image = image_frame.one_instance_ref().instance;
// Prepare the image data for processing
let image_data = bytemuck::cast_vec(image.data.clone());
+6 -6
View File
@@ -62,7 +62,7 @@ impl Clone for ComputePass {
#[node_macro::old_node_impl(MapGpuNode)]
async fn map_gpu<'a: 'input>(image: ImageFrameTable<Color>, node: DocumentNode, editor_api: &'a graphene_core::application_io::EditorApi<WasmApplicationIo>) -> ImageFrameTable<Color> {
let image_frame_table = &image;
let image = image.one_instance().instance;
let image = image.one_instance_ref().instance;
log::debug!("Executing gpu node");
let executor = &editor_api.application_io.as_ref().and_then(|io| io.gpu_executor()).unwrap();
@@ -113,7 +113,7 @@ async fn map_gpu<'a: 'input>(image: ImageFrameTable<Color>, node: DocumentNode,
};
let mut result = ImageFrameTable::new(new_image);
*result.transform_mut() = image_frame_table.transform();
*result.one_instance_mut().alpha_blending = *image_frame_table.one_instance().alpha_blending;
*result.one_instance_mut().alpha_blending = *image_frame_table.one_instance_ref().alpha_blending;
result
}
@@ -133,7 +133,7 @@ where
GraphicElement: From<Image<T>>,
T::Static: Pixel,
{
let image = image.one_instance().instance;
let image = image.one_instance_ref().instance;
let compiler = graph_craft::graphene_compiler::Compiler {};
let inner_network = NodeNetwork::value_network(node);
@@ -278,10 +278,10 @@ async fn blend_gpu_image(_: impl Ctx, foreground: ImageFrameTable<Color>, backgr
let foreground_transform = foreground.transform();
let background_transform = background.transform();
let background_alpha_blending = background.one_instance().alpha_blending;
let background_alpha_blending = background.one_instance_ref().alpha_blending;
let foreground = foreground.one_instance().instance;
let background = background.one_instance().instance;
let foreground = foreground.one_instance_ref().instance;
let background = background.one_instance_ref().instance;
let foreground_size = DVec2::new(foreground.width as f64, foreground.height as f64);
let background_size = DVec2::new(background.width as f64, background.height as f64);
+1 -1
View File
@@ -16,7 +16,7 @@ async fn image_color_palette(
let mut histogram: Vec<usize> = vec![0; (bins + 1.) as usize];
let mut colors: Vec<Vec<Color>> = vec![vec![]; (bins + 1.) as usize];
let image = image.one_instance().instance;
let image = image.one_instance_ref().instance;
for pixel in image.data.iter() {
let r = pixel.r() * GRID;
+4 -4
View File
@@ -29,9 +29,9 @@ impl From<std::io::Error> for Error {
#[node_macro::node(category("Debug: Raster"))]
fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: ImageFrameTable<Color>) -> ImageFrameTable<Color> {
let image_frame_transform = image_frame.transform();
let image_frame_alpha_blending = image_frame.one_instance().alpha_blending;
let image_frame_alpha_blending = image_frame.one_instance_ref().alpha_blending;
let image = image_frame.one_instance().instance;
let image = image_frame.one_instance_ref().instance;
// Resize the image using the image crate
let data = bytemuck::cast_vec(image.data.clone());
@@ -325,7 +325,7 @@ fn extend_image_to_bounds(image: ImageFrameTable<Color>, bounds: DAffine2) -> Im
return image;
}
let image_instance = image.one_instance().instance;
let image_instance = image.one_instance_ref().instance;
if image_instance.width == 0 || image_instance.height == 0 {
return empty_image((), bounds, Color::TRANSPARENT);
}
@@ -355,7 +355,7 @@ fn extend_image_to_bounds(image: ImageFrameTable<Color>, bounds: DAffine2) -> Im
let mut result = ImageFrameTable::new(new_img);
*result.transform_mut() = new_texture_to_layer_space;
*result.one_instance_mut().alpha_blending = *image.one_instance().alpha_blending;
*result.one_instance_mut().alpha_blending = *image.one_instance_ref().alpha_blending;
result
}
+14 -7
View File
@@ -1,10 +1,10 @@
use crate::vector::{VectorData, VectorDataTable};
use graph_craft::wasm_application_io::WasmEditorApi;
use graphene_core::Ctx;
use graphene_core::text::TypesettingConfig;
pub use graphene_core::text::{Font, FontCache, bounding_box, load_face, to_path};
pub use graphene_core::text::{Font, FontCache, bounding_box, load_face, to_group, to_path};
use graphene_core::{Ctx, GraphicGroupTable};
#[node_macro::node(category(""))]
#[node_macro::node(category("Text"))] // Changed category for clarity
fn text<'i: 'n>(
_: impl Ctx,
editor: &'i WasmEditorApi,
@@ -15,7 +15,9 @@ fn text<'i: 'n>(
#[default(1.)] character_spacing: f64,
#[default(None)] max_width: Option<f64>,
#[default(None)] max_height: Option<f64>,
) -> VectorDataTable {
#[default(false)] output_instances: bool, // Added parameter
) -> GraphicGroupTable {
// Changed return type
let buzz_face = editor.font_cache.get(&font_name).map(|data| load_face(data));
let typesetting = TypesettingConfig {
@@ -26,7 +28,12 @@ fn text<'i: 'n>(
max_height,
};
let result = VectorData::from_subpaths(to_path(&text, buzz_face, typesetting), false);
VectorDataTable::new(result)
if output_instances {
to_group(&text, buzz_face, typesetting)
} else {
let vector_data = VectorData::from_subpaths(to_path(&text, buzz_face, typesetting), false);
let vector_table = VectorDataTable::new(vector_data);
// Convert VectorDataTable into GraphicGroupTable
vector_table.into()
}
}
+10 -10
View File
@@ -14,11 +14,11 @@ use std::ops::Mul;
async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, operation: BooleanOperation) -> VectorDataTable {
fn flatten_vector_data(graphic_group_table: &GraphicGroupTable) -> Vec<VectorDataTable> {
graphic_group_table
.instances()
.instance_ref_iter()
.map(|element| match element.instance.clone() {
GraphicElement::VectorData(mut vector_data) => {
// Apply the parent group's transform to each element of vector data
for sub_vector_data in vector_data.instances_mut() {
for sub_vector_data in vector_data.instance_mut_iter() {
*sub_vector_data.transform = *element.transform * *sub_vector_data.transform;
}
@@ -28,12 +28,12 @@ async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, opera
// Apply the parent group's transform to each element of raster data
match &mut image {
graphene_core::RasterFrame::ImageFrame(image) => {
for instance in image.instances_mut() {
for instance in image.instance_mut_iter() {
*instance.transform = *element.transform * *instance.transform;
}
}
graphene_core::RasterFrame::TextureFrame(image) => {
for instance in image.instances_mut() {
for instance in image.instance_mut_iter() {
*instance.transform = *element.transform * *instance.transform;
}
}
@@ -50,7 +50,7 @@ async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, opera
}
GraphicElement::GraphicGroup(mut graphic_group) => {
// Apply the parent group's transform to each element of inner group
for sub_element in graphic_group.instances_mut() {
for sub_element in graphic_group.instance_mut_iter() {
*sub_element.transform = *element.transform * *sub_element.transform;
}
@@ -72,7 +72,7 @@ async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, opera
let result = result.one_instance_mut().instance;
let upper_path_string = to_path(result, DAffine2::IDENTITY);
let lower_path_string = to_path(lower_vector_data.one_instance().instance, transform_of_lower_into_space_of_upper);
let lower_path_string = to_path(lower_vector_data.one_instance_ref().instance, transform_of_lower_into_space_of_upper);
#[allow(unused_unsafe)]
let boolean_operation_string = unsafe { boolean_subtract(upper_path_string, lower_path_string) };
@@ -105,7 +105,7 @@ async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, opera
let result_vector_data = result_vector_data_table.one_instance_mut().instance;
let upper_path_string = to_path(result_vector_data, DAffine2::IDENTITY);
let lower_path_string = to_path(lower_vector_data.one_instance().instance, transform_of_lower_into_space_of_upper);
let lower_path_string = to_path(lower_vector_data.one_instance_ref().instance, transform_of_lower_into_space_of_upper);
#[allow(unused_unsafe)]
let boolean_operation_string = unsafe { boolean_union(upper_path_string, lower_path_string) };
@@ -136,7 +136,7 @@ async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, opera
let result = result.one_instance_mut().instance;
let upper_path_string = to_path(result, DAffine2::IDENTITY);
let lower_path_string = to_path(lower_vector_data.one_instance().instance, transform_of_lower_into_space_of_upper);
let lower_path_string = to_path(lower_vector_data.one_instance_ref().instance, transform_of_lower_into_space_of_upper);
#[allow(unused_unsafe)]
let boolean_operation_string = unsafe { boolean_intersect(upper_path_string, lower_path_string) };
@@ -160,12 +160,12 @@ async fn boolean_operation(_: impl Ctx, group_of_paths: GraphicGroupTable, opera
// Find where all vector data intersect at least once
while let Some(lower_vector_data) = second_vector_data {
let all_other_vector_data = boolean_operation_on_vector_data(&vector_data_table.iter().filter(|v| v != &lower_vector_data).cloned().collect::<Vec<_>>(), BooleanOperation::Union);
let all_other_vector_data_instance = all_other_vector_data.one_instance();
let all_other_vector_data_instance = all_other_vector_data.one_instance_ref();
let transform_of_lower_into_space_of_upper = all_other_vector_data.transform().inverse() * lower_vector_data.transform();
let upper_path_string = to_path(all_other_vector_data_instance.instance, DAffine2::IDENTITY);
let lower_path_string = to_path(lower_vector_data.one_instance().instance, transform_of_lower_into_space_of_upper);
let lower_path_string = to_path(lower_vector_data.one_instance_ref().instance, transform_of_lower_into_space_of_upper);
#[allow(unused_unsafe)]
let boolean_intersection_string = unsafe { boolean_intersect(upper_path_string, lower_path_string) };
+1 -1
View File
@@ -187,7 +187,7 @@ where
..Default::default()
};
for instance in data.instances_mut() {
for instance in data.instance_mut_iter() {
*instance.transform = DAffine2::from_translation(-aabb.start) * *instance.transform;
}
data.render_svg(&mut render, &render_params);
@@ -17,6 +17,7 @@ use graphene_std::GraphicElement;
use graphene_std::any::{ComposeTypeErased, DowncastBothNode, DynAnyNode, FutureWrapperNode, IntoTypeErasedNode};
use graphene_std::application_io::ImageTexture;
use graphene_std::wasm_application_io::*;
use node_registry_macros::{async_node, into_node};
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::Arc;
@@ -24,109 +25,27 @@ use std::sync::Arc;
use wgpu_executor::{ShaderInputFrame, WgpuExecutor};
use wgpu_executor::{WgpuSurface, WindowHandle};
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 {
(from: $from:ty, to: $to:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|mut args| {
Box::pin(async move {
args.reverse();
let node = graphene_core::ops::IntoNode::<$to>::new();
let any: DynAnyNode<$from, _, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::IntoNode::<$to>::new();
let mut node_io = NodeIO::<'_, $from>::to_async_node_io(&node, vec![]);
node_io.call_argument = future!(<$from as StaticType>::Static);
node_io
},
)
};
}
// TODO: turn into hashmap
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
let node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
// (
// ProtoNodeIdentifier::new("graphene_core::ops::IdentityNode"),
// |_| Box::pin(async move { FutureWrapperNode::new(IdentityNode::new()).into_type_erased() }),
// NodeIOTypes::new(generic!(I), generic!(I), vec![]),
// ),
// async_node!(graphene_core::ops::IntoNode<ImageFrameTable<SRGBA8>>, input: ImageFrameTable<Color>, params: []),
// async_node!(graphene_core::ops::IntoNode<ImageFrameTable<Color>>, input: ImageFrameTable<SRGBA8>, params: []),
into_node!(from: f64, to: f64),
into_node!(from: ImageFrameTable<Color>, to: GraphicGroupTable),
into_node!(from: f64,to: f64),
into_node!(from: u32,to: f64),
into_node!(from: u8,to: u32),
into_node!(from: ImageFrameTable<Color>,to: GraphicGroupTable),
into_node!(from: VectorDataTable,to: GraphicGroupTable),
#[cfg(feature = "gpu")]
into_node!(from: &WasmEditorApi,to: &WgpuExecutor),
into_node!(from: VectorDataTable,to: GraphicElement),
into_node!(from: ImageFrameTable<Color>,to: GraphicElement),
into_node!(from: GraphicGroupTable,to: GraphicElement),
into_node!(from: VectorDataTable,to: GraphicGroupTable),
into_node!(from: ImageFrameTable<Color>,to: GraphicGroupTable),
into_node!(from: f64, to: f64),
into_node!(from: u32, to: f64),
into_node!(from: u8, to: u32),
into_node!(from: ImageFrameTable<Color>, to: GraphicGroupTable),
into_node!(from: VectorDataTable, to: GraphicGroupTable),
into_node!(from: VectorDataTable, to: GraphicElement),
into_node!(from: ImageFrameTable<Color>, to: GraphicElement),
into_node!(from: GraphicGroupTable, to: GraphicElement),
into_node!(from: VectorDataTable, to: GraphicGroupTable),
into_node!(from: ImageFrameTable<Color>, to: GraphicGroupTable),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ImageFrameTable<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ImageTexture]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => VectorDataTable]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => GraphicElement]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Artboard]),
#[cfg(feature = "gpu")]
(
ProtoNodeIdentifier::new(stringify!(wgpu_executor::CreateGpuSurfaceNode<_>)),
|args| {
Box::pin(async move {
let editor_api: DowncastBothNode<Context, &WasmEditorApi> = DowncastBothNode::new(args[0].clone());
let node = <wgpu_executor::CreateGpuSurfaceNode<_>>::new(editor_api);
let any: DynAnyNode<Context, _, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = <wgpu_executor::CreateGpuSurfaceNode<_>>::new(graphene_std::any::PanicNode::<Context, dyn_any::DynFuture<'static, &WasmEditorApi>>::new());
let params = vec![fn_type_fut!(Context, &WasmEditorApi)];
let mut node_io = <wgpu_executor::CreateGpuSurfaceNode<_> as NodeIO<'_, Context>>::to_async_node_io(&node, params);
node_io.call_argument = concrete!(<Context as StaticType>::Static);
node_io
},
),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_core::RasterFrame]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_core::instances::Instances<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => String]),
@@ -135,9 +54,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
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 => ()]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Vec<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => BlendMode]),
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_core::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<graphene_core::Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_core::vector::style::Fill]),
@@ -149,40 +70,27 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Vec<graphene_core::uuid::NodeId>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_core::Color]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_core::vector::VectorModification>]),
#[cfg(feature = "gpu")]
(
ProtoNodeIdentifier::new("graphene_std::executor::MapGpuSingleImageNode"),
|args| {
Box::pin(async move {
let document_node: DowncastBothNode<(), graph_craft::document::DocumentNode> = DowncastBothNode::new(args[0].clone());
let editor_api: DowncastBothNode<(), &WasmEditorApi> = DowncastBothNode::new(args[1].clone());
let node = graphene_std::gpu_nodes::MapGpuNode::new(document_node, editor_api);
let any: DynAnyNode<ImageFrameTable<Color>, _, _> = graphene_std::any::DynAnyNode::new(node);
any.into_type_erased()
})
},
NodeIOTypes::new(
concrete!(ImageFrameTable<Color>),
concrete!(ImageFrameTable<Color>),
vec![fn_type!(graph_craft::document::DocumentNode), fn_type!(WasmEditorApi)],
),
),
(
ProtoNodeIdentifier::new("graphene_core::structural::ComposeNode"),
|args| {
Box::pin(async move {
let node = ComposeTypeErased::new(args[0].clone(), args[1].clone());
node.into_type_erased()
})
},
// This is how we can generically define composition of two nodes.
// See further details in the code definition for the `struct ComposeNode<First, Second, I> { ... }` struct.
NodeIOTypes::new(
generic!(T),
generic!(U),
vec![Type::Fn(Box::new(generic!(T)), Box::new(generic!(V))), Type::Fn(Box::new(generic!(V)), Box::new(generic!(U)))],
),
),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => VectorDataTable]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => ImageFrameTable<Color>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Vec<DVec2>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Arc<WasmSurfaceHandle>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => WindowHandle]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Option<wgpu_executor::WgpuSurface>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WindowHandle]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => graphene_std::SurfaceFrame]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: UVec2, fn_params: [UVec2 => graphene_std::SurfaceFrame]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => GraphicElement]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => VectorDataTable]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => WgpuSurface]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => Option<WgpuSurface>]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => ImageTexture]),
// Filters
// TODO: Move these filters to the new node macro and put them in `graphene_core::raster::adjustments`, then add them to the document upgrade script which moves many of the adjustment nodes from `graphene_core::raster` to `graphene_core::raster::adjustments`
(
@@ -214,118 +122,77 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
},
NodeIOTypes::new(concrete!(ImageFrameTable<Color>), concrete!(ImageFrameTable<Color>), vec![fn_type!(f64), fn_type!(f64), fn_type!(bool)]),
),
// (
// ProtoNodeIdentifier::new("graphene_core::raster::CurvesNode"),
// |args| {
// use graphene_core::raster::curve::Curve;
// use graphene_core::raster::GenerateCurvesNode;
// let curve: DowncastBothNode<(), Curve> = DowncastBothNode::new(args[0].clone());
// Box::pin(async move {
// let curve = ClonedNode::new(curve.eval(()).await);
// let generate_curves_node = GenerateCurvesNode::new(curve, ClonedNode::new(0_f32));
// let map_image_frame_node = graphene_std::raster::MapImageNode::new(ValueNode::new(generate_curves_node.eval(())));
// let map_image_frame_node = FutureWrapperNode::new(map_image_frame_node);
// let any: DynAnyNode<ImageFrameTable<Luma>, _, _> = graphene_std::any::DynAnyNode::new(map_image_frame_node);
// any.into_type_erased()
// })
// },
// NodeIOTypes::new(concrete!(ImageFrameTable<Luma>), concrete!(ImageFrameTable<Luma>), vec![fn_type!(graphene_core::raster::curve::Curve)]),
// ),
// TODO: Use channel split and merge for this instead of using LuminanceMut for the whole color.
// (
// ProtoNodeIdentifier::new("graphene_core::raster::CurvesNode"),
// |args| {
// use graphene_core::raster::curve::Curve;
// use graphene_core::raster::GenerateCurvesNode;
// let curve: DowncastBothNode<(), Curve> = DowncastBothNode::new(args[0].clone());
// Box::pin(async move {
// let curve = ValueNode::new(ClonedNode::new(curve.eval(()).await));
// let generate_curves_node = GenerateCurvesNode::new(FutureWrapperNode::new(curve), FutureWrapperNode::new(ClonedNode::new(0_f32)));
// let map_image_frame_node = graphene_std::raster::MapImageNode::new(FutureWrapperNode::new(ValueNode::new(generate_curves_node.eval(()))));
// let map_image_frame_node = FutureWrapperNode::new(map_image_frame_node);
// let any: DynAnyNode<ImageFrameTable<Color>, _, _> = graphene_std::any::DynAnyNode::new(map_image_frame_node);
// any.into_type_erased()
// })
// },
// NodeIOTypes::new(
// concrete!(ImageFrameTable<Color>),
// concrete!(ImageFrameTable<Color>),
// vec![fn_type!(graphene_core::raster::curve::Curve)],
// ),
// ),
// (
// ProtoNodeIdentifier::new("graphene_std::raster::ImaginateNode"),
// |args: Vec<graph_craft::proto::SharedNodeContainer>| {
// Box::pin(async move {
// use graphene_std::raster::ImaginateNode;
// macro_rules! instantiate_imaginate_node {
// ($($i:expr,)*) => { ImaginateNode::new($(graphene_std::any::input_node(args[$i].clone()),)* ) };
// }
// let node: ImaginateNode<Color, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _> = instantiate_imaginate_node!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
// let any = graphene_std::any::DynAnyNode::new(node);
// any.into_type_erased()
// })
// },
// NodeIOTypes::new(
// concrete!(ImageFrameTable<Color>),
// concrete!(ImageFrameTable<Color>),
// vec![
// fn_type!(&WasmEditorApi),
// fn_type!(ImaginateController),
// fn_type!(f64),
// fn_type!(Option<DVec2>),
// fn_type!(u32),
// fn_type!(ImaginateSamplingMethod),
// fn_type!(f64),
// fn_type!(String),
// fn_type!(String),
// fn_type!(bool),
// fn_type!(f64),
// fn_type!(bool),
// fn_type!(f64),
// fn_type!(ImaginateMaskStartingFill),
// fn_type!(bool),
// fn_type!(bool),
// fn_type!(u64),
// ],
// ),
// ),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => VectorDataTable]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => ImageFrameTable<Color>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Vec<DVec2>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Arc<WasmSurfaceHandle>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => WindowHandle]),
(
ProtoNodeIdentifier::new("graphene_core::structural::ComposeNode"),
|args| {
Box::pin(async move {
let node = ComposeTypeErased::new(args[0].clone(), args[1].clone());
node.into_type_erased()
})
},
// This is how we can generically define composition of two nodes.
// See further details in the code definition for the `struct ComposeNode<First, Second, I> { ... }` struct.
NodeIOTypes::new(
generic!(T),
generic!(U),
vec![Type::Fn(Box::new(generic!(T)), Box::new(generic!(V))), Type::Fn(Box::new(generic!(V)), Box::new(generic!(U)))],
),
),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => ShaderInputFrame]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuSurface]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Option<wgpu_executor::WgpuSurface>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WindowHandle]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => graphene_std::SurfaceFrame]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: UVec2, fn_params: [UVec2 => graphene_std::SurfaceFrame]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => GraphicElement]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => VectorDataTable]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => GraphicGroupTable]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => ShaderInputFrame]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => WgpuSurface]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => Option<WgpuSurface>]),
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => ImageTexture]),
#[cfg(feature = "gpu")]
into_node!(from: &WasmEditorApi, to: &WgpuExecutor),
#[cfg(feature = "gpu")]
(
ProtoNodeIdentifier::new("graphene_std::executor::MapGpuSingleImageNode"),
|args| {
Box::pin(async move {
let document_node: DowncastBothNode<(), graph_craft::document::DocumentNode> = DowncastBothNode::new(args[0].clone());
let editor_api: DowncastBothNode<(), &WasmEditorApi> = DowncastBothNode::new(args[1].clone());
let node = graphene_std::gpu_nodes::MapGpuNode::new(document_node, editor_api);
let any: DynAnyNode<ImageFrameTable<Color>, _, _> = graphene_std::any::DynAnyNode::new(node);
any.into_type_erased()
})
},
NodeIOTypes::new(
concrete!(ImageFrameTable<Color>),
concrete!(ImageFrameTable<Color>),
vec![fn_type!(graph_craft::document::DocumentNode), fn_type!(WasmEditorApi)],
),
),
#[cfg(feature = "gpu")]
(
ProtoNodeIdentifier::new(stringify!(wgpu_executor::CreateGpuSurfaceNode<_>)),
|args| {
Box::pin(async move {
let editor_api: DowncastBothNode<Context, &WasmEditorApi> = DowncastBothNode::new(args[0].clone());
let node = <wgpu_executor::CreateGpuSurfaceNode<_>>::new(editor_api);
let any: DynAnyNode<Context, _, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = <wgpu_executor::CreateGpuSurfaceNode<_>>::new(graphene_std::any::PanicNode::<Context, dyn_any::DynFuture<'static, &WasmEditorApi>>::new());
let params = vec![fn_type_fut!(Context, &WasmEditorApi)];
let mut node_io = <wgpu_executor::CreateGpuSurfaceNode<_> as NodeIO<'_, Context>>::to_async_node_io(&node, params);
node_io.call_argument = concrete!(<Context as StaticType>::Static);
node_io
},
),
];
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
for (id, entry) in graphene_core::registry::NODE_REGISTRY.lock().unwrap().iter() {
for (constructor, types) in entry.iter() {
map.entry(id.clone().into()).or_default().insert(types.clone(), *constructor);
}
}
for (id, c, types) in node_types.into_iter() {
// TODO: this is a hack to remove the newline from the node new_name
// This occurs for the ChannelMixerNode presumably because of the long name.
@@ -340,12 +207,67 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
let nid = ProtoNodeIdentifier { name: Cow::Owned(new_name) };
map.entry(nid).or_default().insert(types.clone(), c);
}
map
}
pub static NODE_REGISTRY: Lazy<HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>> = Lazy::new(|| node_registry());
#[cfg(test)]
mod protograph_testing {
// TODO: add tests testing the node registry
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 {
(from: $from:ty, to: $to:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|mut args| {
Box::pin(async move {
args.reverse();
let node = graphene_core::ops::IntoNode::<$to>::new();
let any: DynAnyNode<$from, _, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = graphene_core::ops::IntoNode::<$to>::new();
let mut node_io = NodeIO::<'_, $from>::to_async_node_io(&node, vec![]);
node_io.call_argument = future!(<$from as StaticType>::Static);
node_io
},
)
};
}
pub(crate) use async_node;
pub(crate) use into_node;
}
@@ -0,0 +1,80 @@
//! This has all been copied out of node_registry.rs to avoid leaving many lines of commented out code in that file. It's left here instead for future reference.
// (
// ProtoNodeIdentifier::new("graphene_core::raster::CurvesNode"),
// |args| {
// use graphene_core::raster::curve::Curve;
// use graphene_core::raster::GenerateCurvesNode;
// let curve: DowncastBothNode<(), Curve> = DowncastBothNode::new(args[0].clone());
// Box::pin(async move {
// let curve = ClonedNode::new(curve.eval(()).await);
// let generate_curves_node = GenerateCurvesNode::new(curve, ClonedNode::new(0_f32));
// let map_image_frame_node = graphene_std::raster::MapImageNode::new(ValueNode::new(generate_curves_node.eval(())));
// let map_image_frame_node = FutureWrapperNode::new(map_image_frame_node);
// let any: DynAnyNode<ImageFrameTable<Luma>, _, _> = graphene_std::any::DynAnyNode::new(map_image_frame_node);
// any.into_type_erased()
// })
// },
// NodeIOTypes::new(concrete!(ImageFrameTable<Luma>), concrete!(ImageFrameTable<Luma>), vec![fn_type!(graphene_core::raster::curve::Curve)]),
// ),
// TODO: Use channel split and merge for this instead of using LuminanceMut for the whole color.
// (
// ProtoNodeIdentifier::new("graphene_core::raster::CurvesNode"),
// |args| {
// use graphene_core::raster::curve::Curve;
// use graphene_core::raster::GenerateCurvesNode;
// let curve: DowncastBothNode<(), Curve> = DowncastBothNode::new(args[0].clone());
// Box::pin(async move {
// let curve = ValueNode::new(ClonedNode::new(curve.eval(()).await));
// let generate_curves_node = GenerateCurvesNode::new(FutureWrapperNode::new(curve), FutureWrapperNode::new(ClonedNode::new(0_f32)));
// let map_image_frame_node = graphene_std::raster::MapImageNode::new(FutureWrapperNode::new(ValueNode::new(generate_curves_node.eval(()))));
// let map_image_frame_node = FutureWrapperNode::new(map_image_frame_node);
// let any: DynAnyNode<ImageFrameTable<Color>, _, _> = graphene_std::any::DynAnyNode::new(map_image_frame_node);
// any.into_type_erased()
// })
// },
// NodeIOTypes::new(
// concrete!(ImageFrameTable<Color>),
// concrete!(ImageFrameTable<Color>),
// vec![fn_type!(graphene_core::raster::curve::Curve)],
// ),
// ),
// (
// ProtoNodeIdentifier::new("graphene_std::raster::ImaginateNode"),
// |args: Vec<graph_craft::proto::SharedNodeContainer>| {
// Box::pin(async move {
// use graphene_std::raster::ImaginateNode;
// macro_rules! instantiate_imaginate_node {
// ($($i:expr,)*) => { ImaginateNode::new($(graphene_std::any::input_node(args[$i].clone()),)* ) };
// }
// let node: ImaginateNode<Color, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _> = instantiate_imaginate_node!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
// let any = graphene_std::any::DynAnyNode::new(node);
// any.into_type_erased()
// })
// },
// NodeIOTypes::new(
// concrete!(ImageFrameTable<Color>),
// concrete!(ImageFrameTable<Color>),
// vec![
// fn_type!(&WasmEditorApi),
// fn_type!(ImaginateController),
// fn_type!(f64),
// fn_type!(Option<DVec2>),
// fn_type!(u32),
// fn_type!(ImaginateSamplingMethod),
// fn_type!(f64),
// fn_type!(String),
// fn_type!(String),
// fn_type!(bool),
// fn_type!(f64),
// fn_type!(bool),
// fn_type!(f64),
// fn_type!(ImaginateMaskStartingFill),
// fn_type!(bool),
// fn_type!(bool),
// fn_type!(u64),
// ],
// ),
// ),
+1 -1
View File
@@ -913,7 +913,7 @@ async fn render_texture<'a: 'n>(
async fn upload_texture<'a: 'n>(_: impl ExtractFootprint + Ctx, input: ImageFrameTable<Color>, executor: &'a WgpuExecutor) -> ImageTexture {
// let new_data: Vec<RGBA16F> = input.image.data.into_iter().map(|c| c.into()).collect();
let input = input.one_instance().instance;
let input = input.one_instance_ref().instance;
let new_data: Vec<SRGBA8> = input.data.iter().map(|x| (*x).into()).collect();
let new_image = Image {
width: input.width,
+3 -3
View File
@@ -192,7 +192,7 @@ Stop jumping between programs. Upcoming tools will make Graphite a first-class c
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 15" src="https://static.graphite.rs/icons/icon-atlas-features__2.png" alt="" />
<span>Desktop Publishing</span>
<span>Page Layout & Print</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 16" src="https://static.graphite.rs/icons/icon-atlas-features__2.png" alt="" />
@@ -261,11 +261,11 @@ Presently, Graphite is a lightweight offline web app with features primarily ori
## Desktop-first and web-ready
Where's the download? The web app is [currently live](https://editor.graphite.rs) and desktop apps for Windows, Mac, and Linux should be available in early 2025.
Where's the download? The web app is [currently live](https://editor.graphite.rs) and desktop apps for Windows, Mac, and Linux should be available in 2025.
Graphite is designed principally as a professional desktop application that is also accessible in a browser for quick, casual usage. It's built for speed with (nearly) no JavaScript. And regardless of platform, your work runs locally and privately on your own hardware. There is no server.
Engineering the tech for a native app distributed across three new platforms takes extra time. That's why supporting the web platform, which keeps up-to-date and reaches all devices, has been the initial target. For now, you can <a href="https://support.google.com/chrome/answer/9658361" target="_blank">install the app as a PWA</a> for a desktop-like experience.
<a href="https://github.com/GraphiteEditor/Graphite/issues/2535" target="_blank">Engineering the tech</a> for a native app distributed across three new platforms takes extra time. That's why supporting the web platform, which keeps up-to-date and reaches all devices, has been the initial target. For now, you can <a href="https://support.google.com/chrome/answer/9658361" target="_blank">install the app as a PWA</a> for a desktop-like experience.
Once it's ready to shine, Graphite's code architecture is structured to deliver native performance for your graphically intensive workloads on desktop platforms and very low overhead on the web thanks to WebAssembly and WebGPU, new high-performance browser technologies.
+5 -5
View File
@@ -8,11 +8,9 @@ css = ["/page/donate.css", "/component/feature-box.css"]
<section>
<div class="block">
# Support Graphite
# Funding creativity, not corporations
**Safeguard the sustainable, independent future of quality open source creative software.**
Graphite is 100% built and funded by the community. Your contributions directly help us level up the scope and speed of the project's development. Resources are put towards infrastructure, legal costs, swag to keep contributors happy and motivated, and outreach like exhibiting at conventions and traveling to conferences to foster industry relationships. Hiring full-time developers is the big next step as support grows.
**Own your tools. Own your art.** Invest in the sustainable, independent future of high-quality creative software that's free, and always will be.
<p class="call-to-action">
@@ -23,11 +21,13 @@ Graphite is 100% built and funded by the community. Your contributions directly
<span>
<a href="#supporter-memberships" class="button arrow">Donate: without an account</a>
<em>Be done in just a few clicks</em>
<em>Start to finish in several seconds</em>
</span>
</p>
Graphite is 100% built and funded by the community. Your contributions directly help us level up the scope and speed of the project's development. Resources are put towards infrastructure, operational costs, swag to keep contributors happy and motivated, and outreach like exhibiting at conventions and traveling to conferences to foster industry relationships. Hiring full-time developers is the next crucial milestone.
</div>
</section>
+46 -42
View File
@@ -10,9 +10,9 @@ css = ["/page/features.css", "/component/feature-box.css", "/component/feature-i
# Graphite features
The current alpha version of Graphite is a tool for vector art and graphic design. It also supports a limited, experimental raster editing toolset. All this is built around a central node graph that stores layer data and provides a basic—but continually improving—procedural design and nondestructive editing workflow which is a unique feature among vector editing software.
The current alpha version of Graphite is a tool for vector art and graphic design. It also supports a limited, experimental raster editing toolset. This tooling is built around a procedural graphics engine, letting artists build complex graphics and animations in its visual scripting language.
Throughout 2025, stay tuned for major performance improvements, a multiplatform desktop app with native rendering speed, and the beginnings of a full suite of raster editing tools.
In 2025, stay tuned for performance improvements, native multiplatform desktop apps, and the beginnings of a full raster editing tool suite.
</div>
</section>
@@ -125,45 +125,53 @@ Always on the bleeding edge and built to last— Graphite is written on a robust
<div class="feature-icon ongoing heading" title="Began February 2025" data-year="2025">
<h3>— Alpha 4 —</h3>
</div>
<div class="feature-icon ongoing">
<img class="atlas" style="--atlas-index: 8" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Lambda nodes</span>
<div class="feature-icon complete" title="Development Complete">
<img class="atlas" style="--atlas-index: 46" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Parametric animation</span>
</div>
<div class="feature-icon ongoing">
<div class="feature-icon complete" title="Development Complete">
<img class="atlas" style="--atlas-index: 1" src="https://static.graphite.rs/icons/icon-atlas-features__2.png" alt="" />
<span>Instancer repeat nodes</span>
</div>
<div class="feature-icon ongoing" title="Development Ongoing">
<img class="atlas" style="--atlas-index: 9" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Graph data attribute spreadsheets</span>
</div>
<div class="feature-icon ongoing">
<div class="feature-icon ongoing" title="Development Ongoing">
<img class="atlas" style="--atlas-index: 48" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Robust vector mesh editing/rendering</span>
</div>
<div class="feature-icon ongoing" title="Development Ongoing">
<img class="atlas" style="--atlas-index: 7" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Lightweight desktop app (with <a target="_blank" href="https://tauri.app/">Tauri</a>)</span>
<span>Desktop app (Windows, Mac, Linux)</span>
</div>
<div class="feature-icon">
<div class="feature-icon ongoing">
<img class="atlas" style="--atlas-index: 40" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Contextual properties panel</span>
<span>Simplified main properties panel</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 18" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Node versioning</span>
</div>
<div class="feature-icon" title="Development Ongoing">
<img class="atlas" style="--atlas-index: 14" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Infinitely zoomable/panable content</span>
</div>
<div class="feature-icon" title="Development Ongoing">
<img class="atlas" style="--atlas-index: 12" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>GPU-accelerated raster rendering</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 54" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Local file browser for saving/loading</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 53" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Local fonts access</span>
<img class="atlas" style="--atlas-index: 14" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Infinitely zoomable/panable content</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 41" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Timeline with animation channels</span>
<span>Timeline panel for animation curves</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 18" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Node version management</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 5" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Brush tool rewrite</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 57" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Signed distance fields</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 56" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
@@ -173,26 +181,26 @@ Always on the bleeding edge and built to last— Graphite is written on a robust
<img class="atlas" style="--atlas-index: 52" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Command palette and context menus</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 21" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Select mode (marquee masking)</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 53" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Local fonts access</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 54" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Local file browser for saving/loading</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 19" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Raw photo processing</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 57" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Signed distance fields</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 43" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Stylus and touch interaction</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 5" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Brush tool rewrite</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 21" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Select mode (marquee masking)</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 24" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Dockable workspace panels</span>
@@ -217,10 +225,6 @@ Always on the bleeding edge and built to last— Graphite is written on a robust
<img class="atlas" style="--atlas-index: 49" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>AI nodes and tools (e.g. magic wand)</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 48" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>NURBS and mesh vector formats</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 25" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<span>Liquify and non-affine transforms</span>
@@ -318,7 +322,7 @@ Always on the bleeding edge and built to last— Graphite is written on a robust
<span>Offline edit resolution with CRDTs</span>
</div>
<div class="feature-icon">
<img class="atlas" style="--atlas-index: 46" src="https://static.graphite.rs/icons/icon-atlas-roadmap__3.png" alt="" />
<img class="atlas" style="--atlas-index: 16" src="https://static.graphite.rs/icons/icon-atlas-features__2.png" alt="" />
<span>Animated SVG creation</span>
</div>
<div class="feature-icon">
+1 -1
View File
@@ -8,7 +8,7 @@ css = ["/page/volunteer.css", "/component/feature-box.css"]
<section>
<div class="block">
# Volunteer
# Get involved
**Graphite is 100% built by volunteers.** Get involved in the effort to bring great, free creative software to the world.
+18
View File
@@ -148,6 +148,24 @@ body > .page {
font-size: 0;
}
.heart.heart {
// The same color is also used below in the SVG after the `%23` (URL-encoded `#`)
color: #cc304f;
&::after {
content: "";
background-image: url('data:image/svg+xml;utf8,\
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M8,15C5.12471,9.753694 0.5,8.795225 0.5,4.736524 C0.5,-0.507473 7.468734,0 8,4.967381 C8.531266,0 15.5,-0.507473 15.5,4.736524 C15.5,8.795225 10.87529,9.753694 8,15z" fill="%23cc304f" /></svg>\
');
display: inline-block;
width: 0.75em;
height: 0.75em;
margin-left: 0.25em;
margin-bottom: -0.1em;
vertical-align: baseline;
}
}
@media screen and (max-width: 1200px) {
gap: 30px;
--height: 50px;
+1 -1
View File
@@ -107,7 +107,7 @@
<a href="/about">About</a>
<a href="/blog">Blog</a>
<a href="/volunteer">Volunteer</a>
<a href="/donate">Donate</a>
<a href="/donate" class="heart">Donate</a>
<a href="https://editor.graphite.rs" class="button arrow">Launch</a>
</div>
</div>