ws-tex: codecs/image/Bcn (BC1-7 decode, BC1/3/4/5 encode) + codecs/image/Half

Decoders ported from Pillow BcnDecode.c (CC0) with D3D11 rules (BC6H +32 rounding, float output, reserved modes,
signed RGTC). Tests against Pillow and Godot 4 (bcdec) over random blocks of every BC6H / BC7 mode; encoder PSNR
above Pillow's encoder. Bench lines in tools/bench.luau.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 14:05:10 -05:00
1 parent d3dbba500b
commit b32d45ef99
10 files changed
+1761

No files matched your search

+24
View File
@@ -1078,3 +1078,27 @@ do
jitTune(false)
end
end
do
-- textures (ws-tex): codecs/image/Bcn on a 256 x 256 image (tools/fixtures/bcn.py); MB/s of rgba8 output (decode)
-- or input (encode); BC6H of rgbaf32 output
local Bcn = require("@formats/codecs/image/Bcn")
local BB = require("@tests/gen/bcn_bench")
local w, h = BB.w, BB.h
local px = buffer.fromstring(BB.rgba)
for _, kind in { "bc1", "bc3", "bc5" } do
local blocks = Bcn.encode(kind, px, w, h) :: buffer
bench("bcn decode " .. kind .. " 256x256", 5, w * h * 4, function()
Bcn.decode(kind, blocks, 0, w, h)
end)
bench("bcn encode " .. kind .. " 256x256", 2, w * h * 4, function()
Bcn.encode(kind, px, w, h)
end)
end
local b7, b6 = buffer.fromstring(BB.bc7), buffer.fromstring(BB.bc6h)
bench("bcn decode bc7 256x256", 5, w * h * 4, function()
Bcn.decode("bc7", b7, 0, w, h)
end)
bench("bcn decode bc6h 256x256", 5, w * h * 16, function()
Bcn.decode("bc6h", b6, 0, w, h)
end)
end
+107
View File
@@ -0,0 +1,107 @@
# Shared by the texture fixture generators (bcn.py, etc.py, dds.py, ktx.py): reference block decoders through nix.
# godot(ctx, jobs) Godot 4's Image.decompress (bcdec for BC1-7, etcpak for ETC1 / ETC2 / EAC): each job is
# (raw block bytes, w, h, godot format number, float) -> rgba8 bytes, or rgbaf32 little-endian
# bytes when float is true
# pillow(ctx, jobs) Pillow's DDS reader (BcnDecode.c): each job is (dds bytes) -> (mode, raw bytes)
# dds_dx10(w, h, dxgi, data) / dds_fourcc(w, h, fourcc, data): minimal DDS files around block data
import os, shutil, struct, tempfile
# Godot Image.Format numbers (checked against Godot 4.7)
GODOT = {"bc1": 17, "bc2": 18, "bc3": 19, "bc4": 20, "bc5": 21, "bc7": 22, "bc6hs": 23, "bc6h": 24, "etc1": 25,
"eac_r11": 26, "eac_r11s": 27, "eac_rg11": 28, "eac_rg11s": 29, "etc2_rgb": 30, "etc2_rgba": 31,
"etc2_rgba1": 32}
GD_SCRIPT = r'''extends SceneTree
func _init():
var dir = OS.get_cmdline_user_args()[0]
var lines = FileAccess.get_file_as_string(dir + "/jobs.txt").split("\n", false)
for line in lines:
var a = line.split(" ")
var data = FileAccess.get_file_as_bytes(dir + "/" + a[0])
var img = Image.create_from_data(int(a[1]), int(a[2]), false, int(a[3]), data)
img.decompress()
if a[4] == "1":
img.convert(Image.FORMAT_RGBAF)
else:
img.convert(Image.FORMAT_RGBA8)
var f = FileAccess.open(dir + "/" + a[0] + ".out", FileAccess.WRITE)
f.store_buffer(img.get_data())
f.close()
quit()
'''
def godot(ctx, jobs):
work = tempfile.mkdtemp(prefix="formats-godot-")
try:
lines = []
for i, (data, w, h, fmt, flt) in enumerate(jobs):
with open(os.path.join(work, "j%d" % i), "wb") as f:
f.write(data)
lines.append("j%d %d %d %d %d" % (i, w, h, fmt, 1 if flt else 0))
with open(os.path.join(work, "jobs.txt"), "w") as f:
f.write("\n".join(lines) + "\n")
with open(os.path.join(work, "run.gd"), "w") as f:
f.write(GD_SCRIPT)
ctx.nix("godot", ["godot", "--headless", "--script", os.path.join(work, "run.gd"), "--", work])
out = []
for i in range(len(jobs)):
with open(os.path.join(work, "j%d.out" % i), "rb") as f:
out.append(f.read())
return out
finally:
shutil.rmtree(work, ignore_errors=True)
def pillow(ctx, files):
"""files: list of bytes (any format Pillow reads) -> list of (mode, w, h, raw bytes)"""
work = tempfile.mkdtemp(prefix="formats-pillow-")
try:
for i, data in enumerate(files):
with open(os.path.join(work, "f%d" % i), "wb") as f:
f.write(data)
code = ("import os\nfrom PIL import Image\nw=%r\nfor i in range(%d):\n"
" im=Image.open(os.path.join(w,'f%%d'%%i)); im.load()\n"
" open(os.path.join(w,'f%%d.out'%%i),'wb').write(im.tobytes())\n"
" open(os.path.join(w,'f%%d.mode'%%i),'w').write('%%s %%d %%d'%%(im.mode,im.width,im.height))\n") % (work, len(files))
ctx.python(["pillow"], code)
out = []
for i in range(len(files)):
mode, w, h = open(os.path.join(work, "f%d.mode" % i)).read().split()
out.append((mode, int(w), int(h), open(os.path.join(work, "f%d.out" % i), "rb").read()))
return out
finally:
shutil.rmtree(work, ignore_errors=True)
def dds_header(w, h, pf, caps=0x1000, mips=0, flags=0x1007, pitch=0, depth=0, caps2=0):
if mips:
flags |= 0x20000
return (b"DDS " + struct.pack("<7I", 124, flags, h, w, pitch, depth, mips) + b"\0" * 44 + pf +
struct.pack("<4I", caps, caps2, 0, 0) + b"\0" * 4)
def dds_dx10(w, h, dxgi, data, array=1, misc=0, mips=0, caps2=0):
pf = struct.pack("<2I", 32, 4) + b"DX10" + b"\0" * 20
return dds_header(w, h, pf, mips=mips, caps2=caps2) + struct.pack("<5I", dxgi, 3, misc, array, 0) + data
def dds_fourcc(w, h, fourcc, data, mips=0, caps2=0):
pf = struct.pack("<2I", 32, 4) + fourcc + b"\0" * 20
return dds_header(w, h, pf, mips=mips, caps2=caps2) + data
def rgba_from(mode, raw):
"""Pillow raw bytes of mode L / RGB / RGBA -> rgba8 bytes"""
if mode == "RGBA":
return raw
out = bytearray()
if mode == "L":
for v in raw:
out += bytes((v, v, v, 255))
elif mode == "RGB":
for i in range(0, len(raw), 3):
out += raw[i:i + 3] + b"\xff"
else:
raise ValueError(mode)
return bytes(out)
+119
View File
@@ -0,0 +1,119 @@
# BCn fixtures (tools/fixtures.py): random BC1..BC7 blocks (every BC7 mode and BC6H mode forced in turn, the BC1
# 3-colour mode, odd image sizes) decoded by two references: Pillow's DDS reader and Godot 4 (bcdec); plus encoder
# baselines: test images and the PSNR Pillow's own BC1 / BC3 / BC5 encoder reaches on them.
# tests/gen/bcn.luau { cases = { { name, kind, w, h, data, pillow?, godot?, tol } }, enc = { { name, w, h,
# rgba, psnr = { bc1, bc3, bc5 } } } } (pillow / godot: rgba8 bytes, or rgbaf32 for BC6H)
# tests/gen/bcn_bench.luau a 256 x 256 image and random BC1 / BC6H / BC7 blocks for tools/bench.luau
import importlib.util, math, os, random, struct
_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)
DXGI = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc5s": 84, "bc6h": 95, "bc6hs": 96, "bc7": 98}
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc5s": 16, "bc6h": 16, "bc6hs": 16, "bc7": 16}
BC6_HEADERS = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 31]
def blocks(rng, kind, n, mode=None):
out = bytearray()
for _ in range(n):
b = bytearray(rng.getrandbits(8) for _ in range(BLOCK[kind]))
if kind == "bc7" and mode is not None:
b[0] = (b[0] & ~((2 << mode) - 1) & 0xFF) | (1 << mode)
elif kind.startswith("bc6h") and mode is not None:
bitsn = 2 if mode < 2 else 5
b[0] = (b[0] & ~((1 << bitsn) - 1) & 0xFF) | mode
out += b
return bytes(out)
def test_image(w, h, rng, alpha):
px = bytearray()
for y in range(h):
for x in range(w):
r = int(128 + 100 * math.sin(x / 7.0) * math.cos(y / 11.0))
g = int(255 * x / (w - 1))
b = int(255 * y / (h - 1)) if (x // 16 + y // 16) % 2 else 40
n = rng.randrange(-12, 13)
r, g, b = [max(0, min(255, v + n)) for v in (r, g, b)]
a = 255
if alpha:
a = 0 if (x - w / 2) ** 2 + (y - h / 2) ** 2 < (w / 4) ** 2 else 255
px += bytes((r, g, b, a))
return bytes(px)
def psnr(a, b, channels):
se, n = 0, 0
for i in range(0, len(a), 4):
for c in channels:
d = a[i + c] - b[i + c]
se += d * d
n += 1
return 99.0 if se == 0 else 10 * math.log10(255 * 255 * n / se)
def generate(ctx):
rng = random.Random(7)
cases = []
def add(name, kind, w, h, data):
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
for kind in ("bc1", "bc2", "bc3", "bc4", "bc5", "bc5s"):
add(kind + " 32x32", kind, 32, 32, blocks(rng, kind, 64))
add(kind + " 13x7", kind, 13, 7, blocks(rng, kind, 8))
for m in range(8):
add("bc7 mode %d" % m, "bc7", 32, 16, blocks(rng, "bc7", 32, m))
add("bc7 15x9", "bc7", 15, 9, blocks(rng, "bc7", 12))
for kind in ("bc6h", "bc6hs"):
for m in BC6_HEADERS:
add("%s mode %d" % (kind, m), kind, 16, 16, blocks(rng, kind, 16, m))
# Pillow (BC1..BC5, BC5S, BC7, BC6H as clamped 8-bit)
files = [R.dds_dx10(c["w"], c["h"], DXGI[c["kind"]], c["data"]) for c in cases]
for c, (mode, w, h, raw) in zip(cases, R.pillow(ctx, files)):
c["pillow"] = R.rgba_from(mode, raw)
# Godot (bcdec): everything but the signed BC5 (no Godot format); BC6H as floats
gj, gi = [], []
for i, c in enumerate(cases):
if c["kind"] in R.GODOT:
gj.append((c["data"], c["w"], c["h"], R.GODOT[c["kind"]], c["kind"].startswith("bc6h")))
gi.append(i)
for i, out in zip(gi, R.godot(ctx, gj)):
cases[i]["godot"] = out
# encoder baselines: Pillow's encoder on the same images, decoded by Pillow
enc = []
for name, w, h, alpha in (("photo 64x64", 64, 64, False), ("alpha 64x48", 64, 48, True), ("odd 37x21", 37, 21, False)):
px = test_image(w, h, rng, alpha)
e = {"name": name, "w": w, "h": h, "rgba": px, "psnr": {}}
enc.append(e)
import tempfile, shutil
work = tempfile.mkdtemp(prefix="formats-bcn-")
try:
for i, e in enumerate(enc):
open(os.path.join(work, "src%d" % i), "wb").write(e["rgba"])
code = ("import os\nfrom PIL import Image\nw=%r\n"
"for i, (W, H) in enumerate(%r):\n"
" im=Image.frombytes('RGBA',(W,H),open(os.path.join(w,'src%%d'%%i),'rb').read())\n"
" for pf in ('DXT1','DXT5','BC5'):\n"
" p=os.path.join(w,'e%%d_%%s.dds'%%(i,pf))\n"
" (im if pf!='BC5' else im.convert('RGB')).save(p,pixel_format=pf)\n"
" back=Image.open(p).convert('RGBA')\n"
" open(p+'.rgba','wb').write(back.tobytes())\n") % (work, [(e["w"], e["h"]) for e in enc])
ctx.python(["pillow"], code)
for i, e in enumerate(enc):
for pf, kind, ch in (("DXT1", "bc1", (0, 1, 2)), ("DXT5", "bc3", (0, 1, 2, 3)), ("BC5", "bc5", (0, 1))):
back = open(os.path.join(work, "e%d_%s.dds.rgba" % (i, pf)), "rb").read()
e["psnr"][kind] = psnr(e["rgba"], back, ch)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("bcn", {"cases": cases, "enc": enc})
# bench: a 512 x 512 image, and random BC7 blocks of every mode
w = h = 256
px = test_image(w, h, rng, True)
bench = {"w": w, "h": h, "rgba": px, "bc7": blocks(rng, "bc7", (w // 4) * (h // 4)),
"bc1": blocks(rng, "bc1", (w // 4) * (h // 4)), "bc6h": blocks(rng, "bc6h", (w // 4) * (h // 4), 3)}
ctx.emit("bcn_bench", bench)