summaryrefslogtreecommitdiff
path: root/Assets/ThirdParty/AmplifyShaderEditor/Plugins/Editor/Templates/TemplatesManager.cs
blob: 456cc4dfdccc50d8ddb4e5b8c46b50a991b83986 (plain)
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
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>

using System;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;

namespace AmplifyShaderEditor
{
	[Serializable]
	public class TemplateInputData
	{
		public string PortName;
		public WirePortDataType DataType;
		public MasterNodePortCategory PortCategory;
		public int PortUniqueId;
		public int OrderId;
		public int TagGlobalStartIdx;
		public int TagLocalStartIdx;
		public string TagId;
		public string DefaultValue;
		public string LinkId;

		public TemplateInputData( int tagLocalStartIdx, int tagGlobalStartIdx, string tagId, string portName, string defaultValue, WirePortDataType dataType, MasterNodePortCategory portCategory, int portUniqueId, int orderId, string linkId )
		{
			DefaultValue = defaultValue;
			PortName = portName;
			DataType = dataType;
			PortCategory = portCategory;
			PortUniqueId = portUniqueId;
			OrderId = orderId;
			TagId = tagId;
			TagGlobalStartIdx = tagGlobalStartIdx;
			TagLocalStartIdx = tagLocalStartIdx;
			LinkId = linkId;
		}

		public TemplateInputData( TemplateInputData other )
		{
			DefaultValue = other.DefaultValue;
			PortName = other.PortName;
			DataType = other.DataType;
			PortCategory = other.PortCategory;
			PortUniqueId = other.PortUniqueId;
			OrderId = other.OrderId;
			TagId = other.TagId;
			TagGlobalStartIdx = other.TagGlobalStartIdx;
			LinkId = other.LinkId;
		}
	}



	[Serializable]
	public class TemplatePropertyContainer
	{
		[SerializeField]
		private List<TemplateProperty> m_propertyList = new List<TemplateProperty>();
		private Dictionary<string, TemplateProperty> m_propertyDict = new Dictionary<string, TemplateProperty>();


		public void AddId( TemplateProperty templateProperty )
		{
			BuildInfo();
			m_propertyList.Add( templateProperty );
			m_propertyDict.Add( templateProperty.Id, templateProperty );
		}

		public void AddId( string body, string ID, bool searchIndentation = true )
		{
			AddId( body, ID, searchIndentation, string.Empty );
		}

		public void AddId( string body, string ID, bool searchIndentation, string customIndentation )
		{
			BuildInfo();

			int propertyIndex = body.IndexOf( ID );
			if( propertyIndex > -1 )
			{
				if( searchIndentation )
				{
					int identationIndex = -1;
					for( int i = propertyIndex; i >= 0; i-- )
					{
						if( body[ i ] == TemplatesManager.TemplateNewLine )
						{
							identationIndex = i + 1;
							break;
						}

						if( i == 0 )
						{
							identationIndex = 0;
						}
					}
					if( identationIndex > -1 )
					{
						int length = propertyIndex - identationIndex;
						string indentation = ( length > 0 ) ? body.Substring( identationIndex, length ) : string.Empty;
						TemplateProperty templateProperty = new TemplateProperty( ID, indentation, false );
						m_propertyList.Add( templateProperty );
						m_propertyDict.Add( templateProperty.Id, templateProperty );
					}
					else
					{
						TemplateProperty templateProperty = new TemplateProperty( ID, string.Empty, false );
						m_propertyList.Add( templateProperty );
						m_propertyDict.Add( templateProperty.Id, templateProperty );
					}
				}
				else
				{
					TemplateProperty templateProperty = new TemplateProperty( ID, customIndentation, true );
					m_propertyList.Add( templateProperty );
					m_propertyDict.Add( templateProperty.Id, templateProperty );
				}
			}
		}


		public void AddId( string body, string ID, int propertyIndex, bool searchIndentation )
		{
			AddId( body, ID, propertyIndex, searchIndentation, string.Empty );
		}

