-
Notifications
You must be signed in to change notification settings - Fork 533
/
SF_Editor.cs
executable file
·2098 lines (1511 loc) · 62.5 KB
/
SF_Editor.cs
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 UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Reflection;
using System.Net;
using System.Collections;
namespace ShaderForge {
public delegate T Func<T>();
public enum UpToDateState{ UpToDate, OutdatedSoft, OutdatedHard };
[Serializable]
public class SF_Editor : EditorWindow {
[SerializeField]
public SF_Evaluator shaderEvaluator;
[SerializeField]
public SF_PreviewWindow preview;
[SerializeField]
public SF_EditorNodeView nodeView;
[SerializeField]
public SF_EditorNodeBrowser nodeBrowser;
[SerializeField]
public SF_PassSettings ps; // TODO: Move
[System.NonSerialized]
public static SF_Editor instance;
[SerializeField]
public SFN_Final mainNode;
[SerializeField]
public SF_StatusBox statusBox;
[SerializeField]
public List<SF_Node> nodes;
[SerializeField]
DateTime startTime = DateTime.UtcNow;
[SerializeField]
GUIStyle windowStyle;
[SerializeField]
GUIStyle titleStyle;
[SerializeField]
GUIStyle versionStyle;
[SerializeField]
GUIStyle nodeScrollbarStyle;
[SerializeField]
public SF_DraggableSeparator separatorLeft;
[SerializeField]
public SF_DraggableSeparator separatorRight;
public Vector2 mousePosition = Vector2.zero;
[SerializeField]
public Shader currentShaderAsset;
[SerializeField]
public string currentShaderPath;
[SerializeField]
public List<SF_EditorNodeData> nodeTemplates;
[SerializeField]
private UpToDateState shaderOutdated = UpToDateState.UpToDate;
public UpToDateState ShaderOutdated{
get{
return shaderOutdated;
}
set{
if(shaderOutdated != value){
//Debug.Log("Changed outdated state to " + value);
shaderOutdated = value;
}
}
}
[NonSerialized]
public bool initialized = false;
public SF_Editor() {
if(SF_Debug.window)
Debug.Log( "[SF_LOG] - SF_Editor CONSTRUCTOR SF_Editor()" );
SF_Editor.instance = this;
}
[MenuItem( "Tools/Shader Forge" )]
static void InitEmpty() {
if( SF_Editor.instance == null )
Init( null );
else
EditorWindow.GetWindow<SF_Editor>(); // Focus
}
void OnEnable() {
SF_Settings.LoadAllFromDisk();
titleContent = new GUIContent( "Shader Forge", (Texture)SF_GUI.Icon );
if( this.preview != null )
preview.OnEnable();
}
void OnDisable(){
if(shaderOutdated != UpToDateState.UpToDate){
fullscreenMessage = "Saving...";
Repaint();
shaderEvaluator.Evaluate();
}
if( this.preview != null )
preview.OnDisable();
SF_Settings.SaveAllToDisk();
}
void OnDestroy(){
DestroyImmediate( preview.internalMaterial );
}
public static bool Init( Shader initShader = null ) {
// To make sure you get periods as decimal separators
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
if(SF_Debug.evalFlow || SF_Debug.dynamicNodeLoad)
Debug.Log( "[SF_LOG] - SF_Editor Init(" + initShader + ")" );
SF_Editor materialEditor = (SF_Editor)EditorWindow.GetWindow( typeof( SF_Editor ) );
SF_Editor.instance = materialEditor;
bool loaded = materialEditor.InitializeInstance( initShader );
if( !loaded )
return false;
return true;
}
public int GetUniqueNodeID() {
int[] occupiedIDs = nodes.Select( x => x.id ).ToArray();
int id = -1;
int limit = 1000000;
do {
id = UnityEngine.Random.Range(1,9999);
limit--;
} while( occupiedIDs.Contains( id ) && limit > 0 );
if( limit <= 0 )
Debug.LogError("Ran out of attempts to find a unique node ID");
return id;
}
public void InitializeNodeTemplates() {
nodeTemplates = new List<SF_EditorNodeData>();
// AddTemplate( typeof( SFN_CommentBox ), "Comment Box" );
string catArithmetic = "Arithmetic/";
AddTemplate( typeof( SFN_Abs ), catArithmetic + "Abs" );
AddTemplate( typeof( SFN_Add ), catArithmetic + "Add", KeyCode.A );
AddTemplate( typeof( SFN_Blend ), catArithmetic + "Blend", KeyCode.B );
AddTemplate( typeof( SFN_BlendOver ), catArithmetic + "Blend Over" );
AddTemplate( typeof( SFN_Ceil ), catArithmetic + "Ceil" );
AddTemplate( typeof( SFN_Clamp ), catArithmetic + "Clamp" );
AddTemplate( typeof( SFN_Clamp01 ), catArithmetic + "Clamp 0-1" );
AddTemplate( typeof( SFN_ConstantClamp ), catArithmetic + "Clamp (Simple)",KeyCode.None, "Clamp Simple" );
AddTemplate( typeof( SFN_Divide ), catArithmetic + "Divide", KeyCode.D );
AddTemplate( typeof( SFN_Exp ), catArithmetic + "Exp" );
AddTemplate( typeof( SFN_Floor ), catArithmetic + "Floor" );
AddTemplate( typeof( SFN_Fmod ), catArithmetic + "Fmod" );
AddTemplate( typeof( SFN_Frac ), catArithmetic + "Frac" );
AddTemplate( typeof( SFN_HsvToRgb ), catArithmetic + "HSV to RGB" );
AddTemplate( typeof( SFN_Hue ), catArithmetic + "Hue" );
AddTemplate( typeof( SFN_If ), catArithmetic + "If", KeyCode.I );
AddTemplate( typeof( SFN_InverseLerp ), catArithmetic + "Inverse Lerp" );
AddTemplate( typeof( SFN_ConstantInverseLerp ), catArithmetic + "Inverse Lerp (Simple)" );
AddTemplate( typeof( SFN_Lerp ), catArithmetic + "Lerp", KeyCode.L );
AddTemplate( typeof( SFN_ConstantLerp ), catArithmetic + "Lerp (Simple)", KeyCode.None, "Lerp Simple" );
AddTemplate( typeof( SFN_Log ), catArithmetic + "Log" );
AddTemplate( typeof( SFN_Max ), catArithmetic + "Max" );
AddTemplate( typeof( SFN_Min ), catArithmetic + "Min" );
AddTemplate( typeof( SFN_Multiply ), catArithmetic + "Multiply", KeyCode.M );
AddTemplate( typeof( SFN_MultiplyMatrix ), catArithmetic + "Multiply Matrix" );
AddTemplate( typeof( SFN_Negate ), catArithmetic + "Negate" );
AddTemplate( typeof( SFN_Noise ), catArithmetic + "Noise" );
AddTemplate( typeof( SFN_OneMinus ), catArithmetic + "One Minus", KeyCode.O );
AddTemplate( typeof( SFN_Posterize ), catArithmetic + "Posterize" );
AddTemplate( typeof( SFN_Power ), catArithmetic + "Power", KeyCode.E );
AddTemplate( typeof( SFN_Reciprocal ), catArithmetic + "Reciprocal" );
AddTemplate( typeof( SFN_RemapRangeAdvanced),catArithmetic+ "Remap" );
AddTemplate( typeof( SFN_RemapRange ), catArithmetic + "Remap (Simple)", KeyCode.R, "Remap Simple" );
AddTemplate( typeof( SFN_RgbToHsv ), catArithmetic + "RGB to HSV" );
AddTemplate( typeof( SFN_Round ), catArithmetic + "Round" );
AddTemplate( typeof( SFN_Sign ), catArithmetic + "Sign" );
AddTemplate( typeof( SFN_Smoothstep ), catArithmetic + "Smoothstep" ).MarkAsNewNode();
AddTemplate( typeof( SFN_Sqrt ), catArithmetic + "Sqrt" );
AddTemplate( typeof( SFN_Step ), catArithmetic + "Step (A <= B)", KeyCode.None, "Step" );
AddTemplate( typeof( SFN_Subtract ), catArithmetic + "Subtract", KeyCode.S );
AddTemplate( typeof( SFN_Trunc ), catArithmetic + "Trunc" );
string catConstVecs = "Constant Vectors/";
AddTemplate( typeof( SFN_Vector1 ), catConstVecs + "Value", KeyCode.Alpha1 );
AddTemplate( typeof( SFN_Vector2 ), catConstVecs + "Vector 2", KeyCode.Alpha2 );
AddTemplate( typeof( SFN_Vector3 ), catConstVecs + "Vector 3", KeyCode.Alpha3 );
AddTemplate( typeof( SFN_Vector4 ), catConstVecs + "Vector 4", KeyCode.Alpha4 );
AddTemplate( typeof( SFN_Matrix4x4 ), catConstVecs + "Matrix 4x4" );
string catProps = "Properties/";
AddTemplate( typeof( SFN_Color ), catProps + "Color" );
AddTemplate( typeof( SFN_Cubemap ), catProps + "Cubemap" );
AddTemplate( typeof( SFN_Matrix4x4Property ), catProps + "Matrix 4x4" );
AddTemplate( typeof( SFN_Slider ), catProps + "Slider" );
AddTemplate( typeof( SFN_SwitchProperty ), catProps + "Switch" );
AddTemplate( typeof( SFN_Tex2d ), catProps + "Texture 2D", KeyCode.T );
AddTemplate( typeof( SFN_Tex2dAsset ), catProps + "Texture Asset" );
AddTemplate( typeof( SFN_ToggleProperty ), catProps + "Toggle" );
AddTemplate( typeof( SFN_ValueProperty ), catProps + "Value" );
AddTemplate( typeof( SFN_Vector4Property ), catProps + "Vector 4" );
//string catBranching = "Branching/";
//AddTemplate( typeof( SFN_StaticBranch ), catBranching + "Static Branch" );
string catVecOps = "Vector Operations/";
AddTemplate( typeof( SFN_Append ), catVecOps + "Append", KeyCode.Q );
AddTemplate( typeof( SFN_ChannelBlend ), catVecOps + "Channel Blend");
AddTemplate( typeof( SFN_ComponentMask ), catVecOps + "Component Mask", KeyCode.C );
AddTemplate( typeof( SFN_Cross ), catVecOps + "Cross Product" );
AddTemplate( typeof( SFN_Desaturate ), catVecOps + "Desaturate" );
AddTemplate( typeof( SFN_DDX ), catVecOps + "DDX" );
AddTemplate( typeof( SFN_DDXY ), catVecOps + "DDXY" ).MarkAsNewNode();
AddTemplate( typeof( SFN_DDY ), catVecOps + "DDY" );
AddTemplate( typeof( SFN_Distance ), catVecOps + "Distance" );
AddTemplate( typeof( SFN_Dot ), catVecOps + "Dot Product" );
AddTemplate( typeof( SFN_Length ), catVecOps + "Length" );
AddTemplate( typeof( SFN_Normalize ), catVecOps + "Normalize", KeyCode.N );
AddTemplate( typeof( SFN_NormalBlend ), catVecOps + "Normal Blend" );
AddTemplate( typeof( SFN_Reflect ), catVecOps + "Reflect" );
AddTemplate( typeof( SFN_Transform ), catVecOps + "Transform" );
AddTemplate( typeof( SFN_Transpose ), catVecOps + "Transpose" );
AddTemplate( typeof( SFN_VectorProjection ),catVecOps + "Vector Projection" );
AddTemplate( typeof( SFN_VectorRejection ), catVecOps + "Vector Rejection" );
string catUvOps = "UV Operations/";
AddTemplate( typeof( SFN_Panner ), catUvOps + "Panner", KeyCode.P );
AddTemplate( typeof( SFN_Parallax ), catUvOps + "Parallax" );
AddTemplate( typeof( SFN_Rotator ), catUvOps + "Rotator" );
AddTemplate( typeof( SFN_UVTile ), catUvOps + "UV Tile" );
string catGeoData = "Geometry Data/";
AddTemplate( typeof( SFN_Bitangent ), catGeoData + "Bitangent Dir.");
AddTemplate( typeof( SFN_Depth ), catGeoData + "Depth");
AddTemplate( typeof( SFN_FaceSign ), catGeoData + "Face Sign" );
AddTemplate( typeof( SFN_Fresnel ), catGeoData + "Fresnel", KeyCode.F );
AddTemplate( typeof( SFN_NormalVector ), catGeoData + "Normal Dir." );
AddTemplate( typeof( SFN_ObjectPosition ), catGeoData + "Object Position");
AddTemplate( typeof( SFN_ObjectScale ), catGeoData + "Object Scale" );
AddTemplate( typeof( SFN_ScreenPos ), catGeoData + "Screen Position" );
AddTemplate( typeof( SFN_Tangent ), catGeoData + "Tangent Dir." );
AddTemplate( typeof( SFN_TexCoord ), catGeoData + "UV Coordinates", KeyCode.U );
AddTemplate( typeof( SFN_VertexColor ), catGeoData + "Vertex Color", KeyCode.V );
AddTemplate( typeof( SFN_ViewVector ), catGeoData + "View Dir." );
AddTemplate( typeof( SFN_ViewReflectionVector ), catGeoData + "View Refl. Dir.", KeyCode.None, "View Reflection" );
AddTemplate( typeof( SFN_FragmentPosition ), catGeoData + "World Position", KeyCode.W );
string catLighting = "Lighting/";
AddTemplate( typeof( SFN_AmbientLight ), catLighting + "Ambient Light" );
AddTemplate( typeof( SFN_HalfVector ), catLighting + "Half Direction", KeyCode.H ).UavailableInDeferredPrePass();
AddTemplate( typeof( SFN_LightAttenuation ), catLighting + "Light Attenuation" ).UavailableInDeferredPrePass();
AddTemplate( typeof( SFN_LightColor ), catLighting + "Light Color" ).UavailableInDeferredPrePass();
AddTemplate( typeof( SFN_LightVector ), catLighting + "Light Direction" ).UavailableInDeferredPrePass();
AddTemplate( typeof( SFN_LightPosition ), catLighting + "Light Position" ).UavailableInDeferredPrePass();
string catExtData = "External Data/";
AddTemplate( typeof( SFN_PixelSize ), catExtData + "Pixel Size" );
AddTemplate( typeof( SFN_ProjectionParameters ), catExtData + "Projection Parameters" );
AddTemplate( typeof( SFN_ScreenParameters ), catExtData + "Screen Parameters" );
AddTemplate( typeof( SFN_Time ), catExtData + "Time" );
AddTemplate( typeof( SFN_ViewPosition ), catExtData + "View Position" );
string catSceneData = "Scene Data/";
AddTemplate( typeof(SFN_DepthBlend), catSceneData + "Depth Blend" );
AddTemplate( typeof( SFN_FogColor ), catSceneData + "Fog Color" );
AddTemplate( typeof(SFN_SceneColor), catSceneData + "Scene Color" );
AddTemplate( typeof(SFN_SceneDepth), catSceneData + "Scene Depth" );
string catMathConst = "Math Constants/";
AddTemplate( typeof( SFN_E ), catMathConst + "e", KeyCode.None, "EulersConstant" );
AddTemplate( typeof( SFN_Phi ), catMathConst + "Phi" );
AddTemplate( typeof( SFN_Pi ), catMathConst + "Pi" );
AddTemplate( typeof( SFN_Root2 ), catMathConst + "Root 2" );
AddTemplate( typeof( SFN_Tau ), catMathConst + "Tau (2 Pi)", KeyCode.None, "Tau" );
string catTrig = "Trigonometry/";
AddTemplate( typeof( SFN_ArcCos ), catTrig + "ArcCos" );
AddTemplate( typeof( SFN_ArcSin ), catTrig + "ArcSin" );
AddTemplate( typeof( SFN_ArcTan ), catTrig + "ArcTan" );
AddTemplate( typeof( SFN_ArcTan2 ), catTrig + "ArcTan2" );
AddTemplate( typeof( SFN_Cos ), catTrig + "Cos" );
AddTemplate( typeof( SFN_Sin ), catTrig + "Sin" );
AddTemplate( typeof( SFN_Tan ), catTrig + "Tan" );
string catCode = "Code/";
AddTemplate( typeof( SFN_Code ), catCode + "Code" );
string catUtility = "Utility/";
AddTemplate( typeof( SFN_Relay ), catUtility + "Relay" );
AddTemplate( typeof( SFN_Get ), catUtility + "Get", KeyCode.G ).MarkAsNewNode();
AddTemplate( typeof( SFN_Set ), catUtility + "Set" ).MarkAsNewNode();
SF_EditorNodeData ssDiff = TryAddTemplateDynamic( "SFN_SkyshopDiff", "Skyshop/" + "Skyshop Diffuse" );
if(ssDiff != null)
ssDiff.MarkAsNewNode();
SF_EditorNodeData ssSpec = TryAddTemplateDynamic( "SFN_SkyshopSpec", "Skyshop/" + "Skyshop Specular" );
if( ssSpec != null )
ssSpec.MarkAsNewNode();
}
public static bool NodeExistsAndIs(SF_Node node, string nodeName){
if(NodeExists(nodeName))
if(node.GetType() == GetNodeType(nodeName))
return true;
return false;
}
public static bool NodeExists(string nodeName){
return GetNodeType(nodeName) != null;
}
static Assembly editorAssembly;
public static Assembly EditorAssembly {
get {
if( editorAssembly == null ) {
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach( Assembly assembly in assemblies ) {
if( assembly.FullName.Split( ',' )[0].Trim() == "Assembly-CSharp-Editor" ) {
editorAssembly = assembly;
return editorAssembly;
}
}
//if( SF_Debug.dynamicNodeLoad )
// Debug.LogError("Unable to find the editor assembly" );
}
return editorAssembly;
}
}
public static Type GetNodeType(string nodeName){
Assembly asm = EditorAssembly;
if( asm == null )
return null;
string fullNodeName = nodeName;
if(!nodeName.StartsWith("ShaderForge."))
fullNodeName = "ShaderForge." + nodeName;
if( SF_Debug.dynamicNodeLoad )
Debug.Log( "Trying to dynamically load [" + fullNodeName + "]" + " in assembly [" + asm.FullName + "]" );
return asm.GetType( fullNodeName );
}
public SF_EditorNodeData TryAddTemplateDynamic(string type, string label, KeyCode keyCode = KeyCode.None, string searchName = null ){
Type dynType = GetNodeType(type);
if(dynType != null){
if(SF_Debug.dynamicNodeLoad)
Debug.Log( "TryAddTemplateDynamic of " + type );
return AddTemplate( dynType, label, keyCode, searchName );
}
if( SF_Debug.dynamicNodeLoad )
Debug.Log( "TryAddTemplateDynamic of " + type + " was null" );
return null;
}
public SF_EditorNodeData AddTemplate( Type type, string label, KeyCode keyCode = KeyCode.None, string searchName = null ) {
SF_EditorNodeData item = ScriptableObject.CreateInstance<SF_EditorNodeData>().Initialize( type.FullName, label, keyCode );
if(!string.IsNullOrEmpty(searchName)){
item.SearchName = searchName;
}
this.nodeTemplates.Add( item );
return item;
}
public SF_EditorNodeData GetTemplate<T>() {
foreach( SF_EditorNodeData sft in nodeTemplates ) {
if( sft.type == typeof(T).FullName )
return sft;
}
return null;
}
public SF_EditorNodeData GetTemplate( string typeName ) {
foreach( SF_EditorNodeData sft in nodeTemplates ) {
if( sft.type == typeName )
return sft;
}
return null;
}
public void OnShaderModified(NodeUpdateType updType) {
//Debug.Log("OnShaderModified: " + updType.ToString() );
if( updType == NodeUpdateType.Hard && nodeView.treeStatus.CheckCanCompile() ){
nodeView.lastChangeTime = (float)EditorApplication.timeSinceStartup;
ShaderOutdated = UpToDateState.OutdatedHard;
}
if(updType == NodeUpdateType.Soft && ShaderOutdated == UpToDateState.UpToDate)
ShaderOutdated = UpToDateState.OutdatedSoft;
ps.fChecker.UpdateAvailability();
ps.UpdateAutoSettings();
}
public void ResetRunningOutdatedTimer(){
if(ShaderOutdated == UpToDateState.UpToDate)
return;
if(ShaderOutdated == UpToDateState.OutdatedSoft) // Might not want to have this later
return;
nodeView.lastChangeTime = (float)EditorApplication.timeSinceStartup;
}
/*
public Vector3 GetMouseWorldPos( Vector3 playerPos ) {
Vector3 camDir = Camera.main.transform.forward;
Ray r = Camera.main.ScreenPointToRay( Input.mousePosition );
Plane p = new Plane( camDir * -1, playerPos );
float dist = 0f;
if( p.Raycast( r, out dist ) ) {
return r.GetPoint( dist );
}
Debug.LogError( "Mouse ray did not hit the plane" );
return Vector3.zero;
}*/
public bool InitializeInstance( Shader initShader = null ) {
if(SF_Debug.evalFlow)
Debug.Log( "[SF_LOG] - SF_Editor InitializeInstance(" + initShader + ")" );
//this.title = ;
SF_Settings.InitializeSettings();
this.initialized = true;
this.ps = ScriptableObject.CreateInstance<SF_PassSettings>().Initialize( this );
this.shaderEvaluator = new SF_Evaluator( this );
this.preview = new SF_PreviewWindow( this );
this.statusBox = new SF_StatusBox( /*this*/ );
statusBox.Initialize(this);
InitializeNodeTemplates();
windowStyle = new GUIStyle( EditorStyles.textField );
windowStyle.margin = new RectOffset( 0, 0, 0, 0 );
windowStyle.padding = new RectOffset( 0, 0, 0, 0 );
titleStyle = new GUIStyle( EditorStyles.largeLabel );
titleStyle.fontSize = 24;
versionStyle = new GUIStyle( EditorStyles.miniBoldLabel );
versionStyle.alignment = TextAnchor.MiddleLeft;
versionStyle.fontSize = 9;
versionStyle.normal.textColor = Color.gray;
versionStyle.padding.left = 1;
versionStyle.padding.top = 1;
versionStyle.padding.bottom = 1;
versionStyle.margin.left = 1;
versionStyle.margin.top = 3;
versionStyle.margin.bottom = 1;
this.nodes = new List<SF_Node>();
// Create main output node and add to list
this.nodeView = ScriptableObject.CreateInstance<SF_EditorNodeView>().Initialize( this );
this.ps.catConsole.treeStatus = this.nodeView.treeStatus;
this.nodeBrowser = ScriptableObject.CreateInstance<SF_EditorNodeBrowser>().Initialize( this );
this.separatorLeft = ScriptableObject.CreateInstance<SF_DraggableSeparator>();
this.separatorRight = ScriptableObject.CreateInstance<SF_DraggableSeparator>();
separatorLeft.rect = new Rect(340, 0, 0, 0);
separatorRight.rect = new Rect(Screen.width - 130f, 0, 0, 0);
this.previousPosition = position;
if( initShader == null ) {
// TODO: New menu etc
//CreateOutputNode();
} else {
currentShaderAsset = initShader;
bool loaded = SF_Parser.ParseNodeDataFromShader( this, initShader );
if( !loaded ) {
initShader = null;
DestroyImmediate( this );
return false;
}
// Make preview material use this shader
//preview.material.shader = currentShaderAsset;
Material m = preview.InternalMaterial;
SF_Tools.AssignShaderToMaterialAsset( ref m, currentShaderAsset );
}
// Load data if it was set to initialize things
return true; // Successfully loaded
}
public SF_Node CreateOutputNode() {
//Debug.Log ("Creating output node");
this.mainNode = ScriptableObject.CreateInstance<SFN_Final>().Initialize( this );//new SFN_Final();
this.nodes.Add( mainNode );
return mainNode;
}
public SF_Node GetNodeByID( int id ) {
for( int i = 0; i < nodes.Count; i++ ) {
if( nodes[i].id == id )
return nodes[i];
}
return null;
}
public void UpdateKeyHoldEvents(bool mouseOverSomeNode) {
if( nodeTemplates == null || nodeTemplates.Count == 0 ) {
InitializeNodeTemplates();
}
//Debug.Log( "nodeTemplates.Count = " + nodeTemplates.Count );
foreach( SF_EditorNodeData nData in nodeTemplates ) {
if( nData == null ) {
InitializeNodeTemplates();
return;
}
SF_EditorNodeData requestedNode = nData.CheckHotkeyInput(mouseOverSomeNode);
if( requestedNode != null ) {
AddNode( requestedNode, true );
return;
}
}
/*foreach(KeyValuePair<SF_EditorNodeData, Func<SF_Node>> entry in inputInstancers){
if(entry.Key.CheckHotkeyInput()){
AddNode( entry.Key );
}
}*/
}
public T AddNode<T>() where T:SF_Node {
return AddNode(GetTemplate<T>()) as T;
}
public SF_Node AddNode(string typeName) {
//Debug.Log( "Searching for " + typeName );
return AddNode( GetTemplate( typeName ) );
}
public SF_Node AddNode( SF_EditorNodeData nodeData, bool registerUndo = false ) {
if( nodeData == null ){
Debug.Log("Null node data passed into AddNode");
}
SF_Node node = nodeData.CreateInstance();
if( SF_Debug.dynamicNodeLoad ) {
if( node == null )
Debug.Log( "nodeData failed to create a node of full path: " + nodeData.fullPath );
else
Debug.Log( "Created a node of full path: " + nodeData.fullPath );
}
if(registerUndo){
Undo.RecordObject(this, "add node " + node.nodeName);
}
nodes.Add( node );
if(Event.current != null)
Event.current.Use();
//Repaint();
return node;
}
bool Clicked() {
return Event.current.type == EventType.MouseDown;
}
float fps = 0;
double prevFrameTime = 1;
public double deltaTime = 0.02;
List<IEnumerator> coroutines = new List<IEnumerator>();
//double corLastTime;
// double corDeltaTime;
void UpdateCoroutines(){
//corDeltaTime = EditorApplication.timeSinceStartup - corLastTime;
//corLastTime = EditorApplication.timeSinceStartup;
for(int i = 0; i < coroutines.Count; i++){
IEnumerator routine = coroutines[i];
if(!routine.MoveNext()){
coroutines.RemoveAt(i--);
}
}
}
void StartCoroutine (IEnumerator routine){
coroutines.Add(routine);
}
void Update() {
if( closeMe ) {
base.Close();
return;
}
double now = Now();
double deltaTime = now-prevFrameTime;
fps = 1f/(float)deltaTime;
if(fps > 60)
return; // Wait for target FPS
prevFrameTime = now;
preview.UpdateRot();
for (int i = nodes.Count - 1; i >= 0; i--) {
if(nodes[i] == null)
nodes.Remove(nodes[i]);
else
nodes[i].Update();
}
// Refresh node previews
int maxUpdatesPerFrame = 80;
int updatedNodes = 0;
while( updatedNodes < maxUpdatesPerFrame ) {
bool anyUpdated = false;
for( int i = 0; i < nodes.Count; i++ ) {
if( nodes[i].CheckIfDirty() ) {
anyUpdated = true;
updatedNodes++;
}
}
if( !anyUpdated ) {
break;
}
}
if( ShaderOutdated == UpToDateState.OutdatedHard && SF_Settings.autoCompile && nodeView.GetTimeSinceChanged() >= 1f) {
shaderEvaluator.Evaluate();
}
//UpdateCameraZoomValue();
if(focusedWindow == this)
Repaint(); // Update GUI every frame if focused
}
MethodInfo isDockedMethod;
const float dockedCheckInterval = 1f;
public float dockedLastUpdate = -100f;
public bool _docked = false;
public bool Docked{
get{
if( EditorApplication.timeSinceStartup - dockedLastUpdate > dockedCheckInterval ) {
dockedLastUpdate = (float)EditorApplication.timeSinceStartup;
if( isDockedMethod == null ) {
BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
isDockedMethod = typeof( EditorWindow ).GetProperty( "docked", fullBinding ).GetGetMethod( true );
}
_docked = ( bool ) isDockedMethod.Invoke(this, null);
}
return _docked;
}
}
public int TabOffset{
get{
return Docked ? 19 : 22;
}
}
public double Now(){
TimeSpan t = ( DateTime.UtcNow - startTime );
return t.TotalSeconds;
}
void OnWindowResized( int deltaXsize, int deltaYsize ) {
if(separatorRight == null)
ForceClose();
separatorRight.rect.x += deltaXsize;
}
void ForceClose() {
//Debug.Log("Force close");
closeMe = true;
GUIUtility.ExitGUI();
}
void AddDependenciesHierarchally(SF_Node node, DependencyTree<SF_Node> tree){
node.ReadDependencies();
tree.Add(node);
foreach(SF_Node n in ((IDependable<SF_Node>)node).Dependencies){
AddDependenciesHierarchally(n, tree);
}
}
public List<SF_Node> GetDepthSortedDependencyTreeForConnectedNodes(bool reverse = false){
DependencyTree<SF_Node> tree = new DependencyTree<SF_Node>();
AddDependenciesHierarchally(mainNode, tree);
//Debug.Log(tree.tree.Count);
tree.Sort();
List<SF_Node> list = tree.tree.Select(x=>(SF_Node)x).ToList();
if(reverse)
list.Reverse();
return list;
}
string fullscreenMessage = "";
public Rect previousPosition;
public bool closeMe = false;
void OnGUI() {
//Debug.Log("SF_Editor OnGUI()");
//SF_AllDependencies.DrawDependencyTree(new Rect(0, 0, Screen.width, Screen.height));
//return;
// if(Event.current.keyCode == KeyCode.Space && Event.current.type == EventType.keyDown){
// Debug.Log("Beep");
// Event.current.Use();
//
//
//
// }
if(SF_Parser.quickLoad) // Don't draw while loading
return;
if(SF_Debug.performance)
GUI.Label(new Rect(500,64,128,64),"fps: "+fps.ToString());
if( position != previousPosition ) {
OnWindowResized( (int)(position.width - previousPosition.width), (int)(position.height - previousPosition.height) );
previousPosition = position;
}
Rect fullRect = new Rect( 0, 0, Screen.width, Screen.height);
//Debug.Log( fullRect );
if( currentShaderAsset == null ) {
DrawMainMenu();
return;
}
if(!string.IsNullOrEmpty(fullscreenMessage)){
GUI.Box(fullRect,fullscreenMessage);
return;
}
//UpdateCameraZoomInput();
if(Event.current.rawType == EventType.ValidateCommand && Event.current.commandName == "UndoRedoPerformed"){
Defocus(deselectNodes:false);
CheckForDirtyNodes(); // When undoing, some nodes will come back as dirty, which means they need to update their values
shaderEvaluator.ps.fChecker.UpdateAvailability();
ResetRunningOutdatedTimer();
}
if( nodes != null ) {
//foreach( SF_Node n in nodes ) {
for( int i = 0; i < nodes.Count;i++ ) {
SF_Node n = nodes[i];
if( n == null ) {
// THIS MEANS YOU STARTED UNITY WITH SF OPEN
ForceClose();
return;
} else{
n.DrawConnections();
}
}
}
if(separatorLeft == null){
// THIS MEANS YOU STARTED UNITY WITH SF OPEN
ForceClose();
return;
}
//EditorGUILayout.BeginHorizontal();
//{
//float wPreview = leftSeparator;
//float wNodeBrowser = 130;
Rect pRect = new Rect( fullRect );
pRect.height /= EditorGUIUtility.pixelsPerPoint;
pRect.width /= EditorGUIUtility.pixelsPerPoint;
pRect.width = separatorLeft.rect.x;
SF_GUI.FillBackground( pRect );
DrawPreviewPanel( pRect );
Rect previewPanelRect = pRect;
//pRect.x += leftWidth;
//pRect.width = wSeparator;
//VerticalSeparatorDraggable(ref leftWidth, pRect );
separatorLeft.MinX = 320;
separatorLeft.MaxX = (int)( fullRect.width / 2f - separatorLeft.rect.width );
separatorLeft.Draw( (int)pRect.y, (int)pRect.height );
pRect.x = separatorLeft.rect.x + separatorLeft.rect.width;
if(SF_Settings.showNodeSidebar)
pRect.width = separatorRight.rect.x - separatorLeft.rect.x - separatorLeft.rect.width;
else
pRect.width = Screen.width - separatorLeft.rect.x - separatorLeft.rect.width;
//GUI.Box( new Rect( 300, 0, 512, 32 ), pRect.ToString() );
if( SF_Debug.nodes ) {
Rect r = pRect; r.width = 256; r.height = 16;
for( int i = 0; i < nodes.Count; i++ ) {
GUI.Label( r, "Node[" + i + "] at {" + nodes[i].rect.x + ", " + nodes[i].rect.y + "}", EditorStyles.label ); // nodes[i]
r = r.MovedDown();
}
}
if( Event.current.rawType == EventType.KeyUp ){
foreach(SF_EditorNodeData nd in nodeTemplates){
nd.holding = false;
}
}
nodeView.OnLocalGUI( pRect.PadTop(TabOffset) ); // 22 when not docked, 19 if docked
//GUI.EndGroup();
//pRect.yMin -= 3; // if docked
//pRect.x += pRect.width;
//pRect.width = wSeparator;
//VerticalSeparatorDraggable(ref rightWidth, pRect );
if(SF_Settings.showNodeSidebar){
separatorRight.MinX = (int)(fullRect.width / EditorGUIUtility.pixelsPerPoint) - 150;
separatorRight.MaxX = (int)(fullRect.width / EditorGUIUtility.pixelsPerPoint) - 32;
separatorRight.Draw( (int)pRect.y, (int)pRect.height );
pRect.x += pRect.width + separatorRight.rect.width;
pRect.width = (fullRect.width / EditorGUIUtility.pixelsPerPoint) - separatorRight.rect.x - separatorRight.rect.width;
SF_GUI.FillBackground( pRect );
nodeBrowser.OnLocalGUI( pRect );
}
// Last thing, right?
ssButtonColor = Color.Lerp(ssButtonColor,ssButtonColorTarget, (float)deltaTime*ssButtonFadeSpeed);
if(previewPanelRect.Contains(Event.current.mousePosition)){
ssButtonColorTarget = Color.white;
ssButtonFadeSpeed = 0.4f;
} else {
ssButtonColorTarget = new Color(1f,1f,1f,0f); // TODO LERP
ssButtonFadeSpeed = 1.5f;
}
Rect ssRect = new Rect(8,previewButtonHeightOffset,32,19);
GUI.color = ssButtonColor;
if(GUI.Button(ssRect, SF_GUI.Screenshot_icon)){
GenericMenu menu = new GenericMenu();
menu.AddItem( new GUIContent("Take screenshot of node tree"), false, ContextClickScreenshot, "ss_standard" );
menu.AddItem( new GUIContent("Take screenshot of node tree without 3D preview"), false, ContextClickScreenshot, "ss_nopreview" );
menu.ShowAsContext();
}
GUI.color = Color.white;
//Rect ssRectIcon = new Rect(0f, 0f, SF_GUI.Screenshot_icon.width, SF_GUI.Screenshot_icon.height);
////ssRectIcon.center = ssRect.center;
//GUI.DrawTexture(ssRectIcon, SF_GUI.Screenshot_icon);
if(Event.current.type == EventType.Repaint)
UpdateCoroutines();
DrawTooltip();
}
public void CheckForDirtyNodes(){
for(int i=0;i<nodes.Count;i++){
nodes[i].CheckIfDirty();
}
}