diff --git a/docs/FORMATS.md b/docs/FORMATS.md index dfcdb88..46d0547 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,6 +11,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | +| image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` | | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` | | image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 988b668..718bbaa 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -86,6 +86,18 @@ local list: { Entry } = { return require("@formats/image/jpeg") end, }, + { + name = "ktx", + category = "image", + path = "image/ktx", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, + load = function() + return require("@formats/image/ktx") + end, + }, { name = "png", category = "image", diff --git a/src/Formats/image/ktx/init.luau b/src/Formats/image/ktx/init.luau new file mode 100644 index 0000000..2fd15bb --- /dev/null +++ b/src/Formats/image/ktx/init.luau @@ -0,0 +1,672 @@ +--!strict +-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL +-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the +-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every +-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip +-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are +-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is +-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. +-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 +-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, +-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and +-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Zstd = require("@formats/codecs/compress/Zstd") +local Texel = require("@formats/codecs/image/Texel") +local Texture = require("@formats/codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Ktx = { + name = "ktx", + category = "image", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8) + mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) + surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) + maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface) +} +export type EncodeOptions = { + format: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) + srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb") + mips: boolean?, -- a full mip chain (box filter; default false) + cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube") + zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none) + keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written) +} + +-- ------------------------------------------------------------------------------------------------ constants +local ID1 = "\171KTX 11\187\r\n\26\n" +local ID2 = "\171KTX 20\187\r\n\26\n" + +-- VkFormat -> texture format name +local VK: { [number]: string } = { + [2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1", + [9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8", + [16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8", + [23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8", + [30] = "bgr8", [36] = "bgr8", + [37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8", + [44] = "bgra8", [50] = "bgra8", + [58] = "bgr10a2", [64] = "rgb10a2", + [70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f", + [77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f", + [84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f", + [91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f", + [98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f", + [104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f", + [122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f", + [131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3", + [139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7", + [147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba", + [153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s", +} +local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true } +local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black +-- OpenGL compressed internal formats +local GL_COMPRESSED: { [number]: string } = { + [0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3", + [0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3", + [0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s", + [0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h", + [0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1", + [0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s", +} +local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true } +local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true } +-- glFormat -> channel order; glType -> bit size, Texel suffix +local GL_ORDER: { [number]: string } = { + [0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra", + [0x1909] = "l", [0x190A] = "la", [0x1906] = "a", + [0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats +} +local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true } +local GL_PACKED: { [number]: string } = { + [0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5", +} +local GL_TYPES: { [number]: { any } } = { + [0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" }, + [0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" }, +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } + +local readu32, readstring = buffer.readu32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Ktx.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1)) +end + +-- ------------------------------------------------------------------------------------------------ decode +export type Info = { + version: number, -- 1 or 2 + width: number, + height: number, + depth: number, -- 1 for 2D + layers: number, + faces: number, + levels: number, + format: string?, -- the texture format name (nil when unsupported: see unsupported) + unsupported: string?, + srgb: boolean, + opaque: boolean, -- BC1 RGB + vkFormat: number?, + glInternalFormat: number?, + supercompression: number?, + keyValue: { [string]: string }, + bigEndian: boolean?, + typeSize: number, + dataOffset: number, -- KTX1: the first imageSize field (relative to the file) + levelIndex: { { offset: number, length: number, uncompressed: number } }?, -- KTX2 +} + +local function u64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4 +local function keyValues(b: buffer, p: number, stop: number, be: boolean): { [string]: string } + local kv: { [string]: string } = {} + while p + 4 <= stop do + local n = readu32(b, p) + if be then + n = bit32.byteswap(n) + end + p += 4 + if n > stop - p then + break + end + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + if z then + local v = string.sub(s, z + 1) + if string.sub(v, -1) == "\0" then + v = string.sub(v, 1, -2) + end + kv[string.sub(s, 1, z - 1)] = v + end + p += n + (3 - (n + 3) % 4) + end + return kv +end + +local function info1(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 64 then + return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o) + end + local e = readu32(b, o + 12) + local be = e == 0x01020304 + if not be and e ~= 0x04030201 then + return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12) + end + local function f(i: number): number + local v = readu32(b, o + 16 + i * 4) + return if be then bit32.byteswap(v) else v + end + local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3) + local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16) + end + if 64 + kvBytes > n then + return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64) + end + local info: Info = { + version = 1, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, arr), + faces = faces, + levels = math.max(1, levels), + srgb = GL_SRGB[internal] == true, + opaque = GL_OPAQUE[internal] == true, + glInternalFormat = internal, + keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be), + bigEndian = be, + typeSize = typeSize, + dataOffset = 64 + kvBytes, + } + if glType == 0 then + info.format = GL_COMPRESSED[internal] + if not info.format then + info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal) + end + else + local name = GL_PACKED[glType] + if not name then + local order = GL_ORDER[glFormat] + local int = GL_INTEGER[glFormat] == true + -- glType -> component bits, Texel suffix (normalized / integer) + local t = GL_TYPES[glType] + local size: number? = t and t[1] + local suffix: string = if t then (if int then t[3] else t[2]) else "" + if order and size then + name = order .. tostring(size) .. suffix + end + end + if name and Texel.FORMATS[name] then + info.format = name + else + info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType) + end + end + return info, nil +end + +local function info2(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 80 then + return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o) + end + local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16) + local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28) + local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20) + end + local nl = math.max(1, levels) + if 80 + nl * 24 > n then + return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80) + end + local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60) + local info: Info = { + version = 2, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, layers), + faces = faces, + levels = nl, + srgb = VK_SRGB[vk] == true, + opaque = VK_OPAQUE[vk] == true, + vkFormat = vk, + supercompression = scheme, + keyValue = if kvLen > 0 and kvOff + kvLen <= n then keyValues(b, o + kvOff, o + kvOff + kvLen, false) else {}, + typeSize = typeSize, + dataOffset = 0, + levelIndex = {}, + } + for i = 0, nl - 1 do + local q = o + 80 + i * 24 + table.insert(info.levelIndex :: any, { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) }) + end + -- the colour model of the DFD tells Basis Universal apart + local model = -1 + if dfdLen >= 16 and dfdOff + dfdLen <= n then + model = buffer.readu8(b, o + dfdOff + 12) + if buffer.readu8(b, o + dfdOff + 14) == 2 then + info.srgb = true + end + end + if scheme == 1 or model == 163 then + info.unsupported = "Basis Universal ETC1S / BasisLZ" + elseif model == 166 then + info.unsupported = "Basis Universal UASTC" + elseif scheme > 3 then + info.unsupported = "supercompression scheme " .. scheme + elseif vk == 0 then + info.unsupported = "VK_FORMAT_UNDEFINED" + else + info.format = VK[vk] + if not info.format then + info.unsupported = "VkFormat " .. vk .. (if vk >= 157 and vk <= 184 or vk >= 1000066000 then " (ASTC)" else "") + end + end + return info, nil +end + +-- info(r) -> Info | nil, Err (the headers only) +function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) + local id = r:peek(12) + if id == ID2 then + return info2(r) + elseif id == ID1 then + return info1(r) + end + return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) +end + +-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image +local function swapped(b: buffer, p: number, n: number, size: number): buffer + local out = buffer.create(n) + buffer.copy(out, 0, b, p, n) + for i = 0, n - size, size do + if size == 2 then + buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16)) + else + buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i))) + end + end + return out +end + +-- flips the rows of a decoded surface (KTXorientation T=u) +local function flip(img: Types.Image) + local row = img.width * (Types.BPP[img.format] or 4) + local px = img.pixels + local tmp = buffer.create(row) + for y = 0, img.height // 2 - 1 do + local a, z = y * row, (img.height - 1 - y) * row + buffer.copy(tmp, 0, px, a, row) + buffer.copy(px, a, px, z, row) + buffer.copy(px, z, tmp, 0, row) + end +end + +function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Ktx.info(r) + if not info then + return nil, ierr + end + local fmt = info.format + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format") + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base, limit = r.buf, r.base, r.limit + local bw, bh, bbytes = Texture.block(fmt) + local blockFmt = bw == 4 + local orient = info.keyValue.KTXorientation or "" + local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u") + local list: { Texture.Surface } = {} + local pixels = 0 + local count = info.layers * info.faces + local p = base + info.dataOffset + local w, h, d = info.width, info.height, info.depth + for level = 0, info.levels - 1 do + local want = level == 0 or wantMips + -- the level's data: buf, offset, the image stride and row pitch + local lb, lp = b, 0 + local rowPitch: number? = nil + local imgSize = Texture.size(fmt, w, h) :: number + local stride = imgSize + if info.version == 1 then + if p + 4 > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "missing level 0", p) + end + break + end + local declared = readu32(b, p) + if info.bigEndian then + declared = bit32.byteswap(declared) + end + p += 4 + if not blockFmt then + local tight = (bbytes :: number) * w + rowPitch = tight + (3 - (tight + 3) % 4) + imgSize = (rowPitch :: number) * h + end + stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding + local total = stride * count * d + if declared < imgSize * (if info.faces == 6 and info.layers == 1 then 1 else count * d) and level == 0 then + return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4) + end + if p + total > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p) + end + break + end + lp = p + p += total + p += 3 - (total + 3) % 4 + if info.bigEndian and info.typeSize > 1 and want then + lb, lp = swapped(b, lp, total, info.typeSize), 0 + end + else + local li = (info.levelIndex :: any)[level + 1] + local off, len = base + li.offset, li.length + if off + len > limit or li.offset < 80 then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off) + end + break + end + local expect = imgSize * count * d + if want then + local scheme = info.supercompression + if scheme == 2 or scheme == 3 then + if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24) + end + local out, zerr + if scheme == 2 then + out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed }) + else + out, zerr = Deflate.zlib(b, off, len, li.uncompressed) + end + if not out then + return nil, Err.wrap(zerr) + end + lb, lp = out, 0 + else + lb, lp = b, off + end + if lp + expect > buffer.len(lb) then + return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off) + end + end + end + if want then + for layer = 0, count - 1 do + for slice = 0, d - 1 do + if level == 0 and not wantAll and (layer > 0 or slice > 0) then + continue + end + if level > 0 and (layer > 0 or slice > 0) then + continue + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local at = lp + (layer * d + slice) * stride + local px, pf + if rowPitch then + px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch) + else + px, pf = Texture.decode(fmt, lb, at, w, h, native) + end + if not px then + return nil, Err.from(pf, at) + end + local im = Texture.image(px, pf, w, h) + if info.opaque then + for i = 0, w * h - 1 do + buffer.writeu8(px, i * 4 + 3, 255) + end + end + if up then + flip(im) + end + table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im }) + end + end + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + local layout = if info.depth > 1 then "volume" elseif info.faces == 6 then "cube" elseif info.layers > 1 then "array" else "2d" + local img = Texture.assemble(list, layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no image data") + end + if info.faces == 6 then + img.meta.faces = table.clone(FACES) + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.keyValue = info.keyValue + img.meta.source = { + format = "ktx", + version = info.version, + pixelFormat = fmt, + vkFormat = info.vkFormat, + glInternalFormat = info.glInternalFormat, + supercompression = info.supercompression, + mips = info.levels, + layers = info.layers, + depth = info.depth, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- format -> VkFormat, bytes per texel, component bytes, kind +local OUT: { [string]: { number } } = { + rgba8 = { 37, 4, 1 }, + rgba16 = { 91, 8, 2 }, + rgba16f = { 97, 8, 2 }, + rgba32f = { 109, 16, 4 }, +} + +-- the DFD: one basic descriptor block with four samples (R G B A) +local function dfd(f: string, srgb: boolean): buffer + local spec = OUT[f] + local texel, comp = spec[2], spec[3] + local float = f == "rgba16f" or f == "rgba32f" + local w = Bytes.writer(92) + local blockSize = 24 + 16 * 4 + w:u32le(4 + blockSize) + w:u32le(0) -- vendor 0, descriptor type 0 + w:u32le(2 + blockSize * 65536) -- version 2, block size + w:u8(1) -- colour model RGBSDA + w:u8(1) -- primaries BT.709 + w:u8(if srgb then 2 else 1) -- transfer: sRGB / linear + w:u8(0) -- straight alpha + w:u32le(0) -- texel block 1 x 1 x 1 x 1 + w:u32le(texel) -- bytesPlane0 + w:u32le(0) + for c = 0, 3 do + local channel = if c == 3 then 15 else c + local qual = (if float then 0xC0 else 0) + (if srgb and c == 3 then 0x10 else 0) + w:u16le(c * comp * 8) + w:u8(comp * 8 - 1) + w:u8(channel + qual) + w:u32le(0) -- sample position + if float then + w:u32le(0xBF800000) + w:u32le(0x3F800000) + else + w:u32le(0) + w:u32le(if comp == 1 then 255 else 65535) + end + end + return w:finish() +end + +function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.format) or (if pf == "rgbaf32" then "rgba32f" else pf) + local spec = OUT[f] + if not spec then + return nil, Err.new(Err.ARG, "unknown format " .. tostring(f)) + end + local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("format %s needs an %s Image", f, needs)) + end + local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb")) + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and (#images % 6 ~= 0 or img.width ~= img.height) then + return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer") + end + local faces = if cube then 6 else 1 + local layers = #images // faces + local levels = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + levels += 1 + end + end + local zl = opts and opts.zlib + if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then + return nil, Err.new(Err.ARG, "zlib level must be 1..9") + end + -- level data: the images of every layer / face per level + local levelData: { buffer } = {} + local raw: { number } = {} + local cur = table.clone(images) + for lv = 1, levels do + local w = Bytes.writer() + for i, im in cur do + local data = if f == "rgba16f" then Texture.toHalf(im.pixels, im.width * im.height) else im.pixels + w:bytes(data, 0, im.width * im.height * spec[2]) + if lv < levels then + cur[i] = Texture.halve(im) + end + end + local lb = w:finish() + raw[lv] = buffer.len(lb) + if zl then + lb = Deflate.zlibCompress(lb, { level = zl }) :: buffer + end + levelData[lv] = lb + end + -- key / value data + local kvw = Bytes.writer() + local pairs_: { { string } } = { { "KTXwriter", "formats-luau" } } + if opts and opts.keyValue then + for k, v in opts.keyValue do + if k ~= "KTXwriter" then + table.insert(pairs_, { k, v }) + end + end + end + table.sort(pairs_, function(a: { string }, c: { string }): boolean + return a[1] < c[1] + end) + for _, kv in pairs_ do + local n = #kv[1] + 1 + #kv[2] + 1 + kvw:u32le(n) + kvw:string(kv[1]) + kvw:u8(0) + kvw:string(kv[2]) + kvw:u8(0) + kvw:fill(0, 3 - (n + 3) % 4) + end + local kvd = kvw:finish() + local d = dfd(f, srgb == true) + local dfdOff = 80 + levels * 24 + local kvOff = dfdOff + buffer.len(d) + local dataStart = kvOff + buffer.len(kvd) + local align = if zl then 1 else (if spec[2] % 4 == 0 then spec[2] else 4) + -- smallest level first + local offsets: { number } = {} + local p = dataStart + for lv = levels, 1, -1 do + p += (align - p % align) % align + offsets[lv] = p + p += buffer.len(levelData[lv]) + end + local out = Bytes.writer(p) + out:string(ID2) + out:u32le(if f == "rgba8" and srgb then 43 else spec[1]) + out:u32le(spec[3]) + out:u32le(img.width) + out:u32le(img.height) + out:u32le(0) + out:u32le(if layers > 1 then layers else 0) + out:u32le(faces) + out:u32le(levels) + out:u32le(if zl then 3 else 0) + out:u32le(dfdOff) + out:u32le(buffer.len(d)) + out:u32le(kvOff) + out:u32le(buffer.len(kvd)) + out:u64le(0) + out:u64le(0) + for lv = 1, levels do + out:u64le(offsets[lv]) + out:u64le(buffer.len(levelData[lv])) + out:u64le(raw[lv]) + end + out:bytes(d) + out:bytes(kvd) + for lv = levels, 1, -1 do + out:fill(0, offsets[lv] - out:tell()) + out:bytes(levelData[lv]) + end + return out:finish(), nil +end + +return Ktx diff --git a/tests/image/ktx.luau b/tests/image/ktx.luau new file mode 100644 index 0000000..1c24fbf --- /dev/null +++ b/tests/image/ktx.luau @@ -0,0 +1,167 @@ +-- image/ktx tests: KTX2 files from KTX-Software (`ktx create` from PNGs and raw data in uncompressed / packed / float / +-- BCn / ETC2 / EAC formats, mips, cube maps, arrays, 3D, Zstandard and ZLIB supercompression; Basis Universal is +-- UNSUPPORTED) and KTX1 files from toktx / nvcompress / hand-written ones (big-endian, packed types, row padding, +-- KTXorientation) against their sources or reference decodes; our KTX2 files through `ktx validate` / `ktx extract`; +-- round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ktx.py. +local T = require("@tests/T") +local Ktx = require("@formats/image/ktx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/ktx") + +local t = T.suite("ktx") + +t:eq(Ktx.name, "ktx", "name") +t:check(Ktx.caps.decode and Ktx.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Ktx.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +local function maxDiff(a: buffer, b: buffer, n: number): number + local worst = 0 + for i = 0, n * 4 - 1 do + worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))) + end + return worst +end + +local nsurf = 0 +for _, c in Fx.cases do + if c.unsupported then + local img, e = dec(c.data) + t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")") + continue + end + local img, err = dec(c.data, { mips = true }) + t:check(img, c.name .. ": " .. tostring(err)) + if c.layout then + t:eq(img.meta.layout, c.layout, c.name .. ": layout") + end + if c.mips then + t:eq(img.meta.source.mips, c.mips, c.name .. ": mip count") + end + if c.srgb then + t:eq(img.meta.colorSpace, "srgb", c.name .. ": sRGB") + end + local native = nil + local frames = img.frames or { { image = img } } + for _, s in c.surfaces do + local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice) + local im + if s.level == 0 then + local f = frames[s.layer + s.slice + 1] + im = f and f.image + else + im = img.meta.mipmaps and img.meta.mipmaps[s.level] + end + t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size") + if s.rgba then + local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h) + t:check(d <= s.tol, string.format("%s: %d off the reference", label, d)) + end + if s.floats and s.level == 0 and s.layer == 0 then + native = native or dec(c.data, { native = true }) + local f = buffer.fromstring(s.floats) + local worst = 0 + for i = 0, s.w * s.h * 4 - 1 do + local want = buffer.readf32(f, i * 4) + local got + if native.format == "rgbaf32" then + got = buffer.readf32(native.pixels, i * 4) + elseif native.format == "rgba16" then + got = buffer.readu16(native.pixels, i * 2) / 65535 + else + got = buffer.readu8(native.pixels, i) / 255 + end + if i % 4 ~= 3 or not string.find(c.name, "bc6h") then + worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want))) + end + end + local tol = if native.format == "rgba8" then 1 / 255 elseif native.format == "rgba16" then 1 / 65535 else 1e-3 + t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", label, native.format, worst)) + end + nsurf += 1 + end +end +t:note("%d files, %d surfaces match", #Fx.cases, nsurf) + +-- our files: ktx validate accepts them, ktx extract reads the first image +local function source(w: number, h: number): buffer + local px = buffer.create(w * h * 4) + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5)) + buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5)) + buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5)) + buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5)) + end + end + return px +end +local src = source(37, 23) +for _, o in Fx.ours do + t:check(o.valid, o.name .. ": ktx validate: " .. tostring(o.report)) + local img, err = dec(o.data, { mips = true, native = true }) + t:check(img, o.name .. ": " .. tostring(err)) + if o.png and (string.find(o.name, "rgba8") or string.find(o.name, "srgb")) then + t:eq(o.png, buffer.tostring(src), o.name .. ": ktx extract gives the source") + end + if string.find(o.name, "mips") or string.find(o.name, "zlib") then + t:eq(#img.meta.mipmaps, 5, o.name .. ": mip chain") + end + if string.find(o.name, "cube") then + t:eq(img.meta.layout, "cube", o.name .. ": cube") + t:eq(#img.frames, 6, o.name .. ": faces") + end +end +t:note("%d of our files pass ktx validate", #Fx.ours) + +-- round trips +do + local img = Types.Image.new(37, 23) + img.pixels = src + for _, o in { {}, { mips = true }, { zlib = 9 }, { srgb = true } } do + local back = dec(Ktx.encode(img, o :: any) :: buffer) + t:eq(buffer.tostring(back.pixels), buffer.tostring(src), "rgba8 round trip") + end + local f = Types.Image.new(3, 2, "rgbaf32") + for i = 0, 23 do + buffer.writef32(f.pixels, i * 4, i * 0.37 - 2) + end + local back = dec(Ktx.encode(f) :: buffer, { native = true }) + t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip") + local _, e = Ktx.encode(f, { format = "rgba8" }) + t:check(e and e.code == Err.ARG, "format mismatch") + local _, e2 = Ktx.encode(img, { zlib = 12 }) + t:check(e2 and e2.code == Err.ARG, "zlib level") +end + +-- sniff, info, errors +do + local c = Fx.cases[1] + t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff KTX2") + t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("\171KTX 11\187\r\n\26\n"))), 1, "sniff KTX1") + t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other") + local info = Ktx.info(Bytes.reader(buffer.fromstring(c.data))) + t:check(info and info.version == 2 and info.vkFormat == 37, "info") + local _, e = dec(string.sub(c.data, 1, 60)) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = dec(string.sub(c.data, 1, #c.data - 100)) + t:check(e2 and e2.code == Err.TRUNCATED, "cut data: " .. tostring(e2)) + local _, e3 = dec(c.data, { maxPixels = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "limit") +end + +local samples = {} +for i, c in Fx.cases do + if i % 2 == 0 or c.unsupported then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return dec(b, { mips = true }) +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index cd0d87d..14a7df0 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -73,3 +73,23 @@ if which == "dds" then cube.meta.layout = "array" emit("ours_array_bc1.dds", Dds.encode(cube, { format = "bc1" })) end + +if which == "ktx" then + local Ktx = require("@formats/image/ktx") + local img = image(37, 23, "rgba8", 0) + emit("ours_rgba8.ktx2", Ktx.encode(img)) + emit("ours_rgba8_mips.ktx2", Ktx.encode(img, { mips = true })) + emit("ours_srgb_zlib.ktx2", Ktx.encode(img, { mips = true, srgb = true, zlib = 6 })) + emit("ours_rgba16.ktx2", Ktx.encode(image(37, 23, "rgba16", 0), { mips = true })) + emit("ours_rgba32f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true })) + emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { format = "rgba16f" })) + local cube = image(16, 16, "rgba8", 0) + cube.frames = {} + for i = 1, 6 do + cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + end + cube.meta.layout = "cube" + emit("ours_cube.ktx2", Ktx.encode(cube, { mips = true })) + cube.meta.layout = "array" + emit("ours_array.ktx2", Ktx.encode(cube)) +end diff --git a/tools/fixtures/_tex_reference.py b/tools/fixtures/_tex_reference.py index af25edf..52b51bd 100644 --- a/tools/fixtures/_tex_reference.py +++ b/tools/fixtures/_tex_reference.py @@ -99,6 +99,9 @@ def rgba_from(mode, raw): if mode == "L": for v in raw: out += bytes((v, v, v, 255)) + elif mode == "LA": + for i in range(0, len(raw), 2): + out += bytes((raw[i], raw[i], raw[i], raw[i + 1])) elif mode == "RGB": for i in range(0, len(raw), 3): out += raw[i:i + 3] + b"\xff" diff --git a/tools/fixtures/ktx.py b/tools/fixtures/ktx.py new file mode 100644 index 0000000..1e69fdb --- /dev/null +++ b/tools/fixtures/ktx.py @@ -0,0 +1,279 @@ +# KTX fixtures (tools/fixtures.py): +# - KTX2 from KTX-Software 4.4 (`ktx create`): PNG sources (mip chains, sRGB, cube maps, arrays), --raw data in +# uncompressed / packed / float / BCn / ETC2 / EAC VkFormats, a 3D texture, `ktx deflate` Zstandard and ZLIB +# supercompression, Basis Universal (ETC1S and UASTC: must give UNSUPPORTED); +# - KTX1 from toktx (PNG sources, mips, cube map, odd widths with row padding) and nvcompress -ktx (BC1 / BC3 / BC7), +# plus hand-written big-endian and packed-type KTX1 files; +# - our encoder's KTX2 files (tools/fixtures/_tex_encode.luau -a ktx): `ktx validate` and `ktx extract` read them. +# References: the PNG sources / raw values themselves, `ktx extract` PNGs for the generated mip levels, Pillow (BCn, +# through a one-surface DDS) and Godot (ETC / EAC) for block data. +# tests/gen/ktx.luau { cases = { { name, data, layout?, mips?, surfaces = { { level, layer, slice, w, h, rgba?, +# floats?, tol } }, unsupported? } }, ours = { { name, data, valid, extract = { rgba / floats } } } } +import importlib.util, os, random, shutil, struct, subprocess, tempfile + +_dir = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(_dir, "_tex_reference.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) +_spec2 = importlib.util.spec_from_file_location("_dds_fixture", os.path.join(_dir, "dds.py")) +D = importlib.util.module_from_spec(_spec2) +_spec2.loader.exec_module(D) + +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ktx", "tools/fixtures/dds.py"] + + +def q8(v): + return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5)) + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="formats-ktx-") + try: + cases = _cases(ctx, work, random.Random(9)) + ours = _ours(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + ctx.emit("ktx", {"cases": cases, "ours": ours}) + + +def read_png(ctx, paths): + return [R.rgba_from(m, raw) if m in ("RGB", "L", "LA", "RGBA") else raw for (m, w, h, raw) in + R.pillow(ctx, [open(p, "rb").read() for p in paths])] + + +def _cases(ctx, work, rng): + cases = [] + sh = [] + + def run(cmd): + sh.append(cmd) + + # sources + srcs = {} + for name, w, h, salt in (("a", 37, 23, 0), ("sq", 32, 32, 3)): + srcs[name] = (w, h, D.source(w, h, salt)) + open(os.path.join(work, name + ".png"), "wb").write(D.png(w, h, srcs[name][2])) + faces = [] + for i in range(6): + px = D.source(16, 16, i + 1) + faces.append(px) + open(os.path.join(work, "f%d.png" % i), "wb").write(D.png(16, 16, px)) + fl = " ".join("f%d.png" % i for i in range(6)) + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear a.png k2_rgba8.ktx2") + run("ktx create --format R8G8B8A8_SRGB --assign-tf srgb --generate-mipmap sq.png k2_srgb_mips.ktx2") + run("ktx extract --level all k2_srgb_mips.ktx2 k2mips") + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --cubemap %s k2_cube.ktx2" % fl) + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --layers 3 f0.png f1.png f2.png k2_array.ktx2") + run("ktx create --format R8G8B8_UNORM --assign-tf linear a.png k2_rgb8.ktx2") + run("ktx deflate --zstd 12 k2_srgb_mips.ktx2 k2_zstd.ktx2") + run("ktx deflate --zlib 6 k2_cube.ktx2 k2_zlib.ktx2") + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode basis-lz a.png k2_basis.ktx2") + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode uastc a.png k2_uastc.ktx2") + # raw formats with known values + W, H = 8, 4 + raws = [] + + def raw(name, vk, data, texels=None, block=None, w=W, h=H, extra="", parts=1): + n = len(data) // parts + files = [] + for i in range(parts): + open(os.path.join(work, "%s_%d.raw" % (name, i)), "wb").write(data[i * n:(i + 1) * n]) + files.append("%s_%d.raw" % (name, i)) + run("ktx create --raw --width %d --height %d --format %s %s %s %s.ktx2" % (w, h, vk, extra, " ".join(files), name)) + raws.append((name, texels, block, w, h, data)) + + u8 = bytes(rng.randrange(256) for _ in range(W * H * 4)) + raw("k2_raw_rgba8", "R8G8B8A8_UNORM", u8, [tuple(u8[i + k] / 255 for k in range(4)) for i in range(0, len(u8), 4)]) + raw("k2_raw_bgra8_srgb", "B8G8R8A8_SRGB", u8, [(u8[i + 2] / 255, u8[i + 1] / 255, u8[i] / 255, u8[i + 3] / 255) for i in range(0, len(u8), 4)]) + raw("k2_raw_rg8", "R8G8_UNORM", u8[:W * H * 2], [(u8[i] / 255, u8[i + 1] / 255, 0.0, 1.0) for i in range(0, W * H * 2, 2)]) + vals = [(rng.uniform(-1, 4), rng.uniform(0, 1), rng.uniform(0, 2), rng.uniform(0, 1)) for _ in range(W * H)] + hd = b"".join(struct.pack("<4e", *v) for v in vals) + raw("k2_raw_rgba16f", "R16G16B16A16_SFLOAT", hd, [struct.unpack("<4e", hd[i:i + 8]) for i in range(0, len(hd), 8)]) + fd = b"".join(struct.pack("<4f", *v) for v in vals) + raw("k2_raw_rgba32f", "R32G32B32A32_SFLOAT", fd, [struct.unpack("<4f", fd[i:i + 16]) for i in range(0, len(fd), 16)]) + u16 = [rng.randrange(65536) for _ in range(W * H)] + raw("k2_raw_r16", "R16_UNORM", b"".join(struct.pack("> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in u16]) + p32 = [rng.getrandbits(32) for _ in range(W * H)] + raw("k2_raw_a2b10g10r10", "A2B10G10R10_UNORM_PACK32", b"".join(struct.pack("> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32]) + raw("k2_raw_e5b9g9r9", "E5B9G9R9_UFLOAT_PACK32", b"".join(struct.pack("> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32]) + vol = bytes(rng.randrange(256) for _ in range(4 * 4 * 3 * 4)) + raw("k2_raw_3d", "R8G8B8A8_UNORM", vol, None, None, 4, 4, "--depth 3", 3) + for kind, vk in (("bc1", "BC1_RGB_UNORM_BLOCK"), ("bc1", "BC1_RGBA_UNORM_BLOCK"), ("bc3", "BC3_UNORM_BLOCK"), + ("bc7", "BC7_UNORM_BLOCK"), ("bc6h", "BC6H_UFLOAT_BLOCK"), ("etc2_rgba", "ETC2_R8G8B8A8_UNORM_BLOCK"), + ("etc2_rgb", "ETC2_R8G8B8_UNORM_BLOCK"), ("eac_rg11", "EAC_R11G11_UNORM_BLOCK")): + bb = {"bc1": 8, "bc3": 16, "bc7": 16, "bc6h": 16, "etc2_rgba": 16, "etc2_rgb": 8, "eac_rg11": 16}[kind] + data = bytes(rng.getrandbits(8) for _ in range(4 * 2 * bb)) + raw("k2_raw_" + vk.lower(), vk, data, None, kind, 13, 7) + # KTX1 + run("toktx --genmipmap k1_mips.ktx sq.png") + run("toktx k1_rgba.ktx a.png") + run("toktx --cubemap k1_cube.ktx %s" % fl) + run("ktx2ktx2 -o k1_mips_as2.ktx2 k1_mips.ktx") + run("ktx extract --level all k1_mips_as2.ktx2 k1mips") + ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))]) + ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && nvcompress -silent -ktx -bc1 a.png n_bc1.ktx && nvcompress -silent -ktx -bc3 a.png n_bc3.ktx && nvcompress -silent -ktx -bc7 -nomips a.png n_bc7.ktx" % work]) + + def rd(n): + return open(os.path.join(work, n), "rb").read() + + def surf(level, layer, s, w, h, rgba=None, floats=None, tol=0): + d = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": tol} + if rgba is not None: + d["rgba"] = rgba + if floats is not None: + d["floats"] = floats + return d + + aw, ah, apx = srcs["a"] + sw, shh, spx = srcs["sq"] + cases.append({"name": "k2_rgba8.ktx2", "data": rd("k2_rgba8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]}) + mip_files = sorted(f for f in os.listdir(work) if f.startswith("k2mips") or f.startswith("output_level")) + mips = [] + lw = sw + level = 0 + while True: + p = os.path.join(work, "k2mips_level%d.png" % level) + if not os.path.exists(p): + p = os.path.join(work, "k2mips", "output_level%d.png" % level) + if not os.path.exists(p): + break + mips.append((level, p)) + level += 1 + if not mips: + raise RuntimeError("ktx extract wrote no mip levels: %r" % os.listdir(work)) + pngs = read_png(ctx, [p for _, p in mips]) + msurf = [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for (lv, _), px in zip(mips, pngs)] + cases.append({"name": "k2_srgb_mips.ktx2", "data": rd("k2_srgb_mips.ktx2"), "layout": "2d", "mips": len(mips), "srgb": True, "surfaces": msurf}) + cases.append({"name": "k2_zstd.ktx2", "data": rd("k2_zstd.ktx2"), "layout": "2d", "mips": len(mips), "surfaces": msurf}) + csurf = [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)] + cases.append({"name": "k2_cube.ktx2", "data": rd("k2_cube.ktx2"), "layout": "cube", "surfaces": csurf}) + cases.append({"name": "k2_zlib.ktx2", "data": rd("k2_zlib.ktx2"), "layout": "cube", "surfaces": csurf}) + cases.append({"name": "k2_array.ktx2", "data": rd("k2_array.ktx2"), "layout": "array", "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(3)]}) + opaque = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(apx)) + cases.append({"name": "k2_rgb8.ktx2", "data": rd("k2_rgb8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, opaque)]}) + cases.append({"name": "k2_basis.ktx2", "data": rd("k2_basis.ktx2"), "unsupported": True, "surfaces": []}) + cases.append({"name": "k2_uastc.ktx2", "data": rd("k2_uastc.ktx2"), "unsupported": True, "surfaces": []}) + pil, pil_t, gd, gd_t = [], [], [], [] + for (name, texels, block, w, h, data) in raws: + c = {"name": name + ".ktx2", "data": rd(name + ".ktx2"), "layout": "volume" if name.endswith("3d") else "2d"} + if texels is not None: + c["surfaces"] = [surf(0, 0, 0, w, h, bytes(q8(v) for t in texels for v in t), b"".join(struct.pack("<4f", *t) for t in texels), 1)] + elif block is None: + c["surfaces"] = [surf(0, 0, s, w, h, data[s * w * h * 4:(s + 1) * w * h * 4]) for s in range(3)] + else: + sd = surf(0, 0, 0, w, h) + c["surfaces"] = [sd] + if block.startswith("bc") and block != "bc6h": + dx = {"bc1": 71, "bc3": 77, "bc7": 98}[block] + pil.append(R.dds_dx10(w, h, dx, data)) + pil_t.append((sd, "RGB_UNORM" in name.upper())) + else: + gd.append((data, w, h, R.GODOT[block], block == "bc6h")) + gd_t.append((sd, block)) + cases.append(c) + for (sd, opaque_), (mode, w, h, rw) in zip(pil_t, R.pillow(ctx, pil)): + px = R.rgba_from(mode, rw) + if opaque_: + px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px)) + sd["rgba"] = px + for (sd, block), out in zip(gd_t, R.godot(ctx, gd)): + if block == "bc6h": + sd["floats"] = out + elif block == "eac_rg11": + sd["rgba"] = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(out)) + sd["tol"] = 1 + else: + sd["rgba"] = out + # KTX1 + k1 = [] + level = 0 + while True: + p = os.path.join(work, "k1mips_level%d.png" % level) + if not os.path.exists(p): + p = os.path.join(work, "k1mips", "output_level%d.png" % level) + if not os.path.exists(p): + break + k1.append(p) + level += 1 + k1png = read_png(ctx, k1) + cases.append({"name": "k1_mips.ktx", "data": rd("k1_mips.ktx"), "layout": "2d", "mips": len(k1), + "surfaces": [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for lv, px in enumerate(k1png)]}) + cases.append({"name": "k1_rgba.ktx", "data": rd("k1_rgba.ktx"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]}) + cases.append({"name": "k1_cube.ktx", "data": rd("k1_cube.ktx"), "layout": "cube", + "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]}) + # nvcompress KTX1: the level-0 blocks follow the 64-byte header + key / value data + imageSize + nv = [] + for n, dx in (("n_bc1.ktx", 71), ("n_bc3.ktx", 77), ("n_bc7.ktx", 98)): + d = rd(n) + kvb = struct.unpack("4H", *v) for v in v16) + b"\0" * 0 # rows of 40 bytes: already 4-aligned + cases.append({"name": "hand big-endian RGBA16", "data": ktx1(0x1403, 2, 0x1908, 0x805B, 0x1908, W2, H2, img, True), "layout": "2d", + "surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(x / 65535) for v in v16 for x in v), b"".join(struct.pack("<4f", *(x / 65535 for x in v)) for v in v16), 1)]}) + p565 = [rng.getrandbits(16) for _ in range(W2 * H2)] + rows = b"".join(b"".join(struct.pack("> 11) / 31, ((p >> 5) & 63) / 63, (p & 31) / 31, 1.0)), None, 1)]}) + rgb = bytes(rng.randrange(256) for _ in range(W2 * H2 * 3)) + rows = b"".join(rgb[y * W2 * 3:(y + 1) * W2 * 3] + b"\0" for y in range(H2)) + kv = b"KTXorientation\0S=r,T=u\0" + kv = struct.pack(" %s.val 2>&1; echo $? > %s.rc)" % (n, base, base)) + sh.append("(ktx extract %s %s.x > /dev/null 2>&1 || true)" % (n, base)) + ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " ; ".join(sh))]) + out = [] + pngs, idx = [], [] + for i, n in enumerate(names): + base = n[:-5] + rc = open(os.path.join(work, base + ".rc")).read().strip() + e = {"name": n, "data": files[n], "valid": rc == "0", "report": open(os.path.join(work, base + ".val"), "rb").read()[:2000]} + for ext in (".x", ".x.png", ".x.exr"): + p = os.path.join(work, base + ext) + if os.path.exists(p) and os.path.isfile(p): + e["extracted"] = open(p, "rb").read()[:8] + if open(p, "rb").read(4) == b"\x89PNG": + pngs.append(p) + idx.append(i) + out.append(e) + for i, (mode, w, h, raw) in zip(idx, R.pillow(ctx, [open(p, "rb").read() for p in pngs])): + if mode in ("RGBA", "RGB", "L", "LA"): + out[i]["png"] = R.rgba_from(mode, raw) + return out