		public void AddId( string body, string ID, int propertyIndex, bool searchIndentation, string customIndentation )
		{
			if( body == null || string.IsNullOrEmpty( body ) )
				return;

			BuildInfo();
			if( searchIndentation && propertyIndex > -1 && propertyIndex < body.Length )
			{
				int indentationIndex = -1;
				for( int i = propertyIndex; i > 0; i-- )
				{
					if( body[ i ] == TemplatesManager.TemplateNewLine )
					{
						indentationIndex = i + 1;
						break;
					}
				}

				if( indentationIndex > -1 )
				{
					int length = propertyIndex - indentationIndex;
					string indentation = ( length > 0 ) ? body.Substring( indentationIndex, length ) : string.Empty;
					TemplateProperty templateProperty = new TemplateProperty( ID, indentation, false );
					m_propertyList.Add( templateProperty );
					m_propertyDict.Add( templateProperty.Id, templateProperty );
				}
			}
			else
			{
				TemplateProperty templateProperty = new TemplateProperty( ID, customIndentation, true );
				m_propertyList.Add( templateProperty );
				m_propertyDict.Add( templateProperty.Id, templateProperty );
			}

		}
		public void BuildInfo()
		{
			if( m_propertyDict == null )
			{
				m_propertyDict = new Dictionary<string, TemplateProperty>();
			}

			if( m_propertyList.Count != m_propertyDict.Count )
			{
				m_propertyDict.Clear();
				for( int i = 0; i < m_propertyList.Count; i++ )
				{
					m_propertyDict.Add( m_propertyList[ i ].Id, m_propertyList[ i ] );
				}
			}
		}

		public void ResetTemplateUsageData()
		{
			BuildInfo();
			for( int i = 0; i < m_propertyList.Count; i++ )
			{
				m_propertyList[ i ].Used = false;
			}
		}

		public void Reset()
		{
			m_propertyList.Clear();
			m_propertyDict.Clear();
		}

		public void Destroy()
		{
			m_propertyList.Clear();
			m_propertyList = null;
			m_propertyDict.Clear();
			m_propertyDict = null;
		}


		public Dictionary<string, TemplateProperty> PropertyDict
		{
			get
			{
				BuildInfo();
				return m_propertyDict;
			}
		}
		public List<TemplateProperty> PropertyList { get { return m_propertyList; } }
	}

	[Serializable]
	public class TemplateProperty
	{
		public bool UseIndentationAtStart = false;
		public string Indentation;
		public bool UseCustomIndentation;
		public string Id;
		public bool AutoLineFeed;
		public bool Used;

		public TemplateProperty( string id, string indentation, bool useCustomIndentation )
		{
			Id = id;
			Indentation = indentation;
			UseCustomIndentation = useCustomIndentation;
			AutoLineFeed = !string.IsNullOrEmpty( indentation );
			Used = false;
		}
	}

	[Serializable]
	public class TemplateTessVControlTag
	{
		public string Id;
		public int StartIdx;

		public TemplateTessVControlTag()
		{
			StartIdx = -1;
		}

		public bool IsValid { get { return StartIdx >= 0; } }
	}

	[Serializable]
	public class TemplateTessControlData
	{
		public string Id;
		public int StartIdx;
		public string InVarType;
		public string InVarName;
		public string OutVarType;
		public string OutVarName;

		public bool IsValid { get { return StartIdx >= 0; } }

		public TemplateTessControlData()
		{
			StartIdx = -1;
		}

		public TemplateTessControlData( int startIdx, string id, string inVarInfo, string outVarInfo )
		{
			StartIdx = startIdx;
			Id = id;
			string[] inVarInfoArr = inVarInfo.Split( IOUtils.VALUE_SEPARATOR );
			if( inVarInfoArr.Length > 1 )
			{
				InVarType = inVarInfoArr[ 1 ];
				InVarName = inVarInfoArr[ 0 ];
			}

			string[] outVarInfoArr = outVarInfo.Split( IOUtils.VALUE_SEPARATOR );
			if( outVarInfoArr.Length > 1 )
			{
				OutVarType = outVarInfoArr[ 1 ];
				OutVarName = outVarInfoArr[ 0 ];
			}
		}

