Files
WoW-Hybrid-gateway/ops/item_sparse_compat.py

609 lines
45 KiB
Python

#!/usr/bin/env python3
"""Build bounded70334 ItemSparse compatibility records from authorized snapshots.
Offline build tool only; native runtime needs no SQL/provider process. Original
DB2/schema files are read-only. ID/basic-class collisions fail rather than remap.
"""
import argparse,hashlib,json,math,re,struct
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
LAYOUT=0x6fcc3191;TABLE=0x919be54e
def fields(path,layout=LAYOUT,expected=68):
text=path.read_text();head=text.split('LAYOUT',1)[0]
kinds={}
for line in head.splitlines():
m=re.match(r'(int(?:<[^>]+>)?|float|locstring|string)\s+(\w+)\??',line)
if m:kinds[m[2]]=m[1].split('<')[0]
block=text.split(f'LAYOUT {layout:08X}\n',1)[1].split('\nLAYOUT',1)[0]
if '1.60.1.70334' not in block:raise ValueError('Unverified70334 ItemSparse layout')
result=[]
for line in block.splitlines():
if not line or line.startswith(('BUILD','COMMENT')):continue
if line.startswith('$noninline,id$ID'):continue
if line.startswith('$noninline,relation$'):line=line.split('$',2)[2]
m=re.fullmatch(r'(\w+)(?:<(u?)(8|16|32|64)>)?(?:\[(\d+)\])?',line)
if not m:raise ValueError('Unreviewed ItemSparse field syntax')
name,unsigned,bits,count=m.groups();kind=kinds[name]
if kind=='int' and bits is None:raise ValueError('Integer width missing')
result.append((name,kind,int(bits or 32),bool(unsigned),int(count or 1)))
if len(result)!=expected:raise ValueError('DB2 field-count drift')
return result
def encode(row,schema):
out=bytearray()
for name,kind,bits,unsigned,count in schema:
values=row[name] if count>1 else [row[name]]
if len(values)!=count:raise ValueError('ItemSparse array bound: '+name)
for value in values:
if kind in ('locstring','string'):
if not isinstance(value,str) or '\0' in value or len(value.encode())>4096:raise ValueError('ItemSparse string bound')
out.extend(value.encode()+b'\0')
elif kind=='float':
if not math.isfinite(value):raise ValueError('Nonfinite ItemSparse float')
out.extend(struct.pack('<f',value))
else:out.extend(int(value).to_bytes(bits//8,'little',signed=not unsigned))
if len(out)>65535:raise ValueError('ItemSparse record bound')
return bytes(out)
def f32(v):return struct.unpack('<f',struct.pack('<f',v))[0]
def check_db2(path,table=TABLE,layout=LAYOUT):
with path.open('rb') as f:head=f.read(160)
if len(head)!=160 or head[:4]!=b'WDC5' or struct.unpack_from('<II',head,152)!=(table,layout):raise ValueError('Destination DB2 header/layout mismatch')
if head[8:136].split(b'\0',1)[0]!=b'wowstatic_camelot_1_60_1':raise ValueError('Destination ItemSparse schema mismatch')
def coefficient(value,points):
# Item::GetItemStatValue and classic_armory_commands::ExportItems round
# StatPercentEditor*RandPropPoints*0.0001 to the displayed integer.
center=round(value/points*10000)
for c in (center,center-1,center+1,center-2,center+2,center-3,center+3):
decoded=f32(f32(c*f32(points))*f32(.0001));rounded=int(decoded+(.5 if decoded>=0 else -.5))
if rounded==value:return c
raise ValueError('Stat amount cannot round-trip through verified budget')
def native_item_material(proto, native=None):
"""Keep same-ID native material for the classic -1 sentinel; use zero for new rows."""
material = proto['material']
if material != -1:
return material
if native is not None:
if native['ID'] != proto['entry']:
raise ValueError('Native material belongs to a different item')
return native['Material']
return 0
def bag_family_mask(value):
# Tortoise ItemPrototype.h BagFamily is one category, consumed with equality
# by ItemCanGoIntoBag.70334 ItemTemplate.h BAG_FAMILY_MASK and its matching
# ItemCanGoIntoBag use a bitmask. Preserve only reviewed equal meanings.
# Turtle MEAT/FISH are not equivalent to the native cooking/tackle families.
mapping={0:0,1:0x1,2:0x2,3:0x4,6:0x20,7:0x40,8:0x80,9:0x100,12:0x8,13:0x400}
if type(value) is not int or value not in mapping:
raise ValueError('Source bag family requires reviewed semantic conversion')
return mapping[value]
def item_class_mask(value):
"""Preserve playable source restrictions when a uint32 exceeds native int16.
Source ChrClasses.dbc and SharedDefines.h agree on the nine original IDs;
these identities already match the reviewed native roster contract. Bits
for absent source classes do not restrict any playable source character.
Never truncate the high bits into an unrelated signed destination value.
Existing representable masks retain their original bytes.
"""
if type(value)is not int or not -1<=value<=0xffffffff:
raise ValueError('Source item class mask integer bound')
if value<=0x7fff:return value
from turtle_login_profile import ORIGINAL_CLASSES
playable=sum(1<<(ident-1)for ident in ORIGINAL_CLASSES)
allowed=value&playable
return -1 if allowed==playable else allowed
def legacy_item_flags(value,*,defer_instance_initializer=False):
"""Translate reviewed source restrictions, never copy an arbitrary mask.
Tortoise ItemPrototype.h / Spell.cpp prohibit disenchanting with0x8000;
target ItemTemplate.h / BonusData::Initialize use the matching restriction.
Both Player::CanEquipUniqueItem implementations limit another equipped
instance with0x80000. Both Player::UpdateItemDuration implementations use
REAL_DURATION0x10000 for offline/realtime ticking; that newly supported
flag requires an explicit source lifetime. Source UNK0(0x1) is explicitly
declared unused in ItemPrototype.h and has no consuming source references;
omit it rather than assigning native NO_PICKUP. Source unknown0x40/0x100 are NOT native PLAYERCAST/
LEGACY. Source0x400 IGNORE_BAG_SPACE is NOT native USES_RESOURCES:
retain it in the source record but omit it from destination metadata.
The pinned Tortoise source declares it without any consuming references;
this does not claim legacy-client bag-space behavior is implemented. Server
inventory validation remains authoritative; no inventory capacity is granted.
"""
# Additional paired source/target contracts (not a raw mask copy):
# CONJURED: both mail/auction restrictions and logout expiry use this flag.
# LOOTABLE/HAS_LOOT: source LootMgr/OpenItem and target OpenItem.
# INDESTRUCTIBLE/NO_USER_DESTROY: both DestroyItem handlers reject it.
# NO_EQUIP_COOLDOWN: both ApplyEquipCooldown paths skip the default timer.
# WRAPPER/IS_WRAPPER: both WrapItem handlers validate this capability.
# PARTY_LOOT/MULTI_DROP: source freeforall and target loot per-player state.
# CHARTER/PETITION, HAS_TEXT, NO_CREATOR retain their declared identities.
# Source0x8/0x10/0x40/0x100/0x1000 remain unreviewed:
# several acquired materially different destination meanings.
if type(defer_instance_initializer)is not bool:raise ValueError('Explicit instance-initializer deferral policy required')
mapping={bit:bit for bit in (0x2,0x4,0x20,0x80,0x200,0x800,0x2000,0x4000,
0x8000,0x10000,0x20000,0x80000)}
mapping[0x400]=0
mapping[0x1]=0
# Item.cpp::Create copies this template bit into ITEM_DYNFLAG_UNK6.
# It is not target template PLAYERCAST. Metadata-first publication may
# explicitly defer that unknown instance behavior; ordinary conversion
# remains strict. The catalogue must retain a visible dependency receipt.
if defer_instance_initializer:mapping[0x40]=0
if type(value) is not int or not 0<=value<=0xffffffff or value&~sum(mapping):
raise ValueError('Nonzero legacy flags require reviewed semantic conversion')
result=0
for source,target in mapping.items():
if value&source:result|=target
return result
def armor_adjustment(proto,shield_armor=None,armor_baseline=None):
"""Per-item source armor minus its genuine effective engine baseline.
Keep the established shield-row API. A general armor baseline is produced
by item_armor_compat.native_armor_baseline; the two may never be combined.
"""
if shield_armor is not None and armor_baseline is not None:raise ValueError('Choose one native armor baseline')
if armor_baseline is not None:
identity={key:proto[key]for key in ('entry','class','subclass','inventory_type','item_level','quality')}
base=armor_baseline.get('native_armor')
if (armor_baseline.get('kind')!='native-70334-item-armor-baseline' or armor_baseline.get('identity')!=identity
or any(type(v)is not int for v in identity.values())
or identity['class']!=4 or identity['subclass']not in(1,2,3,4,6)
or type(base)is not int or not 0<=base<=0xffffffff):raise ValueError('Native per-item armor baseline identity differs')
elif int(proto['class'])==4 and int(proto['subclass'])==6 and shield_armor is not None:
quality=3 if int(proto['quality'])==7 else int(proto['quality'])
if shield_armor['ID']!=int(proto['item_level']) or not 0<=quality<=6:raise ValueError('Native shield armor budget identity differs')
base=int(shield_armor['Quality'][quality]+.5)
elif (type(proto.get('class'))is int and (proto['class']==2 or (proto['class']==4 and type(proto.get('subclass'))is int and proto['subclass']in(0,5,7,8,9)))):
# Same-build ItemTemplate::GetArmor returns zero outside cloth..plate
# and shields. Turtle also stores intrinsic armor on rings, necklaces,
# trinkets, held items and relics. Preserve it as flat EXTRA_ARMOR50;
# never borrow an unrelated equip spell or a shared armor curve.
# Source ObjectMgr loads this field with GetInt16; ItemPrototype and
# the real item-query decoder retain its sign. EXTRA_ARMOR and the
# existing stat coefficient path also support signed flat modifiers.
value=proto.get('armor')
if type(value)is not int or not -32768<=value<=32767:raise ValueError('Source intrinsic armor outside signed16 bounds')
return value
else:return 0
if type(proto['armor'])is not int or not 0<=proto['armor']<=0xffffffff:raise ValueError('Source armor outside uint32 bounds')
return proto['armor']-base
def shield_block_stat(proto,enabled=False):
"""Explicit classic intrinsic shield block -> native flat item stat48.
Source ItemPrototype::Block is separate from its primary stat array.
Forever's ItemModType48 and Player::_ApplyItemBonuses consume flat block,
unlike block rating15. Its per-item ItemSparse has no intrinsic block
column; never invent a spell or alter a shared shield/armor curve.
This affects client metadata only, never authoritative combat execution.
"""
value=proto.get('block',0)
if type(value)is not int or not 0<=value<=0x7fffffff:raise ValueError('Source shield block outside signed stat bounds')
if not value:return 0
if not enabled:raise ValueError('Shield block requires explicit flat-value conversion')
if any(type(proto.get(k))is not int for k in('class','subclass','inventory_type')) or (proto['class'],proto['subclass'],proto['inventory_type'])!=(4,6,14):
raise ValueError('Intrinsic block requires an actual source shield')
return value
def requires_stat_budget(proto,shield_armor=None,*,armor_baseline=None,shield_block=False):
"""Only converted nonzero stats use RandPropPoints; item level is retained.
In particular a stat-free level0 item needs no invented level0 budget row.
Keep this predicate aligned with the actual stats collected by convert.
"""
extra_armor=armor_adjustment(proto,shield_armor,armor_baseline)
# Preflight callers also use this budget-only predicate on unsupported
# records. The converter itself rejects a nonzero unenabled block field.
block=shield_block_stat(proto,True) if shield_block else 0
if any(int(proto.get('stat_value'+str(i),0)) for i in range(1,11)):return True
if any(int(proto.get(name,0)) for name in ('fire_res','frost_res','holy_res','shadow_res','nature_res','arcane_res')):return True
return bool(extra_armor or block)
def stat_budget(proto,budgets,shield_armor=None,*,armor_baseline=None,shield_block=False):
"""Select an actual same-level budget only when the conversion uses one."""
if not requires_stat_budget(proto,shield_armor,armor_baseline=armor_baseline,shield_block=shield_block):return None
row=budgets.get(proto['item_level'])
if not isinstance(row,dict) or row.get('ID')!=proto['item_level']:raise ValueError('missing accessible RandPropPoints level')
return row
def intrinsic_stat_fields(proto,points,shield_armor=None,*,armor_baseline=None,shield_block=False):
"""Encode the existing source stat/resistance/armor/block budget fields only."""
extra_armor=armor_adjustment(proto,shield_armor,armor_baseline)
block=shield_block_stat(proto,shield_block)
if requires_stat_budget(proto,shield_armor,armor_baseline=armor_baseline,shield_block=shield_block)and points is None:raise ValueError('Nonzero converted stats require a legitimate RandPropPoints budget')
inv=int(proto['inventory_type']);quality=int(proto['quality'])
row={'StatPercentEditor':[0]*10}
row['StatModifier_bonusStat']=[-1]*10
inv=int(proto['inventory_type']);index=0 if inv in (1,4,5,7,15,17,20,25) else 1 if inv in (3,6,8,10,12) else 2 if inv in (2,9,11,14,16,23) else 3 if inv in (13,21,22) else (3 if int(proto['subclass'])==19 else 0) if inv==26 else 4 if inv==28 else None
#70334client ranged budgets differ from the modern server-reference
# helper: real native bow/crossbow/gun/wand controls use column4.
# Column0produced3instead of10resistance in the owned gun's real API.
# Thrown/ammo keep their separate, not-yet-verified conventions. Wand
# stat budgets do not imply the physical ranged damage multiplier.
if int(proto['class'])==2 and inv in(15,26)and int(proto['subclass'])in(2,3,18,19):index=4
quality=int(proto['quality']);quality_field='GoodF' if quality==2 else 'SuperiorF' if quality in (3,7) else 'EpicF' if quality in (4,5,6) else None
stats=[]
for i in range(1,11):
value=int(proto['stat_value'+str(i)]);stat=int(proto['stat_type'+str(i)])
if not value:continue
if stat not in (0,1,3,4,5,6,7):raise ValueError('Stat requires a separately reviewed conversion')
stats.append((stat,value))
# Destination ItemModType names establish these exact school identities;
# legacy stores resistances outside its ten primary stat slots.
# Source int32 resistance fields use signed BASE_VALUE item bonuses. The
# original native resistance slots likewise retain signed StatPercentEditor
# values (including item10555); use the same signed budget round-trip as
# primary stats rather than dropping or rejecting resistance penalties.
for name,stat in (('fire_res',51),('frost_res',52),('holy_res',53),('shadow_res',54),('nature_res',55),('arcane_res',56)):
value=int(proto.get(name,0))
if value:stats.append((stat,value))
if extra_armor:stats.append((50,extra_armor)) # Source ITEM_MOD_EXTRA_ARMOR, no item-level spoof.
if block:stats.append((48,block)) # Flat block value, NOT block rating15.
if len(stats)>10:raise ValueError('Native item stat capacity exceeded; no truncation')
for i,(stat,value) in enumerate(stats):
if index is None or quality_field is None:raise ValueError('Stat requires a separately reviewed conversion')
row['StatModifier_bonusStat'][i]=stat;row['StatPercentEditor'][i]=coefficient(value,points[quality_field][index])
return row
def convert(proto,basic,points,schema,native=None,shield_armor=None,*,armor_baseline=None,shield_block=False,weapon_baseline=None,weapon_projection=None,weapon_presentation_profile=None,defer_instance_initializer=False,material_retention=None):
retained_material=None
if material_retention is not None:
from item_material_retention import verify
retained_material=verify(proto,basic,native,schema,material_retention)
if weapon_projection is not None:
if weapon_baseline is not None:raise ValueError('Exact baseline and source-presented projection are distinct policies')
from item_damage_profile import verify_native_weapon_projection
weapon_projection=verify_native_weapon_projection(proto,weapon_projection,weapon_presentation_profile)
if any(int(basic[k])!=int(proto[v]) for k,v in [('ClassID','class'),('SubclassID','subclass'),('InventoryType','inventory_type')]):raise ValueError('Same ID has incompatible native basic definition')
source_flags=legacy_item_flags(proto['flags'],defer_instance_initializer=defer_instance_initializer)
# Both Player::UpdateItemDuration pass elapsed time_t seconds to
# Item::UpdateDuration; Create initializes remaining time from the template.
# Template lifetime is NOT an absolute timestamp or the current owned timer.
duration=proto.get('duration',0)
if (type(duration)is not int or not 0<=duration<=0xffffffff
or(source_flags&0x10000 and 'duration'not in proto)):
raise ValueError('Invalid or missing source item duration')
row={name:([0]*count if count>1 else '' if kind in ('string','locstring') else 0) for name,kind,bits,unsigned,count in schema}
row['DurationInInventory']=duration
from source_required_tool_category import category_for
row['TotemCategoryID']=category_for(proto)
if native is not None and native['ID']!=proto['entry']:raise ValueError('Native baseline identity differs; no unrelated item substitution')
if int(proto['class'])==2:
if weapon_baseline is not None:
from item_damage_profile import verify_native_weapon_baseline
weapon_baseline=verify_native_weapon_baseline(proto,weapon_baseline)
row['DmgVariance']=weapon_baseline['dmg_variance'];row['DamageType']=weapon_baseline['damage_type']
elif weapon_projection is not None:
row['DmgVariance']=weapon_projection['dmg_variance'];row['DamageType']=weapon_projection['damage_type']
elif native is None:raise ValueError('Weapon damage conversion incomplete; require matching native baseline')
# Never flatten an existing weapon by zero-initializing its engine
# damage parameters. These remain native, NOT claimed converted from
# legacy multi-school min/max values. Server damage stays authoritative.
else:
row['DmgVariance']=native['DmgVariance'];row['QualityModifier']=native['QualityModifier']
# Source and native primary schools share the reviewed0..6 enum.
# Retaining magnitude parameters must not turn elemental weapons
# into Physical through this new row's default DamageType0. Use the
# actual Source school, including when the same-ID native differs.
school=proto.get('dmg_type1')
if type(school)is not int or not 0<=school<=6:raise ValueError('Unreviewed source primary weapon school')
row['DamageType']=school
elif weapon_baseline is not None or weapon_projection is not None:raise ValueError('Weapon baseline/projection supplied for a non-weapon')
mapping={'Description_lang':'description','Display_lang':'name','StartQuestID':'start_quest','LanguageID':'page_language','ItemRange':'range_mod','Stackable':'stackable','MaxCount':'max_count','MinReputation':'required_reputation_rank','RequiredAbility':'required_spell','SellPrice':'sell_price','BuyPrice':'buy_price','VendorStackCount':'buy_count','ItemSet':'set_id','LockID':'lock_id','PageID':'page_text','ItemDelay':'delay','MinFactionID':'required_reputation_faction','RequiredSkillRank':'required_skill_rank','RequiredSkill':'required_skill','ItemLevel':'item_level','AllowableClass':'allowable_class','SheatheType':'sheath','Material':'material','PageMaterialID':'page_material','Bonding':'bonding','ContainerSlots':'container_slots','RequiredPVPRank':'required_honor_rank','RequiredLevel':'required_level','InventoryType':'inventory_type','OverallQualityID':'quality','AmmunitionType':'ammo_type'}
for dest,source in mapping.items():row[dest]=proto[source]
row['Material'] = retained_material if retained_material is not None else native_item_material(proto, native)
row['AllowableClass']=item_class_mask(proto['allowable_class'])
row['BagFamily']=bag_family_mask(proto['bag_family'])
race=int(proto['allowable_race']);row['AllowableRace']=[race,-1 if race<0 else 0]
if int(proto['map_bound'])<0:raise ValueError('Negative instance binding requires reviewed sentinel conversion')
row['ZoneBound']=[proto['area_bound'],0];row['InstanceBound']=proto['map_bound']
row['PriceVariance']=1;row['PriceRandomValue']=1
# Destination UI policy: exact server prices; authenticated public metadata.
# ItemTemplate.h: DONT_IGNORE_BUY_PRICE / SHOW_BEFORE_DISCOVERED / OVERRIDE_GOLD_COST.
row['Flags']=[source_flags,0x6004,0,0,0]
if (weapon_baseline or weapon_projection or{}).get('caster_curve'):row['Flags'][1]|=0x200 # ITEM_FLAG2_CASTER_WEAPON
row.update(intrinsic_stat_fields(proto,points,shield_armor,armor_baseline=armor_baseline,shield_block=shield_block))
return row
def component(path,args):
profile=json.loads(path.read_text())
if profile['build']!='1.60.1.70334' or profile['input_sha256']['source']!=hashlib.sha256(args.source.read_bytes()).hexdigest():raise ValueError('Component/source identity mismatch')
allowed={'ItemEffect':(0x4002a5b1,24,0x4ca77678,9),'ItemXItemEffect':(0x00cb674f,8,0x96f083ad,2),'ItemArmorShield':(0xffbb8dc2,30,0x7e6c94f9,2)}
schemas={}
for name,meta in profile['native_tables'].items():
if name not in allowed:raise ValueError('Unreviewed component table')
table,size,layout,count=allowed[name];db=args.db2.parent/(name+'.db2');dbd=args.dbd.parent/(name+'.dbd')
check_db2(db,table,layout)
if hashlib.sha256(db.read_bytes()).hexdigest()!=meta['db2_sha256'] or hashlib.sha256(dbd.read_bytes()).hexdigest()!=meta['dbd_sha256']:raise ValueError('Native component schema/data drift')
schemas[name]=fields(dbd,layout,count)
for row in profile['records']:
if row['table_name'] not in schemas:raise ValueError('Record has no reviewed schema')
table,size,layout,count=allowed[row['table_name']];raw=bytes.fromhex(row['wire_hex'])
if int(row['table_hash'],16)!=table or len(raw)!=size or hashlib.sha256(raw).hexdigest()!=row['sha256'] or not 0<row['id']<=0x7fffffff or encode(row['record'],schemas[row['table_name']])!=raw:raise ValueError('Malformed component record')
return profile
# Full item/spell/visual catalogue, still partitioned into the existing bounded
# pushes. Native first/count indices are uint32; aggregate/per-push byte caps
# remain independent and unchanged.
MAX_PACKAGE_ROWS=262144
MAX_PACKAGE_BYTES=67108864
MAX_PUSH_ROWS=4096
MAX_PUSH_BYTES=1048576
WORKING_WIRE_POLICY='recovered-working-native-registry-v1'
WORKING_WIRE_DELTA='explicit-working-registry-delta-v1'
class _WorkingWireBaseline:
def __init__(self, baseline, delta):
self.baseline=baseline
self.expected=baseline|delta
def _wire_registry(rows):
"""Exact status/body identities from a pinned native registry export."""
if not isinstance(rows,list) or not 1<=len(rows)<=MAX_PACKAGE_ROWS:raise ValueError('Working registry row count bound')
out={}
for row in rows:
if (not isinstance(row,dict) or type(row.get('id'))is not int or not 0<=row['id']<=0x7fffffff
or not isinstance(row.get('table_hash'),str) or not re.fullmatch(r'0x[0-9a-fA-F]{1,8}',row['table_hash'])):
raise ValueError('Working registry record identity differs')
key=(int(row['table_hash'],16),row['id']);status=row.get('record_status','valid');wire=row.get('wire_hex')
if not key[0] or key in out or status not in ('valid','removed'):raise ValueError('Working registry identity/status differs')
if (not isinstance(wire,str) or len(wire)>131070 or not re.fullmatch(r'(?:[0-9a-f]{2})*',wire)
or (status=='removed') != (wire=='')):
raise ValueError('Working registry body differs')
digest=hashlib.sha256(bytes.fromhex(wire)).hexdigest()
if digest!=row.get('sha256'):raise ValueError('Working registry body digest differs')
out[key]=(status,wire,digest)
return out
def load_working_wire_baseline(package, *, required=False):
"""Pin the working codec export and the only reviewed changes to it.
Generic offline composers remain usable without this optional provenance.
Continued codec builds require it, so omitting metadata cannot silently
substitute an older catalogue for the last working native registry.
"""
base=package.get('working_wire_baseline');delta=package.get('working_wire_delta')
if base is None and delta is None:
if required:raise ValueError('Verified working wire baseline and explicit delta required for codec builds')
return None
from item_package_preflight import read_public_json,bounded_digest,MAX_COMPATIBILITY_PACKAGE_JSON_BYTES
def path(value):
if not isinstance(value,str) or not value:raise ValueError('Working registry provenance path required')
result=Path(value)
return result if result.is_absolute() else ROOT/result
def pinned(meta,kind,keys):
if not isinstance(meta,dict) or set(meta)!=keys or meta.get('kind')!=kind:raise ValueError('Working registry provenance differs')
if type(meta.get('record_count'))is not int or not (0 if kind==WORKING_WIRE_DELTA else 1)<=meta['record_count']<=MAX_PACKAGE_ROWS:raise ValueError('Working registry provenance count bound')
if not isinstance(meta.get('sha256'),str) or not re.fullmatch('[0-9a-f]{64}',meta['sha256']):raise ValueError('Working registry provenance digest required')
data,digest=read_public_json(path(meta['path']),MAX_COMPATIBILITY_PACKAGE_JSON_BYTES)
if digest!=meta['sha256'] or not isinstance(data,dict) or len(data.get('rows',[]))!=meta['record_count']:raise ValueError('Working registry provenance input differs')
return {} if kind==WORKING_WIRE_DELTA and data['rows']==[] else _wire_registry(data['rows'])
baseline=pinned(base,WORKING_WIRE_POLICY,{'kind','path','sha256','codec_path','codec_sha256','record_count'})
if (not isinstance(base['codec_sha256'],str) or not re.fullmatch('[0-9a-f]{64}',base['codec_sha256'])
or bounded_digest(path(base['codec_path']),MAX_PACKAGE_BYTES)!=base['codec_sha256']):
raise ValueError('Working native codec preimage differs')
changes=pinned(delta,WORKING_WIRE_DELTA,{'kind','path','sha256','record_count'})
return _WorkingWireBaseline(baseline,changes)
def validate_working_wire_registry(rows, wire_baseline):
if not isinstance(wire_baseline,_WorkingWireBaseline):raise ValueError('Validated working registry provenance required')
actual=_wire_registry(rows)
if actual.keys()!=wire_baseline.expected.keys():raise ValueError('Working registry identities dropped or unreviewed identities added')
if actual!=wire_baseline.expected:raise ValueError('Working registry status/body changed outside the explicit delta')
def _package_data(rows, *, wire_baseline=None, compact_payloads=False):
"""Serialize a reviewed registry into independently bounded native pushes.
Schema/semantic conversion belongs to each component. This common boundary
checks the final wire identities, digests and actual codec budgets before
creating the content-derived push and the existing generic native registry.
Row order remains stable so existing packages reproduce byte-for-byte.
"""
if type(compact_payloads)is not bool:raise ValueError('Compact payload selection must be boolean')
if not isinstance(rows,list) or not 1<=len(rows)<=MAX_PACKAGE_ROWS:raise ValueError('Combined native registry count bound')
if wire_baseline is not None:validate_working_wire_registry(rows,wire_baseline)
identities=set();payloads=[];statuses=[]
for row in rows:
if not isinstance(row,dict) or type(row.get('id'))is not int or not 0<=row['id']<=0x7fffffff:raise ValueError('Invalid native package record identity')
value=row.get('table_hash')
if not isinstance(value,str) or not re.fullmatch(r'0x[0-9a-fA-F]{1,8}',value):raise ValueError('Invalid native package table identity')
table=int(value,16)
map_zero = row['id'] == 0
if map_zero:
from spell_passive_compat import SUPPLEMENTAL_TABLES,fields as map_fields,encode as map_encode
if table != SUPPLEMENTAL_TABLES['Map'][0] or row.get('table_name') != 'Map' or row.get('record_status','valid') != 'valid':
raise ValueError('Invalid native package record identity')
if not table:raise ValueError('Zero native package table identity')
identity=(table,row['id'])
if identity in identities:raise ValueError('Duplicate package identities')
identities.add(identity)
status=row.get('record_status','valid')
if status not in ('valid','removed'):raise ValueError('Unreviewed native record status')
wire=row.get('wire_hex')
recovered=row.get('policy')==WORKING_WIRE_POLICY
if recovered and (wire_baseline is None or wire_baseline.baseline.get(identity)!=(status,wire,row.get('sha256'))):
raise ValueError('Recovered native record differs from verified working preimage')
if status=='removed' and not recovered:
# Only reviewed source-owned relationship removals. Never delete
# spells, assets, startup tables or shared effect definitions.
baseline=row.get('baseline_record')
if wire!='' or row.get('record')is not None or not isinstance(baseline,dict):raise ValueError('Unreviewed or unpinned native relation removal')
if table==0x8645bb79 and row.get('table_name')=='ItemSetSpell':
bounds={'ID':(1,0x7fffffff),'ChrSpecID':(0,65535),'SpellID':(1,0xffffffff),
'TraitSubTreeID':(0,65535),'Threshold':(1,255),'ItemSetID':(1,0x7fffffff)}
if (row.get('policy')!='source-authoritative-per-set-bonus-link-replacement'
or set(baseline)!=set(bounds) or any(type(baseline[k])is not int or not low<=baseline[k]<=high for k,(low,high)in bounds.items())
or baseline['ID']!=row['id'] or type(row.get('source_set'))is not int or baseline['ItemSetID']!=row['source_set']
or row.get('baseline_record_sha256')!=hashlib.sha256(struct.pack('<HIHBi',baseline['ChrSpecID'],baseline['SpellID'],baseline['TraitSubTreeID'],baseline['Threshold'],baseline['ItemSetID'])).hexdigest()):
raise ValueError('Unreviewed or unpinned native set relation removal')
elif table==0xff4446f6 and row.get('table_name')=='SkillLineAbility':
from spell_passive_compat import fields as spell_fields,encode as spell_encode
schema=spell_fields(Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/SkillLineAbility.dbd','SkillLineAbility')
if (row.get('policy')!='source-owned-profession-ability-link-replacement-v1'
or baseline.get('ID')!=row['id']or type(row.get('source_skill_line'))is not int
or baseline.get('SkillLine')!=row['source_skill_line']
or row.get('reason')!='destination-spell-absent-from-source-inventory'
or any(not isinstance(row.get(k),str)or not re.fullmatch('[0-9a-f]{64}',row[k])for k in('source_spell_inventory_sha256','source_ability_inventory_sha256'))
or row.get('baseline_record_sha256')!=hashlib.sha256(spell_encode(baseline,schema)).hexdigest()):
raise ValueError('Unreviewed or unpinned native profession relation removal')
elif table==0xf9a4265f and row.get('table_name')=='Talent':
from source_catalogue_compat import schema as talent_schema,validate_talent_removal
validate_talent_removal(row,talent_schema(Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions','Talent'))
elif (table!=0x00cb674f or row.get('table_name')!='ItemXItemEffect'
or row.get('policy')!='source-authoritative-per-item-passive-link-replacement'
or set(baseline)!={'ID','ItemEffectID','ItemID'}
or any(type(baseline[k])is not int or not 0<baseline[k]<=0x7fffffff for k in baseline)
or baseline['ID']!=row['id'] or baseline['ItemID']!=row.get('source_item')
or row.get('baseline_record_sha256')!=hashlib.sha256(struct.pack('<iI',baseline['ItemEffectID'],baseline['ItemID'])).hexdigest()):
raise ValueError('Unreviewed or unpinned native relation removal')
elif status=='valid' and (not isinstance(wire,str) or not wire or len(wire)>131070 or not re.fullmatch(r'(?:[0-9a-f]{2})+',wire)):raise ValueError('Invalid bounded native record payload')
raw=bytes.fromhex(wire)
if map_zero:
original = row.get('record')
if not isinstance(original,dict) or original.get('ID') != 0:
raise ValueError('Complete typed Map0 record required')
schema = map_fields(Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/Map.dbd','Map')
if map_encode(original,schema,table='Map') != raw:
raise ValueError('Typed Map0 record differs from package wire body')
if hashlib.sha256(raw).hexdigest()!=row.get('sha256'):raise ValueError('Native package record digest differs')
# TextureFileData layout BD7C74C2: $id$FileDataID<32>, UsageType<u8>,
# relation MaterialResourcesID<32>. The actual70334 engine asserts if
# its outer record ID differs from this inline primary key. Catch this
# at the shared package boundary, independent of converter metadata.
if table==0x1a473014 and status=='valid' and (len(raw)!=9 or int.from_bytes(raw[:4],'little',signed=True)!=row['id']):
raise ValueError('TextureFileData inline primary key differs from package record identity')
payloads.append(raw);statuses.append(2 if status=='removed' else 1)
if sum(21+len(raw)for raw in payloads)>MAX_PACKAGE_BYTES:raise ValueError('Combined native registry byte bound')
removed=2 in statuses
def content_identity(begin,end):
entries=list(zip(rows[begin:end],payloads[begin:end],statuses[begin:end]))
identity=(b'GW-HOTFIX-STATUS-1\0'+b''.join(struct.pack('<IIB',int(row['table_hash'],16),row['id'],status)+raw for row,raw,status in entries)
if any(status==2 for _,_,status in entries)else b''.join(struct.pack('<II',int(row['table_hash'],16),row['id'])+raw for row,raw,status in entries))
ident=int.from_bytes(hashlib.sha256(identity).digest()[:4],'little')&0x7fffffff
if not ident:raise ValueError('Zero compatibility push identity')
return ident
push_id=content_identity(0,len(rows));pages=[];begin=0;size=8
for index,raw in enumerate(payloads):
if index-begin>=MAX_PUSH_ROWS or size+21+len(raw)>MAX_PUSH_BYTES:
pages.append(dict(push_id=content_identity(begin,index),first=begin,count=index-begin,wire_bytes=size))
begin=index;size=8
size+=21+len(raw)
pages.append(dict(push_id=content_identity(begin,len(rows)),first=begin,count=len(rows)-begin,wire_bytes=size))
if len({p['push_id']for p in pages})!=len(pages):raise ValueError('Compatibility push digest collision')
header='// Generated by ops/item_sparse_compat.py from authorized local snapshots.\n#pragma once\n#include <cstdint>\n#include <span>\nnamespace gateway::item_sparse_compat {\n'
header+=f'inline constexpr int32_t PushID={push_id};\n'
if compact_payloads:
# Ordinary narrow literals may initialize uint8_t (unsigned char) arrays.
# Fixed-width octal escapes preserve NUL/high bytes and cannot consume
# the next byte's digits. Concatenation adds one final sentinel only;
# every record span explicitly excludes it. Keep bounded literal tokens.
blob=b''.join(payloads);offsets=[];offset=0
for raw in payloads:offsets.append(offset);offset+=len(raw)
literals=['"'+''.join(f'\\{byte:03o}'for byte in blob[i:i+64])+'"'for i in range(0,len(blob),64)]
header+='inline constexpr uint8_t PayloadBlob[]=\n'+'\n'.join(literals or ['""'])+';\n'
else:
for n,row in enumerate(rows):
if statuses[n]==1:header+=f'inline constexpr uint8_t Data{n}[]={{'+','.join('0x'+row['wire_hex'][i:i+2] for i in range(0,len(row['wire_hex']),2))+'};\n'
header+='struct Record {uint32_t table,id;std::span<const uint8_t> data;'+('uint8_t status=1;'if removed else '')+'};\ninline constexpr Record Records[]={'+','.join('{'+row['table_hash']+','+str(row['id'])+(',{},2'if statuses[n]==2 else (',{PayloadBlob+'+str(offsets[n])+','+str(len(payloads[n]))+'}'if compact_payloads else ',Data'+str(n)))+'}'for n,row in enumerate(rows))+'};\n'
header+='struct Push {int32_t id;uint32_t first,count;};\ninline constexpr Push Pushes[]={'+','.join('{'+str(p['push_id'])+','+str(p['first'])+','+str(p['count'])+'}'for p in pages)+'};\n'
header+='inline std::span<const uint8_t> find(uint32_t table,uint32_t id){for(const auto& r:Records)if(r.table==table&&r.id==id)return r.data;return {};}\n}\n'
return push_id,header,pages
def verified_frozen_registry_header(path, expected_sha256, generated, rows):
"""Keep a pinned native table's byte-pool layout after validating every public record."""
import codecs
raw = path.read_bytes()
if not re.fullmatch('[0-9a-f]{64}', expected_sha256) or hashlib.sha256(raw).hexdigest() != expected_sha256:
raise ValueError('Frozen native registry header digest differs')
text = raw.decode('ascii')
def split(header):
prefix, payload_and_rows = header.split('inline constexpr uint8_t PayloadBlob[]=\n', 1)
literals, declarations = payload_and_rows.split(';\n', 1)
declarations, record_and_push = declarations.split('inline constexpr Record Records[]={', 1)
records, tail = record_and_push.split('};\n', 1)
return prefix, literals, declarations, records, tail
before, literals, types, records, after = split(text)
ref_before, _, ref_types, _, ref_after = split(generated)
if (before, types, after) != (ref_before, ref_types, ref_after):
raise ValueError('Frozen registry metadata, push descriptors or lookup differs')
blob = codecs.escape_decode(literals.replace('"', '').replace('\n', '').encode('ascii'))[0]
entry = re.compile(r'\{(0x[0-9A-Fa-f]+),(\d+),(?:\{PayloadBlob\+(\d+),(\d+)\}|\{\},2)\}')
position = 0
for index, row in enumerate(rows):
if index:
if records[position:position + 1] != ',':
raise ValueError('Frozen registry record separator differs')
position += 1
match = entry.match(records, position)
if not match or (int(match[1], 16), int(match[2])) != (int(row['table_hash'], 16), row['id']):
raise ValueError('Frozen registry record identity or order differs')
status = 'valid' if match[3] else 'removed'
offset, length = int(match[3] or 0), int(match[4] or 0)
if (status != row.get('record_status', 'valid') or offset + length > len(blob)
or blob[offset:offset + length] != bytes.fromhex(row['wire_hex'])):
raise ValueError('Frozen native registry body or status differs')
position = match.end()
if position != len(records):
raise ValueError('Frozen registry has unexpected trailing entries')
return text
def package_payloads(rows, *, wire_baseline=None, compact_payloads=False):
push,header,_=_package_data(rows,wire_baseline=wire_baseline,compact_payloads=compact_payloads)
return push,header
def package_pages(rows, *, wire_baseline=None):
"""Validated row ownership for Hotfix advertisement and acceptance reports.
The root digest identifies the entire package. Only page digests are sent
on the wire; a one-page package retains its historical push identity.
"""
return _package_data(rows,wire_baseline=wire_baseline)[2]
def main():
p=argparse.ArgumentParser()
for name in ('source','basic','points','header','report'):p.add_argument('--'+name,type=Path,required=True)
for name in ('native-sparse','shield-armor','effects-profile','armor-profile'):p.add_argument('--'+name,type=Path)
p.add_argument('--shield-block',action='store_true',help='Convert actual source shield intrinsic block to native flat-value item stat48; never block rating')
p.add_argument('--dbd',type=Path,default=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/ItemSparse.dbd')
p.add_argument('--db2',type=Path,default=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever/install/bin/dbc/enUS/ItemSparse.db2');a=p.parse_args()
if not all(path.resolve().is_relative_to(ROOT) for path in (a.header,a.report)):p.error('Generated package outputs must stay in gateway')
if a.shield_armor and a.armor_profile:p.error('Choose native baseline armor or the converted armor profile, not both')
check_db2(a.db2)
schema=fields(a.dbd);source=json.loads(a.source.read_text());source=source if isinstance(source,list) else [source]
if not 1<=len(source)<=4096:raise ValueError('Package record count bound')
basics={r['ID']:r for r in json.loads(a.basic.read_text())};budgets={r['ID']:r for r in json.loads(a.points.read_text())};rows=[]
natives={r['ID']:r for r in json.loads(a.native_sparse.read_text())} if a.native_sparse else {}
armor_budgets={r['ID']:r for r in json.loads(a.shield_armor.read_text())} if a.shield_armor else {}
extra=[]
if a.armor_profile:
profile=component(a.armor_profile,a);extra+=profile['records']
armor_budgets={r['id']:r['record'] for r in profile['records'] if r['table_name']=='ItemArmorShield'}
if a.effects_profile:extra+=component(a.effects_profile,a)['records']
for proto in sorted(source,key=lambda r:r['entry']):
entry=int(proto['entry'])
if not 0<entry<=0x7fffffff:raise ValueError('Item identity outside signed hotfix record bounds')
armor=armor_budgets[int(proto['item_level'])] if armor_budgets and int(proto['class'])==4 and int(proto['subclass'])==6 else None
row=convert(proto,basics[entry],budgets[int(proto['item_level'])],schema,natives.get(entry),armor,shield_block=a.shield_block);raw=encode(row,schema);rows.append({'table_name':'ItemSparse','table_hash':hex(TABLE),'id':entry,'record':row,'wire_hex':raw.hex(),'sha256':hashlib.sha256(raw).hexdigest(),'preserved_native_fields':['DmgVariance','QualityModifier'] if int(proto['class'])==2 else []})
rows=extra+rows
push_id,header=package_payloads(rows)
a.header.parent.mkdir(parents=True,exist_ok=True);a.header.write_text(header)
report={'build':'1.60.1.70334','schema':'wowstatic_camelot_1_60_1','layout_hash':hex(LAYOUT),'table_hash':hex(TABLE),'push_id':push_id,'id_remapping':False,'source_sha256':hashlib.sha256(a.source.read_bytes()).hexdigest(),'dbd_sha256':hashlib.sha256(a.dbd.read_bytes()).hexdigest(),'destination_db2_sha256':hashlib.sha256(a.db2.read_bytes()).hexdigest(),'basic_sha256':hashlib.sha256(a.basic.read_bytes()).hexdigest(),'budgets_sha256':hashlib.sha256(a.points.read_bytes()).hexdigest(),'rows':rows,'limitations':['Bounded source-backed metadata package; each revision requires actual-client verification.','Armor curves and spell/effect relationships require separately reviewed component profiles; no universal tooltip or effect equivalence claimed.','Nonzero legacy flags, missing basic IDs and unreviewed stat types are rejected; no unrelated ID substitution.','Build-time snapshot package; native runtime has no database/provider subprocess.','Native hotfix validation proves record acceptance, not gameplay effects; see recorded actual-client evidence for tested revisions.']}
report['native_baseline_sha256']=hashlib.sha256(a.native_sparse.read_bytes()).hexdigest() if a.native_sparse else None
report['effects_profile_sha256']=hashlib.sha256(a.effects_profile.read_bytes()).hexdigest() if a.effects_profile else None
report['shield_armor_budget_sha256']=hashlib.sha256(a.shield_armor.read_bytes()).hexdigest() if a.shield_armor else None
report['shield_intrinsic_block_policy']='source-shield-block-to-native-flat-item-stat48' if a.shield_block else 'reject-nonzero-source-block'
report['armor_profile_sha256']=hashlib.sha256(a.armor_profile.read_bytes()).hexdigest() if a.armor_profile else None
report['limitations'].append('Existing weapons retain same-ID native DmgVariance/QualityModifier and map the validated Source primary school; primary magnitude and additional-school legacy damage conversion is incomplete. New weapons without that baseline are rejected.')
a.report.parent.mkdir(parents=True,exist_ok=True);a.report.write_text(json.dumps(report,indent=2)+'\n');print('Generated',len(rows),'source-backed item compatibility records; no client data files modified.')
if __name__=='__main__':main()