Files

160 lines
7.7 KiB
Python

# Blizzard BLP fixtures (tools/fixtures.py). Pillow (nix python3 pillow) is the reference decoder: it writes BLP2
# palette files itself (not BLP1: Pillow 12 writes BLP1 mip offsets as if the header were BLP2's, 8 bytes short), and decodes the files written here from the wowdev.wiki layout: BLP2 DXT1 / DXT3 / DXT5
# (random blocks), palette with 1 / 4 / 8-bit alpha planes, mip chains, and BLP1 JPEG (a Pillow
# JPEG split into the shared header and the mip data). Pillow's RGBA -> CRC-32. Two cases Pillow reads differently
# from the games (or not at all) are checked against this writer instead: uncompressed BGRA (Pillow 12 has no
# encoding 3), BLP1 palette files with an 8-bit alpha plane, and BLP1
# JPEGs of 4 components (BGRA without colour conversion: CMYK written inverted by Pillow, its Adobe marker removed)
# whose reference is the source pixels (PSNR).
# tests/gen/blp.luau { { name, data, width, height, crc?, rgba?, psnr? } }
import io, json, struct, zlib
CODE = r"""
import io, json, sys, zlib, random, struct
from PIL import Image
args = json.loads(sys.stdin.read())
rng = random.Random(args["seed"])
out = {}
def rgba_crc(im):
return zlib.crc32(im.convert("RGBA").tobytes())
# 1. Pillow-written palette BLPs
pal_img = Image.new("P", (13, 7))
pal_img.putpalette(bytes(rng.randrange(256) for _ in range(768)))
pal_img.putdata([rng.randrange(256) for _ in range(13 * 7)])
for v in ("BLP2",):
b = io.BytesIO()
pal_img.save(b, "BLP", blp_version=v)
data = b.getvalue()
out["pillow-" + v.lower()] = {"data": data.hex(), "crc": rgba_crc(Image.open(io.BytesIO(data))), "w": 13, "h": 7}
# 2. Pillow decodes the hand-made files
for name, hexdata in args["files"].items():
try:
im = Image.open(io.BytesIO(bytes.fromhex(hexdata)))
im.load()
out[name] = {"crc": rgba_crc(im), "w": im.size[0], "h": im.size[1], "rgba": im.convert("RGBA").tobytes().hex()}
except Exception as e:
out[name] = {"failed": str(e)}
# 3. JPEGs for BLP1: a 3-component one and a 4-component (CMYK) one
src = Image.new("RGB", (24, 16))
src.putdata([(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(24 * 16)])
src = src.resize((24, 16))
b = io.BytesIO(); src.save(b, "JPEG", quality=95)
out["jpeg3"] = b.getvalue().hex()
# smooth RGBA source pixels for the 4-component file, stored as B, G, R, A components
px = [((x * 10) % 256, (y * 15) % 256, ((x + y) * 7) % 256, (255 - x * 8) % 256) for y in range(16) for x in range(24)]
cm = Image.new("CMYK", (24, 16))
# Pillow stores CMYK inverted: write 255 - (b, g, r, a) so the stored components are B, G, R, A
cm.putdata([(255 - p[2], 255 - p[1], 255 - p[0], 255 - p[3]) for p in px])
b = io.BytesIO(); cm.save(b, "JPEG", quality=98)
out["jpeg4"] = b.getvalue().hex()
out["jpeg4src"] = bytes(c for p in px for c in p).hex()
print(json.dumps(out))
"""
def blp2(kind, comp, adepth, atype, w, h, mips, palette=b"\0" * 1024):
offs, lens, at = [], [], 1172
for m in mips:
offs.append(at)
lens.append(len(m))
at += len(m)
offs += [0] * (16 - len(mips))
lens += [0] * (16 - len(mips))
head = b"BLP2" + struct.pack("<IBBBBII", kind, comp, adepth, atype, 1 if len(mips) > 1 else 0, w, h)
return head + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + palette + b"".join(mips)
def blp1(comp, adepth, w, h, mips, extra=b""):
base = 156 + len(extra)
offs, lens, at = [], [], base
for m in mips:
offs.append(at)
lens.append(len(m))
at += len(m)
offs += [0] * (16 - len(mips))
lens += [0] * (16 - len(mips))
return b"BLP1" + struct.pack("<6I", comp, adepth, w, h, 4, 1 if len(mips) > 1 else 0) + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + extra + b"".join(mips)
def split_jpeg(j):
# the shared header: everything before the first SOS marker
k = j.index(b"\xff\xda")
return j[:k], j[k:]
def strip_adobe(j):
i = j.find(b"\xff\xee")
if i < 0:
return j
n = struct.unpack(">H", j[i + 2:i + 4])[0]
return j[:i] + j[i + 2 + n:]
def generate(ctx):
rng = ctx.rng(121)
w, h = 16, 12
files = {}
for name, atype, bs in (("dxt1", 0, 8), ("dxt3", 1, 16), ("dxt5", 7, 16)):
blocks = rng.randbytes((w // 4) * (h // 4) * bs)
files[name] = blp2(1, 2, 1 if name == "dxt1" else 8, atype, w, h, [blocks, rng.randbytes(2 * 2 * bs)]) # mip 1: 8 x 6
bgra = rng.randbytes(w * h * 4)
own = [{"name": "bgra", "data": blp2(1, 3, 8, 8, w, h, [bgra]), "width": w, "height": h,
"rgba": b"".join(bytes((bgra[i + 2], bgra[i + 1], bgra[i], bgra[i + 3])) for i in range(0, len(bgra), 4))}]
pal = bytes(rng.randrange(256) for _ in range(1024))
alphas = {}
for depth in (0, 1, 4, 8):
idx = rng.randbytes(w * h)
alpha = rng.randbytes({0: 0, 1: w * h // 8, 4: w * h // 2, 8: w * h}[depth])
files["palette-a%d" % depth] = blp2(1, 1, depth, 0, w, h, [idx + alpha], pal)
# the alpha plane (LSB first), expanded to 8 bits
if depth == 1:
alphas[depth] = bytes(255 if alpha[i // 8] >> (i % 8) & 1 else 0 for i in range(w * h))
elif depth == 4:
alphas[depth] = bytes(((alpha[i // 2] >> (4 * (i % 2))) & 15) * 17 for i in range(w * h))
elif depth == 8:
alphas[depth] = alpha
res = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"seed": 5, "files": {k: v.hex() for k, v in files.items()}}).encode()))
out = []
for name in ("pillow-blp2",):
r = res[name]
out.append({"name": name, "data": bytes.fromhex(r["data"]), "width": r["w"], "height": r["h"], "crc": r["crc"]})
for name, data in files.items():
r = res[name]
if "failed" in r:
raise SystemExit("blp: Pillow cannot read %s: %s" % (name, r["failed"]))
e = {"name": name, "data": data, "width": r["w"], "height": r["h"]}
if name.startswith("dxt"):
# Pillow's own DXT decoder expands the 5 / 6-bit endpoints by shifting only (r << 3), the D3D rule
# replicates the top bits (r << 3 | r >> 2), and divides by 3 without rounding: colours compared within
# 8, alpha exactly
e["ref"], e["tol"] = bytes.fromhex(r["rgba"]), 8
elif name.startswith("palette-a") and name != "palette-a0":
# Pillow ignores the alpha plane (it takes the palette's alpha): RGB from Pillow, alpha from the writer
e["rgbref"], e["alpha"] = bytes.fromhex(r["rgba"]), alphas[int(name[-1])]
else:
e["crc"] = r["crc"]
out.append(e)
out += own
# BLP1 JPEG, 3 components: Pillow decodes it (YCbCr -> RGB, then R / B swapped)
j3 = bytes.fromhex(res["jpeg3"])
hd, body = split_jpeg(j3)
d = blp1(0, 0, 24, 16, [body], struct.pack("<I", len(hd)) + hd)
r = json.loads(ctx.python(["pillow"], CODE.split("# 1.")[0] + "im = Image.open(io.BytesIO(bytes.fromhex(args['d'])))\nprint(json.dumps({'crc': rgba_crc(im)}))\n", input=json.dumps({"seed": 1, "d": d.hex()}).encode()))
out.append({"name": "blp1-jpeg3", "data": d, "width": 24, "height": 16, "crc": r["crc"]})
# BLP1 JPEG, 4 components (BGRA)
j4 = strip_adobe(bytes.fromhex(res["jpeg4"]))
hd, body = split_jpeg(j4)
d = blp1(0, 8, 24, 16, [body], struct.pack("<I", len(hd)) + hd)
out.append({"name": "blp1-jpeg4", "data": d, "width": 24, "height": 16, "rgba": bytes.fromhex(res["jpeg4src"]), "psnr": 30})
# BLP1 palette with an 8-bit alpha plane: indexes then alpha
idx = rng.randbytes(w * h)
alpha = rng.randbytes(w * h)
d = blp1(1, 8, w, h, [idx + alpha], pal)
rgba = b"".join(bytes((pal[i * 4 + 2], pal[i * 4 + 1], pal[i * 4], alpha[k])) for k, i in enumerate(idx))
out.append({"name": "blp1-palette-a8", "data": d, "width": w, "height": h, "rgba": rgba})
ctx.emit("blp", out)