		public string[] GenerateControl( Dictionary<TemplateSemantics, TemplateVertexData> vertexData, List<string> inputList )
		{
			List<string> value = new List<string>();
			if( vertexData != null && vertexData.Count > 0 )
			{
				foreach( var item in vertexData )
				{
					if( inputList.FindIndex( x => { return x.Contains( item.Value.VarName ); } ) > -1 )
						value.Add( string.Format( "{0}.{1} = {2}.{1};", OutVarName, item.Value.VarName, InVarName ) );
				}
			}
			return value.ToArray();
		}
	}

	[Serializable]
	public class TemplateTessDomainData
	{
		public string Id;
		public int StartIdx;
		public string InVarType;
		public string InVarName;
		public string OutVarType;
		public string OutVarName;
		public string BaryVarType;
		public string BaryVarName;

		public bool IsValid { get { return StartIdx >= 0; } }

		public TemplateTessDomainData()
		{
			StartIdx = -1;
		}

		public TemplateTessDomainData( int startIdx, string id, string inVarInfo, string outVarInfo, string baryVarInfo )
		{
			StartIdx = startIdx;
			Id = id;
			string[] inVarInfoArr = inVarInfo.Split( IOUtils.VALUE_SEPARATOR );
			if( inVarInfoArr.Length > 1 )
			{
				InVarType = inVarInfoArr[ 1 ];
				InVarName = inVarInfoArr[ 0 ];
			}

			string[] outVarInfoArr = outVarInfo.Split( IOUtils.VALUE_SEPARATOR );
			if( outVarInfoArr.Length > 1 )
			{
				OutVarType = outVarInfoArr[ 1 ];
				OutVarName = outVarInfoArr[ 0 ];
			}

			string[] baryVarInfoArr = baryVarInfo.Split( IOUtils.VALUE_SEPARATOR );
			if( baryVarInfoArr.Length > 1 )
			{
				BaryVarType = baryVarInfoArr[ 1 ];
				BaryVarName = baryVarInfoArr[ 0 ];
			}
		}

		public string[] GenerateDomain( Dictionary<TemplateSemantics, TemplateVertexData> vertexData, List<string> inputList )
		{
			List<string> value = new List<string>();
			if( vertexData != null && vertexData.Count > 0 )
			{
				foreach( var item in vertexData )
				{
					//o.ase_normal = patch[0].ase_normal * bary.x + patch[1].ase_normal * bary.y + patch[2].ase_normal * bary.z;
					if( inputList.FindIndex( x => { return x.Contains( item.Value.VarName ); } ) > -1 )
						value.Add( string.Format( "{0}.{1} = {2}[0].{1} * {3}.x + {2}[1].{1} * {3}.y + {2}[2].{1} * {3}.z;", OutVarName, item.Value.VarName, InVarName, BaryVarName ) );
				}
			}
			return value.ToArray();
		}
	}

	[Serializable]
	public class TemplateFunctionData
	{
		public int MainBodyLocalIdx;
		public string MainBodyName;

		public string Id;
		public int Position;
		public string InVarType;
		public string InVarName;
		public string OutVarType;
		public string OutVarName;
		public MasterNodePortCategory Category;
		public TemplateFunctionData( int mainBodyLocalIdx, string mainBodyName, string id, int position, string inVarInfo, string outVarInfo, MasterNodePortCategory category )
		{
			MainBodyLocalIdx = mainBodyLocalIdx;
			MainBodyName = mainBodyName;
			Id = id;
			Position = position;
			{
				string[] inVarInfoArr = inVarInfo.Split( IOUtils.VALUE_SEPARATOR );
				if( inVarInfoArr.Length > 1 )
				{
					InVarType = inVarInfoArr[ 1 ];
					InVarName = inVarInfoArr[ 0 ];
				}
			}
			{
				string[] outVarInfoArr = outVarInfo.Split( IOUtils.VALUE_SEPARATOR );
				if( outVarInfoArr.Length > 1 )
				{
					OutVarType = outVarInfoArr[ 1 ];
					OutVarName = outVarInfoArr[ 0 ];
				}
			}
			Category = category;
		}
	}

	[Serializable]
	public class TemplateTagData
	{
		public int StartIdx = -1;
		public string Id;
		public bool SearchIndentation;
		public string CustomIndentation;


