Files
WoW-Hybrid-gateway/tests/m2_track_convert_test.py

177 lines
10 KiB
Python

#!/usr/bin/env python3
import math
from pathlib import Path
import struct
import sys
import unittest
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
from m2_track_convert import convert_track
def source(times,keys,ranges,fmt='3f',global_id=-1,interpolation=1):
raw=bytearray(352);raw[:8]=struct.pack('<4sI',b'MD20',256)
def append(data):offset=len(raw);raw.extend(data);return offset
ro=append(b''.join(struct.pack('<II',*r)for r in ranges))
to=append(struct.pack('<'+'I'*len(times),*times))
ko=append(b''.join(struct.pack('<'+fmt,*k)for k in keys))
struct.pack_into('<Hh6I',raw,324,interpolation,global_id,len(ranges),ro,len(times),to,len(keys),ko)
return bytes(raw)
def decoded(output,header,stride):
_,_,nt,to,nk,ko=struct.unpack('<Hh4I',header);assert nt==nk
def arrays(at,n,s):
result=[]
for i in range(n):
count,offset=struct.unpack_from('<II',output,at+i*8)
result.append(bytes(output[offset:offset+count*s]))
return result
return arrays(to,nt,4),arrays(ko,nk,stride)
class TrackTest(unittest.TestCase):
def test_original_single_key_skeletal_family_from_held11(self):
import hashlib
import json
from unittest.mock import patch
import m2_equipment_convert as converter
job=Path(__file__).resolve().parents[1]/'runtime/rea-system-jobs-20261022/custom-map-resource-closure-20261024'
fixture=job/'held11-exact-track-range-diagnostics.json'
if not fixture.is_file():self.skipTest('Private held11 Source family not attached')
records=json.loads(fixture.read_text())['records'];self.assertEqual(len(records),11)
outdir=job/'model11-private-constant-skeletal-conversion';outdir.mkdir(exist_ok=True)
captured=[];results=[]
original=converter.convert_track
def checked(raw,at,kind,windows,out,**kwargs):
fields=struct.unpack_from('<Hh6I',raw,at)
header,audit=original(raw,at,kind,windows,out,**kwargs)
interpolation,glob,nr,ro,nt,to,nk,ko=fields
if glob==-1 and nr==0 and nt==1 and raw[to:to+4]==bytes(4):
# Source FindKey's range-missing fallback has begin=end=0;
# its early return yields key0 twice before reading time.
# Check the independently decoded target arrays at every
# source sequence, including nonzero animation origins.
stride={'vec3':12,'quaternion':8,'fixed16':2,'visibility':1}[kind]
timestamps,values=decoded(out,header,stride)
self.assertEqual(timestamps,[bytes(4)]*len(windows))
self.assertEqual(len(values),len(windows))
self.assertTrue(all(v==values[0] for v in values))
if kind!='quaternion':
self.assertEqual(values,[raw[ko:ko+stride]]*len(windows))
else:
expected=struct.unpack_from('<4f',raw,ko)
encoded=struct.unpack('<4h',values[0])
actual=[(v+32768)/32767 if v<0 else(v-32767)/32767 for v in encoded]
self.assertLessEqual(max(abs(a-b)for a,b in zip(expected,actual)),1/32767)
captured.append(dict(kind=kind,source_at=at,animation_count=len(windows)))
return header,audit
with patch.object(converter,'convert_track',checked):
for record in records:
source_record=record['Source_payload'];raw=Path(source_record['file']).read_bytes()
self.assertEqual(hashlib.sha256(raw).hexdigest(),source_record['sha256'])
row=dict(Source_member=record['Source_member'],source_sha256=source_record['sha256'])
first=record['first_failing_track'];self.assertEqual((first['kind'],first['key_count'],first['ranges'],first['times']),('vec3',1,[],[0]))
prior=len(captured)
try:
body,skins,report=converter.convert_equipment(raw)
except ValueError as error:
row.update(structural_conversion_complete=False,blocked=str(error))
self.assertNotEqual(str(error),'Per-animation track range count differs')
else:
root=outdir/source_record['sha256'];root.mkdir(exist_ok=True)
outputs=[]
for name,data in [('model.m2',body)]+[(f'view{i}.skin',skin)for i,skin in enumerate(skins)]:
path=root/name;path.write_bytes(data)
outputs.append(dict(file=str(path.relative_to(outdir)),bytes=len(data),sha256=hashlib.sha256(data).hexdigest()))
row.update(structural_conversion_complete=True,outputs=outputs,report=report)
self.assertGreater(len(captured),prior)
row['constant_tracks_checked']=captured[prior:];results.append(row)
# Do not widen missing-range handling to animated/nonzero-time data.
for raw in (source([1],[(1,2,3)],[]),source([0,1],[(1,2,3),(4,5,6)],[])):
out=bytearray(304)
with self.assertRaisesRegex(ValueError,'range count'):convert_track(raw,324,'vec3',[(10,20)],out)
self.assertEqual(out,bytearray(304))
report=dict(kind='Source5875-single-key-skeletal-held11-boundary',records=results,
source_models=11,constant_tracks_checked=len(captured),
converted_bodies=sum(r['structural_conversion_complete']for r in results),
blocked_bodies=sum(not r['structural_conversion_complete']for r in results),
successful782_conversions_repeated=False,Native_body_exports=0,
material_fidelity_proven=False,installed=False,engine_loaded=False,
track_converter_sha256=hashlib.sha256((job.parents[2]/'ops/m2_track_convert.py').read_bytes()).hexdigest())
(outdir/'manifest.json').write_text(json.dumps(report,indent=2)+'\n')
(job/'held11-constant-skeletal-focused-check.json').write_text(json.dumps(dict(status='PASS',**{k:v for k,v in report.items()if k!='records'}),indent=2)+'\n')
def test_inclusive_range_preserves_last_key_and_all_three_times(self):
raw=source([0,333,667],[(1,1,1),(1.3,1.3,1.3),(1,1,1)],[(0,2)])
out=bytearray(304);header,audit=convert_track(raw,324,'vec3',[(0,667)],out)
times,keys=decoded(out,header,12)
self.assertEqual(times,[struct.pack('<3I',0,333,667)])
self.assertEqual(len(keys[0]),36);self.assertEqual(audit['native_sequence_count'],1)
def test_actual_start_rebase_and_unused_default_range_audit(self):
raw=source([3333,6000],[(32767,),(32767,)],[(0,1),(0,0)],'h')
out=bytearray(304);header,audit=convert_track(raw,324,'fixed16',[(3333,6000)],out)
self.assertEqual(decoded(out,header,2)[0],[struct.pack('<2I',0,2667)])
self.assertEqual(audit['unused_default_ranges'],[[0,0]])
def test_global_quaternion_uses_native_offset_compression(self):
q=(0,.12182989,0,.99249244)
raw=source([0],[q],[],'4f',global_id=0,interpolation=0)
out=bytearray(304);header,audit=convert_track(raw,324,'quaternion',[(3333,3366)],out,global_sequence_count=1)
ts,keys=decoded(out,header,8);self.assertEqual(ts,[bytes(4)])
compressed=struct.unpack('<4h',keys[0])
values=[(v+32768)/32767 if v<0 else(v-32767)/32767 for v in compressed]
self.assertLess(max(abs(a-b)for a,b in zip(q,values)),1/32767)
self.assertLessEqual(audit['quaternion_max_quantization_error'],1/32767)
def test_multiple_animations_keep_separate_subarrays(self):
raw=source([100,150,200,250],[(1,)]*4,[(0,1),(2,3)],'B')
out=bytearray(304);header,_=convert_track(raw,324,'visibility',[(100,150),(200,250)],out)
self.assertEqual(decoded(out,header,1)[0],[struct.pack('<2I',0,50)]*2)
def test_static_time_zero_opacity_and_visibility_cover_every_animation(self):
for kind,fmt,key in [('fixed16','h',16384),('visibility','B',1)]:
raw=source([0],[(key,)],[],fmt);out=bytearray(304)
header,audit=convert_track(raw,324,kind,[(3333,3366),(6000,9000)],out)
timestamps,keys=decoded(out,header,struct.calcsize(fmt))
self.assertEqual(timestamps,[bytes(4),bytes(4)])
self.assertEqual(keys,[struct.pack('<'+fmt,key)]*2)
self.assertEqual(audit['static_default_animation_count'],2)
# A one-key track remains constant even when its source timestamp is
# nonzero: Source FindKey returns that same key on both sides.
for kind,fmt,key in [('fixed16','h',16384),('visibility','B',1)]:
for timestamp in (1,333):
raw=source([timestamp],[(key,)],[],fmt);out=bytearray(304)
header,audit=convert_track(raw,324,kind,[(0,10),(6000,9000)],out)
timestamps,keys=decoded(out,header,struct.calcsize(fmt))
self.assertEqual(timestamps,[struct.pack('<I',timestamp)]*2)
self.assertEqual(keys,[struct.pack('<'+fmt,key)]*2)
self.assertEqual(audit['static_default_animation_count'],2)
# Multiple keys without ranges still have no reviewed sequence mapping.
out=bytearray(304)
with self.assertRaisesRegex(ValueError,'range count'):
convert_track(source([0,1],[(1,),(0,)],[],'B'),324,'visibility',[(0,10)],out)
self.assertEqual(out,bytearray(304))
def test_rejections_leave_output_unchanged(self):
invalid=[(source([0],[(math.nan,0,0)],[(0,0)]),'vec3'),
(source([0],[(0,0,0)],[(0,1)]),'vec3'),
(source([10],[(0,0,0)],[(0,0)]),'vec3'),
(source([0],[(0,0,0)],[(0,0)],interpolation=2),'vec3'),
(source([0],[(0,0,0,1.1)],[(0,0)],'4f'),'quaternion'),
(source([0],[(2,)],[(0,0)],'B'),'visibility')]
for raw,kind in invalid:
out=bytearray(304);before=bytes(out)
with self.assertRaises(ValueError):convert_track(raw,324,kind,[(0,0)],out)
self.assertEqual(bytes(out),before)
def test_empty_track_and_input_pins(self):
raw=source([],[],[]);out=bytearray(304)
header,_=convert_track(raw,324,'vec3',[(0,0)],out)
self.assertEqual(struct.unpack('<Hh4I',header),(1,-1,0,0,0,0));self.assertEqual(len(out),304)
with self.assertRaises(ValueError):convert_track(raw[:-1],324,'vec3',[(0,0)],out)
with self.assertRaises(ValueError):convert_track(raw,324,'vec3',[],out)
if __name__=='__main__':unittest.main()