131 lines
6.7 KiB
Python
131 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Compare paired equipment M2s across the observed 256 -> 272/274 boundary.
|
|
|
|
Uses WoWee's M2Header/M2VertexDisk, embedded view and M2SkinHeader layouts.
|
|
Reordering is allowed; multiplicity and triangle winding are preserved. This
|
|
does not infer material/animation equivalence or install/convert an asset.
|
|
"""
|
|
import argparse
|
|
from collections import Counter
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import struct
|
|
|
|
from item_appearance_preflight import model_dependency_chunks, model_vertex_stream
|
|
|
|
|
|
def _extent(raw, offset, count, stride, minimum):
|
|
if count > 1048576 or (count and (offset < minimum or offset > len(raw) or count > (len(raw)-offset)//stride)):
|
|
raise ValueError('Invalid paired-model array extent')
|
|
return raw[offset:offset+count*stride] if count else b''
|
|
|
|
|
|
def _array(raw, offset, stride, minimum):
|
|
count, start = struct.unpack_from('<II', raw, offset)
|
|
data = _extent(raw, start, count, stride, minimum)
|
|
return [data[i:i+stride] for i in range(0, len(data), stride)]
|
|
|
|
|
|
def model(raw):
|
|
summary = model_vertex_stream(raw) # validates finite vertices and textures
|
|
dependencies = None
|
|
if raw[:4] == b'MD21':
|
|
dependencies = model_dependency_chunks(raw)
|
|
size = struct.unpack_from('<I', raw, 4)[0]
|
|
raw = raw[8:8+size]
|
|
old = summary['md20_version'] in (256, 257)
|
|
minimum = 324 if old else 304
|
|
vertices = _array(raw, 68 if old else 60, 48, minimum)
|
|
bone_count, bone_offset = struct.unpack_from('<II', raw, 52 if old else 44)
|
|
_extent(raw, bone_offset, bone_count, 108 if old else 88, minimum)
|
|
view_count = struct.unpack_from('<I', raw, 76 if old else 68)[0]
|
|
if view_count > 32:
|
|
raise ValueError('Paired-model view count bound')
|
|
return dict(body=raw, old=old, minimum=minimum, vertices=vertices,
|
|
summary=summary, dependencies=dependencies,
|
|
bone_count=bone_count, view_count=view_count)
|
|
|
|
|
|
def skin(parsed, skin_raw=None, view=0):
|
|
"""Read source embedded view or one explicitly supplied native SKIN.
|
|
|
|
M2 indices select vertices; triangle indices select the skin index array.
|
|
No filename fallback, skin-ID inference or renderer acceptance assumptions.
|
|
"""
|
|
if parsed['old']:
|
|
if skin_raw is not None or not 0 <= view < parsed['view_count']:
|
|
raise ValueError('Invalid source embedded view selection')
|
|
raw = parsed['body']
|
|
start = struct.unpack_from('<I', raw, 80)[0]
|
|
_extent(raw, start, parsed['view_count'], 44, 324)
|
|
header = struct.unpack_from('<11I', raw, start+view*44)
|
|
minimum, submesh_stride = 324, 32
|
|
else:
|
|
if not isinstance(skin_raw, bytes) or not 64 <= len(skin_raw) <= 67108864 or skin_raw[:4] != b'SKIN':
|
|
raise ValueError('Explicit bounded native SKIN required')
|
|
raw = skin_raw
|
|
header = struct.unpack_from('<11I', raw, 4)
|
|
# Actual272/274 sidecars extend the older48-byte reader with a pair
|
|
# describing12-byte shadow batches and8reserved bytes. Native489766
|
|
# has2 at3136; its trailing alignment padding is NOT part of a record.
|
|
minimum, submesh_stride = 64, 48
|
|
shadows,shadow_offset=struct.unpack_from('<II',raw,48)
|
|
_extent(raw,shadow_offset,shadows,12,minimum)
|
|
arrays = []
|
|
for k, stride in ((0, 2), (2, 2), (4, 4), (6, submesh_stride), (8, 24)):
|
|
count, start = header[k:k+2]
|
|
arrays.append(_extent(raw, start, count, stride, minimum))
|
|
indices = [x[0] for x in struct.iter_unpack('<H', arrays[0])]
|
|
triangles = [x[0] for x in struct.iter_unpack('<H', arrays[1])]
|
|
base=0 if parsed['old']else header[10]
|
|
if len(triangles) % 3 or any(i+base >= len(parsed['vertices']) for i in indices) or any(i >= len(indices) for i in triangles):
|
|
raise ValueError('Invalid paired-model skin topology index')
|
|
faces = []
|
|
for k in range(0, len(triangles), 3):
|
|
face = tuple(parsed['vertices'][base+indices[i]] for i in triangles[k:k+3])
|
|
# Rotate each oriented triangle, never reverse winding.
|
|
faces.append(min(face, face[1:]+face[:1], face[2:]+face[:2]))
|
|
return dict(header=header, arrays=arrays, faces=Counter(faces),
|
|
summary=dict(index_count=len(indices), triangle_count=len(triangles)//3,
|
|
submesh_count=header[6], batch_count=header[8],
|
|
legacy_bone_count_max=header[10]if parsed['old']else None,
|
|
native_lod_vertex_base=None if parsed['old']else header[10],submesh_stride=submesh_stride,
|
|
shadow_batch_count=0 if parsed['old']else shadows,
|
|
batch_rows=[list(row) for row in struct.iter_unpack('<Bb11H', arrays[4])]))
|
|
|
|
|
|
def compare(source, target, target_skin):
|
|
s, t = model(source), model(target)
|
|
if not s['old'] or t['old']:
|
|
raise ValueError('Require observed source256 and native272/274 pair')
|
|
ss, ts = skin(s), skin(t, target_skin)
|
|
attributes = {}
|
|
for name, a, b in (('position',0,12), ('skinning',12,20), ('normal',20,32), ('uv0',32,40), ('uv1',40,48), ('full_vertex',0,48)):
|
|
attributes[name] = Counter(v[a:b] for v in s['vertices']) == Counter(v[a:b] for v in t['vertices'])
|
|
return dict(kind='paired-equipment-model-format-comparison',
|
|
input_sha256={k:hashlib.sha256(v).hexdigest() for k,v in [('source_m2',source),('native_m2',target),('native_skin',target_skin)]},
|
|
source=dict(**s['summary'], bone_count=s['bone_count'], view_count=s['view_count'], skin=ss['summary']),
|
|
target=dict(**t['summary'], bone_count=t['bone_count'], view_count=t['view_count'], skin=ts['summary'], dependencies=t['dependencies']),
|
|
exact_unordered_attribute_multisets_equal=attributes,
|
|
oriented_full_vertex_triangle_multisets_equal=ss['faces']==ts['faces'],
|
|
source_vertex_order_preserved=s['vertices']==t['vertices'],
|
|
material_semantics_equivalent=False, animation_semantics_equivalent=False,
|
|
converted=False, installed=False, engine_loaded=False)
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--source',type=Path,required=True)
|
|
p.add_argument('--target',type=Path,required=True)
|
|
p.add_argument('--skin',type=Path,required=True)
|
|
p.add_argument('--output',type=Path,required=True)
|
|
a=p.parse_args()
|
|
result=compare(a.source.read_bytes(),a.target.read_bytes(),a.skin.read_bytes())
|
|
with a.output.open('x') as f:
|
|
json.dump(result,f,indent=2);f.write('\n')
|
|
print(json.dumps({k:result[k] for k in ('exact_unordered_attribute_multisets_equal','oriented_full_vertex_triangle_multisets_equal','source_vertex_order_preserved','converted')}))
|
|
|
|
|
|
if __name__=='__main__':main()
|