using System.Collections.Concurrent; using System.Globalization; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using EvilEngine.Conversion; using EvilEngine.Formats; using EvilEngine.Formats.Materials; using EvilEngine.Mounts; namespace EvilEngine.Host.Tests; public sealed class GarrysModMaterialOracleTests(ITestOutputHelper output) { private static readonly string Installed = typeof(GarrysModMaterialOracleTests).Assembly .GetCustomAttributes() .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!; private static readonly string[] Flags = [ "debug", "no_debug_override", "no_draw", "use_in_fillrate_mode", "vertexcolor", "vertexalpha", "selfillum", "additive", "alphatest", "multipass", "znearer", "model", "flat", "nocull", "nofog", "ignorez", "decal", "envmapsphere", "noalphamod", "envmapcameraspace", "basealphaenvmapmask", "translucent", "normalmapalphaenvmapmask", "needs_software_skinning", "opaquetexture", "envmapmode", "suppress_decals", "halflambert", "wireframe", "allowalphatocoverage", "ignore_alpha_modulation" ]; private static readonly HashSet Consumed = new(StringComparer.OrdinalIgnoreCase) { "no_fullbright", "nodecal" }; private static string Show(MaterialValue value) { return value switch { MaterialValue.Boolean flag => flag.Value ? "true" : "false", MaterialValue.Integer integer => integer.Value.ToString(CultureInfo.InvariantCulture), MaterialValue.Number number => number.Value.ToString("R", CultureInfo.InvariantCulture), MaterialValue.Vector vector => $"[{string.Join(" ", vector.Values.Select(component => component.ToString("R", CultureInfo.InvariantCulture)))}]", MaterialValue.Text text => $"\"{text.Value}\"", _ => value.GetType().Name }; } private static Dictionary ReadDump(string path) { static string Unescape(string text) { return Regex.Replace(text, @"\\(\d{3})", match => ((char)int.Parse(match.Groups[1].Value)).ToString()); } var materials = new Dictionary(StringComparer.OrdinalIgnoreCase); Dumped? current = null; foreach (var line in File.ReadLines(path, Encoding.UTF8)) { var parts = line.Split('\t'); if (line.StartsWith('@')) { current = new Dumped(Unescape(parts[1]), parts[2] == "true", new Dictionary(StringComparer.OrdinalIgnoreCase)); materials[Unescape(parts[0][1..])] = current; } else if (current is not null && parts.Length == 2) { current.Variables[Unescape(parts[0])] = Unescape(parts[1]); } } return materials; } private static double[] Numbers(string text) { return text.Split(' ', StringSplitOptions.RemoveEmptyEntries) .Select(word => double.Parse(word, CultureInfo.InvariantCulture)).ToArray(); } private static bool Close(double a, double b) { return Math.Abs(a - b) <= 1e-5 * Math.Max(1, Math.Abs(b)); } private static double Gamma(double value) { return value < 0 ? 0 : value >= 0.95 ? 1 : Math.Pow(MathF.Round((float)value * 255f, MidpointRounding.ToEven) / 255.0, 2.2); } private static string? Disagreement(MaterialValue ours, string theirs) { var kind = theirs.Length > 1 ? theirs[..2] : theirs; var value = theirs.Length > 2 ? theirs[2..] : ""; switch (ours) { case MaterialValue.Boolean flag when kind == "n:": return Close(Numbers(value)[0], flag.Value ? 1 : 0) ? null : "bool"; case MaterialValue.Integer integer when kind == "n:": return Close(Numbers(value)[0], integer.Value) ? null : "integer"; case MaterialValue.Number number when kind == "n:": return Close(Numbers(value)[0], number.Value) ? null : "number"; case MaterialValue.Vector vector when kind == "v:": var three = Numbers(value); return vector.Values.Take(3).Select((component, i) => Math.Abs(three[i] - Gamma(component)) < 1e-4) .All(same => same) ? null : "vector"; case MaterialValue.Vector vector when kind == "n:": return Close(Numbers(value)[0], vector.Values[0]) ? null : "vector as number"; case MaterialValue.Boolean or MaterialValue.Integer or MaterialValue.Number when kind == "s:": var expected = ours switch { MaterialValue.Boolean b => b.Value ? 1 : 0, MaterialValue.Integer i => i.Value, MaterialValue.Number n => n.Value, _ => 0 }; return double.TryParse(value, CultureInfo.InvariantCulture, out var parsed) && Close(parsed, expected) ? null : "number held as text"; case MaterialValue.Text text when kind == "s:": return text.Value == value ? null : "text"; case MaterialValue.Text when kind == "n:": return "text a shader turns into a number"; case MaterialValue.Table: return kind == "m:" ? null : "transform"; default: return $"{ours.GetType().Name} against {kind}"; } } [Fact] public void MatchesWhatGarrysModHoldsForEveryMaterial() { var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD"); var dump = Environment.GetEnvironmentVariable("EVIL_GMOD_MATERIALS"); Assert.SkipWhen(gmod is null || dump is null, "Set EVIL_GMOD to a Garry's Mod install and EVIL_GMOD_MATERIALS to its material dumps, split by the path separator."); var dumped = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var part in dump!.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) foreach (var (name, material) in ReadDump(part)) dumped[name] = material; var host = new EngineHost(); host.Adapters.LoadAll([Installed]); var mount = host.Mounts.Open(Assert.Single(host.Mounts.Probe(gmod!))); host.Conversion.AddNamespace(ContentNamespace.For(mount)); var compared = 0; var kinds = new ConcurrentDictionary(); var samples = new ConcurrentDictionary>(); var shaders = new ConcurrentDictionary(); var every = new ConcurrentBag(); void Note(string kind, string sample) { every.Add($"{kind}\t{sample}"); kinds.AddOrUpdate(kind, 1, (_, count) => count + 1); var bag = samples.GetOrAdd(kind, _ => []); if (bag.Count < 40) bag.Add(sample); } var unmounted = mount.Layers .Where(layer => layer.Name.StartsWith("workshop/", StringComparison.Ordinal)) .Where(layer => layer.Files.EnumerateAll().Any(entry => entry.Path.Value.StartsWith("materials/", StringComparison.OrdinalIgnoreCase) && entry.Path.Value.EndsWith(".vmt", StringComparison.OrdinalIgnoreCase) && !dumped.ContainsKey(entry.Path.Value["materials/".Length..^4]))) .Select(layer => layer.Name) .ToHashSet(); output.WriteLine($"Workshop items with no materials in GMod's dump: {string.Join(", ", unmounted.Order())}"); Parallel.ForEach(dumped, pair => { var (name, theirs) = pair; if (mount.Origin(VirtualPath.Parse($"materials/{name}.vmt")) is { } origin && unmounted.Contains(origin.Layer.Name)) { Note("from a workshop item missing from GMod's dump", name); return; } var result = host.Conversion.Get(ContentKind.Material, ContentId.Create("gmod", $"materials/{name}")); if (!result.Succeeded) { Note( result.Diagnostics[^1].Contains("No converter") ? "not in this mount" : theirs.Error ? "fails here, error in GMod" : "fails here, loads in GMod", $"{name}: {result.Diagnostics[^1]}"); return; } var ours = MaterialText.Read(Encoding.UTF8.GetString(result.Content!.Data.Span), name); if (theirs.Error) { Note( name.Contains('.') ? "a name with a dot, which GMod cuts at the dot and can't load" : "GMod couldn't load it", name); return; } if (ours.Shader.Name == "shaders/subrect") { Note("subrect, which GMod turns into the material it names", name); return; } Interlocked.Increment(ref compared); shaders.AddOrUpdate($"{ours.Shader.Name[8..]} → {theirs.Shader.ToLowerInvariant()}", 1, (_, count) => count + 1); var flags = theirs.Variables.TryGetValue("$flags", out var bits) && bits.StartsWith("n:") ? (long)Numbers(bits[2..])[0] : 0; var defined = theirs.Variables.TryGetValue("$flags_defined", out var mask) && mask.StartsWith("n:") ? (long)Numbers(mask[2..])[0] : 0; foreach (var (key, value) in ours.Parameters) { var bit = Array.IndexOf(Flags, key); if (bit >= 0) { var set = ((flags >> bit) & 1) == 1; if (value is MaterialValue.Boolean flag && flag.Value != set) Note( set ? "flag GMod's shader sets" : ((defined >> bit) & 1) == 1 ? "flag GMod's shader clears" : "flag we set that GMod doesn't", $"{name}: ${key} ours {Show(value)}, GMod $flags bit {(set ? 1 : 0)}, defined {(defined >> bit) & 1}"); continue; } if (!theirs.Variables.TryGetValue($"${key}", out var held)) Note( Consumed.Contains(key) ? "kept, though GMod's material system takes it into its own flags" : "parameter GMod doesn't hold", $"{name}: ${key} = {Show(value)}"); else if (Disagreement(value, held) is { } kind) Note(kind.StartsWith("text a shader") ? kind : $"{kind} differs", $"{name}: ${key} ours {Show(value)}, GMod {held}, shader {theirs.Shader}"); } foreach (var (key, id) in ours.Textures) if (!theirs.Variables.TryGetValue($"${key}", out var held)) { Note( id == ContentId.Parse("evil:targets/probe") ? "env_cubemap, which GMod binds as it draws" : "texture GMod's shader leaves out", $"{name}: ${key} = {id}"); } else if (!held.StartsWith("t:") && !held.StartsWith("s:")) { Note("texture GMod holds as something else", $"{name}: ${key} ours {id}, GMod {held}"); } else { var texture = held[2..].Split('|')[0].Replace('\\', '/').ToLowerInvariant(); var expected = id.Namespace == "evil" ? null : id.Name["materials/".Length..]; if (texture == "error") Note("GMod draws its error texture", $"{name}: ${key} ours {id}"); else if (expected is not null && texture != expected && texture != $"{expected}.hdr" && key == "startexture" && ours.Games.ContainsKey("gmod")) Note("written by GMod's SkyPaint proxy as it draws", $"{name}: ${key} ours {id}, GMod {held}"); else if (expected is not null && texture != expected && texture != $"{expected}.hdr" && mount.Origin(VirtualPath.Parse($"{id.Name}.vtf")) is { Layer.Name: var layer } && layer.StartsWith("workshop/", StringComparison.Ordinal)) Note("a texture only in a workshop GMA, which the oracle run unpacked no textures from", $"{name}: ${key} ours {id}, GMod {held}"); else if (expected is not null && expected.StartsWith("engine/defaultcubemap", StringComparison.Ordinal) && texture != expected && texture != $"{expected}.hdr") Note("a cube map in depot content this mount doesn't layer yet", $"{name}: ${key} ours {id}, GMod {held}"); else if (expected is not null && texture != expected && texture != $"{expected}.hdr") Note("texture differs", $"{name}: ${key} ours {id}, GMod {held}"); } if (ours.Games.TryGetValue("gmod", out var block) && block.Entries.TryGetValue("unprefixed", out var extra) && extra is MaterialValue.Table unprefixed) foreach (var (key, value) in unprefixed.Entries) if (!theirs.Variables.TryGetValue(key, out var held)) Note("key without a $ GMod doesn't hold", $"{name}: {key} = {Show(value)}"); else if (Disagreement(value, held) is { } kind) Note($"key without a $ differs ({kind})", $"{name}: {key} ours {Show(value)}, GMod {held}"); foreach (var (key, held) in theirs.Variables) { if (!key.StartsWith('$') || !held.StartsWith("t:") || key.Equals("$flashlighttexture", StringComparison.OrdinalIgnoreCase)) continue; var bare = key[1..].ToLowerInvariant(); if (!ours.Textures.ContainsKey(bare) && !ours.Parameters.ContainsKey(bare)) Note("texture only GMod holds", $"{name}: {key} = {held}"); } }); if (Environment.GetEnvironmentVariable("EVIL_GMOD_MATERIALS_REPORT") is { } report) File.WriteAllLines(report, every.Order(StringComparer.Ordinal)); output.WriteLine($"{dumped.Count} materials in GMod's dump, {compared} compared"); foreach (var (kind, count) in kinds.OrderByDescending(pair => pair.Value)) { output.WriteLine($"{count,6} × {kind}"); foreach (var sample in samples[kind].Order(StringComparer.Ordinal)) output.WriteLine($" {sample}"); } foreach (var (pair, count) in shaders.OrderByDescending(pair => pair.Value)) output.WriteLine($"{count,6} × shader {pair}"); Assert.True(compared > 0); Assert.DoesNotContain(kinds.Keys, kind => kind.EndsWith("differs") || kind.StartsWith("fails here") || kind.StartsWith("flag we set")); } private sealed record Dumped(string Shader, bool Error, Dictionary Variables); }