54 lines
2.4 KiB
Python
54 lines
2.4 KiB
Python
"""Keep MD21 material metadata in step with appended character materials."""
|
|
import struct
|
|
|
|
|
|
def _chunks(raw):
|
|
if not isinstance(raw, bytes) or not 8 <= len(raw) <= 67108864 or raw[:4] != b'MD21':
|
|
raise ValueError('Expected a bounded MD21 character model')
|
|
parts = {}
|
|
offset = 0
|
|
while offset < len(raw):
|
|
if offset + 8 > len(raw):
|
|
raise ValueError('Truncated model chunk header')
|
|
tag, length = struct.unpack_from('<4sI', raw, offset)
|
|
end = offset + 8 + length
|
|
if end > len(raw) or tag in parts:
|
|
raise ValueError('Truncated or duplicate model chunk')
|
|
parts[tag] = raw[offset + 8:end]
|
|
offset = end
|
|
body = parts[b'MD21']
|
|
if len(body) < 304 or body[:4] != b'MD20' or b'TXAC' not in parts:
|
|
raise ValueError('Missing character model body or material metadata')
|
|
if struct.unpack_from('<I', body, 296)[0]:
|
|
raise ValueError('Character material conversion expects no particle emitters')
|
|
count, start = struct.unpack_from('<II', body, 112)
|
|
if not count or start < 304 or start + count * 4 > len(body):
|
|
raise ValueError('Invalid character material array')
|
|
return parts, list(struct.iter_unpack('<HH', body[start:start + count * 4]))
|
|
|
|
|
|
def complete_appended_material_metadata(model, donor):
|
|
"""Copy the exact native TXAC entry for the last material of a generated model.
|
|
|
|
Earlier entries belong to existing material slots. A donor with multiple
|
|
matching flags/blend pairs is usable only if their metadata agrees.
|
|
"""
|
|
parts, materials = _chunks(model)
|
|
other, templates = _chunks(donor)
|
|
entries = other[b'TXAC']
|
|
if len(entries) != 2 * len(templates):
|
|
raise ValueError('Invalid donor material metadata length')
|
|
matches = {entries[2*i:2*i+2] for i, material in enumerate(templates)
|
|
if material == materials[-1]}
|
|
if len(matches) != 1:
|
|
raise ValueError('Missing or ambiguous donor material metadata')
|
|
entry, = matches
|
|
current = parts[b'TXAC']
|
|
if len(current) == 2 * len(materials) and current[-2:] == entry:
|
|
return model
|
|
if len(current) != 2 * (len(materials) - 1):
|
|
raise ValueError('Expected one appended material without metadata')
|
|
parts[b'TXAC'] = current + entry
|
|
return b''.join(struct.pack('<4sI', tag, len(payload)) + payload
|
|
for tag, payload in parts.items())
|