		public TemplateTagData( int startIdx, string id, bool searchIndentation )
		{
			StartIdx = startIdx;
			Id = id;
			SearchIndentation = searchIndentation;
			CustomIndentation = string.Empty;
		}

		public TemplateTagData( string id, bool searchIndentation )
		{
			Id = id;
			SearchIndentation = searchIndentation;
			CustomIndentation = string.Empty;
		}

		public TemplateTagData( string id, bool searchIndentation, string customIndentation )
		{
			Id = id;
			SearchIndentation = searchIndentation;
			CustomIndentation = customIndentation;
		}

		public bool IsValid { get { return StartIdx >= 0; } }
	}

	public enum TemplatePortIds
	{
		Name = 0,
		DataType,
		UniqueId,
		OrderId,
		Link
	}

	public enum TemplateCommonTagId
	{
		Property = 0,
		Global = 1,
		Function = 2,
		Tag = 3,
		Pragmas = 4,
		Pass = 5,
		Params_Vert = 6,
		Params_Frag = 7
		//CullMode	= 8,
		//BlendMode   = 9,
		//BlendOp		= 10,
		//ColorMask	= 11,
		//StencilOp	= 12
	}

	[Serializable]
	public class TemplatesManager : ScriptableObject
	{
		public static int MPShaderVersion = 14503;
		
		public static readonly string TemplateShaderNameBeginTag = "/*ase_name*/";
		public static readonly string TemplateStencilTag = "/*ase_stencil*/\n";
		public static readonly string TemplateAllModulesTag = "/*ase_all_modules*/\n";
		public static readonly string TemplateMPSubShaderTag = "\\bSubShader\\b\\s*{";
		//public static readonly string TemplateMPPassTag = "^\\s*Pass\b\\s*{";//"\\bPass\\b\\s*{";
		public static readonly string TemplateMPPassTag = "\\bPass\\b\\s*{";
		public static readonly string TemplateLocalVarTag = "/*ase_local_var*/";
		public static readonly string TemplateDependenciesListTag = "/*ase_dependencies_list*/";
		public static readonly string TemplatePragmaBeforeTag = "/*ase_pragma_before*/";
		public static readonly string TemplatePragmaTag = "/*ase_pragma*/";
		public static readonly string TemplatePassTag = "/*ase_pass*/";
		public static readonly string TemplatePassesEndTag = "/*ase_pass_end*/";
		public static readonly string TemplateLODsTag = "/*ase_lod*/";
		//public static readonly string TemplatePassTagPattern = @"\s\/\*ase_pass\*\/";
		public static readonly string TemplatePassTagPattern = @"\s\/\*ase_pass[:\*]+";
		public static readonly string TemplatePropertyTag = "/*ase_props*/";
		public static readonly string TemplateGlobalsTag = "/*ase_globals*/";
		public static readonly string TemplateSRPBatcherTag = "/*ase_srp_batcher*/\n";
		public static readonly string TemplateInterpolatorBeginTag = "/*ase_interp(";
		public static readonly string TemplateVertexDataTag = "/*ase_vdata:";

		public static readonly string TemplateTessVControlTag = "/*ase_vcontrol*/";
		public static readonly string TemplateTessControlCodeArea = "/*ase_control_code:";
		public static readonly string TemplateTessDomainCodeArea = "/*ase_domain_code:";

		//public static readonly string TemplateExcludeFromGraphTag = "/*ase_hide_pass*/";
		public static readonly string TemplateMainPassTag = "/*ase_main_pass*/";

		public static readonly string TemplateFunctionsTag = "/*ase_funcs*/\n";
		//public static readonly string TemplateTagsTag = "/*ase_tags*/";

		//public static readonly string TemplateCullModeTag = "/*ase_cull_mode*/";
		//public static readonly string TemplateBlendModeTag = "/*ase_blend_mode*/";
		//public static readonly string TemplateBlendOpTag = "/*ase_blend_op*/";
		//public static readonly string TemplateColorMaskTag = "/*ase_color_mask*/";
		//public static readonly string TemplateStencilOpTag = "/*ase_stencil*/";

