Files
2026-11-30 10:44:01 +02:00

163 lines
12 KiB
Python

#!/usr/bin/env python3
"""Stage source-authoritative Classic reputations in the existing hotfix package.
Local data only; preserve wire faction IDs, standings and source race/class bases.
Native-only reputation indices are stable presentation identifiers, never SQL IDs.
"""
import argparse,base64,copy,hashlib,json,struct
from pathlib import Path
from item_sparse_compat import fields,encode,check_db2,package_payloads
ROOT=Path(__file__).resolve().parents[1]
TABLE=0x06f624d7;LAYOUT=0x6d443c38
NATIVE=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever/install/bin/dbc/enUS/Faction.db2'
DBD=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/Faction.dbd'
def sha(raw):return hashlib.sha256(raw).hexdigest()
def encoded(value):return (json.dumps(value,sort_keys=True,ensure_ascii=False,separators=(',',':'),allow_nan=False)+'\n').encode()
def signed(value):return struct.unpack('<i',struct.pack('<I',value))[0]
def source_rows(raw):
if not isinstance(raw,bytes) or not 20<=len(raw)<=4194304:raise ValueError('Faction DBC byte bound')
magic,n,f,width,strings=struct.unpack_from('<4s4I',raw)
if magic!=b'WDBC' or f!=37 or width!=148 or not 1<=n<=4096 or len(raw)!=20+n*width+strings:raise ValueError('Unreviewed source Faction schema')
text=raw[20+n*width:];out=[];ids=set();indices=set()
def string(at):
if at>=len(text):raise ValueError('Faction string offset bound')
end=text.find(b'\0',at)
if end<0 or end-at>4096:raise ValueError('Faction string terminator bound')
return text[at:end].decode('utf-8')
for i in range(n):
v=struct.unpack_from('<37I',raw,20+i*width);ident,index=v[0],signed(v[1])
if not 0<ident<=0x7fffffff or ident in ids:raise ValueError('Duplicate/invalid faction ID')
ids.add(ident)
if index<0:continue
if index>=256 or index in indices:raise ValueError('Duplicate/unbounded source reputation index')
indices.add(index)
if any(x&~0x7f for x in v[14:18]):raise ValueError('Unreviewed source reputation flags')
out.append(dict(id=ident,index=index,name=string(v[19]),description=string(v[28]),parent=v[18],
races=list(v[2:6]),classes=list(v[6:10]),bases=list(map(signed,v[10:14])),flags=list(v[14:18])))
return sorted(out,key=lambda row:row['id'])
def flags(value):
# Same reviewed semantic conversion as forever_reputation_flags: source
# forced-invisible8 -> Hidden4, never native Header8; Rival64 not propagated.
result=value&0x37
return (result|4)&~1 if value&8 else result
def convert(source,native,aliases,registry,schema):
if registry.get('version')!=1 or not isinstance(registry.get('indices'),dict):raise ValueError('Faction registry version')
by_id={r['ID']:r for r in native}
if len(by_id)!=len(native) or not native:raise ValueError('Duplicate/empty native factions')
used={r['ReputationIndex']for r in native if r['ReputationIndex']>=0}
if used and max(used)>=256:raise ValueError('Native faction index budget requires explicit expansion')
reserved=set();new_index=max(used,default=-1)+1
for key,index in registry['indices'].items():
if not key.isdecimal() or type(index)is not int or not 0<=index<256 or index in used or index in reserved:raise ValueError('Faction index registry collision')
reserved.add(index)
records=[];mapping=[]
for old in source:
ident=old['id'];prior=by_id.get(ident)
if prior is not None and prior['ReputationIndex']>=0:index=prior['ReputationIndex']
else:
key=str(ident)
if key not in registry['indices']:
while new_index in used or new_index in reserved:new_index+=1
if new_index>=256:raise ValueError('Faction index capacity exceeded')
registry['indices'][key]=new_index;reserved.add(new_index)
index=registry['indices'][key]
# Preserve unrelated native presentation fields for existing identities.
# New rows have no modern renown/friendship/paragon/propagation system.
row=copy.deepcopy(prior) if prior else {name:([0]*count if count>1 else '' if kind in ('locstring','string')else 0)for name,kind,bits,unsigned,count in schema}
row['ID']=ident
cap=row.get('ParentFactionCap',[0,0])
if isinstance(cap,str):cap=list(base64.b64decode(cap,validate=True))
row['ParentFactionCap']=cap
row.update(Name_lang=old['name'],Description_lang=old['description'],ReputationIndex=index,ParentFactionID=old['parent'],
ReputationClassMask=old['classes'],ReputationBase=old['bases'],ReputationFlags=list(map(flags,old['flags'])),ReputationMax=[42999]*4)
for j,mask in enumerate(old['races']):
# Existing documented Goblin/HighElf visual aliases; wire races stay
# unchanged. Keep wildcard0 as wildcard, not a fabricated mask.
for original,presented in aliases:
if mask&(1<<(original-1)):mask=(mask&~(1<<(original-1)))|(1<<(presented-1))
row['ReputationRaceMasks'+str(j)]=[signed(mask&0xffffffff),signed(mask>>32)]
wire=encode(row,schema)
records.append(dict(table_name='Faction',table_hash=hex(TABLE),id=ident,record=row,wire_hex=wire.hex(),sha256=sha(wire),
policy='source-authoritative-reputation-definition',baseline_record_sha256=sha(encoded(prior))if prior else None))
mapping.append(dict(source_index=old['index'],id=ident,index=index))
if len({r['index']for r in mapping})!=len(mapping):raise ValueError('Duplicate translated reputation index')
return records,mapping
def mapping_header(mapping):
return '// Generated by ops/faction_compat.py; server faction IDs unchanged.\n#pragma once\n#include <cstdint>\nnamespace gateway::source_factions {\nstruct Mapping {uint32_t source_index,id,index;};\ninline constexpr Mapping Mappings[]={'+','.join('{'+','.join(str(r[k])for k in ('source_index','id','index'))+'}'for r in mapping)+'};\n}\n'
def merge_records(package,records,replace=False):
"""Merge Source definitions, restoring omitted reputation slots automatically."""
package_payloads(package['rows'])
prior={r['id']:r for r in package['rows']if int(r['table_hash'],16)==TABLE}
incoming={r['id']:r for r in records}
if len(incoming)!=len(records)or set(prior)-set(incoming):raise ValueError('Duplicate or removed faction definitions require review')
changed={i for i in prior if prior[i]['wire_hex']!=incoming[i]['wire_hex']}
def restores_omitted_slots(before,after):
if before.get('policy')!='source-authoritative-reputation-definition' or before.get('policy')!=after.get('policy'):return False
a,b=before['record'],after['record']
slots=[]
for i in range(4):
keys=[('ReputationClassMask',i),('ReputationBase',i),('ReputationFlags',i),('ReputationMax',i)]
race='ReputationRaceMasks'+str(i)
old=[a[key][index] for key,index in keys]+list(a[race])
new=[b[key][index] for key,index in keys]+list(b[race])
if old!=new:
# A missing Source slot has no race, class, or flags; its
# base/max may already be populated by an earlier bake.
if any(old[j] for j in (0,2,4,5)) or not any(new[j] for j in (0,2,4,5)):return False
if old[1]!=new[1] or old[3]!=new[3]:return False
slots.append(i)
if not slots:return False
for key in a:
if key in ('ReputationClassMask','ReputationBase','ReputationFlags','ReputationMax') or key.startswith('ReputationRaceMasks'):continue
if a[key]!=b[key]:return False
return True
if changed and not replace and any(not restores_omitted_slots(prior[i],incoming[i]) for i in changed):
raise ValueError('Changed faction definitions require explicit --replace-factions')
result=copy.deepcopy(package)
result['rows']=[incoming[r['id']]if int(r['table_hash'],16)==TABLE and r['id']in changed else r for r in result['rows']]
result['rows'] += [r for r in records if r['id']not in prior]
return result,dict(added=len(set(incoming)-set(prior)),updated=len(changed),unchanged=len(prior)-len(changed))
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--source-dbc',type=Path,default=Path.home()/'Servers/tortoise-docker/data/dbc/Faction.dbc')
p.add_argument('--native',type=Path,required=True);p.add_argument('--registry',type=Path);p.add_argument('--output',type=Path,required=True)
p.add_argument('--replace-factions',action='store_true',help='Explicitly stage changed definitions; unrelated content remains unchanged')
p.add_argument('--package',type=Path,default=ROOT/'docs/evidence/data/item-sparse-compat/package.json')
p.add_argument('--aliases',type=Path,default=ROOT/'docs/evidence/data/turtle-login-profile.json');a=p.parse_args()
out=a.output.absolute()
if not out.is_relative_to(ROOT/'runtime') or out.exists():p.error('Use a new runtime staging directory')
inputs=[a.source_dbc,a.native,a.package,a.aliases,NATIVE,DBD]+([a.registry]if a.registry else [])
raw={str(path):path.read_bytes() for path in inputs}
if any(len(v)>134217728 for v in raw.values()):raise ValueError('Faction input bound')
check_db2(NATIVE,TABLE,LAYOUT);schema=fields(DBD,LAYOUT,21)
source=source_rows(raw[str(a.source_dbc)]);native=json.loads(raw[str(a.native)])
login=json.loads(raw[str(a.aliases)])
aliases=[(v['source_race'],v['target_visual_race'])for v in login['roster_visual_aliases']['aliases']]
if len(set(aliases))!=len(aliases)or any(not 1<=x<=32 or not 1<=y<=64 for x,y in aliases):raise ValueError('Faction race presentation aliases')
registry=json.loads(raw[str(a.registry)])if a.registry else dict(version=1,indices={})
records,mapping=convert(source,native,aliases,registry,schema)
package=json.loads(raw[str(a.package)]);original=len(package['rows'])
package,changes=merge_records(package,records,a.replace_factions);push,header=package_payloads(package['rows']);package['push_id']=push
component=dict(kind='source-faction-compatibility',build='1.60.1.70334',schema_version=1,source_factions=source,mappings=mapping,
records=records,registry=registry,input_sha256={k:sha(v)for k,v in raw.items()},source_scope='pinned-local-Tortoise; live-Octo equivalence unverified',
target_table_hash=hex(TABLE),target_layout_hash=hex(LAYOUT),server_faction_ids_preserved=True,source_bases_preserved=True,
engine_loaded=False,gameplay_verified=False,source_standings_modified=False)
if changes['added']or changes['updated']:
package['components']=[c for c in package.get('components',[])if c.get('role')!=component['kind']]
package['components'].append(dict(role=component['kind'],component_sha256=sha(encoded(component)),record_count=len(records)))
payloads={'package.json':encoded(package),'item_sparse_compat.hpp':header.encode(),'source_faction_profile.hpp':mapping_header(mapping).encode(),
'component.json':encoded(component),'registry.json':encoded(registry)}
if sum(map(len,payloads.values()))>67108864:raise ValueError('Faction stage size bound')
out.mkdir(mode=0o700)
for name,value in payloads.items():(out/name).write_bytes(value)
for path in inputs:
if path.read_bytes()!=raw[str(path)]:raise ValueError('Faction input drift during staging')
(out/'manifest.json').write_bytes(encoded(dict(kind='staged-source-faction-package',added_records=changes['added'],updated_records=changes['updated'],unchanged_faction_records=changes['unchanged'],preserved_records=original-changes['updated'],total_records=len(package['rows']),push_id=push,
input_sha256=component['input_sha256'],files=[dict(path=k,bytes=len(v),sha256=sha(v))for k,v in payloads.items()],installed=False,native_verified=False)))
print('Staged',len(records),'faction definitions;',len(registry['indices']),'native-only reputation indices; source IDs/standings preserved; native acceptance pending.')
if __name__=='__main__':main()