-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathPreviewManager.cs
More file actions
1379 lines (1170 loc) · 61 KB
/
PreviewManager.cs
File metadata and controls
1379 lines (1170 loc) · 61 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 UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
using UnityEditor.ShaderGraph.Internal;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
using Unity.Profiling;
namespace UnityEditor.ShaderGraph.Drawing
{
delegate void OnPrimaryMasterChanged();
class PreviewManager : IDisposable
{
GraphData m_Graph;
MessageManager m_Messenger;
MaterialPropertyBlock m_SharedPreviewPropertyBlock; // stores preview properties (shared among ALL preview nodes)
Dictionary<AbstractMaterialNode, PreviewRenderData> m_RenderDatas = new Dictionary<AbstractMaterialNode, PreviewRenderData>(); // stores all of the PreviewRendererData, mapped by node
PreviewRenderData m_MasterRenderData; // ref to preview renderer data for the master node
int m_MaxPreviewsCompiling = 2; // max preview shaders we want to async compile at once
// state trackers
HashSet<AbstractMaterialNode> m_NodesShaderChanged = new HashSet<AbstractMaterialNode>(); // nodes whose shader code has changed, this node and nodes that read from it are put into NeedRecompile
HashSet<AbstractMaterialNode> m_NodesPropertyChanged = new HashSet<AbstractMaterialNode>(); // nodes whose property values have changed, the properties will need to be updated and all nodes that use that property re-rendered
HashSet<PreviewRenderData> m_PreviewsNeedsRecompile = new HashSet<PreviewRenderData>(); // previews we need to recompile the preview shader
HashSet<PreviewRenderData> m_PreviewsCompiling = new HashSet<PreviewRenderData>(); // previews currently being compiled
HashSet<PreviewRenderData> m_PreviewsToDraw = new HashSet<PreviewRenderData>(); // previews to re-render the texture (either because shader compile changed or property changed)
HashSet<PreviewRenderData> m_TimedPreviews = new HashSet<PreviewRenderData>(); // previews that are dependent on a time node -- i.e. animated / need to redraw every frame
double m_LastTimedUpdateTime = 0.0f;
bool m_TopologyDirty; // indicates topology changed, used to rebuild timed node list and preview type (2D/3D) inheritance.
HashSet<BlockNode> m_MasterNodeTempBlocks = new HashSet<BlockNode>(); // temp blocks used by the most recent master node preview generation.
// used to detect when texture assets have been modified
HashSet<string> m_PreviewTextureGUIDs = new HashSet<string>();
PreviewSceneResources m_SceneResources;
Texture2D m_ErrorTexture;
Vector2? m_NewMasterPreviewSize;
const AbstractMaterialNode kMasterProxyNode = null;
public PreviewRenderData masterRenderData
{
get { return m_MasterRenderData; }
}
public PreviewManager(GraphData graph, MessageManager messenger)
{
m_SharedPreviewPropertyBlock = new MaterialPropertyBlock();
m_Graph = graph;
m_Messenger = messenger;
m_ErrorTexture = GenerateFourSquare(Color.magenta, Color.black);
m_SceneResources = new PreviewSceneResources();
foreach (var node in m_Graph.GetNodes<AbstractMaterialNode>())
AddPreview(node);
AddMasterPreview();
}
static Texture2D GenerateFourSquare(Color c1, Color c2)
{
var tex = new Texture2D(2, 2);
tex.SetPixel(0, 0, c1);
tex.SetPixel(0, 1, c2);
tex.SetPixel(1, 0, c2);
tex.SetPixel(1, 1, c1);
tex.filterMode = FilterMode.Point;
tex.Apply();
return tex;
}
public void ResizeMasterPreview(Vector2 newSize)
{
m_NewMasterPreviewSize = newSize;
}
public PreviewRenderData GetPreviewRenderData(AbstractMaterialNode node)
{
PreviewRenderData result = null;
if (node == kMasterProxyNode ||
node is BlockNode ||
node == m_Graph.outputNode) // the outputNode, if it exists, is mapped to master
{
result = m_MasterRenderData;
}
else
{
m_RenderDatas.TryGetValue(node, out result);
}
return result;
}
void AddMasterPreview()
{
m_MasterRenderData = new PreviewRenderData
{
previewName = "Master Preview",
renderTexture =
new RenderTexture(400, 400, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default)
{
hideFlags = HideFlags.HideAndDontSave
},
previewMode = PreviewMode.Preview3D,
};
m_MasterRenderData.renderTexture.Create();
var shaderData = new PreviewShaderData
{
// even though a SubGraphOutputNode can be directly mapped to master (via m_Graph.outputNode)
// we always keep master node associated with kMasterProxyNode instead
// just easier if the association is always dynamic
node = kMasterProxyNode,
passesCompiling = 0,
isOutOfDate = true,
hasError = false,
};
m_MasterRenderData.shaderData = shaderData;
m_PreviewsNeedsRecompile.Add(m_MasterRenderData);
m_PreviewsToDraw.Add(m_MasterRenderData);
m_TopologyDirty = true;
}
public void UpdateMasterPreview(ModificationScope scope)
{
if (scope == ModificationScope.Topological ||
scope == ModificationScope.Graph)
{
// mark the master preview for recompile if it exists
// if not, no need to do it here, because it is always marked for recompile on creation
if (m_MasterRenderData != null)
m_PreviewsNeedsRecompile.Add(m_MasterRenderData);
m_TopologyDirty = true;
}
else if (scope == ModificationScope.Node)
{
if (m_MasterRenderData != null)
m_PreviewsToDraw.Add(m_MasterRenderData);
}
}
void AddPreview(AbstractMaterialNode node)
{
Assert.IsNotNull(node);
// BlockNodes have no preview for themselves, but are mapped to the "Master" preview
// SubGraphOutput nodes have their own previews, but will use the "Master" preview if they are the m_Graph.outputNode
if (node is BlockNode)
{
node.RegisterCallback(OnNodeModified);
UpdateMasterPreview(ModificationScope.Topological);
m_NodesPropertyChanged.Add(node);
return;
}
var renderData = new PreviewRenderData
{
previewName = node.name ?? "UNNAMED NODE",
renderTexture =
new RenderTexture(200, 200, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default)
{
hideFlags = HideFlags.HideAndDontSave
}
};
renderData.renderTexture.Create();
var shaderData = new PreviewShaderData
{
node = node,
passesCompiling = 0,
isOutOfDate = true,
hasError = false,
};
renderData.shaderData = shaderData;
m_RenderDatas.Add(node, renderData);
node.RegisterCallback(OnNodeModified);
m_PreviewsNeedsRecompile.Add(renderData);
m_NodesPropertyChanged.Add(node);
m_TopologyDirty = true;
}
void OnNodeModified(AbstractMaterialNode node, ModificationScope scope)
{
Assert.IsNotNull(node);
if (scope == ModificationScope.Topological ||
scope == ModificationScope.Graph)
{
m_NodesShaderChanged.Add(node); // shader code for this node changed, this will trigger m_PreviewsShaderChanged for all nodes downstream
m_NodesPropertyChanged.Add(node); // properties could also have changed at the same time and need to be re-collected
m_TopologyDirty = true;
}
else if (scope == ModificationScope.Node)
{
// if we only changed a constant on the node, we don't have to recompile the shader for it, just re-render it with the updated constant
// should instead flag m_NodesConstantChanged
m_NodesPropertyChanged.Add(node);
}
}
// temp structures that are kept around statically to avoid GC churn (not thread safe)
static Stack<AbstractMaterialNode> m_TempNodeWave = new Stack<AbstractMaterialNode>();
static HashSet<AbstractMaterialNode> m_TempAddedToNodeWave = new HashSet<AbstractMaterialNode>();
// cache the Action to avoid GC
static Action<AbstractMaterialNode> AddNextLevelNodesToWave =
nextLevelNode =>
{
if (!m_TempAddedToNodeWave.Contains(nextLevelNode))
{
m_TempNodeWave.Push(nextLevelNode);
m_TempAddedToNodeWave.Add(nextLevelNode);
}
};
internal enum PropagationDirection
{
Upstream,
Downstream
}
// ADDs all nodes in sources, and all nodes in the given direction relative to them, into result
// sources and result can be the same HashSet
private static readonly ProfilerMarker PropagateNodesMarker = new ProfilerMarker("PropagateNodes");
internal static void PropagateNodes(HashSet<AbstractMaterialNode> sources, PropagationDirection dir, HashSet<AbstractMaterialNode> result)
{
using (PropagateNodesMarker.Auto())
if (sources.Count > 0)
{
// NodeWave represents the list of nodes we still have to process and add to result
m_TempNodeWave.Clear();
m_TempAddedToNodeWave.Clear();
foreach (var node in sources)
{
m_TempNodeWave.Push(node);
m_TempAddedToNodeWave.Add(node);
}
while (m_TempNodeWave.Count > 0)
{
var node = m_TempNodeWave.Pop();
if (node == null)
continue;
result.Add(node);
// grab connected nodes in propagation direction, add them to the node wave
ForeachConnectedNode(node, dir, AddNextLevelNodesToWave);
}
// clean up any temp data
m_TempNodeWave.Clear();
m_TempAddedToNodeWave.Clear();
}
}
static void ForeachConnectedNode(AbstractMaterialNode node, PropagationDirection dir, Action<AbstractMaterialNode> action)
{
using (var tempEdges = PooledList<IEdge>.Get())
using (var tempSlots = PooledList<MaterialSlot>.Get())
{
// Loop through all nodes that the node feeds into.
if (dir == PropagationDirection.Downstream)
node.GetOutputSlots(tempSlots);
else
node.GetInputSlots(tempSlots);
foreach (var slot in tempSlots)
{
// get the edges out of each slot
tempEdges.Clear(); // and here we serialize another list, ouch!
node.owner.GetEdges(slot.slotReference, tempEdges);
foreach (var edge in tempEdges)
{
// We look at each node we feed into.
var connectedSlot = (dir == PropagationDirection.Downstream) ? edge.inputSlot : edge.outputSlot;
var connectedNode = connectedSlot.node;
action(connectedNode);
}
}
}
// Custom Interpolator Blocks have implied connections to their Custom Interpolator Nodes...
if (dir == PropagationDirection.Downstream && node is BlockNode bnode && bnode.isCustomBlock)
{
foreach (var cin in CustomInterpolatorUtils.GetCustomBlockNodeDependents(bnode))
{
action(cin);
}
}
// ... Just as custom Interpolator Nodes have implied connections to their custom interpolator blocks
if (dir == PropagationDirection.Upstream && node is CustomInterpolatorNode ciNode && ciNode.e_targetBlockNode != null)
{
action(ciNode.e_targetBlockNode);
}
}
public void ReloadChangedFiles(string ChangedFileDependencyGUIDs)
{
if (m_PreviewTextureGUIDs.Contains(ChangedFileDependencyGUIDs))
{
// have to setup the textures on the MaterialPropertyBlock again
// easiest is to just mark everything as needing property update
m_NodesPropertyChanged.UnionWith(m_RenderDatas.Keys);
}
}
public void HandleGraphChanges()
{
foreach (var node in m_Graph.addedNodes)
{
AddPreview(node);
m_TopologyDirty = true;
}
foreach (var edge in m_Graph.addedEdges)
{
var node = edge.inputSlot.node;
if (node != null)
{
if ((node is BlockNode) || (node is SubGraphOutputNode))
UpdateMasterPreview(ModificationScope.Topological);
else
m_NodesShaderChanged.Add(node);
m_TopologyDirty = true;
}
}
foreach (var node in m_Graph.removedNodes)
{
DestroyPreview(node);
m_TopologyDirty = true;
}
foreach (var edge in m_Graph.removedEdges)
{
var node = edge.inputSlot.node;
if ((node is BlockNode) || (node is SubGraphOutputNode))
{
UpdateMasterPreview(ModificationScope.Topological);
}
m_NodesShaderChanged.Add(node);
//When an edge gets deleted, if the node had the edge on creation, the properties would get out of sync and no value would get set.
//Fix for https://fogbugz.unity3d.com/f/cases/1284033/
m_NodesPropertyChanged.Add(node);
m_TopologyDirty = true;
}
foreach (var edge in m_Graph.addedEdges)
{
var node = edge.inputSlot.node;
if (node != null)
{
if ((node is BlockNode) || (node is SubGraphOutputNode))
{
UpdateMasterPreview(ModificationScope.Topological);
}
m_NodesShaderChanged.Add(node);
m_TopologyDirty = true;
}
}
// remove the nodes from the state trackers
m_NodesShaderChanged.ExceptWith(m_Graph.removedNodes);
m_NodesPropertyChanged.ExceptWith(m_Graph.removedNodes);
m_Messenger.ClearNodesFromProvider(this, m_Graph.removedNodes);
}
private static readonly ProfilerMarker CollectPreviewPropertiesMarker = new ProfilerMarker("CollectPreviewProperties");
void CollectPreviewProperties(IEnumerable<AbstractMaterialNode> nodesToCollect, PooledList<PreviewProperty> perMaterialPreviewProperties)
{
using (CollectPreviewPropertiesMarker.Auto())
using (var tempPreviewProps = PooledList<PreviewProperty>.Get())
{
// collect from all of the changed nodes
foreach (var propNode in nodesToCollect)
propNode.CollectPreviewMaterialProperties(tempPreviewProps);
// also grab all graph properties (they are updated every frame)
foreach (var prop in m_Graph.properties)
tempPreviewProps.Add(prop.GetPreviewMaterialProperty());
foreach (var previewProperty in tempPreviewProps)
{
previewProperty.SetValueOnMaterialPropertyBlock(m_SharedPreviewPropertyBlock);
// record guids for any texture properties
if ((previewProperty.propType >= PropertyType.Texture2D) && (previewProperty.propType <= PropertyType.Cubemap))
{
if (previewProperty.propType != PropertyType.Cubemap)
{
if (previewProperty.textureValue != null)
if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(previewProperty.textureValue, out string guid, out long localID))
{
// Note, this never gets cleared, so we accumulate texture GUIDs over time, if the user keeps changing textures
m_PreviewTextureGUIDs.Add(guid);
}
}
else
{
if (previewProperty.cubemapValue != null)
if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(previewProperty.cubemapValue, out string guid, out long localID))
{
// Note, this never gets cleared, so we accumulate texture GUIDs over time, if the user keeps changing textures
m_PreviewTextureGUIDs.Add(guid);
}
}
}
// virtual texture assignments must be pushed to the materials themselves (MaterialPropertyBlocks not supported)
if ((previewProperty.propType == PropertyType.VirtualTexture) &&
(previewProperty.vtProperty?.value?.layers != null))
{
perMaterialPreviewProperties.Add(previewProperty);
}
}
}
}
void AssignPerMaterialPreviewProperties(Material mat, List<PreviewProperty> perMaterialPreviewProperties)
{
foreach (var prop in perMaterialPreviewProperties)
{
switch (prop.propType)
{
case PropertyType.VirtualTexture:
// setup the VT textures on the material
bool setAnyTextures = false;
var vt = prop.vtProperty.value;
for (int layer = 0; layer < vt.layers.Count; layer++)
{
var texture = vt.layers[layer].layerTexture?.texture;
int propIndex = mat.shader.FindPropertyIndex(vt.layers[layer].layerRefName);
if (propIndex != -1)
{
mat.SetTexture(vt.layers[layer].layerRefName, texture);
setAnyTextures = true;
}
}
// also put in a request for the VT tiles, since preview rendering does not have feedback enabled
if (setAnyTextures)
{
#if ENABLE_VIRTUALTEXTURES
int stackPropertyId = Shader.PropertyToID(prop.vtProperty.referenceName);
try
{
// Ensure we always request the mip sized 256x256
int width, height;
UnityEngine.Rendering.VirtualTexturing.Streaming.GetTextureStackSize(mat, stackPropertyId, out width, out height);
int textureMip = (int)Math.Max(Mathf.Log(width, 2f), Mathf.Log(height, 2f));
const int baseMip = 8;
int mip = Math.Max(textureMip - baseMip, 0);
UnityEngine.Rendering.VirtualTexturing.Streaming.RequestRegion(mat, stackPropertyId, new Rect(0.0f, 0.0f, 1.0f, 1.0f), mip, UnityEngine.Rendering.VirtualTexturing.System.AllMips);
}
catch (InvalidOperationException)
{
// This gets thrown when the system is in an indeterminate state (like a material with no textures assigned which can obviously never have a texture stack streamed).
// This is valid in this case as we're still authoring the material.
}
#endif // ENABLE_VIRTUALTEXTURES
}
break;
}
}
}
bool TimedNodesShouldUpdate(EditorWindow editorWindow)
{
// get current screen FPS, clamp to what we consider a valid range
// this is probably not accurate for multi-monitor.. but should be relevant to at least one of the monitors
double monitorFPS = Screen.currentResolution.refreshRateRatio.value;
if (Double.IsInfinity(monitorFPS) || Double.IsNaN(monitorFPS))
monitorFPS = 60.0f;
monitorFPS = Math.Min(monitorFPS, 144.0);
monitorFPS = Math.Max(monitorFPS, 30.0);
var curTime = EditorApplication.timeSinceStartup;
var deltaTime = curTime - m_LastTimedUpdateTime;
bool isFocusedWindow = (EditorWindow.focusedWindow == editorWindow);
// we throttle the update rate, based on whether the window is focused and if unity is active
const double k_AnimatedFPS_WhenNotFocused = 10.0;
const double k_AnimatedFPS_WhenInactive = 2.0;
double maxAnimatedFPS =
(UnityEditorInternal.InternalEditorUtility.isApplicationActive ?
(isFocusedWindow ? monitorFPS : k_AnimatedFPS_WhenNotFocused) :
k_AnimatedFPS_WhenInactive);
bool update = (deltaTime > (1.0 / maxAnimatedFPS));
if (update)
m_LastTimedUpdateTime = curTime;
return update;
}
private static readonly ProfilerMarker RenderPreviewsMarker = new ProfilerMarker("RenderPreviews");
public void RenderPreviews(EditorWindow editorWindow, bool requestShaders = true)
{
using (RenderPreviewsMarker.Auto())
using (var renderList2D = PooledList<PreviewRenderData>.Get())
using (var renderList3D = PooledList<PreviewRenderData>.Get())
using (var nodesToDraw = PooledHashSet<AbstractMaterialNode>.Get())
using (var perMaterialPreviewProperties = PooledList<PreviewProperty>.Get())
{
// update topology cached data
// including list of time-dependent previews, and the preview mode (2d/3d)
UpdateTopology();
if (requestShaders)
UpdateShaders();
// Need to late capture custom interpolators because of how their type changes
// can have downstream impacts on dynamic slots.
HashSet<AbstractMaterialNode> customProps = new HashSet<AbstractMaterialNode>();
PropagateNodes(
new HashSet<AbstractMaterialNode>(m_NodesPropertyChanged.OfType<BlockNode>().Where(b => b.isCustomBlock)),
PropagationDirection.Downstream,
customProps);
m_NodesPropertyChanged.UnionWith(customProps);
// all nodes downstream of a changed property must be redrawn (to display the updated the property value)
PropagateNodes(m_NodesPropertyChanged, PropagationDirection.Downstream, nodesToDraw);
// always update properties from temporary blocks created by master node preview generation
m_NodesPropertyChanged.UnionWith(m_MasterNodeTempBlocks);
CollectPreviewProperties(m_NodesPropertyChanged, perMaterialPreviewProperties);
m_NodesPropertyChanged.Clear();
// timed nodes are animated, so they should be updated regularly (but not necessarily on every update)
// (m_TimedPreviews has been pre-propagated downstream)
// HOWEVER they do not need to collect properties. (the only property changing is time..)
if (TimedNodesShouldUpdate(editorWindow))
m_PreviewsToDraw.UnionWith(m_TimedPreviews);
ForEachNodesPreview(nodesToDraw, p => m_PreviewsToDraw.Add(p));
// redraw master when it is resized
if (m_NewMasterPreviewSize.HasValue)
m_PreviewsToDraw.Add(m_MasterRenderData);
// apply filtering to determine what nodes really get drawn
bool renderMasterPreview = false;
int drawPreviewCount = 0;
foreach (var preview in m_PreviewsToDraw)
{
Assert.IsNotNull(preview);
{ // skip if the node doesn't have a preview expanded (unless it's master)
var node = preview.shaderData.node;
if ((node != kMasterProxyNode) && (!node.hasPreview || !node.previewExpanded))
continue;
}
// check that we've got shaders and materials generated
// if not ,replace the rendered texture with null
if ((preview.shaderData.shader == null) ||
(preview.shaderData.mat == null))
{
// avoid calling NotifyPreviewChanged repeatedly
if (preview.texture != null)
{
preview.texture = null;
preview.NotifyPreviewChanged();
}
continue;
}
if (preview.shaderData.hasError)
{
preview.texture = m_ErrorTexture;
preview.NotifyPreviewChanged();
continue;
}
// skip rendering while a preview shader is being compiled
if (m_PreviewsCompiling.Contains(preview))
continue;
// we want to render this thing, now categorize what kind of render it is
if (preview == m_MasterRenderData)
renderMasterPreview = true;
else if (preview.previewMode == PreviewMode.Preview2D)
renderList2D.Add(preview);
else
renderList3D.Add(preview);
drawPreviewCount++;
}
// if we actually don't want to render anything at all, early out here
if (drawPreviewCount <= 0)
return;
var time = Time.realtimeSinceStartup;
var timeParameters = new Vector4(time, Mathf.Sin(time), Mathf.Cos(time), 0.0f);
m_SharedPreviewPropertyBlock.SetVector("_TimeParameters", timeParameters);
EditorUtility.SetCameraAnimateMaterialsTime(m_SceneResources.camera, time);
m_SceneResources.light0.enabled = true;
m_SceneResources.light0.intensity = 1.0f;
m_SceneResources.light0.transform.rotation = Quaternion.Euler(50f, 50f, 0);
m_SceneResources.light1.enabled = true;
m_SceneResources.light1.intensity = 1.0f;
m_SceneResources.camera.clearFlags = CameraClearFlags.Color;
// Render 2D previews
m_SceneResources.camera.transform.SetPositionAndRotation(-Vector3.forward * 2, Quaternion.identity);
m_SceneResources.camera.orthographicSize = 0.5f;
m_SceneResources.camera.orthographic = true;
foreach (var renderData in renderList2D)
RenderPreview(renderData, m_SceneResources.quad, Matrix4x4.identity, perMaterialPreviewProperties);
// Render 3D previews
m_SceneResources.camera.transform.SetPositionAndRotation(-Vector3.forward * 5, Quaternion.identity);
m_SceneResources.camera.orthographic = false;
foreach (var renderData in renderList3D)
RenderPreview(renderData, m_SceneResources.sphere, Matrix4x4.identity, perMaterialPreviewProperties);
if (renderMasterPreview)
{
if (m_NewMasterPreviewSize.HasValue)
{
if (masterRenderData.renderTexture != null)
Object.DestroyImmediate(masterRenderData.renderTexture, true);
masterRenderData.renderTexture = new RenderTexture((int)m_NewMasterPreviewSize.Value.x, (int)m_NewMasterPreviewSize.Value.y, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave };
masterRenderData.renderTexture.Create();
masterRenderData.texture = masterRenderData.renderTexture;
m_NewMasterPreviewSize = null;
}
var mesh = m_Graph.previewData.serializedMesh.mesh;
var preventRotation = m_Graph.previewData.preventRotation;
if (!mesh)
{
var useSpritePreview =
m_Graph.activeTargets.LastOrDefault(t => t.IsActive())?.prefersSpritePreview ?? false;
mesh = useSpritePreview ? m_SceneResources.quad : m_SceneResources.sphere;
preventRotation = useSpritePreview;
}
var previewTransform = preventRotation ? Matrix4x4.identity : Matrix4x4.Rotate(m_Graph.previewData.rotation);
var scale = m_Graph.previewData.scale;
previewTransform *= Matrix4x4.Scale((Vector3.one).magnitude * scale * Vector3.one / mesh.bounds.size.magnitude);
previewTransform *= Matrix4x4.Translate(-mesh.bounds.center);
RenderPreview(masterRenderData, mesh, previewTransform, perMaterialPreviewProperties);
}
m_SceneResources.light0.enabled = false;
m_SceneResources.light1.enabled = false;
foreach (var renderData in renderList2D)
renderData.NotifyPreviewChanged();
foreach (var renderData in renderList3D)
renderData.NotifyPreviewChanged();
if (renderMasterPreview)
masterRenderData.NotifyPreviewChanged();
}
}
private static readonly ProfilerMarker ProcessCompletedShaderCompilationsMarker = new ProfilerMarker("ProcessCompletedShaderCompilations");
private int compileFailRekicks = 0;
void ProcessCompletedShaderCompilations()
{
// Check for shaders that finished compiling and set them to redraw
using (ProcessCompletedShaderCompilationsMarker.Auto())
using (var previewsCompiled = PooledHashSet<PreviewRenderData>.Get())
{
foreach (var preview in m_PreviewsCompiling)
{
{
var node = preview.shaderData.node;
Assert.IsFalse(node is BlockNode);
}
PreviewRenderData renderData = preview;
PreviewShaderData shaderData = renderData.shaderData;
// Assert.IsTrue(shaderData.passesCompiling > 0);
if (shaderData.passesCompiling <= 0)
{
Debug.Log("Zero Passes: " + preview.previewName + " (" + shaderData.passesCompiling + " passes, " + renderData.shaderData.mat.passCount + " mat passes)");
}
if (shaderData.passesCompiling != renderData.shaderData.mat.passCount)
{
// attempt to re-kick the compilation a few times
Debug.Log("Rekicking Compiling: " + preview.previewName + " (" + shaderData.passesCompiling + " passes, " + renderData.shaderData.mat.passCount + " mat passes)");
compileFailRekicks++;
if (compileFailRekicks <= 3)
{
shaderData.passesCompiling = 0;
previewsCompiled.Add(renderData);
m_PreviewsNeedsRecompile.Add(renderData);
continue;
}
else if (compileFailRekicks == 4)
{
Debug.LogWarning("Unexpected error in compiling preview shaders: some previews might not update. You can try to re-open the Shader Graph window, or select <b>Help > Report a Bug</b> in the menu and report this bug.");
}
}
// check that all passes have compiled
var allPassesCompiled = true;
for (var i = 0; i < renderData.shaderData.mat.passCount; i++)
{
if (!ShaderUtil.IsPassCompiled(renderData.shaderData.mat, i))
{
allPassesCompiled = false;
break;
}
}
if (!allPassesCompiled)
{
// keep waiting
continue;
}
// Force the material to re-generate all it's shader properties, by reassigning the shader
renderData.shaderData.mat.shader = renderData.shaderData.shader;
renderData.shaderData.passesCompiling = 0;
renderData.shaderData.isOutOfDate = false;
CheckForErrors(renderData.shaderData);
previewsCompiled.Add(renderData);
}
// removed compiled nodes from compiling list
m_PreviewsCompiling.ExceptWith(previewsCompiled);
// and add them to the draw list to display updated shader (note this will only redraw specifically this node, not any others)
m_PreviewsToDraw.UnionWith(previewsCompiled);
}
}
private static readonly ProfilerMarker KickOffShaderCompilationsMarker = new ProfilerMarker("KickOffShaderCompilations");
void KickOffShaderCompilations()
{
// Start compilation for nodes that need to recompile
using (KickOffShaderCompilationsMarker.Auto())
using (var previewsToCompile = PooledHashSet<PreviewRenderData>.Get())
{
// master node compile is first in the priority list, as it takes longer than the other previews
if (m_PreviewsCompiling.Count + previewsToCompile.Count < m_MaxPreviewsCompiling)
{
if (m_PreviewsNeedsRecompile.Contains(m_MasterRenderData) &&
!m_PreviewsCompiling.Contains(m_MasterRenderData))
{
previewsToCompile.Add(m_MasterRenderData);
m_PreviewsNeedsRecompile.Remove(m_MasterRenderData);
}
}
// add each node to compile list if it needs a preview, is not already compiling, and we have room
// (we don't want to double kick compiles, so wait for the first one to get back before kicking another)
for (int i = 0; i < m_PreviewsNeedsRecompile.Count; i++)
{
if (m_PreviewsCompiling.Count + previewsToCompile.Count >= m_MaxPreviewsCompiling)
break;
var preview = m_PreviewsNeedsRecompile.ElementAt(i);
if (preview == m_MasterRenderData) // master preview is handled specially above
continue;
var node = preview.shaderData.node;
Assert.IsNotNull(node);
Assert.IsFalse(node is BlockNode);
if (node.hasPreview && node.previewExpanded && !m_PreviewsCompiling.Contains(preview))
{
previewsToCompile.Add(preview);
}
}
if (previewsToCompile.Count >= 0)
using (var nodesToCompile = PooledHashSet<AbstractMaterialNode>.Get())
{
// remove the selected nodes from the recompile list
m_PreviewsNeedsRecompile.ExceptWith(previewsToCompile);
// Reset error states for the UI, the shader, and all render data for nodes we're recompiling
nodesToCompile.UnionWith(previewsToCompile.Select(x => x.shaderData.node));
nodesToCompile.Remove(null);
// TODO: not sure if we need to clear BlockNodes when master gets rebuilt?
m_Messenger.ClearNodesFromProvider(this, nodesToCompile);
// Force async compile on
var wasAsyncAllowed = ShaderUtil.allowAsyncCompilation;
ShaderUtil.allowAsyncCompilation = true;
// kick async compiles for all nodes in m_NodeToCompile
foreach (var preview in previewsToCompile)
{
if (preview == m_MasterRenderData)
{
CompileMasterNodeShader();
continue;
}
var node = preview.shaderData.node;
Assert.IsNotNull(node); // master preview is handled above
// Get shader code and compile
var generator = new Generator(node.owner, node, GenerationMode.Preview, $"hidden/preview/{node.GetVariableNameForNode()}");
BeginCompile(preview, generator.generatedShader);
}
ShaderUtil.allowAsyncCompilation = wasAsyncAllowed;
}
}
}
private static readonly ProfilerMarker UpdateShadersMarker = new ProfilerMarker("UpdateShaders");
void UpdateShaders()
{
using (UpdateShadersMarker.Auto())
{
ProcessCompletedShaderCompilations();
if (m_NodesShaderChanged.Count > 0)
{
// nodes with shader changes cause all downstream nodes to need recompilation
// (since they presumably include the code for these nodes)
using (var nodesToRecompile = PooledHashSet<AbstractMaterialNode>.Get())
{
PropagateNodes(m_NodesShaderChanged, PropagationDirection.Downstream, nodesToRecompile);
ForEachNodesPreview(nodesToRecompile, p => m_PreviewsNeedsRecompile.Add(p));
m_NodesShaderChanged.Clear();
}
}
// if there's nothing to update, or if too many nodes are still compiling, then just return
if ((m_PreviewsNeedsRecompile.Count == 0) || (m_PreviewsCompiling.Count >= m_MaxPreviewsCompiling))
return;
// flag all nodes in m_PreviewsNeedsRecompile as having out of date textures, and redraw them
foreach (var preview in m_PreviewsNeedsRecompile)
{
Assert.IsNotNull(preview);
if (!preview.shaderData.isOutOfDate)
{
preview.shaderData.isOutOfDate = true;
preview.NotifyPreviewChanged();
}
}
InitializeSRPIfNeeded(); // SRP must be initialized to compile master node previews
KickOffShaderCompilations();
}
}
private static readonly ProfilerMarker BeginCompileMarker = new ProfilerMarker("BeginCompile");
void BeginCompile(PreviewRenderData renderData, string shaderStr)
{
using (BeginCompileMarker.Auto())
{
var shaderData = renderData.shaderData;
// want to ensure this so we don't get confused with multiple compile versions in flight
Assert.IsTrue(shaderData.passesCompiling == 0);
if (shaderData.shader == null)
{
shaderData.shader = ShaderUtil.CreateShaderAsset(shaderStr, false);
shaderData.shader.hideFlags = HideFlags.HideAndDontSave;
}
else
{
ShaderUtil.ClearCachedData(shaderData.shader);
ShaderUtil.ClearShaderMessages(shaderData.shader);
ShaderUtil.UpdateShaderAsset(shaderData.shader, shaderStr, false);
}
// Set up the material we use for the preview
// Due to case 1259744, we have to re-create the material to update the preview material keywords
Object.DestroyImmediate(shaderData.mat);
{
shaderData.mat = new Material(shaderData.shader) { hideFlags = HideFlags.HideAndDontSave };
if (renderData == m_MasterRenderData)
{
// apply active target settings to the Material
foreach (var target in m_Graph.activeTargets)
{
if (target.IsActive())
target.ProcessPreviewMaterial(renderData.shaderData.mat);
}
}
}
int materialPassCount = shaderData.mat.passCount;
if (materialPassCount <= 0)
Debug.Log("Zero Passes ON COMPILE: " + shaderData.node.name + " (" + shaderData.passesCompiling + " passes, " + renderData.shaderData.mat.passCount + " mat passes)");
else
{
shaderData.passesCompiling = materialPassCount;
for (var i = 0; i < materialPassCount; i++)
{
ShaderUtil.CompilePass(shaderData.mat, i);
}
m_PreviewsCompiling.Add(renderData);
}
}
}
private void ForEachNodesPreview(
IEnumerable<AbstractMaterialNode> nodes,
Action<PreviewRenderData> action)
{
foreach (var node in nodes)
{
var preview = GetPreviewRenderData(node);
if (preview != null) // some output nodes may have no preview
action(preview);
}
}
class NodeProcessor
{
// parameters
GraphData graphData;
Action<AbstractMaterialNode, IEnumerable<AbstractMaterialNode>> process;
// node tracking state
HashSet<AbstractMaterialNode> processing = new HashSet<AbstractMaterialNode>();
HashSet<AbstractMaterialNode> processed = new HashSet<AbstractMaterialNode>();
// iteration state stack
Stack<AbstractMaterialNode> nodeStack = new Stack<AbstractMaterialNode>();
Stack<int> childStartStack = new Stack<int>();
Stack<int> curChildStack = new Stack<int>();
Stack<int> stateStack = new Stack<int>();
List<AbstractMaterialNode> allChildren = new List<AbstractMaterialNode>();
public NodeProcessor(GraphData graphData, Action<AbstractMaterialNode, IEnumerable<AbstractMaterialNode>> process)
{
this.graphData = graphData;
this.process = process;
}
public void ProcessInDependencyOrder(AbstractMaterialNode root)
{
// early out to skip a bit of work
if (processed.Contains(root))
return;
// push root node in the initial state
stateStack.Push(0);
nodeStack.Push(root);
while (nodeStack.Count > 0)
{
// check the state of the top of the stack
switch (stateStack.Pop())
{
case 0: // node initial state (valid stacks: nodeStack)
{
var node = nodeStack.Peek();
if (processed.Contains(node))
{
// finished with this node, pop it off the stack
nodeStack.Pop();
continue;
}
if (processing.Contains(node))
{
// not processed, but still processing.. means there was a circular dependency here