Skip to content

Commit

Permalink
v25
Browse files Browse the repository at this point in the history
  • Loading branch information
DarthShader committed Sep 1, 2020
1 parent d4c3112 commit 43605be
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 80 deletions.
61 changes: 38 additions & 23 deletions Shaders/Kaj/Editor/KajShaderEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@ public enum LightMode
VertexLM
}

// Reusable enum for texture UV modes, technically shader specific but
// it's either add this or remake the regular width Enum drawer
public enum UVMapping
{
UV0,
UV1,
UV2,
UV3,
WorldTriplanar,
ObjectTriplanar,
XYWorldPlanar,
YZWorldPlanar,
ZXWorldPlanar,
XYObjectPlanar,
YZObjectPlanar,
ZXObjectPlanar
}

// Simple indent and unindent decorators
// 2px padding is still added around each decorator, might change to -2 height later
public class IndentDecorator : MaterialPropertyDrawer
Expand Down Expand Up @@ -424,6 +442,8 @@ public class ShaderEditor : ShaderGUI
const string togglePrefix = "toggle_"; // foldout combined with a checkbox i.e. group_toggle_Parallax
const string endPrefix = "end_";
GUIStyle foldoutStyle;
bool m_FirstTimeApply = true;
string[] modeNames;

public enum DisableBatchingFlags
{
Expand Down Expand Up @@ -451,30 +471,10 @@ public enum PreviewType
// Shader Optimizer
MaterialProperty shaderOptimizer = null;

bool m_FirstTimeApply = true;
string[] modeNames;

public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
{
// Move to constructor?
foldoutStyle = new GUIStyle("ShurikenModuleTitle");
foldoutStyle.font = new GUIStyle(EditorStyles.label).font;
foldoutStyle.border = new RectOffset(15, 7, 4, 4);
foldoutStyle.fixedHeight = 22;
foldoutStyle.contentOffset = new Vector2(20f, -2f);


blendMode = FindProperty("_Mode", props, false);
if (blendMode == null) Debug.LogWarning("[Kaj Shader Editor] Shader Property _Mode not found");
// Cache the names of each mode preset
if (blendMode != null)
{
int modeCount = Int32.Parse(blendMode.displayName);
modeNames = new string[modeCount];
for (int i=0; i<modeCount;i++)
modeNames[i] = Array.Find(props, x => x.name == "_Mode" + i).displayName.Split(';')[0];
}

lightModes = FindProperty("_LightModes", props, false);
if (lightModes == null) Debug.LogWarning("[Kaj Shader Editor] Shader Property _LightModes not found");
disableBatching = FindProperty("_DisableBatching", props, false);
Expand All @@ -489,13 +489,28 @@ public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] pro
if (previewType == null) Debug.LogWarning("[Kaj Shader Editor] Shader Property _PreviewType not found");
ditheredLODcrossfade = FindProperty("_DitheredLODCrossfade", props, false);
if (ditheredLODcrossfade == null) Debug.LogWarning("[Kaj Shader Editor] Shader Property _DitheredLODCrossfade not found");
Material material = materialEditor.target as Material;

shaderOptimizer = FindProperty("_ShaderOptimizerEnabled", props, false);
if (shaderOptimizer == null) Debug.LogWarning("[Kaj Shader Editor] Shader Property _ShaderOptimizerEnabled not found");
Material material = materialEditor.target as Material;

if (m_FirstTimeApply)
{
foldoutStyle = new GUIStyle("ShurikenModuleTitle");
foldoutStyle.font = new GUIStyle(EditorStyles.label).font;
foldoutStyle.border = new RectOffset(15, 7, 4, 4);
foldoutStyle.fixedHeight = 22;
foldoutStyle.contentOffset = new Vector2(20f, -2f);

// Cache the names of each mode preset
if (blendMode != null)
{
int modeCount = 0;
while (FindProperty("_Mode" + modeCount, props, false) != null) modeCount++;
modeNames = new string[modeCount];
for (int i=0; i<modeCount;i++)
modeNames[i] = FindProperty("_Mode" + i, props, false).displayName.Split(';')[0];
}

// Materials could have their existing tags/override tags assigned to the convention named
// properties for them, but those tags might not be consistent across multiple materials, and also might not exist.
// Conversely, properties also shouldn't be auto-applied to override tags if they have mixed values.
Expand Down Expand Up @@ -852,7 +867,7 @@ protected void DrawPropertiesGUIRecursive(MaterialEditor materialEditor, Materia
}

// Derived from MaterialEditor.PropertiesDefaultGUI https://github.com/Unity-Technologies/UnityCsReference/
if ((props[i].flags & MaterialProperty.PropFlags.HideInInspector) != 0)
if ((props[i].flags & MaterialProperty.PropFlags.HideInInspector) != 0)
continue;
float h = materialEditor.GetPropertyHeight(props[i], props[i].displayName);
Rect r = EditorGUILayout.GetControlRect(true, h, EditorStyles.layerMaskField);
Expand Down
84 changes: 43 additions & 41 deletions Shaders/Kaj/Editor/KajShaderOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class ShaderOptimizer
// (The compiler is not smart enough to cull VS output that isn't used anywhere in the PS)
// Additionally, simply enabling the optimizer can define a keyword, whose name is stored here.
// This keyword is added to the beginning of all passes, right after CGPROGRAM
// NOT IMPLEMENTED YET
public static readonly string OptimizerEnabledKeyword = "OPTIMIZER_ENABLED";

// In-order list of inline sampler state names that will be replaced by InlineSamplerState() lines
Expand Down Expand Up @@ -153,17 +154,13 @@ public static bool Lock(Material material, MaterialProperty[] props)
// File filepaths and names
Shader shader = material.shader;
string shaderFilePath = AssetDatabase.GetAssetPath(shader);
string materialFullName = AssetDatabase.GetAssetPath(material);
// Remove the assets folder prefix safely (all mats should be in the assets folder anyway)
if (materialFullName.StartsWith("Assets/"))
materialFullName = materialFullName.Remove(0, "Assets/".Length);
materialFullName = materialFullName.Remove(materialFullName.Length-".mat".Length, ".mat".Length);
string materialFilePath = AssetDatabase.GetAssetPath(material);
string materialFolder = Path.GetDirectoryName(materialFilePath);
string smallguid = Guid.NewGuid().ToString().Split('-')[0];
string newShaderName = shader.name + ".Optimized/" + material.name + "-" + smallguid;
string newShaderDirectory = shaderFilePath.Remove(shaderFilePath.Length-".shader".Length, ".shader".Length) + ".Optimized/" + material.name + "-" + smallguid + "/";
string newShaderDirectory = materialFolder + "/OptimizedShaders/" + material.name + "-" + smallguid + "/";

// Parse shader and cginc files, renaming them and moving them to a new directory
// Also gets preprocessor macros
// Parse shader and cginc files, also gets preprocessor macros
List<ParsedShaderFile> shaderFiles = new List<ParsedShaderFile>();
List<Macro> macros = new List<Macro>();
if (!ParseShaderFilesRecursive(props, shaderFiles, newShaderDirectory, newShaderName, shaderFilePath, macros))
Expand All @@ -173,6 +170,10 @@ public static bool Lock(Material material, MaterialProperty[] props)
List<PropertyData> constantProps = new List<PropertyData>();
foreach (MaterialProperty prop in props)
{
if (prop == null) continue;
// Properties ending with convention suffix will be skipped!
if (prop.name.EndsWith(AnimatedPropertySuffix)) continue;

// Check for the convention 'Animated' Property to be true otherwise assume all properties are constant
MaterialProperty animatedProp = Array.Find(props, x => x.name == prop.name + AnimatedPropertySuffix);
if (animatedProp != null && animatedProp.floatValue == 1)
Expand All @@ -185,8 +186,9 @@ public static bool Lock(Material material, MaterialProperty[] props)
propData = new PropertyData();
propData.type = PropertyType.Vector;
propData.name = prop.name;
// Could probably check for Gamma space color property flag
propData.value = prop.colorValue.linear;
if ((prop.flags & MaterialProperty.PropFlags.Gamma) == 0)
propData.value = prop.colorValue.linear;
else propData.value = prop.colorValue;
constantProps.Add(propData);
break;
case MaterialProperty.PropType.Vector:
Expand All @@ -211,32 +213,28 @@ public static bool Lock(Material material, MaterialProperty[] props)
constantProps.Add(propData);
break;
case MaterialProperty.PropType.Texture:
if (prop.textureDimension == UnityEngine.Rendering.TextureDimension.Tex2D)
animatedProp = Array.Find(props, x => x.name == prop.name + "_ST" + AnimatedPropertySuffix);
if (!(animatedProp != null && animatedProp.floatValue == 1))
{
animatedProp = Array.Find(props, x => x.name == prop.name + "_ST" + AnimatedPropertySuffix);
if (!(animatedProp != null && animatedProp.floatValue == 1))
{
PropertyData ST = new PropertyData();
ST.type = PropertyType.Vector;
ST.name = prop.name + "_ST";
Vector2 offset = material.GetTextureOffset(prop.name);
Vector2 scale = material.GetTextureScale(prop.name);
ST.value = new Vector4(scale.x, scale.y, offset.x, offset.y);
constantProps.Add(ST);
}
animatedProp = Array.Find(props, x => x.name == prop.name + "_TexelSize" + AnimatedPropertySuffix);
if (!(animatedProp != null && animatedProp.floatValue == 1))
{
PropertyData TexelSize = new PropertyData();
TexelSize.type = PropertyType.Vector;
TexelSize.name = prop.name + "_TexelSize";
Texture t = prop.textureValue;
if (t != null)
TexelSize.value = new Vector4(1.0f / t.width, 1.0f / t.height, t.width, t.height);
else TexelSize.value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
constantProps.Add(TexelSize);
}

PropertyData ST = new PropertyData();
ST.type = PropertyType.Vector;
ST.name = prop.name + "_ST";
Vector2 offset = material.GetTextureOffset(prop.name);
Vector2 scale = material.GetTextureScale(prop.name);
ST.value = new Vector4(scale.x, scale.y, offset.x, offset.y);
constantProps.Add(ST);
}
animatedProp = Array.Find(props, x => x.name == prop.name + "_TexelSize" + AnimatedPropertySuffix);
if (!(animatedProp != null && animatedProp.floatValue == 1))
{
PropertyData TexelSize = new PropertyData();
TexelSize.type = PropertyType.Vector;
TexelSize.name = prop.name + "_TexelSize";
Texture t = prop.textureValue;
if (t != null)
TexelSize.value = new Vector4(1.0f / t.width, 1.0f / t.height, t.width, t.height);
else TexelSize.value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
constantProps.Add(TexelSize);
}
break;
}
Expand All @@ -253,17 +251,18 @@ public static bool Lock(Material material, MaterialProperty[] props)
// because they're only in .shader files outside the CG blocks, so isolate CG blocks and
// treat each of them like a full cginclude file
// Cheese it and only process any text between CGPROGRAM and ENDCG and CGINCLUDE and ENDCG anywhere
// Should probably stringbuilder these
output = "";
int cgIndex;
// Use IndexOf(String, int startIndex) as to not reallocate string of the original contents, still returns -1
// Stringbuilder the output
while ((cgIndex = fileContents.IndexOf("CGINCLUDE")) != -1)
{
output += fileContents.Substring(0, cgIndex + "CGINCLUDE".Length);
fileContents = fileContents.Remove(0, cgIndex + "CGINCLUDE".Length);
int ENDCG = fileContents.IndexOf("ENDCG");
string cg = fileContents.Substring(0, ENDCG);
fileContents = fileContents.Remove(0, ENDCG);
output += ReplaceShaderValues(cg, constantProps, macros);
output += ReplaceShaderValues(cg, constantProps, macros);
}
while ((cgIndex = fileContents.IndexOf("CGPROGRAM")) != -1)
{
Expand Down Expand Up @@ -296,8 +295,8 @@ public static bool Lock(Material material, MaterialProperty[] props)

// Write original shader to override tag
material.SetOverrideTag("OriginalShader", shader.name);
// Write the new shader name in an override tag so ONLY EXACTLY THAT SUBFOLDER WILL GET DELETED
material.SetOverrideTag("OptimizedShaderFolder", newShaderDirectory);
// Write the new shader folder name in an override tag so it will be deleted
material.SetOverrideTag("OptimizedShaderFolder", material.name + "-" + smallguid);

// For some reason when shaders are swapped on a material the RenderType override tag gets completely deleted and render queue set back to -1
// So these are saved as temp values and reassigned after switching shaders
Expand Down Expand Up @@ -686,11 +685,14 @@ public static bool Unlock (Material material)
Debug.LogError("[Kaj Shader Optimizer] Optimized shader folder could not be found, not deleting anything");
return false;
}
string materialFilePath = AssetDatabase.GetAssetPath(material);
string materialFolder = Path.GetDirectoryName(materialFilePath);
string newShaderDirectory = materialFolder + "/OptimizedShaders/" + shaderDirectory;
// Both safe ways of removing the shader make the editor GUI throw an error, so just don't refresh the
// asset database immediately
//AssetDatabase.DeleteAsset(shaderFilePath);
FileUtil.DeleteFileOrDirectory(shaderDirectory);
FileUtil.DeleteFileOrDirectory(shaderDirectory.TrimEnd('/') + ".meta");
FileUtil.DeleteFileOrDirectory(newShaderDirectory + "/");
FileUtil.DeleteFileOrDirectory(newShaderDirectory + ".meta");
//AssetDatabase.Refresh();

return true;
Expand Down
Loading

0 comments on commit 43605be

Please sign in to comment.