208 lines
9.6 KiB
Python
208 lines
9.6 KiB
Python
"""Extract reviewed Noggit terrain edits into the 70334 Azeroth 32_48 roles."""
|
|
import argparse
|
|
import collections
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import struct
|
|
from pathlib import Path
|
|
|
|
import editor_client_127 as editor
|
|
|
|
SOURCE = Path('/mnt/Games/@project/editor-client-127/Data/patch.MPQ/world/maps/azeroth/azeroth_32_48.adt')
|
|
TAGS = b'|'.join((b'TVCM', b'RNCM', b'YLCM', b'FRCR', b'LACM', b'HSCM', b'ESCM', b'QLCM', b'VCCM'))
|
|
|
|
|
|
def top(raw):
|
|
return [(tag, raw[at:at + size]) for tag, at, size in editor.chunks(raw)]
|
|
|
|
|
|
def chunk_map(raw):
|
|
rows = top(raw)
|
|
if [tag for tag, _ in rows].count('MCNK') != 256:
|
|
raise ValueError('expected 256 MCNKs')
|
|
return {tag: body for tag, body in rows if tag != 'MCNK'}, [body for tag, body in rows if tag == 'MCNK']
|
|
|
|
|
|
def subchunks(body):
|
|
found = {}
|
|
for hit in re.finditer(TAGS, body[128:]):
|
|
at = hit.start() + 128
|
|
size = struct.unpack_from('<I', body, at + 4)[0]
|
|
tag = body[at:at + 4][::-1].decode()
|
|
if size > len(body) - at - 8 or tag in found:
|
|
raise ValueError('unreviewed MCNK subchunk layout: ' + tag)
|
|
found[tag] = body[at + 8:at + 8 + size]
|
|
if not {'MCVT', 'MCNR'} <= found.keys():
|
|
raise ValueError('missing terrain subchunks')
|
|
return found
|
|
|
|
|
|
def water_semantics(payload):
|
|
if len(payload) < 3072:
|
|
raise ValueError('short MH2O')
|
|
cells = []
|
|
for cell in range(256):
|
|
at, count, _ = struct.unpack_from('<3I', payload, cell * 12)
|
|
if count > 8 or (count and at + count * 24 > len(payload)):
|
|
raise ValueError('MH2O layer extent')
|
|
layers = set()
|
|
for i in range(count):
|
|
kind, flags, low, high, x, y, width, height, mask_at, vert_at = struct.unpack_from('<HHff4BII', payload, at + i * 24)
|
|
if not (0 <= x <= 8 and 0 <= y <= 8 and 0 <= width <= 8 - x and 0 <= height <= 8 - y):
|
|
raise ValueError('MH2O rectangle')
|
|
count_vertices = (width + 1) * (height + 1)
|
|
if vert_at + count_vertices * 4 > len(payload) or (mask_at and mask_at + 8 > len(payload)):
|
|
raise ValueError('MH2O payload extent')
|
|
mask = int.from_bytes(payload[mask_at:mask_at + 8], 'little') if mask_at else (1 << 64) - 1
|
|
heights = struct.unpack_from('<' + 'f' * count_vertices, payload, vert_at)
|
|
visible = []
|
|
for row in range(height):
|
|
for col in range(width):
|
|
if mask >> (row * width + col) & 1:
|
|
corners = tuple(round(heights[(row + dy) * (width + 1) + col + dx], 3)
|
|
for dy, dx in ((0, 0), (0, 1), (1, 0), (1, 1)))
|
|
visible.append((row, col, corners))
|
|
layers.add((flags, x, y, width, height, tuple(visible)))
|
|
cells.append(frozenset(layers))
|
|
return tuple(cells)
|
|
|
|
|
|
def placement_rows(payload, width):
|
|
if len(payload) % width:
|
|
raise ValueError('placement record width')
|
|
rows = {}
|
|
for at in range(0, len(payload), width):
|
|
record = payload[at:at + width]
|
|
uid = struct.unpack_from('<I', record, 4)[0]
|
|
if uid in rows:
|
|
raise ValueError('duplicate placement id')
|
|
rows[uid] = record
|
|
return rows
|
|
|
|
|
|
def extract(source, edited, native_root, native_obj0):
|
|
source_top, source_cells = chunk_map(source)
|
|
saved_top, saved_cells = chunk_map(edited)
|
|
if set(source_top) != set(saved_top):
|
|
raise ValueError('top-level chunk set changed')
|
|
for tag in source_top:
|
|
if tag in ('MCIN', 'MDDF', 'MODF', 'MH2O'):
|
|
continue
|
|
if source_top[tag] != saved_top[tag]:
|
|
raise ValueError('non-terrain top-level chunk changed: ' + tag)
|
|
if water_semantics(source_top['MH2O']) != water_semantics(saved_top['MH2O']):
|
|
raise ValueError('MH2O visible liquid instances/heights changed')
|
|
before_wmo = placement_rows(source_top['MODF'], 64)
|
|
after_wmo = placement_rows(saved_top['MODF'], 64)
|
|
if before_wmo.keys() != after_wmo.keys():
|
|
raise ValueError('MODF uniqueId set changed')
|
|
for uid, prior in before_wmo.items():
|
|
now = after_wmo[uid]
|
|
if prior[:62] != now[:62] or struct.unpack_from('<H', prior, 62)[0] not in (0, 1024) or struct.unpack_from('<H', now, 62)[0] not in (0, 1024):
|
|
raise ValueError(f'MODF semantic placement changed: {uid}')
|
|
before_doodads = placement_rows(source_top['MDDF'], 36)
|
|
after_doodads = placement_rows(saved_top['MDDF'], 36)
|
|
if before_doodads.keys() != after_doodads.keys():
|
|
raise ValueError('MDDF uniqueId set changed')
|
|
moved = {}
|
|
for uid, prior in before_doodads.items():
|
|
now = after_doodads[uid]
|
|
if prior[:8] != now[:8] or prior[20:] != now[20:]:
|
|
raise ValueError(f'MDDF model/rotation/scale/flags changed: {uid}')
|
|
if prior[8:20] != now[8:20]:
|
|
moved[uid] = now[8:20]
|
|
changed = {}
|
|
retained_shadows = []
|
|
report = collections.Counter()
|
|
for index, (before, after) in enumerate(zip(source_cells, saved_cells)):
|
|
if struct.unpack_from('<II', before, 4) != struct.unpack_from('<II', after, 4):
|
|
raise ValueError(f'MCNK coordinates changed: {index}')
|
|
src = subchunks(before)
|
|
dst = subchunks(after)
|
|
for tag in src.keys() | dst.keys():
|
|
if tag in ('MCVT', 'MCNR', 'MCSH', 'MCLQ'):
|
|
continue
|
|
if src.get(tag) != dst.get(tag):
|
|
raise ValueError(f'MCNK {index} non-height {tag} changed')
|
|
if src.get('MCSH') != dst.get('MCSH'):
|
|
if src.get('MCSH') and any(src['MCSH']):
|
|
raise ValueError(f'MCNK {index} nonzero shadow changed')
|
|
report['empty_shadow_dropped'] += 1
|
|
if src.get('MCLQ') != dst.get('MCLQ'):
|
|
if src.get('MCLQ', b'') or dst.get('MCLQ', b''):
|
|
raise ValueError(f'MCNK {index} legacy liquid changed')
|
|
report['empty_legacy_liquid_dropped'] += 1
|
|
base = struct.unpack_from('<f', before, 112)[0]
|
|
edit_base = struct.unpack_from('<f', after, 112)[0]
|
|
original = struct.unpack('<145f', src['MCVT'])
|
|
modified = struct.unpack('<145f', dst['MCVT'])
|
|
height_delta = max(abs((base + a) - (edit_base + b)) for a, b in zip(original, modified))
|
|
if height_delta > .001:
|
|
if len(dst['MCNR']) != 435:
|
|
raise ValueError(f'MCNK {index} normal width')
|
|
changed[index] = (dst['MCVT'], dst['MCNR'], edit_base)
|
|
if src.get('MCSH'):
|
|
retained_shadows.append(index)
|
|
elif src['MCNR'][:435] != dst['MCNR'][:435]:
|
|
raise ValueError(f'MCNK {index} normals changed without heights')
|
|
root_rows = top(native_root)
|
|
root_cells = [body for tag, body in root_rows if tag == 'MCNK']
|
|
if len(root_cells) != 256:
|
|
raise ValueError('shipped root MCNK count')
|
|
patched_root = []
|
|
index = 0
|
|
for tag, body in root_rows:
|
|
if tag == 'MCNK':
|
|
if index in changed:
|
|
heights, normals, base = changed[index]
|
|
native = bytearray(body)
|
|
subs = list(editor.chunks(body[128:]))
|
|
offsets = {name: (128 + at, size) for name, at, size in subs}
|
|
if offsets['MCVT'][1] != 580 or offsets['MCNR'][1] < 435:
|
|
raise ValueError('shipped terrain layout')
|
|
native[offsets['MCVT'][0]:offsets['MCVT'][0] + 580] = heights
|
|
native[offsets['MCNR'][0]:offsets['MCNR'][0] + 435] = normals
|
|
struct.pack_into('<f', native, 112, base)
|
|
body = bytes(native)
|
|
index += 1
|
|
patched_root.append(tag[::-1].encode() + struct.pack('<I', len(body)) + body)
|
|
native_parts = dict(top(native_obj0))
|
|
native_doodads = placement_rows(native_parts['MDDF'], 36)
|
|
if not moved.keys() <= native_doodads.keys():
|
|
raise ValueError('snapped doodad absent from shipped OBJ0')
|
|
patched_obj = []
|
|
for tag, body in top(native_obj0):
|
|
if tag == 'MDDF' and moved:
|
|
mutable = bytearray(body)
|
|
for at in range(0, len(mutable), 36):
|
|
uid = struct.unpack_from('<I', mutable, at + 4)[0]
|
|
if uid in moved:
|
|
mutable[at + 8:at + 20] = moved[uid]
|
|
body = bytes(mutable)
|
|
patched_obj.append(tag[::-1].encode() + struct.pack('<I', len(body)) + body)
|
|
report.update(changed_mcnks=len(changed), snapped_doodads=len(moved),
|
|
nonzero_shadows_kept=len(retained_shadows))
|
|
return b''.join(patched_root), b''.join(patched_obj), dict(report,
|
|
changed_coordinates=[(i % 16, i // 16) for i in changed],
|
|
snapped_unique_ids=sorted(moved), stale_shadow_coordinates=[(i % 16, i // 16) for i in retained_shadows])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('edited', type=Path)
|
|
parser.add_argument('--native-root', type=Path, required=True)
|
|
parser.add_argument('--native-obj0', type=Path, required=True)
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
original = SOURCE.read_bytes()
|
|
base = args.native_root.read_bytes()
|
|
if editor.roundtrip_root(original) != base:
|
|
raise ValueError('source roundtrip differs from shipped native root')
|
|
root, obj0, report = extract(original, args.edited.read_bytes(), base, args.native_obj0.read_bytes())
|
|
args.output.mkdir(parents=True, exist_ok=True)
|
|
(args.output / 'root.adt').write_bytes(root)
|
|
(args.output / 'obj0.adt').write_bytes(obj0)
|
|
(args.output / 'report.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
print(json.dumps(report))
|