-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathGraphData.cs
More file actions
2961 lines (2499 loc) · 115 KB
/
GraphData.cs
File metadata and controls
2961 lines (2499 loc) · 115 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.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEditor.Rendering;
using UnityEditor.ShaderGraph.Internal;
using UnityEditor.ShaderGraph.Legacy;
using UnityEditor.ShaderGraph.Serialization;
using UnityEditor.ShaderGraph.Drawing;
using Edge = UnityEditor.Graphing.Edge;
using UnityEngine.UIElements;
using UnityEngine.Assertions;
using UnityEngine.Pool;
using UnityEngine.Serialization;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[FormerName("UnityEditor.ShaderGraph.MaterialGraph")]
[FormerName("UnityEditor.ShaderGraph.SubGraph")]
[FormerName("UnityEditor.ShaderGraph.AbstractMaterialGraph")]
sealed partial class GraphData : JsonObject
{
public override int latestVersion => 3;
public GraphObject owner { get; set; }
#region Input data
[SerializeField]
List<JsonData<AbstractShaderProperty>> m_Properties = new List<JsonData<AbstractShaderProperty>>();
public DataValueEnumerable<AbstractShaderProperty> properties => m_Properties.SelectValue();
[SerializeField]
List<JsonData<ShaderKeyword>> m_Keywords = new List<JsonData<ShaderKeyword>>();
public DataValueEnumerable<ShaderKeyword> keywords => m_Keywords.SelectValue();
[SerializeField]
List<JsonData<ShaderDropdown>> m_Dropdowns = new List<JsonData<ShaderDropdown>>();
public DataValueEnumerable<ShaderDropdown> dropdowns => m_Dropdowns.SelectValue();
[NonSerialized]
List<ShaderInput> m_AddedInputs = new List<ShaderInput>();
public IEnumerable<ShaderInput> addedInputs
{
get { return m_AddedInputs; }
}
[NonSerialized]
List<ShaderInput> m_RemovedInputs = new List<ShaderInput>();
public IEnumerable<ShaderInput> removedInputs
{
get { return m_RemovedInputs; }
}
[NonSerialized]
List<ShaderInput> m_MovedInputs = new List<ShaderInput>();
public IEnumerable<ShaderInput> movedInputs
{
get { return m_MovedInputs; }
}
[NonSerialized]
List<CategoryData> m_AddedCategories = new List<CategoryData>();
public IEnumerable<CategoryData> addedCategories
{
get { return m_AddedCategories; }
}
[NonSerialized]
List<CategoryData> m_RemovedCategories = new List<CategoryData>();
public IEnumerable<CategoryData> removedCategories
{
get { return m_RemovedCategories; }
}
[NonSerialized]
List<CategoryData> m_MovedCategories = new List<CategoryData>();
public IEnumerable<CategoryData> movedCategories
{
get { return m_MovedCategories; }
}
[NonSerialized]
bool m_MovedContexts = false;
public bool movedContexts => m_MovedContexts;
public string assetGuid { get; set; }
#endregion
#region Category Data
[SerializeField]
List<JsonData<CategoryData>> m_CategoryData = new List<JsonData<CategoryData>>();
public DataValueEnumerable<CategoryData> categories => m_CategoryData.SelectValue();
#endregion
#region Node data
[SerializeField]
List<JsonData<AbstractMaterialNode>> m_Nodes = new List<JsonData<AbstractMaterialNode>>();
[NonSerialized]
Dictionary<string, AbstractMaterialNode> m_NodeDictionary = new Dictionary<string, AbstractMaterialNode>();
[NonSerialized]
Dictionary<string, AbstractMaterialNode> m_LegacyUpdateDictionary = new Dictionary<string, AbstractMaterialNode>();
public IEnumerable<T> GetNodes<T>()
{
return m_Nodes.SelectValue().OfType<T>();
}
[NonSerialized]
List<AbstractMaterialNode> m_AddedNodes = new List<AbstractMaterialNode>();
public IEnumerable<AbstractMaterialNode> addedNodes
{
get { return m_AddedNodes; }
}
[NonSerialized]
List<AbstractMaterialNode> m_RemovedNodes = new List<AbstractMaterialNode>();
public IEnumerable<AbstractMaterialNode> removedNodes
{
get { return m_RemovedNodes; }
}
[NonSerialized]
List<AbstractMaterialNode> m_PastedNodes = new List<AbstractMaterialNode>();
public IEnumerable<AbstractMaterialNode> pastedNodes
{
get { return m_PastedNodes; }
}
#endregion
#region Group Data
[SerializeField]
List<JsonData<GroupData>> m_GroupDatas = new List<JsonData<GroupData>>();
public DataValueEnumerable<GroupData> groups
{
get { return m_GroupDatas.SelectValue(); }
}
[NonSerialized]
List<GroupData> m_AddedGroups = new List<GroupData>();
public IEnumerable<GroupData> addedGroups
{
get { return m_AddedGroups; }
}
[NonSerialized]
List<GroupData> m_RemovedGroups = new List<GroupData>();
public IEnumerable<GroupData> removedGroups
{
get { return m_RemovedGroups; }
}
[NonSerialized]
List<GroupData> m_PastedGroups = new List<GroupData>();
public IEnumerable<GroupData> pastedGroups
{
get { return m_PastedGroups; }
}
[NonSerialized]
List<ParentGroupChange> m_ParentGroupChanges = new List<ParentGroupChange>();
public IEnumerable<ParentGroupChange> parentGroupChanges
{
get { return m_ParentGroupChanges; }
}
[NonSerialized]
GroupData m_MostRecentlyCreatedGroup;
public GroupData mostRecentlyCreatedGroup => m_MostRecentlyCreatedGroup;
[NonSerialized]
Dictionary<JsonRef<GroupData>, List<IGroupItem>> m_GroupItems = new Dictionary<JsonRef<GroupData>, List<IGroupItem>>();
public IEnumerable<IGroupItem> GetItemsInGroup(GroupData groupData)
{
if (m_GroupItems.TryGetValue(groupData, out var nodes))
{
return nodes;
}
return Enumerable.Empty<IGroupItem>();
}
#endregion
#region StickyNote Data
[SerializeField]
List<JsonData<StickyNoteData>> m_StickyNoteDatas = new List<JsonData<StickyNoteData>>();
public DataValueEnumerable<StickyNoteData> stickyNotes => m_StickyNoteDatas.SelectValue();
[NonSerialized]
List<StickyNoteData> m_AddedStickyNotes = new List<StickyNoteData>();
public List<StickyNoteData> addedStickyNotes => m_AddedStickyNotes;
[NonSerialized]
List<StickyNoteData> m_RemovedNotes = new List<StickyNoteData>();
public IEnumerable<StickyNoteData> removedNotes => m_RemovedNotes;
[NonSerialized]
List<StickyNoteData> m_PastedStickyNotes = new List<StickyNoteData>();
public IEnumerable<StickyNoteData> pastedStickyNotes => m_PastedStickyNotes;
#endregion
#region Edge data
[SerializeField]
List<Edge> m_Edges = new List<Edge>();
public IEnumerable<Edge> edges => m_Edges;
[NonSerialized]
Dictionary<string, List<IEdge>> m_NodeEdges = new Dictionary<string, List<IEdge>>();
[NonSerialized]
List<IEdge> m_AddedEdges = new List<IEdge>();
public IEnumerable<IEdge> addedEdges
{
get { return m_AddedEdges; }
}
[NonSerialized]
List<IEdge> m_RemovedEdges = new List<IEdge>();
public IEnumerable<IEdge> removedEdges
{
get { return m_RemovedEdges; }
}
#endregion
#region Context Data
[SerializeField]
ContextData m_VertexContext;
[SerializeField]
ContextData m_FragmentContext;
// We build this once and cache it as it uses reflection
// This list is used to build the Create Node menu entries for Blocks
// as well as when deserializing descriptor fields on serialized Blocks
[NonSerialized]
List<BlockFieldDescriptor> m_BlockFieldDescriptors;
public ContextData vertexContext => m_VertexContext;
public ContextData fragmentContext => m_FragmentContext;
public List<BlockFieldDescriptor> blockFieldDescriptors => m_BlockFieldDescriptors;
#endregion
[SerializeField]
InspectorPreviewData m_PreviewData = new InspectorPreviewData();
public InspectorPreviewData previewData
{
get { return m_PreviewData; }
set { m_PreviewData = value; }
}
[SerializeField]
string m_Path;
public string path
{
get { return m_Path; }
set
{
if (m_Path == value)
return;
m_Path = value;
if (owner != null)
owner.RegisterCompleteObjectUndo("Change Path");
}
}
public MessageManager messageManager { get; set; }
public bool isSubGraph { get; set; }
// we default this to Graph for subgraphs
// but for shadergraphs, this will get replaced with Single
[SerializeField]
private GraphPrecision m_GraphPrecision = GraphPrecision.Graph;
public GraphPrecision graphDefaultPrecision
{
get
{
// shader graphs are not allowed to have graph precision
// we force them to Single if they somehow get set to graph
if ((!isSubGraph) && (m_GraphPrecision == GraphPrecision.Graph))
return GraphPrecision.Single;
return m_GraphPrecision;
}
}
public ConcretePrecision graphDefaultConcretePrecision
{
get
{
// when in "Graph switchable" mode, we choose Half as the default concrete precision
// so you can visualize the worst-case
return graphDefaultPrecision.ToConcrete(ConcretePrecision.Half);
}
}
// Some state has been changed that requires checking for the auto add/removal of blocks.
// This needs to be checked at a later point in time so actions like replace (remove + add) don't remove blocks.
internal bool checkAutoAddRemoveBlocks { get; set; }
public void SetGraphDefaultPrecision(GraphPrecision newGraphDefaultPrecision)
{
if ((!isSubGraph) && (newGraphDefaultPrecision == GraphPrecision.Graph))
{
// shader graphs can't be set to "Graph", only subgraphs can
Debug.LogError("Cannot set ShaderGraph to a default precision of Graph");
}
else
{
m_GraphPrecision = newGraphDefaultPrecision;
}
}
// NOTE: having preview mode default to 3D preserves the old behavior of pre-existing subgraphs
// if we change this, we would have to introduce a versioning step if we want to maintain the old behavior
[SerializeField]
private PreviewMode m_PreviewMode = PreviewMode.Preview3D;
public PreviewMode previewMode
{
get => m_PreviewMode;
set => m_PreviewMode = value;
}
[SerializeField]
JsonRef<AbstractMaterialNode> m_OutputNode;
public AbstractMaterialNode outputNode
{
get => m_OutputNode;
set => m_OutputNode = value;
}
internal delegate void SaveGraphDelegate(Shader shader, object context);
internal static SaveGraphDelegate onSaveGraph;
#region Targets
// Serialized list of user-selected active targets, sorted in displayName order (to maintain deterministic serialization order)
// some of these may be MultiJsonInternal.UnknownTargetType if we can't recognize the type of the target
[SerializeField]
internal List<JsonData<Target>> m_ActiveTargets = new List<JsonData<Target>>(); // After adding to this list, you MUST call SortActiveTargets()
public DataValueEnumerable<Target> activeTargets => m_ActiveTargets.SelectValue();
// this stores all of the current possible Target types (including any unknown target types we serialized in)
class PotentialTarget
{
// the potential Target
Target m_Target;
// a Target is either known (we know the Type) or unknown (can't find a matching definition of the Type)
// Targets of unknown type are stored in an UnknownTargetType
private Type m_KnownType;
private MultiJsonInternal.UnknownTargetType m_UnknownTarget;
public PotentialTarget(Target target)
{
m_Target = target;
if (target is MultiJsonInternal.UnknownTargetType)
{
m_UnknownTarget = (MultiJsonInternal.UnknownTargetType)target;
m_KnownType = null;
}
else
{
m_UnknownTarget = null;
m_KnownType = target.GetType();
}
}
public bool IsUnknown()
{
return m_UnknownTarget != null;
}
public MultiJsonInternal.UnknownTargetType GetUnknown()
{
return m_UnknownTarget;
}
public Type knownType { get { return m_KnownType; } }
public bool Is(Target t)
{
return t == m_Target;
}
public string GetDisplayName()
{
return m_Target.displayName;
}
public void ReplaceStoredTarget(Target t)
{
if (m_KnownType != null)
Assert.IsTrue(t.GetType() == m_KnownType);
m_Target = t;
}
public Target GetTarget()
{
return m_Target;
}
}
[NonSerialized]
List<PotentialTarget> m_AllPotentialTargets = new List<PotentialTarget>();
public IEnumerable<Target> allPotentialTargets => m_AllPotentialTargets.Select(x => x.GetTarget());
public int GetTargetIndexByKnownType(Type targetType)
{
return m_AllPotentialTargets.FindIndex(pt => pt.knownType == targetType);
}
public int GetTargetIndex(Target t)
{
int result = m_AllPotentialTargets.FindIndex(pt => pt.Is(t));
return result;
}
public List<string> GetPotentialTargetDisplayNames()
{
List<string> displayNames = new List<string>(m_AllPotentialTargets.Count);
for (int validIndex = 0; validIndex < m_AllPotentialTargets.Count; validIndex++)
{
displayNames.Add(m_AllPotentialTargets[validIndex].GetDisplayName());
}
return displayNames;
}
public void SetTargetActive(Target target, bool skipSortAndUpdate = false)
{
int activeIndex = m_ActiveTargets.IndexOf(target);
if (activeIndex < 0)
{
activeIndex = m_ActiveTargets.Count;
m_ActiveTargets.Add(target);
}
// active known targets should replace the stored Target in AllPotentialTargets
if (target is MultiJsonInternal.UnknownTargetType unknownTarget)
{
// find any existing potential target with the same unknown jsonData
int targetIndex = m_AllPotentialTargets.FindIndex(
pt => pt.IsUnknown() && (pt.GetUnknown().jsonData == unknownTarget.jsonData));
// replace existing target, or add it if there is none
if (targetIndex >= 0)
m_AllPotentialTargets[targetIndex] = new PotentialTarget(target);
else
m_AllPotentialTargets.Add(new PotentialTarget(target));
}
else
{
// known types should already have been registered
Type targetType = target.GetType();
int targetIndex = GetTargetIndexByKnownType(targetType);
Assert.IsTrue(targetIndex >= 0);
m_AllPotentialTargets[targetIndex].ReplaceStoredTarget(target);
}
if (!skipSortAndUpdate)
SortAndUpdateActiveTargets();
}
public void SetTargetActive(int targetIndex, bool skipSortAndUpdate = false)
{
Target target = m_AllPotentialTargets[targetIndex].GetTarget();
SetTargetActive(target, skipSortAndUpdate);
}
public void SetTargetInactive(Target target, bool skipSortAndUpdate = false)
{
int activeIndex = m_ActiveTargets.IndexOf(target);
if (activeIndex < 0)
return;
int targetIndex = GetTargetIndex(target);
// if a target was in the active targets, it should also have been in the potential targets list
Assert.IsTrue(targetIndex >= 0);
m_ActiveTargets.RemoveAt(activeIndex);
if (!skipSortAndUpdate)
SortAndUpdateActiveTargets();
}
// this list is populated by graph validation, and lists all of the targets that nodes did not like
[NonSerialized]
List<Target> m_UnsupportedTargets = new List<Target>();
public List<Target> unsupportedTargets { get => m_UnsupportedTargets; }
private Comparison<Target> targetComparison = new Comparison<Target>((a, b) => string.Compare(a.displayName, b.displayName));
public void SortActiveTargets()
{
activeTargets.Sort(targetComparison);
}
// TODO: Need a better way to handle this
#if VFX_GRAPH_10_0_0_OR_NEWER
public bool hasVFXCompatibleTarget => activeTargets.Any(o => o.SupportsVFX());
public bool hasVFXTarget
{
get
{
bool supports = true;
supports &= !isSubGraph;
supports &= activeTargets.Any();
// Maintain support for VFXTarget and VFX compatible targets.
supports &= activeTargets.OfType<VFXTarget>().Any() || hasVFXCompatibleTarget;
return supports;
}
}
public bool isOnlyVFXTarget => activeTargets.Count() == 1 &&
activeTargets.Count(t => t is VFXTarget) == 1;
#else
public bool isVFXTarget => false;
public bool isOnlyVFXTarget => false;
#endif
#endregion
public GraphData()
{
m_GroupItems[null] = new List<IGroupItem>();
GetBlockFieldDescriptors();
AddKnownTargetsToPotentialTargets();
}
// used to initialize the graph with targets, i.e. when creating new graphs via the popup menu
public void InitializeOutputs(Target[] targets, BlockFieldDescriptor[] blockDescriptors)
{
if (targets == null)
return;
foreach (var target in targets)
{
if (GetTargetIndexByKnownType(target.GetType()) >= 0)
{
SetTargetActive(target, true);
}
}
SortActiveTargets();
if (blockDescriptors != null)
{
foreach (var descriptor in blockDescriptors)
{
var contextData = descriptor.shaderStage == ShaderStage.Fragment ? m_FragmentContext : m_VertexContext;
var block = (BlockNode)Activator.CreateInstance(typeof(BlockNode));
block.Init(descriptor);
AddBlockNoValidate(block, contextData, contextData.blocks.Count);
}
}
ValidateGraph();
var activeBlocks = GetActiveBlocksForAllActiveTargets();
UpdateActiveBlocks(activeBlocks);
}
void GetBlockFieldDescriptors()
{
m_BlockFieldDescriptors = new List<BlockFieldDescriptor>();
var asmTypes = TypeCache.GetTypesWithAttribute<GenerateBlocksAttribute>();
foreach (var type in asmTypes)
{
var attrs = type.GetCustomAttributes(typeof(GenerateBlocksAttribute), false);
if (attrs == null || attrs.Length <= 0)
continue;
var attribute = attrs[0] as GenerateBlocksAttribute;
// Get all fields that are BlockFieldDescriptor
// If field and context stages match add to list
foreach (var fieldInfo in type.GetFields())
{
if (fieldInfo.GetValue(type) is BlockFieldDescriptor blockFieldDescriptor)
{
blockFieldDescriptor.path = attribute.path;
m_BlockFieldDescriptors.Add(blockFieldDescriptor);
}
}
}
}
void AddKnownTargetsToPotentialTargets()
{
Assert.AreEqual(m_AllPotentialTargets.Count, 0);
// Find all valid Targets by looking in the TypeCache
var targetTypes = TypeCache.GetTypesDerivedFrom<Target>();
foreach (var type in targetTypes)
{
if (type.IsAbstract || type.IsGenericType || !type.IsClass)
continue;
// create a new instance of the Target, to represent the potential Target
// NOTE: this instance may be replaced later if we serialize in an Active Target of that type
var target = (Target)Activator.CreateInstance(type);
if (!target.isHidden)
{
m_AllPotentialTargets.Add(new PotentialTarget(target));
}
}
}
public void SortAndUpdateActiveTargets()
{
SortActiveTargets();
ValidateGraph();
NodeUtils.ReevaluateActivityOfNodeList(m_Nodes.SelectValue());
}
public void ClearChanges()
{
m_AddedNodes.Clear();
m_RemovedNodes.Clear();
m_PastedNodes.Clear();
m_ParentGroupChanges.Clear();
m_AddedGroups.Clear();
m_RemovedGroups.Clear();
m_PastedGroups.Clear();
m_AddedEdges.Clear();
m_RemovedEdges.Clear();
m_AddedInputs.Clear();
m_RemovedInputs.Clear();
m_MovedInputs.Clear();
m_AddedCategories.Clear();
m_RemovedCategories.Clear();
m_MovedCategories.Clear();
m_AddedStickyNotes.Clear();
m_RemovedNotes.Clear();
m_PastedStickyNotes.Clear();
m_MostRecentlyCreatedGroup = null;
m_MovedContexts = false;
}
public void AddNode(AbstractMaterialNode node)
{
if (node is AbstractMaterialNode materialNode)
{
if (isSubGraph && !materialNode.allowedInSubGraph)
{
Debug.LogWarningFormat("Attempting to add {0} to Sub Graph. This is not allowed.", materialNode.GetType());
return;
}
AddNodeNoValidate(materialNode);
// If adding a Sub Graph node whose asset contains Keywords
// Need to restest Keywords against the variant limit
if (node is SubGraphNode subGraphNode &&
subGraphNode.asset != null &&
subGraphNode.asset.keywords.Any())
{
OnKeywordChangedNoValidate();
}
ValidateGraph();
}
else
{
Debug.LogWarningFormat("Trying to add node {0} to Material graph, but it is not a {1}", node, typeof(AbstractMaterialNode));
}
}
public void CreateGroup(GroupData groupData)
{
if (AddGroup(groupData))
{
m_MostRecentlyCreatedGroup = groupData;
}
}
bool AddGroup(GroupData groupData)
{
if (m_GroupDatas.Contains(groupData))
return false;
m_GroupDatas.Add(groupData);
m_AddedGroups.Add(groupData);
m_GroupItems.Add(groupData, new List<IGroupItem>());
return true;
}
public void RemoveGroup(GroupData groupData)
{
RemoveGroupNoValidate(groupData);
ValidateGraph();
}
void RemoveGroupNoValidate(GroupData group)
{
if (!m_GroupDatas.Contains(group))
throw new InvalidOperationException("Cannot remove a group that doesn't exist.");
m_GroupDatas.Remove(group);
m_RemovedGroups.Add(group);
if (m_GroupItems.TryGetValue(group, out var items))
{
foreach (IGroupItem groupItem in items.ToList())
{
SetGroup(groupItem, null);
}
m_GroupItems.Remove(group);
}
}
public void AddStickyNote(StickyNoteData stickyNote)
{
if (m_StickyNoteDatas.Contains(stickyNote))
{
throw new InvalidOperationException("Sticky note has already been added to the graph.");
}
if (!m_GroupItems.ContainsKey(stickyNote.group))
{
throw new InvalidOperationException("Trying to add sticky note with group that doesn't exist.");
}
m_StickyNoteDatas.Add(stickyNote);
m_AddedStickyNotes.Add(stickyNote);
m_GroupItems[stickyNote.group].Add(stickyNote);
}
void RemoveNoteNoValidate(StickyNoteData stickyNote)
{
if (!m_StickyNoteDatas.Contains(stickyNote))
{
throw new InvalidOperationException("Cannot remove a note that doesn't exist.");
}
m_StickyNoteDatas.Remove(stickyNote);
m_RemovedNotes.Add(stickyNote);
if (m_GroupItems.TryGetValue(stickyNote.group, out var groupItems))
{
groupItems.Remove(stickyNote);
}
}
public void RemoveStickyNote(StickyNoteData stickyNote)
{
RemoveNoteNoValidate(stickyNote);
ValidateGraph();
}
public void SetGroup(IGroupItem node, GroupData group)
{
var groupChange = new ParentGroupChange()
{
groupItem = node,
oldGroup = node.group,
// Checking if the groupdata is null. If it is, then it means node has been removed out of a group.
// If the group data is null, then maybe the old group id should be removed
newGroup = group,
};
node.group = groupChange.newGroup;
var oldGroupNodes = m_GroupItems[groupChange.oldGroup];
oldGroupNodes.Remove(node);
m_GroupItems[groupChange.newGroup].Add(node);
m_ParentGroupChanges.Add(groupChange);
}
public void AddContexts()
{
m_VertexContext = new ContextData();
m_VertexContext.shaderStage = ShaderStage.Vertex;
m_VertexContext.position = new Vector2(0, 0);
m_FragmentContext = new ContextData();
m_FragmentContext.shaderStage = ShaderStage.Fragment;
m_FragmentContext.position = new Vector2(0, 200);
}
public void AddBlock(BlockNode blockNode, ContextData contextData, int index)
{
AddBlockNoValidate(blockNode, contextData, index);
ValidateGraph();
var activeBlocks = GetActiveBlocksForAllActiveTargets();
UpdateActiveBlocks(activeBlocks);
}
void AddBlockNoValidate(BlockNode blockNode, ContextData contextData, int index)
{
// Regular AddNode path
AddNodeNoValidate(blockNode);
// Set BlockNode properties
blockNode.contextData = contextData;
// Add to ContextData
if (index == -1 || index >= contextData.blocks.Count)
{
contextData.blocks.Add(blockNode);
}
else
{
contextData.blocks.Insert(index, blockNode);
}
}
public List<BlockFieldDescriptor> GetActiveBlocksForAllActiveTargets()
{
// Get list of active Block types
var currentBlocks = GetNodes<BlockNode>();
var context = new TargetActiveBlockContext(currentBlocks.Select(x => x.descriptor).ToList(), null);
foreach (var target in activeTargets)
{
target.GetActiveBlocks(ref context);
}
// custom blocks aren't going to exist in GetActiveBlocks, we need to ensure we grab those too.
foreach (var cibnode in currentBlocks.Where(bn => bn.isCustomBlock))
{
context.AddBlock(cibnode.descriptor);
}
return context.activeBlocks;
}
public void UpdateActiveBlocks(List<BlockFieldDescriptor> activeBlockDescriptors)
{
// Set Blocks as active based on supported Block list
//Note: we never want unknown blocks to be active, so explicitly set them to inactive always
bool disableCI = activeTargets.All(at => at.ignoreCustomInterpolators);
foreach (var vertexBlock in vertexContext.blocks)
{
if (vertexBlock.value?.isCustomBlock == true)
{
vertexBlock.value.SetOverrideActiveState(disableCI ? AbstractMaterialNode.ActiveState.ExplicitInactive : AbstractMaterialNode.ActiveState.ExplicitActive);
}
else if (vertexBlock.value?.descriptor?.isUnknown == true)
{
vertexBlock.value.SetOverrideActiveState(AbstractMaterialNode.ActiveState.ExplicitInactive);
}
else
{
vertexBlock.value.SetOverrideActiveState(activeBlockDescriptors.Contains(vertexBlock.value.descriptor) ? AbstractMaterialNode.ActiveState.ExplicitActive
: AbstractMaterialNode.ActiveState.ExplicitInactive);
}
}
foreach (var fragmentBlock in fragmentContext.blocks)
{
if (fragmentBlock.value?.descriptor?.isUnknown == true)
{
fragmentBlock.value.SetOverrideActiveState(AbstractMaterialNode.ActiveState.ExplicitInactive);
}
else
{
fragmentBlock.value.SetOverrideActiveState(activeBlockDescriptors.Contains(fragmentBlock.value.descriptor) ? AbstractMaterialNode.ActiveState.ExplicitActive
: AbstractMaterialNode.ActiveState.ExplicitInactive);
}
}
}
public void AddRemoveBlocksFromActiveList(List<BlockFieldDescriptor> activeBlockDescriptors)
{
var blocksToRemove = ListPool<BlockNode>.Get();
void GetBlocksToRemoveForContext(ContextData contextData)
{
for (int i = 0; i < contextData.blocks.Count; i++)
{
if (contextData.blocks[i].value?.isCustomBlock == true) // custom interpolators are fine.
continue;
var block = contextData.blocks[i];
if (!activeBlockDescriptors.Contains(block.value.descriptor))
{
var slot = block.value.FindSlot<MaterialSlot>(0);
//Need to check if a slot is not default value OR is an untracked unknown block type
if (slot.IsUsingDefaultValue() || block.value.descriptor.isUnknown) // TODO: How to check default value
{
blocksToRemove.Add(block);
}
}
}
}
void TryAddBlockToContext(BlockFieldDescriptor descriptor, ContextData contextData)
{
if (descriptor.shaderStage != contextData.shaderStage)
return;
if (contextData.blocks.Any(x => x.value.descriptor.Equals(descriptor)))
return;
var node = (BlockNode)Activator.CreateInstance(typeof(BlockNode));
node.Init(descriptor);
AddBlockNoValidate(node, contextData, contextData.blocks.Count);
}
// Get inactive Blocks to remove
GetBlocksToRemoveForContext(vertexContext);
GetBlocksToRemoveForContext(fragmentContext);
// Remove blocks
foreach (var block in blocksToRemove)
{
RemoveNodeNoValidate(block);
}
// Add active Blocks not currently in Contexts
foreach (var descriptor in activeBlockDescriptors)
{
TryAddBlockToContext(descriptor, vertexContext);
TryAddBlockToContext(descriptor, fragmentContext);
}
}
void AddNodeNoValidate(AbstractMaterialNode node)
{
if (node.group != null && !m_GroupItems.ContainsKey(node.group))
{
throw new InvalidOperationException("Cannot add a node whose group doesn't exist.");
}
node.owner = this;
m_Nodes.Add(node);
m_NodeDictionary.Add(node.objectId, node);
m_AddedNodes.Add(node);
m_GroupItems[node.group].Add(node);
}
public void RemoveNode(AbstractMaterialNode node)
{
if (!node.canDeleteNode)
{
throw new InvalidOperationException($"Node {node.name} ({node.objectId}) cannot be deleted.");
}
RemoveNodeNoValidate(node);
ValidateGraph();
if (node is BlockNode blockNode)
{
var activeBlocks = GetActiveBlocksForAllActiveTargets();
UpdateActiveBlocks(activeBlocks);
blockNode.Dirty(ModificationScope.Graph);
}
}
void RemoveNodeNoValidate(AbstractMaterialNode node)
{
if (!m_NodeDictionary.ContainsKey(node.objectId) && node.isActive && !m_RemovedNodes.Contains(node))
{
throw new InvalidOperationException("Cannot remove a node that doesn't exist.");
}