Skip to content
0.2.0-dev Download ZIP
182 lines ·8.0 KB Raw
1using System.Buffers.Binary;
2using System.Collections.Concurrent;
3using EvilEngine.Adapters.Gma;
4using EvilEngine.Adapters.Source.Textures;
5using EvilEngine.Adapters.Vpk;
6using EvilEngine.Formats.Textures;
7using EvilEngine.Mounts;
8
9namespace EvilEngine.Adapters.Tests;
10
11public sealed class GarrysModVtfTests(ITestOutputHelper output)
12{
13 private static readonly int[][] Orders = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]];
14
15 private static List<(string Name, Func<byte[]> Read)> EveryVtf()
16 {
17 var path = Environment.GetEnvironmentVariable("EVIL_GMOD");
18 Assert.SkipWhen(path is null, "Set EVIL_GMOD to a Garry's Mod install to convert its VTFs.");
19 var install = new FolderSource(path!, CaseRule.Insensitive);
20 var files = new List<(string, Func<byte[]>)>();
21
22 void Add(IFileSource source, string prefix, IEnumerable<VirtualPath> paths)
23 {
24 foreach (var file in paths.Where(file => file.Value.EndsWith(".vtf", StringComparison.OrdinalIgnoreCase)))
25 files.Add(($"{prefix}{file}", () =>
26 {
27 using var stream = source.Open(file);
28 using var buffer = new MemoryStream();
29 stream.CopyTo(buffer);
30 return buffer.ToArray();
31 }));
32 }
33
34 var vpks = new VpkContainer();
35 foreach (var directory in install.EnumerateAll().Select(entry => entry.Path)
36 .Where(file => file.Name.EndsWith("_dir.vpk", StringComparison.OrdinalIgnoreCase)).Order())
37 {
38 var vpk = (VpkSource)vpks.Open(install, directory);
39 Add(vpk, $"{directory}:", vpk.Archive.Entries.Select(entry => entry.Path));
40 }
41
42 Add(install, "", install.EnumerateAll().Select(entry => entry.Path));
43 var workshop = Path.GetFullPath(Path.Combine(path!, "../../workshop/content/4000"));
44 if (Directory.Exists(workshop))
45 {
46 var items = new FolderSource(workshop, CaseRule.Insensitive);
47 var gmas = new GmaContainer();
48 foreach (var item in items.EnumerateAll().Select(entry => entry.Path)
49 .Where(file => gmas.Recognises(items, file)).Order())
50 {
51 var gma = (GmaSource)gmas.Open(items, item);
52 Add(gma, $"{item}:", gma.EnumerateAll().Select(entry => entry.Path));
53 }
54 }
55
56 return files;
57 }
58
59 [Fact]
60 public void ConvertsEveryVtfInARealInstall()
61 {
62 var files = EveryVtf();
63 var failures = new ConcurrentBag<string>();
64 var warnings = new ConcurrentBag<string>();
65 var tally = new ConcurrentDictionary<string, int>();
66 var orderError = new ConcurrentDictionary<string, double[]>();
67
68 void Count(string key)
69 {
70 tally.AddOrUpdate(key, 1, (_, count) => count + 1);
71 }
72
73 Parallel.ForEach(files, file =>
74 {
75 try
76 {
77 var bytes = file.Read();
78 var vtf = VtfFile.Read(bytes, file.Name);
79 var texture = VtfTexture.From(vtf, warnings.Add);
80 var back = TextureFile.Read(TextureFile.Write(texture), file.Name);
81 Assert.Equal(texture.Levels.Count, back.Levels.Count);
82 for (var level = 0; level < texture.Levels.Count; level++)
83 Assert.Equal(texture.Levels[level], back.Levels[level]);
84 Count($"{VtfFormats.Name(vtf.Format)} as {texture.Format}");
85 if (texture.Cube)
86 Count(vtf.HasSphereMap ? "cube maps whose sphere map was dropped" : "cube maps with six faces");
87 if (texture.Layers > 1)
88 Count("animated");
89 if (texture.Sheet is not null)
90 Count("sheets");
91 if (texture.Detail?.Largest is not null)
92 Count("clamped at full detail");
93 if (Order(vtf, texture) is { } errors)
94 orderError.AddOrUpdate(VtfFormats.Name(vtf.Format), errors,
95 (_, sum) => sum.Zip(errors, (a, b) => a + b).ToArray());
96 }
97 catch (Exception error) when (error is VtfFormatException or TextureFormatException or ArgumentException)
98 {
99 failures.Add(error is ArgumentException ? $"{file.Name}: {error.Message}" : error.Message);
100 }
101 });
102
103 foreach (var (key, count) in tally.OrderByDescending(pair => pair.Value))
104 output.WriteLine($"{count,6} × {key}");
105 foreach (var (format, errors) in orderError.OrderBy(pair => pair.Key))
106 output.WriteLine(
107 $"{format} against its thumbnail: {string.Join(", ", Orders.Select((order, i) => $"{string.Concat(order.Select(c => "rgb"[c]))} {errors[i]:F0}"))}");
108 output.WriteLine($"{files.Count} VTFs, {failures.Count} failed, {warnings.Count} warned");
109 foreach (var warning in warnings.Order(StringComparer.Ordinal))
110 output.WriteLine(warning);
111 foreach (var failure in failures.Order(StringComparer.Ordinal).Take(100))
112 output.WriteLine(failure);
113 Assert.NotEmpty(files);
114 Assert.Empty(failures);
115 foreach (var (format, errors) in orderError)
116 Assert.True(errors[0] <= errors.Skip(1).Min(),
117 $"{format}'s channels sit closer to its thumbnail in another order: {string.Join(", ", errors)}");
118 }
119
120 private static double[]? Order(VtfFile vtf, Texture texture)
121 {
122 if (vtf.LowResFormat != VtfFormat.Dxt1 || vtf.LowRes.IsEmpty ||
123 texture.Format is not (TextureFormat.R8G8B8Unorm or TextureFormat.R8G8B8A8Unorm) ||
124 texture.Swizzle != "rgba")
125 return null;
126 var thumbnail = Mean(Bc1(vtf.LowRes, vtf.LowResWidth, vtf.LowResHeight), 4);
127 var stride = texture.Format == TextureFormat.R8G8B8Unorm ? 3 : 4;
128 var image = Mean(texture.Image(0).ToArray(), stride);
129 return Orders.Select(order => Enumerable.Range(0, 3).Sum(c => Math.Abs(image[order[c]] - thumbnail[c])))
130 .ToArray();
131 }
132
133 private static double[] Mean(byte[] texels, int stride)
134 {
135 var sum = new double[3];
136 var count = texels.Length / stride;
137 for (var i = 0; i < count; i++)
138 for (var c = 0; c < 3; c++)
139 sum[c] += texels[i * stride + c];
140 return sum.Select(value => value / count).ToArray();
141 }
142
143 private static byte[] Bc1(ReadOnlyMemory<byte> blocks, int width, int height)
144 {
145 var texels = new byte[width * height * 4];
146 var span = blocks.Span;
147
148 (int R, int G, int B) Color(ushort value)
149 {
150 return ((value >> 11) * 255 / 31, ((value >> 5) & 63) * 255 / 63, (value & 31) * 255 / 31);
151 }
152
153 for (int by = 0, block = 0; by < (height + 3) / 4; by++)
154 for (var bx = 0; bx < (width + 3) / 4; bx++, block++)
155 {
156 var at = span[(block * 8)..];
157 var (c0, c1) = (BinaryPrimitives.ReadUInt16LittleEndian(at),
158 BinaryPrimitives.ReadUInt16LittleEndian(at[2..]));
159 var (a, b) = (Color(c0), Color(c1));
160 (int R, int G, int B)[] palette = c0 > c1
161 ?
162 [
163 a, b, ((2 * a.R + b.R) / 3, (2 * a.G + b.G) / 3, (2 * a.B + b.B) / 3),
164 ((a.R + 2 * b.R) / 3, (a.G + 2 * b.G) / 3, (a.B + 2 * b.B) / 3)
165 ]
166 : [a, b, ((a.R + b.R) / 2, (a.G + b.G) / 2, (a.B + b.B) / 2), (0, 0, 0)];
167 var indices = BinaryPrimitives.ReadUInt32LittleEndian(at[4..]);
168 for (var i = 0; i < 16; i++)
169 {
170 var (x, y) = (bx * 4 + i % 4, by * 4 + i / 4);
171 if (x >= width || y >= height)
172 continue;
173 var color = palette[(indices >> (i * 2)) & 3];
174 var texel = (y * width + x) * 4;
175 (texels[texel], texels[texel + 1], texels[texel + 2], texels[texel + 3]) =
176 ((byte)color.R, (byte)color.G, (byte)color.B, 255);
177 }
178 }
179
180 return texels;
181 }
182}