		public static readonly string TemplateCodeSnippetAttribBegin = "#CODE_SNIPPET_ATTRIBS_BEGIN#";
		public static readonly string TemplateCodeSnippetAttribEnd = "#CODE_SNIPPET_ATTRIBS_END#\n";
		public static readonly string TemplateCodeSnippetEnd = "#CODE_SNIPPET_END#\n";

		public static readonly char TemplateNewLine = '\n';

		// INPUTS AREA
		public static readonly string TemplateInputsVertBeginTag = "/*ase_vert_out:";
		public static readonly string TemplateInputsFragBeginTag = "/*ase_frag_out:";
		public static readonly string TemplateInputsVertParamsTag = "/*ase_vert_input*/";
		public static readonly string TemplateInputsFragParamsTag = "/*ase_frag_input*/";


		// CODE AREA
		public static readonly string TemplateVertexCodeBeginArea = "/*ase_vert_code:";
		public static readonly string TemplateFragmentCodeBeginArea = "/*ase_frag_code:";


		public static readonly string TemplateEndOfLine = "*/\n";
		public static readonly string TemplateEndSectionTag = "*/";
		public static readonly string TemplateFullEndTag = "/*end*/";

		public static readonly string NameFormatter = "\"{0}\"";

		public static readonly TemplateTagData[] CommonTags = { new TemplateTagData( TemplatePropertyTag,true),
																new TemplateTagData( TemplateGlobalsTag,true),
																new TemplateTagData( TemplateSRPBatcherTag,true),
																new TemplateTagData( TemplateFunctionsTag,true),
																//new TemplateTagData( TemplateTagsTag,false," "),
																new TemplateTagData( TemplatePragmaBeforeTag,true),
																new TemplateTagData( TemplatePragmaTag,true),
																new TemplateTagData( TemplatePassTag,true),
																new TemplateTagData( TemplateInputsVertParamsTag,false),
																new TemplateTagData( TemplateInputsFragParamsTag,false),
																new TemplateTagData( TemplateLODsTag,true)
																//new TemplateTagData( TemplateCullModeTag,false),
																//new TemplateTagData( TemplateBlendModeTag,false),
																//new TemplateTagData( TemplateBlendOpTag,false),
																//new TemplateTagData( TemplateColorMaskTag,false),
																//new TemplateTagData( TemplateStencilOpTag,true),
																};
		public static string LightweigthPBRGUID = "1976390536c6c564abb90fe41f6ee334";
		public static string LightweigthUnlitGUID = "e2514bdcf5e5399499a9eb24d175b9db";
		public static string UniversalPBRGUID = "94348b07e5e8bab40bd6c8a1e3df54cd";
		public static string UniversalUnlitGUID = "2992e84f91cbeb14eab234972e07ea9d";

		public static string HDNewLitGUID = "53b46d85872c5b24c8f4f0a1c3fe4c87";
		public static string HDNewPBRGUID = "41e04be03f2c20941bc749271be1c937";
		public static string HDNewUnlitGUID = "7f5cb9c3ea6481f469fdd856555439ef";
		public static string HDLitGUID = "091c43ba8bd92c9459798d59b089ce4e";
		public static string HDPBRGUID = "bb308bce79762c34e823049efce65141";
		public static string HDUnlitGUID = "dfe2f27ac20b08c469b2f95c236be0c3";

		public static Dictionary<string, string> OfficialTemplates = new Dictionary<string, string>()
		{
			{ "0770190933193b94aaa3065e307002fa","Legacy/Unlit"},
			{ "32139be9c1eb75640a847f011acf3bcf","Legacy/Post-Processing Stack"},
			{ "6ce779933eb99f049b78d6163735e06f","Legacy/Custom RT Init"},
			{ "32120270d1b3a8746af2aca8bc749736","Legacy/Custom RT Update"},
			{ LightweigthPBRGUID,"LW/PBR"},
			{ LightweigthUnlitGUID,"LW/Unlit"},
			{ UniversalPBRGUID,"Universal/PBR"},
			{ UniversalUnlitGUID,"Universal/Unlit"},
			{ "53b46d85872c5b24c8f4f0a1c3fe4c87","HD/Lit"},
			{ HDLitGUID,"Deprecated/HD/Lit"},
			{ HDPBRGUID,"Deprecated/HD/PBR"},
			{ HDUnlitGUID,"Deprecated/HD/Unlit"},
			{ "c71b220b631b6344493ea3cf87110c93","Legacy/Post Process" },
			{ "6e114a916ca3e4b4bb51972669d463bf","Deprecated/Legacy/Default Unlit" },
			{ "5056123faa0c79b47ab6ad7e8bf059a4","Legacy/Default UI" },
			{ "899e609c083c74c4ca567477c39edef0","Legacy/Unlit Lightmap" },
			{ "0f8ba0101102bb14ebf021ddadce9b49","Legacy/Default Sprites" },
			{ "0b6a9f8b4f707c74ca64c0be8e590de0","Legacy/Particles Alpha Blended" },
			{ "e1de45c0d41f68c41b2cc20c8b9c05ef","Legacy/Multi Pass Unlit" }
		};

