Skip to content
0.2.0-dev Download ZIP
445 lines ·18.0 KB Raw
1using System.Buffers.Binary;
2using System.Text;
3using System.Text.Json;
4
5namespace EvilEngine.Formats.Textures;
6
7internal sealed class Ktx2Reader
8{
9 private readonly ReadOnlyMemory<byte> _file;
10 private readonly string _name;
11
12 private Ktx2Reader(ReadOnlyMemory<byte> file, string name)
13 {
14 _file = file;
15 _name = name;
16 }
17
18 public static Texture Read(ReadOnlyMemory<byte> file, string name)
19 {
20 return new Ktx2Reader(file, name).Read();
21 }
22
23 private Texture Read()
24 {
25 var span = _file.Span;
26 if (span.Length < 80 || !span[..12].SequenceEqual(Ktx2Writer.Identifier))
27 throw Error("isn't a KTX2 file.");
28 var vkFormat = U32(12);
29 var typeSize = U32(16);
30 var width = U32(20);
31 var height = U32(24);
32 var depth = U32(28);
33 var layers = U32(32);
34 var faces = U32(36);
35 var levelCount = U32(40);
36 var scheme = U32(44);
37
38 if (scheme != 0)
39 throw Error(
40 $"is supercompressed (scheme {scheme}), and Evil Engine only takes texels as they were stored.");
41 var format = (TextureFormat)vkFormat;
42 if (!TextureFormats.IsSupported(format))
43 throw Error($"is in Vulkan format {vkFormat}, which isn't one Evil Engine takes.");
44 var info = TextureFormats.Info(format);
45 if (typeSize != info.TypeSize)
46 throw Error($"says its type size is {typeSize}, and {format} has {info.TypeSize}.");
47 if (width == 0)
48 throw Error("is 0 texels wide.");
49 if (faces != 1 && faces != 6)
50 throw Error($"has {faces} faces, and a texture has 1 or a cube map 6.");
51 if (faces == 6 && (width != height || depth != 0))
52 throw Error(
53 $"is a cube map with {width}×{height}×{depth} faces, and its faces have to be square and flat.");
54 if (depth != 0 && layers != 0)
55 throw Error("has depth and layers, which KTX2 doesn't allow together.");
56 if (width > 65536 || height > 65536 || depth > 65536 || layers > 65536)
57 throw Error(
58 $"is {width}×{height}×{depth} with {layers} layers, past the 65536 Evil Engine takes on any side.");
59
60 var size = (Width: (int)width, Height: Math.Max(1, (int)height), Depth: Math.Max(1, (int)depth));
61 var levels = Math.Max(1, (int)levelCount);
62 var full = TextureFormats.FullMipCount(size.Width, size.Height, size.Depth);
63 if (levels > full)
64 throw Error(
65 $"has {levels} levels, and a {size.Width}×{size.Height}×{size.Depth} texture has at most {full}.");
66 if (levelCount == 0 && info.Compressed)
67 throw Error("asks for its levels to be generated, which KTX2 doesn't allow for block-compressed formats.");
68
69 CheckDescriptor(format);
70 var values = ReadKeyValues();
71 var shell = new Texture(format, size.Width, size.Height, size.Depth, Math.Max(1, (int)layers), faces == 6, []);
72 var data = new ReadOnlyMemory<byte>[levels];
73 var indexEnd = 80 + 24L * levels;
74 if (indexEnd > span.Length)
75 throw Error("ends inside its level index.");
76 for (var level = 0; level < levels; level++)
77 {
78 var at = 80 + 24 * level;
79 var offset = U64(at);
80 var length = U64(at + 8);
81 var uncompressed = U64(at + 16);
82 ulong expected;
83 try
84 {
85 expected = (ulong)shell.LevelBytes(level);
86 }
87 catch (OverflowException)
88 {
89 throw Error(
90 $"is {size.Width}×{size.Height}×{size.Depth} with {shell.Layers} layers, too large to hold.");
91 }
92
93 if (length != expected || uncompressed != expected)
94 throw Error($"has level {level} as {length} bytes, and its size and format make it {expected}.");
95 if (offset > (ulong)span.Length || length > (ulong)span.Length - offset)
96 throw Error($"has level {level} past the end of the file.");
97 data[level] = _file.Slice((int)offset, (int)length);
98 }
99
100 return Apply(shell with { Levels = data }, values);
101 }
102
103 private void CheckDescriptor(TextureFormat format)
104 {
105 var offset = U32(48);
106 var length = U32(52);
107 var span = _file.Span;
108 if (length < 28 || offset + (ulong)length > (ulong)span.Length)
109 throw Error("has no format descriptor inside the file.");
110 var descriptor = span.Slice((int)offset, (int)length);
111 if (BinaryPrimitives.ReadUInt32LittleEndian(descriptor) != length)
112 throw Error("has a format descriptor whose size doesn't match the index.");
113 var (model, transfer) = Ktx2Descriptor.Describe(descriptor);
114 var (expectedModel, expectedTransfer) = Ktx2Descriptor.Describe(format);
115 if (model != expectedModel || transfer != expectedTransfer)
116 throw Error(
117 $"has a format descriptor of colour model {model} and transfer {transfer}, and {format} needs {expectedModel} and {expectedTransfer}.");
118 }
119
120 private Dictionary<string, ReadOnlyMemory<byte>> ReadKeyValues()
121 {
122 var values = new Dictionary<string, ReadOnlyMemory<byte>>(StringComparer.Ordinal);
123 var offset = U32(56);
124 var length = U32(60);
125 if (length == 0)
126 return values;
127 if (offset + (ulong)length > (ulong)_file.Length)
128 throw Error("has key and value data past the end of the file.");
129 var block = _file.Slice((int)offset, (int)length);
130 var at = 0;
131 while (at < block.Length)
132 {
133 if (at + 4 > block.Length)
134 throw Error("has key and value data that ends inside an entry's length.");
135 var size = BinaryPrimitives.ReadUInt32LittleEndian(block.Span[at..]);
136 if (size < 2 || size > block.Length - at - 4)
137 throw Error($"has a key and value entry of {size} bytes that doesn't fit its data.");
138 var entry = block.Slice(at + 4, (int)size);
139 var nul = entry.Span.IndexOf((byte)0);
140 if (nul < 1)
141 throw Error("has a key and value entry with no key.");
142 var key = Encoding.UTF8.GetString(entry.Span[..nul]);
143 if (!values.TryAdd(key, entry[(nul + 1)..]))
144 throw Error($"has the key '{key}' twice.");
145 at += 4 + (int)((size + 3) / 4 * 4);
146 }
147
148 return values;
149 }
150
151 private Texture Apply(Texture texture, Dictionary<string, ReadOnlyMemory<byte>> values)
152 {
153 if (values.TryGetValue("KTXorientation", out var orientation))
154 {
155 var value = Text(orientation);
156 var expected = texture.Depth > 1 ? "rdi" : "rd";
157 if (value != expected && !(texture.Depth == 1 && value == "r"))
158 throw Error(
159 $"is stored with orientation '{value}', and Evil Engine takes textures stored top row first ('{expected}').");
160 }
161
162 if (values.TryGetValue("KTXswizzle", out var swizzle))
163 {
164 var value = Text(swizzle);
165 if (value.Length != 4 || value.Any(c => !"rgba01".Contains(c)))
166 throw Error($"has the swizzle '{value}', which isn't four of r, g, b, a, 0 and 1.");
167 texture = texture with { Swizzle = value };
168 }
169
170 if (values.TryGetValue(TextureFile.Key, out var metadata))
171 texture = ReadMetadata(texture, metadata);
172 return texture;
173 }
174
175 private Texture ReadMetadata(Texture texture, ReadOnlyMemory<byte> value)
176 {
177 var bytes = value.Span;
178 if (bytes.Length > 0 && bytes[^1] == 0)
179 bytes = bytes[..^1];
180 JsonDocument document;
181 try
182 {
183 document = JsonDocument.Parse(bytes.ToArray());
184 }
185 catch (JsonException error)
186 {
187 throw Error($"has {TextureFile.Key} data that isn't JSON: {error.Message}");
188 }
189
190 using (document)
191 {
192 var root = document.RootElement;
193 if (root.ValueKind != JsonValueKind.Object)
194 throw Error($"has {TextureFile.Key} data that isn't a JSON object.");
195 var sampling = TextureSampling.Default;
196 foreach (var property in root.EnumerateObject())
197 {
198 var path = $"{TextureFile.Key}.{property.Name}";
199 var item = property.Value;
200 switch (property.Name)
201 {
202 case "wrap":
203 if (item.ValueKind != JsonValueKind.Array || item.GetArrayLength() != 3)
204 throw Error($"{path} must be three of repeat, clamp, mirror and border.");
205 var wraps = item.EnumerateArray()
206 .Select((wrap, index) => Parse<TextureWrap>(wrap, $"{path}[{index}]")).ToArray();
207 sampling = sampling with { WrapU = wraps[0], WrapV = wraps[1], WrapW = wraps[2] };
208 break;
209 case "filter":
210 sampling = sampling with { Filter = Parse<TextureFilter>(item, path) };
211 break;
212 case "mips":
213 sampling = sampling with { Mips = Parse<TextureMipFilter>(item, path) };
214 break;
215 case "anisotropic":
216 sampling = sampling with { Anisotropic = Bool(item, path) };
217 break;
218 case "normal":
219 texture = texture with { Normal = ReadNormal(item, path) };
220 break;
221 case "selfShadowedBump":
222 texture = texture with { SelfShadowedBump = Bool(item, path) };
223 break;
224 case "hdr":
225 texture = texture with { Hdr = Parse<TextureHdr>(item, path) };
226 break;
227 case "detail":
228 texture = texture with { Detail = ReadDetail(item, path) };
229 break;
230 case "sheet":
231 texture = texture with { Sheet = ReadSheet(item, path) };
232 break;
233 default:
234 throw Error($"{path} isn't something a texture holds.");
235 }
236 }
237
238 return texture with { Sampling = sampling };
239 }
240 }
241
242 private TextureNormal ReadNormal(JsonElement item, string path)
243 {
244 if (item.ValueKind != JsonValueKind.Object)
245 throw Error($"{path} must be an object with green and z.");
246 NormalGreen? green = null;
247 bool? rebuild = null;
248 foreach (var property in item.EnumerateObject())
249 {
250 var inner = $"{path}.{property.Name}";
251 switch (property.Name)
252 {
253 case "green":
254 green = Parse<NormalGreen>(property.Value, inner);
255 break;
256 case "z":
257 rebuild = property.Value.ValueKind == JsonValueKind.String
258 ? property.Value.GetString() switch
259 {
260 "stored" => false,
261 "rebuilt" => true,
262 _ => null
263 }
264 : null;
265 if (rebuild is null)
266 throw Error($"{inner} must be stored or rebuilt.");
267 break;
268 default:
269 throw Error($"{inner} isn't something a normal map holds.");
270 }
271 }
272
273 if (green is null || rebuild is null)
274 throw Error($"{path} needs both green and z.");
275 return new TextureNormal(green.Value, rebuild.Value);
276 }
277
278 private TextureDetail ReadDetail(JsonElement item, string path)
279 {
280 if (item.ValueKind != JsonValueKind.Object)
281 throw Error($"{path} must be an object with largest or fixed.");
282 var detail = new TextureDetail();
283 foreach (var property in item.EnumerateObject())
284 {
285 var inner = $"{path}.{property.Name}";
286 switch (property.Name)
287 {
288 case "largest":
289 var sides = Array(property.Value, inner, 2, 2)
290 .Select((side, index) => Int(side, $"{inner}[{index}]", 1)).ToArray();
291 detail = detail with { Largest = (sides[0], sides[1]) };
292 break;
293 case "fixed":
294 detail = detail with { Fixed = Bool(property.Value, inner) };
295 break;
296 default:
297 throw Error($"{inner} isn't something a texture's detail holds.");
298 }
299 }
300
301 return detail;
302 }
303
304 private TextureSequence[] ReadSheet(JsonElement item, string path)
305 {
306 return Array(item, path, 1, int.MaxValue)
307 .Select((sequence, index) => ReadSequence(sequence, $"{path}[{index}]")).ToArray();
308 }
309
310 private TextureSequence ReadSequence(JsonElement item, string path)
311 {
312 if (item.ValueKind != JsonValueKind.Object)
313 throw Error($"{path} must be an object with sequence and frames.");
314 int? number = null;
315 var clamp = false;
316 float? duration = null;
317 TextureFrame[]? frames = null;
318 foreach (var property in item.EnumerateObject())
319 {
320 var inner = $"{path}.{property.Name}";
321 switch (property.Name)
322 {
323 case "sequence":
324 number = Int(property.Value, inner, 0);
325 break;
326 case "clamp":
327 clamp = Bool(property.Value, inner);
328 break;
329 case "duration":
330 duration = Float(property.Value, inner);
331 break;
332 case "frames":
333 frames = Array(property.Value, inner, 1, int.MaxValue)
334 .Select((frame, index) => ReadFrame(frame, $"{inner}[{index}]")).ToArray();
335 break;
336 default:
337 throw Error($"{inner} isn't something a sheet's sequence holds.");
338 }
339 }
340
341 if (number is null || frames is null)
342 throw Error($"{path} needs both sequence and frames.");
343 return new TextureSequence(number.Value, clamp, frames, duration);
344 }
345
346 private TextureFrame ReadFrame(JsonElement item, string path)
347 {
348 if (item.ValueKind != JsonValueKind.Object)
349 throw Error($"{path} must be an object with duration and rects.");
350 float? duration = null;
351 TextureRect[]? rects = null;
352 foreach (var property in item.EnumerateObject())
353 {
354 var inner = $"{path}.{property.Name}";
355 switch (property.Name)
356 {
357 case "duration":
358 duration = Float(property.Value, inner);
359 break;
360 case "rects":
361 if (property.Value.ValueKind != JsonValueKind.Array ||
362 property.Value.GetArrayLength() is not (1 or 4))
363 throw Error($"{inner} must hold one rectangle or four.");
364 rects = property.Value.EnumerateArray().Select((rect, index) =>
365 {
366 var at = $"{inner}[{index}]";
367 var sides = Array(rect, at, 4, 4).Select((side, corner) => Float(side, $"{at}[{corner}]"))
368 .ToArray();
369 return new TextureRect(sides[0], sides[1], sides[2], sides[3]);
370 }).ToArray();
371 break;
372 default:
373 throw Error($"{inner} isn't something a sheet's frame holds.");
374 }
375 }
376
377 if (duration is null || rects is null)
378 throw Error($"{path} needs both duration and rects.");
379 return new TextureFrame(duration.Value, rects);
380 }
381
382 private JsonElement[] Array(JsonElement item, string path, int fewest, int most)
383 {
384 if (item.ValueKind != JsonValueKind.Array || item.GetArrayLength() < fewest || item.GetArrayLength() > most)
385 throw Error(fewest == most
386 ? $"{path} must be an array of {fewest}."
387 : $"{path} must be an array of at least {fewest}.");
388 return item.EnumerateArray().ToArray();
389 }
390
391 private int Int(JsonElement item, string path, int least)
392 {
393 if (item.ValueKind == JsonValueKind.Number && item.TryGetInt32(out var value) && value >= least)
394 return value;
395 throw Error($"{path} must be a whole number of at least {least}.");
396 }
397
398 private float Float(JsonElement item, string path)
399 {
400 if (item.ValueKind == JsonValueKind.Number && item.TryGetSingle(out var value) && float.IsFinite(value))
401 return value;
402 throw Error($"{path} must be a finite number.");
403 }
404
405 private T Parse<T>(JsonElement item, string path) where T : struct, Enum
406 {
407 if (item.ValueKind == JsonValueKind.String)
408 foreach (var value in Enum.GetValues<T>())
409 if (Ktx2Writer.Name(value) == item.GetString())
410 return value;
411 throw Error($"{path} must be one of {string.Join(", ", Enum.GetValues<T>().Select(Ktx2Writer.Name))}.");
412 }
413
414 private bool Bool(JsonElement item, string path)
415 {
416 return item.ValueKind switch
417 {
418 JsonValueKind.True => true,
419 JsonValueKind.False => false,
420 _ => throw Error($"{path} must be true or false.")
421 };
422 }
423
424 private static string Text(ReadOnlyMemory<byte> value)
425 {
426 var span = value.Span;
427 var nul = span.IndexOf((byte)0);
428 return Encoding.UTF8.GetString(nul >= 0 ? span[..nul] : span);
429 }
430
431 private uint U32(int at)
432 {
433 return BinaryPrimitives.ReadUInt32LittleEndian(_file.Span[at..]);
434 }
435
436 private ulong U64(int at)
437 {
438 return BinaryPrimitives.ReadUInt64LittleEndian(_file.Span[at..]);
439 }
440
441 private TextureFormatException Error(string message)
442 {
443 return new TextureFormatException(_name, message);
444 }
445}