Files

95 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""Stage seven reviewed Octo-only presentation definitions through the existing converter."""
import argparse,hashlib,json,struct,subprocess,sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from turtle_data import DBC
from octo_spell_presentation import presentation_rows
from addon_source_authority import select_variant
PAIRS={65314:27206,59509:59507,59515:59507,59516:59507,59510:59512,59517:59512,59518:59512}
DANGLING={5223:5681,5229:5714,5406:6258,55023:90001,55026:90002,55030:90003,55032:90005}
TABLES=('SpellName','Spell','SpellMisc','SpellEffect')
def load(path):return json.loads(path.read_text())
def save(path,value):path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(value,indent=2)+'\n')
def decoded(path):return {r['id']:r['fields'] for r in map(json.loads,path.read_text().splitlines())}
def source_pair(dbc,ident,reference):
a=dbc.by_id[ident];b=dbc.by_id[reference]
allowed={0,76,*range(120,128)}
if any(x!=y and i not in allowed for i,(x,y) in enumerate(zip(a,b))):raise ValueError('Source analogue has unrelated differences')
if ident==65314 and a[76]!=b[76]:raise ValueError('Pet damage analogue magnitude differs')
if any(a[61+i] for i in (1,2)):raise ValueError('Expected one Source effect')
return tuple(x-(1<<32) if x>=(1<<31) else x for x in a)
def convert(a):
root=a.root;root.mkdir(parents=True,exist_ok=True)
for path in a.parent.iterdir():
if path.name in ('candidate','HANDOFF.md','host-test.log','native-spells','native-spell-references.json'):continue
dest=root/path.name
if not dest.exists():dest.symlink_to(path)
variant=select_variant(load(a.parent/'source-spell-variants.json')['rows']);path=Path(variant['file'])
if hashlib.sha256(path.read_bytes()).hexdigest()!=variant['sha256']:raise ValueError('Source Spell pin')
dbc=DBC(path,173);request=root/'spell-request.json';save(request,{t:[-1] for t in (*TABLES,'SpellDuration','SpellCastTimes','SpellRange')});data=root/'spell-baseline'
def read_tables(directory,out,req):
result=subprocess.run(['dotnet',str(a.reader),str(directory),str(a.defs),str(req),str(out)],capture_output=True,text=True)
(root/(out.name+'.log')).write_text(result.stdout+result.stderr)
if result.returncode:raise ValueError('DB2 reader failed')
read_tables(a.baseline,data,request);native={t:decoded(data/(t+'.jsonl')) for t in load(request)};package=load(a.package)['rows']
next_id={}
for table in ('SpellMisc','SpellEffect','SpellAuraOptions'):
raw=(a.baseline/(table+'.db2')).read_bytes()
if raw[:4]!=b'WDC5':raise ValueError('Expected WDC5')
next_id[table]=1+max([struct.unpack_from('<I',raw,164)[0],*native.get(table,{}),*[int(r['id']) for r in package if r.get('table_name')==table]])
additions={t:[] for t in TABLES};proof=[]
for ident,reference in PAIRS.items():
row=source_pair(dbc,ident,reference)
if ident in native['SpellName'] or ident in native['Spell'] or any(r['SpellID']==ident for t in ('SpellMisc','SpellEffect') for r in native[t].values()):raise ValueError('New spell already exists')
misc=[r for r in native['SpellMisc'].values() if r['SpellID']==reference and r['DifficultyID']==0]
if len(misc)!=1 or not misc[0]['SpellIconFileDataID']:raise ValueError('Native analogue icon unavailable')
for table,index in [('SpellCastTimes',row[18]),('SpellDuration',row[30]),('SpellRange',row[36])]:
if index and index not in native[table]:raise ValueError('Missing timing/range reference')
if row[109] and row[109] not in native['SpellName']:raise ValueError('Missing triggered spell')
converted=presentation_rows(row,dbc.string,misc[0]['SpellIconFileDataID'],next_id)
if converted['SpellAuraOptions']:raise ValueError('Unexpected proc options')
for table in TABLES:additions[table].extend(converted[table])
proof.append({'spell_id':ident,'source_analogue':reference,'source_icon_index':row[117],'native_icon_fdid':misc[0]['SpellIconFileDataID'],'source_sha256':variant['sha256'],'name':dbc.string(row[120])})
out=root/'spell-db2';out.mkdir(exist_ok=True)
for table,rows in additions.items():
request_path=root/'spell-rows'/(table+'.json');save(request_path,rows)
result=subprocess.run(['dotnet',str(a.baker),'addrows',str(a.baseline),str(a.defs),table,str(request_path),str(out/(table+'.db2'))],capture_output=True,text=True)
(root/(table+'.bake.log')).write_text(result.stdout+result.stderr)
if result.returncode or 'roundtripBad=0' not in result.stdout:raise ValueError('Spell bake failed: '+table)
combined=root/'combined-baseline';combined.mkdir(exist_ok=True)
for path in a.baseline.glob('*.db2'):
target=out/path.name if (out/path.name).exists() else path
dest=combined/path.name
if dest.is_symlink():dest.unlink()
dest.symlink_to(target)
read_tables(combined,root/'native-spells',request)
for table in TABLES:
after=decoded(root/'native-spells'/(table+'.jsonl'));before=native[table]
if any(after.get(k)!=v for k,v in before.items()) or set(after)-set(before)!={r['ID'] for r in additions[table]}:raise ValueError('Unrelated spell row changed')
for expected in additions[table]:
actual=after[expected['ID']]
for key,value in expected.items():
if isinstance(value,float):value={'f32_bits':struct.unpack('<I',struct.pack('<f',value))[0]}
if actual[key]!=value:raise ValueError('Converted field mismatch: '+table+'.'+key)
refs=load(a.parent/'native-spell-references.json')
for table in ('SpellMisc','SpellEffect'):refs[table]=sorted(set(refs[table])|set(PAIRS))
save(root/'native-spell-references.json',refs)
effects=load(a.parent/'effect-columns.json');slots=[]
for line in (a.parent/'source-effects.tsv').read_text().splitlines():
row=dict(zip(effects,line.split('\t')));item=int(row['entry'])
if item not in DANGLING:continue
for slot in range(1,6):
spell=int(row['spellid_'+str(slot)])
if spell==DANGLING[item]:
if spell in dbc.by_id or spell in native['SpellName']:raise ValueError('Dangling spell now exists; review required')
slots.append({'item_id':item,'slot':slot,'spell_id':spell,'reason':'Absent from Source and server Spell.dbc; owner decision 20a'})
if len(slots)!=7:raise ValueError('Expected exactly seven reviewed dangling slots')
save(root/'reviewed-dangling-slots.json',slots);save(root/'spell-conversion-proof.json',proof)
save(root/'spell-manifest.json',{'source':variant,'tables':{t:hashlib.sha256((out/(t+'.db2')).read_bytes()).hexdigest() for t in TABLES},'parent_input_sha256':{str((a.baseline/(t+'.db2')).resolve()):hashlib.sha256((a.baseline/(t+'.db2')).read_bytes()).hexdigest() for t in TABLES},'presentation_only':True})
print('Staged 7 Source spell definitions in 4 DB2s; 7 reviewed dangling item slots listed')
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
for name in ['root','parent','baseline','reader','baker','defs','package']:p.add_argument('--'+name,type=Path,required=True)
convert(p.parse_args())