		public static readonly string TemplateMenuItemsFileGUID = "da0b931bd234a1e43b65f684d4b59bfb";

		private Dictionary<string, TemplateDataParent> m_availableTemplates = new Dictionary<string, TemplateDataParent>();

		[SerializeField]
		private List<TemplateDataParent> m_sortedTemplates = new List<TemplateDataParent>();

		[SerializeField]
		public string[] AvailableTemplateNames;

		[SerializeField]
		public bool Initialized = false;

		private Dictionary<string, bool> m_optionsInitialSetup = new Dictionary<string, bool>();

		public static string CurrTemplateGUIDLoaded = string.Empty;

		public static bool IsTestTemplate { get { return CurrTemplateGUIDLoaded.Equals( "a95a019bbc760714bb8228af04c291d1" ); } }
		public static bool ShowDebugMessages = false;
		public void RefreshAvailableTemplates()
		{
			if( m_availableTemplates.Count != m_sortedTemplates.Count )
			{
				m_availableTemplates.Clear();
				int count = m_sortedTemplates.Count;
				for( int i = 0; i < count; i++ )
				{
					m_availableTemplates.Add( m_sortedTemplates[ i ].GUID, m_sortedTemplates[ i ] );
				}
			}
		}

		public void Init()
		{
			if( !Initialized )
			{
				if( ShowDebugMessages )
					Debug.Log( "Initialize" );

				string templateMenuItems = IOUtils.LoadTextFileFromDisk( AssetDatabase.GUIDToAssetPath( TemplateMenuItemsFileGUID ) );
				bool refreshTemplateMenuItems = false;

				foreach( KeyValuePair<string, string> kvp in OfficialTemplates )
				{
					if( !string.IsNullOrEmpty( AssetDatabase.GUIDToAssetPath( kvp.Key ) ) )
					{
						TemplateMultiPass template = ScriptableObject.CreateInstance<TemplateMultiPass>();
						template.Init( kvp.Value, kvp.Key, false );
						AddTemplate( template );
						if( !refreshTemplateMenuItems && templateMenuItems.IndexOf( kvp.Value ) < 0 )
							refreshTemplateMenuItems = true;
					}
				}

				// Search for other possible templates on the project
				string[] allShaders = AssetDatabase.FindAssets( "t:shader" );
				for( int i = 0; i < allShaders.Length; i++ )
				{
					if( !m_availableTemplates.ContainsKey( allShaders[ i ] ) )
					{
						CheckAndLoadTemplate( allShaders[ i ] );
					}
				}

				// TODO: Sort list alphabeticaly 
				AvailableTemplateNames = new string[ m_sortedTemplates.Count + 1 ];
				AvailableTemplateNames[ 0 ] = "Custom";
				for( int i = 0; i < m_sortedTemplates.Count; i++ )
				{
					m_sortedTemplates[ i ].OrderId = i;
					AvailableTemplateNames[ i + 1 ] = m_sortedTemplates[ i ].Name;
				}

				if( refreshTemplateMenuItems )
					CreateTemplateMenuItems();

				Initialized = true;
			}
		}

		//[MenuItem( "Window/Amplify Shader Editor/Create Menu Items", false, 1000 )]
		//public static void ForceCreateTemplateMenuItems()
		//{
		//	UIUtils.CurrentWindow.TemplatesManagerInstance.CreateTemplateMenuItems();
		//}

