merge ws/tex
This commit is contained in:
commit
93a5afbe65
63 files changed
+11009
-3
No files matched your search
@@ -14,6 +14,18 @@ export type Entry = {
|
||||
}
|
||||
|
||||
local list: { Entry } = {
|
||||
{
|
||||
name = "ani",
|
||||
category = "image",
|
||||
path = "image/ani",
|
||||
extensions = { "ani" },
|
||||
mime = { "application/x-navi-animation" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
|
||||
caps = { decode = true, encode = true, alpha = true, animation = true, frames = true },
|
||||
load = function()
|
||||
return require("@formats/image/ani")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bmp",
|
||||
category = "image",
|
||||
@@ -26,6 +38,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/bmp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dds",
|
||||
category = "image",
|
||||
path = "image/dds",
|
||||
extensions = { "dds" },
|
||||
mime = { "image/vnd-ms.dds", "image/x-dds" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "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" } },
|
||||
load = function()
|
||||
return require("@formats/image/dds")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "exr",
|
||||
category = "image",
|
||||
path = "image/exr",
|
||||
extensions = { "exr" },
|
||||
mime = { "image/x-exr", "image/aces" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true },
|
||||
load = function()
|
||||
return require("@formats/image/exr")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "gif",
|
||||
category = "image",
|
||||
@@ -50,6 +86,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/hdr")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "icns",
|
||||
category = "image",
|
||||
path = "image/icns",
|
||||
extensions = { "icns" },
|
||||
mime = { "image/icns", "image/x-icns" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/icns")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ico",
|
||||
category = "image",
|
||||
@@ -62,6 +110,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/ico")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ilbm",
|
||||
category = "image",
|
||||
path = "image/ilbm",
|
||||
extensions = { "iff", "ilbm", "lbm", "pbm" },
|
||||
mime = { "image/x-ilbm", "image/x-iff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/ilbm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "jpeg",
|
||||
category = "image",
|
||||
@@ -74,6 +134,30 @@ 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 = "pcx",
|
||||
category = "image",
|
||||
path = "image/pcx",
|
||||
extensions = { "pcx", "pcc", "dcx" },
|
||||
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/pcx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "png",
|
||||
category = "image",
|
||||
@@ -110,6 +194,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/qoi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "sgi",
|
||||
category = "image",
|
||||
path = "image/sgi",
|
||||
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
|
||||
mime = { "image/sgi", "image/x-rgb" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
|
||||
load = function()
|
||||
return require("@formats/image/sgi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "sunras",
|
||||
category = "image",
|
||||
path = "image/sunras",
|
||||
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
|
||||
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/sunras")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tga",
|
||||
category = "image",
|
||||
@@ -146,6 +254,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/webp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xbm",
|
||||
category = "image",
|
||||
path = "image/xbm",
|
||||
extensions = { "xbm", "bm" },
|
||||
mime = { "image/x-xbitmap", "image/x-xbm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, depths = { 1 } },
|
||||
load = function()
|
||||
return require("@formats/image/xbm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xpm",
|
||||
category = "image",
|
||||
path = "image/xpm",
|
||||
extensions = { "xpm", "pm" },
|
||||
mime = { "image/x-xpixmap", "image/x-xpm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/image/xpm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "aac",
|
||||
category = "audio",
|
||||
@@ -1046,6 +1178,18 @@ local list: { Entry } = {
|
||||
return require("@formats/layered/aseprite")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ora",
|
||||
category = "layered",
|
||||
path = "layered/ora",
|
||||
extensions = { "ora" },
|
||||
mime = { "image/openraster" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" },
|
||||
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/layered/ora")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "psd",
|
||||
category = "layered",
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's
|
||||
-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where
|
||||
-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit
|
||||
-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate
|
||||
-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte
|
||||
-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size.
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3
|
||||
local pal = buffer.create(16) -- 4 rgba8 colours
|
||||
|
||||
local function c565(c: number): (number, number, number)
|
||||
local r = rshift(band(c, 0xF800), 8)
|
||||
local g = rshift(band(c, 0x7E0), 3)
|
||||
local b = lshift(band(c, 0x1F), 3)
|
||||
return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5))
|
||||
end
|
||||
|
||||
-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette)
|
||||
local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean)
|
||||
local c0, c1 = readu16(src, p), readu16(src, p + 2)
|
||||
local r0, g0, b0 = c565(c0)
|
||||
local r1, g1, b1 = c565(c1)
|
||||
writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000)
|
||||
writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000)
|
||||
if c0 > c1 or fourColour then
|
||||
writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000)
|
||||
writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000)
|
||||
else
|
||||
writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000)
|
||||
writeu32(pal, 12, 0)
|
||||
end
|
||||
local idx = readu32(src, p + 4)
|
||||
for i = 0, 15 do
|
||||
writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4))
|
||||
end
|
||||
end
|
||||
|
||||
-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals
|
||||
local vals = table.create(8, 0)
|
||||
local function ramp8(a0: number, a1: number)
|
||||
vals[1], vals[2] = a0, a1
|
||||
if a0 > a1 then
|
||||
for i = 1, 6 do
|
||||
vals[i + 2] = ((7 - i) * a0 + i * a1) // 7
|
||||
end
|
||||
else
|
||||
for i = 1, 4 do
|
||||
vals[i + 2] = ((5 - i) * a0 + i * a1) // 5
|
||||
end
|
||||
vals[7], vals[8] = 0, 255
|
||||
end
|
||||
end
|
||||
|
||||
-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255
|
||||
local function ramp8s(u0: number, u1: number)
|
||||
local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127)
|
||||
local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127)
|
||||
vals[1], vals[2] = s0 + 128, s1 + 128
|
||||
if s0 > s1 then
|
||||
for i = 1, 6 do
|
||||
vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128
|
||||
end
|
||||
else
|
||||
for i = 1, 4 do
|
||||
vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128
|
||||
end
|
||||
vals[7], vals[8] = 1, 255
|
||||
end
|
||||
end
|
||||
|
||||
-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread)
|
||||
local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean)
|
||||
if signed then
|
||||
ramp8s(readu8(src, p), readu8(src, p + 1))
|
||||
else
|
||||
ramp8(readu8(src, p), readu8(src, p + 1))
|
||||
end
|
||||
local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536
|
||||
local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536
|
||||
for i = 0, 15 do
|
||||
local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7)
|
||||
local v = vals[sel + 1]
|
||||
local o = i * 4
|
||||
if spread then
|
||||
writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000)
|
||||
else
|
||||
writeu8(blk, o + channel, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Decode.bc1(src: buffer, p: number, blk: buffer)
|
||||
colour(src, p, blk, false)
|
||||
end
|
||||
|
||||
function Decode.bc2(src: buffer, p: number, blk: buffer)
|
||||
colour(src, p + 8, blk, true)
|
||||
for i = 0, 15 do
|
||||
local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15)
|
||||
writeu8(blk, i * 4 + 3, a * 17)
|
||||
end
|
||||
end
|
||||
|
||||
function Decode.bc3(src: buffer, p: number, blk: buffer)
|
||||
colour(src, p + 8, blk, true)
|
||||
single(src, p, blk, 3, false, false)
|
||||
end
|
||||
|
||||
function Decode.bc4(src: buffer, p: number, blk: buffer)
|
||||
single(src, p, blk, 0, false, true)
|
||||
end
|
||||
|
||||
function Decode.bc4s(src: buffer, p: number, blk: buffer)
|
||||
single(src, p, blk, 0, true, true)
|
||||
end
|
||||
|
||||
local function bc5(src: buffer, p: number, blk: buffer, signed: boolean)
|
||||
for i = 0, 15 do
|
||||
writeu32(blk, i * 4, 0xFF000000)
|
||||
end
|
||||
single(src, p, blk, 0, signed, false)
|
||||
single(src, p + 8, blk, 1, signed, false)
|
||||
end
|
||||
function Decode.bc5(src: buffer, p: number, blk: buffer)
|
||||
bc5(src, p, blk, false)
|
||||
end
|
||||
function Decode.bc5s(src: buffer, p: number, blk: buffer)
|
||||
bc5(src, p, blk, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BPTC tables
|
||||
-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices
|
||||
local SI2 = {
|
||||
0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000,
|
||||
0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c,
|
||||
0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660,
|
||||
0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22,
|
||||
}
|
||||
local SI3 = {
|
||||
0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500,
|
||||
0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0,
|
||||
0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414,
|
||||
0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50,
|
||||
0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8,
|
||||
0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000,
|
||||
0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254,
|
||||
}
|
||||
local AI0 = {
|
||||
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2,
|
||||
15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15,
|
||||
}
|
||||
local AI1 = {
|
||||
3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15,
|
||||
8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3,
|
||||
}
|
||||
local AI2 = {
|
||||
15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8,
|
||||
15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8,
|
||||
}
|
||||
local W2 = { [0] = 0, 21, 43, 64 }
|
||||
local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 }
|
||||
local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 }
|
||||
local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 }
|
||||
Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS
|
||||
|
||||
local function subset(ns: number, part: number, i: number): number
|
||||
if ns == 2 then
|
||||
return band(rshift(SI2[part + 1], i), 1)
|
||||
elseif ns == 3 then
|
||||
return band(rshift(SI3[part + 1], 2 * i), 3)
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- the 128-bit block as four u32 words: bits(at, n) for n <= 16
|
||||
local w0, w1, w2, w3 = 0, 0, 0, 0
|
||||
local function load(src: buffer, p: number)
|
||||
w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12)
|
||||
end
|
||||
local function word(i: number): number
|
||||
return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3
|
||||
end
|
||||
local function bits(at: number, n: number): number
|
||||
if n == 0 then
|
||||
return 0
|
||||
end
|
||||
local wi, sh = rshift(at, 5), band(at, 31)
|
||||
local v = rshift(word(wi), sh)
|
||||
if sh + n > 32 and wi < 3 then
|
||||
v = bor(v, lshift(word(wi + 1), 32 - sh))
|
||||
end
|
||||
return band(v, lshift(1, n) - 1)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC7
|
||||
-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2
|
||||
local MODES7 = {
|
||||
{ 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 },
|
||||
{ 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 },
|
||||
{ 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 },
|
||||
{ 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 },
|
||||
{ 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 },
|
||||
{ 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 },
|
||||
{ 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 },
|
||||
{ 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 },
|
||||
}
|
||||
local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0)
|
||||
|
||||
local function expand(v: number, n: number): number
|
||||
v = band(lshift(v, 8 - n), 255)
|
||||
return bor(v, rshift(v, n))
|
||||
end
|
||||
|
||||
function Decode.bc7(src: buffer, p: number, blk: buffer)
|
||||
local m0 = readu8(src, p)
|
||||
if m0 == 0 then
|
||||
buffer.fill(blk, 0, 0, 64)
|
||||
return
|
||||
end
|
||||
load(src, p)
|
||||
local mode = 0
|
||||
while band(m0, lshift(1, mode)) == 0 do
|
||||
mode += 1
|
||||
end
|
||||
local info = MODES7[mode + 1]
|
||||
local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10]
|
||||
local bit = mode + 1
|
||||
local part = bits(bit, pb)
|
||||
bit += pb
|
||||
local rot = bits(bit, rb)
|
||||
bit += rb
|
||||
local sel = bits(bit, isb)
|
||||
bit += isb
|
||||
local nep = ns * 2
|
||||
for i = 1, nep do
|
||||
er[i] = bits(bit, cb)
|
||||
bit += cb
|
||||
end
|
||||
for i = 1, nep do
|
||||
eg[i] = bits(bit, cb)
|
||||
bit += cb
|
||||
end
|
||||
for i = 1, nep do
|
||||
eb[i] = bits(bit, cb)
|
||||
bit += cb
|
||||
end
|
||||
for i = 1, nep do
|
||||
if ab > 0 then
|
||||
ea[i] = bits(bit, ab)
|
||||
bit += ab
|
||||
else
|
||||
ea[i] = 255
|
||||
end
|
||||
end
|
||||
if epb == 1 then
|
||||
cb += 1
|
||||
if ab > 0 then
|
||||
ab += 1
|
||||
end
|
||||
for i = 1, nep do
|
||||
local v = bits(bit, 1)
|
||||
bit += 1
|
||||
er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v
|
||||
if ab > 0 then
|
||||
ea[i] = ea[i] * 2 + v
|
||||
end
|
||||
end
|
||||
end
|
||||
if spb == 1 then
|
||||
cb += 1
|
||||
if ab > 0 then
|
||||
ab += 1
|
||||
end
|
||||
for i = 1, nep, 2 do
|
||||
local v = bits(bit, 1)
|
||||
bit += 1
|
||||
for j = i, i + 1 do
|
||||
er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v
|
||||
if ab > 0 then
|
||||
ea[j] = ea[j] * 2 + v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, nep do
|
||||
er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb)
|
||||
if ab > 0 then
|
||||
ea[i] = expand(ea[i], ab)
|
||||
end
|
||||
end
|
||||
local cw = WEIGHTS[ib]
|
||||
local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw
|
||||
local cbit = bit
|
||||
local abit = cbit + 16 * ib - ns
|
||||
local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1
|
||||
local a2 = if ns == 3 then AI2[part + 1] else -1
|
||||
for i = 0, 15 do
|
||||
local s = subset(ns, part, i) * 2 + 1
|
||||
local n = ib
|
||||
if i == 0 or i == a1 or i == a2 then
|
||||
n -= 1
|
||||
end
|
||||
local i0 = bits(cbit, n)
|
||||
cbit += n
|
||||
local wc, wa
|
||||
if ab > 0 and ib2 > 0 then
|
||||
local n2 = if i == 0 then ib2 - 1 else ib2
|
||||
local i1 = bits(abit, n2)
|
||||
abit += n2
|
||||
if sel == 1 then
|
||||
wc, wa = aw[i1], cw[i0]
|
||||
else
|
||||
wc, wa = cw[i0], aw[i1]
|
||||
end
|
||||
else
|
||||
wc, wa = cw[i0], cw[i0]
|
||||
end
|
||||
local tc, ta = 64 - wc, 64 - wa
|
||||
local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6)
|
||||
local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6)
|
||||
local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6)
|
||||
local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6)
|
||||
if rot == 1 then
|
||||
r, a = a, r
|
||||
elseif rot == 2 then
|
||||
g, a = a, g
|
||||
elseif rot == 3 then
|
||||
b, a = a, b
|
||||
end
|
||||
writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC6H
|
||||
-- ns, transformed, pb, epb, rb, gb, bb
|
||||
local MODES6 = {
|
||||
{ 2, 1, 5, 10, 5, 5, 5 },
|
||||
{ 2, 1, 5, 7, 6, 6, 6 },
|
||||
{ 2, 1, 5, 11, 5, 4, 4 },
|
||||
{ 2, 1, 5, 11, 4, 5, 4 },
|
||||
{ 2, 1, 5, 11, 4, 4, 5 },
|
||||
{ 2, 1, 5, 9, 5, 5, 5 },
|
||||
{ 2, 1, 5, 8, 6, 5, 5 },
|
||||
{ 2, 1, 5, 8, 5, 6, 5 },
|
||||
{ 2, 1, 5, 8, 5, 5, 6 },
|
||||
{ 2, 0, 5, 6, 6, 6, 6 },
|
||||
{ 1, 0, 0, 10, 10, 10, 10 },
|
||||
{ 1, 1, 0, 11, 9, 9, 9 },
|
||||
{ 1, 1, 0, 12, 8, 8, 8 },
|
||||
{ 1, 1, 0, 16, 4, 4, 4 },
|
||||
}
|
||||
-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3)
|
||||
local PACK6 = {
|
||||
{ 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 },
|
||||
}
|
||||
local ep = table.create(12, 0)
|
||||
local uq = table.create(12, 0)
|
||||
|
||||
local function signExtend(v: number, n: number): number
|
||||
v = band(v, lshift(1, n) - 1)
|
||||
return if v >= lshift(1, n - 1) then v - lshift(1, n) else v
|
||||
end
|
||||
|
||||
local function unquantize(x: number, n: number, signed: boolean): number
|
||||
if not signed then
|
||||
if n >= 15 or x == 0 then
|
||||
return x
|
||||
elseif x == lshift(1, n) - 1 then
|
||||
return 0xFFFF
|
||||
end
|
||||
return rshift(x * 32768 + 0x4000, n - 1)
|
||||
end
|
||||
if n >= 16 then
|
||||
return x
|
||||
end
|
||||
local neg = x < 0
|
||||
if neg then
|
||||
x = -x
|
||||
end
|
||||
if x ~= 0 then
|
||||
if x >= lshift(1, n - 1) - 1 then
|
||||
x = 0x7FFF
|
||||
else
|
||||
x = rshift(x * 32768 + 0x4000, n - 1)
|
||||
end
|
||||
end
|
||||
return if neg then -x else x
|
||||
end
|
||||
|
||||
local function finish(v: number, signed: boolean): number
|
||||
if signed then
|
||||
if v < 0 then
|
||||
return -HALF[(-v * 31) // 32]
|
||||
end
|
||||
return HALF[(v * 31) // 32]
|
||||
end
|
||||
return HALF[(v * 31) // 64]
|
||||
end
|
||||
|
||||
-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1)
|
||||
function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean)
|
||||
load(src, p)
|
||||
local m = band(w0, 31)
|
||||
local mode, bit, epbits, ib
|
||||
local low = band(m, 3)
|
||||
if low < 2 then
|
||||
mode, bit, epbits, ib = low, 2, 75, 3
|
||||
elseif low == 2 then
|
||||
mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3
|
||||
else
|
||||
mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4
|
||||
end
|
||||
if mode >= 14 then
|
||||
for i = 0, 15 do
|
||||
local o = i * 16
|
||||
writef32(blk, o, 0)
|
||||
writef32(blk, o + 4, 0)
|
||||
writef32(blk, o + 8, 0)
|
||||
writef32(blk, o + 12, 1)
|
||||
end
|
||||
return
|
||||
end
|
||||
local info = MODES6[mode + 1]
|
||||
local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7]
|
||||
local nep = if ns == 2 then 12 else 6
|
||||
for i = 1, 12 do
|
||||
ep[i] = 0
|
||||
end
|
||||
local pack = PACK6[mode + 1]
|
||||
for i = 1, epbits do
|
||||
local d = pack[i]
|
||||
local e = rshift(d, 4) + 1
|
||||
ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15)))
|
||||
end
|
||||
bit += epbits
|
||||
local part = bits(bit, pb)
|
||||
bit += pb
|
||||
local mask = lshift(1, epb) - 1
|
||||
if signed then
|
||||
ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb)
|
||||
end
|
||||
if signed or tr == 1 then
|
||||
for i = 4, nep, 3 do
|
||||
ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits)
|
||||
end
|
||||
end
|
||||
if tr == 1 then
|
||||
for i = 4, nep, 3 do
|
||||
for c = 0, 2 do
|
||||
local v = band(ep[i + c] + ep[1 + c], mask)
|
||||
ep[i + c] = if signed then signExtend(v, epb) else v
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, nep do
|
||||
uq[i] = unquantize(ep[i], epb, signed)
|
||||
end
|
||||
local w = WEIGHTS[ib]
|
||||
local a1 = if ns == 2 then AI0[part + 1] else -1
|
||||
for i = 0, 15 do
|
||||
local s = subset(ns, part, i) * 6 + 1
|
||||
local n = if i == 0 or i == a1 then ib - 1 else ib
|
||||
local wt = w[bits(bit, n)]
|
||||
bit += n
|
||||
local t = 64 - wt
|
||||
local o = i * 16
|
||||
-- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would
|
||||
writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed))
|
||||
writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed))
|
||||
writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed))
|
||||
writef32(blk, o + 12, 1)
|
||||
end
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,442 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in formats-luau; the approach follows stb_dxt by
|
||||
-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the
|
||||
-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping
|
||||
-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as
|
||||
-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws.
|
||||
local Encode = {}
|
||||
|
||||
local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
|
||||
local function exp5(v: number): number
|
||||
return bor(lshift(v, 3), rshift(v, 2))
|
||||
end
|
||||
local function exp6(v: number): number
|
||||
return bor(lshift(v, 2), rshift(v, 4))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ single colours
|
||||
-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1)
|
||||
-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit
|
||||
local OM: { { number } }? = nil
|
||||
local function singleTables(): { { number } }
|
||||
local om = OM
|
||||
if om then
|
||||
return om
|
||||
end
|
||||
local t: { { number } } = {}
|
||||
for k = 1, 4 do
|
||||
local bitsN = if k <= 2 then 5 else 6
|
||||
local maxq = lshift(1, bitsN) - 1
|
||||
local exp: (number) -> number = if bitsN == 5 then exp5 else exp6
|
||||
local best = table.create(256, 1e9)
|
||||
local pick = table.create(256, 0)
|
||||
for a = 0, maxq do
|
||||
local ea = exp(a)
|
||||
for b = 0, maxq do
|
||||
local eb = exp(b)
|
||||
local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2
|
||||
-- prefer endpoints close to each other (less error if the colour shifts)
|
||||
local e = math.abs(ea - eb) * 0.01
|
||||
for target = math.max(0, v - 8), math.min(255, v + 8) do
|
||||
local err = (target - v) ^ 2 + e
|
||||
if err < best[target + 1] then
|
||||
best[target + 1] = err
|
||||
pick[target + 1] = a * 256 + b
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t[k] = pick
|
||||
end
|
||||
OM = t
|
||||
return t
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC1 colour
|
||||
local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0)
|
||||
local USE = table.create(16, true)
|
||||
local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0)
|
||||
local IDX = table.create(16, 0)
|
||||
local BEST = table.create(16, 0)
|
||||
|
||||
local function palette(c0: number, c1: number, four: boolean)
|
||||
local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31))
|
||||
local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31))
|
||||
PR[1], PG[1], PB[1] = r0, g0, b0
|
||||
PR[2], PG[2], PB[2] = r1, g1, b1
|
||||
if four then
|
||||
PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3
|
||||
PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3
|
||||
else
|
||||
PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2
|
||||
PR[4], PG[4], PB[4] = 0, 0, 0
|
||||
end
|
||||
end
|
||||
|
||||
-- indices for the palette into IDX (0-based); returns the squared error of the used pixels
|
||||
local function assign(four: boolean): number
|
||||
local n = if four then 4 else 3
|
||||
local total = 0
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
local r, g, b = R[i], G[i], B[i]
|
||||
local bi, be = 0, math.huge
|
||||
for k = 1, n do
|
||||
local dr, dg, db = r - PR[k], g - PG[k], b - PB[k]
|
||||
local e = dr * dr + dg * dg + db * db
|
||||
if e < be then
|
||||
be, bi = e, k - 1
|
||||
end
|
||||
end
|
||||
IDX[i] = bi
|
||||
total += be
|
||||
else
|
||||
IDX[i] = 3
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
local function q565(r: number, g: number, b: number): number
|
||||
local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31)
|
||||
local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63)
|
||||
local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31)
|
||||
return qr * 2048 + qg * 32 + qb
|
||||
end
|
||||
|
||||
-- the endpoint weights of index k (the e0 share)
|
||||
local W4 = { 1, 0, 2 / 3, 1 / 3 }
|
||||
local W3 = { 1, 0, 0.5, 0 }
|
||||
|
||||
-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate
|
||||
local function refine(four: boolean): (number?, number?)
|
||||
local W = if four then W4 else W3
|
||||
local aa, bb, ab = 0, 0, 0
|
||||
local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
local w = W[IDX[i] + 1]
|
||||
local v = 1 - w
|
||||
aa += w * w
|
||||
bb += v * v
|
||||
ab += w * v
|
||||
ar += w * R[i]
|
||||
ag += w * G[i]
|
||||
ab_ += w * B[i]
|
||||
br += v * R[i]
|
||||
bg += v * G[i]
|
||||
bb_ += v * B[i]
|
||||
end
|
||||
end
|
||||
local det = aa * bb - ab * ab
|
||||
if math.abs(det) < 1e-9 then
|
||||
return nil, nil
|
||||
end
|
||||
local f = 1 / det
|
||||
local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f
|
||||
local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f
|
||||
return q565(r0, g0, b0), q565(r1, g1, b1)
|
||||
end
|
||||
|
||||
-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode
|
||||
-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels
|
||||
local function colourBlock(out: buffer, o: number, four: boolean)
|
||||
local n, mr, mg, mb = 0, 0, 0, 0
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
n += 1
|
||||
mr += R[i]
|
||||
mg += G[i]
|
||||
mb += B[i]
|
||||
end
|
||||
end
|
||||
if n == 0 then
|
||||
writeu16(out, o, 0)
|
||||
writeu16(out, o + 2, 0)
|
||||
writeu32(out, o + 4, 0xFFFFFFFF)
|
||||
return
|
||||
end
|
||||
mr, mg, mb = mr / n, mg / n, mb / n
|
||||
local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0
|
||||
local same = true
|
||||
local fr, fg, fb = -1, -1, -1
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
if fr < 0 then
|
||||
fr, fg, fb = R[i], G[i], B[i]
|
||||
elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then
|
||||
same = false
|
||||
end
|
||||
local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb
|
||||
crr += dr * dr
|
||||
cgg += dg * dg
|
||||
cbb += db * db
|
||||
crg += dr * dg
|
||||
crb += dr * db
|
||||
cgb += dg * db
|
||||
end
|
||||
end
|
||||
local c0, c1
|
||||
if same then
|
||||
local t = singleTables()
|
||||
local k = if four then 0 else 1
|
||||
local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1]
|
||||
c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8)
|
||||
c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255)
|
||||
local i2 = 2
|
||||
if c0 == c1 then
|
||||
i2 = 0
|
||||
end
|
||||
-- index 2 everywhere (or 0 for an exact endpoint); order fixed below
|
||||
for i = 1, 16 do
|
||||
IDX[i] = if USE[i] then i2 else 3
|
||||
end
|
||||
else
|
||||
-- principal axis
|
||||
local vr, vg, vb = 1, 1, 1
|
||||
for _ = 1, 8 do
|
||||
local nr = crr * vr + crg * vg + crb * vb
|
||||
local ng = crg * vr + cgg * vg + cgb * vb
|
||||
local nb = crb * vr + cgb * vg + cbb * vb
|
||||
local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb))
|
||||
if m < 1e-9 then
|
||||
break
|
||||
end
|
||||
vr, vg, vb = nr / m, ng / m, nb / m
|
||||
end
|
||||
local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
local d = R[i] * vr + G[i] * vg + B[i] * vb
|
||||
if d < lo then
|
||||
lo, li = d, i
|
||||
end
|
||||
if d > hi then
|
||||
hi, hi_ = d, i
|
||||
end
|
||||
end
|
||||
end
|
||||
c0 = q565(R[hi_], G[hi_], B[hi_])
|
||||
c1 = q565(R[li], G[li], B[li])
|
||||
palette(c0, c1, four)
|
||||
local err = assign(four)
|
||||
for i = 1, 16 do
|
||||
BEST[i] = IDX[i]
|
||||
end
|
||||
for _ = 1, 2 do
|
||||
local n0, n1 = refine(four)
|
||||
if not n0 or not n1 then
|
||||
break
|
||||
end
|
||||
palette(n0, n1, four)
|
||||
local e2 = assign(four)
|
||||
if e2 < err then
|
||||
err, c0, c1 = e2, n0, n1
|
||||
for i = 1, 16 do
|
||||
BEST[i] = IDX[i]
|
||||
end
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
for i = 1, 16 do
|
||||
IDX[i] = BEST[i]
|
||||
end
|
||||
end
|
||||
-- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1
|
||||
if four then
|
||||
if c0 < c1 then
|
||||
c0, c1 = c1, c0
|
||||
for i = 1, 16 do
|
||||
local v = IDX[i]
|
||||
IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2
|
||||
end
|
||||
elseif c0 == c1 then
|
||||
for i = 1, 16 do
|
||||
IDX[i] = 0
|
||||
end
|
||||
end
|
||||
elseif c0 > c1 then
|
||||
c0, c1 = c1, c0
|
||||
for i = 1, 16 do
|
||||
local v = IDX[i]
|
||||
IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v
|
||||
end
|
||||
end
|
||||
writeu16(out, o, c0)
|
||||
writeu16(out, o + 2, c1)
|
||||
local bitsv = 0
|
||||
for i = 16, 1, -1 do
|
||||
bitsv = bitsv * 4 + IDX[i]
|
||||
end
|
||||
writeu32(out, o + 4, bitsv)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC4 channel
|
||||
local V = table.create(16, 0)
|
||||
local RAMP = table.create(8, 0)
|
||||
local SEL = table.create(16, 0)
|
||||
local SELB = table.create(16, 0)
|
||||
|
||||
local function ramp(a0: number, a1: number)
|
||||
RAMP[1], RAMP[2] = a0, a1
|
||||
if a0 > a1 then
|
||||
for i = 1, 6 do
|
||||
RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7
|
||||
end
|
||||
else
|
||||
for i = 1, 4 do
|
||||
RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5
|
||||
end
|
||||
RAMP[7], RAMP[8] = 0, 255
|
||||
end
|
||||
end
|
||||
|
||||
local function pick(): number
|
||||
local total = 0
|
||||
for i = 1, 16 do
|
||||
local v = V[i]
|
||||
local bi, be = 0, math.huge
|
||||
for k = 1, 8 do
|
||||
local d = v - RAMP[k]
|
||||
local e = d * d
|
||||
if e < be then
|
||||
be, bi = e, k - 1
|
||||
end
|
||||
end
|
||||
SEL[i] = bi
|
||||
total += be
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o]
|
||||
local function channelBlock(out: buffer, o: number)
|
||||
local lo, hi = 255, 0
|
||||
local lo2, hi2 = 255, 0
|
||||
for i = 1, 16 do
|
||||
local v = V[i]
|
||||
lo, hi = math.min(lo, v), math.max(hi, v)
|
||||
if v > 0 and v < 255 then
|
||||
lo2, hi2 = math.min(lo2, v), math.max(hi2, v)
|
||||
end
|
||||
end
|
||||
local a0, a1
|
||||
if lo == hi then
|
||||
a0, a1 = lo, lo
|
||||
ramp(a0, a1)
|
||||
pick()
|
||||
else
|
||||
-- 8-value ramp, then a few nudged endpoints
|
||||
local bestErr, b0, b1 = math.huge, hi, lo
|
||||
for d0 = 0, 1 do
|
||||
for d1 = 0, 1 do
|
||||
local x0, x1 = hi - d0, lo + d1
|
||||
if x0 > x1 then
|
||||
ramp(x0, x1)
|
||||
local e = pick()
|
||||
if e < bestErr then
|
||||
bestErr, b0, b1 = e, x0, x1
|
||||
for i = 1, 16 do
|
||||
SELB[i] = SEL[i]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- 6-value ramp with the 0 / 255 extremes
|
||||
if lo2 > hi2 then
|
||||
lo2, hi2 = lo, lo
|
||||
end
|
||||
ramp(lo2, hi2)
|
||||
local e = pick()
|
||||
if e < bestErr then
|
||||
bestErr, b0, b1 = e, lo2, hi2
|
||||
for i = 1, 16 do
|
||||
SELB[i] = SEL[i]
|
||||
end
|
||||
end
|
||||
a0, a1 = b0, b1
|
||||
for i = 1, 16 do
|
||||
SEL[i] = SELB[i]
|
||||
end
|
||||
end
|
||||
writeu8(out, o, a0)
|
||||
writeu8(out, o + 1, a1)
|
||||
local lo24, hi24 = 0, 0
|
||||
for i = 8, 1, -1 do
|
||||
lo24 = lo24 * 8 + SEL[i]
|
||||
hi24 = hi24 * 8 + SEL[i + 8]
|
||||
end
|
||||
writeu8(out, o + 2, band(lo24, 255))
|
||||
writeu8(out, o + 3, band(rshift(lo24, 8), 255))
|
||||
writeu8(out, o + 4, rshift(lo24, 16))
|
||||
writeu8(out, o + 5, band(hi24, 255))
|
||||
writeu8(out, o + 6, band(rshift(hi24, 8), 255))
|
||||
writeu8(out, o + 7, rshift(hi24, 16))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ whole images
|
||||
-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat)
|
||||
local function gather(px: buffer, w: number, h: number, bx: number, by: number)
|
||||
for y = 0, 3 do
|
||||
local sy = math.min(by * 4 + y, h - 1)
|
||||
for x = 0, 3 do
|
||||
local sx = math.min(bx * 4 + x, w - 1)
|
||||
local s = (sy * w + sx) * 4
|
||||
local i = y * 4 + x + 1
|
||||
R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5)
|
||||
function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16
|
||||
local out = buffer.create(bw * bh * bytes)
|
||||
local o = 0
|
||||
for by = 0, bh - 1 do
|
||||
for bx = 0, bw - 1 do
|
||||
gather(px, w, h, bx, by)
|
||||
if kind == "bc1" then
|
||||
local any = false
|
||||
for i = 1, 16 do
|
||||
local u = A[i] >= threshold
|
||||
USE[i] = u
|
||||
any = any or not u
|
||||
end
|
||||
colourBlock(out, o, not any)
|
||||
elseif kind == "bc3" then
|
||||
for i = 1, 16 do
|
||||
USE[i] = true
|
||||
V[i] = A[i]
|
||||
end
|
||||
channelBlock(out, o)
|
||||
colourBlock(out, o + 8, true)
|
||||
elseif kind == "bc4" then
|
||||
for i = 1, 16 do
|
||||
V[i] = R[i]
|
||||
end
|
||||
channelBlock(out, o)
|
||||
else
|
||||
for i = 1, 16 do
|
||||
V[i] = R[i]
|
||||
end
|
||||
channelBlock(out, o)
|
||||
for i = 1, 16 do
|
||||
V[i] = G[i]
|
||||
end
|
||||
channelBlock(out, o + 8)
|
||||
end
|
||||
o += bytes
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,121 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
|
||||
-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2,
|
||||
-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM).
|
||||
-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws.
|
||||
--
|
||||
-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs)
|
||||
-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks)
|
||||
-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks)
|
||||
--
|
||||
-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by
|
||||
-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below
|
||||
-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode.
|
||||
local Decode = require("@formats/codecs/image/Bcn/Decode")
|
||||
local Encode = require("@formats/codecs/image/Bcn/Encode")
|
||||
|
||||
local Bcn = {}
|
||||
|
||||
-- kind -> bytes per 4x4 block
|
||||
Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number }
|
||||
-- kinds that decode to rgbaf32
|
||||
Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean }
|
||||
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
|
||||
local BLOCKS: { [string]: (buffer, number, buffer) -> () } = {
|
||||
bc1 = Decode.bc1,
|
||||
bc2 = Decode.bc2,
|
||||
bc3 = Decode.bc3,
|
||||
bc4 = Decode.bc4,
|
||||
bc4s = Decode.bc4s,
|
||||
bc5 = Decode.bc5,
|
||||
bc5s = Decode.bc5s,
|
||||
bc7 = Decode.bc7,
|
||||
bc6h = function(src: buffer, p: number, blk: buffer)
|
||||
Decode.bc6h(src, p, blk, false)
|
||||
end,
|
||||
bc6hs = function(src: buffer, p: number, blk: buffer)
|
||||
Decode.bc6h(src, p, blk, true)
|
||||
end,
|
||||
}
|
||||
|
||||
-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind)
|
||||
function Bcn.size(kind: string, w: number, h: number): number?
|
||||
local b = Bcn.BLOCK[kind]
|
||||
if not b then
|
||||
return nil
|
||||
end
|
||||
return ((w + 3) // 4) * ((h + 3) // 4) * b
|
||||
end
|
||||
|
||||
-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message.
|
||||
-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer.
|
||||
function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?)
|
||||
local fn = BLOCKS[kind]
|
||||
if not fn then
|
||||
return nil, "unsupported: unknown block format " .. tostring(kind)
|
||||
end
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, "bad image size"
|
||||
end
|
||||
local need = Bcn.size(kind, w, h) :: number
|
||||
if offset < 0 or offset + need > buffer.len(src) then
|
||||
return nil, "truncated: block data runs past the end"
|
||||
end
|
||||
local float = Bcn.FLOAT[kind] == true
|
||||
local bpp = if float then 16 else 4
|
||||
local oo = outOffset or 0
|
||||
local dst = out or buffer.create(w * h * bpp)
|
||||
if oo + w * h * bpp > buffer.len(dst) then
|
||||
return nil, "output buffer too small"
|
||||
end
|
||||
local bytes = Bcn.BLOCK[kind]
|
||||
local blk = buffer.create(16 * bpp)
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local p = offset
|
||||
local rowBytes = w * bpp
|
||||
for by = 0, bh - 1 do
|
||||
local rows = math.min(4, h - by * 4)
|
||||
for bx = 0, bw - 1 do
|
||||
fn(src, p, blk)
|
||||
p += bytes
|
||||
local cols = math.min(4, w - bx * 4)
|
||||
local base = oo + (by * 4) * rowBytes + bx * 4 * bpp
|
||||
if cols == 4 and not float then
|
||||
for y = 0, rows - 1 do
|
||||
local d, s = base + y * rowBytes, y * 16
|
||||
writeu32(dst, d, readu32(blk, s))
|
||||
writeu32(dst, d + 4, readu32(blk, s + 4))
|
||||
writeu32(dst, d + 8, readu32(blk, s + 8))
|
||||
writeu32(dst, d + 12, readu32(blk, s + 12))
|
||||
end
|
||||
else
|
||||
for y = 0, rows - 1 do
|
||||
buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return dst, nil
|
||||
end
|
||||
|
||||
export type EncodeOptions = {
|
||||
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque)
|
||||
}
|
||||
|
||||
-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5.
|
||||
function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?)
|
||||
if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then
|
||||
return nil, "unsupported: no encoder for " .. tostring(kind)
|
||||
end
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then
|
||||
return nil, "needs w x h rgba8 pixels"
|
||||
end
|
||||
local t = opts and opts.alphaThreshold or 128
|
||||
return Encode.run(kind, px, w, h, t), nil
|
||||
end
|
||||
|
||||
return Bcn
|
||||
@@ -0,0 +1,315 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar
|
||||
-- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11
|
||||
-- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new
|
||||
-- in formats-luau. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead.
|
||||
--
|
||||
-- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels
|
||||
-- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits)
|
||||
-- Etc.size("etc1", w, h) -- bytes of the block data
|
||||
--
|
||||
-- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b),
|
||||
-- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535).
|
||||
local Etc = {}
|
||||
|
||||
Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number }
|
||||
|
||||
local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tables
|
||||
local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b
|
||||
{ 2, 8, -2, -8 },
|
||||
{ 5, 17, -5, -17 },
|
||||
{ 9, 29, -9, -29 },
|
||||
{ 13, 42, -13, -42 },
|
||||
{ 18, 60, -18, -60 },
|
||||
{ 24, 80, -24, -80 },
|
||||
{ 33, 106, -33, -106 },
|
||||
{ 47, 183, -47, -183 },
|
||||
}
|
||||
local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances
|
||||
local EAC = {
|
||||
{ -3, -6, -9, -15, 2, 5, 8, 14 },
|
||||
{ -3, -7, -10, -13, 2, 6, 9, 12 },
|
||||
{ -2, -5, -8, -13, 1, 4, 7, 12 },
|
||||
{ -2, -4, -6, -13, 1, 3, 5, 12 },
|
||||
{ -3, -6, -8, -12, 2, 5, 7, 11 },
|
||||
{ -3, -7, -9, -11, 2, 6, 8, 10 },
|
||||
{ -4, -7, -8, -11, 3, 6, 7, 10 },
|
||||
{ -3, -5, -8, -11, 2, 4, 7, 10 },
|
||||
{ -2, -6, -8, -10, 1, 5, 7, 9 },
|
||||
{ -2, -5, -8, -10, 1, 4, 7, 9 },
|
||||
{ -2, -4, -8, -10, 1, 3, 7, 9 },
|
||||
{ -2, -5, -7, -10, 1, 4, 6, 9 },
|
||||
{ -3, -4, -7, -10, 2, 3, 6, 9 },
|
||||
{ -1, -2, -3, -10, 0, 1, 2, 9 },
|
||||
{ -4, -6, -8, -9, 3, 5, 7, 8 },
|
||||
{ -3, -5, -7, -9, 2, 4, 6, 8 },
|
||||
}
|
||||
|
||||
local function clamp8(v: number): number
|
||||
return if v < 0 then 0 elseif v > 255 then 255 else v
|
||||
end
|
||||
local function rgb(r: number, g: number, b: number): number
|
||||
return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ colour blocks
|
||||
-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x)
|
||||
local P = table.create(4, 0) -- T / H paint colours (rgba8 u32)
|
||||
|
||||
local function be32(src: buffer, p: number): number
|
||||
return byteswap(readu32(src, p))
|
||||
end
|
||||
|
||||
-- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y)
|
||||
local function pix(lo: number, i: number): number
|
||||
return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1)
|
||||
end
|
||||
|
||||
-- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque).
|
||||
local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean)
|
||||
local hi, lo = be32(src, p), be32(src, p + 4)
|
||||
local diffBit = band(rshift(hi, 1), 1)
|
||||
local flip = band(hi, 1)
|
||||
local opaque = not punch or diffBit == 1
|
||||
local r1, g1, b1, r2, g2, b2
|
||||
if not punch and diffBit == 0 then
|
||||
r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17
|
||||
g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17
|
||||
b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17
|
||||
else
|
||||
local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31)
|
||||
local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7)
|
||||
if dR >= 4 then
|
||||
dR -= 8
|
||||
end
|
||||
if dG >= 4 then
|
||||
dG -= 8
|
||||
end
|
||||
if dB >= 4 then
|
||||
dB -= 8
|
||||
end
|
||||
local R2, G2, B2 = R + dR, G + dG, B + dB
|
||||
if etc2 and (R2 < 0 or R2 > 31) then
|
||||
-- T mode
|
||||
local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3)
|
||||
local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17
|
||||
local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17
|
||||
local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1]
|
||||
P[1] = rgb(c1r, c1g, c1b)
|
||||
P[2] = rgb(c2r + d, c2g + d, c2b + d)
|
||||
P[3] = rgb(c2r, c2g, c2b)
|
||||
P[4] = rgb(c2r - d, c2g - d, c2b - d)
|
||||
elseif etc2 and (G2 < 0 or G2 > 31) then
|
||||
-- H mode
|
||||
local q1r = band(rshift(hi, 27), 15)
|
||||
local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1)
|
||||
local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7)
|
||||
local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15)
|
||||
local order = if q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b then 1 else 0
|
||||
local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1]
|
||||
local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17
|
||||
P[1] = rgb(c1r + d, c1g + d, c1b + d)
|
||||
P[2] = rgb(c1r - d, c1g - d, c1b - d)
|
||||
P[3] = rgb(c2r + d, c2g + d, c2b + d)
|
||||
P[4] = rgb(c2r - d, c2g - d, c2b - d)
|
||||
elseif etc2 and (B2 < 0 or B2 > 31) then
|
||||
-- planar (always opaque)
|
||||
local ro = band(rshift(hi, 25), 63)
|
||||
local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63)
|
||||
local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7)
|
||||
local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1)
|
||||
local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63)
|
||||
local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63)
|
||||
ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4)
|
||||
go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6)
|
||||
bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4)
|
||||
for y = 0, 3 do
|
||||
for x = 0, 3 do
|
||||
local r = (x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) // 4
|
||||
local g = (x * (gh - go) + y * (gv - go) + 4 * go + 2) // 4
|
||||
local b = (x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) // 4
|
||||
writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b))
|
||||
end
|
||||
end
|
||||
return
|
||||
else
|
||||
r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2)
|
||||
r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2)
|
||||
end
|
||||
if not r1 then
|
||||
-- T / H: the paint colours by index
|
||||
for i = 0, 15 do
|
||||
local x, y = rshift(i, 2), band(i, 3)
|
||||
local idx = pix(lo, i)
|
||||
local c = if not opaque and idx == 2 then 0 else P[idx + 1]
|
||||
writeu32(blk, (y * 4 + x) * 4, c)
|
||||
end
|
||||
return
|
||||
end
|
||||
end
|
||||
local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1]
|
||||
for i = 0, 15 do
|
||||
local x, y = rshift(i, 2), band(i, 3)
|
||||
local second = if flip == 0 then x >= 2 else y >= 2
|
||||
local idx = pix(lo, i)
|
||||
local c
|
||||
if not opaque and idx == 2 then
|
||||
c = 0
|
||||
else
|
||||
local m = if second then t2[idx + 1] else t1[idx + 1]
|
||||
if not opaque and idx == 0 then
|
||||
m = 0
|
||||
end
|
||||
if second then
|
||||
c = rgb((r2 :: number) + m, (g2 :: number) + m, (b2 :: number) + m)
|
||||
else
|
||||
c = rgb((r1 :: number) + m, (g1 :: number) + m, (b1 :: number) + m)
|
||||
end
|
||||
end
|
||||
writeu32(blk, (y * 4 + x) * 4, c)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ EAC
|
||||
local VALS = table.create(16, 0)
|
||||
|
||||
-- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit)
|
||||
local function eac(src: buffer, p: number, mode: string)
|
||||
local base = readu8(src, p)
|
||||
local b1 = readu8(src, p + 1)
|
||||
local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1]
|
||||
-- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits
|
||||
local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4)
|
||||
local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7)
|
||||
if mode == "s11" then
|
||||
if base >= 128 then
|
||||
base -= 256
|
||||
end
|
||||
if base == -128 then
|
||||
base = -127
|
||||
end
|
||||
end
|
||||
for i = 0, 15 do
|
||||
local idx = if i < 8 then band(rshift(hiIdx, 21 - i * 3), 7) else band(rshift(loIdx, 21 - (i - 8) * 3), 7)
|
||||
local m = tab[idx + 1]
|
||||
local v
|
||||
if mode == "alpha" then
|
||||
v = clamp8(base + m * mult)
|
||||
elseif mode == "u11" then
|
||||
v = if mult == 0 then base * 8 + 4 + m else base * 8 + 4 + m * mult * 8
|
||||
v = if v < 0 then 0 elseif v > 2047 then 2047 else v
|
||||
else
|
||||
v = if mult == 0 then base * 8 + m else base * 8 + m * mult * 8
|
||||
v = if v < -1023 then -1023 elseif v > 1023 then 1023 else v
|
||||
end
|
||||
VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v
|
||||
end
|
||||
end
|
||||
|
||||
-- 11-bit values -> 8 / 16 bits
|
||||
local function to8(v: number, signed: boolean): number
|
||||
if signed then
|
||||
return math.floor(v * 127 / 1023 + 0.5) + 128
|
||||
end
|
||||
return math.floor(v * 255 / 2047 + 0.5)
|
||||
end
|
||||
local function to16(v: number, signed: boolean): number
|
||||
if signed then
|
||||
return math.floor((v + 1023) * 65535 / 2046 + 0.5)
|
||||
end
|
||||
return v * 32 + rshift(v, 6)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- size(kind, w, h) -> bytes of the block data | nil for an unknown kind
|
||||
function Etc.size(kind: string, w: number, h: number): number?
|
||||
local b = Etc.BLOCK[kind]
|
||||
return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil
|
||||
end
|
||||
|
||||
-- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC
|
||||
-- kinds when wide is true.
|
||||
function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?)
|
||||
local bytes = Etc.BLOCK[kind]
|
||||
if not bytes then
|
||||
return nil, "unsupported: unknown block format " .. tostring(kind)
|
||||
end
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, "bad image size"
|
||||
end
|
||||
local need = Etc.size(kind, w, h) :: number
|
||||
if offset < 0 or offset + need > buffer.len(src) then
|
||||
return nil, "truncated: block data runs past the end"
|
||||
end
|
||||
local isEac = string.sub(kind, 1, 3) == "eac"
|
||||
local w16 = isEac and wide == true
|
||||
local bpp = if w16 then 8 else 4
|
||||
local oo = outOffset or 0
|
||||
local dst = out or buffer.create(w * h * bpp)
|
||||
if oo + w * h * bpp > buffer.len(dst) then
|
||||
return nil, "output buffer too small"
|
||||
end
|
||||
local signed = kind == "eac_r11s" or kind == "eac_rg11s"
|
||||
local two = kind == "eac_rg11" or kind == "eac_rg11s"
|
||||
local mode11 = if signed then "s11" else "u11"
|
||||
local etc2 = kind ~= "etc1"
|
||||
local punch = kind == "etc2_rgba1"
|
||||
local blk = buffer.create(16 * bpp)
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local p = offset
|
||||
local rowBytes = w * bpp
|
||||
for by = 0, bh - 1 do
|
||||
local rows = math.min(4, h - by * 4)
|
||||
for bx = 0, bw - 1 do
|
||||
if isEac then
|
||||
eac(src, p, mode11)
|
||||
for i = 0, 15 do
|
||||
local v = VALS[i + 1]
|
||||
if w16 then
|
||||
local q = to16(v, signed)
|
||||
writeu16(blk, i * 8, q)
|
||||
writeu16(blk, i * 8 + 2, if two then 0 else q)
|
||||
writeu16(blk, i * 8 + 4, if two then 0 else q)
|
||||
writeu16(blk, i * 8 + 6, 65535)
|
||||
else
|
||||
local q = to8(v, signed)
|
||||
writeu32(blk, i * 4, if two then q + 0xFF000000 else q + q * 256 + q * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
if two then
|
||||
eac(src, p + 8, mode11)
|
||||
for i = 0, 15 do
|
||||
local v = VALS[i + 1]
|
||||
if w16 then
|
||||
writeu16(blk, i * 8 + 2, to16(v, signed))
|
||||
else
|
||||
writeu8(blk, i * 4 + 1, to8(v, signed))
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif kind == "etc2_rgba" then
|
||||
colour(src, p + 8, blk, true, false)
|
||||
eac(src, p, "alpha")
|
||||
for i = 0, 15 do
|
||||
writeu8(blk, i * 4 + 3, VALS[i + 1])
|
||||
end
|
||||
else
|
||||
colour(src, p, blk, etc2, punch)
|
||||
end
|
||||
p += bytes
|
||||
local cols = math.min(4, w - bx * 4)
|
||||
local base = oo + (by * 4) * rowBytes + bx * 4 * bpp
|
||||
for y = 0, rows - 1 do
|
||||
buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
return dst, nil
|
||||
end
|
||||
|
||||
return Etc
|
||||
@@ -0,0 +1,74 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H,
|
||||
-- OpenEXR HALF channels). New in formats-luau. Never throws.
|
||||
--
|
||||
-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table)
|
||||
-- local f = Half.toFloat(h) -- the same, computed
|
||||
-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN
|
||||
local Half = {}
|
||||
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
|
||||
-- toFloat(h) -> number (h a 16-bit pattern)
|
||||
local function toFloat(h: number): number
|
||||
local s = if h >= 32768 then -1 else 1
|
||||
local e = band(rshift(h, 10), 31)
|
||||
local m = band(h, 1023)
|
||||
if e == 0 then
|
||||
return s * m * 2 ^ -24
|
||||
elseif e == 31 then
|
||||
return if m == 0 then s * math.huge else 0 / 0
|
||||
end
|
||||
return s * (1024 + m) * 2 ^ (e - 25)
|
||||
end
|
||||
Half.toFloat = toFloat
|
||||
|
||||
local TABLE: { [number]: number } = table.create(65536, 0)
|
||||
for h = 0, 65535 do
|
||||
TABLE[h] = toFloat(h)
|
||||
end
|
||||
Half.TABLE = TABLE
|
||||
|
||||
local scratch = buffer.create(4)
|
||||
|
||||
-- fromFloat(f) -> the nearest half bit pattern (ties to even)
|
||||
function Half.fromFloat(f: number): number
|
||||
if f ~= f then
|
||||
return 0x7E00
|
||||
end
|
||||
buffer.writef32(scratch, 0, f)
|
||||
local x = buffer.readu32(scratch, 0)
|
||||
local sign = band(rshift(x, 16), 0x8000)
|
||||
local e = band(rshift(x, 23), 0xFF)
|
||||
local m = band(x, 0x7FFFFF)
|
||||
if e == 255 then
|
||||
return bor(sign, 0x7C00)
|
||||
end
|
||||
local ne = e - 112
|
||||
if ne >= 31 then
|
||||
return bor(sign, 0x7C00)
|
||||
elseif ne <= 0 then
|
||||
if ne < -10 then
|
||||
return sign
|
||||
end
|
||||
m = bor(m, 0x800000)
|
||||
local shift = 14 - ne
|
||||
local hm = rshift(m, shift)
|
||||
local rem = band(m, lshift(1, shift) - 1)
|
||||
local halfway = lshift(1, shift - 1)
|
||||
if rem > halfway or (rem == halfway and band(hm, 1) == 1) then
|
||||
hm += 1
|
||||
end
|
||||
return sign + hm
|
||||
end
|
||||
local hm = rshift(m, 13)
|
||||
local rem = band(m, 0x1FFF)
|
||||
if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then
|
||||
hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should
|
||||
end
|
||||
return sign + ne * 1024 + hm
|
||||
end
|
||||
|
||||
return Half
|
||||
@@ -0,0 +1,398 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
|
||||
-- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in formats-luau. Formats are named
|
||||
-- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8,
|
||||
-- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones:
|
||||
-- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other
|
||||
-- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws.
|
||||
--
|
||||
-- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels
|
||||
-- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit)
|
||||
-- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode
|
||||
--
|
||||
-- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque.
|
||||
-- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped
|
||||
-- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32
|
||||
-- (snorm -> -1..1, integers as their values).
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Texel = {}
|
||||
|
||||
export type Channel = { c: string, shift: number, bits: number } -- packed channels (c = r g b a l)
|
||||
export type Desc = {
|
||||
bytes: number, -- per texel
|
||||
kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv",
|
||||
size: number?, -- array: bytes per component (1, 2, 4)
|
||||
type: string?, -- array: unorm / snorm / uint / sint / float
|
||||
order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb)
|
||||
channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word
|
||||
}
|
||||
|
||||
local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32
|
||||
local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ formats
|
||||
local FORMATS: { [string]: Desc } = {}
|
||||
local function array(name: string, size: number, typ: string, order: string)
|
||||
FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order }
|
||||
end
|
||||
for _, o in { "r", "rg", "rgb", "rgba" } do
|
||||
array(o .. "8", 1, "unorm", o)
|
||||
array(o .. "8s", 1, "snorm", o)
|
||||
array(o .. "8ui", 1, "uint", o)
|
||||
array(o .. "8i", 1, "sint", o)
|
||||
array(o .. "16", 2, "unorm", o)
|
||||
array(o .. "16s", 2, "snorm", o)
|
||||
array(o .. "16ui", 2, "uint", o)
|
||||
array(o .. "16i", 2, "sint", o)
|
||||
array(o .. "16f", 2, "float", o)
|
||||
array(o .. "32ui", 4, "uint", o)
|
||||
array(o .. "32i", 4, "sint", o)
|
||||
array(o .. "32f", 4, "float", o)
|
||||
end
|
||||
array("bgr8", 1, "unorm", "bgr")
|
||||
array("bgra8", 1, "unorm", "bgra")
|
||||
array("bgrx8", 1, "unorm", "bgrx")
|
||||
array("rgbx8", 1, "unorm", "rgbx")
|
||||
array("a8", 1, "unorm", "a")
|
||||
array("l8", 1, "unorm", "l")
|
||||
array("la8", 1, "unorm", "la")
|
||||
array("l16", 2, "unorm", "l")
|
||||
array("la16", 2, "unorm", "la")
|
||||
array("a16", 2, "unorm", "a")
|
||||
|
||||
local function packed(name: string, bytes: number, spec: { any })
|
||||
local ch: { Channel } = {}
|
||||
for i = 1, #spec, 3 do
|
||||
table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] })
|
||||
end
|
||||
FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch }
|
||||
end
|
||||
packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 })
|
||||
packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 })
|
||||
packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 })
|
||||
packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 })
|
||||
packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 })
|
||||
packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 })
|
||||
packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 })
|
||||
packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 })
|
||||
packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 })
|
||||
packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 })
|
||||
packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 })
|
||||
packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 })
|
||||
packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 })
|
||||
FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" }
|
||||
FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" }
|
||||
-- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range
|
||||
FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" }
|
||||
FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" }
|
||||
FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" }
|
||||
FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" }
|
||||
FORMATS.ayuv = { bytes = 4, kind = "ayuv" }
|
||||
Texel.FORMATS = FORMATS
|
||||
|
||||
-- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance:
|
||||
-- the r mask is a luminance channel
|
||||
function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc?
|
||||
if bytes < 1 or bytes > 4 then
|
||||
return nil
|
||||
end
|
||||
local ch: { Channel } = {}
|
||||
for i, m in { r, g, b, a } do
|
||||
if m ~= 0 then
|
||||
local shift = 0
|
||||
while band(m, lshift(1, shift)) == 0 and shift < 31 do
|
||||
shift += 1
|
||||
end
|
||||
local bits = 0
|
||||
while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do
|
||||
bits += 1
|
||||
end
|
||||
local name = if i == 1 then (if luminance then "l" else "r") elseif i == 2 then "g" elseif i == 3 then "b" else "a"
|
||||
table.insert(ch, { c = name, shift = shift, bits = bits })
|
||||
end
|
||||
end
|
||||
if #ch == 0 then
|
||||
return nil
|
||||
end
|
||||
return { bytes = bytes, kind = "packed", channels = ch }
|
||||
end
|
||||
|
||||
-- size(fmt, w, h) -> bytes (rows tightly packed) | nil
|
||||
function Texel.size(fmt: string | Desc, w: number, h: number): number?
|
||||
local d = if type(fmt) == "string" then FORMATS[fmt] else fmt
|
||||
if not d then
|
||||
return nil
|
||||
end
|
||||
return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
-- the native output of a descriptor: rgba8 / rgba16 / rgbaf32
|
||||
local function nativeOf(d: Desc): string
|
||||
if d.kind == "array" then
|
||||
local t, s = d.type, d.size :: number
|
||||
if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then
|
||||
return "rgbaf32"
|
||||
end
|
||||
return if s == 1 then "rgba8" else "rgba16"
|
||||
elseif d.kind == "packed" then
|
||||
local wide = false
|
||||
for _, c in d.channels :: { Channel } do
|
||||
wide = wide or c.bits > 8
|
||||
end
|
||||
return if wide then "rgba16" else "rgba8"
|
||||
end
|
||||
return "rgbaf32"
|
||||
end
|
||||
Texel.nativeOf = nativeOf
|
||||
|
||||
local function uf11(v: number): number
|
||||
local e, m = rshift(v, 6), band(v, 63)
|
||||
if e == 0 then
|
||||
return m / 64 * 2 ^ -14
|
||||
elseif e == 31 then
|
||||
return if m == 0 then math.huge else 0 / 0
|
||||
end
|
||||
return (1 + m / 64) * 2 ^ (e - 15)
|
||||
end
|
||||
local function uf10(v: number): number
|
||||
local e, m = rshift(v, 5), band(v, 31)
|
||||
if e == 0 then
|
||||
return m / 32 * 2 ^ -14
|
||||
elseif e == 31 then
|
||||
return if m == 0 then math.huge else 0 / 0
|
||||
end
|
||||
return (1 + m / 32) * 2 ^ (e - 15)
|
||||
end
|
||||
|
||||
-- one component at q of an array format -> a float (native meaning) and its rgba8 byte
|
||||
local function component(src: buffer, q: number, size: number, typ: string): (number, number)
|
||||
if typ == "unorm" then
|
||||
if size == 1 then
|
||||
local v = readu8(src, q)
|
||||
return v / 255, v
|
||||
elseif size == 2 then
|
||||
local v = readu16(src, q)
|
||||
return v / 65535, (v * 255 + 32767) // 65535
|
||||
end
|
||||
local v = readu32(src, q)
|
||||
return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5)
|
||||
elseif typ == "snorm" then
|
||||
if size == 1 then
|
||||
local v = math.max(readi8(src, q), -127)
|
||||
return v / 127, v + 128
|
||||
elseif size == 2 then
|
||||
local v = math.max(readi16(src, q), -32767)
|
||||
return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128
|
||||
end
|
||||
local v = math.max(readi32(src, q), -2147483647)
|
||||
return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128
|
||||
elseif typ == "float" then
|
||||
local f = if size == 2 then HALF[readu16(src, q)] else readf32(src, q)
|
||||
local c = if f ~= f then 0 elseif f < 0 then 0 elseif f > 1 then 1 else f
|
||||
return f, math.floor(c * 255 + 0.5)
|
||||
elseif typ == "uint" then
|
||||
local v = if size == 1 then readu8(src, q) elseif size == 2 then readu16(src, q) else readu32(src, q)
|
||||
return v, math.min(v, 255)
|
||||
end
|
||||
local v = if size == 1 then readi8(src, q) elseif size == 2 then readi16(src, q) else readi32(src, q)
|
||||
return v, math.clamp(v, 0, 255)
|
||||
end
|
||||
|
||||
-- BT.601 limited-range Y'CbCr -> an rgba8 u32
|
||||
local function ycc(y: number, u: number, v: number, a: number): number
|
||||
local c, d, e = 1.164 * (y - 16), u - 128, v - 128
|
||||
local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255)
|
||||
local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255)
|
||||
local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255)
|
||||
return r + g * 256 + b * 65536 + a * 16777216
|
||||
end
|
||||
|
||||
-- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources)
|
||||
local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer
|
||||
local n = 0
|
||||
local order = d.order or ""
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for x = 0, w - 1 do
|
||||
if d.kind == "ayuv" then
|
||||
local q = s + x * 4
|
||||
writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3)))
|
||||
else
|
||||
local q = s + (x // 2) * 4
|
||||
local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3)
|
||||
local odd = x % 2 == 1
|
||||
if order == "yuyv" then
|
||||
writeu32(dst, n, ycc(if odd then b2 else b0, b1, b3, 255))
|
||||
elseif order == "uyvy" then
|
||||
writeu32(dst, n, ycc(if odd then b3 else b1, b0, b2, 255))
|
||||
elseif order == "rgbg" then
|
||||
writeu32(dst, n, b0 + (if odd then b3 else b1) * 256 + b2 * 65536 + 0xFF000000)
|
||||
else
|
||||
writeu32(dst, n, b1 + (if odd then b2 else b0) * 256 + b3 * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
n += 4
|
||||
end
|
||||
end
|
||||
return dst
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil,
|
||||
-- message. rowPitch: bytes per source row (default tight).
|
||||
function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string)
|
||||
local d = if type(fmt) == "string" then FORMATS[fmt] else fmt
|
||||
if not d then
|
||||
return nil, "unsupported: unknown texel format " .. tostring(fmt)
|
||||
end
|
||||
local tb = d.bytes
|
||||
local rowBytes = if d.kind == "pair" then ((w + 1) // 2) * 4 else tb * w
|
||||
local pitch = rowPitch or rowBytes
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then
|
||||
return nil, "bad image size"
|
||||
end
|
||||
if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then
|
||||
return nil, "truncated: texel data runs past the end"
|
||||
end
|
||||
local out = if native and d.kind ~= "pair" and d.kind ~= "ayuv" then nativeOf(d) else "rgba8"
|
||||
local bpp = if out == "rgba8" then 4 elseif out == "rgba16" then 8 else 16
|
||||
local dst = buffer.create(w * h * bpp)
|
||||
local n = 0
|
||||
if d.kind == "array" then
|
||||
local order, size, typ = d.order :: string, d.size :: number, d.type :: string
|
||||
-- fast paths
|
||||
if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then
|
||||
local swap = order == "bgra" or order == "bgrx"
|
||||
local opaque = order == "bgrx" or order == "rgbx"
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for x = 0, w - 1 do
|
||||
local v = readu32(src, s + x * 4)
|
||||
if swap then
|
||||
v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16)
|
||||
end
|
||||
if opaque then
|
||||
v = band(v, 0xFFFFFF) + 0xFF000000
|
||||
end
|
||||
writeu32(dst, n, v)
|
||||
n += 4
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
end
|
||||
local nc = #order
|
||||
local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip
|
||||
for i = 1, nc do
|
||||
local c = string.sub(order, i, i)
|
||||
map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1
|
||||
end
|
||||
local f = table.create(4, 0)
|
||||
local q8 = table.create(4, 0)
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for _ = 0, w - 1 do
|
||||
f[1], f[2], f[3], f[4] = 0, 0, 0, 1
|
||||
q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255
|
||||
for i = 1, nc do
|
||||
local m = map[i]
|
||||
if m >= 0 then
|
||||
local fv, bv = component(src, s, size, typ)
|
||||
if m == 4 then
|
||||
f[1], f[2], f[3] = fv, fv, fv
|
||||
q8[1], q8[2], q8[3] = bv, bv, bv
|
||||
else
|
||||
f[m + 1], q8[m + 1] = fv, bv
|
||||
end
|
||||
end
|
||||
s += size
|
||||
end
|
||||
if out == "rgba8" then
|
||||
writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216)
|
||||
elseif out == "rgba16" then
|
||||
for c = 0, 3 do
|
||||
writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5))
|
||||
end
|
||||
else
|
||||
for c = 0, 3 do
|
||||
writef32(dst, n + c * 4, f[c + 1])
|
||||
end
|
||||
end
|
||||
n += bpp
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
elseif d.kind == "packed" then
|
||||
local chs = d.channels :: { Channel }
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for _ = 0, w - 1 do
|
||||
local v = if tb == 1 then readu8(src, s) elseif tb == 2 then readu16(src, s) elseif tb == 3 then readu16(src, s) + readu8(src, s + 2) * 65536 else readu32(src, s)
|
||||
s += tb
|
||||
local r, g, b, a = 0, 0, 0, 1
|
||||
for _, c in chs do
|
||||
local maxv = lshift(1, c.bits) - 1
|
||||
local x = band(rshift(v, c.shift), maxv) / (if c.bits >= 32 then 4294967295 else maxv)
|
||||
local k = c.c
|
||||
if k == "r" then
|
||||
r = x
|
||||
elseif k == "g" then
|
||||
g = x
|
||||
elseif k == "b" then
|
||||
b = x
|
||||
elseif k == "a" then
|
||||
a = x
|
||||
else
|
||||
r, g, b = x, x, x
|
||||
end
|
||||
end
|
||||
if out == "rgba8" then
|
||||
writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216)
|
||||
else
|
||||
writeu16(dst, n, math.floor(r * 65535 + 0.5))
|
||||
writeu16(dst, n + 2, math.floor(g * 65535 + 0.5))
|
||||
writeu16(dst, n + 4, math.floor(b * 65535 + 0.5))
|
||||
writeu16(dst, n + 6, math.floor(a * 65535 + 0.5))
|
||||
end
|
||||
n += bpp
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
end
|
||||
if d.kind == "pair" or d.kind == "ayuv" then
|
||||
return yuv(d, src, offset, w, h, pitch, dst), out
|
||||
end
|
||||
-- shared-exponent / packed floats
|
||||
local nine = d.kind == "rgb9e5"
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for _ = 0, w - 1 do
|
||||
local v = readu32(src, s)
|
||||
s += 4
|
||||
local sc = if nine then 2 ^ (rshift(v, 27) - 24) else 0
|
||||
local r: number = if nine then band(v, 511) * sc else uf11(band(v, 2047))
|
||||
local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047))
|
||||
local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22))
|
||||
if out == "rgba8" then
|
||||
local function q(x: number): number
|
||||
return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5)
|
||||
end
|
||||
writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000)
|
||||
else
|
||||
writef32(dst, n, r)
|
||||
writef32(dst, n + 4, g)
|
||||
writef32(dst, n + 8, b)
|
||||
writef32(dst, n + 12, 1)
|
||||
end
|
||||
n += bpp
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
end
|
||||
|
||||
return Texel
|
||||
@@ -0,0 +1,162 @@
|
||||
--!strict
|
||||
-- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
|
||||
-- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format
|
||||
-- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one
|
||||
-- Types.Image, halve() makes the next mip level of an image for writers. New in formats-luau. Never throws.
|
||||
--
|
||||
-- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format
|
||||
-- Texture.size("etc2_rgb", w, h) -- bytes of one surface
|
||||
-- local img = Texture.image(px, pf, w, h) -- a Types.Image around them
|
||||
-- local smaller = Texture.halve(img) -- box-filtered next mip level
|
||||
local Types = require("@formats/Types")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Etc = require("@formats/codecs/image/Etc")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Texture = {}
|
||||
|
||||
-- known(name) -> "bcn" | "etc" | "texel" | nil
|
||||
function Texture.known(name: string): string?
|
||||
if Bcn.BLOCK[name] then
|
||||
return "bcn"
|
||||
elseif Etc.BLOCK[name] then
|
||||
return "etc"
|
||||
elseif Texel.FORMATS[name] then
|
||||
return "texel"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- size(name, w, h) -> bytes of a w x h surface | nil
|
||||
function Texture.size(name: string, w: number, h: number): number?
|
||||
return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h)
|
||||
end
|
||||
|
||||
-- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil
|
||||
function Texture.block(name: string): (number?, number?, number?)
|
||||
local b = Bcn.BLOCK[name] or Etc.BLOCK[name]
|
||||
if b then
|
||||
return 4, 4, b
|
||||
end
|
||||
local d = Texel.FORMATS[name]
|
||||
if d then
|
||||
return 1, 1, d.bytes
|
||||
end
|
||||
return nil, nil, nil
|
||||
end
|
||||
|
||||
-- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is
|
||||
-- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm).
|
||||
function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string)
|
||||
if Bcn.BLOCK[name] then
|
||||
local px, err = Bcn.decode(name, src, offset, w, h)
|
||||
if not px then
|
||||
return nil, err or "bad block data"
|
||||
end
|
||||
if Bcn.FLOAT[name] then
|
||||
if native then
|
||||
return px, "rgbaf32"
|
||||
end
|
||||
local out = buffer.create(w * h * 4)
|
||||
for i = 0, w * h - 1 do
|
||||
for c = 0, 3 do
|
||||
local v = buffer.readf32(px, i * 16 + c * 4)
|
||||
buffer.writeu8(out, i * 4 + c, if v ~= v or v <= 0 then 0 elseif v >= 1 then 255 else math.floor(v * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return out, "rgba8"
|
||||
end
|
||||
return px, "rgba8"
|
||||
elseif Etc.BLOCK[name] then
|
||||
local wide = native == true and string.sub(name, 1, 3) == "eac"
|
||||
local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide)
|
||||
if not px then
|
||||
return nil, err or "bad block data"
|
||||
end
|
||||
return px, if wide then "rgba16" else "rgba8"
|
||||
end
|
||||
return Texel.decode(name, src, offset, w, h, native)
|
||||
end
|
||||
|
||||
-- image(pixels, pixel format, w, h) -> Types.Image
|
||||
function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image
|
||||
local img = Types.Image.new(0, 0, pf :: any)
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
return img
|
||||
end
|
||||
|
||||
export type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image }
|
||||
|
||||
-- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces /
|
||||
-- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface
|
||||
function Texture.assemble(list: { Surface }, layout: string): Types.Image?
|
||||
local first: Types.Image? = nil
|
||||
local frames: { Types.Frame } = {}
|
||||
local mips: { Types.Image } = {}
|
||||
for _, s in list do
|
||||
if s.level == 0 then
|
||||
first = first or s.image
|
||||
local fr: Types.Frame = { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
table.insert(frames, fr)
|
||||
elseif s.layer == 0 and s.face == 0 and s.slice == 0 then
|
||||
mips[s.level] = s.image
|
||||
end
|
||||
end
|
||||
if not first then
|
||||
return nil
|
||||
end
|
||||
local img = Texture.image(first.pixels, first.format, first.width, first.height)
|
||||
if #frames > 1 then
|
||||
img.frames = frames
|
||||
end
|
||||
if #mips > 0 then
|
||||
img.meta.mipmaps = mips
|
||||
end
|
||||
img.meta.layout = layout
|
||||
return img
|
||||
end
|
||||
|
||||
-- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format
|
||||
-- (rgba8 / rgba16 / rgbaf32)
|
||||
function Texture.halve(img: Types.Image): Types.Image
|
||||
local w, h = img.width, img.height
|
||||
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
|
||||
local fmt = img.format
|
||||
local out = Types.Image.new(nw, nh, fmt)
|
||||
local src, dst = img.pixels, out.pixels
|
||||
local cs = if fmt == "rgba8" then 1 elseif fmt == "rgba16" then 2 else 4
|
||||
local function get(x: number, y: number, c: number): number
|
||||
local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs
|
||||
return if cs == 1 then buffer.readu8(src, o) elseif cs == 2 then buffer.readu16(src, o) else buffer.readf32(src, o)
|
||||
end
|
||||
for y = 0, nh - 1 do
|
||||
for x = 0, nw - 1 do
|
||||
for c = 0, 3 do
|
||||
local x0, y0 = x * 2, y * 2
|
||||
local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4
|
||||
local o = ((y * nw + x) * 4 + c) * cs
|
||||
if cs == 1 then
|
||||
buffer.writeu8(dst, o, math.floor(v + 0.5))
|
||||
elseif cs == 2 then
|
||||
buffer.writeu16(dst, o, math.floor(v + 0.5))
|
||||
else
|
||||
buffer.writef32(dst, o, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers)
|
||||
function Texture.toHalf(px: buffer, n: number): buffer
|
||||
local out = buffer.create(n * 8)
|
||||
local from = Half.fromFloat
|
||||
for i = 0, n * 4 - 1 do
|
||||
buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4)))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Texture
|
||||
@@ -0,0 +1,183 @@
|
||||
--!strict
|
||||
-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks;
|
||||
-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one,
|
||||
-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files)
|
||||
-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames
|
||||
-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors
|
||||
-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a
|
||||
-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ani = {
|
||||
name = "ani",
|
||||
category = "image",
|
||||
extensions = { "ani" },
|
||||
mime = { "application/x-navi-animation" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
|
||||
caps = { decode = true, encode = true, alpha = true, animation = true, frames = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one)
|
||||
maxFrames: number?, -- refuse more steps (default 10000)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ani.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local f, ferr = Riff.read(r)
|
||||
if not f then
|
||||
return nil, ferr
|
||||
end
|
||||
if f.form ~= "ACON" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8)
|
||||
end
|
||||
local anih = Riff.find(f, "anih")
|
||||
if not anih or anih.avail < 36 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12)
|
||||
end
|
||||
local a = anih.offset
|
||||
local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8)
|
||||
local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32)
|
||||
local maxFrames = opts and opts.maxFrames or 10000
|
||||
if nSteps == 0 then
|
||||
nSteps = nFrames
|
||||
end
|
||||
if nFrames > maxFrames or nSteps > maxFrames then
|
||||
return nil, Err.new(Err.LIMIT, "too many frames", a + 4)
|
||||
end
|
||||
if bit32.band(flags, 1) == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32)
|
||||
end
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
if not decodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook")
|
||||
end
|
||||
-- the icon chunks
|
||||
local icons: { Types.Image } = {}
|
||||
for _, c in f.chunks do
|
||||
if c.id == "LIST" and Riff.listType(f, c) == "fram" then
|
||||
for _, ic in Riff.list(f, c) do
|
||||
if ic.id == "icon" then
|
||||
local sub = buffer.create(ic.avail)
|
||||
buffer.copy(sub, 0, f.buf, ic.offset, ic.avail)
|
||||
local ok, im, ierr = pcall(decodeImage, sub)
|
||||
if not ok or not im then
|
||||
return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring(if ok then ierr else im), ic.offset)
|
||||
end
|
||||
table.insert(icons, im :: Types.Image)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #icons == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no icon frames")
|
||||
end
|
||||
local rate = Riff.find(f, "rate")
|
||||
local seq = Riff.find(f, "seq ")
|
||||
local frames: { Types.Frame } = {}
|
||||
for s = 0, nSteps - 1 do
|
||||
local idx = s
|
||||
if seq and seq.avail >= (s + 1) * 4 then
|
||||
idx = Riff.u32(f, seq.offset + s * 4)
|
||||
end
|
||||
local im = icons[idx + 1]
|
||||
if not im then
|
||||
if s >= #icons and not seq then
|
||||
break -- fewer icons than steps: keep what is there
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx)
|
||||
end
|
||||
local jiffies = dispRate
|
||||
if rate and rate.avail >= (s + 1) * 4 then
|
||||
jiffies = Riff.u32(f, rate.offset + s * 4)
|
||||
end
|
||||
table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame)
|
||||
end
|
||||
local first = frames[1].image
|
||||
local img = Types.Image.new(0, 0, first.format)
|
||||
img.width, img.height, img.pixels = first.width, first.height, first.pixels
|
||||
img.frames = frames
|
||||
img.loops = 0
|
||||
img.meta.hotspot = first.meta.hotspot
|
||||
local text: { [string]: string } = {}
|
||||
for _, c in f.chunks do
|
||||
if c.id == "LIST" and Riff.listType(f, c) == "INFO" then
|
||||
for _, it in Riff.list(f, c) do
|
||||
local key = if it.id == "INAM" then "title" elseif it.id == "IART" then "author" else nil
|
||||
if key then
|
||||
text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", ""))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if next(text) then
|
||||
img.meta.text = text
|
||||
end
|
||||
img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ani.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
if not encodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook")
|
||||
end
|
||||
local frames: { Types.Frame } = if type(img.frames) == "table" and #img.frames > 0 then img.frames else { { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame }
|
||||
local w = Riff.writer("ACON")
|
||||
local jiffies: { number } = {}
|
||||
local same = true
|
||||
for i, fr in frames do
|
||||
jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5))
|
||||
same = same and jiffies[i] == jiffies[1]
|
||||
end
|
||||
local head = Bytes.writer(36)
|
||||
head:u32le(36)
|
||||
head:u32le(#frames)
|
||||
head:u32le(#frames)
|
||||
head:u32le(0)
|
||||
head:u32le(0)
|
||||
head:u32le(0)
|
||||
head:u32le(0)
|
||||
head:u32le(jiffies[1])
|
||||
head:u32le(1)
|
||||
w:chunk("anih", head:finish())
|
||||
if not same then
|
||||
local rw = Bytes.writer(#frames * 4)
|
||||
for _, j in jiffies do
|
||||
rw:u32le(j)
|
||||
end
|
||||
w:chunk("rate", rw:finish())
|
||||
end
|
||||
local items = {}
|
||||
for i, fr in frames do
|
||||
local im = fr.image
|
||||
local ok, data, err = pcall(encodeImage, im, "ico")
|
||||
if not ok or not data then
|
||||
return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring(if ok then err else data))
|
||||
end
|
||||
table.insert(items, { "icon", data })
|
||||
end
|
||||
w:list("fram", items)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
return Ani
|
||||
@@ -0,0 +1,497 @@
|
||||
--!strict
|
||||
-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new
|
||||
-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM /
|
||||
-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the
|
||||
-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the
|
||||
-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six
|
||||
-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there
|
||||
-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" /
|
||||
-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by
|
||||
-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more.
|
||||
-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32
|
||||
-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the
|
||||
-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8),
|
||||
-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Texture = require("@formats/codecs/image/Texture")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Dds = {
|
||||
name = "dds",
|
||||
category = "image",
|
||||
extensions = { "dds" },
|
||||
mime = { "image/vnd-ms.dds", "image/x-dds" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "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" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H 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, counted over every decoded surface)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default:
|
||||
-- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones
|
||||
mips: boolean?, -- write a full mip chain (default false)
|
||||
dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays)
|
||||
cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube")
|
||||
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- DXGI_FORMAT -> texture format name, sRGB
|
||||
local DXGI: { [number]: string } = {
|
||||
[1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i",
|
||||
[5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i",
|
||||
[9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i",
|
||||
[15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i",
|
||||
[23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f",
|
||||
[27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i",
|
||||
[33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i",
|
||||
[39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i",
|
||||
[48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i",
|
||||
[53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i",
|
||||
[60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8",
|
||||
[67] = "rgb9e5", [68] = "rgbg", [69] = "grgb",
|
||||
[70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3",
|
||||
[79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s",
|
||||
[85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8",
|
||||
[94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7",
|
||||
[100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4",
|
||||
}
|
||||
local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true }
|
||||
-- legacy FourCC codes (strings and D3DFMT numbers)
|
||||
local FOURCC: { [string]: string } = {
|
||||
DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3",
|
||||
ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s",
|
||||
YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb",
|
||||
}
|
||||
local D3DFMT: { [number]: string } = {
|
||||
[36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f",
|
||||
[114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s",
|
||||
}
|
||||
local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" }
|
||||
local MAGIC = "DDS "
|
||||
|
||||
local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000
|
||||
local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000
|
||||
local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000
|
||||
local MISC_CUBE = 0x4
|
||||
|
||||
local band = bit32.band
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Dds.sniff(r: Bytes.Reader): number
|
||||
return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
depth: number,
|
||||
mips: number,
|
||||
format: string, -- the texture format name (codecs/image/Texture)
|
||||
layout: string, -- "2d" | "cube" | "array" | "volume"
|
||||
layers: number,
|
||||
faces: { string }, -- cube faces present (in file order), else { }
|
||||
srgb: boolean,
|
||||
dxgi: number?,
|
||||
fourcc: string?,
|
||||
dataOffset: number, -- relative to the file start
|
||||
alphaMode: number?,
|
||||
premultiplied: boolean?,
|
||||
masked: Texel.Desc?, -- legacy bit-mask formats (format = "masked" unless the masks have a name)
|
||||
}
|
||||
|
||||
local function u32(b: buffer, o: number): number
|
||||
return buffer.readu32(b, o)
|
||||
end
|
||||
|
||||
-- info(r) -> Info | nil, Err (the headers only)
|
||||
function Dds.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b, o, n = r.buf, r.base, r.limit - r.base
|
||||
if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then
|
||||
return nil, Err.new(if n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC then Err.TRUNCATED else Err.CORRUPT, "not a DDS file", o)
|
||||
end
|
||||
if u32(b, o + 4) ~= 124 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4)
|
||||
end
|
||||
local flags = u32(b, o + 8)
|
||||
local h, w = u32(b, o + 12), u32(b, o + 16)
|
||||
local depth = u32(b, o + 24)
|
||||
local mips = u32(b, o + 28)
|
||||
local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84)
|
||||
local bitCount = u32(b, o + 88)
|
||||
local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104)
|
||||
local caps2 = u32(b, o + 112)
|
||||
if w == 0 or h == 0 or w > 65536 or h > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12)
|
||||
end
|
||||
if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then
|
||||
mips = 1 -- a count without the flag or the caps bit: some writers leave garbage
|
||||
end
|
||||
mips = math.max(1, mips)
|
||||
local maxMips = 1
|
||||
do
|
||||
local m = math.max(w, h, depth)
|
||||
while m > 1 do
|
||||
m //= 2
|
||||
maxMips += 1
|
||||
end
|
||||
end
|
||||
if mips > maxMips then
|
||||
return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28)
|
||||
end
|
||||
local info: Info = {
|
||||
width = w,
|
||||
height = h,
|
||||
depth = 1,
|
||||
mips = mips,
|
||||
format = "",
|
||||
layout = "2d",
|
||||
layers = 1,
|
||||
faces = {},
|
||||
srgb = false,
|
||||
dataOffset = 128,
|
||||
}
|
||||
local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1
|
||||
if band(pfFlags, DDPF_FOURCC) ~= 0 then
|
||||
local fourcc = buffer.readstring(b, o + 84, 4)
|
||||
if fourcc == "DX10" then
|
||||
if n < 148 then
|
||||
return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128)
|
||||
end
|
||||
local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144)
|
||||
info.dxgi = dxgi
|
||||
info.dataOffset = 148
|
||||
local name = DXGI[dxgi]
|
||||
if not name then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128)
|
||||
end
|
||||
info.format = name
|
||||
info.srgb = SRGB[dxgi] == true
|
||||
info.alphaMode = band(misc2, 7)
|
||||
info.premultiplied = band(misc2, 7) == 2
|
||||
info.layers = math.max(1, arr)
|
||||
if info.layers > 4096 then
|
||||
return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140)
|
||||
end
|
||||
if dim == 4 then
|
||||
volume = true
|
||||
elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132)
|
||||
else
|
||||
volume = false
|
||||
end
|
||||
if band(misc, MISC_CUBE) ~= 0 then
|
||||
info.layout = "cube"
|
||||
info.faces = table.clone(FACES)
|
||||
elseif info.layers > 1 then
|
||||
info.layout = "array"
|
||||
end
|
||||
else
|
||||
info.fourcc = fourcc
|
||||
local name = FOURCC[fourcc] or D3DFMT[fourccNum]
|
||||
if not name then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84)
|
||||
end
|
||||
info.format = name
|
||||
info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4"
|
||||
end
|
||||
elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then
|
||||
local bytes = bitCount // 8
|
||||
if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88)
|
||||
end
|
||||
local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0
|
||||
local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0
|
||||
local a = if band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 then am else 0
|
||||
local d
|
||||
if alphaOnly then
|
||||
d = Texel.masked(bytes, 0, 0, 0, if am ~= 0 then am else 0xFF)
|
||||
elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then
|
||||
d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC
|
||||
else
|
||||
d = Texel.masked(bytes, rm, if lum then 0 else gm, if lum then 0 else bm, a, lum)
|
||||
end
|
||||
if not d then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92)
|
||||
end
|
||||
-- the common masks map onto named texel formats (fast paths, sane names)
|
||||
local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum))
|
||||
local named = ({
|
||||
["32:ff:ff00:ff0000:ff000000:false"] = "rgba8",
|
||||
["32:ff0000:ff00:ff:ff000000:false"] = "bgra8",
|
||||
["32:ff0000:ff00:ff:0:false"] = "bgrx8",
|
||||
["32:ff:ff00:ff0000:0:false"] = "rgbx8",
|
||||
["24:ff0000:ff00:ff:0:false"] = "bgr8",
|
||||
["24:ff:ff00:ff0000:0:false"] = "rgb8",
|
||||
["8:ff:0:0:0:true"] = "l8",
|
||||
["16:ffff:0:0:0:true"] = "l16",
|
||||
} :: { [string]: string })[key]
|
||||
info.format = named or "masked"
|
||||
info.masked = d
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80)
|
||||
end
|
||||
if volume then
|
||||
info.layout = "volume"
|
||||
info.depth = math.max(1, depth)
|
||||
if info.depth > 2048 then
|
||||
return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24)
|
||||
end
|
||||
elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then
|
||||
info.layout = "cube"
|
||||
for i, f in FACES do
|
||||
if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then
|
||||
table.insert(info.faces, f)
|
||||
end
|
||||
end
|
||||
if #info.faces == 0 then
|
||||
info.faces = table.clone(FACES)
|
||||
end
|
||||
end
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- the bytes of one surface of format f
|
||||
local function surfaceSize(info: any, w: number, h: number): number
|
||||
if info.format == "masked" then
|
||||
return (info.masked :: Texel.Desc).bytes * w * h
|
||||
end
|
||||
return Texture.size(info.format, w, h) :: number
|
||||
end
|
||||
|
||||
function Dds.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local info, ierr = Dds.info(r)
|
||||
if not info then
|
||||
return nil, ierr
|
||||
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 = r.buf, r.base
|
||||
local p = base + info.dataOffset
|
||||
local limit = r.limit
|
||||
local count = if info.layout == "cube" then #info.faces * info.layers else info.layers
|
||||
local list: { Texture.Surface } = {}
|
||||
local pixels = 0
|
||||
local stop = false
|
||||
for layer = 0, count - 1 do
|
||||
local w, h, d = info.width, info.height, info.depth
|
||||
for level = 0, info.mips - 1 do
|
||||
local size = surfaceSize(info, w, h)
|
||||
for slice = 0, d - 1 do
|
||||
local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0)
|
||||
if want then
|
||||
if p + size > limit then
|
||||
if level > 0 or layer > 0 or slice > 0 then
|
||||
stop = true -- a cut mip chain / later surface: keep what decoded
|
||||
break
|
||||
end
|
||||
return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p)
|
||||
end
|
||||
pixels += w * h
|
||||
if pixels > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels))
|
||||
end
|
||||
local px, pf
|
||||
if info.format == "masked" then
|
||||
px, pf = Texel.decode(info.masked :: Texel.Desc, b, p, w, h, native)
|
||||
else
|
||||
px, pf = Texture.decode(info.format, b, p, w, h, native)
|
||||
end
|
||||
if not px then
|
||||
return nil, Err.from(pf, p)
|
||||
end
|
||||
local face = if info.layout == "cube" then layer % #info.faces else 0
|
||||
table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) })
|
||||
end
|
||||
p += size
|
||||
end
|
||||
if stop then
|
||||
break
|
||||
end
|
||||
w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2)
|
||||
end
|
||||
if stop then
|
||||
break
|
||||
end
|
||||
end
|
||||
local img = Texture.assemble(list, info.layout)
|
||||
if not img then
|
||||
return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset)
|
||||
end
|
||||
if info.layout == "cube" then
|
||||
img.meta.faces = info.faces
|
||||
end
|
||||
if info.srgb then
|
||||
img.meta.colorSpace = "srgb"
|
||||
elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then
|
||||
img.meta.colorSpace = "linear"
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "dds",
|
||||
pixelFormat = info.format,
|
||||
dxgi = info.dxgi,
|
||||
fourcc = info.fourcc,
|
||||
mips = info.mips,
|
||||
layers = info.layers,
|
||||
depth = info.depth,
|
||||
premultiplied = info.premultiplied,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 }
|
||||
local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 }
|
||||
|
||||
-- the surface bytes of one image in format f
|
||||
local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local w, h, px = img.width, img.height, img.pixels
|
||||
if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then
|
||||
local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil)
|
||||
if not blocks then
|
||||
return nil, Err.new(Err.ARG, tostring(err))
|
||||
end
|
||||
return blocks, nil
|
||||
elseif f == "bgra8" then
|
||||
local out = buffer.create(w * h * 4)
|
||||
for i = 0, w * h - 1 do
|
||||
local v = buffer.readu32(px, i * 4)
|
||||
buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16))
|
||||
end
|
||||
return out, nil
|
||||
elseif f == "rgba16f" then
|
||||
return Texture.toHalf(px, w * h), nil
|
||||
end
|
||||
local out = buffer.create(w * h * (BYTES_PF[f] :: number))
|
||||
buffer.copy(out, 0, px, 0, buffer.len(out))
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local function writeHeader(out: Bytes.Writer, w: number, h: number, f: string, mips: number, dx10: boolean, layers: number, cube: boolean)
|
||||
local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5"
|
||||
out:string(MAGIC)
|
||||
out:u32le(124)
|
||||
local flags = 0x1007 + (if mips > 1 then DDSD_MIPMAPCOUNT else 0) + (if blockFmt then 0x80000 else 0x8)
|
||||
out:u32le(flags)
|
||||
out:u32le(h)
|
||||
out:u32le(w)
|
||||
out:u32le(if blockFmt then Texture.size(f, w, h) :: number else w * (BYTES_PF[f] :: number))
|
||||
out:u32le(0)
|
||||
out:u32le(if mips > 1 then mips else 0)
|
||||
out:fill(0, 44)
|
||||
-- DDS_PIXELFORMAT
|
||||
out:u32le(32)
|
||||
if dx10 then
|
||||
out:u32le(DDPF_FOURCC)
|
||||
out:string("DX10")
|
||||
out:fill(0, 20)
|
||||
elseif blockFmt then
|
||||
out:u32le(DDPF_FOURCC)
|
||||
out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } :: { [string]: string })[f])
|
||||
out:fill(0, 20)
|
||||
else
|
||||
out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS)
|
||||
out:u32le(0)
|
||||
out:u32le(32)
|
||||
if f == "bgra8" then
|
||||
out:u32le(0xFF0000)
|
||||
out:u32le(0xFF00)
|
||||
out:u32le(0xFF)
|
||||
else
|
||||
out:u32le(0xFF)
|
||||
out:u32le(0xFF00)
|
||||
out:u32le(0xFF0000)
|
||||
end
|
||||
out:u32le(0xFF000000)
|
||||
end
|
||||
out:u32le(0x1000 + (if mips > 1 then 0x400008 else 0) + (if cube then 0x8 else 0))
|
||||
out:u32le(if cube then 0xFE00 else 0)
|
||||
out:fill(0, 12)
|
||||
if dx10 then
|
||||
out:u32le(DX10_OUT[f])
|
||||
out:u32le(3)
|
||||
out:u32le(if cube then MISC_CUBE else 0)
|
||||
out:u32le(if cube then layers // 6 else layers)
|
||||
out:u32le(0)
|
||||
end
|
||||
end
|
||||
|
||||
function Dds.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.pixelFormat) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f")
|
||||
if not DX10_OUT[f] then
|
||||
return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f))
|
||||
end
|
||||
local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8"
|
||||
if pf ~= needs then
|
||||
return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs))
|
||||
end
|
||||
-- surfaces: the frames (array / cube faces) or the image
|
||||
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 then
|
||||
return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer")
|
||||
end
|
||||
local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6))
|
||||
local mips = 1
|
||||
if opts and opts.mips then
|
||||
local m = math.max(img.width, img.height)
|
||||
while m > 1 do
|
||||
m //= 2
|
||||
mips += 1
|
||||
end
|
||||
end
|
||||
local out = Bytes.writer(img.width * img.height * 4 * #images + 200)
|
||||
writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true)
|
||||
for _, im in images do
|
||||
local level = im
|
||||
for m = 1, mips do
|
||||
local data, err = surface(level, f, opts)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
out:bytes(data)
|
||||
if m < mips then
|
||||
level = Texture.halve(level)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
Dds.DXGI = DXGI
|
||||
|
||||
return Dds
|
||||
@@ -0,0 +1,117 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3-
|
||||
-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave),
|
||||
-- ZIP encode, and the per-line channel sample conversion to floats. Never throws.
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Codec = {}
|
||||
|
||||
local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- undoes the predictor and the interleave of t (n bytes) -> a new buffer
|
||||
local function reconstruct(t: buffer, n: number): buffer
|
||||
local prev = if n > 0 then readu8(t, 0) else 0
|
||||
for i = 1, n - 1 do
|
||||
prev = (prev + readu8(t, i) - 128) % 256
|
||||
writeu8(t, i, prev)
|
||||
end
|
||||
local out = buffer.create(n)
|
||||
local half = (n + 1) // 2
|
||||
for i = 0, half - 1 do
|
||||
writeu8(out, i * 2, readu8(t, i))
|
||||
end
|
||||
for i = 0, n - half - 1 do
|
||||
writeu8(out, i * 2 + 1, readu8(t, half + i))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- rle(src, p, n, outSize) -> the raw block | nil, message
|
||||
function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
|
||||
local t = buffer.create(outSize)
|
||||
local o, stop = 0, p + n
|
||||
while p < stop do
|
||||
local c = readi8(src, p)
|
||||
p += 1
|
||||
if c < 0 then
|
||||
local cnt = -c
|
||||
if p + cnt > stop or o + cnt > outSize then
|
||||
return nil, "bad RLE run"
|
||||
end
|
||||
buffer.copy(t, o, src, p, cnt)
|
||||
p += cnt
|
||||
o += cnt
|
||||
else
|
||||
if p >= stop or o + c + 1 > outSize then
|
||||
return nil, "bad RLE run"
|
||||
end
|
||||
buffer.fill(t, o, readu8(src, p), c + 1)
|
||||
p += 1
|
||||
o += c + 1
|
||||
end
|
||||
end
|
||||
if o ~= outSize then
|
||||
return nil, "RLE data too short"
|
||||
end
|
||||
return reconstruct(t, outSize), nil
|
||||
end
|
||||
|
||||
-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS)
|
||||
function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
|
||||
local t, err = Deflate.zlib(src, p, n, outSize)
|
||||
if not t then
|
||||
return nil, tostring(err)
|
||||
end
|
||||
if buffer.len(t) ~= outSize then
|
||||
return nil, "zlib block has the wrong size"
|
||||
end
|
||||
return reconstruct(t, outSize), nil
|
||||
end
|
||||
|
||||
-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib)
|
||||
function Codec.zip(raw: buffer, level: number): buffer
|
||||
local n = buffer.len(raw)
|
||||
local t = buffer.create(n)
|
||||
local half = (n + 1) // 2
|
||||
for i = 0, n - 1 do
|
||||
local v = readu8(raw, i)
|
||||
if i % 2 == 0 then
|
||||
writeu8(t, i // 2, v)
|
||||
else
|
||||
writeu8(t, half + i // 2, v)
|
||||
end
|
||||
end
|
||||
local prev = if n > 0 then readu8(t, 0) else 0
|
||||
for i = 1, n - 1 do
|
||||
local v = readu8(t, i)
|
||||
writeu8(t, i, (v - prev + 384) % 256)
|
||||
prev = v
|
||||
end
|
||||
return Deflate.zlibCompress(t, { level = level }) :: buffer
|
||||
end
|
||||
|
||||
-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into
|
||||
-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them
|
||||
function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number
|
||||
if kind == 1 then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)])
|
||||
end
|
||||
return p + count * 2
|
||||
elseif kind == 2 then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * step, readf32(src, p + i * 4))
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * step, readu32(src, p + i * 4))
|
||||
end
|
||||
end
|
||||
return p + count * 4
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,367 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor
|
||||
-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman
|
||||
-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit
|
||||
-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data.
|
||||
local Piz = {}
|
||||
|
||||
local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
|
||||
local USHORT_RANGE, BITMAP_SIZE = 65536, 8192
|
||||
local HUF_ENCSIZE = 65537
|
||||
local DECBITS = 14
|
||||
local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Huffman
|
||||
-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1)
|
||||
local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number?
|
||||
local c, lc = 0, 0
|
||||
local function bits(n: number): number?
|
||||
while lc < n do
|
||||
if p >= limit then
|
||||
return nil
|
||||
end
|
||||
c = c * 256 + readu8(src, p)
|
||||
p += 1
|
||||
lc += 8
|
||||
end
|
||||
lc -= n
|
||||
local v = c // 2 ^ lc
|
||||
c -= v * 2 ^ lc
|
||||
return v
|
||||
end
|
||||
local i = im
|
||||
while i <= iM do
|
||||
local l = bits(6)
|
||||
if not l then
|
||||
return nil
|
||||
end
|
||||
if l == LONG_ZEROCODE_RUN then
|
||||
local z = bits(8)
|
||||
if not z then
|
||||
return nil
|
||||
end
|
||||
z += SHORTEST_LONG_RUN
|
||||
if i + z > iM + 1 then
|
||||
return nil
|
||||
end
|
||||
for k = i, i + z - 1 do
|
||||
len[k + 1] = 0
|
||||
end
|
||||
i += z
|
||||
elseif l >= SHORT_ZEROCODE_RUN then
|
||||
local z = l - SHORT_ZEROCODE_RUN + 2
|
||||
if i + z > iM + 1 then
|
||||
return nil
|
||||
end
|
||||
for k = i, i + z - 1 do
|
||||
len[k + 1] = 0
|
||||
end
|
||||
i += z
|
||||
else
|
||||
len[i + 1] = l
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message
|
||||
local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string?
|
||||
if n == 0 then
|
||||
return if nRaw == 0 then nil else "empty Huffman data"
|
||||
end
|
||||
if n < 20 then
|
||||
return "truncated Huffman header"
|
||||
end
|
||||
local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12)
|
||||
if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then
|
||||
return "bad Huffman symbol range"
|
||||
end
|
||||
local limit = p + n
|
||||
local len = table.create(HUF_ENCSIZE, 0)
|
||||
local q = unpackTable(src, p + 20, limit, im, iM, len)
|
||||
if not q then
|
||||
return "bad Huffman table"
|
||||
end
|
||||
if q + (nBits + 7) // 8 > limit then
|
||||
return "truncated Huffman data"
|
||||
end
|
||||
-- canonical codes (OpenEXR's order: longest codes get the smallest values)
|
||||
local count = table.create(59, 0)
|
||||
for s = im, iM do
|
||||
local l = len[s + 1]
|
||||
if l > 58 then
|
||||
return "bad Huffman code length"
|
||||
end
|
||||
count[l + 1] += 1
|
||||
end
|
||||
local start = table.create(59, 0)
|
||||
local c = 0
|
||||
for l = 58, 1, -1 do
|
||||
local nc = (c + count[l + 1]) // 2
|
||||
start[l + 1] = c
|
||||
c = nc
|
||||
end
|
||||
local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid
|
||||
local long: { [number]: { [number]: number } } = {}
|
||||
local maxLong = 0
|
||||
for s = im, iM do
|
||||
local l = len[s + 1]
|
||||
if l > 0 then
|
||||
local code = start[l + 1]
|
||||
start[l + 1] = code + 1
|
||||
if l <= DECBITS then
|
||||
local base = code * 2 ^ (DECBITS - l)
|
||||
local v = (s + 1) * 64 + l
|
||||
for k = base, base + 2 ^ (DECBITS - l) - 1 do
|
||||
if k < lshift(1, DECBITS) then
|
||||
buffer.writeu32(fast, k * 4, v)
|
||||
end
|
||||
end
|
||||
else
|
||||
if l > 52 then
|
||||
return "unsupported: Huffman code longer than 52 bits"
|
||||
end
|
||||
local t = long[l]
|
||||
if not t then
|
||||
t = {}
|
||||
long[l] = t
|
||||
end
|
||||
t[code] = s
|
||||
maxLong = math.max(maxLong, l)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- decode MSB-first from a zero-padded copy
|
||||
local nbytes = (nBits + 7) // 8
|
||||
local data = buffer.create(nbytes + 8)
|
||||
buffer.copy(data, 0, src, q, nbytes)
|
||||
local bp = 0
|
||||
local o = 0
|
||||
local rlc = iM
|
||||
local mask = lshift(1, DECBITS) - 1
|
||||
while bp < nBits do
|
||||
local byte = rshift(bp, 3)
|
||||
local w = bit32.byteswap(readu32(data, byte))
|
||||
local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask)
|
||||
local e = readu32(fast, peek * 4)
|
||||
local sym: number, l: number = 0, 0
|
||||
if e ~= 0 then
|
||||
sym = e // 64 - 1
|
||||
l = band(e, 63)
|
||||
else
|
||||
-- a long code: bit by bit from length 15
|
||||
sym = -1
|
||||
local code = 0
|
||||
for k = 0, maxLong - 1 do
|
||||
local bitAt = bp + k
|
||||
code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1)
|
||||
if k + 1 > DECBITS then
|
||||
local t = long[k + 1]
|
||||
local found: number? = if t then t[code] else nil
|
||||
if found then
|
||||
sym = found
|
||||
l = k + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if sym < 0 then
|
||||
return "invalid Huffman code"
|
||||
end
|
||||
end
|
||||
bp += l
|
||||
if bp > nBits then
|
||||
return "Huffman code past the end of the data"
|
||||
end
|
||||
if sym == rlc then
|
||||
if bp + 8 > nBits then
|
||||
return "truncated run length"
|
||||
end
|
||||
local b2 = bit32.byteswap(readu32(data, rshift(bp, 3)))
|
||||
local cs = band(rshift(b2, 24 - band(bp, 7)), 255)
|
||||
bp += 8
|
||||
if o + cs > nRaw then
|
||||
return "too much Huffman data"
|
||||
end
|
||||
if o == 0 then
|
||||
return "run length at the start"
|
||||
end
|
||||
local s = readu16(out, (o - 1) * 2)
|
||||
for _ = 1, cs do
|
||||
writeu16(out, o * 2, s)
|
||||
o += 1
|
||||
end
|
||||
else
|
||||
if o >= nRaw then
|
||||
return "too much Huffman data"
|
||||
end
|
||||
writeu16(out, o * 2, sym)
|
||||
o += 1
|
||||
end
|
||||
end
|
||||
if o ~= nRaw then
|
||||
return "not enough Huffman data"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ wavelet
|
||||
-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements)
|
||||
local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number)
|
||||
local w14 = mx < 16384
|
||||
local n = math.min(nx, ny)
|
||||
local p = 1
|
||||
while p <= n do
|
||||
p *= 2
|
||||
end
|
||||
p //= 2
|
||||
local p2 = p
|
||||
p //= 2
|
||||
local function dec(l: number, h: number): (number, number)
|
||||
if w14 then
|
||||
local ls = if l >= 32768 then l - 65536 else l
|
||||
local hs = if h >= 32768 then h - 65536 else h
|
||||
local ai = ls + hs % 2 + hs // 2
|
||||
return ai % 65536, (ai - hs) % 65536
|
||||
end
|
||||
local bb = (l - rshift(h, 1)) % 65536
|
||||
return (h + bb - 32768) % 65536, bb
|
||||
end
|
||||
while p >= 1 do
|
||||
local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2
|
||||
local py = base
|
||||
local ey = base + oy * (ny - p2)
|
||||
while py <= ey do
|
||||
local px = py
|
||||
local ex = py + ox * (nx - p2)
|
||||
while px <= ex do
|
||||
local p01 = px + ox1
|
||||
local p10 = px + oy1
|
||||
local p11 = p10 + ox1
|
||||
local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2))
|
||||
local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2))
|
||||
local a, b = dec(i00, i01)
|
||||
writeu16(t, px * 2, a)
|
||||
writeu16(t, p01 * 2, b)
|
||||
local c, d = dec(i10, i11)
|
||||
writeu16(t, p10 * 2, c)
|
||||
writeu16(t, p11 * 2, d)
|
||||
px += ox2
|
||||
end
|
||||
if band(nx, p) ~= 0 then
|
||||
local p10 = px + oy1
|
||||
local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2))
|
||||
writeu16(t, px * 2, a)
|
||||
writeu16(t, p10 * 2, b)
|
||||
end
|
||||
py += oy2
|
||||
end
|
||||
if band(ny, p) ~= 0 then
|
||||
local px = py
|
||||
local ex = py + ox * (nx - p2)
|
||||
while px <= ex do
|
||||
local p01 = px + ox1
|
||||
local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2))
|
||||
writeu16(t, px * 2, a)
|
||||
writeu16(t, p01 * 2, b)
|
||||
px += ox2
|
||||
end
|
||||
end
|
||||
p2 = p
|
||||
p //= 2
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Chan = { nx: number, ny: number, size: number, ys: number }
|
||||
|
||||
-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message.
|
||||
-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and
|
||||
-- ySampling.
|
||||
function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?)
|
||||
local total = 0
|
||||
for _, c in chans do
|
||||
total += c.nx * c.ny * c.size
|
||||
end
|
||||
if total * 2 ~= outSize then
|
||||
return nil, "PIZ block size mismatch"
|
||||
end
|
||||
local out = buffer.create(outSize)
|
||||
if total == 0 then
|
||||
return out, nil
|
||||
end
|
||||
local limit = p + n
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated PIZ header"
|
||||
end
|
||||
local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2)
|
||||
p += 4
|
||||
if maxNZ >= BITMAP_SIZE then
|
||||
return nil, "bad PIZ bitmap range"
|
||||
end
|
||||
local bitmap = buffer.create(BITMAP_SIZE)
|
||||
if minNZ <= maxNZ then
|
||||
local cnt = maxNZ - minNZ + 1
|
||||
if p + cnt > limit then
|
||||
return nil, "truncated PIZ bitmap"
|
||||
end
|
||||
buffer.copy(bitmap, minNZ, src, p, cnt)
|
||||
p += cnt
|
||||
end
|
||||
-- reverse LUT
|
||||
local lut = buffer.create(USHORT_RANGE * 2)
|
||||
local k = 0
|
||||
for i = 0, USHORT_RANGE - 1 do
|
||||
if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then
|
||||
writeu16(lut, k * 2, i)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
local maxValue = k - 1
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated PIZ length"
|
||||
end
|
||||
local length = readu32(src, p)
|
||||
p += 4
|
||||
if length > limit - p then
|
||||
return nil, "truncated PIZ data"
|
||||
end
|
||||
local tmp = buffer.create(total * 2)
|
||||
local herr = huffman(src, p, length, tmp, total)
|
||||
if herr then
|
||||
return nil, herr
|
||||
end
|
||||
local starts = table.create(#chans, 0)
|
||||
local at = 0
|
||||
for i, c in chans do
|
||||
starts[i] = at
|
||||
for j = 0, c.size - 1 do
|
||||
wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue)
|
||||
end
|
||||
at += c.nx * c.ny * c.size
|
||||
end
|
||||
for i = 0, total - 1 do
|
||||
writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2))
|
||||
end
|
||||
-- planes -> scanlines
|
||||
local o = 0
|
||||
local cursor = table.clone(starts)
|
||||
for y = minY, maxY do
|
||||
for i, c in chans do
|
||||
if y % c.ys == 0 then
|
||||
local cnt = c.nx * c.size
|
||||
buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2)
|
||||
cursor[i] += cnt
|
||||
o += cnt * 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Piz
|
||||
@@ -0,0 +1,782 @@
|
||||
--!strict
|
||||
-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ
|
||||
-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and
|
||||
-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts
|
||||
-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips),
|
||||
-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any
|
||||
-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image
|
||||
-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels.
|
||||
-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear
|
||||
-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
|
||||
-- for colour, round(clamp(a, 0, 1) * 255) for alpha.
|
||||
-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only
|
||||
-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A /
|
||||
-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Half = require("@formats/codecs/image/Half")
|
||||
local Codec = require("@formats/image/exr/Codec")
|
||||
local Piz = require("@formats/image/exr/Piz")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Exr = {
|
||||
name = "exr",
|
||||
category = "image",
|
||||
extensions = { "exr" },
|
||||
mime = { "image/x-exr", "image/aces" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
|
||||
part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1)
|
||||
layer: string?, -- read <layer>.R / .G / .B / .A instead of R / G / B / A
|
||||
mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compression: ("none" | "zips" | "zip")?, -- default "zip"
|
||||
pixelType: ("half" | "float")?, -- default "half"
|
||||
alpha: boolean?, -- write A (default: when some alpha is not 1)
|
||||
level: number?, -- zlib level 1..9 (default 6)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "\118\47\49\1"
|
||||
local COMPRESSION: { [number]: string } = { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" }
|
||||
local LINES: { [number]: number } = { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 }
|
||||
local GAMMA = 1 / 2.2
|
||||
|
||||
local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Exr.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, MAGIC)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Channel = { name: string, kind: number, linear: boolean, xs: number, ys: number }
|
||||
type Part = {
|
||||
attrs: { [string]: any },
|
||||
channels: { Channel },
|
||||
compression: number,
|
||||
box: { number }, -- data window xMin, yMin, xMax, yMax
|
||||
display: { number },
|
||||
tiled: boolean,
|
||||
tiles: { number }?, -- xSize, ySize, mode, rounding
|
||||
name: string?,
|
||||
type: string?,
|
||||
chunks: number,
|
||||
offsets: { number },
|
||||
}
|
||||
|
||||
local function cstr(b: buffer, p: number, limit: number, max: number): (string?, number)
|
||||
local q = p
|
||||
while q < limit and q - p <= max do
|
||||
if readu8(b, q) == 0 then
|
||||
return readstring(b, p, q - p), q + 1
|
||||
end
|
||||
q += 1
|
||||
end
|
||||
return nil, q
|
||||
end
|
||||
|
||||
local function f32(b: buffer, o: number): number
|
||||
return readf32(b, o)
|
||||
end
|
||||
|
||||
-- one attribute value of a known type
|
||||
local function value(b: buffer, p: number, size: number, typ: string): any
|
||||
if typ == "chlist" then
|
||||
local list: { Channel } = {}
|
||||
local q, stop = p, p + size
|
||||
while q < stop and readu8(b, q) ~= 0 do
|
||||
local name, nq = cstr(b, q, stop, 255)
|
||||
if not name or nq + 16 > stop then
|
||||
return nil
|
||||
end
|
||||
table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) })
|
||||
q = nq + 16
|
||||
end
|
||||
return list
|
||||
elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then
|
||||
return if size >= 1 then readu8(b, p) else nil
|
||||
elseif typ == "box2i" then
|
||||
return if size >= 16 then { readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } else nil
|
||||
elseif typ == "box2f" then
|
||||
return if size >= 16 then { f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } else nil
|
||||
elseif typ == "v2i" then
|
||||
return if size >= 8 then { readi32(b, p), readi32(b, p + 4) } else nil
|
||||
elseif typ == "v2f" then
|
||||
return if size >= 8 then { f32(b, p), f32(b, p + 4) } else nil
|
||||
elseif typ == "v3f" then
|
||||
return if size >= 12 then { f32(b, p), f32(b, p + 4), f32(b, p + 8) } else nil
|
||||
elseif typ == "float" then
|
||||
return if size >= 4 then f32(b, p) else nil
|
||||
elseif typ == "double" then
|
||||
return if size >= 8 then buffer.readf64(b, p) else nil
|
||||
elseif typ == "int" then
|
||||
return if size >= 4 then readi32(b, p) else nil
|
||||
elseif typ == "string" then
|
||||
return readstring(b, p, size)
|
||||
elseif typ == "tiledesc" then
|
||||
if size < 9 then
|
||||
return nil
|
||||
end
|
||||
local m = readu8(b, p + 8)
|
||||
return { readu32(b, p), readu32(b, p + 4), m % 16, m // 16 }
|
||||
elseif typ == "chromaticities" then
|
||||
if size < 32 then
|
||||
return nil
|
||||
end
|
||||
local t = {}
|
||||
for i = 0, 7 do
|
||||
t[i + 1] = f32(b, p + i * 4)
|
||||
end
|
||||
return t
|
||||
end
|
||||
local raw = buffer.create(size)
|
||||
buffer.copy(raw, 0, b, p, size)
|
||||
return raw
|
||||
end
|
||||
|
||||
-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err
|
||||
local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?)
|
||||
local attrs: { [string]: any } = {}
|
||||
local types: { [string]: string } = {}
|
||||
while true do
|
||||
if p >= limit then
|
||||
return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p)
|
||||
end
|
||||
if readu8(b, p) == 0 then
|
||||
attrs._types = types
|
||||
return attrs, p + 1, nil
|
||||
end
|
||||
local name, q = cstr(b, p, limit, 255)
|
||||
if not name then
|
||||
return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p)
|
||||
end
|
||||
local typ, q2 = cstr(b, q, limit, 255)
|
||||
if not typ then
|
||||
return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q)
|
||||
end
|
||||
if q2 + 4 > limit then
|
||||
return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2)
|
||||
end
|
||||
local size = readi32(b, q2)
|
||||
if size < 0 or q2 + 4 + size > limit then
|
||||
return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2)
|
||||
end
|
||||
attrs[name] = value(b, q2 + 4, size, typ)
|
||||
types[name] = typ
|
||||
p = q2 + 4 + size
|
||||
end
|
||||
end
|
||||
|
||||
-- level sizes of a tiled part
|
||||
local function levelSize(n: number, l: number, roundUp: boolean): number
|
||||
local d = 2 ^ l
|
||||
return math.max(1, if roundUp then math.ceil(n / d) else n // d)
|
||||
end
|
||||
local function levelCount(w: number, h: number, mode: number, roundUp: boolean): (number, number)
|
||||
local function count(n: number): number
|
||||
local c = 1
|
||||
while levelSize(n, c - 1, roundUp) > 1 do
|
||||
c += 1
|
||||
end
|
||||
return c
|
||||
end
|
||||
if mode == 0 then
|
||||
return 1, 1
|
||||
elseif mode == 1 then
|
||||
local c = count(math.max(w, h))
|
||||
return c, c
|
||||
end
|
||||
return count(w), count(h)
|
||||
end
|
||||
|
||||
-- chunk count of a part (single-part files: computed)
|
||||
local function chunkCount(pt: Part): number
|
||||
local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1
|
||||
if not pt.tiled then
|
||||
return (h + LINES[pt.compression] - 1) // LINES[pt.compression]
|
||||
end
|
||||
local t = pt.tiles :: { number }
|
||||
local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1
|
||||
local lx, ly = levelCount(w, h, mode, roundUp)
|
||||
local n = 0
|
||||
if mode == 2 then
|
||||
for y = 0, ly - 1 do
|
||||
for x = 0, lx - 1 do
|
||||
n += math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty)
|
||||
end
|
||||
end
|
||||
else
|
||||
for l = 0, lx - 1 do
|
||||
n += math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty)
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
export type Info = { multipart: boolean, tiled: boolean, deep: boolean, parts: { Part }, dataStart: number }
|
||||
|
||||
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base)
|
||||
end
|
||||
local ver = readu32(b, base + 4)
|
||||
if ver % 256 ~= 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4)
|
||||
end
|
||||
local flags = ver // 256
|
||||
local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0
|
||||
local info: Info = { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 }
|
||||
local p = base + 8
|
||||
repeat
|
||||
local attrs, q, herr = header(b, p, limit)
|
||||
if not attrs then
|
||||
return nil, herr
|
||||
end
|
||||
p = q
|
||||
local chans = attrs.channels
|
||||
local box = attrs.dataWindow
|
||||
if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then
|
||||
return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p)
|
||||
end
|
||||
local typ = attrs.type
|
||||
local pt: Part = {
|
||||
attrs = attrs,
|
||||
channels = chans,
|
||||
compression = attrs.compression,
|
||||
box = box,
|
||||
display = attrs.displayWindow or box,
|
||||
tiled = if typ then (typ == "tiledimage" or typ == "deeptile") else tiledFlag,
|
||||
tiles = attrs.tiles,
|
||||
name = attrs.name,
|
||||
type = typ,
|
||||
chunks = 0,
|
||||
offsets = {},
|
||||
}
|
||||
if pt.tiled and type(pt.tiles) ~= "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p)
|
||||
end
|
||||
if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data window", p)
|
||||
end
|
||||
if pt.tiled and ((pt.tiles :: any)[1] < 1 or (pt.tiles :: any)[2] < 1) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad tile size", p)
|
||||
end
|
||||
for _, c in chans do
|
||||
if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p)
|
||||
end
|
||||
end
|
||||
table.insert(info.parts, pt)
|
||||
if #info.parts > 4096 then
|
||||
return nil, Err.new(Err.LIMIT, "too many parts", p)
|
||||
end
|
||||
until not multi or (p < limit and readu8(b, p) == 0)
|
||||
if multi then
|
||||
p += 1
|
||||
end
|
||||
-- offset tables
|
||||
for _, pt in info.parts do
|
||||
local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0)
|
||||
if n < 0 or n > 2 ^ 24 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad chunk count", p)
|
||||
end
|
||||
pt.chunks = n
|
||||
if p + n * 8 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296
|
||||
end
|
||||
p += n * 8
|
||||
end
|
||||
info.dataStart = p - base
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err
|
||||
function Exr.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
return parse(r)
|
||||
end
|
||||
|
||||
-- bytes of a sample kind
|
||||
local SIZE = { [0] = 4, 2, 4 }
|
||||
|
||||
-- number of multiples of s in [a, b]
|
||||
local function samples(a: number, b: number, s: number): number
|
||||
return b // s - (a - 1) // s
|
||||
end
|
||||
|
||||
type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey)
|
||||
|
||||
local function newPlane(pw: number, ph: number): buffer
|
||||
local px = buffer.create(pw * ph * 16)
|
||||
for i = 0, pw * ph - 1 do
|
||||
buffer.writef32(px, i * 16 + 12, 1)
|
||||
end
|
||||
return px
|
||||
end
|
||||
-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy)
|
||||
local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err?
|
||||
local p = dp
|
||||
for y = y0, y1 do
|
||||
for i, c in part.channels do
|
||||
if y % c.ys == 0 then
|
||||
local nx = if c.xs == 1 then bw else samples(x0, x0 + bw - 1, c.xs)
|
||||
local sz = SIZE[c.kind]
|
||||
if p + nx * sz > buffer.len(data) then
|
||||
return Err.new(Err.CORRUPT, "block too short")
|
||||
end
|
||||
local k = target[i]
|
||||
if k ~= nil then
|
||||
local row = y - oy
|
||||
if c.xs == 1 and c.ys == 1 and k < 4 then
|
||||
Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16)
|
||||
else
|
||||
local tmp = buffer.create(nx * 4)
|
||||
Codec.samples(data, p, nx, c.kind, tmp, 0, 4)
|
||||
local first = (x0 + c.xs - 1) // c.xs * c.xs
|
||||
for s = 0, nx - 1 do
|
||||
local v = buffer.readf32(tmp, s * 4)
|
||||
local sx = first + s * c.xs
|
||||
for yy = row, math.min(row + c.ys - 1, ph - 1) do
|
||||
for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do
|
||||
local o = (yy * pw + xx) * 16
|
||||
if k == 4 then
|
||||
buffer.writef32(plane, o, v)
|
||||
buffer.writef32(plane, o + 4, v)
|
||||
buffer.writef32(plane, o + 8, v)
|
||||
else
|
||||
buffer.writef32(plane, o + k * 4, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
p += nx * sz
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- the raw bytes of a block (uncompressed size raw)
|
||||
local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?)
|
||||
if size == raw or comp == 0 then
|
||||
if size < raw then
|
||||
return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p)
|
||||
end
|
||||
return b, p, nil
|
||||
end
|
||||
local out, err
|
||||
if comp == 1 then
|
||||
out, err = Codec.rle(b, p, size, raw)
|
||||
elseif comp == 2 or comp == 3 then
|
||||
out, err = Codec.unzip(b, p, size, raw)
|
||||
else
|
||||
local chans: { Piz.Chan } = {}
|
||||
for i, c in part.channels do
|
||||
chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = SIZE[c.kind] // 2, ys = c.ys }
|
||||
end
|
||||
out, err = Piz.decode(b, p, size, chans, y0, y1, raw)
|
||||
end
|
||||
if not out then
|
||||
return nil, 0, Err.from(err, p)
|
||||
end
|
||||
return out, 0, nil
|
||||
end
|
||||
|
||||
local function rawSize(part: Part, y0: number, y1: number, x0: number, bw: number): number
|
||||
local n = 0
|
||||
for y = y0, y1 do
|
||||
for _, c in part.channels do
|
||||
if y % c.ys == 0 then
|
||||
n += samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind]
|
||||
end
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local info, perr = parse(r)
|
||||
if not info then
|
||||
return nil, perr
|
||||
end
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local want = opts and opts.part or 1
|
||||
local pt: Part? = nil
|
||||
local partIndex = 0
|
||||
for i, p in info.parts do
|
||||
if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then
|
||||
pt, partIndex = p, i
|
||||
end
|
||||
end
|
||||
if not pt then
|
||||
return nil, Err.new(Err.ARG, "no part " .. tostring(want))
|
||||
end
|
||||
local part = pt :: Part
|
||||
if info.deep or (part.type and string.find(part.type, "deep")) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "deep data")
|
||||
end
|
||||
local comp: number = part.compression
|
||||
if comp > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp)))
|
||||
end
|
||||
local box = part.box
|
||||
local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4]
|
||||
local w, h = xMax - xMin + 1, yMax - yMin + 1
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
-- channel -> output component
|
||||
local prefix = if opts and opts.layer then opts.layer .. "." else ""
|
||||
local target: Target = {}
|
||||
local hasRgb = false
|
||||
for i, c in part.channels do
|
||||
local n = c.name
|
||||
if string.sub(n, 1, #prefix) == prefix then
|
||||
local s = string.sub(n, #prefix + 1)
|
||||
local k = if s == "R" or s == "r" then 0 elseif s == "G" or s == "g" then 1 elseif s == "B" or s == "b" then 2 elseif s == "A" or s == "a" then 3 else nil
|
||||
if k then
|
||||
target[i] = k
|
||||
hasRgb = hasRgb or k < 3
|
||||
end
|
||||
end
|
||||
end
|
||||
if not hasRgb then
|
||||
for i, c in part.channels do
|
||||
if c.name == prefix .. "Y" then
|
||||
target[i] = 4
|
||||
end
|
||||
end
|
||||
end
|
||||
local multi = info.multipart
|
||||
-- offsets: single-part tables with holes are rebuilt from the chunk sequence
|
||||
local offsets = part.offsets
|
||||
local bad = false
|
||||
for _, o in offsets do
|
||||
if o < info.dataStart or base + o + 8 > limit then
|
||||
bad = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
-- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part)
|
||||
offsets = {}
|
||||
local p = base + info.dataStart
|
||||
local total = 0
|
||||
for _, q in info.parts do
|
||||
total += q.chunks
|
||||
end
|
||||
for _ = 1, total do
|
||||
local pi = 1
|
||||
local at = p
|
||||
if multi then
|
||||
if p + 4 > limit then
|
||||
break
|
||||
end
|
||||
pi = readi32(b, p) + 1
|
||||
p += 4
|
||||
end
|
||||
local q = info.parts[pi]
|
||||
if not q then
|
||||
break
|
||||
end
|
||||
local head = if q.tiled then 20 else 8
|
||||
if p + head > limit then
|
||||
break
|
||||
end
|
||||
local size = readi32(b, p + head - 4)
|
||||
if size < 0 then
|
||||
break
|
||||
end
|
||||
if pi == partIndex then
|
||||
table.insert(offsets, at - base)
|
||||
end
|
||||
p += head + size
|
||||
end
|
||||
end
|
||||
|
||||
local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels
|
||||
local tiles = part.tiles
|
||||
local roundUp = tiles ~= nil and tiles[4] == 1
|
||||
local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1
|
||||
|
||||
local lpb = LINES[comp]
|
||||
for ci, off in offsets do
|
||||
local p = base + off
|
||||
if multi then
|
||||
if p + 4 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "chunk past the end", p)
|
||||
end
|
||||
if readi32(b, p) ~= partIndex - 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p)
|
||||
end
|
||||
p += 4
|
||||
end
|
||||
if part.tiled then
|
||||
if p + 20 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "tile header past the end", p)
|
||||
end
|
||||
local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16)
|
||||
p += 20
|
||||
local t = tiles :: { number }
|
||||
local level = if lx == 0 and ly == 0 then 0 elseif wantMips and lx == ly then lx else -1
|
||||
if level >= 0 then
|
||||
local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp)
|
||||
local x0, y0 = tx * t[1], ty * t[2]
|
||||
if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then
|
||||
return nil, Err.new(Err.CORRUPT, "tile outside the image", p)
|
||||
end
|
||||
if size < 0 or p + size > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "tile data past the end", p)
|
||||
end
|
||||
local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0)
|
||||
local plane = planes[level]
|
||||
if not plane then
|
||||
plane = newPlane(lw, lh)
|
||||
planes[level] = plane
|
||||
end
|
||||
-- tile coordinates are relative to the level's data window origin
|
||||
local ax, ay = xMin + x0, yMin + y0
|
||||
local raw = rawSize(part, ay, ay + bh - 1, ax, bw)
|
||||
local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw)
|
||||
if not data then
|
||||
return nil, uerr
|
||||
end
|
||||
local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin)
|
||||
if berr then
|
||||
return nil, berr
|
||||
end
|
||||
end
|
||||
else
|
||||
if p + 8 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p)
|
||||
end
|
||||
local y, size = readi32(b, p), readi32(b, p + 4)
|
||||
p += 8
|
||||
if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8)
|
||||
end
|
||||
if size < 0 or p + size > limit then
|
||||
if ci > 1 then
|
||||
break -- a cut file: keep the lines that decoded (meta.truncated)
|
||||
end
|
||||
return nil, Err.new(Err.TRUNCATED, "block data past the end", p)
|
||||
end
|
||||
local y1 = math.min(y + lpb - 1, yMax)
|
||||
local raw = rawSize(part, y, y1, xMin, w)
|
||||
local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w)
|
||||
if not data then
|
||||
return nil, uerr
|
||||
end
|
||||
local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin)
|
||||
if berr then
|
||||
return nil, berr
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local native = opts and opts.native
|
||||
local function finish(px: buffer, pw: number, ph: number): Types.Image
|
||||
if native then
|
||||
local img = Types.Image.new(0, 0, "rgbaf32")
|
||||
img.width, img.height, img.pixels = pw, ph, px
|
||||
return img
|
||||
end
|
||||
local img = Types.Image.new(pw, ph, "rgba8")
|
||||
local o = img.pixels
|
||||
for i = 0, pw * ph - 1 do
|
||||
for c = 0, 3 do
|
||||
local v = buffer.readf32(px, i * 16 + c * 4)
|
||||
v = if v ~= v or v <= 0 then 0 elseif v >= 1 then 1 else v
|
||||
buffer.writeu8(o, i * 4 + c, math.floor((if c < 3 then v ^ GAMMA else v) * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
local img = finish(planes[0], w, h)
|
||||
if wantMips then
|
||||
local mips = {}
|
||||
local l = 1
|
||||
while planes[l] do
|
||||
mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp))
|
||||
l += 1
|
||||
end
|
||||
if #mips > 0 then
|
||||
img.meta.mipmaps = mips
|
||||
end
|
||||
end
|
||||
local names, parts = {}, {}
|
||||
for i, c in part.channels do
|
||||
names[i] = c.name
|
||||
end
|
||||
for i, p in info.parts do
|
||||
parts[i] = { name = p.name or "", type = p.type or (if p.tiled then "tiledimage" else "scanlineimage") }
|
||||
end
|
||||
img.meta.colorSpace = "linear"
|
||||
img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h }
|
||||
local dw = part.display
|
||||
img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 }
|
||||
local attrs = {}
|
||||
for k, v in part.attrs do
|
||||
if k ~= "_types" and (type(v) == "string" or type(v) == "number") then
|
||||
attrs[k] = v
|
||||
end
|
||||
end
|
||||
img.meta.attributes = attrs
|
||||
local kinds = {}
|
||||
for i, c in part.channels do
|
||||
kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind]
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "exr",
|
||||
compression = COMPRESSION[comp],
|
||||
channels = names,
|
||||
pixelTypes = kinds,
|
||||
part = partIndex,
|
||||
parts = parts,
|
||||
tiled = part.tiled,
|
||||
lineOrder = part.attrs.lineOrder,
|
||||
bitDepth = if kinds[1] == "half" then 16 else 32,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function attr(w: Bytes.Writer, name: string, typ: string, data: buffer)
|
||||
w:cstring(name)
|
||||
w:cstring(typ)
|
||||
w:u32le(buffer.len(data))
|
||||
w:bytes(data)
|
||||
end
|
||||
|
||||
function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
|
||||
return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "bad image size")
|
||||
end
|
||||
local compName = opts and opts.compression or "zip"
|
||||
local comp = if compName == "none" then 0 elseif compName == "zips" then 2 elseif compName == "zip" then 3 else nil
|
||||
if not comp then
|
||||
return nil, Err.new(Err.ARG, "compression must be none, zips or zip")
|
||||
end
|
||||
local ptype = opts and opts.pixelType or "half"
|
||||
if ptype ~= "half" and ptype ~= "float" then
|
||||
return nil, Err.new(Err.ARG, "pixelType must be half or float")
|
||||
end
|
||||
local level = opts and opts.level or 6
|
||||
-- the float values
|
||||
local n = w * h
|
||||
local fl = buffer.create(n * 16)
|
||||
if img.format == "rgbaf32" then
|
||||
buffer.copy(fl, 0, img.pixels, 0, n * 16)
|
||||
else
|
||||
for i = 0, n * 4 - 1 do
|
||||
local v = buffer.readu8(img.pixels, i) / 255
|
||||
buffer.writef32(fl, i * 4, if i % 4 < 3 then v ^ 2.2 else v)
|
||||
end
|
||||
end
|
||||
local alpha = opts and opts.alpha
|
||||
if alpha == nil then
|
||||
alpha = false
|
||||
for i = 0, n - 1 do
|
||||
if buffer.readf32(fl, i * 16 + 12) ~= 1 then
|
||||
alpha = true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
local chans = if alpha then { { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } else { { "B", 2 }, { "G", 1 }, { "R", 0 } }
|
||||
local kind = if ptype == "half" then 1 else 2
|
||||
local sz = if kind == 1 then 2 else 4
|
||||
local lpb = LINES[comp]
|
||||
local nblocks = (h + lpb - 1) // lpb
|
||||
-- header
|
||||
local hw = Bytes.writer(512)
|
||||
hw:string(MAGIC)
|
||||
hw:u32le(2)
|
||||
local cl = Bytes.writer()
|
||||
for _, c in chans do
|
||||
cl:cstring(c[1])
|
||||
cl:u32le(kind)
|
||||
cl:u8(0)
|
||||
cl:fill(0, 3)
|
||||
cl:u32le(1)
|
||||
cl:u32le(1)
|
||||
end
|
||||
cl:u8(0)
|
||||
attr(hw, "channels", "chlist", cl:finish())
|
||||
attr(hw, "compression", "compression", buffer.fromstring(string.char(comp)))
|
||||
local bw = Bytes.writer(16)
|
||||
bw:u32le(0)
|
||||
bw:u32le(0)
|
||||
bw:u32le(w - 1)
|
||||
bw:u32le(h - 1)
|
||||
local boxb = bw:finish()
|
||||
attr(hw, "dataWindow", "box2i", boxb)
|
||||
attr(hw, "displayWindow", "box2i", boxb)
|
||||
attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0"))
|
||||
local fw = Bytes.writer(4)
|
||||
fw:f32le(1)
|
||||
attr(hw, "pixelAspectRatio", "float", fw:finish())
|
||||
attr(hw, "screenWindowCenter", "v2f", buffer.create(8))
|
||||
attr(hw, "screenWindowWidth", "float", fw:finish())
|
||||
hw:u8(0)
|
||||
local tableAt = hw:tell()
|
||||
hw:fill(0, nblocks * 8)
|
||||
local from = Half.fromFloat
|
||||
for bi = 0, nblocks - 1 do
|
||||
local y0 = bi * lpb
|
||||
local y1 = math.min(y0 + lpb - 1, h - 1)
|
||||
local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz)
|
||||
local o = 0
|
||||
for y = y0, y1 do
|
||||
for _, c in chans do
|
||||
local k = c[2]
|
||||
for x = 0, w - 1 do
|
||||
local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4)
|
||||
if kind == 1 then
|
||||
buffer.writeu16(raw, o, from(v))
|
||||
else
|
||||
buffer.writef32(raw, o, v)
|
||||
end
|
||||
o += sz
|
||||
end
|
||||
end
|
||||
end
|
||||
local data = raw
|
||||
if comp ~= 0 then
|
||||
local z = Codec.zip(raw, level)
|
||||
if buffer.len(z) < buffer.len(raw) then
|
||||
data = z
|
||||
end
|
||||
end
|
||||
local at = hw:tell()
|
||||
hw:setU32le(tableAt + bi * 8, at)
|
||||
hw:u32le(y0)
|
||||
hw:u32le(buffer.len(data))
|
||||
hw:bytes(data)
|
||||
end
|
||||
return hw:finish(), nil
|
||||
end
|
||||
|
||||
return Exr
|
||||
@@ -0,0 +1,337 @@
|
||||
--!strict
|
||||
-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode:
|
||||
-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha
|
||||
-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any
|
||||
-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them),
|
||||
-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists
|
||||
-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns
|
||||
-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage
|
||||
-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 /
|
||||
-- 48 / 128 with masks.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Chunks = require("@formats/containers/Chunks")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Icns = {
|
||||
name = "icns",
|
||||
category = "image",
|
||||
extensions = { "icns" },
|
||||
mime = { "image/icns", "image/x-icns" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
|
||||
maxPixels: number?, -- refuse entries larger than this (default 2^22)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
|
||||
legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local RGB: { [string]: { any } } = { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } }
|
||||
local MASKS: { [string]: boolean } = { s8mk = true, l8mk = true, h8mk = true, t8mk = true }
|
||||
local ARGB: { [string]: number } = { ic04 = 16, ic05 = 32 }
|
||||
local MONO: { [string]: { number } } = { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } }
|
||||
local PNG_TYPES: { [number]: string } = { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" }
|
||||
local LEGACY: { [number]: { string } } = { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } }
|
||||
local LAYOUT: Chunks.Layout = {
|
||||
bigEndian = true,
|
||||
resize = function(_id: string, declared: number): number?
|
||||
return math.max(0, declared - 8)
|
||||
end,
|
||||
}
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Icns.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, "icns")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4)
|
||||
local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean
|
||||
for _, ch in channels do
|
||||
local i = 0
|
||||
while i < count do
|
||||
if p >= stop then
|
||||
return false
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if c >= 128 then
|
||||
local n = c - 125
|
||||
if p >= stop then
|
||||
return false
|
||||
end
|
||||
local v = readu8(b, p)
|
||||
p += 1
|
||||
for _ = 1, math.min(n, count - i) do
|
||||
buffer.writeu8(out, i * 4 + ch, v)
|
||||
i += 1
|
||||
end
|
||||
else
|
||||
local n = c + 1
|
||||
if p + n > stop then
|
||||
return false
|
||||
end
|
||||
for k = 0, math.min(n, count - i) - 1 do
|
||||
buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k))
|
||||
end
|
||||
i += math.min(n, count - i)
|
||||
p += n
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function isPng(b: buffer, p: number, n: number): boolean
|
||||
return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n"
|
||||
end
|
||||
local function isJp2(b: buffer, p: number, n: number): boolean
|
||||
return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81")
|
||||
end
|
||||
|
||||
function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an icns file", o)
|
||||
end
|
||||
local total = bit32.byteswap(buffer.readu32(b, o + 4))
|
||||
local stop = math.min(limit, o + math.max(total, 8))
|
||||
local list = Chunks.walk(b, o + 8, stop, LAYOUT)
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 22
|
||||
local masks: { [string]: Chunks.Chunk } = {}
|
||||
for _, c in list do
|
||||
if MASKS[c.id] then
|
||||
masks[c.id] = c
|
||||
end
|
||||
end
|
||||
local frames: { Types.Frame } = {}
|
||||
local skipped: { string } = {}
|
||||
local function add(im: Types.Image, typ: string, extra: { [string]: any }?)
|
||||
local src: { [string]: any } = { format = "icns", type = typ }
|
||||
if extra then
|
||||
for k, v in extra do
|
||||
src[k] = v
|
||||
end
|
||||
end
|
||||
im.meta.source = src :: any
|
||||
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame)
|
||||
end
|
||||
for _, c in list do
|
||||
local id, p, n = c.id, c.offset, c.avail
|
||||
if c.truncated then
|
||||
table.insert(skipped, id .. " (truncated)")
|
||||
elseif RGB[id] then
|
||||
local size = RGB[id][1]
|
||||
local im = Types.Image.new(size, size, "rgba8")
|
||||
local px = im.pixels
|
||||
local q = if id == "it32" then p + 4 else p
|
||||
local count = size * size
|
||||
local ok
|
||||
if n == count * 3 then
|
||||
for i = 0, count - 1 do
|
||||
for k = 0, 2 do
|
||||
buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i))
|
||||
end
|
||||
end
|
||||
ok = true
|
||||
else
|
||||
ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count)
|
||||
end
|
||||
local m = masks[RGB[id][2]]
|
||||
for i = 0, count - 1 do
|
||||
buffer.writeu8(px, i * 4 + 3, if m and m.avail >= count then readu8(b, m.offset + i) else 255)
|
||||
end
|
||||
if ok then
|
||||
add(im, id, { bitDepth = 24, mask = m ~= nil })
|
||||
else
|
||||
table.insert(skipped, id .. " (bad RLE)")
|
||||
end
|
||||
elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then
|
||||
local size = ARGB[id]
|
||||
local im = Types.Image.new(size, size, "rgba8")
|
||||
if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then
|
||||
add(im, id, { bitDepth = 32 })
|
||||
else
|
||||
table.insert(skipped, id .. " (bad RLE)")
|
||||
end
|
||||
elseif MONO[id] then
|
||||
local w, h = MONO[id][1], MONO[id][2]
|
||||
local bytes = w * h // 8
|
||||
if n >= bytes * 2 then
|
||||
local im = Types.Image.new(w, h, "rgba8")
|
||||
for i = 0, w * h - 1 do
|
||||
local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1)
|
||||
local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1)
|
||||
buffer.writeu32(im.pixels, i * 4, (if bit == 1 then 0 else 0xFFFFFF) + mbit * 0xFF000000)
|
||||
end
|
||||
add(im, id, { bitDepth = 1 })
|
||||
end
|
||||
elseif isPng(b, p, n) then
|
||||
if decodeImage then
|
||||
local sub = buffer.create(n)
|
||||
buffer.copy(sub, 0, b, p, n)
|
||||
local okc, im, ierr = pcall(decodeImage, sub)
|
||||
if okc and im then
|
||||
if im.width * im.height <= maxPixels then
|
||||
add(im :: Types.Image, id, { png = true })
|
||||
else
|
||||
table.insert(skipped, id .. " (over maxPixels)")
|
||||
end
|
||||
else
|
||||
table.insert(skipped, id .. " (PNG: " .. tostring(if okc then ierr else im) .. ")")
|
||||
end
|
||||
else
|
||||
table.insert(skipped, id .. " (PNG: no decodeImage hook)")
|
||||
end
|
||||
elseif isJp2(b, p, n) then
|
||||
table.insert(skipped, id .. " (JPEG 2000)")
|
||||
elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then
|
||||
table.insert(skipped, id)
|
||||
end
|
||||
end
|
||||
if #frames == 0 then
|
||||
if #skipped > 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")")
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8)
|
||||
end
|
||||
local main = frames[1].image
|
||||
for _, f in frames do
|
||||
if f.image.width * f.image.height > main.width * main.height then
|
||||
main = f.image
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(0, 0, "rgba8")
|
||||
img.width, img.height, img.pixels = main.width, main.height, main.pixels
|
||||
if #frames > 1 then
|
||||
img.frames = frames
|
||||
end
|
||||
if #skipped > 0 then
|
||||
img.meta.skipped = skipped
|
||||
end
|
||||
img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the icns RLE of one channel (count bytes, step 4 from ch) into w
|
||||
local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number)
|
||||
local i = 0
|
||||
while i < count do
|
||||
local v = readu8(px, i * 4 + ch)
|
||||
local run = 1
|
||||
while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 then
|
||||
w:u8(run + 125)
|
||||
w:u8(v)
|
||||
i += run
|
||||
else
|
||||
local lit = 0
|
||||
while i + lit < count and lit < 128 do
|
||||
local a = readu8(px, (i + lit) * 4 + ch)
|
||||
if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then
|
||||
break
|
||||
end
|
||||
lit += 1
|
||||
end
|
||||
lit = math.max(lit, 1)
|
||||
w:u8(lit - 1)
|
||||
for k = 0, lit - 1 do
|
||||
w:u8(readu8(px, (i + k) * 4 + ch))
|
||||
end
|
||||
i += lit
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Icns.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local images: { Types.Image } = {}
|
||||
local seen: { [number]: boolean } = {}
|
||||
local function take(im: Types.Image): Err.Err?
|
||||
if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then
|
||||
return Err.new(Err.ARG, "icons are square rgba8 images")
|
||||
end
|
||||
if not seen[im.width] then
|
||||
seen[im.width] = true
|
||||
table.insert(images, im)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local e = take(img)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
if type(img.frames) == "table" then
|
||||
for _, f in img.frames do
|
||||
local fe = take(f.image)
|
||||
if fe then
|
||||
return nil, fe
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(images, function(a: Types.Image, c: Types.Image): boolean
|
||||
return a.width < c.width
|
||||
end)
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
local legacy = (opts and opts.legacy) or encodeImage == nil
|
||||
local body = Bytes.writer()
|
||||
local function chunk(id: string, data: buffer)
|
||||
body:string(id)
|
||||
body:u32be(buffer.len(data) + 8)
|
||||
body:bytes(data)
|
||||
end
|
||||
for _, im in images do
|
||||
local s = im.width
|
||||
if legacy and LEGACY[s] then
|
||||
local types = LEGACY[s]
|
||||
local w = Bytes.writer()
|
||||
if s == 128 then
|
||||
w:u32be(0)
|
||||
end
|
||||
for ch = 0, 2 do
|
||||
rle(w, im.pixels, ch, s * s)
|
||||
end
|
||||
chunk(types[1], w:finish())
|
||||
local m = buffer.create(s * s)
|
||||
for i = 0, s * s - 1 do
|
||||
buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3))
|
||||
end
|
||||
chunk(types[2], m)
|
||||
elseif encodeImage and PNG_TYPES[s] then
|
||||
local ok, png, perr = pcall(encodeImage, im, "png")
|
||||
if not ok or not png then
|
||||
return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring(if ok then perr else png))
|
||||
end
|
||||
chunk(PNG_TYPES[s], png :: buffer)
|
||||
else
|
||||
return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, if encodeImage then "" else " without an encodeImage hook (16 / 32 / 48 / 128 only)"))
|
||||
end
|
||||
end
|
||||
local data = body:finish()
|
||||
local out = Bytes.writer(buffer.len(data) + 8)
|
||||
out:string("icns")
|
||||
out:u32be(buffer.len(data) + 8)
|
||||
out:bytes(data)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Icns
|
||||
@@ -0,0 +1,324 @@
|
||||
--!strict
|
||||
-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks
|
||||
-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a
|
||||
-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A),
|
||||
-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or
|
||||
-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH
|
||||
-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else
|
||||
-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer
|
||||
-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local PackBits = require("@formats/codecs/compress/PackBits")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ilbm = {
|
||||
name = "ilbm",
|
||||
category = "image",
|
||||
extensions = { "iff", "ilbm", "lbm", "pbm" },
|
||||
mime = { "image/x-ilbm", "image/x-iff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compress: boolean?, -- ByteRun1 (default true)
|
||||
}
|
||||
|
||||
local readu8, readu16 = buffer.readu8, buffer.readu16
|
||||
local function be16(b: buffer, o: number): number
|
||||
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ilbm.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) ~= "FORM" then
|
||||
return 0
|
||||
end
|
||||
local t = r:peek(4, 8)
|
||||
return if t == "ILBM" or t == "PBM " then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o)
|
||||
end
|
||||
local form = buffer.readstring(b, o + 8, 4)
|
||||
if form ~= "ILBM" and form ~= "PBM " then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8)
|
||||
end
|
||||
local chunky = form == "PBM "
|
||||
local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF)
|
||||
local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY")
|
||||
if not bmhd or bmhd.avail < 20 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12)
|
||||
end
|
||||
if not body then
|
||||
return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12)
|
||||
end
|
||||
local q = bmhd.offset
|
||||
local w, h = be16(b, q), be16(b, q + 2)
|
||||
local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10)
|
||||
local trans = be16(b, q + 12)
|
||||
if w == 0 or h == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad size", q)
|
||||
end
|
||||
if comp > 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10)
|
||||
end
|
||||
if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local camg = 0
|
||||
local c = Chunks.find(list, "CAMG")
|
||||
if c and c.avail >= 4 then
|
||||
camg = bit32.byteswap(buffer.readu32(b, c.offset))
|
||||
end
|
||||
local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8)
|
||||
local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham
|
||||
-- palette
|
||||
local pal = buffer.create(1024)
|
||||
local ncol = 0
|
||||
if cmap then
|
||||
ncol = math.min(256, cmap.avail // 3)
|
||||
local low = true
|
||||
for i = 0, ncol * 3 - 1 do
|
||||
low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0
|
||||
end
|
||||
local adjust = low and opts and opts.adjustColors
|
||||
for i = 0, ncol - 1 do
|
||||
local function ch(k: number): number
|
||||
local v = readu8(b, cmap.offset + i * 3 + k)
|
||||
return if adjust then v + bit32.rshift(v, 4) else v
|
||||
end
|
||||
buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
if ncol == 0 and planes <= 8 then
|
||||
local n = bit32.lshift(1, planes)
|
||||
for i = 0, n - 1 do
|
||||
local g = (i * 255) // math.max(1, n - 1)
|
||||
buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000)
|
||||
end
|
||||
ncol = n
|
||||
end
|
||||
if ehb then
|
||||
for i = 0, 31 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255)
|
||||
buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
-- the body, decompressed
|
||||
local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2
|
||||
local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h
|
||||
local raw = buffer.create(total)
|
||||
local truncated
|
||||
if comp == 1 then
|
||||
local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total)
|
||||
truncated = written < total
|
||||
else
|
||||
local n = math.min(total, body.avail)
|
||||
buffer.copy(raw, 0, b, body.offset, n)
|
||||
truncated = n < total
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
if chunky then
|
||||
Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal)
|
||||
if masking == 2 then
|
||||
for i = 0, w * h - 1 do
|
||||
local y, x = i // w, i % w
|
||||
if readu8(raw, y * rowBytes + x) == trans then
|
||||
buffer.writeu32(px, i * 4, 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
local stride = rowBytes * (planes + (if masking == 1 then 1 else 0))
|
||||
local deep = planes >= 24
|
||||
local bits = planes - 2
|
||||
for y = 0, h - 1 do
|
||||
local row = y * stride
|
||||
local pr: number, pg: number, pb: number = 0, 0, 0
|
||||
if ham then
|
||||
local v = buffer.readu32(pal, 0)
|
||||
pr = bit32.band(v, 255)
|
||||
pg = bit32.band(bit32.rshift(v, 8), 255)
|
||||
pb = bit32.band(bit32.rshift(v, 16), 255)
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7)
|
||||
local idx = 0
|
||||
for k = 0, planes - 1 do
|
||||
idx += bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k
|
||||
end
|
||||
local out: number
|
||||
if deep then
|
||||
local a = if planes == 32 then bit32.rshift(idx, 24) % 256 else 255
|
||||
out = bit32.band(idx, 0xFFFFFF) + a * 16777216
|
||||
elseif ham then
|
||||
local ctl = bit32.rshift(idx, bits)
|
||||
local val = bit32.band(idx, bit32.lshift(1, bits) - 1)
|
||||
local v8 = if bits == 4 then val * 17 else val * 4 + bit32.rshift(val, 4)
|
||||
if ctl == 0 then
|
||||
local v = buffer.readu32(pal, val * 4)
|
||||
pr = bit32.band(v, 255)
|
||||
pg = bit32.band(bit32.rshift(v, 8), 255)
|
||||
pb = bit32.band(bit32.rshift(v, 16), 255)
|
||||
elseif ctl == 1 then
|
||||
pb = v8
|
||||
elseif ctl == 2 then
|
||||
pr = v8
|
||||
else
|
||||
pg = v8
|
||||
end
|
||||
out = pr + pg * 256 + pb * 65536 + 0xFF000000
|
||||
else
|
||||
out = buffer.readu32(pal, bit32.band(idx, 255) * 4)
|
||||
if masking == 2 and idx == trans then
|
||||
out = 0
|
||||
end
|
||||
end
|
||||
if masking == 1 then
|
||||
local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1)
|
||||
if m == 0 then
|
||||
out = 0
|
||||
end
|
||||
end
|
||||
buffer.writeu32(px, (y * w + x) * 4, out)
|
||||
end
|
||||
end
|
||||
end
|
||||
if ncol > 0 and planes <= 8 and not ham then
|
||||
local plist: { { number } } = {}
|
||||
for i = 0, (if ehb then 64 else ncol) - 1 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
|
||||
end
|
||||
img.meta.palette = plist
|
||||
end
|
||||
local text: { [string]: string } = {}
|
||||
for _, ch in list do
|
||||
if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then
|
||||
local s = buffer.readstring(b, ch.offset, ch.avail)
|
||||
local key = string.gsub(ch.id, "[^%w]", "")
|
||||
text[string.lower(key)] = (string.gsub(s, "%z+$", ""))
|
||||
end
|
||||
end
|
||||
if next(text) then
|
||||
img.meta.text = text
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ilbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "size must be 1..65535")
|
||||
end
|
||||
local px = img.pixels
|
||||
local cols, alpha = Pixels.colours(px, w * h, 256)
|
||||
local usePal = not alpha and #cols <= 256
|
||||
local planes = if usePal then 1 elseif alpha then 32 else 24
|
||||
if usePal then
|
||||
while bit32.lshift(1, planes) < #cols do
|
||||
planes += 1
|
||||
end
|
||||
end
|
||||
local compress = not (opts and opts.compress == false)
|
||||
local index: { [number]: number } = {}
|
||||
for i, cv in cols do
|
||||
index[cv] = i - 1
|
||||
end
|
||||
local rowBytes = ((w + 15) // 16) * 2
|
||||
local body = Bytes.writer(rowBytes * planes * h)
|
||||
local row = buffer.create(rowBytes)
|
||||
for y = 0, h - 1 do
|
||||
for k = 0, planes - 1 do
|
||||
buffer.fill(row, 0, 0, rowBytes)
|
||||
for x = 0, w - 1 do
|
||||
local v = buffer.readu32(px, (y * w + x) * 4)
|
||||
local idx = if usePal then (index[bit32.band(v, 0xFFFFFF)] or 0) else v
|
||||
if bit32.band(bit32.rshift(idx, k), 1) == 1 then
|
||||
local at = bit32.rshift(x, 3)
|
||||
buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7))))
|
||||
end
|
||||
end
|
||||
if compress then
|
||||
body:bytes(PackBits.encode(row, 0, rowBytes))
|
||||
else
|
||||
body:bytes(row)
|
||||
end
|
||||
end
|
||||
end
|
||||
local bodyData = body:finish()
|
||||
local out = Bytes.writer(buffer.len(bodyData) + 900)
|
||||
out:string("FORM")
|
||||
out:u32be(0)
|
||||
out:string("ILBM")
|
||||
out:string("BMHD")
|
||||
out:u32be(20)
|
||||
out:u16be(w)
|
||||
out:u16be(h)
|
||||
out:u16be(0)
|
||||
out:u16be(0)
|
||||
out:u8(planes)
|
||||
out:u8(0)
|
||||
out:u8(if compress then 1 else 0)
|
||||
out:u8(0)
|
||||
out:u16be(0)
|
||||
out:u8(1)
|
||||
out:u8(1)
|
||||
out:u16be(w)
|
||||
out:u16be(h)
|
||||
if usePal then
|
||||
local n = bit32.lshift(1, planes)
|
||||
out:string("CMAP")
|
||||
out:u32be(n * 3)
|
||||
for i = 1, n do
|
||||
local cv = cols[i] or 0
|
||||
out:u8(bit32.band(cv, 255))
|
||||
out:u8(bit32.band(bit32.rshift(cv, 8), 255))
|
||||
out:u8(bit32.rshift(cv, 16))
|
||||
end
|
||||
if (n * 3) % 2 == 1 then
|
||||
out:u8(0)
|
||||
end
|
||||
end
|
||||
out:string("BODY")
|
||||
out:u32be(buffer.len(bodyData))
|
||||
out:bytes(bodyData)
|
||||
if buffer.len(bodyData) % 2 == 1 then
|
||||
out:u8(0)
|
||||
end
|
||||
local res = out:finish()
|
||||
buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8))
|
||||
return res, nil
|
||||
end
|
||||
|
||||
return Ilbm
|
||||
@@ -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 = {
|
||||
pixelFormat: ("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.pixelFormat) or (if pf == "rgbaf32" then "rgba32f" else pf)
|
||||
local spec = OUT[f]
|
||||
if not spec then
|
||||
return nil, Err.new(Err.ARG, "unknown pixelFormat " .. 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("pixelFormat %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
|
||||
@@ -0,0 +1,266 @@
|
||||
--!strict
|
||||
-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit
|
||||
-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the
|
||||
-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross
|
||||
-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as
|
||||
-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Pcx = {
|
||||
name = "pcx",
|
||||
category = "image",
|
||||
extensions = { "pcx", "pcc", "dcx" },
|
||||
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes
|
||||
}
|
||||
|
||||
local readu8, readu16 = buffer.readu8, buffer.readu16
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Pcx.sniff(r: Bytes.Reader): number
|
||||
if r:size() < 128 then
|
||||
return 0
|
||||
end
|
||||
local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3)
|
||||
if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then
|
||||
return 0
|
||||
end
|
||||
return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 128 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if readu8(b, o) ~= 10 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a PCX file", o)
|
||||
end
|
||||
local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3)
|
||||
local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10)
|
||||
local planes, bpl = readu8(b, o + 65), readu16(b, o + 66)
|
||||
local w, h = x1 - x0 + 1, y1 - y0 + 1
|
||||
if x1 < x0 or y1 < y0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad window", o + 4)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local kind
|
||||
if bpp == 8 and planes == 1 then
|
||||
kind = "pal8"
|
||||
elseif bpp == 8 and (planes == 3 or planes == 4) then
|
||||
kind = "rgb"
|
||||
elseif bpp == 1 and planes >= 1 and planes <= 4 then
|
||||
kind = "planar"
|
||||
elseif (bpp == 2 or bpp == 4) and planes == 1 then
|
||||
kind = "packed"
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3)
|
||||
end
|
||||
if bpl * 8 < w * bpp then
|
||||
return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66)
|
||||
end
|
||||
-- the scan lines (planes after each other per line), RLE across lines
|
||||
local total = bpl * planes * h
|
||||
local raw = buffer.create(total)
|
||||
local p, q = o + 128, 0
|
||||
local truncated = false
|
||||
if enc == 1 then
|
||||
while q < total do
|
||||
if p >= limit then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if c >= 0xC0 then
|
||||
if p >= limit then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local n = math.min(c - 0xC0, total - q)
|
||||
buffer.fill(raw, q, readu8(b, p), n)
|
||||
p += 1
|
||||
q += n
|
||||
else
|
||||
buffer.writeu8(raw, q, c)
|
||||
q += 1
|
||||
end
|
||||
end
|
||||
else
|
||||
local n = math.min(total, limit - p)
|
||||
buffer.copy(raw, 0, b, p, n)
|
||||
p += n
|
||||
truncated = n < total
|
||||
end
|
||||
-- palettes
|
||||
local pal = buffer.create(1024)
|
||||
local function setPal(i: number, rr: number, gg: number, bb: number)
|
||||
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
|
||||
end
|
||||
if kind == "pal8" then
|
||||
local at = limit - 769
|
||||
if at >= p and readu8(b, at) == 12 then
|
||||
for i = 0, 255 do
|
||||
setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3))
|
||||
end
|
||||
else
|
||||
for i = 0, 255 do
|
||||
setPal(i, i, i, i)
|
||||
end
|
||||
end
|
||||
elseif kind == "planar" and planes == 1 then
|
||||
setPal(0, 0, 0, 0)
|
||||
setPal(1, 255, 255, 255)
|
||||
else
|
||||
for i = 0, 15 do
|
||||
setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3))
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
if kind == "pal8" or kind == "packed" then
|
||||
Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal)
|
||||
elseif kind == "planar" then
|
||||
for y = 0, h - 1 do
|
||||
local row = y * bpl * planes
|
||||
for x = 0, w - 1 do
|
||||
local idx = 0
|
||||
for pl = 0, planes - 1 do
|
||||
local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3))
|
||||
idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl)
|
||||
end
|
||||
buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4))
|
||||
end
|
||||
end
|
||||
else
|
||||
for y = 0, h - 1 do
|
||||
local row = y * bpl * planes
|
||||
for x = 0, w - 1 do
|
||||
local d = (y * w + x) * 4
|
||||
buffer.writeu8(px, d, readu8(raw, row + x))
|
||||
buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x))
|
||||
buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x))
|
||||
buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255)
|
||||
end
|
||||
end
|
||||
end
|
||||
if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then
|
||||
local list: { { number } } = {}
|
||||
for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
|
||||
end
|
||||
img.meta.palette = list
|
||||
end
|
||||
local hd, vd = readu16(b, o + 12), readu16(b, o + 14)
|
||||
if hd > 0 and vd > 0 then
|
||||
img.meta.dpi = { x = hd, y = vd }
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- RLE of one plane row into w
|
||||
local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number)
|
||||
local i = 0
|
||||
while i < n do
|
||||
local v = readu8(src, p + i)
|
||||
local run = 1
|
||||
while i + run < n and run < 63 and readu8(src, p + i + run) == v do
|
||||
run += 1
|
||||
end
|
||||
if run > 1 or v >= 0xC0 then
|
||||
out:u8(0xC0 + run)
|
||||
end
|
||||
out:u8(v)
|
||||
i += run
|
||||
end
|
||||
end
|
||||
|
||||
function Pcx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "size must be 1..65535")
|
||||
end
|
||||
local px = img.pixels
|
||||
local cols, alpha = Pixels.colours(px, w * h, 256)
|
||||
local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false)
|
||||
local planes = if usePal then 1 elseif alpha then 4 else 3
|
||||
local bpl = w + w % 2
|
||||
local out = Bytes.writer(128 + w * h * planes + 800)
|
||||
out:u8(10)
|
||||
out:u8(5)
|
||||
out:u8(1)
|
||||
out:u8(8)
|
||||
out:u16le(0)
|
||||
out:u16le(0)
|
||||
out:u16le(w - 1)
|
||||
out:u16le(h - 1)
|
||||
local dpi = img.meta and img.meta.dpi
|
||||
out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72)
|
||||
out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72)
|
||||
out:fill(0, 48)
|
||||
out:u8(0)
|
||||
out:u8(planes)
|
||||
out:u16le(bpl)
|
||||
out:u16le(1)
|
||||
out:fill(0, 58)
|
||||
local row = buffer.create(bpl)
|
||||
local index: { [number]: number } = {}
|
||||
for i, c in cols do
|
||||
index[c] = i - 1
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
for pl = 0, planes - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s = (y * w + x) * 4
|
||||
local v
|
||||
if usePal then
|
||||
v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0
|
||||
else
|
||||
v = readu8(px, s + pl)
|
||||
end
|
||||
buffer.writeu8(row, x, v)
|
||||
end
|
||||
rleRow(out, row, 0, bpl)
|
||||
end
|
||||
end
|
||||
if usePal then
|
||||
out:u8(12)
|
||||
for i = 0, 255 do
|
||||
local c = cols[i + 1] or 0
|
||||
out:u8(bit32.band(c, 255))
|
||||
out:u8(bit32.band(bit32.rshift(c, 8), 255))
|
||||
out:u8(bit32.rshift(c, 16))
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Pcx
|
||||
@@ -0,0 +1,286 @@
|
||||
--!strict
|
||||
-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format"
|
||||
-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB)
|
||||
-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16
|
||||
-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is
|
||||
-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen /
|
||||
-- colour-map files (colormap field 1..3: UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Sgi = {
|
||||
name = "sgi",
|
||||
category = "image",
|
||||
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
|
||||
mime = { "image/sgi", "image/x-rgb" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- rgba16 for 2-byte files (default false: rgba8)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
rle: boolean?, -- RLE storage (default true)
|
||||
name: string?, -- the image name (up to 79 bytes; default meta.text.name)
|
||||
}
|
||||
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
local function be16(b: buffer, o: number): number
|
||||
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
|
||||
end
|
||||
local function be32(b: buffer, o: number): number
|
||||
return bit32.byteswap(readu32(b, o))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Sgi.sniff(r: Bytes.Reader): number
|
||||
if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then
|
||||
return 0
|
||||
end
|
||||
local st, bpc = r:peekU8(2), r:peekU8(3)
|
||||
return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 512 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if be16(b, o) ~= 474 then
|
||||
return nil, Err.new(Err.CORRUPT, "not an SGI image", o)
|
||||
end
|
||||
local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4)
|
||||
local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10)
|
||||
if dim == 1 then
|
||||
h, z = 1, 1
|
||||
elseif dim == 2 then
|
||||
z = 1
|
||||
end
|
||||
if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header", o + 2)
|
||||
end
|
||||
if z > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10)
|
||||
end
|
||||
local cmap = be32(b, o + 104)
|
||||
if cmap ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
-- channel planes as 16-bit samples (8-bit values scaled * 257)
|
||||
local plane = buffer.create(w * h * z * 2)
|
||||
local truncated = false
|
||||
local function put(c: number, row: number, x: number, v: number)
|
||||
buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v)
|
||||
end
|
||||
if rle == 0 then
|
||||
local need = w * h * z * bpc
|
||||
local p = o + 512
|
||||
local avail = math.min(need, limit - p)
|
||||
truncated = avail < need
|
||||
for i = 0, avail // bpc - 1 do
|
||||
local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2)
|
||||
buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v)
|
||||
end
|
||||
else
|
||||
local n = h * z
|
||||
if o + 512 + n * 8 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512)
|
||||
end
|
||||
for c = 0, z - 1 do
|
||||
for row = 0, h - 1 do
|
||||
local i = c * h + row
|
||||
local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4)
|
||||
local p = o + start
|
||||
local stop = math.min(limit, p + len)
|
||||
local x = 0
|
||||
while x < w and p + bpc <= stop do
|
||||
local cnt = if bpc == 1 then readu8(b, p) else be16(b, p)
|
||||
p += bpc
|
||||
local count = bit32.band(cnt, 0x7F)
|
||||
if count == 0 then
|
||||
break
|
||||
end
|
||||
if bit32.band(cnt, 0x80) ~= 0 then
|
||||
for _ = 1, count do
|
||||
if x >= w or p + bpc > stop then
|
||||
break
|
||||
end
|
||||
put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p))
|
||||
p += bpc
|
||||
x += 1
|
||||
end
|
||||
else
|
||||
if p + bpc > stop then
|
||||
break
|
||||
end
|
||||
local v = if bpc == 1 then readu8(b, p) else be16(b, p)
|
||||
p += bpc
|
||||
for _ = 1, count do
|
||||
if x >= w then
|
||||
break
|
||||
end
|
||||
put(c, row, x, v)
|
||||
x += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
if x < w then
|
||||
truncated = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local wide = opts and opts.native and bpc == 2
|
||||
local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8")
|
||||
local px = img.pixels
|
||||
for y = 0, h - 1 do
|
||||
local row = h - 1 - y
|
||||
for x = 0, w - 1 do
|
||||
local function s(c: number): number
|
||||
return buffer.readu16(plane, ((c * h + row) * w + x) * 2)
|
||||
end
|
||||
local rr: number = s(0)
|
||||
local gg: number = if z >= 3 then s(1) else rr
|
||||
local bb: number = if z >= 3 then s(2) else rr
|
||||
local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535
|
||||
local d = (y * w + x)
|
||||
if wide then
|
||||
buffer.writeu16(px, d * 8, rr)
|
||||
buffer.writeu16(px, d * 8 + 2, gg)
|
||||
buffer.writeu16(px, d * 8 + 4, bb)
|
||||
buffer.writeu16(px, d * 8 + 6, aa)
|
||||
else
|
||||
buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216)
|
||||
end
|
||||
end
|
||||
end
|
||||
local name = buffer.readstring(b, o + 24, 80)
|
||||
local zpos = string.find(name, "\0", 1, true)
|
||||
name = if zpos then string.sub(name, 1, zpos - 1) else name
|
||||
if name ~= "" then
|
||||
img.meta.text = { name = name }
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "size must be 1..65535")
|
||||
end
|
||||
local wide = img.format == "rgba16"
|
||||
local bpc = if wide then 2 else 1
|
||||
local px = img.pixels
|
||||
local function sample(x: number, y: number, c: number): number
|
||||
local i = (y * w + x) * 4 + c
|
||||
return if wide then buffer.readu16(px, i * 2) else readu8(px, i)
|
||||
end
|
||||
local z = 3
|
||||
for i = 0, w * h - 1 do
|
||||
if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then
|
||||
z = 4
|
||||
break
|
||||
end
|
||||
end
|
||||
local rle = not (opts and opts.rle == false)
|
||||
local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8)
|
||||
out:u16be(474)
|
||||
out:u8(if rle then 1 else 0)
|
||||
out:u8(bpc)
|
||||
out:u16be(3)
|
||||
out:u16be(w)
|
||||
out:u16be(h)
|
||||
out:u16be(z)
|
||||
out:u32be(0)
|
||||
out:u32be(if wide then 65535 else 255)
|
||||
out:u32be(0)
|
||||
local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or ""
|
||||
name = string.sub(name, 1, 79)
|
||||
out:string(name)
|
||||
out:fill(0, 80 - #name)
|
||||
out:u32be(0)
|
||||
out:fill(0, 404)
|
||||
local function put(v: number)
|
||||
if wide then
|
||||
out:u16be(v)
|
||||
else
|
||||
out:u8(v)
|
||||
end
|
||||
end
|
||||
if not rle then
|
||||
for c = 0, z - 1 do
|
||||
for row = 0, h - 1 do
|
||||
local y = h - 1 - row
|
||||
for x = 0, w - 1 do
|
||||
put(sample(x, y, c))
|
||||
end
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
local tables = out:tell()
|
||||
out:fill(0, h * z * 8)
|
||||
for c = 0, z - 1 do
|
||||
for row = 0, h - 1 do
|
||||
local y = h - 1 - row
|
||||
local start = out:tell()
|
||||
local x = 0
|
||||
while x < w do
|
||||
-- a run of equal samples (>= 3) or literals up to the next run
|
||||
local v = sample(x, y, c)
|
||||
local run = 1
|
||||
while x + run < w and run < 127 and sample(x + run, y, c) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 then
|
||||
put(run)
|
||||
put(v)
|
||||
x += run
|
||||
else
|
||||
local lit = 0
|
||||
while x + lit < w and lit < 127 do
|
||||
local a = sample(x + lit, y, c)
|
||||
if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then
|
||||
break
|
||||
end
|
||||
lit += 1
|
||||
end
|
||||
lit = math.max(lit, 1)
|
||||
put(0x80 + lit)
|
||||
for k = 0, lit - 1 do
|
||||
put(sample(x + k, y, c))
|
||||
end
|
||||
x += lit
|
||||
end
|
||||
end
|
||||
put(0)
|
||||
local i = c * h + row
|
||||
out:setU32be(tables + i * 4, start)
|
||||
out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start)
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Sgi
|
||||
@@ -0,0 +1,247 @@
|
||||
--!strict
|
||||
-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour
|
||||
-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD,
|
||||
-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in
|
||||
-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the
|
||||
-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED),
|
||||
-- raw colour maps (RMT_RAW is ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Sunras = {
|
||||
name = "sunras",
|
||||
category = "image",
|
||||
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
|
||||
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD
|
||||
}
|
||||
|
||||
local MAGIC = "\89\166\106\149"
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local function be32(b: buffer, o: number): number
|
||||
return bit32.byteswap(readu32(b, o))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Sunras.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, MAGIC)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 32 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if buffer.readstring(b, o, 4) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "not a Sun raster", o)
|
||||
end
|
||||
local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28)
|
||||
if w == 0 or h == 0 or w > 65536 or h > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad size", o + 4)
|
||||
end
|
||||
if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12)
|
||||
end
|
||||
if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local p = o + 32
|
||||
if p + maplen > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
|
||||
end
|
||||
local pal = buffer.create(1024)
|
||||
local ncol = 0
|
||||
if maptype == 1 and maplen > 0 then
|
||||
ncol = math.min(256, maplen // 3)
|
||||
for i = 0, ncol - 1 do
|
||||
buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000)
|
||||
end
|
||||
elseif depth == 1 then
|
||||
buffer.writeu32(pal, 0, 0xFFFFFFFF)
|
||||
buffer.writeu32(pal, 4, 0xFF000000)
|
||||
else
|
||||
for i = 0, 255 do
|
||||
buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
p += maplen
|
||||
local stride = ((w * depth + 15) // 16) * 2
|
||||
local total = stride * h
|
||||
local raw = buffer.create(total + 4)
|
||||
local truncated = false
|
||||
if typ == 2 then
|
||||
local q = 0
|
||||
while q < total and p < limit do
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if c ~= 0x80 then
|
||||
buffer.writeu8(raw, q, c)
|
||||
q += 1
|
||||
else
|
||||
if p >= limit then
|
||||
break
|
||||
end
|
||||
local n = readu8(b, p)
|
||||
p += 1
|
||||
if n == 0 then
|
||||
buffer.writeu8(raw, q, 0x80)
|
||||
q += 1
|
||||
else
|
||||
if p >= limit then
|
||||
break
|
||||
end
|
||||
local cnt = math.min(n + 1, total - q)
|
||||
buffer.fill(raw, q, readu8(b, p), cnt)
|
||||
p += 1
|
||||
q += cnt
|
||||
end
|
||||
end
|
||||
end
|
||||
truncated = q < total
|
||||
else
|
||||
local n = math.min(total, limit - p)
|
||||
buffer.copy(raw, 0, b, p, n)
|
||||
truncated = n < total
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
if depth <= 8 then
|
||||
Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal)
|
||||
else
|
||||
local rgb = typ == 3
|
||||
local bytes = depth // 8
|
||||
local alpha = false
|
||||
if bytes == 4 then
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
if readu8(raw, y * stride + x * 4) ~= 0 then
|
||||
alpha = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s = y * stride + x * bytes
|
||||
local a = 255
|
||||
if bytes == 4 then
|
||||
a = if alpha then readu8(raw, s) else 255
|
||||
s += 1
|
||||
end
|
||||
local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
|
||||
local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0
|
||||
buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216)
|
||||
end
|
||||
end
|
||||
end
|
||||
if ncol > 0 then
|
||||
local list: { { number } } = {}
|
||||
for i = 0, ncol - 1 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
|
||||
end
|
||||
img.meta.palette = list
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Sunras.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
local px = img.pixels
|
||||
local alpha = false
|
||||
for i = 0, w * h - 1 do
|
||||
if readu8(px, i * 4 + 3) < 255 then
|
||||
alpha = true
|
||||
break
|
||||
end
|
||||
end
|
||||
local depth = if alpha then 32 else 24
|
||||
local bytes = depth // 8
|
||||
local stride = ((w * depth + 15) // 16) * 2
|
||||
local raw = buffer.create(stride * h)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s, d = (y * w + x) * 4, y * stride + x * bytes
|
||||
if alpha then
|
||||
buffer.writeu8(raw, d, readu8(px, s + 3))
|
||||
d += 1
|
||||
end
|
||||
buffer.writeu8(raw, d, readu8(px, s + 2))
|
||||
buffer.writeu8(raw, d + 1, readu8(px, s + 1))
|
||||
buffer.writeu8(raw, d + 2, readu8(px, s))
|
||||
end
|
||||
end
|
||||
local rle = not (opts and opts.rle == false)
|
||||
local body = raw
|
||||
if rle then
|
||||
local wr = Bytes.writer(stride * h)
|
||||
local i, n = 0, stride * h
|
||||
while i < n do
|
||||
local v = readu8(raw, i)
|
||||
local run = 1
|
||||
while i + run < n and run < 256 and readu8(raw, i + run) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 or v == 0x80 then
|
||||
if run == 1 then
|
||||
wr:u8(0x80)
|
||||
wr:u8(0)
|
||||
else
|
||||
wr:u8(0x80)
|
||||
wr:u8(run - 1)
|
||||
wr:u8(v)
|
||||
end
|
||||
else
|
||||
for _ = 1, run do
|
||||
wr:u8(v)
|
||||
end
|
||||
end
|
||||
i += run
|
||||
end
|
||||
body = wr:finish()
|
||||
end
|
||||
local out = Bytes.writer(32 + buffer.len(body))
|
||||
out:string(MAGIC)
|
||||
out:u32be(w)
|
||||
out:u32be(h)
|
||||
out:u32be(depth)
|
||||
out:u32be(buffer.len(body))
|
||||
out:u32be(if rle then 2 else 1)
|
||||
out:u32be(0)
|
||||
out:u32be(0)
|
||||
out:bytes(body)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Sunras
|
||||
@@ -0,0 +1,162 @@
|
||||
--!strict
|
||||
-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height
|
||||
-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black,
|
||||
-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below
|
||||
-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xbm = {
|
||||
name = "xbm",
|
||||
category = "image",
|
||||
extensions = { "xbm", "bm" },
|
||||
mime = { "image/x-xbitmap", "image/x-xbm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, depths = { 1 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
transparent: boolean?, -- clear bits transparent (default false: white)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _)
|
||||
threshold: number?, -- luminance below this is black (default 128)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xbm.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 256, true)
|
||||
if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n > 2 ^ 26 then
|
||||
return nil, Err.new(Err.LIMIT, "file too large")
|
||||
end
|
||||
local s = buffer.readstring(r.buf, r.base, n)
|
||||
local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)"))
|
||||
local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)"))
|
||||
if not w or not h or w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing width / height defines")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local brace = string.find(s, "{", 1, true)
|
||||
if not brace then
|
||||
return nil, Err.new(Err.CORRUPT, "missing bits array")
|
||||
end
|
||||
local decl = string.sub(s, 1, brace)
|
||||
local short = string.find(decl, "short", 1, true) ~= nil
|
||||
local unit = if short then 16 else 8
|
||||
local per = (w + unit - 1) // unit
|
||||
local want = per * h
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF
|
||||
local got = 0
|
||||
local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ")
|
||||
for tok in string.gmatch(body, "[%w]+") do
|
||||
if got >= want then
|
||||
break
|
||||
end
|
||||
local v
|
||||
if string.match(tok, "^0[xX]%x+$") then
|
||||
v = tonumber(string.sub(tok, 3), 16)
|
||||
elseif string.match(tok, "^0%d+$") then
|
||||
v = tonumber(tok, 8)
|
||||
elseif string.match(tok, "^%d+$") then
|
||||
v = tonumber(tok)
|
||||
end
|
||||
if v then
|
||||
local y, cx = got // per, (got % per) * unit
|
||||
for k = 0, unit - 1 do
|
||||
local x = cx + k
|
||||
if x < w then
|
||||
buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear)
|
||||
end
|
||||
end
|
||||
got += 1
|
||||
end
|
||||
end
|
||||
if got < want then
|
||||
for i = got * unit, want * unit - 1 do
|
||||
local y, x = i // (per * unit), i % (per * unit)
|
||||
if x < w then
|
||||
buffer.writeu32(px, (y * w + x) * 4, clear)
|
||||
end
|
||||
end
|
||||
img.meta.truncated = true
|
||||
end
|
||||
local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)"))
|
||||
local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)"))
|
||||
if hx and hy then
|
||||
img.meta.hotspot = { x = hx, y = hy }
|
||||
end
|
||||
local name = string.match(s, "#define%s+([%w_]-)_?width%s")
|
||||
img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
|
||||
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
|
||||
if name == "" or string.match(name, "^%d") then
|
||||
name = "_" .. name
|
||||
end
|
||||
local th = opts and opts.threshold or 128
|
||||
local px = img.pixels
|
||||
local parts = {
|
||||
string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h),
|
||||
}
|
||||
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
|
||||
if hs then
|
||||
table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y))
|
||||
end
|
||||
table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name))
|
||||
local per = (w + 7) // 8
|
||||
local bytes = {}
|
||||
for y = 0, h - 1 do
|
||||
for bx = 0, per - 1 do
|
||||
local v = 0
|
||||
for k = 0, 7 do
|
||||
local x = bx * 8 + k
|
||||
if x < w then
|
||||
local o = (y * w + x) * 4
|
||||
local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2)
|
||||
if lum < th and buffer.readu8(px, o + 3) >= 128 then
|
||||
v += bit32.lshift(1, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(bytes, string.format("0x%02x", v))
|
||||
end
|
||||
end
|
||||
for i = 1, #bytes, 12 do
|
||||
table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n"))
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
return Xbm
|
||||
@@ -0,0 +1,57 @@
|
||||
--!strict
|
||||
-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's
|
||||
-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100.
|
||||
-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil.
|
||||
local Names = {}
|
||||
|
||||
local HEX: { [string]: number } = {
|
||||
aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF,
|
||||
beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF,
|
||||
blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00,
|
||||
chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C,
|
||||
cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9,
|
||||
darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F,
|
||||
darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F,
|
||||
darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1,
|
||||
darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969,
|
||||
dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF,
|
||||
gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE,
|
||||
green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4,
|
||||
indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA,
|
||||
lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080,
|
||||
lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90,
|
||||
lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA,
|
||||
lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0,
|
||||
lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060,
|
||||
mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB,
|
||||
mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC,
|
||||
mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5,
|
||||
navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23,
|
||||
orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98,
|
||||
paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F,
|
||||
pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000,
|
||||
rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460,
|
||||
seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB,
|
||||
slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F,
|
||||
steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0,
|
||||
violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32,
|
||||
}
|
||||
|
||||
-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces)
|
||||
function Names.lookup(name: string): number?
|
||||
local v = HEX[name]
|
||||
if v then
|
||||
return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536
|
||||
end
|
||||
local n = string.match(name, "^gr[ae]y(%d+)$")
|
||||
if n then
|
||||
local k = tonumber(n) :: number
|
||||
if k <= 100 then
|
||||
local g = math.floor(k * 255 / 100 + 0.49)
|
||||
return g * 0x10101
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Names
|
||||
@@ -0,0 +1,272 @@
|
||||
--!strict
|
||||
-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode:
|
||||
-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 /
|
||||
-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour
|
||||
-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in
|
||||
-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None,
|
||||
-- the fewest chars per pixel; opts.name (default "image").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Names = require("@formats/image/xpm/Names")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xpm = {
|
||||
name = "xpm",
|
||||
category = "image",
|
||||
extensions = { "xpm", "pm" },
|
||||
mime = { "image/x-xpixmap", "image/x-xpm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _)
|
||||
}
|
||||
|
||||
-- the characters of pixel codes (printable ASCII without '"' and '\')
|
||||
local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xpm.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 64, true)
|
||||
if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- colour value -> rgba8 u32, or nil for an unknown name
|
||||
local function colour(v: string): number?
|
||||
local l = string.lower(v)
|
||||
if l == "none" or l == "transparent" then
|
||||
return 0
|
||||
end
|
||||
if string.sub(v, 1, 1) == "#" then
|
||||
local hex = string.sub(v, 2)
|
||||
local n = #hex
|
||||
if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then
|
||||
return nil
|
||||
end
|
||||
local k = n // 3
|
||||
local mx = 16 ^ k - 1
|
||||
local c = 0
|
||||
for i = 0, 2 do
|
||||
local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number
|
||||
c += math.floor(x * 255 / mx + 0.5) * 256 ^ i
|
||||
end
|
||||
return c + 0xFF000000
|
||||
end
|
||||
local rgb = Names.lookup(l)
|
||||
return if rgb then rgb + 0xFF000000 else nil
|
||||
end
|
||||
|
||||
-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2)
|
||||
local function strings(s: string): { string }
|
||||
local out = {}
|
||||
if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then
|
||||
local first = true
|
||||
for line in string.gmatch(s, "[^\n]+") do
|
||||
if first then
|
||||
first = false
|
||||
else
|
||||
table.insert(out, (string.gsub(line, "\r$", "")))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local i, n = 1, #s
|
||||
while i <= n do
|
||||
local c = string.sub(s, i, i)
|
||||
if c == "/" and string.sub(s, i + 1, i + 1) == "*" then
|
||||
local e = string.find(s, "*/", i + 2, true)
|
||||
i = if e then e + 2 else n + 1
|
||||
elseif c == '"' then
|
||||
local parts = {}
|
||||
local j = i + 1
|
||||
while j <= n do
|
||||
local d = string.sub(s, j, j)
|
||||
if d == "\\" then
|
||||
table.insert(parts, string.sub(s, j + 1, j + 1))
|
||||
j += 2
|
||||
elseif d == '"' then
|
||||
break
|
||||
else
|
||||
local e = string.find(s, '["\\]', j)
|
||||
local stop = (e or n + 1) - 1
|
||||
table.insert(parts, string.sub(s, j, stop))
|
||||
j = stop + 1
|
||||
end
|
||||
end
|
||||
table.insert(out, table.concat(parts))
|
||||
i = j + 1
|
||||
else
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local KEYS = { c = true, m = true, g4 = true, g = true, s = true }
|
||||
|
||||
function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n > 2 ^ 27 then
|
||||
return nil, Err.new(Err.LIMIT, "file too large")
|
||||
end
|
||||
local list = strings(buffer.readstring(r.buf, r.base, n))
|
||||
if #list == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no XPM strings")
|
||||
end
|
||||
local vals: { number } = {}
|
||||
for tok in string.gmatch(list[1], "%S+") do
|
||||
table.insert(vals, tonumber(tok) or -1)
|
||||
end
|
||||
local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1
|
||||
if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad values line")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels or nc > 2 ^ 24 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
if #list < 1 + nc then
|
||||
return nil, Err.new(Err.TRUNCATED, "colour table runs past the end")
|
||||
end
|
||||
local map: { [string]: number } = {}
|
||||
local unknown: { string } = {}
|
||||
local palette: { { number } } = {}
|
||||
for i = 1, nc do
|
||||
local line = list[1 + i]
|
||||
local code = string.sub(line, 1, cpp)
|
||||
local rest = string.sub(line, cpp + 1)
|
||||
local found: { [string]: string } = {}
|
||||
local key: string? = nil
|
||||
local acc = {}
|
||||
for tok in string.gmatch(rest, "%S+") do
|
||||
if KEYS[tok] and (key == nil or #acc > 0) then
|
||||
if key then
|
||||
found[key] = table.concat(acc, " ")
|
||||
end
|
||||
key, acc = tok, {}
|
||||
else
|
||||
table.insert(acc, tok)
|
||||
end
|
||||
end
|
||||
if key then
|
||||
found[key] = table.concat(acc, " ")
|
||||
end
|
||||
local v = found.c or found.g or found.g4 or found.m
|
||||
local c = if v then colour(v) else nil
|
||||
if v and not c then
|
||||
c = colour((string.gsub(v, " ", "")))
|
||||
end
|
||||
local cv: number = c or 0xFF000000
|
||||
if not c then
|
||||
table.insert(unknown, v or "")
|
||||
end
|
||||
c = cv
|
||||
map[code] = cv
|
||||
palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) }
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local truncated = false
|
||||
for y = 0, h - 1 do
|
||||
local row = list[2 + nc + y]
|
||||
if not row then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)]
|
||||
buffer.writeu32(px, (y * w + x) * 4, c or 0)
|
||||
end
|
||||
end
|
||||
if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then
|
||||
img.meta.hotspot = { x = vals[5], y = vals[6] }
|
||||
end
|
||||
if #unknown > 0 then
|
||||
img.meta.unknownColours = unknown
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.palette = palette
|
||||
img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
|
||||
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
|
||||
if name == "" or string.match(name, "^%d") then
|
||||
name = "_" .. name
|
||||
end
|
||||
local px = img.pixels
|
||||
local index: { [number]: number } = {}
|
||||
local order: { number } = {}
|
||||
local keys = table.create(w * h, 0)
|
||||
for i = 0, w * h - 1 do
|
||||
local v = buffer.readu32(px, i * 4)
|
||||
local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF)
|
||||
if not index[k] then
|
||||
table.insert(order, k)
|
||||
index[k] = #order
|
||||
end
|
||||
keys[i + 1] = index[k]
|
||||
end
|
||||
local nchars = #CODE_CHARS
|
||||
local cpp = 1
|
||||
while nchars ^ cpp < #order do
|
||||
cpp += 1
|
||||
end
|
||||
local codes: { string } = {}
|
||||
for i = 1, #order do
|
||||
local v, s = i - 1, ""
|
||||
for _ = 1, cpp do
|
||||
local d = v % nchars
|
||||
s ..= string.sub(CODE_CHARS, d + 1, d + 1)
|
||||
v //= nchars
|
||||
end
|
||||
codes[i] = s
|
||||
end
|
||||
local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) }
|
||||
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
|
||||
if hs then
|
||||
table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y))
|
||||
else
|
||||
table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp))
|
||||
end
|
||||
for i, k in order do
|
||||
local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16))
|
||||
table.insert(parts, string.format('"%s c %s",\n', codes[i], col))
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local row = table.create(w, "")
|
||||
for x = 0, w - 1 do
|
||||
row[x + 1] = codes[keys[y * w + x + 1]]
|
||||
end
|
||||
table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n"))
|
||||
end
|
||||
table.insert(parts, "};\n")
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
return Xpm
|
||||
@@ -0,0 +1,293 @@
|
||||
--!strict
|
||||
-- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with
|
||||
-- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png.
|
||||
-- Decode: the stack tree (nested <stack> = groups: isolation="auto" is passThrough; <layer> name / src / x / y /
|
||||
-- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written),
|
||||
-- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it:
|
||||
-- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups)
|
||||
-- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to
|
||||
-- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the <text> / <filter> /
|
||||
-- <selection> elements (ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Xml = require("@formats/codecs/text/Xml")
|
||||
local Blend = require("@formats/codecs/image/Blend")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ora = {
|
||||
name = "ora",
|
||||
category = "layered",
|
||||
extensions = { "ora" },
|
||||
mime = { "image/openraster" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" },
|
||||
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one)
|
||||
composite: boolean?, -- decode mergedimage.png into meta.composite (default true)
|
||||
maxLayers: number?, -- default 10000
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one)
|
||||
composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend)
|
||||
thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MIME = "image/openraster"
|
||||
local OPS: { [string]: string } = {
|
||||
["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay",
|
||||
["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn",
|
||||
["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference",
|
||||
["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color",
|
||||
["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge",
|
||||
}
|
||||
local BACK: { [string]: string } = {}
|
||||
for k, v in OPS do
|
||||
BACK[v] = k
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ora.sniff(r: Bytes.Reader): number
|
||||
-- a zip whose first (stored) entry is "mimetype" holding image/openraster
|
||||
if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function num(v: any, default: number): number
|
||||
local n = tonumber(v)
|
||||
return if n and n == n then n else default
|
||||
end
|
||||
|
||||
function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
|
||||
local zip, zerr = Zip.open(r)
|
||||
if not zip then
|
||||
return nil, zerr
|
||||
end
|
||||
local mt = zip:readString("mimetype")
|
||||
if mt and string.gsub(mt, "%s+$", "") ~= MIME then
|
||||
return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME)
|
||||
end
|
||||
local stackText, serr = zip:readString("stack.xml")
|
||||
if not stackText then
|
||||
return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml")
|
||||
end
|
||||
local doc, xerr = Xml.decode(stackText)
|
||||
if not doc then
|
||||
return nil, xerr
|
||||
end
|
||||
local root = doc.root
|
||||
if not root or root.name ~= "image" then
|
||||
return nil, Err.new(Err.CORRUPT, "stack.xml has no <image> root")
|
||||
end
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
if not decodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook")
|
||||
end
|
||||
local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0)
|
||||
if W < 1 or H < 1 or W > 65536 or H > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad image size")
|
||||
end
|
||||
local maxLayers = opts and opts.maxLayers or 10000
|
||||
local count = 0
|
||||
local function png(path: string): (Types.Image?, Err.Err?)
|
||||
local data, derr = zip:read(path)
|
||||
if not data then
|
||||
return nil, derr or Err.new(Err.CORRUPT, "missing " .. path)
|
||||
end
|
||||
local ok, img, ierr = pcall(decodeImage, data)
|
||||
if not ok or not img then
|
||||
return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring(if ok then ierr else img))
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
-- a <stack>'s children, top first in the file -> bottom to top
|
||||
local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?)
|
||||
local out: { Types.Layer } = {}
|
||||
for _, ch in node.children do
|
||||
if type(ch) ~= "table" then
|
||||
continue
|
||||
end
|
||||
local a = ch.attrs or {}
|
||||
local visible = a.visibility ~= "hidden"
|
||||
local op = a["composite-op"] or "svg:src-over"
|
||||
local blend = OPS[op] or op
|
||||
local x, y = ox + num(a.x, 0), oy + num(a.y, 0)
|
||||
count += 1
|
||||
if count > maxLayers then
|
||||
return nil, Err.new(Err.LIMIT, "too many layers")
|
||||
end
|
||||
if ch.name == "layer" then
|
||||
local src = a.src
|
||||
if type(src) ~= "string" then
|
||||
continue
|
||||
end
|
||||
if string.lower(string.sub(src, -4)) ~= ".png" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src)
|
||||
end
|
||||
local img, perr = png(src)
|
||||
if not img then
|
||||
return nil, perr
|
||||
end
|
||||
local layer = Types.Layered.layer(a.name or src, img :: Types.Image, x, y)
|
||||
layer.opacity = math.clamp(num(a.opacity, 1), 0, 1)
|
||||
layer.visible = visible
|
||||
layer.blend = blend
|
||||
table.insert(out, 1, layer)
|
||||
elseif ch.name == "stack" then
|
||||
local kids, kerr = stack(ch, x, y)
|
||||
if not kids then
|
||||
return nil, kerr
|
||||
end
|
||||
local g = Types.Layered.group(a.name or "group", kids :: { Types.Layer })
|
||||
g.opacity = math.clamp(num(a.opacity, 1), 0, 1)
|
||||
g.visible = visible
|
||||
g.blend = if a.isolation == "isolate" then (if blend == "normal" then "normal" else blend) else "passThrough"
|
||||
table.insert(out, 1, g)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local top = Xml.child(root, "stack")
|
||||
if not top then
|
||||
return nil, Err.new(Err.CORRUPT, "stack.xml has no <stack>")
|
||||
end
|
||||
local layers, lerr = stack(top, 0, 0)
|
||||
if not layers then
|
||||
return nil, lerr
|
||||
end
|
||||
local doc2 = Types.Layered.new(W, H)
|
||||
doc2.layers = layers :: { Types.Layer }
|
||||
if not (opts and opts.composite == false) and zip:find("mergedimage.png") then
|
||||
doc2.meta.composite = png("mergedimage.png")
|
||||
end
|
||||
local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres)
|
||||
if xr and yr then
|
||||
doc2.meta.dpi = { x = xr, y = yr }
|
||||
end
|
||||
doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count }
|
||||
return doc2, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- nearest-neighbour downscale to fit max x max
|
||||
local function thumbnail(img: Types.Image, max: number): Types.Image
|
||||
local w, h = img.width, img.height
|
||||
local s = math.min(1, max / math.max(w, h))
|
||||
local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s))
|
||||
local t = Types.Image.new(tw, th, "rgba8")
|
||||
for y = 0, th - 1 do
|
||||
local sy = math.min(h - 1, math.floor(y / s))
|
||||
for x = 0, tw - 1 do
|
||||
local sx = math.min(w - 1, math.floor(x / s))
|
||||
buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4))
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then
|
||||
return nil, Err.new(Err.ARG, "needs a Layered document")
|
||||
end
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
if not encodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook")
|
||||
end
|
||||
local W, H = doc.width, doc.height
|
||||
local zw = Zip.writer()
|
||||
zw:add("mimetype", MIME, { method = "store" })
|
||||
local files: { { any } } = {}
|
||||
local n = 0
|
||||
local function png(img: Types.Image, label: string): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" then
|
||||
return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images")
|
||||
end
|
||||
local ok, data, err = pcall(encodeImage, img, "png")
|
||||
if not ok or not data then
|
||||
return nil, Err.new(Err.ARG, label .. ": " .. tostring(if ok then err else data))
|
||||
end
|
||||
return data, nil
|
||||
end
|
||||
-- layers bottom to top -> xml children top first
|
||||
local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?)
|
||||
local kids = {}
|
||||
for i = #layers, 1, -1 do
|
||||
local l = layers[i]
|
||||
local attrs: { [string]: string } = {
|
||||
name = l.name or "",
|
||||
opacity = string.format("%.6g", l.opacity or 1),
|
||||
visibility = if l.visible == false then "hidden" else "visible",
|
||||
}
|
||||
if l.children then
|
||||
attrs.isolation = if l.blend == "passThrough" then "auto" else "isolate"
|
||||
if l.blend ~= "passThrough" then
|
||||
attrs["composite-op"] = BACK[l.blend] or l.blend
|
||||
end
|
||||
local sub, serr = stack(l.children)
|
||||
if not sub then
|
||||
return nil, serr
|
||||
end
|
||||
table.insert(kids, Xml.element("stack", attrs, sub))
|
||||
else
|
||||
n += 1
|
||||
local path = string.format("data/layer%03d.png", n)
|
||||
local data, perr = png(l.image, "layer " .. tostring(l.name))
|
||||
if not data then
|
||||
return nil, perr
|
||||
end
|
||||
table.insert(files, { path, data })
|
||||
attrs.src = path
|
||||
attrs.x = tostring(math.floor(l.x or 0))
|
||||
attrs.y = tostring(math.floor(l.y or 0))
|
||||
attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over"
|
||||
table.insert(kids, Xml.element("layer", attrs))
|
||||
end
|
||||
end
|
||||
return kids, nil
|
||||
end
|
||||
local kids, kerr = stack(doc.layers)
|
||||
if not kids then
|
||||
return nil, kerr
|
||||
end
|
||||
local rootAttrs: { [string]: string } = { version = "0.0.6", w = tostring(W), h = tostring(H) }
|
||||
local dpi = doc.meta and doc.meta.dpi
|
||||
if dpi then
|
||||
rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y)
|
||||
end
|
||||
local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids :: any) })), { indent = 1 })
|
||||
zw:add("stack.xml", xml :: string)
|
||||
for _, f in files do
|
||||
zw:add(f[1], f[2], { method = "store" })
|
||||
end
|
||||
local merged = opts and opts.composite
|
||||
if not merged then
|
||||
local m = Types.Image.new(W, H, "rgba8")
|
||||
Blend.flatten(doc.layers, m.pixels, W, H, false)
|
||||
merged = m
|
||||
end
|
||||
local mdata, merr = png(merged :: Types.Image, "mergedimage")
|
||||
if not mdata then
|
||||
return nil, merr
|
||||
end
|
||||
zw:add("mergedimage.png", mdata, { method = "store" })
|
||||
if not (opts and opts.thumbnail == false) then
|
||||
local tdata, terr = png(thumbnail(merged :: Types.Image, 256), "thumbnail")
|
||||
if not tdata then
|
||||
return nil, terr
|
||||
end
|
||||
zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" })
|
||||
end
|
||||
return zw:finish()
|
||||
end
|
||||
|
||||
return Ora
|
||||
Reference in new issue
Block a user