Skip to content

Instantly share code, notes, and snippets.

@Jayatubi
Last active October 6, 2019 11:30
Show Gist options
  • Save Jayatubi/425b678eab20888ec6a26a10b2b7dd40 to your computer and use it in GitHub Desktop.
Save Jayatubi/425b678eab20888ec6a26a10b2b7dd40 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Rendering;
public class ShaderVariantStripper : IPreprocessShaders
{
public int callbackOrder { get { return 0; } }
private const string ShaderRoot = "Assets/AssetBundle/Shader/Variant";
private const string MaterialRoot = "Assets";
private List<Material> m_materials;
class EqualityComparer : IEqualityComparer<string[]>
{
public bool Equals(string[] x, string[] y)
{
Array.Sort(x);
Array.Sort(y);
return x.SequenceEqual(y);
}
public int GetHashCode(string[] obj)
{
int hashCode = 0;
Array.Sort(obj);
foreach (var e in obj)
{
hashCode ^= e.GetHashCode();
}
return hashCode;
}
}
public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList<ShaderCompilerData> data)
{
var shaderPath = AssetDatabase.GetAssetPath(shader);
if (shaderPath.StartsWith(ShaderRoot))
{
if (m_materials == null)
{
m_materials = new List<Material>();
foreach (var path in Directory.GetFiles(MaterialRoot, "*.mat", SearchOption.AllDirectories))
{
var material = AssetDatabase.LoadAssetAtPath<Material>(path);
if (material != null)
{
m_materials.Add(material);
}
}
}
var validKeywords = UtilityFunction.GetShaderKeywords(shader);
var keywordsInUse = new HashSet<string[]>(new EqualityComparer());
keywordsInUse.UnionWith(m_materials.Where(m => m.shader == shader).Select(m => m.shaderKeywords.Where(k => validKeywords.Contains(k)).ToArray()));
for (int i = data.Count - 1; i >= 0; i--)
{
var keywordSet = data[i].shaderKeywordSet;
var enabledKeywords = keywordSet.GetShaderKeywords().Select(k => k.GetKeywordName()).ToArray();
if (!keywordsInUse.Contains(enabledKeywords))
{
data.RemoveAt(i);
}
}
Debug.Log($"Build shader {shader} with {data.Count} variants");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment