using System.Buffers.Binary; using System.Text; using System.Text.Json; namespace EvilEngine.Formats.Textures; internal sealed class Ktx2Reader { private readonly ReadOnlyMemory _file; private readonly string _name; private Ktx2Reader(ReadOnlyMemory file, string name) { _file = file; _name = name; } public static Texture Read(ReadOnlyMemory file, string name) { return new Ktx2Reader(file, name).Read(); } private Texture Read() { var span = _file.Span; if (span.Length < 80 || !span[..12].SequenceEqual(Ktx2Writer.Identifier)) throw Error("isn't a KTX2 file."); var vkFormat = U32(12); var typeSize = U32(16); var width = U32(20); var height = U32(24); var depth = U32(28); var layers = U32(32); var faces = U32(36); var levelCount = U32(40); var scheme = U32(44); if (scheme != 0) throw Error( $"is supercompressed (scheme {scheme}), and Evil Engine only takes texels as they were stored."); var format = (TextureFormat)vkFormat; if (!TextureFormats.IsSupported(format)) throw Error($"is in Vulkan format {vkFormat}, which isn't one Evil Engine takes."); var info = TextureFormats.Info(format); if (typeSize != info.TypeSize) throw Error($"says its type size is {typeSize}, and {format} has {info.TypeSize}."); if (width == 0) throw Error("is 0 texels wide."); if (faces != 1 && faces != 6) throw Error($"has {faces} faces, and a texture has 1 or a cube map 6."); if (faces == 6 && (width != height || depth != 0)) throw Error( $"is a cube map with {width}×{height}×{depth} faces, and its faces have to be square and flat."); if (depth != 0 && layers != 0) throw Error("has depth and layers, which KTX2 doesn't allow together."); if (width > 65536 || height > 65536 || depth > 65536 || layers > 65536) throw Error( $"is {width}×{height}×{depth} with {layers} layers, past the 65536 Evil Engine takes on any side."); var size = (Width: (int)width, Height: Math.Max(1, (int)height), Depth: Math.Max(1, (int)depth)); var levels = Math.Max(1, (int)levelCount); var full = TextureFormats.FullMipCount(size.Width, size.Height, size.Depth); if (levels > full) throw Error( $"has {levels} levels, and a {size.Width}×{size.Height}×{size.Depth} texture has at most {full}."); if (levelCount == 0 && info.Compressed) throw Error("asks for its levels to be generated, which KTX2 doesn't allow for block-compressed formats."); CheckDescriptor(format); var values = ReadKeyValues(); var shell = new Texture(format, size.Width, size.Height, size.Depth, Math.Max(1, (int)layers), faces == 6, []); var data = new ReadOnlyMemory[levels]; var indexEnd = 80 + 24L * levels; if (indexEnd > span.Length) throw Error("ends inside its level index."); for (var level = 0; level < levels; level++) { var at = 80 + 24 * level; var offset = U64(at); var length = U64(at + 8); var uncompressed = U64(at + 16); ulong expected; try { expected = (ulong)shell.LevelBytes(level); } catch (OverflowException) { throw Error( $"is {size.Width}×{size.Height}×{size.Depth} with {shell.Layers} layers, too large to hold."); } if (length != expected || uncompressed != expected) throw Error($"has level {level} as {length} bytes, and its size and format make it {expected}."); if (offset > (ulong)span.Length || length > (ulong)span.Length - offset) throw Error($"has level {level} past the end of the file."); data[level] = _file.Slice((int)offset, (int)length); } return Apply(shell with { Levels = data }, values); } private void CheckDescriptor(TextureFormat format) { var offset = U32(48); var length = U32(52); var span = _file.Span; if (length < 28 || offset + (ulong)length > (ulong)span.Length) throw Error("has no format descriptor inside the file."); var descriptor = span.Slice((int)offset, (int)length); if (BinaryPrimitives.ReadUInt32LittleEndian(descriptor) != length) throw Error("has a format descriptor whose size doesn't match the index."); var (model, transfer) = Ktx2Descriptor.Describe(descriptor); var (expectedModel, expectedTransfer) = Ktx2Descriptor.Describe(format); if (model != expectedModel || transfer != expectedTransfer) throw Error( $"has a format descriptor of colour model {model} and transfer {transfer}, and {format} needs {expectedModel} and {expectedTransfer}."); } private Dictionary> ReadKeyValues() { var values = new Dictionary>(StringComparer.Ordinal); var offset = U32(56); var length = U32(60); if (length == 0) return values; if (offset + (ulong)length > (ulong)_file.Length) throw Error("has key and value data past the end of the file."); var block = _file.Slice((int)offset, (int)length); var at = 0; while (at < block.Length) { if (at + 4 > block.Length) throw Error("has key and value data that ends inside an entry's length."); var size = BinaryPrimitives.ReadUInt32LittleEndian(block.Span[at..]); if (size < 2 || size > block.Length - at - 4) throw Error($"has a key and value entry of {size} bytes that doesn't fit its data."); var entry = block.Slice(at + 4, (int)size); var nul = entry.Span.IndexOf((byte)0); if (nul < 1) throw Error("has a key and value entry with no key."); var key = Encoding.UTF8.GetString(entry.Span[..nul]); if (!values.TryAdd(key, entry[(nul + 1)..])) throw Error($"has the key '{key}' twice."); at += 4 + (int)((size + 3) / 4 * 4); } return values; } private Texture Apply(Texture texture, Dictionary> values) { if (values.TryGetValue("KTXorientation", out var orientation)) { var value = Text(orientation); var expected = texture.Depth > 1 ? "rdi" : "rd"; if (value != expected && !(texture.Depth == 1 && value == "r")) throw Error( $"is stored with orientation '{value}', and Evil Engine takes textures stored top row first ('{expected}')."); } if (values.TryGetValue("KTXswizzle", out var swizzle)) { var value = Text(swizzle); if (value.Length != 4 || value.Any(c => !"rgba01".Contains(c))) throw Error($"has the swizzle '{value}', which isn't four of r, g, b, a, 0 and 1."); texture = texture with { Swizzle = value }; } if (values.TryGetValue(TextureFile.Key, out var metadata)) texture = ReadMetadata(texture, metadata); return texture; } private Texture ReadMetadata(Texture texture, ReadOnlyMemory value) { var bytes = value.Span; if (bytes.Length > 0 && bytes[^1] == 0) bytes = bytes[..^1]; JsonDocument document; try { document = JsonDocument.Parse(bytes.ToArray()); } catch (JsonException error) { throw Error($"has {TextureFile.Key} data that isn't JSON: {error.Message}"); } using (document) { var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object) throw Error($"has {TextureFile.Key} data that isn't a JSON object."); var sampling = TextureSampling.Default; foreach (var property in root.EnumerateObject()) { var path = $"{TextureFile.Key}.{property.Name}"; var item = property.Value; switch (property.Name) { case "wrap": if (item.ValueKind != JsonValueKind.Array || item.GetArrayLength() != 3) throw Error($"{path} must be three of repeat, clamp, mirror and border."); var wraps = item.EnumerateArray() .Select((wrap, index) => Parse(wrap, $"{path}[{index}]")).ToArray(); sampling = sampling with { WrapU = wraps[0], WrapV = wraps[1], WrapW = wraps[2] }; break; case "filter": sampling = sampling with { Filter = Parse(item, path) }; break; case "mips": sampling = sampling with { Mips = Parse(item, path) }; break; case "anisotropic": sampling = sampling with { Anisotropic = Bool(item, path) }; break; case "normal": texture = texture with { Normal = ReadNormal(item, path) }; break; case "selfShadowedBump": texture = texture with { SelfShadowedBump = Bool(item, path) }; break; case "hdr": texture = texture with { Hdr = Parse(item, path) }; break; case "detail": texture = texture with { Detail = ReadDetail(item, path) }; break; case "sheet": texture = texture with { Sheet = ReadSheet(item, path) }; break; default: throw Error($"{path} isn't something a texture holds."); } } return texture with { Sampling = sampling }; } } private TextureNormal ReadNormal(JsonElement item, string path) { if (item.ValueKind != JsonValueKind.Object) throw Error($"{path} must be an object with green and z."); NormalGreen? green = null; bool? rebuild = null; foreach (var property in item.EnumerateObject()) { var inner = $"{path}.{property.Name}"; switch (property.Name) { case "green": green = Parse(property.Value, inner); break; case "z": rebuild = property.Value.ValueKind == JsonValueKind.String ? property.Value.GetString() switch { "stored" => false, "rebuilt" => true, _ => null } : null; if (rebuild is null) throw Error($"{inner} must be stored or rebuilt."); break; default: throw Error($"{inner} isn't something a normal map holds."); } } if (green is null || rebuild is null) throw Error($"{path} needs both green and z."); return new TextureNormal(green.Value, rebuild.Value); } private TextureDetail ReadDetail(JsonElement item, string path) { if (item.ValueKind != JsonValueKind.Object) throw Error($"{path} must be an object with largest or fixed."); var detail = new TextureDetail(); foreach (var property in item.EnumerateObject()) { var inner = $"{path}.{property.Name}"; switch (property.Name) { case "largest": var sides = Array(property.Value, inner, 2, 2) .Select((side, index) => Int(side, $"{inner}[{index}]", 1)).ToArray(); detail = detail with { Largest = (sides[0], sides[1]) }; break; case "fixed": detail = detail with { Fixed = Bool(property.Value, inner) }; break; default: throw Error($"{inner} isn't something a texture's detail holds."); } } return detail; } private TextureSequence[] ReadSheet(JsonElement item, string path) { return Array(item, path, 1, int.MaxValue) .Select((sequence, index) => ReadSequence(sequence, $"{path}[{index}]")).ToArray(); } private TextureSequence ReadSequence(JsonElement item, string path) { if (item.ValueKind != JsonValueKind.Object) throw Error($"{path} must be an object with sequence and frames."); int? number = null; var clamp = false; float? duration = null; TextureFrame[]? frames = null; foreach (var property in item.EnumerateObject()) { var inner = $"{path}.{property.Name}"; switch (property.Name) { case "sequence": number = Int(property.Value, inner, 0); break; case "clamp": clamp = Bool(property.Value, inner); break; case "duration": duration = Float(property.Value, inner); break; case "frames": frames = Array(property.Value, inner, 1, int.MaxValue) .Select((frame, index) => ReadFrame(frame, $"{inner}[{index}]")).ToArray(); break; default: throw Error($"{inner} isn't something a sheet's sequence holds."); } } if (number is null || frames is null) throw Error($"{path} needs both sequence and frames."); return new TextureSequence(number.Value, clamp, frames, duration); } private TextureFrame ReadFrame(JsonElement item, string path) { if (item.ValueKind != JsonValueKind.Object) throw Error($"{path} must be an object with duration and rects."); float? duration = null; TextureRect[]? rects = null; foreach (var property in item.EnumerateObject()) { var inner = $"{path}.{property.Name}"; switch (property.Name) { case "duration": duration = Float(property.Value, inner); break; case "rects": if (property.Value.ValueKind != JsonValueKind.Array || property.Value.GetArrayLength() is not (1 or 4)) throw Error($"{inner} must hold one rectangle or four."); rects = property.Value.EnumerateArray().Select((rect, index) => { var at = $"{inner}[{index}]"; var sides = Array(rect, at, 4, 4).Select((side, corner) => Float(side, $"{at}[{corner}]")) .ToArray(); return new TextureRect(sides[0], sides[1], sides[2], sides[3]); }).ToArray(); break; default: throw Error($"{inner} isn't something a sheet's frame holds."); } } if (duration is null || rects is null) throw Error($"{path} needs both duration and rects."); return new TextureFrame(duration.Value, rects); } private JsonElement[] Array(JsonElement item, string path, int fewest, int most) { if (item.ValueKind != JsonValueKind.Array || item.GetArrayLength() < fewest || item.GetArrayLength() > most) throw Error(fewest == most ? $"{path} must be an array of {fewest}." : $"{path} must be an array of at least {fewest}."); return item.EnumerateArray().ToArray(); } private int Int(JsonElement item, string path, int least) { if (item.ValueKind == JsonValueKind.Number && item.TryGetInt32(out var value) && value >= least) return value; throw Error($"{path} must be a whole number of at least {least}."); } private float Float(JsonElement item, string path) { if (item.ValueKind == JsonValueKind.Number && item.TryGetSingle(out var value) && float.IsFinite(value)) return value; throw Error($"{path} must be a finite number."); } private T Parse(JsonElement item, string path) where T : struct, Enum { if (item.ValueKind == JsonValueKind.String) foreach (var value in Enum.GetValues()) if (Ktx2Writer.Name(value) == item.GetString()) return value; throw Error($"{path} must be one of {string.Join(", ", Enum.GetValues().Select(Ktx2Writer.Name))}."); } private bool Bool(JsonElement item, string path) { return item.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => throw Error($"{path} must be true or false.") }; } private static string Text(ReadOnlyMemory value) { var span = value.Span; var nul = span.IndexOf((byte)0); return Encoding.UTF8.GetString(nul >= 0 ? span[..nul] : span); } private uint U32(int at) { return BinaryPrimitives.ReadUInt32LittleEndian(_file.Span[at..]); } private ulong U64(int at) { return BinaryPrimitives.ReadUInt64LittleEndian(_file.Span[at..]); } private TextureFormatException Error(string message) { return new TextureFormatException(_name, message); } }