-
Notifications
You must be signed in to change notification settings - Fork 878
Expand file tree
/
Copy pathVFXView.cs
More file actions
3491 lines (3003 loc) · 136 KB
/
Copy pathVFXView.cs
File metadata and controls
3491 lines (3003 loc) · 136 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEditor.Experimental;
using UnityEditor.Experimental.GraphView;
using UnityEditor.Toolbars;
using UnityEditor.VersionControl;
using UnityEngine;
using UnityEngine.VFX;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEngine.Profiling;
using PositionType = UnityEngine.UIElements.Position;
using Task = UnityEditor.VersionControl.Task;
namespace UnityEditor.VFX.UI
{
/// <summary>
/// Unexpected public API VFXViewModicationProcessor : Use a custom UnityEditor.AssetModificationProcessor.
/// </summary>
[Obsolete("Unexpected public API VFXViewModicationProcessor : Use a custom UnityEditor.AssetModificationProcessor")]
public class VFXViewModicationProcessor : UnityEditor.AssetModificationProcessor
{
/// <summary>
/// Initialized to false by default.
/// Obsolete API : Use a custom UnityEditor.AssetModificationProcessor and implement OnWillMoveAsset if you relied on this behavior.
/// </summary>
public static bool assetMoved = false;
}
class VFXViewModificationProcessor : UnityEditor.AssetModificationProcessor
{
public static bool assetMoved = false;
private static AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath)
{
assetMoved = true;
return AssetMoveResult.DidNotMove;
}
}
class EdgeDragInfo : VisualElement
{
VFXView m_View;
public EdgeDragInfo(VFXView view)
{
m_View = view;
var tpl = Resources.Load<VisualTreeAsset>("uxml/EdgeDragInfo");
tpl.CloneTree(this);
this.AddStyleSheetPath("EdgeDragInfo");
m_Text = this.Q<Label>("title");
pickingMode = PickingMode.Ignore;
m_Text.pickingMode = PickingMode.Ignore;
}
Label m_Text;
public void StartEdgeDragInfo(VFXDataAnchor draggedAnchor, VFXDataAnchor overAnchor)
{
string error = null;
if (draggedAnchor != overAnchor)
{
if (draggedAnchor.direction == overAnchor.direction)
{
if (draggedAnchor.direction == Direction.Input)
error = "You must link an input to an output";
else
error = "You must link an output to an input";
}
else if (draggedAnchor.controller.connections.Any(t => draggedAnchor.direction == Direction.Input ? t.output == overAnchor.controller : t.input == overAnchor.controller))
{
error = "An edge with the same input and output already exists";
}
else if (!draggedAnchor.controller.model.CanLink(overAnchor.controller.model))
{
error = "The input and output have incompatible types";
}
else
{
bool can = draggedAnchor.controller.CanLink(overAnchor.controller);
if (!can)
{
if (!draggedAnchor.controller.CanLinkToNode(overAnchor.controller.sourceNode, null))
error = "The edge would create a loop in the operators";
else
error = "Link impossible for an unknown reason";
}
}
}
if (error == null)
style.display = DisplayStyle.None;
else
m_Text.text = error;
var layout = overAnchor.connector.parent.ChangeCoordinatesTo(m_View, overAnchor.connector.layout);
style.top = layout.yMax + 16;
style.left = layout.xMax;
}
}
struct VFXViewSettings
{
private bool m_IsAttachedLocked;
private VisualEffect m_AttachedVisualEffect;
public void Load(bool force = false)
{
m_IsAttachedLocked = EditorPrefs.GetBool(nameof(m_IsAttachedLocked));
if (EditorApplication.isPlaying || force)
{
var attachedVisualEffectPath = EditorPrefs.GetString(nameof(m_AttachedVisualEffect));
if (!string.IsNullOrEmpty(attachedVisualEffectPath))
{
var go = GameObject.Find(attachedVisualEffectPath);
if (go != null)
{
m_AttachedVisualEffect = go.GetComponent<VisualEffect>();
}
}
}
}
public VisualEffect AttachedVisualEffect
{
get => m_AttachedVisualEffect;
set
{
m_AttachedVisualEffect = value;
if (!EditorApplication.isPlaying)
{
if (m_AttachedVisualEffect != null)
{
var go = m_AttachedVisualEffect.gameObject;
var path = go.GetComponentsInParent<UnityEngine.Transform>()
.Select(x => x.name)
.Reverse()
.ToArray();
EditorPrefs.SetString(nameof(m_AttachedVisualEffect), "/" + string.Join('/', path));
}
else
{
EditorPrefs.SetString(nameof(m_AttachedVisualEffect), null);
}
}
}
}
public bool AttachedLocked
{
get => m_IsAttachedLocked;
set
{
m_IsAttachedLocked = value;
EditorPrefs.SetBool(nameof(m_IsAttachedLocked), m_IsAttachedLocked);
}
}
}
class VFXView : GraphView, IControlledElement<VFXViewController>, IControllerListener, IDisposable
{
private const int MaximumNameLengthInNotification = 128;
private const float GrayedOutGraphOpacity = 0.6f;
private const string AttachGameObjectLabel = "attach-toolbar-button";
private const string LockAutoAttachLabel = "lock-auto-attach";
// Only changed in aut test to avoid dialog box
public bool askForConfirmationBeforeDelete = true;
internal static class Contents
{
public static readonly GUIContent clickToUnlock = EditorGUIUtility.TrTextContent("Click to enable auto-attachment to selection");
public static readonly GUIContent clickToLock = EditorGUIUtility.TrTextContent("Click to disable auto-attachment to selection");
public static readonly GUIContent attachedToGameObject = EditorGUIUtility.TrTextContent("Attached to {0}");
public static readonly GUIContent notAttached = EditorGUIUtility.TrTextContent("Select a Game Object running this VFX to attach it");
}
private static readonly List<string> ToolbarElementsToDisableWhenNoAsset = new ()
{
nameof(VFXSaveDropdownButton),
nameof(VFXCompileDropdownButton),
AttachGameObjectLabel,
LockAutoAttachLabel,
nameof(VFXVCSDropdownButton),
nameof(CreateFromTemplateDropDownButton)
};
public readonly HashSet<VFXEditableDataAnchor> allDataAnchors = new HashSet<VFXEditableDataAnchor>();
public readonly VFXErrorManager errorManager;
public bool locked => m_VFXSettings.AttachedLocked;
void IControllerListener.OnControllerEvent(ControllerEvent e)
{
if (e is VFXRecompileEvent)
{
var recompileEvent = e as VFXRecompileEvent;
foreach (var anchor in allDataAnchors)
{
anchor.OnRecompile(recompileEvent.valueOnly);
}
}
}
VFXViewSettings m_VFXSettings;
VisualElement m_NoAssetElement;
VisualElement m_LockedElement;
Button m_BackButton;
Vector2 m_pastCenter;
VFXViewController m_Controller;
Controller IControlledElement.controller
{
get { return m_Controller; }
}
void DisconnectController(VFXViewController previousController)
{
if (previousController.model && previousController.graph)
{
previousController.graph.ForceShaderDebugSymbols(VFXViewPreference.generateShadersWithDebugSymbols, false); // Remove debug symbols override from view but don't reimport (this is done by the SetCompilation below)
previousController.graph.SetCompilationMode(VFXViewPreference.forceEditionCompilation ? VFXCompilationMode.Edition : VFXCompilationMode.Runtime);
}
previousController.UnregisterHandler(this);
previousController.useCount--;
serializeGraphElements = null;
unserializeAndPaste = null;
deleteSelection = null;
nodeCreationRequest = null;
elementsAddedToGroup = null;
elementsRemovedFromGroup = null;
groupTitleChanged = null;
m_GeometrySet = false;
// Remove all in view now that the controller has been disconnected.
foreach (var element in rootGroupNodeElements.Values)
{
RemoveElement(element);
}
foreach (var element in groupNodes.Values)
{
RemoveElement(element);
}
foreach (var element in dataEdges.Values)
{
RemoveElement(element);
}
foreach (var element in flowEdges.Values)
{
RemoveElement(element);
}
foreach (var system in m_Systems)
{
RemoveElement(system);
}
groupNodes.Clear();
stickyNotes.Clear();
rootNodes.Clear();
rootGroupNodeElements.Clear();
m_Systems.Clear();
VFXExpression.ClearCache();
m_NodeProvider = null;
if (Provider.enabled && !IsOffline())
{
m_VCSDropDown.SetStatus(Asset.States.None);
}
SceneView.duringSceneGui -= OnSceneGUI;
OnFocus();
}
void ConnectController()
{
schedule.Execute(() =>
{
if (controller != null && controller.graph)
controller.graph.SetCompilationMode(m_IsRuntimeMode ? VFXCompilationMode.Runtime : VFXCompilationMode.Edition);
}).ExecuteLater(1);
m_Controller.RegisterHandler(this);
m_Controller.useCount++;
serializeGraphElements = SerializeElements;
unserializeAndPaste = UnserializeAndPasteElements;
deleteSelection = Delete;
nodeCreationRequest = OnCreateNode;
elementsAddedToGroup = ElementAddedToGroupNode;
elementsRemovedFromGroup = ElementRemovedFromGroupNode;
groupTitleChanged = GroupNodeTitleChanged;
m_NodeProvider = new VFXNodeProvider(controller, (d, mPos) => AddNode(d, mPos), null, GetAcceptedTypeNodes());
//Make sure a subgraph block as a block subgraph context
if (controller.model.isSubgraph && controller.model.subgraph is VisualEffectSubgraphBlock)
{
if (!controller.graph.children.Any(t => t is VFXBlockSubgraphContext))
{
controller.graph.AddChild(VFXBlockSubgraphContext.CreateInstance<VFXBlockSubgraphContext>(), 0);
}
}
SceneView.duringSceneGui += OnSceneGUI;
}
IEnumerable<Type> GetAcceptedTypeNodes()
{
if (!controller.model.isSubgraph)
return null;
return new Type[] { typeof(VFXOperator) };
}
public VisualEffect attachedComponent
{
get
{
return m_ComponentBoard.GetAttachedComponent();
}
set
{
if (value == null)
{
m_ComponentBoard.Detach();
m_ProfilingBoard.Detach();
}
else
{
m_ComponentBoard.Attach(value);
m_ProfilingBoard.Attach(value);
}
}
}
public void RemoveAnchorEdges(VFXDataAnchor anchor)
{
foreach (var edge in dataEdges.Where(t => t.Value.input == anchor || t.Value.output == anchor).ToArray())
{
if (edge.Value.input == anchor)
edge.Value.output.Disconnect(edge.Value);
else
edge.Value.input.Disconnect(edge.Value);
RemoveElement(edge.Value);
dataEdges.Remove(edge.Key);
}
}
public void RemoveNodeEdges(VFXNodeUI node)
{
foreach (var edge in dataEdges.Where(t => t.Value.input.node == node || t.Value.output.node == node).ToArray())
{
RemoveElement(edge.Value);
dataEdges.Remove(edge.Key);
}
}
public bool TryRemoveCustomAttribute(string customAttributeName)
{
if (askForConfirmationBeforeDelete && controller.graph.IsCustomAttributeUsed(customAttributeName) && !EditorUtility.DisplayDialog("Confirmation",
$"The custom attribute '{customAttributeName}' is used in the graph. Removing this attribute will remove get and set nodes automatically.\nAre you sure?",
"Yes",
"No"))
{
return false;
}
controller.graph.RemoveCustomAttribute(customAttributeName);
return true;
}
private bool TryRemoveCategory(string category)
{
if (askForConfirmationBeforeDelete && controller.parameterControllers.Any(x => string.Compare(x.model.category, category, StringComparison.OrdinalIgnoreCase) == 0) && !EditorUtility.DisplayDialog("Confirmation",
$"The category '{category}' contains one or more properties. Removing this category will remove these properties too.\nAre you sure?",
"Yes",
"No"))
{
return false;
}
return controller.RemoveCategory(category);
}
public bool TryRemoveParameter(VFXParameterController parameterController)
{
if (askForConfirmationBeforeDelete && parameterController.hasNodes && !EditorUtility.DisplayDialog("Confirmation",
$"The property '{parameterController.model.exposedName}' is used in the graph. Removing this property will remove nodes automatically.\nAre you sure?",
"Yes",
"No"))
{
return false;
}
controller.RemoveElement(parameterController);
return true;
}
public VFXViewController controller
{
get { return m_Controller; }
set
{
if (m_Controller != value)
{
var previousController = m_Controller;
if (value == null)
{
m_Controller = null;
if (!VFXViewWindow.CloseIfNotLast(this))
{
DisconnectController(previousController);
NewControllerSet();
}
}
else
{
if (m_Controller != null)
{
DisconnectController(previousController);
}
m_Controller = value;
if (m_Controller != null)
{
ConnectController();
}
if (m_Controller != null)
{
NewControllerSet();
AttachToSelection();
m_ComponentBoard.ResetPlayRate();
}
}
}
}
}
public VFXGroupNode GetPickedGroupNode(Vector2 panelPosition)
{
List<VisualElement> picked = new List<VisualElement>();
panel.PickAll(panelPosition, picked);
return picked.OfType<VFXGroupNode>().FirstOrDefault();
}
internal VFXNodeController AddOperator(Type type)
{
var desc = VFXLibrary.GetOperators().FirstOrDefault(x => x.modelType == type);
return AddNode(desc.variant, Event.current.mousePosition);
}
public VFXNodeController AddNode(Variant variant, Vector2 mPos)
{
UpdateSelectionWithNewNode();
var groupNode = GetPickedGroupNode(mPos);
mPos = this.ChangeCoordinatesTo(contentViewContainer, mPos);
if (variant.modelType == typeof(VisualEffectSubgraphOperator))
{
var path = variant.settings.Single(x => x.Key == "path").Value as string;
var subGraph = AssetDatabase.LoadAssetAtPath<VisualEffectSubgraphOperator>(path);
if (subGraph != null && (!controller.model.isSubgraph || !subGraph.GetResource().GetOrCreateGraph().subgraphDependencies.Contains(controller.model.subgraph) && subGraph.GetResource() != controller.model))
{
VFXModel newModel = ScriptableObject.CreateInstance<VFXSubgraphOperator>();
controller.AddVFXModel(mPos, newModel);
newModel.SetSettingValue("m_Subgraph", subGraph);
UpdateSelectionWithNewNode();
controller.LightApplyChanges();
return controller.GetNewNodeController(newModel);
}
}
else if (variant is VFXModelDescriptorParameters.ParameterVariant)
{
var parameterController = controller.parameterControllers.Single(x => x.exposedName == variant.name);
UpdateSelectionWithNewNode();
return controller.AddVFXParameter(mPos, parameterController, groupNode?.controller);
}
else
{
UpdateSelectionWithNewNode();
return controller.AddNode(mPos, variant, groupNode?.controller);
}
return null;
}
public bool HasCustomAttributeConflicts(IEnumerable<VFXAttribute> customAttributes)
{
var conflictingAttributes = new Dictionary<VFXAttribute, VFXAttributeHelper.Match>();
var attributeManager = controller.graph.attributesManager;
foreach (var attribute in customAttributes)
{
if (controller.graph.TryFindCustomAttributeDescriptor(attribute.name, out var attributeDescriptor) && !attributeDescriptor.isReadOnly)
{
attributeManager.TryFind(attribute.name, out var conflictingAttribute);
conflictingAttributes[attribute] = VFXAttributeHelper.GetMatch(attribute, conflictingAttribute);
}
}
var message = new StringBuilder();
var notPerfectMatches = conflictingAttributes.Where(x => x.Value.status != VFXAttributeHelper.VFXAttributeMatch.PerfectMath).ToArray();
if (notPerfectMatches.Length > 0)
{
message.Append("The following custom attribute(s) already exist in the graph but have different type or name (Only differ in casing).\nYou should either rename them or change type accordingly:\n");
foreach (var typeDifference in notPerfectMatches)
{
message.AppendFormat("\n{0} ({1}) => {2} ({3})", typeDifference.Value.attribute.name, typeDifference.Value.attribute.type, typeDifference.Key.name, typeDifference.Key.type);
}
EditorUtility.DisplayDialog("Custom Attribute Conflict", message.ToString(), "Close");
return true;
}
if (conflictingAttributes.Count > 0)
{
message.Append("If you continue, custom attributes shared with the imported subgraph will become 'read-only' and the description will be overwritten by the one from the subgraph.");
return !EditorUtility.DisplayDialog("Custom Attribute Conflict", message.ToString(), "Continue", "Cancel");
}
return false;
}
public void RefreshErrors(VFXModel model)
{
try
{
using var reporter = StartInvalidateErrorReport(model);
model.GenerateErrors(reporter);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
readonly VisualElement m_Toolbar;
readonly ToolbarToggle m_LockToggle;
readonly EditorToolbarDropdown m_AttachDropDownButton;
readonly Texture2D m_LinkedIcon;
readonly Texture2D m_UnlinkedIcon;
readonly VFXVCSDropdownButton m_VCSDropDown;
VFXNodeProvider m_NodeProvider;
bool m_IsRuntimeMode;
bool m_ForceShaderDebugSymbols;
bool m_ForceShaderValidation;
public static StyleSheet LoadStyleSheet(string text)
{
string path = string.Format("{0}/uss/{1}.uss", VisualEffectAssetEditorUtility.editorResourcesPath, text);
return AssetDatabase.LoadAssetAtPath<StyleSheet>(path);
}
public static VisualTreeAsset LoadUXML(string text)
{
string path = string.Format("{0}/uxml/{1}.uxml", VisualEffectAssetEditorUtility.editorResourcesPath, text);
return AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(path);
}
public static Texture2D LoadImage(string text)
{
string path = string.Format("{0}/VFX/{1}.png", VisualEffectAssetEditorUtility.editorResourcesPath, text);
return EditorGUIUtility.LoadIcon(path);
}
SelectionDragger m_SelectionDragger;
RectangleSelector m_RectangleSelector;
private void OnCreateAsset()
{
VFXTemplateWindow.ShowCreateFromTemplate(this, null);
}
public VFXView()
{
errorManager = new VFXErrorManager();
errorManager.onRegisterError += RegisterError;
errorManager.onClearAllErrors += ClearAllErrors;
m_UseInternalClipboard = false;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
SetupZoom(0.125f, 8);
this.AddManipulator(new ContentDragger());
m_SelectionDragger = new SelectionDragger();
m_RectangleSelector = new RectangleSelector();
this.AddManipulator(m_SelectionDragger);
this.AddManipulator(m_RectangleSelector);
this.AddManipulator(new FreehandSelector());
var vfxViewStyleSheet = LoadStyleSheet("VFXView");
styleSheets.Add(vfxViewStyleSheet);
if (!EditorGUIUtility.isProSkin)
{
styleSheets.Add(LoadStyleSheet("VFXView-light"));
}
else
{
styleSheets.Add(LoadStyleSheet("VFXView-dark"));
}
AddLayer(-1);
AddLayer(1);
AddLayer(2);
focusable = true;
m_Toolbar = new UnityEditor.UIElements.Toolbar();
m_Toolbar.styleSheets.Add(vfxViewStyleSheet);
var saveDropDownButton = new VFXSaveDropdownButton(this);
m_Toolbar.Add(saveDropDownButton);
var compileDropDownButton = new VFXCompileDropdownButton(this);
m_Toolbar.Add(compileDropDownButton);
m_LinkedIcon = EditorGUIUtility.LoadIcon(Path.Combine(EditorResources.iconsPath, "Linked.png"));
m_UnlinkedIcon = EditorGUIUtility.LoadIcon(Path.Combine(EditorResources.iconsPath, "UnLinked.png"));
m_AttachDropDownButton = new EditorToolbarDropdown(m_UnlinkedIcon, OnOpenAttachMenu);
m_AttachDropDownButton.name = AttachGameObjectLabel;
m_Toolbar.Add(m_AttachDropDownButton);
m_LockToggle = new ToolbarToggle();
m_LockToggle.style.unityTextAlign = TextAnchor.MiddleLeft;
m_LockToggle.tooltip = locked ? Contents.clickToUnlock.text : Contents.clickToLock.text;
m_LockToggle.name = LockAutoAttachLabel;
m_LockToggle.RegisterCallback<ChangeEvent<bool>>(OnToggleLock);
m_Toolbar.Add(m_LockToggle);
m_VCSDropDown = new VFXVCSDropdownButton(this);
m_Toolbar.Add(m_VCSDropDown);
var templateDropDownButton = new CreateFromTemplateDropDownButton(this);
m_Toolbar.Add(templateDropDownButton);
m_BackButton = new ToolbarButton { tooltip = "Back to parent", name = "BackButton" };
m_BackButton.Add(new Image { image = EditorGUIUtility.LoadIcon(Path.Combine(EditorResources.iconsPath, "back.png")) });
m_BackButton.AddStyleSheetPath("VFXToolbar");
m_BackButton.clicked += OnBackToParent;
m_Toolbar.Add(m_BackButton);
var flexSpacer = new ToolbarSpacer();
flexSpacer.style.flexGrow = 1f;
m_Toolbar.Add(flexSpacer);
var toggleBlackboard = new ToolbarToggle { tooltip = "Blackboard" };
toggleBlackboard.Add(new Image { image = EditorGUIUtility.LoadIcon(Path.Combine(VisualEffectGraphPackageInfo.assetPackagePath, "Editor/UIResources/VFX/variableswindow.png")) });
toggleBlackboard.RegisterCallback<ChangeEvent<bool>>(ToggleBlackboard);
m_Toolbar.Add(toggleBlackboard);
m_ToggleComponentBoard = new ToolbarToggle { tooltip = "Displays controls for the GameObject currently attached" };
m_ToggleComponentBoard.Add(new Image { image = EditorGUIUtility.LoadIcon(Path.Combine(VisualEffectGraphPackageInfo.assetPackagePath, "Editor/UIResources/VFX/controls.png")) });
m_ToggleComponentBoard.style.borderRightWidth = 1;
m_ToggleComponentBoard.RegisterCallback<ChangeEvent<bool>>(ToggleComponentBoard);
m_Toolbar.Add(m_ToggleComponentBoard);
m_ToggleProfilingBoard = new ToolbarToggle { tooltip = "Display profiling information about current attached GameObject." };
m_ToggleProfilingBoard.Add(new Image { image = EditorGUIUtility.LoadIcon(Path.Combine(VisualEffectGraphPackageInfo.assetPackagePath, "Editor/UIResources/VFX/debug.png")) });
m_ToggleProfilingBoard.style.borderRightWidth = 1;
m_ToggleProfilingBoard.RegisterCallback<ChangeEvent<bool>>(ToggleProfilingBoard);
m_Toolbar.Add(m_ToggleProfilingBoard);
var helpDropDownButton = new VFXHelpDropdownButton(this);
m_Toolbar.Add(helpDropDownButton);
// End Toolbar
var noAssetLabel = new Label("To begin creating Visual Effects, create a new Visual Effect Graph Asset.\n(or double-click an existing Visual Effect Graph in the project view)");
var createButton = new Button { text = "Create new Visual Effect Graph" };
createButton.clicked += OnCreateAsset;
m_NoAssetElement = new VisualElement { name = "no-asset" };
m_NoAssetElement.Add(noAssetLabel);
m_NoAssetElement.Add(createButton);
m_LockedElement = new VisualElement { name = "lockedContainer"};
var lockLabel = new Label("\u2b06 Check out to modify") { name = "lockedMessage" };
lockLabel.focusable = true;
m_LockedElement.Add(lockLabel);
m_Blackboard = new VFXBlackboard(this);
bool blackboardVisible = BoardPreferenceHelper.IsVisible(BoardPreferenceHelper.Board.blackboard, true);
if (blackboardVisible)
Add(m_Blackboard);
toggleBlackboard.value = blackboardVisible;
m_ComponentBoard = new VFXComponentBoard(this);
m_ProfilingBoard = new VFXProfilingBoard(this);
#if _ENABLE_RESTORE_BOARD_VISIBILITY
bool componentBoardVisible = BoardPreferenceHelper.IsVisible(BoardPreferenceHelper.Board.componentBoard, false);
if (componentBoardVisible)
ShowComponentBoard();
toggleComponentBoard.value = componentBoardVisible;
#endif
Add(m_LockedElement);
Add(m_NoAssetElement);
SetToolbarEnabled(false);
m_VFXSettings = new VFXViewSettings();
m_VFXSettings.Load();
m_LockToggle.value = m_VFXSettings.AttachedLocked;
RegisterCallback<DragUpdatedEvent>(OnDragUpdated);
RegisterCallback<DragPerformEvent>(OnDragPerform);
RegisterCallback<ValidateCommandEvent>(ValidateCommand);
RegisterCallback<ExecuteCommandEvent>(ExecuteCommand);
RegisterCallback<AttachToPanelEvent>(OnEnterPanel);
RegisterCallback<DetachFromPanelEvent>(OnLeavePanel);
RegisterCallback<MouseMoveEvent>(OnMouseMoveEvent);
graphViewChanged = VFXGraphViewChanged;
elementResized = VFXElementResized;
canPasteSerializedData = VFXCanPaste;
viewDataKey = "VFXView";
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
internal bool GetIsRuntimeMode() => m_IsRuntimeMode;
internal bool GetForceShaderDebugSymbols() => m_ForceShaderDebugSymbols;
public void Dispose()
{
controller = null;
UnregisterCallback<DragUpdatedEvent>(OnDragUpdated);
UnregisterCallback<DragPerformEvent>(OnDragPerform);
UnregisterCallback<ValidateCommandEvent>(ValidateCommand);
UnregisterCallback<ExecuteCommandEvent>(ExecuteCommand);
UnregisterCallback<AttachToPanelEvent>(OnEnterPanel);
UnregisterCallback<DetachFromPanelEvent>(OnLeavePanel);
UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged);
UnregisterCallback<MouseMoveEvent>(OnMouseMoveEvent);
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
}
void OnPlayModeStateChanged(PlayModeStateChange playModeState)
{
if (playModeState == PlayModeStateChange.EnteredEditMode)
{
m_VFXSettings.Load(true);
TryAttachTo(m_VFXSettings.AttachedVisualEffect, false);
}
m_ComponentBoard.SetDebugMode(VFXUIDebug.Modes.None);
}
void OnOpenAttachMenu()
{
var attachPanel = ScriptableObject.CreateInstance<VFXAttachPanel>();
attachPanel.SetView(this);
var bounds = new Rect(ViewToScreenPosition(m_AttachDropDownButton.worldBound.position), m_AttachDropDownButton.worldBound.size);
bounds.xMin++;
attachPanel.ShowAsDropDown(bounds, attachPanel.WindowSize, new[] { PopupLocation.BelowAlignLeft });
}
internal void ToggleRuntimeMode()
{
m_IsRuntimeMode = !m_IsRuntimeMode;
controller.graph.SetCompilationMode(m_IsRuntimeMode ? VFXCompilationMode.Runtime : VFXCompilationMode.Edition);
}
internal void ToggleForceShaderDebugSymbols()
{
m_ForceShaderDebugSymbols = !m_ForceShaderDebugSymbols;
controller.graph.ForceShaderDebugSymbols(m_ForceShaderDebugSymbols);
}
internal bool GetShaderValidation() => m_ForceShaderValidation;
internal void ToggleShaderValidationChanged()
{
m_ForceShaderValidation = !m_ForceShaderValidation;
controller.graph.SetForceShaderValidation(m_ForceShaderValidation);
}
[NonSerialized]
Dictionary<VFXModel, List<VFXIconBadge>> m_InvalidateBadges = new();
[NonSerialized]
List<VFXIconBadge> m_CompileBadges = new();
private void SetToolbarEnabled(bool enabled)
{
ToolbarElementsToDisableWhenNoAsset.ForEach(x => m_Toolbar.Q<VisualElement>(x).SetEnabled(enabled));
}
private void RegisterError(VFXModel model, VFXErrorOrigin errorOrigin, string error, VFXErrorType type, string description)
{
VisualElement target = null;
VisualElement targetParent = null;
if (model is VFXSlot)
{
var slot = (VFXSlot)model;
// todo manage parameter slot if they can have error
var nodeController = controller.GetNodeController(slot.owner as VFXModel, 0);
if (nodeController == null)
return;
var anchorController = (slot.direction == VFXSlot.Direction.kInput ? nodeController.inputPorts : nodeController.outputPorts).FirstOrDefault(t => t.model == slot);
if (anchorController == null)
return;
targetParent = GetNodeByController(nodeController);
target = (targetParent as VFXNodeUI).GetPorts(slot.direction == VFXSlot.Direction.kInput, slot.direction != VFXSlot.Direction.kInput).FirstOrDefault(t => t.controller == anchorController);
}
else if (model is IVFXSlotContainer)
{
var node = model;
var nodeController = controller.GetNodeController(node, 0);
if (nodeController == null)
return;
target = GetNodeByController(nodeController);
if (target == null)
return;
if (nodeController is VFXBlockController blkController)
{
VFXNodeUI targetContext = GetNodeByController(blkController.contextController);
if (targetContext == null)
return;
targetParent = targetContext.parent;
}
else
{
targetParent = target.parent;
}
}
if (target != null && targetParent != null)
{
var badge = new VFXIconBadge(description, type);
var badgeHolder = target.Children().SingleOrDefault(x => x.name == "BadgesHolder");
if (badgeHolder == null)
{
badgeHolder = new VisualElement { name = "BadgesHolder" };
badgeHolder.AddStyleSheetPath("VFXIconBadge");
target.Add(badgeHolder);
}
badgeHolder.Add(badge);
if (errorOrigin == VFXErrorOrigin.Compilation)
{
m_CompileBadges.Add(badge);
}
else
{
List<VFXIconBadge> badges;
if (!m_InvalidateBadges.TryGetValue(model, out badges))
{
badges = new List<VFXIconBadge>();
m_InvalidateBadges[model] = badges;
}
badges.Add(badge);
}
badge.AddManipulator(new Clickable(() => badge.RemoveFromHierarchy()));
badge.AddManipulator(new ContextualMenuManipulator(e =>
{
e.menu.AppendAction("Hide", _ => { badge.RemoveFromHierarchy(); });
if (type != VFXErrorType.Error)
{
e.menu.AppendAction("Ignore", _ =>
{
badge.RemoveFromHierarchy();
model.IgnoreError(error);
});
}
e.StopImmediatePropagation();
}));
}
}
private void ClearAllErrors(VFXModel model, VFXErrorOrigin errorOrigin)
{
if (errorOrigin == VFXErrorOrigin.Compilation)
{
foreach (var badge in m_CompileBadges)
{
badge.RemoveFromHierarchy();
}
m_CompileBadges.Clear();
}
else
{
if (!object.ReferenceEquals(model, null))
{
if (m_InvalidateBadges.TryGetValue(model, out var badges))
{
foreach (var badge in badges)
{
badge.RemoveFromHierarchy();
}
m_InvalidateBadges.Remove(model);
}
}
else
throw new InvalidOperationException("Can't clear in Invalidate mode without a model");
}
}
public void SetBoardToFront(GraphElement board)
{
board.BringToFront();
}
public bool TryAttachTo(VisualEffect visualEffect, bool showNotification)
{
if (m_Controller == null || m_Controller.graph == null || visualEffect == null)
{
return false;
}
bool attached = false;
VisualEffectAsset controllerAsset = controller.graph.visualEffectResource.asset;
if (controllerAsset != null && controllerAsset == visualEffect.visualEffectAsset)
{
attached = m_ComponentBoard.Attach(visualEffect);
m_ProfilingBoard.Attach(visualEffect);
}
if (attached && showNotification)
{
var vfxWindow = VFXViewWindow.GetWindowNoShow(this);
if (vfxWindow != null)
{
string truncatedObjectName = TruncateName(visualEffect.name, MaximumNameLengthInNotification);
vfxWindow.ShowNotification(new GUIContent($"Attached to {truncatedObjectName}"), 1.5);
vfxWindow.Repaint();
}
}
m_VFXSettings.AttachedVisualEffect = attachedComponent;
UpdateToolbarButtons();
return attached;
}
internal void Detach()
{
m_ComponentBoard.Detach();
m_ProfilingBoard.Detach();
UpdateToolbarButtons();
}
internal void AttachToSelection()
{
TryAttachTo((Selection.activeObject as GameObject)?.GetComponent<VisualEffect>(), true);
}
private void UpdateToolbarButtons()
{
if (attachedComponent != null)
{
m_AttachDropDownButton.AddToClassList("checked");
m_AttachDropDownButton.icon = m_LinkedIcon;
}
else
{
m_AttachDropDownButton.RemoveFromClassList("checked");
m_AttachDropDownButton.icon = m_UnlinkedIcon;
}
m_LockToggle.tooltip = locked ? Contents.clickToUnlock.text : Contents.clickToLock.text;
m_AttachDropDownButton.tooltip = attachedComponent != null && !string.IsNullOrEmpty(attachedComponent.name)
? string.Format(Contents.attachedToGameObject.text, TruncateName(attachedComponent.name, MaximumNameLengthInNotification))
: Contents.notAttached.text;
}
string TruncateName(string nameToTruncate, int maxLength)
{