107 lines
4.8 KiB
Python
107 lines
4.8 KiB
Python
"""Encode an authored character atlas in its native BLP2 block layout."""
|
|
import io
|
|
import struct
|
|
|
|
import numpy as np
|
|
from PIL import Image
|
|
|
|
BC1 = bytes((2, 0, 0, 1))
|
|
BC3 = bytes((2, 8, 7, 1))
|
|
BGRA = bytes((3, 8, 8, 1))
|
|
|
|
|
|
def _mask_blocks(mask, width, height):
|
|
nx, ny = (width + 3) // 4, (height + 3) // 4
|
|
padded = np.pad(mask, ((0, ny * 4 - height), (0, nx * 4 - width)))
|
|
return padded.reshape(ny, 4, nx, 4).any(axis=(1, 3)).ravel()
|
|
|
|
|
|
def _layout(blob, formats):
|
|
if len(blob) < 1172 or blob[:8] != b'BLP2\x01\0\0\0' or blob[8:12] not in formats:
|
|
raise ValueError('Unsupported BLP2 character atlas header')
|
|
width, height = struct.unpack_from('<II', blob, 12)
|
|
if any(not 1 <= dim <= 8192 or dim & (dim - 1) for dim in (width, height)):
|
|
raise ValueError('Expected power-of-two character atlas dimensions')
|
|
levels = []
|
|
previous_end = 1172
|
|
for mip in range(max(width, height).bit_length()):
|
|
pos = struct.unpack_from('<I', blob, 20 + 4 * mip)[0]
|
|
count = struct.unpack_from('<I', blob, 84 + 4 * mip)[0]
|
|
block_count = ((width + 3) // 4) * ((height + 3) // 4)
|
|
expected = width * height * 4 if blob[8:12] == BGRA else block_count * (8 if blob[8:12] == BC1 else 16)
|
|
if count != expected or pos < previous_end or pos + count > len(blob):
|
|
raise ValueError('Missing or invalid BLP2 mip payload')
|
|
levels.append((width, height, pos, count))
|
|
previous_end = pos + count
|
|
width, height = max(1, width // 2), max(1, height // 2)
|
|
return levels
|
|
|
|
|
|
def encode_character_atlas(native, authored, *, coverage=None, occupied=None):
|
|
"""Keep native mip headers and untouched BC blocks when adding a face patch.
|
|
|
|
For a face patch, coverage marks the authored area and occupied marks pixels used
|
|
by the existing mesh. A block containing any occupied pixel stays byte-identical
|
|
at that mip. Omit both masks for a fully authored layer. BLP2 alpha encoding 7 stores DXT5 blocks.
|
|
"""
|
|
target = _layout(native, (BC1, BC3))
|
|
source = _layout(authored, (BGRA,))
|
|
width, height = target[0][:2]
|
|
if source[0][:2] != (width, height):
|
|
raise ValueError('Source and destination atlas dimensions differ')
|
|
if (coverage is None) != (occupied is None):
|
|
raise ValueError('Partial overlays require both pixel masks')
|
|
if coverage is not None:
|
|
coverage, occupied = (np.asarray(m, dtype=bool) for m in (coverage, occupied))
|
|
if coverage.shape != (height, width) or occupied.shape != coverage.shape:
|
|
raise ValueError('Pixel masks must match the full atlas')
|
|
output = bytearray(native)
|
|
for (width, height, pos, count), (_, _, src, length) in zip(target, source, strict=True):
|
|
rgba = np.frombuffer(authored, 'u1', length, src).reshape(height, width, 4)[:, :, [2, 1, 0, 3]]
|
|
pixel_format = 'DXT5' if native[8:12] == BC3 else 'DXT1'
|
|
image = Image.fromarray(rgba)
|
|
if pixel_format == 'DXT1':
|
|
image = image.convert('RGB')
|
|
dds = io.BytesIO()
|
|
image.save(dds, 'DDS', pixel_format=pixel_format)
|
|
data = dds.getvalue()
|
|
if data[84:88] != pixel_format.encode('ascii'):
|
|
raise ValueError('DDS encoder returned an unexpected format')
|
|
encoded = data[128:]
|
|
if len(encoded) != count:
|
|
raise ValueError('Block encoder returned the wrong mip size')
|
|
if coverage is None:
|
|
output[pos:pos + count] = encoded
|
|
continue
|
|
update = _mask_blocks(coverage, width, height) & ~_mask_blocks(occupied, width, height)
|
|
dest = np.frombuffer(output, 'u1', count, pos).reshape(update.size, -1)
|
|
dest[update] = np.frombuffer(encoded, 'u1').reshape(dest.shape)[update]
|
|
if width > 1 or height > 1:
|
|
coverage, occupied = (m.reshape(max(1, height // 2), min(2, height),
|
|
max(1, width // 2), min(2, width)).any(axis=(1, 3))
|
|
for m in (coverage, occupied))
|
|
return bytes(output)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
from argparse import ArgumentParser
|
|
from pathlib import Path
|
|
|
|
parser = ArgumentParser(description=__doc__)
|
|
parser.add_argument('native', type=Path)
|
|
parser.add_argument('authored', type=Path)
|
|
parser.add_argument('output', type=Path)
|
|
parser.add_argument('--coverage', type=Path, help='Patch coverage mask at full atlas size')
|
|
parser.add_argument('--occupied', type=Path, help='Existing mesh coverage to preserve')
|
|
args = parser.parse_args()
|
|
|
|
def read_mask(path):
|
|
if path is not None:
|
|
with Image.open(path) as image:
|
|
return np.asarray(image.convert('L')) != 0
|
|
return None
|
|
|
|
args.output.write_bytes(encode_character_atlas(
|
|
args.native.read_bytes(), args.authored.read_bytes(),
|
|
coverage=read_mask(args.coverage), occupied=read_mask(args.occupied)))
|