diff --git a/Assets/CameraReplacementShader_BiRP/TestReplacementShader.cs b/Assets/CameraReplacementShader_BiRP/TestReplacementShader.cs new file mode 100644 index 0000000..7269d78 --- /dev/null +++ b/Assets/CameraReplacementShader_BiRP/TestReplacementShader.cs @@ -0,0 +1,57 @@ +using UnityEngine; + +// BuiltinRP only +// https://docs.unity3d.com/Manual/SL-ShaderReplacement.html +public class TestReplacementShader : MonoBehaviour +{ + public Camera cam; + public Shader replaceShader; + + public enum RenderTypes + { + All, + RenderType, + } + + public RenderTypes renderType = RenderTypes.RenderType; + + void OnEnable() + { + Setup(); + } + + void OnValidate() + { + Setup(); + } + + void OnDisable() + { + Cleanup(); + } + + void OnDestroy() + { + Cleanup(); + } + + private void Setup() + { + string renderTypeStr = ""; + if (renderType != RenderTypes.All) + { + renderTypeStr = renderType.ToString(); + } + cam.SetReplacementShader (replaceShader, renderTypeStr); + + Debug.Log("Configured Replacement Shader."); + } + + private void Cleanup() + { + cam.ResetReplacementShader(); + + Debug.Log("Reset Replacement Shader."); + } +} + diff --git a/Assets/CameraReplacementShader_BiRP/TestReplacementShader.shader b/Assets/CameraReplacementShader_BiRP/TestReplacementShader.shader new file mode 100644 index 0000000..b4e308c --- /dev/null +++ b/Assets/CameraReplacementShader_BiRP/TestReplacementShader.shader @@ -0,0 +1,120 @@ +Shader "Test Replacement Shader" +{ + Properties + { + _Color ("Main Color", Color) = (1,1,1,1) + _MainTex ("_MainTex (RGBA)", 2D) = "white" {} + } + + CGINCLUDE + + #include "UnityCG.cginc" + + struct appdata + { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + }; + + struct v2f + { + float2 uv : TEXCOORD0; + float4 vertex : SV_POSITION; + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + float4 _Color; + + v2f vert (appdata v) + { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.uv, _MainTex); + return o; + } + + ENDCG + + SubShader // Opaque = Red + { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque" } + Cull Off Lighting Off ZWrite Off + Blend SrcAlpha OneMinusSrcAlpha + + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + + fixed4 frag (v2f i) : SV_Target + { + return float4(1,0,0,0.1); + } + + ENDCG + } + } + SubShader // Transparent = Green + { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + Cull Off Lighting Off ZWrite Off + Blend SrcAlpha OneMinusSrcAlpha + + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + + fixed4 frag (v2f i) : SV_Target + { + return float4(0,1,0,0.1); + } + + ENDCG + } + } + SubShader // Background = Cyan + { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Background" } + Cull Off Lighting Off ZWrite Off + Blend SrcAlpha OneMinusSrcAlpha + + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + + fixed4 frag (v2f i) : SV_Target + { + return float4(0,1,1,0.1); + } + + ENDCG + } + } + SubShader // Overlay = Yellow + { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Overlay" } + Cull Off Lighting Off ZWrite Off + Blend SrcAlpha OneMinusSrcAlpha + + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + + fixed4 frag (v2f i) : SV_Target + { + return float4(1,1,0,0.1); + } + + ENDCG + } + } +} diff --git a/Assets/Editor/AvailableProfilerMarkersAndSamplers.cs b/Assets/Editor/AvailableProfilerMarkersAndSamplers.cs new file mode 100644 index 0000000..995e107 --- /dev/null +++ b/Assets/Editor/AvailableProfilerMarkersAndSamplers.cs @@ -0,0 +1,85 @@ +//script originally comes from https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Unity.Profiling.LowLevel.Unsafe.ProfilerRecorderHandle.GetAvailable.html + +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using Unity.Profiling; +using Unity.Profiling.LowLevel.Unsafe; +using UnityEditor; + +public class AvailableProfilerMarkersAndSamplers +{ + struct StatInfo + { + public ProfilerCategory Cat; + public string Name; + public ProfilerMarkerDataUnit Unit; + } + + [MenuItem("Test/GetAvailableProfilerMarkers")] + static unsafe void EnumerateProfilerStats() + { + var availableStatHandles = new List(); + ProfilerRecorderHandle.GetAvailable(availableStatHandles); + + var availableStats = new List(availableStatHandles.Count); + foreach (var h in availableStatHandles) + { + var statDesc = ProfilerRecorderHandle.GetDescription(h); + var statInfo = new StatInfo() + { + Cat = statDesc.Category, + Name = statDesc.Name, + Unit = statDesc.UnitType + }; + availableStats.Add(statInfo); + } + availableStats.Sort((a, b) => + { + var result = string.Compare(a.Cat.ToString(), b.Cat.ToString()); + if (result != 0) + return result; + + return string.Compare(a.Name, b.Name); + }); + + var sb = new StringBuilder("Available stats:"+" "+availableStats.Count+"\n"); + foreach (var s in availableStats) + { + sb.AppendLine($"{(int)s.Cat}\t\t - {s.Name}\t\t - {s.Unit}"); + } + + string filePath = Application.dataPath+"/AvailableProfilerMarkers.txt"; + using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath)) + { + file.WriteLine(sb.ToString()); + } + + Debug.Log("saved_to: "+filePath); + + AssetDatabase.Refresh(); + } + + [MenuItem("Test/GetAvailableSamplers")] + static unsafe void EnumerateSamplers() + { + List names = new List(); + UnityEngine.Profiling.Sampler.GetNames(names); + + var sb = new StringBuilder("Active Samplers:"+" "+names.Count+"\n"); + foreach (var n in names) + { + sb.AppendLine(n); + } + + string filePath = Application.dataPath+"/AvailableSamplers.txt"; + using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath)) + { + file.WriteLine(sb.ToString()); + } + + Debug.Log("saved_to: "+filePath); + + AssetDatabase.Refresh(); + } +} \ No newline at end of file diff --git a/Assets/Editor/PlaceObjectsTool.cs b/Assets/Editor/PlaceObjectsTool.cs index c3be3df..fcb9a43 100644 --- a/Assets/Editor/PlaceObjectsTool.cs +++ b/Assets/Editor/PlaceObjectsTool.cs @@ -1,9 +1,5 @@ using UnityEditor; using UnityEngine; -using System.Linq; -using System.Collections.Generic; -using System; - public class PlaceObjectsTool : EditorWindow { @@ -27,6 +23,8 @@ public class PlaceObjectsTool : EditorWindow bool tg_ran_pos = false; bool tg_ran_rot = false; bool tg_ran_sca = false; + bool tg_ran_scaUniform = false; + bool tg_ranSphere = false; //Distribute evenly Vector3 spacing = Vector3.one; //-1 means no limit @@ -51,6 +49,7 @@ public class PlaceObjectsTool : EditorWindow Vector3 ran_rot_max = Vector3.zero; Vector3 ran_sca_min = Vector3.one; Vector3 ran_sca_max = Vector3.one; + private float tg_ranSphere_radius = 1f; [MenuItem("Window/Place Objects Tool")] public static void ShowWindow () @@ -119,12 +118,27 @@ void OnGUI () tg_ran_sca = EditorGUILayout.Foldout (tg_ran_sca, "Random Scale"); if(tg_ran_sca) { - ran_sca_min = EditorGUILayout.Vector3Field("Min", ran_sca_min); - ran_sca_max = EditorGUILayout.Vector3Field("Max", ran_sca_max); + tg_ran_scaUniform = EditorGUILayout.Toggle("Uniform Scale", tg_ran_scaUniform); + if (tg_ran_scaUniform) + { + ran_sca_min.x = EditorGUILayout.FloatField("Min", ran_sca_min.x); + ran_sca_max.x = EditorGUILayout.FloatField("Max", ran_sca_max.x); + } + else + { + ran_sca_min = EditorGUILayout.Vector3Field("Min", ran_sca_min); + ran_sca_max = EditorGUILayout.Vector3Field("Max", ran_sca_max); + } } EditorGUILayout.EndToggleGroup(); GUILayout.Space(15); + //Random title + tg_ranSphere = EditorGUILayout.BeginToggleGroup ("Random In Sphere", tg_ranSphere); + tg_ranSphere_radius = EditorGUILayout.FloatField("Radius", tg_ranSphere_radius); + EditorGUILayout.EndToggleGroup(); + GUILayout.Space(15); + //Buttons Color original = GUI.backgroundColor; EditorGUILayout.BeginHorizontal(); @@ -353,7 +367,24 @@ void PlaceObjects() { for (int i = 0; i < objs.Length; i++) { - objs[i].localScale = RandomV3(ran_sca_min, ran_sca_max); + if (tg_ran_scaUniform) + { + float ran = Random.Range(ran_sca_min.x, ran_sca_max.x); + objs[i].localScale = new Vector3(ran, ran, ran); + } + else + { + objs[i].localScale = RandomV3(ran_sca_min, ran_sca_max); + } + } + } + + //Random in sphere + if (tg_ranSphere) + { + for (int i = 0; i < objs.Length; i++) + { + objs[i].localPosition = UnityEngine.Random.insideUnitSphere * tg_ranSphere_radius; } } } diff --git a/Assets/Editor/Read_Compiled_Shader_Tool.meta b/Assets/Editor/Read_Compiled_Shader_Tool.meta new file mode 100644 index 0000000..d5a88fe --- /dev/null +++ b/Assets/Editor/Read_Compiled_Shader_Tool.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1960e96237bff9d4db05b0cd298954b2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/Read_Compiled_Shader_Tool/README.md b/Assets/Editor/Read_Compiled_Shader_Tool/README.md new file mode 100644 index 0000000..bdf942e --- /dev/null +++ b/Assets/Editor/Read_Compiled_Shader_Tool/README.md @@ -0,0 +1,12 @@ +# Read Compiled Shader Tool +Unity 2022.2+\ +This tool reads compiled shader code (D3D only!) and put counts and summary numbers on the tool. +\ + +### How to use: +1. Add the scripts to an Editor folder +2. Top > Windows > ReadCompiledShaderTool +3. See steps on the tool. +\ +\ +![](ReadCompiledShaderTool.JPG) \ No newline at end of file diff --git a/Assets/Editor/Read_Compiled_Shader_Tool/README.md.meta b/Assets/Editor/Read_Compiled_Shader_Tool/README.md.meta new file mode 100644 index 0000000..8bc1293 --- /dev/null +++ b/Assets/Editor/Read_Compiled_Shader_Tool/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4f7c06d3866d297478624f749c136a4f +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.JPG b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.JPG new file mode 100644 index 0000000..0a666c6 Binary files /dev/null and b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.JPG differ diff --git a/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.JPG.meta b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.JPG.meta new file mode 100644 index 0000000..4918854 --- /dev/null +++ b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.JPG.meta @@ -0,0 +1,136 @@ +fileFormatVersion: 2 +guid: cd6b7c87105cf684fa3c9d2101ae3e95 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 12 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + flipGreenChannel: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMipmapLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Server + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.cs b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.cs new file mode 100644 index 0000000..e0a113f --- /dev/null +++ b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.cs @@ -0,0 +1,540 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System.IO; +using System.Reflection; +using UnityEditor.Rendering; +using System.Text; + +namespace GfxQA.ReadCompiledShaderTool +{ + public class ReadCompiledShaderTool : EditorWindow + { + public string path = "";//"C:\\Users\\XYZ\\Documents\\Compiled-ABC.shader"; + public Shader shader; + private bool includeAllVariants = true; + + //Variant Data + private List sList = new List(); + struct VariantCompileStat + { + public int subshaderID; + public int passID; + public string passName; + public string variant; + + public int countMath; + public int countTmpReg; + public int countBranches; + public int countTextures; + } + + //For menu selection + private int selectedSubShaderPass = 0; + private List pList = new List(); + private List pListMenu = new List(); + struct SubShaderPass + { + public int subshaderID; + public int passID; + public string passName; + public string summary; + } + + [MenuItem("Window/ReadCompiledShaderTool")] + public static void ShowWindow () + { + var window = EditorWindow.GetWindow (typeof(ReadCompiledShaderTool)); + window.name = "ReadCompiledShaderTool"; + window.titleContent = new GUIContent("ReadCompiledShaderTool"); + } + + void Awake() + { + + } + + void OnGUI () + { + Color originalBackgroundColor = GUI.backgroundColor; + + //Title + GUI.color = Color.yellow; + GUILayout.Label ( + //"How to use: \n"+ + // "1. Select a shader, on Inspector, click on the little triangle next to Compile and Show Code \n"+ + // "2. Select only D3D on the list \n"+ + // "3. If you want all the variants (i.e. even unused ones), untick Skip unused shader_features \n"+ + // "4. Click Compile and Show Code. It will take awhile depends on how big your shader is \n"+ + // "5. After the compiled shader code is opened, save the file to somewhere, copy the path of the file \n"+ + // " e.g. C:\\Users\\XYZ\\Documents\\Compiled-ABC.shader \n"+ + // "6. Paste the path into box below" + "This only works for showing D3D compiler math numbers. \n"+ + "If you select include all variants, avoid shaders with a lot of keywords. \n" + ); + //GUILayout.Space(10); + GUI.color = Color.white; + + //path + //path = GUILayout.TextField(path); + + //shader file + shader = (Shader)EditorGUILayout.ObjectField(shader, typeof(Shader), true); + if (shader != null) + { + includeAllVariants = GUILayout.Toggle (includeAllVariants, "Include all variants?"); + if(GUILayout.Button ("Compile shader",GUILayout.Width(200))) + { + path = ""; + CleanUpData(); + CompileShader(); + } + } + + //open compiled shader file + if (path != "" ) + { + GUI.color = Color.green; + GUILayout.Label ("Compiled: "+path , EditorStyles.wordWrappedLabel); + GUI.color = Color.white; + if(GUILayout.Button ("Open Compiled shader File",GUILayout.Width(200))) + { + Application.OpenURL (path); + } + } + + //read data + // if (path != "" && GUILayout.Button ("Read data",GUILayout.Width(200))) + // { + // ReadCompiledD3DShader(path); + // } + + GUILayout.Space(20); + + //Subshader Pass selection + if(pList.Count>0) + { + selectedSubShaderPass = EditorGUILayout.Popup("Select Subshader / Pass", selectedSubShaderPass, pListMenu.ToArray()); + GUILayout.Space(10); + ShowData(); + } + + //End Window + GUILayout.FlexibleSpace(); + EditorGUILayout.Separator(); + } + + private void CompileShader() + { + // Editor/Mono/ShaderUtil.bindings.cs + // extern internal static void OpenCompiledShader(Shader shader, int mode, int externPlatformsMask, bool includeAllVariants, bool preprocessOnly, bool stripLineDirectives); + // extern internal static void CompileShaderForTargetCompilerPlatform(Shader shader, ShaderCompilerPlatform platform); + + System.Type t = typeof(ShaderUtil); + MethodInfo dynMethod = t.GetMethod("OpenCompiledShader", BindingFlags.NonPublic | BindingFlags.Static); + int defaultMask = (1 << System.Enum.GetNames(typeof(UnityEditor.Rendering.ShaderCompilerPlatform)).Length - 1); + dynMethod.Invoke(null, new object[] { shader, 1, defaultMask, includeAllVariants, false, true}); + + //This does not generate the compiled file + // System.Type t = typeof(ShaderUtil); + // MethodInfo dynMethod = t.GetMethod("CompileShaderForTargetCompilerPlatform", BindingFlags.NonPublic | BindingFlags.Static); + // dynMethod.Invoke(null, new object[] { shader, ShaderCompilerPlatform.D3D}); + + //Compiled shader file stored in project Temp folder, with name e.g. Compiled-Unlit-NewUnlitShader.shader + path = Application.dataPath.Replace("Assets","Temp")+"/Compiled-"+shader.name.Replace("/","-")+".shader"; + Debug.Log("Compiled Shader : "+path); + + ReadCompiledD3DShader(path); + } + + private void ShowData() + { + SubShaderPass selected = pList[selectedSubShaderPass]; + + //Results Sum + int r_countVariant_sum = 0; + int r_countMath_sum = 0; + int r_countTmpReg_sum = 0; + int r_countBranches_sum = 0; + int r_countTextures_sum = 0; + + //Results Avg + int r_countMath_avg = 0; + int r_countTmpReg_avg = 0; + int r_countBranches_avg = 0; + int r_countTextures_avg = 0; + + //Results Max + int r_countMath_max = 0; + int r_countTmpReg_max = 0; + int r_countBranches_max = 0; + int r_countTextures_max = 0; + + //The king sList IDs + int countMath_king = 0; + int countTmpReg_king = 0; + int countBranches_king = 0; + int countTextures_king = 0; + + for(int i=0; i sList[countMath_king].countMath ) countMath_king = i; + if( sList[i].countTmpReg > sList[countTmpReg_king].countTmpReg ) countTmpReg_king = i; + if( sList[i].countBranches > sList[countBranches_king].countBranches ) countBranches_king = i; + if( sList[i].countTextures > sList[countTextures_king].countTextures ) countTextures_king = i; + } + } + + if(r_countVariant_sum > 0) + { + //Avg + r_countMath_avg = r_countMath_sum / r_countVariant_sum; + r_countTmpReg_avg = r_countTmpReg_sum / r_countVariant_sum; + r_countBranches_avg = r_countBranches_sum / r_countVariant_sum; + r_countTextures_avg = r_countTextures_sum / r_countVariant_sum; + + //Max + r_countMath_max = sList[countMath_king].countMath; + r_countTmpReg_max = sList[countTmpReg_king].countTmpReg; + r_countBranches_max = sList[countBranches_king].countBranches; + r_countTextures_max = sList[countTextures_king].countTextures; + } + + //Width for the columns & style + float currentSize = this.position.width; + float[] columnWidth = new float[] + { + 0.5f, + 0.3f, + 0.3f, + 0.3f, + 2f + }; + float widthForEach = currentSize / columnWidth.Length; + GUILayoutOption[] columnLayoutOption = new GUILayoutOption[columnWidth.Length]; + for(int i=0; i 0 ? sList[countMath_king].variant : ""; + if(GUILayout.Button(kingText,kingButtonStyle,columnLayoutOption[layoutID])) + { + GUIUtility.systemCopyBuffer = kingText; + } + + kingText = countTmpReg_king > 0 ? sList[countTmpReg_king].variant : ""; + if(GUILayout.Button(kingText,kingButtonStyle,columnLayoutOption[layoutID])) + { + GUIUtility.systemCopyBuffer = kingText; + } + + kingText = countBranches_king > 0 ? sList[countBranches_king].variant : ""; + if(GUILayout.Button(kingText,kingButtonStyle,columnLayoutOption[layoutID])) + { + GUIUtility.systemCopyBuffer = kingText; + } + + kingText = countTextures_king > 0 ? sList[countTextures_king].variant : ""; + if(GUILayout.Button(kingText,kingButtonStyle,columnLayoutOption[layoutID])) + { + GUIUtility.systemCopyBuffer = kingText; + } + + GUILayout.EndVertical(); + + GUILayout.EndHorizontal(); + + } + + private void CleanUpData() + { + sList.Clear(); + pList.Clear(); + pListMenu.Clear(); + } + + private void ReadCompiledD3DShader(string path) + { + FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + + //For iteration of file texts + bool variantstart = false; + string keywordsText = ""; + + //Data for packing into VariantCompileStat + int data_subshaderID = -1; + int data_passID = -1; + string data_passName = ""; + string data_variant = ""; + int data_countMath = 0; + int data_countTmpReg = 0; + int data_countBranches = 0; + int data_countTextures = 0; + + //CleanUp + CleanUpData(); + + using (StreamReader sr = new StreamReader(fs)) + { + string currentLine = ""; + while(currentLine != null) //while(!sr.EndOfStream) does not work + { + currentLine = sr.ReadLine(); + if(currentLine != null) + { + //SUBSHADER + if(currentLine.Contains("SubShader { ")) + { + data_subshaderID ++; + data_passID = -1; + + //Pack into struct + SubShaderPass newData = new SubShaderPass(); + newData.subshaderID = data_subshaderID; + newData.passID = -1; + newData.passName = ""; + pList.Add(newData); + } + + //PASS + else if(currentLine.Contains(" Name "+'"')) + { + data_passID ++; + data_passName = currentLine.Replace(" Name ", ""); + + //Pack into struct + SubShaderPass newData = new SubShaderPass(); + newData.subshaderID = data_subshaderID; + newData.passID = data_passID; + newData.passName = data_passName; + pList.Add(newData); + } + + //VARIANT START + else if(currentLine.Contains("Keywords: ")) + { + keywordsText = currentLine.Replace("Keywords: ",""); + variantstart = true; + } + + //STATS for VARIANT + else if(currentLine.Contains("// Stats: ")) + { + //VARIANT + if(variantstart) + { + data_variant = keywordsText; + keywordsText = ""; + variantstart = false; + } + + /* + math -> temp registers -> textures -> branches + // Stats: 79 math, 7 temp registers, 33 branches + // Stats: 0 math, 1 textures + // Stats: 2 math, 2 temp registers, 1 textures + // Stats: 98 math, 11 temp registers, 1 textures, 6 branches + */ + + //DATA + string data = currentLine; + data = data.Replace("// Stats: ",""); + + //math count + string temp = ExtractString(data, ""," math",true); + data_countMath = int.Parse(temp); + data = data.Replace(data_countMath+" math, ",""); + + //register count + if(data.Contains("temp registers")) + { + temp = ExtractString(data, ""," temp registers",true); + data_countTmpReg = int.Parse(temp); + data = data.Replace(data_countTmpReg+" temp registers, ",""); + } + + //textures count + if(data.Contains("textures")) + { + temp = ExtractString(data, ""," textures",true); + data_countTextures = int.Parse(temp); + data = data.Replace(data_countTextures+" textures, ",""); + } + + //branch count + if(data.Contains("branches")) + { + temp = ExtractString(data, ""," branches",true); + data_countBranches = int.Parse(temp); + } + + //Pack into struct + VariantCompileStat newData = new VariantCompileStat(); + newData.subshaderID = data_subshaderID; + newData.passID = data_passID; + newData.passName = data_passName; + newData.variant = data_variant; + newData.countMath = data_countMath; + newData.countTmpReg = data_countTmpReg; + newData.countBranches = data_countBranches; + newData.countTextures = data_countTextures; + sList.Add(newData); + } + + //STATS for PASS (SUMMARY OF PASS) + else if(currentLine.Contains("// Stats for ")) + { + // Stats for Vertex shader: + // d3d11: 9 math + // Stats for Fragment shader: + // d3d11: 0 math, 1 texture + + string summary = ""; + summary += currentLine + "\n"; + currentLine = sr.ReadLine(); + summary += currentLine + "\n"; + + //Summary comes before the pass, i.e. Subshader > summary > Pass, so this ID is offset by 1. + //Offset compensates in ShowData() + int pListID = pList.Count-1; + var temp = pList[pListID]; + temp.summary += summary; + pList[pListID] = temp; + } + } + } + } + + //Add options to Subshader/Pass menu list + foreach(SubShaderPass pData in pList) + { + if(pData.passID == -1) + { + //Subshader + pListMenu.Add("Subshader: "+pData.subshaderID); + } + else + { + //Pass + pListMenu.Add("Subshader: "+pData.subshaderID+" > Pass: "+pData.passName); + } + } + } + + //==========HELPER=========== + private static string ExtractString(string line, string from, string to, bool takeLastIndexOfTo = true) + { + int pFrom = 0; + if(from != "") + { + int index = line.IndexOf(from); + if(index >= 0) pFrom = index + from.Length; + } + + int pTo = line.Length; + if(to != "") + { + int index = line.LastIndexOf(to); + if(!takeLastIndexOfTo) + { + index = line.IndexOf(to); + } + + if(index >= 0) pTo = index; + } + + return line.Substring(pFrom, pTo - pFrom); + } + } +} + + + diff --git a/Assets/Editor/ShaderVariantTool/ShaderVariantTool_ComputePreprocess.cs.meta b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.cs.meta similarity index 83% rename from Assets/Editor/ShaderVariantTool/ShaderVariantTool_ComputePreprocess.cs.meta rename to Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.cs.meta index 8325fe1..674a614 100644 --- a/Assets/Editor/ShaderVariantTool/ShaderVariantTool_ComputePreprocess.cs.meta +++ b/Assets/Editor/Read_Compiled_Shader_Tool/ReadCompiledShaderTool.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 937781451af9258439d4bf6a4bc25a5c +guid: 9190b198980a22645941ce3e9c572535 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/Editor/SaveObjectAndNullPathImage.cs b/Assets/Editor/SaveObjectAndNullPathImage.cs new file mode 100644 index 0000000..0ecb69c --- /dev/null +++ b/Assets/Editor/SaveObjectAndNullPathImage.cs @@ -0,0 +1,62 @@ +using System.Collections; +using System.Collections.Generic; +#if UNITY_EDITOR +using UnityEditor; +using UnityEngine.UI; +#endif +using UnityEngine; + +// Use this tool to save a prefab to Asset folder together +// with the images that is loaded on UI Image/RawImage components, +// which the images are downloaded that they only exist in memory. + +// This is useful if you want to isolate some assets for debugging purposes, +// that you don't want to complicate the project with setting up the downloading of the images +// just for reproduce an unrelated bug. + +public class SaveObjectAndNullPathImage +{ + #if UNITY_EDITOR + [MenuItem("Test/SaveAsset")] + public static void SaveAsset() + { + var selected = Selection.activeObject as GameObject; + + var allImage = selected.GetComponentsInChildren(); + foreach (var img in allImage) + { + if (img.sprite != null) + { + string path = AssetDatabase.GetAssetPath(img.sprite); + if (path == "") + { + AssetDatabase.CreateAsset(img.sprite, "Assets/_CMWTest/SaveAsset/" + img.sprite.name + ".asset"); + } + } + } + + var allRawImage = selected.GetComponentsInChildren(); + foreach (var img in allRawImage) + { + if (img.texture != null) + { + string path = AssetDatabase.GetAssetPath(img.texture); + if (path == "") + { + AssetDatabase.CreateAsset(img.texture, "Assets/_CMWTest/SaveAsset/" + img.texture.name + ".asset"); + } + } + } + + Debug.Log(selected.name); + bool prefabSuccess; + string localPath = "Assets/_CMWTest/SaveAsset/" + selected.name + ".prefab"; + PrefabUtility.SaveAsPrefabAsset(selected, localPath, out prefabSuccess); + Debug.Log(localPath+ " = " +prefabSuccess); + } + #endif + +} + + + diff --git a/Assets/Editor/ScenesThatContainThis.cs b/Assets/Editor/ScenesThatContainThis.cs new file mode 100644 index 0000000..8bbb8eb --- /dev/null +++ b/Assets/Editor/ScenesThatContainThis.cs @@ -0,0 +1,133 @@ +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using System.Collections.Generic; +using System; +using Object = UnityEngine.Object; +using System.Linq; +using UnityEditor.SceneManagement; + +public class ScenesThatContainThis : EditorWindow +{ + private string msg = ""; + private MonoScript searchType; + private Dictionary result = new Dictionary(); + + [MenuItem("Window/ScenesThatContainThis")] + public static void ShowWindow () + { + EditorWindow.GetWindow (typeof(ScenesThatContainThis)); + } + + public void Update() + { + Repaint(); + } + + void OnGUI () + { + GUIStyle labelStyle = new GUIStyle(GUI.skin.label); + labelStyle.wordWrap = true; + labelStyle.richText = true; + + GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); + buttonStyle.wordWrap = true; + buttonStyle.richText = true; + buttonStyle.alignment = TextAnchor.MiddleLeft; + + GUI.color = Color.cyan; + GUILayout.Label ("Scenes that contain objects that are using this script:", EditorStyles.boldLabel); + + searchType = (MonoScript)EditorGUILayout.ObjectField("Assign a script",searchType, typeof(MonoScript), false); + + GUI.color = Color.white; + GUILayout.Space(15); + + //Button + if (GUILayout.Button ("Let's check") && searchType != null) DoJob(); + + GUILayout.Space(15); + + //Result + GUILayout.Label (msg, labelStyle); + if(result.Count>0) + { + for( int i=0; i"+objcount + " objects"+"",buttonStyle)) + { + OpenScene(scenepath); + } + } + GUI.color = Color.cyan; + if (GUILayout.Button ("Remove component from all the scenes")) RemoveComponent(); + GUI.color = Color.white; + } + + GUILayout.Space(15); + } + + void DoJob() + { + GUI.color = Color.white; + msg = "Search for : "+searchType.GetClass().ToString()+""+"\n"; + + //Get all the scenes in project + var scenesGUIDs = AssetDatabase.FindAssets("t:Scene",new[] {"Assets/"}); + msg += "Search in : "+scenesGUIDs.Length+" scenes"+"\n"; + + if(result == null) result = new Dictionary(); + result.Clear(); + for(int i=0; i 0) + { + result.Add(scenePath,subsceneObjs.Length); + } + } + + msg += "Result : "+result.Count+" scenes"+"\n"; + msg +="\n"; + } + + void RemoveComponent() + { + for( int i=0; i Windows > ShaderVariantTool -\ -\ -![](README01.jpg) - - -# ShaderStripping Example scripts - -### How to use: -1. Add the scripts to an Editor folder: \ -StrippingExample_Shader.cs \ -StrippingExample_ComputeShader.cs -2. Edit the scripts so that you can define what you want to strip -3. Make a player build -4. You can use ShaderVariantTool to verify if those variants are stripped - +Tool is moved to a new repo: https://github.com/cinight/ShaderVariantTool diff --git a/Assets/Editor/ShaderVariantTool/README.md.meta b/Assets/Editor/ShaderVariantTool/README.md.meta new file mode 100644 index 0000000..2514bdc --- /dev/null +++ b/Assets/Editor/ShaderVariantTool/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 63d73fcd3309bbc45b52ec908b0d7495 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/ShaderVariantTool/README01.jpg b/Assets/Editor/ShaderVariantTool/README01.jpg deleted file mode 100644 index 6659774..0000000 Binary files a/Assets/Editor/ShaderVariantTool/README01.jpg and /dev/null differ diff --git a/Assets/Editor/ShaderVariantTool/ShaderVariantTool.cs b/Assets/Editor/ShaderVariantTool/ShaderVariantTool.cs deleted file mode 100644 index e64f6db..0000000 --- a/Assets/Editor/ShaderVariantTool/ShaderVariantTool.cs +++ /dev/null @@ -1,301 +0,0 @@ -using UnityEditor; -using UnityEngine; -using System.Linq; -using System.Collections.Generic; - -public class ShaderVariantTool : EditorWindow -{ - Vector2 scrollPosition; - - public static string folderPath = ""; - public static string savedFile = ""; - - //ColumnSetup - Color columnColor1 = new Color(0.3f,0.3f,0.3f,1); - Color columnColor2 = new Color(0.28f,0.28f,0.28f,1); - float[] widthScale = new float[] - { - 0, //we don't show shader name - - 0.9f, - 1.8f, - 1.2f, - - 1.2f, - - 0.6f, - 0.8f, - - 2.1f, - 1f, - 0.5f, - 0.5f, - 0.5f, - - 0.4f, - }; - - [MenuItem("Window/ShaderVariantTool")] - public static void ShowWindow () - { - var window = EditorWindow.GetWindow (typeof(ShaderVariantTool)); - } - - // public void Awake() - // { - // } - - // public void OnDestroy() - // { - // } - - void OnGUI () - { - Color originalBackgroundColor = GUI.backgroundColor; - - //Title - GUI.color = Color.cyan; - GUILayout.Label ("Build the player and see the variants list here.", EditorStyles.wordWrappedLabel); - GUI.color = Color.white; - - if(savedFile != "") - { - GUI.color = Color.green; - - //Result - GUILayout.Label ( "Build Time : " + SVL.buildTime.ToString("0.000") + " seconds", EditorStyles.wordWrappedLabel ); - GUILayout.Label ( "Shader Count : " + SVL.shaderlist.Count, EditorStyles.wordWrappedLabel ); - GUILayout.Label ( "Total Variant Count : " + SVL.variantTotalCount, EditorStyles.wordWrappedLabel ); - //GUILayout.Label ( "Total Data Count : " + SVL.compiledTotalCount, EditorStyles.wordWrappedLabel ); - - //Saved file path - GUILayout.Label ( "Saved: "+savedFile, EditorStyles.wordWrappedLabel); - - //Show folder button - GUI.color = Color.white; - if (GUILayout.Button ("Show in explorer",GUILayout.Width(200))) - { - System.Diagnostics.Process.Start("explorer.exe", "/select,"+savedFile.Replace(@"/", @"\")); // explorer doesn't like front slashes - } - } - GUI.color = Color.white; - GUILayout.Space(15); - - //Width for the columns & style - float currentSize = this.position.width; - float widthForEach = currentSize / (SVL.columns.Length-1+currentSize*0.0002f); - GUIStyle background = new GUIStyle - { - normal = - { - background = Texture2D.whiteTexture, - textColor = Color.white - } - }; - - //Column Titles - EditorGUILayout.BeginHorizontal(); - for(int i=1;i0 && SVL.rowData.Count > 0) - { - for(int k=1; k < SVL.rowData.Count; k++) //first row is title so start with 1 - { - string shaderName = SVL.rowData[k][0]; - int shaderIndex = SVL.shaderlist.FindIndex( o=> o.name == shaderName ); - CompiledShader currentShader = SVL.shaderlist[shaderIndex]; - - if(shaderName != SVL.rowData[k-1][0]) //show title - { - GUI.backgroundColor = originalBackgroundColor; - currentShader.guiEnabled = EditorGUILayout.Foldout( currentShader.guiEnabled, shaderName + " (" + currentShader.noOfVariantsForThisShader + ")" ); - SVL.shaderlist[shaderIndex] = currentShader; - } - - //Show the shader variants - if( currentShader.guiEnabled ) - { - EditorGUILayout.BeginHorizontal(); - for(int i=1;i variantlist = new List(); - public static List shaderlist = new List(); - public static List rowData = new List(); - public static string[] columns = new string[] - { - "Shader", - "PassType", - "PassName", - "ShaderType", - "KernelName", - "GfxTier", - "Platform", - "Keyword Name", - "Keyword Type", - "Keyword Index", - "Keyword Valid", - "Keyword Enabled", - "Compiled Count" - }; - - public static void ResetBuildList() - { - if(!buildProcessStarted) - { - SVL.shaderlist.Clear(); - SVL.variantlist.Clear(); - SVL.compiledTotalCount = 0; - SVL.variantTotalCount = 0; - - buildProcessStarted = true; - } - } - - public static void Sorting() - { - //sort the list according to shader name - variantlist = variantlist.OrderBy(o=>o.shaderName).ThenBy(o=>o.shaderType).ThenBy(o=>o.shaderKeywordIndex).ToList(); - - //Unique item and duplicate counts - Dictionary uniqueSet = new Dictionary(); - - //count duplicates - for(int i=0; i data) - { - int newVariantsForThisShader = 0; - - //The real variant count - newVariantsForThisShader+=data.Count; - - //Go through all the variants - for (int i = 0; i < data.Count; ++i) - { - ShaderKeyword[] sk = data[i].shaderKeywordSet.GetShaderKeywords(); - - //The default variant - if(sk.Length==0) - { - CompiledShaderVariant scv_default = new CompiledShaderVariant(); - //scv.id = id; - scv_default.shaderName = shader.name; - scv_default.kernelName = kernelName; - scv_default.passName = "--"; - scv_default.passType = "--"; - scv_default.shaderType = "--"; - scv_default.graphicsTier = "--"; - scv_default.shaderCompilerPlatform = "--"; - scv_default.shaderKeywordName = "No Keyword / All Off"; - scv_default.shaderKeywordType = "--"; - scv_default.shaderKeywordIndex = "-1"; - scv_default.isShaderKeywordValid = "--"; - scv_default.isShaderKeywordEnabled = "--"; - SVL.variantlist.Add(scv_default); - SVL.compiledTotalCount++; - } - - for (int k = 0; k < sk.Length; ++k) - { - CompiledShaderVariant scv = new CompiledShaderVariant(); - - //scv.id = id; - scv.shaderName = shader.name; - scv.kernelName = kernelName; - scv.passName = "--"; - scv.passType = "--"; - scv.shaderType = "--"; - - scv.graphicsTier = data[i].graphicsTier.ToString(); - scv.shaderCompilerPlatform = data[i].shaderCompilerPlatform.ToString(); - //scv.shaderRequirements = ""+data[i].shaderRequirements; - //scv.platformKeywordName = ""+data[i].platformKeywordSet.ToString(); - //scv.isplatformKeywordEnabled = ""+data[i].platformKeywordSet.IsEnabled(BuiltinShaderDefine.SHADER_API_DESKTOP); - - bool isLocal = ShaderKeyword.IsKeywordLocal(sk[k]); - scv.shaderKeywordName = ( isLocal? "[Local] " : "[Global] " ) + ShaderKeyword.GetKeywordName(shader,sk[k]); //sk[k].GetKeywordName(); - scv.shaderKeywordType = ShaderKeyword.GetKeywordType(shader,sk[k]).ToString(); //""+sk[k].GetKeywordType().ToString(); - scv.shaderKeywordIndex = sk[k].index.ToString(); - scv.isShaderKeywordValid = sk[k].IsValid().ToString(); - scv.isShaderKeywordEnabled = data[i].shaderKeywordSet.IsEnabled(sk[k]).ToString(); - - SVL.variantlist.Add(scv); - SVL.compiledTotalCount++; - - //Just to verify API is correct - string globalShaderKeywordName = ShaderKeyword.GetGlobalKeywordName(sk[k]); - if( !isLocal && globalShaderKeywordName != ShaderKeyword.GetKeywordName(shader,sk[k]) ) Debug.LogError("Bug. ShaderKeyword.GetGlobalKeywordName() and ShaderKeyword.GetKeywordName() is wrong"); - ShaderKeywordType globalShaderKeywordType = ShaderKeyword.GetGlobalKeywordType(sk[k]); - if( !isLocal && globalShaderKeywordType != ShaderKeyword.GetKeywordType(shader,sk[k]) ) Debug.LogError("Bug. ShaderKeyword.GetGlobalKeywordType() and ShaderKeyword.GetKeywordType() is wrong"); - } - } - - //Add to shader list - int compiledShaderId = SVL.shaderlist.FindIndex( o=> o.name == shader.name ); - if( compiledShaderId == -1 ) - { - CompiledShader newCompiledShader = new CompiledShader(); - newCompiledShader.name = shader.name; - newCompiledShader.guiEnabled = false; - newCompiledShader.noOfVariantsForThisShader = 0; - SVL.shaderlist.Add(newCompiledShader); - compiledShaderId=SVL.shaderlist.Count-1; - } - - //Add variant count to shader - CompiledShader compiledShader = SVL.shaderlist[compiledShaderId]; - compiledShader.noOfVariantsForThisShader += newVariantsForThisShader; - SVL.shaderlist[compiledShaderId] = compiledShader; - - //Add to total count - SVL.variantTotalCount+=newVariantsForThisShader; - } -} \ No newline at end of file diff --git a/Assets/Editor/ShaderVariantTool/ShaderVariantTool_ShaderPreprocess.cs b/Assets/Editor/ShaderVariantTool/ShaderVariantTool_ShaderPreprocess.cs deleted file mode 100644 index e9f6ba2..0000000 --- a/Assets/Editor/ShaderVariantTool/ShaderVariantTool_ShaderPreprocess.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using UnityEditor; -using UnityEditor.Build; -using UnityEditor.Build.Reporting; -using UnityEditor.Rendering; -using UnityEditorInternal; -using UnityEngine; -using UnityEngine.Rendering; - -class ShaderVariantTool_ShaderPreprocess : IPreprocessShaders -{ - public ShaderVariantTool_ShaderPreprocess() - { - SVL.ResetBuildList(); - } - - public int callbackOrder { get { return 10; } } - - public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList data) - { - int newVariantsForThisShader = 0; - - //The real variant count - newVariantsForThisShader+=data.Count; - - //Go through all the variants - for (int i = 0; i < data.Count; ++i) - { - ShaderKeyword[] sk = data[i].shaderKeywordSet.GetShaderKeywords(); - - //The default variant - if(sk.Length==0) - { - CompiledShaderVariant scv_default = new CompiledShaderVariant(); - //scv.id = id; - scv_default.shaderName = shader.name; - scv_default.passName = snippet.passName; - scv_default.passType = snippet.passType.ToString(); - scv_default.shaderType = snippet.shaderType.ToString(); - scv_default.kernelName = "--"; - scv_default.graphicsTier = "--"; - scv_default.shaderCompilerPlatform = "--"; - scv_default.shaderKeywordName = "No Keyword / All Off"; - scv_default.shaderKeywordType = "--"; - scv_default.shaderKeywordIndex = "-1"; - scv_default.isShaderKeywordValid = "--"; - scv_default.isShaderKeywordEnabled = "--"; - SVL.variantlist.Add(scv_default); - SVL.compiledTotalCount++; - } - - for (int k = 0; k < sk.Length; ++k) - { - CompiledShaderVariant scv = new CompiledShaderVariant(); - - //scv.id = id; - scv.shaderName = shader.name; - scv.passName = snippet.passName; - scv.passType = snippet.passType.ToString(); - scv.shaderType = snippet.shaderType.ToString(); - scv.kernelName = "--"; - - scv.graphicsTier = data[i].graphicsTier.ToString(); - scv.shaderCompilerPlatform = data[i].shaderCompilerPlatform.ToString(); - //scv.shaderRequirements = ""+data[i].shaderRequirements; - //scv.platformKeywordName = ""+data[i].platformKeywordSet.ToString(); - //scv.isplatformKeywordEnabled = ""+data[i].platformKeywordSet.IsEnabled(BuiltinShaderDefine.SHADER_API_DESKTOP); - - bool isLocal = ShaderKeyword.IsKeywordLocal(sk[k]); - scv.shaderKeywordName = ( isLocal? "[Local] " : "[Global] " ) + ShaderKeyword.GetKeywordName(shader,sk[k]); //sk[k].GetKeywordName(); - scv.shaderKeywordType = ShaderKeyword.GetKeywordType(shader,sk[k]).ToString(); //""+sk[k].GetKeywordType().ToString(); - scv.shaderKeywordIndex = sk[k].index.ToString(); - scv.isShaderKeywordValid = sk[k].IsValid().ToString(); - scv.isShaderKeywordEnabled = data[i].shaderKeywordSet.IsEnabled(sk[k]).ToString(); - - SVL.variantlist.Add(scv); - SVL.compiledTotalCount++; - - //Just to verify API is correct - string globalShaderKeywordName = ShaderKeyword.GetGlobalKeywordName(sk[k]); - if( !isLocal && globalShaderKeywordName != ShaderKeyword.GetKeywordName(shader,sk[k]) ) Debug.LogError("Bug. ShaderKeyword.GetGlobalKeywordName() and ShaderKeyword.GetKeywordName() is wrong"); - ShaderKeywordType globalShaderKeywordType = ShaderKeyword.GetGlobalKeywordType(sk[k]); - if( !isLocal && globalShaderKeywordType != ShaderKeyword.GetKeywordType(shader,sk[k]) ) Debug.LogError("Bug. ShaderKeyword.GetGlobalKeywordType() and ShaderKeyword.GetKeywordType() is wrong"); - } - } - - //Add to shader list - int compiledShaderId = SVL.shaderlist.FindIndex( o=> o.name == shader.name ); - if( compiledShaderId == -1 ) - { - CompiledShader newCompiledShader = new CompiledShader(); - newCompiledShader.name = shader.name; - newCompiledShader.guiEnabled = false; - newCompiledShader.noOfVariantsForThisShader = 0; - SVL.shaderlist.Add(newCompiledShader); - compiledShaderId=SVL.shaderlist.Count-1; - } - - //Add variant count to shader - CompiledShader compiledShader = SVL.shaderlist[compiledShaderId]; - compiledShader.noOfVariantsForThisShader += newVariantsForThisShader; - SVL.shaderlist[compiledShaderId] = compiledShader; - - //Add to total count - SVL.variantTotalCount+=newVariantsForThisShader; - } -} - -class ShaderVariantTool_BuildPreprocess : IPreprocessBuildWithReport -{ - public int callbackOrder { get { return 10; } } - public void OnPreprocessBuild(BuildReport report) - { - //Debug.Log("ShaderVariantTool_BuildPreprocess starts now.."); - SVL.ResetBuildList(); - SVL.buildTime = EditorApplication.timeSinceStartup; - } -} - -class ShaderVariantTool_BuildPostprocess : IPostprocessBuildWithReport -{ - public int callbackOrder { get { return 10; } } - - public void OnPostprocessBuild(BuildReport report) - { - //Calculate build time - SVL.buildTime = EditorApplication.timeSinceStartup - SVL.buildTime; - - //Sort the results and make row data - SVL.Sorting(); - - //Prepare CSV string - List outputRows = new List(); - - //Get Unity & branch version - string version_changeset = Convert.ToString(InternalEditorUtility.GetUnityRevision(), 16); - string version_branch = InternalEditorUtility.GetUnityBuildBranch(); - string unity_version = Application.unityVersion +" "+ version_branch+" ("+version_changeset+")"; - - //Get Graphics API list - var gfxAPIsList = PlayerSettings.GetGraphicsAPIs(report.summary.platform); - string gfxAPIs = ""; - for(int i=0; i