Files
2026-11-23 03:28:32 +02:00

106 lines
5.4 KiB
Python

"""Repair the two observed BLP2 equipment mip directory defects."""
import struct
PAL8 = (1, 8, 8, 1)
DXT3 = (2, 8, 1, 1)
PREFIX = 148 + 256 * 4
def _downsample_palette(raw, palette, source_width, source_height, width, height):
"""Box-filter the last authored mip, weighting each texel's color by its alpha."""
pixels = source_width * source_height
indices, opacity = raw[:pixels], raw[pixels:]
xstep, ystep = source_width // width, source_height // height
area = xstep * ystep
new_indices, new_opacity = bytearray(), bytearray()
for y in range(0, source_height, ystep):
for x in range(0, source_width, xstep):
sums = [0, 0, 0]
total_alpha = 0
for j in range(y, y + ystep):
for i in range(j * source_width + x, j * source_width + x + xstep):
weight = opacity[i]
total_alpha += weight
for component, value in enumerate(palette[indices[i]]):
sums[component] += weight * value
# Select the nearest original BGR triplet. Integer cross products
# preserve exact means and choose the lowest index on a tie.
index = min(range(256), key=lambda n: sum(
(value * total_alpha - target) ** 2
for value, target in zip(palette[n], sums)))
new_indices.append(index)
new_opacity.append((total_alpha + area // 2) // area)
return bytes(new_indices + new_opacity)
def normalize_equipment_mip_tail(raw):
"""Return (normalized BLP2 bytes, audit) for exact EOF or last-level aliases.
Other malformed directories raise ValueError. Already-canonical paletted
alpha8 and BC2 mip chains are returned unchanged.
"""
if (not isinstance(raw, bytes) or len(raw) < PREFIX or raw[:8] != b'BLP2\x01\x00\x00\x00'
or tuple(raw[8:12]) not in (PAL8, DXT3)):
raise ValueError("Unsupported equipment BLP2 header")
encoding = tuple(raw[8:12])
width, height = struct.unpack_from('<II', raw, 12)
if any(d < 1 or d > 4096 or d & (d - 1) for d in (width, height)):
raise ValueError("Bounded power-of-two mip dimensions required")
count = max(width, height).bit_length()
offsets = struct.unpack_from('<16I', raw, 20)
sizes = struct.unpack_from('<16I', raw, 84)
slots = list(zip(offsets, sizes))
cursor = PREFIX
generated = []
added = bytearray()
header = bytearray(raw[:PREFIX])
for level, (offset, size) in enumerate(slots[:count]):
w, h = max(1, width >> level), max(1, height >> level)
expected = 2 * w * h if encoding == PAL8 else 16 * ((w + 3) // 4) * ((h + 3) // 4)
if offset == cursor and size == expected and offset + size <= len(raw):
cursor += size
continue
# Some rectangular source writers stop when the *shorter* side
# reaches one. The authored chain at EOF is valid as a partial chain.
if (level and cursor == len(raw) and min(width, height).bit_length() == level and (
(offset, size) == (cursor, (-cursor) & 0xffffffff)
or slots[level:] == [(0, 0)] * (16 - level))):
count = level
break
if not (encoding == PAL8 and (width, height) in ((128, 32), (128, 64)) and level == 3
and slots[level:count] == [slots[level - 1]] * (count - level)
and cursor == len(raw) and slots[count:] == [(0, 0)] * (16 - count)):
raise ValueError("Unrecognized or incomplete authored mip chain")
source = raw[slots[level - 1][0]:cursor]
# Raw1 palette entries contain B,G,R,unused. Separate one-byte alpha
# planes follow each mip's indices (benilla-blp decode_raw1).
palette = [raw[at:at + 3] for at in range(148, PREFIX, 4)]
for k in range(level, count):
payload = _downsample_palette(source, palette, width >> (level - 1), height >> (level - 1),
max(1, width >> k), max(1, height >> k))
struct.pack_into('<I', header, 20 + k * 4, cursor + len(added))
struct.pack_into('<I', header, 84 + k * 4, len(payload))
added.extend(payload)
generated.append(k)
break
if cursor != len(raw):
raise ValueError("Unexpected trailing mip payload")
repair = 'regenerated-aliased-paletted-tail' if generated else 'unchanged'
unused = [(0, 0)] * (16 - count)
if slots[count:] != unused:
# The writer filled slot N with (EOF, 0 - EOF) and the final size
# with size[0]. Every real mip already consumes its full extent.
overflow = unused.copy()
overflow[0] = (len(raw), (-len(raw)) & 0xffffffff)
overflow[-1] = (0, sizes[0])
if slots[count:] != overflow:
raise ValueError("Unrecognized post-1x1 mip directory")
for k in range(count, 16):
struct.pack_into('<I', header, 20 + k * 4, 0)
struct.pack_into('<I', header, 84 + k * 4, 0)
repair = 'cleared-post-1x1-directory' if count == max(width,height).bit_length() else 'cleared-post-authored-directory'
output = raw if repair == 'unchanged' else bytes(header) + raw[PREFIX:] + added
return output, dict(repair=repair, width=width, height=height, mip_count=count,
preserved_levels=list(range(count - len(generated))), regenerated_levels=generated)