vc-online/tools/mobile-icons.py

80 lines
2.9 KiB
Python

#!/usr/bin/env python3
# Turns the mobile version's HUD texture database (texdb/hud.dxt.*) into PNG files.
# Usage: python tools/mobile-icons.py <dir with hud.txt, hud.dxt.toc, hud.dxt.dat> <output dir>
import os, re, struct, sys
import numpy as np
from PIL import Image
src, out = sys.argv[1], sys.argv[2]
os.makedirs(out, exist_ok=True)
names = re.findall(r'^"([^"]+)"', open(f'{src}/hud.txt', encoding='latin1').read(), re.M)
toc = struct.unpack(f'<{os.path.getsize(src + "/hud.dxt.toc") // 4}I', open(f'{src}/hud.dxt.toc', 'rb').read())[1:]
dat = open(f'{src}/hud.dxt.dat', 'rb').read()
print(len(names), 'names', len(toc), 'offsets')
def c565(c):
return np.array([((c >> 11) & 31) * 255 // 31, ((c >> 5) & 63) * 255 // 63, (c & 31) * 255 // 31], dtype=np.int32)
def colour_block(b, opaque_only):
c0, c1, bits = struct.unpack('<HHI', b)
p = [c565(c0), c565(c1)]
alpha = [255, 255, 255, 255]
if c0 > c1 or opaque_only:
p += [(2 * p[0] + p[1]) // 3, (p[0] + 2 * p[1]) // 3]
else:
p += [(p[0] + p[1]) // 2, np.zeros(3, dtype=np.int32)]
alpha[3] = 0
px = np.zeros((4, 4, 4), dtype=np.uint8)
for i in range(16):
k = (bits >> (2 * i)) & 3
px[i // 4, i % 4, :3] = p[k]
px[i // 4, i % 4, 3] = alpha[k]
return px
def alpha5(b):
a0, a1 = b[0], b[1]
bits = int.from_bytes(b[2:8], 'little')
t = [a0, a1]
if a0 > a1:
t += [((7 - i) * a0 + i * a1) // 7 for i in range(1, 7)]
else:
t += [((5 - i) * a0 + i * a1) // 5 for i in range(1, 5)] + [0, 255]
return np.array([t[(bits >> (3 * i)) & 7] for i in range(16)], dtype=np.uint8).reshape(4, 4)
def decode(kind, w, h, d):
img = np.zeros((h, w, 4), dtype=np.uint8)
size = 8 if kind in (0x83f0, 0x83f1) else 16
at = 0
for y in range(0, h, 4):
for x in range(0, w, 4):
if kind in (0x83f0, 0x83f1):
px = colour_block(d[at:at + 8], False)
elif kind == 0x83f2:
px = colour_block(d[at + 8:at + 16], True)
bits = int.from_bytes(d[at:at + 8], 'little')
px[:, :, 3] = np.array([((bits >> (4 * i)) & 15) * 17 for i in range(16)], dtype=np.uint8).reshape(4, 4)
else:
px = colour_block(d[at + 8:at + 16], True)
px[:, :, 3] = alpha5(d[at:at + 8])
at += size
img[y:y + 4, x:x + 4] = px[:min(4, h - y), :min(4, w - x)]
return img
done = 0
kinds = {}
for name, off in zip(names, toc):
if off == 0xffffffff:
continue
_, kind, w, h = struct.unpack('<HHHH', dat[off:off + 8])
h &= 0x7fff
kinds[hex(kind)] = kinds.get(hex(kind), 0) + 1
if kind not in (0x83f0, 0x83f1, 0x83f2, 0x83f3) or not w or not h or w & 3 or h & 3:
continue
Image.fromarray(decode(kind, w, h, dat[off + 8:]), 'RGBA').save(f'{out}/{name}.png')
done += 1
print('saved', done, 'formats', kinds)