ws-tex: image/ktx (KTX1 + KTX2 read: BCn / ETC2 / EAC / uncompressed, mips, cube, arrays, 3D, Zstd / ZLIB; Basis UNSUPPORTED; KTX2 write)

KTX2 writer: rgba8 (UNORM / SRGB), rgba16, rgba16f / rgba32f with a full DFD, mips, cube / array frames, ZLIB.
Tested against ktx create / deflate / extract, toktx, nvcompress -ktx and hand-written KTX1 (big-endian, packed,
row padding, T=u); our files pass ktx validate.
This commit is contained in:
4DBug committed 2026-10-31 14:30:30 -05:00
1 parent e59f5409a7
commit ef2cd93c88
7 files changed
+1154

No files matched your search

+12
View File
@@ -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",
+672
View File
@@ -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