		public void CreateTemplateMenuItems()
		{
			if( m_sortedTemplates == null || m_sortedTemplates.Count == 0 )
				return;

			// change names for duplicates
			for( int i = 0; i < m_sortedTemplates.Count; i++ )
			{
				for( int j = 0; j < i; j++ )
				{
					if( m_sortedTemplates[ i ].Name == m_sortedTemplates[ j ].Name )
					{
						var match = Regex.Match( m_sortedTemplates[ i ].Name, @".+(\d+)" );
						if( match.Success )
						{
							string strNumber = match.Groups[ 1 ].Value;
							int number = int.Parse( strNumber ) + 1;
							string firstPart = m_sortedTemplates[ i ].Name.Substring( 0, match.Groups[ 1 ].Index );
							string secondPart = m_sortedTemplates[ i ].Name.Substring( match.Groups[ 1 ].Index + strNumber.Length );
							m_sortedTemplates[ i ].Name = firstPart + number + secondPart;
						}
						else
						{
							m_sortedTemplates[ i ].Name += " 1";
						}
					}
				}
			}

			System.Text.StringBuilder fileContents = new System.Text.StringBuilder();
			fileContents.Append( "// Amplify Shader Editor - Visual Shader Editing Tool\n" );
			fileContents.Append( "// Copyright (c) Amplify Creations, Lda <info@amplify.pt>\n" );
			fileContents.Append( "using UnityEditor;\n" );
			fileContents.Append( "\n" );
			fileContents.Append( "namespace AmplifyShaderEditor\n" );
			fileContents.Append( "{\n" );
			fileContents.Append( "\tpublic class TemplateMenuItems\n" );
			fileContents.Append( "\t{\n" );
			int fixedPriority = 85;
			for( int i = 0; i < m_sortedTemplates.Count; i++ )
			{
				fileContents.AppendFormat( "\t\t[MenuItem( \"Assets/Create/Amplify Shader/{0}\", false, {1} )]\n", m_sortedTemplates[ i ].Name, fixedPriority );
				string itemName = UIUtils.RemoveInvalidCharacters( m_sortedTemplates[ i ].Name );
				fileContents.AppendFormat( "\t\tpublic static void ApplyTemplate{0}()\n", itemName/*i*/ );
				fileContents.Append( "\t\t{\n" );
				//fileContents.AppendFormat( "\t\t\tAmplifyShaderEditorWindow.CreateNewTemplateShader( \"{0}\" );\n", m_sortedTemplates[ i ].GUID );
				fileContents.AppendFormat( "\t\t\tAmplifyShaderEditorWindow.CreateConfirmationTemplateShader( \"{0}\" );\n", m_sortedTemplates[ i ].GUID );
				fileContents.Append( "\t\t}\n" );
			}
			fileContents.Append( "\t}\n" );
			fileContents.Append( "}\n" );
			string filePath = AssetDatabase.GUIDToAssetPath( TemplateMenuItemsFileGUID );
			IOUtils.SaveTextfileToDisk( fileContents.ToString(), filePath, false );
			AssetDatabase.ImportAsset( filePath );
		}

		public int GetIdForTemplate( TemplateData templateData )
		{
			if( templateData == null )
				return -1;

			for( int i = 0; i < m_sortedTemplates.Count; i++ )
			{
				if( m_sortedTemplates[ i ].GUID.Equals( templateData.GUID ) )
					return m_sortedTemplates[ i ].OrderId;
			}
			return -1;
		}



		public void AddTemplate( TemplateDataParent templateData )
		{
			if( templateData == null || !templateData.IsValid )
				return;
			RefreshAvailableTemplates();
			if( !m_availableTemplates.ContainsKey( templateData.GUID ) )
			{
				m_sortedTemplates.Add( templateData );
				m_availableTemplates.Add( templateData.GUID, templateData );
			}
		}

		public void RemoveTemplate( string guid )
		{
			TemplateDataParent templateData = GetTemplate( guid );
			if( templateData != null )
			{
				RemoveTemplate( templateData );
			}
		}

