using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Poiyomi.ModularShaderSystem.CibbiExtensions; using UnityEditor; using UnityEngine; namespace Poiyomi.ModularShaderSystem { public static class ShaderGenerator { const string ITERATOR_NAMING = @"\[IDX_\w+(\+\+)?]"; // do [IDX_{}++] to increase the iterator; public static void GenerateShader(string path, ModularShader shader, bool hideVariants = false) { GenerateShader(path, shader, null, hideVariants); } public static void GenerateShader(string path, ModularShader shader, Action postGeneration, bool hideVariants = false) { GenerateShaders(new[] { (path, shader) }, postGeneration, hideVariants); } // Every import refresh reloads all shaders in the project, so shaders generated together share one. public static void GenerateShaders(IEnumerable<(string path, ModularShader shader)> shaders, Action postGeneration = null, bool hideVariants = false) { var duplicateCache = new Dictionary<(ShaderModule, int), ShaderModule[]>(); var prepared = new List<(ShaderContext context, Dictionary duplicates)>(); foreach (var (path, shader) in shaders) { var (contexts, duplicates) = PrepareShaderContexts(path, shader, postGeneration, hideVariants, duplicateCache); prepared.AddRange(contexts.Select(context => (context, duplicates))); } prepared.AsParallel().ForAll(x => x.context.GenerateShader(x.duplicates)); var generated = prepared.Select(x => x.context).ToList(); WriteShaderFiles(generated); AssetDatabase.Refresh(); ApplyDefaultTextures(generated); foreach (var context in generated) context.Shader.LastGeneratedShaders.Add(AssetDatabase.LoadAssetAtPath($"{context.FilePath}/" + context.VariantFileName)); AssetDatabase.Refresh(); } /// /// Generates shader files without refreshing the asset database. Use this for batching multiple shader generations. /// Call AssetDatabase.Refresh(), ApplyDefaultTextures(), and FinalizeGeneratedShaders() after all shaders are generated. /// public static List GenerateShaderBatched(string path, ModularShader shader, Action postGeneration = null, bool hideVariants = false) { var (contexts, duplicates) = PrepareShaderContexts(path, shader, postGeneration, hideVariants); contexts.AsParallel().ForAll(x => x.GenerateShader(duplicates)); WriteShaderFiles(contexts); return contexts; } /// /// Prepares shader contexts without generating them. Must be called on the main thread. /// Returns contexts and duplicates dictionary needed for generation. /// Use GenerateShaderContexts() to run the actual generation (can be parallelized). /// public static (List contexts, Dictionary duplicates) PrepareShaderContexts( string path, ModularShader shader, Action postGeneration = null, bool hideVariants = false, Dictionary<(ShaderModule, int), ShaderModule[]> duplicateCache = null) { if(Path.IsPathRooted(path) && !Directory.Exists(path)) Directory.CreateDirectory(path); path = GetPathRelativeToProject(path); var modules = FindAllModules(shader); var duplicates = GenerateDuplicates(modules, duplicateCache); ApplyDupliactes(modules, duplicates); var freshAssets = new Dictionary(); freshAssets.AddFreshShaderToList(shader.ShaderTemplate); freshAssets.AddFreshShaderToList(shader.ShaderPropertiesTemplate); foreach ((var template, var isCopy) in modules.SelectMany(x => x.Templates.Select(t => (t,x.IsCopy)))) freshAssets.AddFreshShaderToList(template.Template, isCopy); foreach ((var function, var isCopy) in modules.SelectMany(x => x.Functions.Select(f => (f,x.IsCopy)))) freshAssets.AddFreshShaderToList(function.ShaderFunctionCode, isCopy); var possibleVariants = GetShaderVariants(modules); var contexts = new List(); var completePropertiesBlock = GetPropertiesBlock(shader, modules, freshAssets); foreach (var variant in possibleVariants) { contexts.Add(new ShaderContext { Shader = shader, PostGeneration = postGeneration, ActiveEnablers = variant, PreparedModules = FindActiveModules(shader, variant, duplicates), DisabledSections = shader.DisabledSections?.ToArray() ?? Array.Empty(), FreshAssets = freshAssets, FilePath = path, PropertiesBlock = completePropertiesBlock, AreVariantsHidden = hideVariants }); } // Clear old generated shaders if (shader.LastGeneratedShaders != null) { foreach (Shader generatedShader in shader.LastGeneratedShaders.Where(x => x != null)) { string assetPath = AssetDatabase.GetAssetPath(generatedShader); if (string.IsNullOrWhiteSpace(assetPath)) File.Delete(assetPath); } } shader.LastGeneratedShaders = new List(); return (contexts, duplicates); } /// /// Writes generated shader files to disk. Call after GenerateShader() has been called on all contexts. /// public static void WriteShaderFiles(List contexts) { foreach (var context in contexts) { string filePath = $"{context.FilePath}/" + context.VariantFileName; string text = context.ShaderFile.ToString(); if (File.Exists(filePath)) { FileAttributes fileAttributes = File.GetAttributes(filePath) & ~FileAttributes.ReadOnly; // An untouched file isn't reimported if (new FileInfo(filePath).Length == Encoding.UTF8.GetByteCount(text) && File.ReadAllText(filePath) == text) { File.SetAttributes(filePath, fileAttributes | FileAttributes.ReadOnly); continue; } File.SetAttributes(filePath, fileAttributes); File.WriteAllText(filePath, text); File.SetAttributes(filePath, fileAttributes | FileAttributes.ReadOnly); } else { File.WriteAllText(filePath, text); File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.ReadOnly); } } } private static string GetPathRelativeToProject(string path) { if (!Directory.Exists(path)) throw new DirectoryNotFoundException($"The folder \"{path}\" is not found"); // Already a relative path if (path.StartsWith("Assets") || path.StartsWith("Packages")) return path; // Get project root (parent of Assets folder) string projectRoot = Directory.GetParent(Application.dataPath).FullName.Replace("\\", "/"); path = path.Replace("\\", "/"); // Check if path is within the project if (!path.StartsWith(projectRoot)) throw new DirectoryNotFoundException($"The folder \"{path}\" is not part of the unity project"); // Convert to relative path path = path.Substring(projectRoot.Length).TrimStart('/'); return path; } public static void GenerateMinimalShader(string path, ModularShader shader, IEnumerable materials, Action postGeneration = null) { path = GetPathRelativeToProject(path); var modules = FindAllModules(shader); var possibleVariants = GetMinimalVariants(modules, materials); var contexts = new List(); foreach (var (variant, variantMaterials) in possibleVariants) { AssetDatabase.TryGetGUIDAndLocalFileIdentifier(variantMaterials[0], out string guid, out long _); contexts.Add(new ShaderContext { Shader = shader, PostGeneration = postGeneration, ActiveEnablers = variant, FilePath = path, OptimizedShader = true, Materials = variantMaterials, Guid = guid }); } contexts.GenerateMinimalShaders(); } public static List EnqueueShadersToGenerate(string path, ModularShader shader, IEnumerable materials, Action postGeneration = null) { path = GetPathRelativeToProject(path); var modules = FindAllModules(shader); var possibleVariants = GetMinimalVariants(modules, materials); var contexts = new List(); foreach (var (variant, variantMaterials) in possibleVariants) { AssetDatabase.TryGetGUIDAndLocalFileIdentifier(variantMaterials[0], out string guid, out long _); contexts.Add(new ShaderContext { Shader = shader, PostGeneration = postGeneration, ActiveEnablers = variant, FilePath = path, OptimizedShader = true, Materials = variantMaterials, Guid = guid }); } return contexts; } public static void GenerateMinimalShaders(this List contexts) { if (contexts == null || contexts.Count == 0) return; var alreadyDoneShaders = new List(); var freshAssets = new Dictionary(); foreach (var context in contexts) { context.FreshAssets = freshAssets; context.PreparedModules = FindActiveModules(context.Shader, context.ActiveEnablers, null); context.DisabledSections = context.Shader.DisabledSections?.ToArray() ?? Array.Empty(); if (alreadyDoneShaders.Contains(context.Shader)) continue; var shader = context.Shader; var modules = FindAllModules(shader); freshAssets.AddFreshShaderToList(shader.ShaderTemplate); freshAssets.AddFreshShaderToList(shader.ShaderPropertiesTemplate); foreach (var template in modules.SelectMany(x => x.Templates)) freshAssets.AddFreshShaderToList(template.Template); foreach (var function in modules.SelectMany(x => x.Functions)) freshAssets.AddFreshShaderToList(function.ShaderFunctionCode); alreadyDoneShaders.Add(shader); } EditorUtility.DisplayProgressBar("Generating Optimized Shaders", "generating shader files", 1 / (contexts.Count + 3)); contexts.AsParallel().ForAll(x => x.GenerateShader()); try { AssetDatabase.StartAssetEditing(); int i = 0; foreach (var context in contexts) { EditorUtility.DisplayProgressBar("Generating Optimized Shaders", "Saving " + context.VariantFileName, 1 + i / (contexts.Count + 3)); File.WriteAllText($"{context.FilePath}/" + context.VariantFileName, context.ShaderFile.ToString()); i++; } } finally { EditorUtility.DisplayProgressBar("Generating Optimized Shaders", "waiting for unity to compile shaders", contexts.Count - 2 / (contexts.Count + 3)); AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); } ApplyDefaultTextures(contexts); EditorUtility.DisplayProgressBar("Generating Optimized Shaders", "applying shaders to materials", contexts.Count - 1 / (contexts.Count + 3)); foreach (var context in contexts) { var shader = Shader.Find(context.ShaderName); foreach (var material in context.Materials) { material.shader = shader; } } EditorUtility.ClearProgressBar(); } private static List> GetShaderVariants(List modules) { var dictionary = new Dictionary>(); foreach (ShaderModule module in modules) { if (module == null) continue; foreach (EnableProperty property in module.EnableProperties) { if (property == null || string.IsNullOrWhiteSpace(property.Name) || !(module.Templates?.Any(x => x.NeedsVariant) ?? false)) continue; if (dictionary.ContainsKey(property.Name)) dictionary[property.Name].Add(property.EnableValue); else dictionary.Add(property.Name, new List(new[] { property.EnableValue })); } } var keys = dictionary.Keys.ToList(); foreach (KeyValuePair> keyValuePair in dictionary) if(!keyValuePair.Value.Contains(0)) keyValuePair.Value.Insert(0,0); var states = new List>(); UnrollVariants(states, new Dictionary(), dictionary, keys); return states; } private static List<(Dictionary, List)> GetMinimalVariants(List modules, IEnumerable materials) { var enablers = new List(); foreach (ShaderModule module in modules) { if (module == null) continue; foreach (EnableProperty property in module.EnableProperties) { if (property == null || string.IsNullOrWhiteSpace(property.Name)) continue; enablers.Add(property.Name); } } enablers = enablers.Distinct().ToList(); var states = new List<(Dictionary, List)>(); foreach (Material material in materials) { var state = new Dictionary(); foreach (string enabler in enablers) state.Add(enabler, (int)material.GetFloat(enabler)); var equalState = states.Where(x => { var keys = state.Keys; foreach (string key in keys) if (x.Item1[key] != state[key]) return false; return true; }).FirstOrDefault(); if(equalState == (null, null)) states.Add((state, new List(new [] {material}))); else equalState.Item2.Add(material); } return states; } private static void UnrollVariants(ICollection> states, Dictionary current, IReadOnlyDictionary> dictionary, IReadOnlyList keys) { if (current.Count == keys.Count) { states.Add(current); return; } foreach (var value in dictionary[keys[current.Count]]) { var next = new Dictionary(current); next[keys[current.Count]] = value; UnrollVariants(states, next, dictionary, keys); } } public static string GetVariantCode(Dictionary activeEnablers) { var keys = activeEnablers.Keys.OrderBy(x => x).ToList(); bool isAllZeroes = true; var b = new StringBuilder(); foreach (string key in keys) { if (activeEnablers[key] != 0) isAllZeroes = false; b.Append($"-{activeEnablers[key]}"); } return isAllZeroes ? "" : b.ToString(); } private static void AddFreshShaderToList(this Dictionary dictionary, TemplateAsset asset, bool isModuleCopy = false) { if ((object)asset == null) return; if (asset.Equals(null)) return; if (dictionary.ContainsKey(asset)) return; if(isModuleCopy) { dictionary.Add(asset, asset); return; } string assetName = asset.name; string assetPath = AssetDatabase.GetAssetPath(asset); var genericAsset = AssetDatabase.LoadMainAssetAtPath(assetPath); TemplateAsset template = null; switch (genericAsset) { case TemplateCollectionAsset collection: template = collection.Templates.FirstOrDefault(x => x.name.Equals(assetName)); break; case TemplateAsset t: template = t; break; } dictionary.Add(asset, template); } private static TemplateAsset GetTemplate(this Dictionary dictionary, TemplateAsset asset) { if ((object)asset == null) return null; if (asset.Equals(null)) return null; return dictionary.TryGetValue(asset, out TemplateAsset result) ? result : null; } public class ShaderContext { public ModularShader Shader; public Dictionary ActiveEnablers; public Dictionary FreshAssets; public Action PostGeneration; // Captured on the editor thread. Worker generation must not read local asset preferences. public List PreparedModules; public string[] DisabledSections = Array.Empty(); private List _liveUpdateEnablers; public string FilePath; public string VariantFileName; public string VariantName; public string ShaderName; public string PropertiesBlock; public bool AreVariantsHidden; public bool OptimizedShader; public List Materials; public StringBuilder ShaderFile; private List _modules; private List _functions; private List _reorderedFunctions; private Dictionary _modulesByFunctions; public string Guid; public List Modules => _modules; public void ReleaseGeneratedText() { ShaderFile = null; _functions = null; _reorderedFunctions = null; _modulesByFunctions = null; _liveUpdateEnablers = null; FreshAssets = null; PropertiesBlock = null; ActiveEnablers = null; PreparedModules = null; DisabledSections = null; } // Drop everything not needed once shader files are imported and default textures applied. // Call this after ApplyDefaultTextures has run. public void ReleaseAll() { ReleaseGeneratedText(); _modules = null; Materials = null; PostGeneration = null; } public void GenerateShader(Dictionary duplicatedModules = null) { _modules = PreparedModules ?? FindActiveModules(Shader, ActiveEnablers, duplicatedModules); GetLiveUpdateEnablers(); ShaderFile = new StringBuilder(); VariantName = GetVariantCode(ActiveEnablers); VariantFileName = OptimizedShader ? $"{Shader.Name}{(string.IsNullOrEmpty(VariantName) ? "" : $"-g-{Guid}")}.shader" : $"{Shader.Name}{(string.IsNullOrEmpty(VariantName) ? "" : $"-v{VariantName}")}.shader"; VariantFileName = string.Join("_", VariantFileName.Split(Path.GetInvalidFileNameChars())); if (OptimizedShader) ShaderName = $"Hidden/{Shader.ShaderPath}-g-{Guid}"; else if (AreVariantsHidden && !string.IsNullOrEmpty(VariantName)) ShaderName = $"Hidden/{Shader.ShaderPath}-v{VariantName}"; else ShaderName = $"{Shader.ShaderPath}{VariantName}"; ShaderFile.AppendLine($"Shader \"{ShaderName}\""); ShaderFile.AppendLine("{"); ShaderFile.Append(string.IsNullOrEmpty(PropertiesBlock) ? GetPropertiesBlock(Shader, _modules, FreshAssets, false) : PropertiesBlock); WriteShaderSkeleton(); _functions = new List(); _reorderedFunctions = new List(); _modulesByFunctions = new Dictionary(); foreach (var module in _modules) { _functions.AddRange(module.Functions); foreach (ShaderFunction function in module.Functions) { _modulesByFunctions.Add(function, module); } } WriteVariablesToKeywords(); WriteFunctionCallsToKeywords(); WriteFunctionsToKeywords(); if (!string.IsNullOrWhiteSpace(Shader.CustomEditor)) ShaderFile.AppendLine($"CustomEditor \"{Shader.CustomEditor}\""); ShaderFile.AppendLine("}"); // Unity otherwise scans the whole file for legacy syntax to upgrade on every import ShaderFile.AppendLine("// UNITY_SHADER_NO_UPGRADE"); PostGeneration?.Invoke(ShaderFile, this); RemoveKeywords(); HandleIterators(); string shaderText; if (DisabledSections != null && DisabledSections.Length > 0) { var repeatedIds = new HashSet(_modules.GroupBy(m => m.Id).Where(g => g.Count() > 1).Select(g => g.Key)); shaderText = ShaderSectionFilter.Apply(ShaderFile.ToString(), DisabledSections, _modules.Select((m, i) => new { module = m, index = i }).Where(x => repeatedIds.Contains(x.module.Id)).Select(x => x.index)); } else shaderText = ShaderSectionFilter.RemoveTemplateAnnotations(ShaderFile.ToString()); ShaderFile = CleanupShaderFile(shaderText.Replace("\r\n", "\n")); } private void HandleIterators() { string shader = ShaderFile.ToString(); ShaderFile = new StringBuilder(shader.Length); Dictionary iterators = new Dictionary(); MatchCollection m = Regex.Matches(shader, ITERATOR_NAMING); int startIdx = 0; foreach (Match match in m) { ShaderFile.Append(shader, startIdx, match.Index - startIdx); string idx_id = match.Value; bool iterate = idx_id.Contains("++"); idx_id = idx_id.Substring(1, idx_id.Length - (iterate ? 3 : 1)); if(!iterators.ContainsKey(idx_id)) iterators.Add(idx_id, 0); ShaderFile.Append(iterators[idx_id].ToString()); if(iterate) iterators[idx_id]++; startIdx = match.Index + match.Length; } ShaderFile.Append(shader, startIdx, shader.Length - startIdx); } private void GetLiveUpdateEnablers() { _liveUpdateEnablers = new List(); var staticEnablers = ActiveEnablers.Keys.ToList(); foreach (var property in _modules.SelectMany(x => x.EnableProperties)) { if(property != null && !string.IsNullOrWhiteSpace(property.Name) && !staticEnablers.Contains(property.Name)) _liveUpdateEnablers.Add(property); } _liveUpdateEnablers = _liveUpdateEnablers.Distinct().ToList(); } private void WriteFunctionCallsToKeywords() { foreach (var startKeyword in _functions.Where(x => x.AppendAfter?.StartsWith("#K#") ?? false).Select(x => x.AppendAfter).Distinct()) { var matches = Regex.Matches(ShaderFile.ToString(), $@"{startKeyword}(\s|$)", RegexOptions.Multiline); if (matches.Count == 0) continue; var callSequence = new StringBuilder(); WriteFunctionCallSequence(callSequence, startKeyword); for (int i = matches.Count - 1; i >= 0; i--) ShaderFile.Insert(matches[i].Index, callSequence.ToString()); } } private void WriteShaderSkeleton() { ShaderFile.AppendLine("SubShader"); ShaderFile.AppendLine("{"); ShaderFile.AppendLine(FreshAssets.GetTemplate(Shader.ShaderTemplate).Template); Dictionary moduleByTemplate = new Dictionary(); Dictionary<(string, string), string> convertedKeyword = new Dictionary<(string, string), string>(); int instanceCounter = 0; var document = new KeywordDocument(ShaderFile.ToString()); foreach (var module in _modules) foreach (var template in module.Templates) moduleByTemplate.Add(template, module); foreach (var template in _modules.SelectMany(x => x.Templates).OrderBy(x => x.Queue)) { var freshTemplate = FreshAssets.GetTemplate(template.Template); var module = moduleByTemplate[template]; if (freshTemplate == null) continue; bool hasEnabler = module.EnableProperties.Any(x => x != null && !string.IsNullOrEmpty(x.Name)); bool isFilteredIn = hasEnabler && module.EnableProperties.All(x => (x == null || string.IsNullOrEmpty(x.Name)) || ActiveEnablers.TryGetValue(x.Name, out _)); bool needsIf = hasEnabler && !isFilteredIn && !template.NeedsVariant; var tmp = new StringBuilder(); if (!needsIf) { tmp.AppendLine(freshTemplate.Template); } else { string condition = string.Join(" && ", module.EnableProperties .Where(x => (x != null && !string.IsNullOrEmpty(x.Name)) && !ActiveEnablers.TryGetValue(x.Name, out _)) .Select(x => $"{x.Name} == {x.EnableValue}")); tmp.AppendLine($"if({condition})"); tmp.AppendLine("{"); tmp.AppendLine(freshTemplate.Template); tmp.AppendLine("}"); } MatchCollection mki = freshTemplate.Template.Contains("#KI#") ? Regex.Matches(tmp.ToString(), @"#KI#\S*", RegexOptions.Multiline) : null; for (int i = (mki?.Count ?? 0) - 1; i >= 0; i--) { string newKeyword; if (convertedKeyword.TryGetValue((module.Id, mki[i].Value), out string replacedKeyword)) { newKeyword = replacedKeyword; } else { newKeyword = $"{mki[i].Value}{instanceCounter++}"; convertedKeyword.Add((module.Id, mki[i].Value), newKeyword); } tmp.Replace(mki[i].Value, newKeyword); } // Temporary provenance survives nested #K# insertion, then is removed before // writing the shader. Indices refer to the full expanded list, never a filtered list. if (DisabledSections != null && DisabledSections.Length > 0) { int moduleIndex = _modules.IndexOf(module); tmp.Insert(0, ShaderSectionFilter.BeginModule(moduleIndex)); tmp.Append(ShaderSectionFilter.EndModule(moduleIndex)); } var fragment = KeywordDocument.Parse(tmp.ToString()); foreach (var keyword in template.Keywords.Count == 0 ? new[] { MSSConstants.DEFAULT_CODE_KEYWORD } : template.Keywords.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()) { document.InsertBefore($"#K#{keyword}", fragment); if (convertedKeyword.TryGetValue((module.Id, $@"#KI#{keyword}"), out string replacedKeyword)) document.InsertBefore(replacedKeyword, fragment); } } ShaderFile = document.Build(); ShaderFile.AppendLine("}"); } private void WriteVariablesToKeywords() { var variableDeclarations = new Dictionary>(); foreach (ShaderFunction function in _functions) { if (function.VariableKeywords.Count > 0) { foreach (string keyword in function.VariableKeywords) { if (!variableDeclarations.ContainsKey(keyword)) variableDeclarations.Add(keyword, new List()); foreach (Variable variable in function.UsedVariables) variableDeclarations[keyword].Add(variable); } } else { if (!variableDeclarations.ContainsKey(MSSConstants.DEFAULT_VARIABLES_KEYWORD)) variableDeclarations.Add(MSSConstants.DEFAULT_VARIABLES_KEYWORD, new List()); foreach (Variable variable in function.UsedVariables) variableDeclarations[MSSConstants.DEFAULT_VARIABLES_KEYWORD].Add(variable); } } foreach (var declaration in variableDeclarations) { declaration.Value.AddRange(_liveUpdateEnablers.Select(x => x.ToVariable())); var decCode = string.Join("\n", declaration.Value.Distinct().OrderBy(x => x.Type).Select(x => x.GetDefinition())) + "\n\n"; MatchCollection m = Regex.Matches(ShaderFile.ToString(), $@"#K#{declaration.Key}\s", RegexOptions.Multiline); for (int i = m.Count - 1; i >= 0; i--) ShaderFile.Insert(m[i].Index, decCode); } } private void WriteFunctionsToKeywords() { var keywordedCode = new Dictionary)>(); foreach (ShaderFunction function in _reorderedFunctions) { var freshAsset = FreshAssets.GetTemplate(function.ShaderFunctionCode); if (function.CodeKeywords.Count > 0) { foreach (string keyword in function.CodeKeywords) { if (!keywordedCode.ContainsKey(keyword)) keywordedCode.Add(keyword, (new StringBuilder(), new List())); if (freshAsset == null) continue; (StringBuilder builder, List assets) = keywordedCode[keyword]; if (assets.Contains(freshAsset)) continue; builder.AppendLine(freshAsset.Template); assets.Add(freshAsset); } } else { if (!keywordedCode.ContainsKey(MSSConstants.DEFAULT_CODE_KEYWORD)) keywordedCode.Add(MSSConstants.DEFAULT_CODE_KEYWORD, (new StringBuilder(), new List())); if (freshAsset == null) continue; (StringBuilder builder, List assets) = keywordedCode[MSSConstants.DEFAULT_CODE_KEYWORD]; if (assets.Contains(freshAsset)) continue; builder.AppendLine(freshAsset.Template); assets.Add(freshAsset); } } foreach (var code in keywordedCode) { MatchCollection m = Regex.Matches(ShaderFile.ToString(), $@"#K#{code.Key}\s", RegexOptions.Multiline); for (int i = m.Count - 1; i >= 0; i--) ShaderFile.Insert(m[i].Index, code.Value.Item1.ToString()); } } private void WriteFunctionCallSequence(StringBuilder callSequence, string appendAfter) { foreach (var function in _functions.Where(x => x.AppendAfter.Equals(appendAfter)).OrderBy(x => x.Queue)) { _reorderedFunctions.Add(function); ShaderModule module = _modulesByFunctions[function]; bool hasEnabler = module.EnableProperties.Any(x => x != null && !string.IsNullOrEmpty(x.Name)); bool isFilteredIn = hasEnabler && module.EnableProperties.All(x => (x == null || string.IsNullOrEmpty(x.Name)) || ActiveEnablers.TryGetValue(x.Name, out _)); bool needsIf = hasEnabler && !isFilteredIn; if (needsIf) { string condition = string.Join(" && ", module.EnableProperties .Where(x => (x != null && !string.IsNullOrEmpty(x.Name)) && !ActiveEnablers.TryGetValue(x.Name, out _)) .Select(x => $"{x.Name} == {x.EnableValue}")); callSequence.AppendLine($"if({condition})"); callSequence.AppendLine("{"); } callSequence.AppendLine($"{function.Name}();"); WriteFunctionCallSequence(callSequence, function.Name); if (needsIf) callSequence.AppendLine("}"); } } private void RemoveKeywords() { string source = ShaderFile.ToString(); var output = new StringBuilder(source.Length); int position = 0, marker; while ((marker = source.IndexOf("#K#", position, StringComparison.Ordinal)) >= 0) { output.Append(source, position, marker - position); position = marker + 3; while (position < source.Length && !char.IsWhiteSpace(source[position])) position++; } ShaderFile = output.Append(source, position, source.Length - position); } private static bool CheckPropertyBlockLine(StringBuilder builder, StringReader reader, string line, ref int tabs, ref bool deleteEmptyLine) { string ln = null; line = line.Trim(); if (string.IsNullOrEmpty(line)) { if (deleteEmptyLine) return false; deleteEmptyLine = true; } else { deleteEmptyLine = false; } if (line.StartsWith("}") && (ln = reader.ReadLine()) != null && ln.Trim().StartsWith("SubShader")) tabs--; builder.AppendLineTabbed(tabs, line); if (!string.IsNullOrWhiteSpace(ln)) if (CheckPropertyBlockLine(builder, reader, ln, ref tabs, ref deleteEmptyLine)) return true; if (line.StartsWith("}") && ln != null && ln.Trim().StartsWith("SubShader")) return true; return false; } private static StringBuilder CleanupShaderFile(string shaderVariant) { var finalFile = new StringBuilder(shaderVariant.Length + shaderVariant.Length / 8); using (var sr = new StringReader(shaderVariant)) { string line; int tabs = 0; bool deleteEmptyLine = false; while ((line = sr.ReadLine()) != null) { line = line.Trim(); if (string.IsNullOrEmpty(line)) { if (deleteEmptyLine) continue; deleteEmptyLine = true; } else { deleteEmptyLine = false; } if (line.StartsWith("Properties")) { finalFile.AppendLineTabbed(tabs, line); string ln = sr.ReadLine()?.Trim(); // When the previous line is the one containing "Properties" we always know finalFile.AppendLineTabbed(tabs, ln); // that the next line is "{" so we just write it down before increasing the tabs tabs++; while ((ln = sr.ReadLine()) != null) // we should be escaping this loop way before actually meeting the condition, but you never know { if (CheckPropertyBlockLine(finalFile, sr, ln, ref tabs, ref deleteEmptyLine)) break; } continue; } int openingId = line.IndexOf('{'); int closingId = line.IndexOf('}'); bool hasOpening = openingId != -1; bool hasClosing = closingId != -1; if (!line.StartsWith("//", StringComparison.Ordinal) && hasClosing && !hasOpening) tabs--; if (hasClosing && hasOpening && closingId < openingId) { finalFile.AppendLineTabbed(tabs - 1, line); } else { finalFile.AppendLineTabbed(tabs, line); } if (!line.StartsWith("//", StringComparison.Ordinal) && hasOpening && !hasClosing) tabs++; } } return finalFile; } } // The file split at its #K# and #KI# markers, so inserting before a marker never rescans or copies the file. private sealed class KeywordDocument { public sealed class Fragment { public string Source; public readonly List<(int start, int length)> Text = new List<(int, int)>(); public readonly List Markers = new List(); } private sealed class Marker { public string Name; public List Inserted; } private sealed class Instance { public Fragment Source; public Marker[] Markers; } private readonly Dictionary> _markers = new Dictionary>(); private readonly Instance _root; public KeywordDocument(string text) => _root = Instantiate(Parse(text)); public static Fragment Parse(string text) { var fragment = new Fragment { Source = text }; int start = 0, i = 0; while ((i = text.IndexOf("#K", i, StringComparison.Ordinal)) >= 0) { int length = i + 2 < text.Length && text[i + 2] == '#' ? 3 : i + 3 < text.Length && text[i + 2] == 'I' && text[i + 3] == '#' ? 4 : 0; if (length == 0) { i += 2; continue; } int end = i + length; while (end < text.Length && !char.IsWhiteSpace(text[end])) end++; fragment.Text.Add((start, i - start)); fragment.Markers.Add(text.Substring(i, end - i)); start = i = end; } fragment.Text.Add((start, text.Length - start)); return fragment; } // Copies inserted by this call don't receive the fragment again. public void InsertBefore(string marker, Fragment fragment) { if (!_markers.TryGetValue(marker, out var targets)) return; foreach (var target in targets.ToArray()) (target.Inserted ??= new List()).Add(Instantiate(fragment)); } private Instance Instantiate(Fragment fragment) { var instance = new Instance { Source = fragment, Markers = new Marker[fragment.Markers.Count] }; for (int i = 0; i < instance.Markers.Length; i++) { var marker = instance.Markers[i] = new Marker { Name = fragment.Markers[i] }; if (!_markers.TryGetValue(marker.Name, out var markers)) _markers.Add(marker.Name, markers = new List()); markers.Add(marker); } return instance; } // #KI# markers are left out: they only mark where a module's own templates go. public StringBuilder Build() { var builder = new StringBuilder(Length(_root) + 1024); Write(_root, builder); return builder; } private static bool IsWritten(Marker marker) => !marker.Name.StartsWith("#KI#", StringComparison.Ordinal); private static int Length(Instance instance) { int length = 0; foreach (var (_, textLength) in instance.Source.Text) length += textLength; foreach (var marker in instance.Markers) { if (marker.Inserted != null) foreach (var inserted in marker.Inserted) length += Length(inserted); if (IsWritten(marker)) length += marker.Name.Length; } return length; } private static void Write(Instance instance, StringBuilder builder) { string source = instance.Source.Source; for (int i = 0; i < instance.Markers.Length; i++) { var (start, length) = instance.Source.Text[i]; builder.Append(source, start, length); if (instance.Markers[i].Inserted != null) foreach (var inserted in instance.Markers[i].Inserted) Write(inserted, builder); if (IsWritten(instance.Markers[i])) builder.Append(instance.Markers[i].Name); } var (lastStart, lastLength) = instance.Source.Text[instance.Markers.Length]; builder.Append(source, lastStart, lastLength); } } private static string GetPropertiesBlock(ModularShader shader, List modules, Dictionary freshAssets, bool includeEnablers = true) { var block = new StringBuilder(); block.AppendLine("Properties"); block.AppendLine("{"); if (shader.UseTemplatesForProperties) { var freshTemplate = freshAssets.GetTemplate(shader.ShaderPropertiesTemplate); if (freshTemplate != null) block.AppendLine(freshTemplate.Template); block.AppendLine($"#K#{MSSConstants.TEMPLATE_PROPERTIES_KEYWORD}"); } else { List properties = new List(); properties.AddRange(shader.Properties.Where(x => !string.IsNullOrWhiteSpace(x.Name) || x.Attributes.Count > 0)); foreach (var module in modules.Where(x => x != null)) { properties.AddRange(module.Properties.Where(x => !string.IsNullOrWhiteSpace(x.Name) || x.Attributes.Count > 0)); if (module.EnableProperties.Count > 0 && includeEnablers) properties.AddRange(module.EnableProperties.Where(x => !string.IsNullOrWhiteSpace(x.Name))); } foreach (var prop in properties.Distinct()) { if (string.IsNullOrWhiteSpace(prop.Type) && !string.IsNullOrWhiteSpace(prop.Name)) { prop.Type = "Float"; prop.DefaultValue = "0.0"; } string attributes = prop.Attributes.Count == 0 ? "" : $"[{string.Join("][", prop.Attributes)}]"; block.AppendLine(string.IsNullOrWhiteSpace(prop.Name) ? attributes : $"{attributes} {prop.Name}(\"{prop.DisplayName}\", {prop.Type}) = {prop.DefaultValue}"); } } block.AppendLine("}"); return block.ToString(); } public static void ApplyDefaultTextures(List contexts) { // Unity reparses every shader with errors after each import, so import once for all of them. AssetDatabase.StartAssetEditing(); try { foreach (var context in contexts) { string path = $"{context.FilePath}/" + context.VariantFileName; var importedShader = AssetImporter.GetAtPath(path) as ShaderImporter; var customTextures = context.Modules.SelectMany(x => x.Properties).Where(x => x.DefaultTextureAsset != null).ToList(); customTextures.AddRange(context.Shader.Properties.Where(x => x.DefaultTextureAsset != null).ToList()); if (importedShader != null) { string[] names = customTextures.Select(x => x.Name).ToArray(); Texture[] textures = customTextures.Select(x => x.DefaultTextureAsset).ToArray(); var serializedImporter = new SerializedObject(importedShader); if (HasTextures(serializedImporter, "m_DefaultTextures", names, textures) && HasTextures(serializedImporter, "m_NonModifiableTextures", names, textures)) continue; importedShader.SetDefaultTextures(names, textures); importedShader.SetNonModifiableTextures(names, textures); } AssetDatabase.ImportAsset(path); } } finally { AssetDatabase.StopAssetEditing(); } } private static bool HasTextures(SerializedObject importer, string listName, string[] names, Texture[] textures) { var list = importer.FindProperty(listName); if (list == null || !list.isArray || list.arraySize != names.Length) return false; for (int i = 0; i < names.Length; i++) { var entry = list.GetArrayElementAtIndex(i); if (entry.FindPropertyRelative("first")?.stringValue != names[i] || entry.FindPropertyRelative("second")?.objectReferenceValue != textures[i]) return false; } return true; } public static List FindAllModules(ModularShader shader) { List modules = new List(); if (shader == null) return modules; HashSet collectionIDs = new HashSet(); FindModules(shader.BaseModules.Where(x => x != null), modules, collectionIDs); FindModules(shader.AdditionalModules.Where(x => x != null), modules, collectionIDs); return modules; } public static void FindModules(IEnumerable modules, List output, HashSet collectionIDs) { foreach (var module in modules) { if (module == null) continue; switch (module) { case ModuleCollection collection: if (collectionIDs.Contains(collection.Id)) continue; collectionIDs.Add(collection.Id); FindModules(collection.Modules, output, collectionIDs); break; default: output.Add(module); break; } } } struct IdReplacement { public string IndexKeyword; public int StartIndex; public bool SkipOriginal; } // Instances are built from the group's first module alone, so groups with the same first module and size can share them. static Dictionary GenerateDuplicates(List modules, Dictionary<(ShaderModule, int), ShaderModule[]> cache = null) { Dictionary generatedDuplicates = new Dictionary(); var duplicates = modules.GroupBy(x => x.Id).Where(x => x.Count() > 1 || x.First().ForceDuplicateLogic).Select(x => x.Key).ToList(); foreach (var duplicateId in duplicates) { var dupeIndices = modules.Select((x, i) => (x, i)).Where(x => x.x.Id.Equals(duplicateId)).Select(x => x.i).ToList(); var cacheKey = (modules[dupeIndices[0]], dupeIndices.Count); if (cache != null && cache.TryGetValue(cacheKey, out var cachedInstances)) { generatedDuplicates.Add(duplicateId, cachedInstances); continue; } ShaderModule[] moduleInstances = new ShaderModule[dupeIndices.Count]; moduleInstances[0] = modules[dupeIndices[0]].DeepCopy(); string allCode = string.Join("\n", moduleInstances[0].Templates.Select(x => x.Template.Template)); if (moduleInstances.Length > 1) { // Remove structs from duplicate code moduleInstances[1] = moduleInstances[0].DeepCopy(); foreach (var template in moduleInstances[1].Templates) template.Template.Template = RemoveStructs(template.Template.Template); } // Code that needs to differ between first and other instances string[] codeSectionKeywords = { "", "", "", "" }; if(moduleInstances.Length == 1) RemoveCodeSections(moduleInstances[0], new bool[] { true, false, true, true }); else RemoveCodeSections(moduleInstances[0], new bool[] { true, false, false, false }); if (moduleInstances.Length == 2) { RemoveCodeSections(moduleInstances[1], new bool[] { false, true, true, true }); } else if (moduleInstances.Length > 2) { moduleInstances[moduleInstances.Length - 1] = moduleInstances[1].DeepCopy(); RemoveCodeSections(moduleInstances[1], new bool[] { false, true, true, false }); RemoveCodeSections(moduleInstances[moduleInstances.Length - 1], new bool[] { false, true, false, true }); } for (int i = 2; i < moduleInstances.Length - 1; i++) moduleInstances[i] = moduleInstances[1].DeepCopy(); string[] automaticSuffixes = new string[moduleInstances.Length]; automaticSuffixes[0] = ""; for (int i = 1; i < moduleInstances.Length; i++) automaticSuffixes[i] = $"__{i}"; void RemoveCodeSections(ShaderModule module, bool[] includeSection) { foreach (var template in module.Templates) { string code = template.Template.Template; StringBuilder sb = new StringBuilder(); int codeIndex = 0; do { int msIncludeIndex = code.IndexOf("", msIncludeIndex, StringComparison.OrdinalIgnoreCase); if (endIndex == -1) break; string sectionName = code.Substring(msIncludeIndex, endIndex - msIncludeIndex + 1); int sectionIndex = Array.IndexOf(codeSectionKeywords, sectionName); // Find section start and end int sectionStart = code.IndexOf("{", endIndex + 1, StringComparison.OrdinalIgnoreCase); int sectionEnd = sectionStart; int depth = 0; while (sectionEnd < code.Length) { if (code[sectionEnd] == '{') depth++; else if (code[sectionEnd] == '}') depth--; if (depth == 0) break; sectionEnd++; } if (depth != 0) break; // Unmatched braces, exit loop // include previous code sb.Append(code.Substring(codeIndex, msIncludeIndex - codeIndex)); codeIndex = sectionEnd + 1; // Move past the closing brace // include or remove code section if (sectionIndex != -1 && includeSection[sectionIndex]) { sb.Append(code.Substring(sectionStart + 1, sectionEnd - sectionStart - 1)); } else { // Remove code section if(code[codeIndex] == '\r') codeIndex += 2; if(code[sectionEnd + 1] == '\n') codeIndex += 1; } }while(true); sb.Append(code.Substring(codeIndex)); template.Template.Template = sb.ToString(); } } string RemoveStructs(string code) { int i = 0; while((i = code.IndexOf("struct", i + 1, StringComparison.Ordinal)) != -1) { int depth = 0; int checkJ = code.IndexOf(';', i); int j = code.IndexOf('{', i); // check if struct definition or use if(checkJ < j || j == -1) continue; while(j < code.Length) { if(code[j] == '{') depth++; else if(code[j] == '}') depth--; if(depth == 0) break; j++; } // find line end while(j < code.Length && code[j] != '\n') j++; if(j < code.Length) { code = code.Remove(i, j - i + 1); } } return code; } // Find all property declarations MatchCollection matches = Regex.Matches(allCode, @"\w+(?=\s*\("")"); IEnumerable properties = matches.Cast().Select(x => x.Value).Distinct(); matches = Regex.Matches(allCode, @"\w+(?=\s*\("".*2D)"); IEnumerable textures = matches.Cast().Select(x => x.Value).Distinct(); matches = Regex.Matches(allCode, @"^( |\t)*(inline +)?\w+ +\w+(?=\s*\((\w|\s|,)*\)\s*{)", RegexOptions.Multiline); IEnumerable functionNames = matches.Cast().Select(x => x.Value.Split(' ').Last()).Distinct(); matches = Regex.Matches(allCode, @"(?<=#pragma shader_feature_local )\w+"); // Local Keywords IEnumerable keywords = matches.Cast().Select(x => x.Value).Distinct(); matches = Regex.Matches(allCode, @"(?<=#pragma shader_feature )\w+"); // Global Keywords keywords = keywords.Concat(matches.Cast().Select(x => x.Value).Distinct()); matches = Regex.Matches(allCode, @"PROP_\w+"); // Shader Optimizer Texture Keywords keywords = keywords.Concat(matches.Cast().Select(x => x.Value).Distinct()); matches = Regex.Matches(allCode, @"^( |\t)*\w+\s+\w+(?=\s*(=|;))(?![^;]*;\/\/)", RegexOptions.Multiline); IEnumerable localVariables = matches.Cast().Select(x => x.Value.Split(' ').Last()).Distinct(); localVariables = localVariables.Where(x => !properties.Contains(x) && !textures.Contains(x) && !functionNames.Contains(x) && !keywords.Contains(x)); MatchCollection Find(string input, string keyword) { return Regex.Matches(input, @"(? replacer) { for(int i=1; i < moduleInstances.Length; i++) { ReplaceInModule(moduleInstances[i], matchPhrase, replacer(i, keywordIn)); } } // -> start at 0 // -> start at 1 // -> start at 0, replace original with empty // -> start at 1, replace original with empty IdReplacement[] idReplacementTypes = { new IdReplacement() { IndexKeyword = "__mID__", StartIndex = 0, SkipOriginal = false }, new IdReplacement() { IndexKeyword = "__mID1__", StartIndex = 1, SkipOriginal = false }, new IdReplacement() { IndexKeyword = "__mIDx__", StartIndex = 0, SkipOriginal = true }, new IdReplacement() { IndexKeyword = "__mID1x__", StartIndex = 1, SkipOriginal = true } }; void MakeUnique(IEnumerable inputKeywords, Func keywordTransformer, Func replacer) { foreach(var keywordIn in inputKeywords) { string matchPhrase = keywordTransformer == null ? keywordIn : keywordTransformer(keywordIn); bool hasSpecifiedIdentifier = false; foreach (IdReplacement idReplacement in idReplacementTypes) { if (matchPhrase.IndexOf(idReplacement.IndexKeyword, StringComparison.OrdinalIgnoreCase) != -1) { ReplaceCustomKeywordId(matchPhrase, idReplacement); hasSpecifiedIdentifier = true; break; } } if(!hasSpecifiedIdentifier) { ReplaceAutomaticKeywordId(matchPhrase, keywordIn, replacer); } } } MakeUnique(properties, null, (i, x) => x + automaticSuffixes[i]); MakeUnique(textures, x => x + "_ST", (i, x) => x + automaticSuffixes[i] + "_ST"); MakeUnique(textures, x => x + "_TexelSize", (i, x) => x + automaticSuffixes[i] + "_TexelSize"); // I think this is already covered by the 'keywords' replacement // MakeUnique(textures, x => "PROP" + x.ToUpper(), (i, x) => "PROP" + x.ToUpper() + automaticSuffixes[i].ToUpper()); MakeUnique(functionNames, null, (i, x) => x + automaticSuffixes[i]); MakeUnique(keywords, null, (i, x) => x + automaticSuffixes[i].ToUpper()); MakeUnique(localVariables, null, (i, x) => x + automaticSuffixes[i]); // StringBuilders Dictionary stringBuilders = new Dictionary(); foreach(ShaderModule module in moduleInstances) { foreach(var template in module.Templates) { int index=0; while((index = template.Template.Template.IndexOf("", index, StringComparison.OrdinalIgnoreCase); int lineEnd = template.Template.Template.IndexOf("\n", index, StringComparison.OrdinalIgnoreCase); string id = template.Template.Template.Substring(index + 19, idEnd - index - 19); string data = template.Template.Template.Substring(idEnd + 1, lineEnd - idEnd - 2).TrimEnd(); if(stringBuilders.TryGetValue(id, out StringBuilder sb)) { sb.Append(data); } else { sb = new StringBuilder(data); stringBuilders.Add(id, sb); } template.Template.Template = template.Template.Template.Remove(index, lineEnd - index + 1); } } } // String Writers foreach(var sb in stringBuilders) { foreach(ShaderModule module in moduleInstances) { foreach(var template in module.Templates) { int index=-1; while((index = template.Template.Template.IndexOf($"", index + 1, StringComparison.OrdinalIgnoreCase)) != -1) { template.Template.Template = template.Template.Template.Remove(index, sb.Key.Length + 19).Insert(index, sb.Value.ToString()); } } } } generatedDuplicates.Add(duplicateId, moduleInstances); if (cache != null) cache[cacheKey] = moduleInstances; } return generatedDuplicates; } static void ApplyDupliactes(List modules, Dictionary duplicates) { foreach (var duplicate in duplicates) { var dupeIndices = modules.Select((x, i) => (x, i)).Where(x => x.x.Id.Equals(duplicate.Key)).Select(x => x.i).ToList(); for (int i = 0; i < dupeIndices.Count; i++) { modules[dupeIndices[i]] = duplicate.Value[i]; } } } public static List FindAllProperties(ModularShader shader) { List properties = new List(); if (shader == null) return properties; properties.AddRange(shader.Properties.Where(x => !string.IsNullOrWhiteSpace(x.Name) || x.Attributes.Count == 0)); foreach (var module in shader.BaseModules.Where(x => x != null)) { properties.AddRange(module.Properties.Where(x => !string.IsNullOrWhiteSpace(x.Name) || x.Attributes.Count == 0)); if (module.EnableProperties.Count > 0) properties.AddRange(module.EnableProperties.Where(x => !string.IsNullOrWhiteSpace(x.Name))); } foreach (var module in shader.AdditionalModules.Where(x => x != null)) { properties.AddRange(module.Properties.Where(x => !string.IsNullOrWhiteSpace(x.Name) || x.Attributes.Count == 0)); if (module.EnableProperties.Count > 0) properties.AddRange(module.EnableProperties.Where(x => !string.IsNullOrWhiteSpace(x.Name))); } return properties.Distinct().ToList(); } public static List FindAllFunctions(ModularShader shader) { var functions = new List(); if (shader == null) return functions; foreach (var module in shader.BaseModules) functions.AddRange(module.Functions); foreach (var module in shader.AdditionalModules) functions.AddRange(module.Functions); return functions; } public static List FindActiveModules(ModularShader shader, Dictionary activeEnablers, Dictionary duplicatedModules) { List modules = new List(); if (shader == null) return modules; HashSet collectionIDs = new HashSet(); FindActiveModules(shader.BaseModules, activeEnablers, modules, collectionIDs, shader, true); FindActiveModules(shader.AdditionalModules, activeEnablers, modules, collectionIDs, shader, false); if(duplicatedModules != null) ApplyDupliactes(modules, duplicatedModules); return modules.Distinct().ToList(); } private static void FindActiveModules(IEnumerable modules, Dictionary activeEnablers, List output, HashSet collectionIDs, ModularShader shader, bool isBaseModules) { var modulesList = modules.ToList(); List shaderToggles = null; if (isBaseModules && shader != null) shaderToggles = ModuleTogglePreferences.GetToggles(shader, modulesList.Count); for (int i = 0; i < modulesList.Count; i++) { var module = modulesList[i]; if (module == null) continue; if (shaderToggles != null && i < shaderToggles.Count && !shaderToggles[i]) continue; if (module is ModuleCollection collection) { if (collectionIDs.Contains(collection.Id)) continue; collectionIDs.Add(collection.Id); var collectionModulesList = collection.Modules.ToList(); var collectionToggles = ModuleTogglePreferences.GetToggles(collection, collectionModulesList.Count); var filteredModules = new List(); for (int j = 0; j < collectionModulesList.Count; j++) { if (j < collectionToggles.Count && !collectionToggles[j]) continue; filteredModules.Add(collectionModulesList[j]); } FindActiveModules(filteredModules, activeEnablers, output, collectionIDs, shader, false); continue; } bool hasEnabler = module.EnableProperties.Any(x => x != null && !string.IsNullOrEmpty(x.Name)); bool hasKey = hasEnabler && module.EnableProperties.Any(x => activeEnablers.TryGetValue(x.Name, out _)); if (!hasEnabler || !hasKey || (module.EnableProperties.All(x => { if (x.Name == null || string.IsNullOrEmpty(x.Name)) return true; if (!activeEnablers.TryGetValue(x.Name, out int value)) return true; return x.EnableValue == value; }))) output.Add(module); } } public static List CheckShaderIssues(ModularShader shader) { List errors = new List(); var modules = FindAllModules(shader); for (int i = 0; i < modules.Count; i++) { var dependencies = new List(modules[i].ModuleDependencies); for (int j = 0; j < modules.Count; j++) { if (modules[j].IncompatibleWith.Any(x => x.Equals(modules[i].Id))) errors.Add($"Module \"{modules[j].Name}\" ({modules[j].Id}) is incompatible with module \"{modules[i].name}\" ({modules[i].Id})."); if (i != j && modules[i].Id.Equals(modules[j].Id) && !modules[i].AllowDuplicates) errors.Add($"Module \"{modules[i].Name}\" ({modules[i].Id}) is duplicate."); if (modules[i] is CibbiExtensions.ModuleCollection) { foreach (ShaderModule module in ((CibbiExtensions.ModuleCollection)modules[i]).Modules) { if (module.Id.Equals(modules[j].Id) && !module.AllowDuplicates) errors.Add($"Module \"{modules[i].Name}\" ({modules[i].Id}) is duplicate in ModuleCollection: {modules[i]?.Name} ({modules[i].Id})"); } } if (dependencies.Contains(modules[j].Id)) dependencies.Remove(modules[j].Id); } foreach (string t in dependencies) errors.Add($"Module \"{modules[i].Name}\" ({modules[i].Id}) has missing dependency id \"{t}\"."); } return errors; } public static List CheckShaderIssues(List modules) { List errors = new List(); for (int i = 0; i < modules.Count; i++) { var dependencies = new List(modules[i].ModuleDependencies); for (int j = 0; j < modules.Count; j++) { if (modules[j].IncompatibleWith.Any(x => x.Equals(modules[i].Id))) errors.Add($"Module \"{modules[j].Name}\" ({modules[j].Id}) is incompatible with module \"{modules[i].name}\" ({modules[i].Id})."); if (i != j && modules[i].Id.Equals(modules[j].Id)) errors.Add($"Module \"{modules[i].Name}\" ({modules[i].Id}) is duplicate."); if (dependencies.Contains(modules[j].Id)) dependencies.Remove(modules[j].Id); } foreach (string t in dependencies) errors.Add($"Module \"{modules[i].Name}\" ({modules[i].Id}) has missing dependency id \"{t}\"."); } return errors; } } }