ws-tex: image/dds (read every DXGI / legacy FourCC / bit-mask format, mips, cube, arrays, volumes; write rgba8 / BC1/3/4/5 / 16-bit / float)
New shared codecs: codecs/image/Texel (uncompressed GPU texel formats incl. packed, shared exponent, YUY2), codecs/image/Texture (dispatch over Bcn / Etc / Texel, surface assembly, mip halving). Tested against nvcompress / nvassemble / ImageMagick files (Pillow per surface, Godot for BC6H floats), hand-written formats, and our files read back by Pillow + nvddsinfo.
This commit is contained in:
1 parent
be643a66c8
commit
672948f7d7
8 files changed
+1691
No files matched your search
@@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|
||||
|---|---|---|---|---|---|---|
|
||||
| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` |
|
||||
| image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` |
|
||||
| image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` |
|
||||
| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` |
|
||||
| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` |
|
||||
@@ -123,6 +124,8 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
|
||||
- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
|
||||
- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
|
||||
- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
|
||||
- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
|
||||
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
|
||||
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
|
||||
@@ -26,6 +26,18 @@ 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 = "gif",
|
||||
category = "image",
|
||||
|
||||
@@ -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,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 = {
|
||||
format: ("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.format) 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 format " .. 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("format %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,212 @@
|
||||
-- image/dds tests: files from NVIDIA Texture Tools (BGRA, BC1..BC7 incl. BC6H, mips, DX10, cube / array / volume)
|
||||
-- and ImageMagick against every surface's reference decode (Pillow per surface, Godot floats for BC6H); hand-written
|
||||
-- uncompressed DXGI / legacy / FourCC formats against their values (rgba8 and native floats); our encoder's files read
|
||||
-- by Pillow and nvddsinfo, and round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dds.py.
|
||||
local T = require("@tests/T")
|
||||
local Dds = require("@formats/image/dds")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/dds")
|
||||
|
||||
local t = T.suite("dds")
|
||||
|
||||
t:eq(Dds.name, "dds", "name")
|
||||
t:check(Dds.caps.decode and Dds.caps.encode, "caps")
|
||||
|
||||
local function dec(data: any, opts: any?): (any, any)
|
||||
return Dds.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
|
||||
end
|
||||
|
||||
local function maxDiff(a: buffer, b: buffer, n: number): number
|
||||
local worst = 0
|
||||
for i = 0, n * 4 - 1 do
|
||||
worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i)))
|
||||
end
|
||||
return worst
|
||||
end
|
||||
|
||||
-- tool-written files
|
||||
local surfaces = 0
|
||||
for _, c in Fx.cases do
|
||||
local img, err = dec(c.data, { mips = true })
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:eq(img.meta.layout, c.layout, c.name .. ": layout")
|
||||
t:eq(img.meta.source.mips, c.mips, c.name .. ": mips")
|
||||
local frames = img.frames or { { image = img } }
|
||||
local native = nil
|
||||
for _, s in c.surfaces do
|
||||
local im
|
||||
if s.level == 0 then
|
||||
local idx = s.layer * (if c.layout == "volume" then c.depth else 1) + s.slice + 1
|
||||
im = frames[idx] and frames[idx].image
|
||||
else
|
||||
im = img.meta.mipmaps and img.meta.mipmaps[s.level]
|
||||
end
|
||||
local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice)
|
||||
t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size")
|
||||
if s.floats then
|
||||
native = native or dec(c.data, { native = true, mips = true })
|
||||
local nim = if s.level == 0 then native else native.meta.mipmaps[s.level]
|
||||
t:eq(nim.format, "rgbaf32", label .. ": native rgbaf32")
|
||||
local g = buffer.fromstring(s.floats)
|
||||
local worst = 0
|
||||
for i = 0, s.w * s.h * 4 - 1 do
|
||||
if i % 4 ~= 3 then
|
||||
local a, b = buffer.readf32(nim.pixels, i * 4), buffer.readf32(g, i * 4)
|
||||
worst = math.max(worst, math.abs(a - b) / math.max(math.abs(b), 1e-3))
|
||||
end
|
||||
end
|
||||
t:check(worst < 1e-3, label .. ": floats against Godot " .. worst)
|
||||
else
|
||||
local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h)
|
||||
t:check(d <= s.tol, string.format("%s: %d off the reference", label, d))
|
||||
end
|
||||
surfaces += 1
|
||||
end
|
||||
-- surfaces = false keeps only the first
|
||||
local one = dec(c.data, { surfaces = false })
|
||||
t:check(one and one.frames == nil, c.name .. ": surfaces = false")
|
||||
end
|
||||
t:note("%d tool-written files, %d surfaces match the references", #Fx.cases, surfaces)
|
||||
|
||||
-- hand-written formats
|
||||
for _, c in Fx.hand do
|
||||
local img, err = dec(c.data)
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
local n = img.width * img.height
|
||||
local d = maxDiff(img.pixels, buffer.fromstring(c.rgba8), n)
|
||||
t:check(d <= 1, string.format("%s: rgba8 %d off", c.name, d))
|
||||
if c.floats then
|
||||
local nimg = dec(c.data, { native = true })
|
||||
local f = buffer.fromstring(c.floats)
|
||||
local worst = 0
|
||||
local bpp = Types.BPP[nimg.format]
|
||||
for i = 0, n * 4 - 1 do
|
||||
local want = buffer.readf32(f, i * 4)
|
||||
local got
|
||||
if nimg.format == "rgbaf32" then
|
||||
got = buffer.readf32(nimg.pixels, i * 4)
|
||||
elseif nimg.format == "rgba16" then
|
||||
got = buffer.readu16(nimg.pixels, i * 2) / 65535
|
||||
else
|
||||
got = buffer.readu8(nimg.pixels, i) / 255
|
||||
end
|
||||
worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want)))
|
||||
end
|
||||
local tol = if nimg.format == "rgba8" then 1 / 255 elseif nimg.format == "rgba16" then 1 / 65535 else 1e-6
|
||||
t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", c.name, nimg.format, worst))
|
||||
t:check(bpp ~= nil, c.name .. ": a standard format")
|
||||
end
|
||||
end
|
||||
t:note("%d hand-written formats match", #Fx.hand)
|
||||
|
||||
-- our encoder: Pillow / nvddsinfo read the files, and they round-trip
|
||||
local function source(w: number, h: number): buffer
|
||||
local px = buffer.create(w * h * 4)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local o = (y * w + x) * 4
|
||||
buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return px
|
||||
end
|
||||
local src = source(37, 23)
|
||||
for _, o in Fx.ours do
|
||||
local img, err = dec(o.data, { mips = true, native = true })
|
||||
t:check(img, o.name .. ": " .. tostring(err))
|
||||
t:check(o.width == img.width and o.height == img.height, o.name .. ": nvddsinfo size")
|
||||
local mips = img.meta.source.mips
|
||||
t:eq(math.max(1, o.mipcount), mips, o.name .. ": nvddsinfo mip count")
|
||||
if string.find(o.name, "mips") or string.find(o.name, "rgba16") or string.find(o.name, "rgba32f") or string.find(o.name, "cube") or string.find(o.name, "dx10") then
|
||||
if not string.find(o.name, "rgba16f") and not string.find(o.name, "array") then
|
||||
t:check(mips > 1 and #img.meta.mipmaps == mips - 1, o.name .. ": a mip chain")
|
||||
end
|
||||
end
|
||||
if o.pillow then
|
||||
local p = buffer.fromstring(o.pillow)
|
||||
local exact = string.find(o.name, "rgba8") or string.find(o.name, "bgra8")
|
||||
local d = maxDiff(img.pixels, p, img.width * img.height)
|
||||
t:check(d == 0, string.format("%s: Pillow reads %d off our decode", o.name, d))
|
||||
if exact then
|
||||
t:eq(buffer.tostring(p), buffer.tostring(src), o.name .. ": Pillow reads the source exactly")
|
||||
end
|
||||
end
|
||||
if string.find(o.name, "cube") then
|
||||
t:eq(img.meta.layout, "cube", o.name .. ": cube")
|
||||
t:eq(#img.frames, 6, o.name .. ": 6 faces")
|
||||
t:check(string.find(o.caps2, "FE00", 1, true) ~= nil, o.name .. ": nvddsinfo sees all faces")
|
||||
elseif string.find(o.name, "array") then
|
||||
t:eq(#img.frames, 6, o.name .. ": 6 layers")
|
||||
t:eq(o.array, "6", o.name .. ": nvddsinfo array size")
|
||||
end
|
||||
if string.find(o.name, "rgba32f") then
|
||||
t:check(string.find(o.dxgi, "R32G32B32A32_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
|
||||
t:eq(img.format, "rgbaf32", o.name .. ": rgbaf32")
|
||||
t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-6, o.name .. ": float values kept")
|
||||
elseif string.find(o.name, "rgba16f") then
|
||||
t:check(string.find(o.dxgi, "R16G16B16A16_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
|
||||
t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-3, o.name .. ": half values")
|
||||
elseif string.find(o.name, "rgba16") then
|
||||
t:check(string.find(o.dxgi, "R16G16B16A16_UNORM", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
|
||||
t:eq(img.format, "rgba16", o.name .. ": rgba16")
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read by Pillow / nvddsinfo", #Fx.ours)
|
||||
|
||||
-- round trips
|
||||
do
|
||||
local img = Types.Image.new(37, 23)
|
||||
img.pixels = src
|
||||
for _, f in { "rgba8", "bgra8" } do
|
||||
local back = dec(Dds.encode(img, { format = f :: any }) :: buffer)
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(src), f .. " round trip")
|
||||
end
|
||||
local f = Types.Image.new(3, 2, "rgbaf32")
|
||||
for i = 0, 23 do
|
||||
buffer.writef32(f.pixels, i * 4, i * 0.37 - 2)
|
||||
end
|
||||
local back = dec(Dds.encode(f) :: buffer, { native = true })
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip")
|
||||
local _, e1 = Dds.encode(f, { format = "bc1" })
|
||||
t:check(e1 and e1.code == Err.ARG, "bc1 needs rgba8")
|
||||
local _, e2 = Dds.encode(img, { format = "bc7" :: any })
|
||||
t:check(e2 and e2.code == Err.ARG, "no bc7 encoder")
|
||||
end
|
||||
|
||||
-- sniff and errors
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
t:eq(Dds.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
|
||||
t:eq(Dds.sniff(Bytes.reader(buffer.fromstring("DDX \124\0\0\0"))), 0, "sniff other")
|
||||
local _, e = dec(string.sub(c.data, 1, 100))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = dec(string.sub(c.data, 1, 140))
|
||||
t:check(e2 and e2.code == Err.TRUNCATED, "no pixels: " .. tostring(e2))
|
||||
local bad = buffer.fromstring(c.data)
|
||||
buffer.writeu32(bad, 4, 100)
|
||||
local _, e3 = dec(bad)
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "bad header size")
|
||||
local _, e4 = dec(c.data, { maxPixels = 10 })
|
||||
t:check(e4 and e4.code == Err.LIMIT, "limit")
|
||||
local info = Dds.info(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(info and info.width > 0, "info")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i, c in Fx.cases do
|
||||
if i % 3 == 0 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
for _, c in Fx.hand do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return dec(b, { mips = true })
|
||||
end, samples, { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,75 @@
|
||||
-- tools/fixtures/_tex_encode.luau: our texture encoders' output for the reference tools to read (run by
|
||||
-- tools/fixtures/{dds,ktx,exr}.py as `luau tools/fixtures/_tex_encode.luau -a <format>`). Prints "name\thex" lines.
|
||||
-- The source images are generated here (tools/fixtures/_tex_reference.py makes the same ones: source()).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local which = ({ ... } :: { string })[1] or "dds"
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local t = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(t)
|
||||
end
|
||||
|
||||
-- the test pattern (x, y, channel) -> 0..1, the same formula as _tex_reference.source()
|
||||
local function value(x: number, y: number, c: number, w: number, h: number, salt: number): number
|
||||
if c == 0 then
|
||||
return x / math.max(1, w - 1)
|
||||
elseif c == 1 then
|
||||
return y / math.max(1, h - 1)
|
||||
elseif c == 2 then
|
||||
return ((x * 7 + y * 13 + salt * 31) % 64) / 63
|
||||
end
|
||||
return ((x + y + salt) % 5) / 4
|
||||
end
|
||||
|
||||
local function image(w: number, h: number, fmt: string, salt: number, scale: number?): Types.Image
|
||||
local img = Types.Image.new(w, h, fmt :: any)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
for c = 0, 3 do
|
||||
local v = value(x, y, c, w, h, salt)
|
||||
local o = (y * w + x) * 4 + c
|
||||
if fmt == "rgba8" then
|
||||
buffer.writeu8(img.pixels, o, math.floor(v * 255 + 0.5))
|
||||
elseif fmt == "rgba16" then
|
||||
buffer.writeu16(img.pixels, o * 2, math.floor(v * 65535 + 0.5))
|
||||
else
|
||||
buffer.writef32(img.pixels, o * 4, if c < 3 then v * (scale or 1) else v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
local function emit(name: string, b: buffer?, err: any?)
|
||||
if not b then
|
||||
error(name .. ": " .. tostring(err))
|
||||
end
|
||||
print(name .. "\t" .. hex(b))
|
||||
end
|
||||
|
||||
if which == "dds" then
|
||||
local Dds = require("@formats/image/dds")
|
||||
local img = image(37, 23, "rgba8", 0)
|
||||
for _, f in { "rgba8", "bgra8", "bc1", "bc3", "bc4", "bc5" } do
|
||||
emit("ours_" .. f .. ".dds", Dds.encode(img, { format = f :: any }))
|
||||
emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { format = f :: any, mips = true }))
|
||||
end
|
||||
emit("ours_rgba8_dx10.dds", Dds.encode(img, { dx10 = true, mips = true }))
|
||||
emit("ours_rgba16.dds", Dds.encode(image(37, 23, "rgba16", 0), { mips = true }))
|
||||
emit("ours_rgba32f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
|
||||
emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { format = "rgba16f" }))
|
||||
local cube = image(16, 16, "rgba8", 0)
|
||||
cube.frames = {}
|
||||
for i = 1, 6 do
|
||||
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
cube.meta.layout = "cube"
|
||||
emit("ours_cube.dds", Dds.encode(cube, { mips = true }))
|
||||
cube.meta.layout = "array"
|
||||
emit("ours_array_bc1.dds", Dds.encode(cube, { format = "bc1" }))
|
||||
end
|
||||
@@ -0,0 +1,332 @@
|
||||
# DDS fixtures (tools/fixtures.py):
|
||||
# - files written by NVIDIA Texture Tools (nvcompress: uncompressed BGRA, BC1 / BC1a / BC2 / BC3 / BC4 / BC5 / BC6H /
|
||||
# BC7, with and without mip chains, legacy and DX10 headers; nvassemble: cube maps, arrays, volumes) and by
|
||||
# ImageMagick (none / DXT1 / DXT5 with mip maps);
|
||||
# - hand-written ones for the uncompressed DXGI and legacy formats nothing here writes (floats, snorm, packed,
|
||||
# shared exponent, YUY2, luminance, bit masks, D3DFMT numbers), with the values they hold;
|
||||
# - our encoder's files (tools/fixtures/_tex_encode.luau -a dds) read back by Pillow and nvddsinfo.
|
||||
# Reference pixels: every surface is cut out here (an independent walk of the DDS layout) and decoded by Pillow
|
||||
# (BCn through a one-surface DX10 file; BC6H by Godot as floats); the hand-written files carry their expected values.
|
||||
# tests/gen/dds.luau { cases = { { name, data, layout, mips, layers, depth, surfaces = { { level, layer, slice, w,
|
||||
# h, rgba?, floats?, tol } } } }, ours = { { name, data, pillow?, info } } }
|
||||
import importlib.util, json, math, os, random, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
|
||||
R = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(R)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/dds", "src/Formats/codecs/image/Bcn", "src/Formats/codecs/image/Texture.luau"]
|
||||
|
||||
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc6h": 16, "bc7": 16}
|
||||
DXGI_BC = {70: "bc1", 71: "bc1", 72: "bc1", 73: "bc2", 74: "bc2", 75: "bc2", 76: "bc3", 77: "bc3", 78: "bc3", 79: "bc4",
|
||||
80: "bc4", 82: "bc5", 83: "bc5", 94: "bc6h", 95: "bc6h", 97: "bc7", 98: "bc7", 99: "bc7"}
|
||||
FOURCC_BC = {b"DXT1": "bc1", b"DXT3": "bc2", b"DXT5": "bc3", b"ATI1": "bc4", b"BC4U": "bc4", b"ATI2": "bc5", b"BC5U": "bc5"}
|
||||
|
||||
|
||||
def png(w, h, rgba):
|
||||
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
|
||||
chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def source(w, h, salt=0):
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
r = x / max(1, w - 1)
|
||||
g = y / max(1, h - 1)
|
||||
b = ((x * 7 + y * 13 + salt * 31) % 64) / 63
|
||||
a = ((x + y + salt) % 5) / 4
|
||||
out += bytes(int(v * 255 + 0.5) for v in (r, g, b, a))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def layout(data):
|
||||
"""an independent walk of a DDS file: (info, [(level, layer, slice, w, h, format, offset, size)])"""
|
||||
flags, h, w, pitch, depth, mips = struct.unpack("<6I", data[8:32])
|
||||
pf_flags, fourcc, bits, rm, gm, bm, am = struct.unpack("<I4s5I", data[80:108])
|
||||
caps2 = struct.unpack("<I", data[112:116])[0]
|
||||
mips = max(1, mips if flags & 0x20000 else 1)
|
||||
off, layers, fmt, cube = 128, 1, None, False
|
||||
if pf_flags & 4 and fourcc == b"DX10":
|
||||
dxgi, dim, misc, arr = struct.unpack("<4I", data[128:144])
|
||||
off, layers = 148, max(1, arr)
|
||||
fmt = DXGI_BC.get(dxgi) or ("dxgi%d" % dxgi)
|
||||
cube = bool(misc & 4)
|
||||
volume = dim == 4
|
||||
elif pf_flags & 4:
|
||||
fmt = FOURCC_BC[fourcc]
|
||||
volume = bool(caps2 & 0x200000)
|
||||
cube = bool(caps2 & 0x200)
|
||||
else:
|
||||
fmt = "rgb%d" % bits
|
||||
volume = bool(caps2 & 0x200000)
|
||||
cube = bool(caps2 & 0x200)
|
||||
d0 = max(1, depth) if volume else 1
|
||||
count = layers * (6 if cube else 1)
|
||||
out = []
|
||||
for layer in range(count):
|
||||
lw, lh, ld = w, h, d0
|
||||
for level in range(mips):
|
||||
if fmt in BLOCK:
|
||||
size = ((lw + 3) // 4) * ((lh + 3) // 4) * BLOCK[fmt]
|
||||
elif fmt.startswith("rgb"):
|
||||
size = lw * lh * bits // 8
|
||||
else:
|
||||
size = lw * lh * 4 # dxgi28 / 87 (the only uncompressed DX10 ones nvassemble writes)
|
||||
for s in range(ld):
|
||||
out.append((level, layer, s, lw, lh, fmt, off, size))
|
||||
off += size
|
||||
lw, lh, ld = max(1, lw // 2), max(1, lh // 2), max(1, ld // 2)
|
||||
return {"w": w, "h": h, "mips": mips, "layers": layers, "cube": cube, "volume": volume, "depth": d0, "masks": (rm, gm, bm, am), "bits": bits}, out
|
||||
|
||||
|
||||
def mask_decode(raw, bits, masks):
|
||||
"""legacy bit-mask pixels -> rgba8 with rounding (the Texel rule)"""
|
||||
out = bytearray()
|
||||
nb = bits // 8
|
||||
for i in range(0, len(raw), nb):
|
||||
v = int.from_bytes(raw[i:i + nb], "little")
|
||||
px = []
|
||||
for k, m in enumerate(masks):
|
||||
if m == 0:
|
||||
px.append(255 if k == 3 else 0)
|
||||
continue
|
||||
sh = (m & -m).bit_length() - 1
|
||||
mx = m >> sh
|
||||
px.append(int(((v & m) >> sh) / mx * 255 + 0.5))
|
||||
out += bytes(px)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def references(ctx, cases):
|
||||
"""fill c["surfaces"] for files from the tools: Pillow per surface (BCn / masks), Godot floats for BC6H"""
|
||||
pil_files, pil_targets, gd_jobs, gd_targets = [], [], [], []
|
||||
for c in cases:
|
||||
info, surf = layout(c["data"])
|
||||
c["layout"] = "volume" if info["volume"] else ("cube" if info["cube"] else ("array" if info["layers"] > 1 else "2d"))
|
||||
c["mips"], c["layers"], c["depth"] = info["mips"], info["layers"], info["depth"]
|
||||
c["surfaces"] = []
|
||||
for (level, layer, s, w, h, fmt, off, size) in surf:
|
||||
if level > 0 and (layer > 0 or s > 0):
|
||||
continue
|
||||
sd = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": 0}
|
||||
raw = c["data"][off:off + size]
|
||||
c["surfaces"].append(sd)
|
||||
if fmt == "bc6h":
|
||||
gd_jobs.append((raw, w, h, R.GODOT["bc6h"], True))
|
||||
gd_targets.append(sd)
|
||||
elif fmt in BLOCK:
|
||||
dx = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc7": 98}[fmt]
|
||||
pil_files.append(R.dds_dx10(w, h, dx, raw))
|
||||
pil_targets.append((sd, fmt))
|
||||
elif fmt.startswith("rgb"):
|
||||
sd["rgba"] = mask_decode(raw, info["bits"], info["masks"])
|
||||
elif fmt == "dxgi28":
|
||||
sd["rgba"] = raw
|
||||
elif fmt == "dxgi87":
|
||||
sd["rgba"] = bytes(raw[i + k] for i in range(0, len(raw), 4) for k in (2, 1, 0, 3))
|
||||
for (sd, fmt), (mode, w, h, raw) in zip(pil_targets, R.pillow(ctx, pil_files)):
|
||||
rgba = R.rgba_from(mode, raw)
|
||||
if fmt == "bc5":
|
||||
rgba = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(rgba))
|
||||
sd["rgba"] = rgba
|
||||
for sd, out in zip(gd_targets, R.godot(ctx, gd_jobs)):
|
||||
sd["floats"] = out
|
||||
|
||||
|
||||
def hand_cases(rng):
|
||||
"""uncompressed formats with known values: (name, dds bytes, expected rgba8, expected floats or None)"""
|
||||
W, H = 5, 3
|
||||
cases = []
|
||||
|
||||
def f32(v):
|
||||
return struct.unpack("<f", struct.pack("<f", v))[0]
|
||||
|
||||
def half(v):
|
||||
return struct.unpack("<e", struct.pack("<e", v))[0]
|
||||
|
||||
def q8(v):
|
||||
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
|
||||
|
||||
def add(name, dds, texels):
|
||||
"""texels: list of (r, g, b, a) floats (the native values) -> expected rgba8 by the rules"""
|
||||
cases.append({"name": name, "data": dds, "rgba8": bytes(q8(v) for t in texels for v in t),
|
||||
"floats": b"".join(struct.pack("<4f", *t) for t in texels)})
|
||||
|
||||
# floats
|
||||
vals = [(rng.uniform(-0.5, 3), rng.uniform(0, 1), rng.uniform(0, 1.5), rng.uniform(0, 1)) for _ in range(W * H)]
|
||||
data = b"".join(struct.pack("<4f", *v) for v in vals)
|
||||
add("dxgi R32G32B32A32_FLOAT", R.dds_dx10(W, H, 2, data), [tuple(f32(x) for x in v) for v in vals])
|
||||
data = b"".join(struct.pack("<4e", *v) for v in vals)
|
||||
add("dxgi R16G16B16A16_FLOAT", R.dds_dx10(W, H, 10, data), [tuple(half(x) for x in v) for v in vals])
|
||||
add("d3dfmt 113 (A16B16G16R16F)", R.dds_fourcc(W, H, struct.pack("<I", 113), data), [tuple(half(x) for x in v) for v in vals])
|
||||
data = b"".join(struct.pack("<f", v[0]) for v in vals)
|
||||
add("dxgi R32_FLOAT (grey)", R.dds_dx10(W, H, 41, data), [(f32(v[0]),) * 3 + (1.0,) for v in vals])
|
||||
data = b"".join(struct.pack("<2e", v[0], v[1]) for v in vals)
|
||||
add("dxgi R16G16_FLOAT", R.dds_dx10(W, H, 34, data), [(half(v[0]), half(v[1]), 0.0, 1.0) for v in vals])
|
||||
data = b"".join(struct.pack("<3f", *v[:3]) for v in vals)
|
||||
add("dxgi R32G32B32_FLOAT", R.dds_dx10(W, H, 6, data), [tuple(f32(x) for x in v[:3]) + (1.0,) for v in vals])
|
||||
# unorm / snorm
|
||||
u16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W * H)]
|
||||
add("dxgi R16G16B16A16_UNORM", R.dds_dx10(W, H, 11, b"".join(struct.pack("<4H", *v) for v in u16)),
|
||||
[tuple(x / 65535 for x in v) for v in u16])
|
||||
add("d3dfmt 36 (A16B16G16R16)", R.dds_fourcc(W, H, struct.pack("<I", 36), b"".join(struct.pack("<4H", *v) for v in u16)),
|
||||
[tuple(x / 65535 for x in v) for v in u16])
|
||||
s8 = [tuple(rng.randrange(-128, 128) for _ in range(4)) for _ in range(W * H)]
|
||||
cases_s8 = [tuple(max(x, -127) / 127 for x in v) for v in s8]
|
||||
cases.append({"name": "dxgi R8G8B8A8_SNORM", "data": R.dds_dx10(W, H, 31, b"".join(struct.pack("<4b", *v) for v in s8)),
|
||||
"rgba8": bytes(max(x, -127) + 128 for v in s8 for x in v),
|
||||
"floats": b"".join(struct.pack("<4f", *v) for v in cases_s8)})
|
||||
u8 = [tuple(rng.randrange(256) for _ in range(4)) for _ in range(W * H)]
|
||||
add("dxgi R8_UNORM (grey)", R.dds_dx10(W, H, 61, bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
|
||||
add("dxgi R8G8_UNORM", R.dds_dx10(W, H, 49, bytes(x for v in u8 for x in v[:2])), [(v[0] / 255, v[1] / 255, 0.0, 1.0) for v in u8])
|
||||
add("dxgi A8_UNORM", R.dds_dx10(W, H, 65, bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
|
||||
add("dxgi B8G8R8X8_UNORM", R.dds_dx10(W, H, 88, bytes(x for v in u8 for x in (v[2], v[1], v[0], 7))),
|
||||
[(v[0] / 255, v[1] / 255, v[2] / 255, 1.0) for v in u8])
|
||||
add("dxgi R16_UNORM (grey)", R.dds_dx10(W, H, 56, b"".join(struct.pack("<H", v[0]) for v in u16)), [(v[0] / 65535,) * 3 + (1.0,) for v in u16])
|
||||
# packed
|
||||
p32 = [rng.getrandbits(32) for _ in range(W * H)]
|
||||
add("dxgi R10G10B10A2_UNORM", R.dds_dx10(W, H, 24, b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
|
||||
|
||||
def uf(v, mb):
|
||||
e, m = v >> mb, v & ((1 << mb) - 1)
|
||||
if e == 0:
|
||||
return m / (1 << mb) * 2 ** -14
|
||||
return (1 + m / (1 << mb)) * 2 ** (e - 15)
|
||||
p11 = [rng.getrandbits(32) & ~((1 << 30) | (1 << 9) | (1 << 20)) for _ in range(W * H)] # keep exponents < 31
|
||||
add("dxgi R11G11B10_FLOAT", R.dds_dx10(W, H, 26, b"".join(struct.pack("<I", v) for v in p11)),
|
||||
[(uf(v & 2047, 6), uf((v >> 11) & 2047, 6), uf(v >> 22, 5), 1.0) for v in p11])
|
||||
add("dxgi R9G9B9E5_SHAREDEXP", R.dds_dx10(W, H, 67, b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
|
||||
p16 = [rng.getrandbits(16) for _ in range(W * H)]
|
||||
add("dxgi B5G6R5_UNORM", R.dds_dx10(W, H, 85, b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
|
||||
add("dxgi B5G5R5A1_UNORM", R.dds_dx10(W, H, 86, b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
|
||||
add("dxgi B4G4R4A4_UNORM", R.dds_dx10(W, H, 115, b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
|
||||
# legacy masks
|
||||
def legacy(bits, flags, masks, data):
|
||||
pf = struct.pack("<2I4s5I", 32, flags, b"\0\0\0\0", bits, *masks)
|
||||
return R.dds_header(W, H, pf) + data
|
||||
add("legacy R5G6B5", legacy(16, 0x40, (0xF800, 0x7E0, 0x1F, 0), b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
|
||||
add("legacy A1R5G5B5", legacy(16, 0x41, (0x7C00, 0x3E0, 0x1F, 0x8000), b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
|
||||
add("legacy X8R8G8B8", legacy(32, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
|
||||
add("legacy R8G8B8 (24-bit)", legacy(24, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v)[:3] for v in p32)),
|
||||
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
|
||||
add("legacy A2B10G10R10", legacy(32, 0x41, (0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000), b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
|
||||
add("legacy L8", legacy(8, 0x20000, (0xFF, 0, 0, 0), bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
|
||||
add("legacy A8L8", legacy(16, 0x20001, (0xFF, 0, 0, 0xFF00), bytes(x for v in u8 for x in (v[0], v[3]))),
|
||||
[(v[0] / 255,) * 3 + (v[3] / 255,) for v in u8])
|
||||
add("legacy A8", legacy(8, 0x2, (0, 0, 0, 0xFF), bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
|
||||
add("legacy A4R4G4B4", legacy(16, 0x41, (0xF00, 0xF0, 0xF, 0xF000), b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
|
||||
# YUY2 (BT.601 limited range)
|
||||
def ycc(y, u, v):
|
||||
c, d, e = 1.164 * (y - 16), u - 128, v - 128
|
||||
cl = lambda x: max(0, min(255, int(math.floor(x + 0.5))))
|
||||
return (cl(c + 1.596 * e), cl(c - 0.392 * d - 0.813 * e), cl(c + 2.017 * d), 255)
|
||||
W2 = 6
|
||||
yuy = bytes(rng.randrange(16, 240) for _ in range(W2 * H * 2))
|
||||
exp = []
|
||||
for y in range(H):
|
||||
for x in range(W2):
|
||||
q = y * W2 * 2 + (x // 2) * 4
|
||||
exp.append(ycc(yuy[q + (2 if x % 2 else 0)], yuy[q + 1], yuy[q + 3]))
|
||||
pf = struct.pack("<2I4s5I", 32, 4, b"YUY2", 0, 0, 0, 0, 0)
|
||||
cases.append({"name": "fourcc YUY2", "data": R.dds_header(W2, H, pf) + yuy, "rgba8": bytes(v for t in exp for v in t)})
|
||||
return cases
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(5)
|
||||
work = tempfile.mkdtemp(prefix="formats-dds-")
|
||||
try:
|
||||
cases = _tools(ctx, work)
|
||||
references(ctx, cases)
|
||||
hand = hand_cases(rng)
|
||||
ours = _ours(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
ctx.emit("dds", {"cases": cases, "hand": hand, "ours": ours})
|
||||
|
||||
|
||||
def _tools(ctx, work):
|
||||
cases = []
|
||||
for name, w, h in (("a", 37, 23), ("b", 64, 32)):
|
||||
with open(os.path.join(work, name + ".png"), "wb") as f:
|
||||
f.write(png(w, h, source(w, h)))
|
||||
jobs = []
|
||||
for src in ("a", "b"):
|
||||
for fl in ("-rgb", "-bc1", "-bc1a", "-bc2", "-bc3", "-bc4", "-bc5", "-bc7"):
|
||||
jobs.append((src, fl, []))
|
||||
jobs.append((src, "-bc1", ["-nomips", "-dds10"]))
|
||||
jobs.append(("a", "-bc6", ["-nomips"]))
|
||||
script = []
|
||||
for src, fl, extra in jobs:
|
||||
out = "%s%s%s.dds" % (src, fl, "".join(extra))
|
||||
script.append("nvcompress -silent %s %s %s.png %s" % (fl, " ".join(extra), src, out))
|
||||
for i in range(6):
|
||||
with open(os.path.join(work, "f%d.png" % i), "wb") as f:
|
||||
f.write(png(16, 16, source(16, 16, i + 1)))
|
||||
faces = " ".join("f%d.png" % i for i in range(6))
|
||||
script.append("nvassemble -cube %s -o cube.dds" % faces)
|
||||
script.append("nvassemble -array f0.png f1.png f2.png -o array.dds")
|
||||
script.append("nvassemble -volume f0.png f1.png f2.png f3.png -o volume.dds")
|
||||
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(script))])
|
||||
im = []
|
||||
for comp in ("none", "dxt1", "dxt5"):
|
||||
im.append("magick a.png -define dds:compression=%s -define dds:mipmaps=3 im_%s.dds" % (comp, comp))
|
||||
ctx.nix("imagemagick", ["sh", "-c", "cd %s && %s" % (work, " && ".join(im))])
|
||||
names = ["%s%s%s.dds" % (s, f, "".join(e)) for s, f, e in jobs] + ["cube.dds", "array.dds", "volume.dds"] + ["im_%s.dds" % c for c in ("none", "dxt1", "dxt5")]
|
||||
for n in names:
|
||||
cases.append({"name": n, "data": open(os.path.join(work, n), "rb").read()})
|
||||
return cases
|
||||
|
||||
|
||||
def _ours(ctx, work):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "dds"], cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
n, hx = line.split("\t", 1)
|
||||
files[n] = bytes.fromhex(hx.strip())
|
||||
out = []
|
||||
pil, pil_idx = [], []
|
||||
names = sorted(files)
|
||||
for n in names:
|
||||
with open(os.path.join(work, n), "wb") as f:
|
||||
f.write(files[n])
|
||||
info = ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && for f in %s; do echo \"== $f\"; nvddsinfo $f; done" % (work, " ".join(names))]).decode(errors="replace")
|
||||
blocks = {}
|
||||
for part in info.split("== ")[1:]:
|
||||
n, body = part.split("\n", 1)
|
||||
blocks[n.strip()] = body
|
||||
for i, n in enumerate(names):
|
||||
body = blocks.get(n, "")
|
||||
def field(key):
|
||||
for line in body.split("\n"):
|
||||
if line.strip().startswith(key):
|
||||
return line.split(":", 1)[1].strip()
|
||||
return ""
|
||||
e = {"name": n, "data": files[n], "width": int(field("Width") or 0), "height": int(field("Height") or 0),
|
||||
"mipcount": int(field("Mipmap count") or 0), "dxgi": field("DXGI Format"), "array": field("Array size"),
|
||||
"caps2": field("Caps 2")}
|
||||
out.append(e)
|
||||
if not any(k in n for k in ("rgba16", "rgba32f", "rgba16f", "cube", "array")):
|
||||
pil.append(files[n])
|
||||
pil_idx.append(i)
|
||||
for i, (mode, w, h, raw) in zip(pil_idx, R.pillow(ctx, pil)):
|
||||
out[i]["pillow"] = R.rgba_from(mode, raw)
|
||||
out[i]["pillowMode"] = mode
|
||||
return out
|
||||
Reference in new issue
Block a user