		public void RemoveTemplate( TemplateDataParent templateData )
		{
			RefreshAvailableTemplates();

			if( m_availableTemplates != null )
				m_availableTemplates.Remove( templateData.GUID );

			m_sortedTemplates.Remove( templateData );
			templateData.Destroy();
		}

		public void Destroy()
		{
			if( TemplatesManager.ShowDebugMessages )
				Debug.Log( "Destroy Manager" );
			if( m_availableTemplates != null )
			{
				foreach( KeyValuePair<string, TemplateDataParent> kvp in m_availableTemplates )
				{
					kvp.Value.Destroy();
				}
				m_availableTemplates.Clear();
				m_availableTemplates = null;
			}
			int count = m_sortedTemplates.Count;

			for( int i = 0; i < count; i++ )
			{
				ScriptableObject.DestroyImmediate( m_sortedTemplates[ i ] );
			}

			m_sortedTemplates.Clear();
			m_sortedTemplates = null;

			AvailableTemplateNames = null;
			Initialized = false;
		}

		public TemplateDataParent GetTemplate( int id )
		{
			if( id < m_sortedTemplates.Count )
				return m_sortedTemplates[ id ];

			return null;
		}

		public TemplateDataParent GetTemplate( string guid )
		{
			RefreshAvailableTemplates();
			if( m_availableTemplates == null && m_sortedTemplates != null )
			{
				m_availableTemplates = new Dictionary<string, TemplateDataParent>();
				for( int i = 0; i < m_sortedTemplates.Count; i++ )
				{
					m_availableTemplates.Add( m_sortedTemplates[ i ].GUID, m_sortedTemplates[ i ] );
				}
			}

			if( m_availableTemplates.ContainsKey( guid ) )
				return m_availableTemplates[ guid ];

			return null;
		}


		public TemplateDataParent GetTemplateByName( string name )
		{
			RefreshAvailableTemplates();
			if( m_availableTemplates == null && m_sortedTemplates != null )
			{
				m_availableTemplates = new Dictionary<string, TemplateDataParent>();
				for( int i = 0; i < m_sortedTemplates.Count; i++ )
				{
					m_availableTemplates.Add( m_sortedTemplates[ i ].GUID, m_sortedTemplates[ i ] );
				}
			}

			foreach( KeyValuePair<string, TemplateDataParent> kvp in m_availableTemplates )
			{
				if( kvp.Value.DefaultShaderName.Equals( name ) )
				{
					return kvp.Value;
				}
			}
			return null;
		}

		public TemplateDataParent CheckAndLoadTemplate( string guid )
		{
			TemplateDataParent templateData = GetTemplate( guid );
			if( templateData == null )
			{
				string datapath = AssetDatabase.GUIDToAssetPath( guid );
				string body = IOUtils.LoadTextFileFromDisk( datapath );

				if( body.IndexOf( TemplatesManager.TemplateShaderNameBeginTag ) > -1 )
				{
					templateData = ScriptableObject.CreateInstance<TemplateMultiPass>();
					templateData.Init( string.Empty, guid, true );
					if( templateData.IsValid )
					{
						AddTemplate( templateData );
						return templateData;
					}
				}
			}

			return null;
		}

		private void OnEnable()
		{
			if( !Initialized )
			{
				Init();
			}
			else
			{
				RefreshAvailableTemplates();
			}
			hideFlags = HideFlags.HideAndDontSave;
			if( ShowDebugMessages )
				Debug.Log( "On Enable Manager: " + this.GetInstanceID() );
		}

		public void ResetOptionsSetupData()
		{
			if( ShowDebugMessages )
			Debug.Log( "Reseting options setup data" );
			m_optionsInitialSetup.Clear();
		}

		public bool SetOptionsValue( string optionId, bool value )
		{
			if( m_optionsInitialSetup.ContainsKey( optionId ) )
			{
				m_optionsInitialSetup[ optionId ] = m_optionsInitialSetup[ optionId ] || value;
			}
			else
			{
				m_optionsInitialSetup.Add( optionId, value );
			}
			return m_optionsInitialSetup[ optionId ];
		}

		public int TemplateCount { get { return m_sortedTemplates.Count; } }
	}
}