Files
WoW-Hybrid-gateway/ops/source_catalogue_compat.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

403 lines
21 KiB
Python

#!/usr/bin/env python3
"""Encode reviewed Source catalogue relationships in the actual 70334 layouts.
This is definition data only. Journal ownership and server gameplay remain
separate protocol work. Inputs are named native exports and Source row specs;
packed WDC storage words are deliberately never used as hotfix fields.
"""
from copy import deepcopy
from collections.abc import Mapping
from functools import lru_cache
import hashlib
import math
import class_spell_compat as spells
POLICY = 'source-catalogue-relationships-70334-v1'
TALENT_REMOVAL_POLICY = 'source-authoritative-talent-tree-replacement-v1'
TALENT_SOURCE_SHA256 = '48d8d121ccec21d23922f809023a0b8d78b7a565878e357269832d79c87e6a39'
TALENT_INVENTORY_SHA256 = 'a7ffe1790916ad446d7816ab70dac4393529886504b55401ed16db93683f4e0c'
TABLES = {
'SpellCategory': (3502494094, 3080419553, '7993ebdc6b4766b88163ebf24e141cdef4ecaf2c5c4de336b1b891ba58b0e68f'),
'Talent': (4188284511, 343605317, '1c5ea7b385d74d029b67a6f81e54fe034a7f62773cf5f9c92c03208c1f265779'),
'SkillLine': (3040725462, 1734549884, '625446338a0fd5e9294ffed774de5f256b47dbde3a147b065a76582e8229f814'),
'CreatureFamily': (916407967, 2145635239, 'b104af3cdf8963d9a45d1c904fde28a74cc4f8428723a5f641a7f82f03dd5150'),
'SkillRaceClassInfo': (112059424, 606567240, '12c1e019656bb88814ce18b74a0eb7baa04ed6b0086544248c00f36b062ece71'),
'SkillLineAbility': (4282664694, 575635104, 'd66e6b0eb5a030752f757cbf67dd05f6bae1946118f63695e2136634a137dace'),
'Mount': (2524150337, 3837205369, 'bb4ff8337f2daa7e3c4db3abc40221a814c661e2ca82e8ba16509d10032c9fd2'),
'MountXDisplay': (2030087241, 3227190767, '08c111071a42a90c215de0c5959454720806b1a39050d156fcd4e2b1d7fc0566'),
'BattlePetSpecies': (1821637041, 1486611074, '21849ee64157fc2504c9d73825a36c9de66d16e8f8ddf4fdf918b35ef2272ece'),
'Toy': (2063803484, 2182831392, '65cf1afbb02abf0f3ecfb25ed0f7cb466b61aab7332b1489d3e0bc6ee42107d4'),
'GameObjectDisplayInfo': (1829768651, 382852449, '909332fa1c5cc80266068abd8b355c2686bea09ca3f0b8f3f1619c66f3a587c2'),
}
@lru_cache(maxsize=len(TABLES))
def schema(dbd, table):
fields = spells.raw_schema(dbd, table, metadata=TABLES[table])
if spells.canonical_sha256(fields) != TABLES[table][2]:
raise ValueError('Reviewed catalogue layout changed: ' + table)
return fields
def empty_record(fields, ident):
row = {'ID': ident}
for name, kind, _, _, count in fields:
if name == 'ID':
continue
value = '' if kind in ('string', 'locstring') else 0
row[name] = [value] * count if count > 1 else value
return row
def signed32(value):
if not -(1 << 31) <= value < (1 << 32):
raise ValueError('Source 32-bit mask bound')
return value - (1 << 32) if value >= 1 << 31 else value
def race_masks(value):
if not 0 <= value < 1 << 64:
raise ValueError('Source 64-bit race mask bound')
return [signed32(value & 0xffffffff), signed32(value >> 32)]
def source_predecessors(source_rows):
"""Source column8 names the next rank; native SupercedesSpell is previous.
This reuses the established class_spell_compat.skill_line_rows contract,
including links whose preceding row is outside the added-row subset.
"""
result = {}
for row in source_rows:
if row[8]:
key = (row[1], row[8])
if key in result and result[key] != row[2]:
raise ValueError('Ambiguous Source skill predecessor')
result[key] = row[2]
return result
def validate_gameobject_geometry(box):
"""The six native floats are minimum XYZ followed by maximum XYZ.
No model-size heuristic belongs here: a large, ordered finite box is not
proof of malformed geometry. Catalogue-specific sentinel audits are separate.
"""
if (not isinstance(box, (list, tuple)) or len(box) != 6 or
any(type(v) not in (int, float) or
abs(v) > float.fromhex('0x1.fffffep+127') or not math.isfinite(v) for v in box)):
raise ValueError('GameObject GeoBox requires six finite native floats')
if any(box[axis] > box[axis + 3] for axis in range(3)):
raise ValueError('GameObject GeoBox minimum exceeds maximum')
def _catalogue_records(records, label, key_field):
"""Copy active named records with explicit positive identity fields."""
result = {}
values = records.values() if isinstance(records, Mapping) else records
for record in values:
if (not isinstance(record, Mapping) or
any(type(record.get(field)) is not int or
not 0 < record[field] <= 0xffffffff for field in ('ID', key_field))):
raise ValueError(label + ' requires positive ID and ' + key_field)
row = deepcopy(dict(record))
if row['ID'] in result and result[row['ID']] != row:
raise ValueError(label + ' ID has conflicting records')
result[row['ID']] = row
return result
def _qualify_unique_records(records, *, native_records, existing_records, key_field, kind):
"""Only named, separately qualified table indexes may call this helper."""
native = _catalogue_records(native_records, 'Native ' + kind, key_field)
existing = _catalogue_records(existing_records, 'Existing ' + kind, key_field)
context = {**native, **existing}
context_by_key = {}
for row in context.values():
value = row[key_field]
if value in context_by_key:
raise ValueError('Existing effective ' + kind + ' ' + key_field + ' is not unique')
context_by_key[value] = row
proposed = _catalogue_records(records, 'Source ' + kind, key_field)
accepted, held, aliases, groups = [], [], [], {}
def normalized(row):
return {k: v for k, v in row.items() if k != 'ID'}
def hold(row, reason, conflicts):
held.append(dict(id=row['ID'], **{key_field: row[key_field]}, reason=reason,
source_record=deepcopy(row), conflicting_records=deepcopy(conflicts)))
for ident, row in sorted(proposed.items()):
if ident in context and row != context[ident]:
hold(row, kind + '-id-conflicts-with-effective-catalogue', [context[ident]])
else:
groups.setdefault(row[key_field], []).append(row)
for value, candidates in sorted(groups.items()):
prior = context_by_key.get(value)
if prior is not None:
for row in candidates:
if row == prior:
accepted.append(row) # An identical same-ID overlay is harmless.
elif normalized(row) == normalized(prior):
aliases.append(dict(id=row['ID'], canonical_id=prior['ID'],
**{key_field: value}, reason='identical-effective-' + kind))
else:
prefix = 'creature-id' if key_field == 'CreatureID' else key_field
hold(row, prefix + '-conflicts-with-effective-catalogue', [prior])
elif all(normalized(row) == normalized(candidates[0]) for row in candidates):
canonical = candidates[0] # proposed was sorted by ID, not input order.
accepted.append(canonical)
for row in candidates[1:]:
aliases.append(dict(id=row['ID'], canonical_id=canonical['ID'],
**{key_field: value}, reason='identical-source-' + kind))
else:
for row in candidates:
noun = 'creature' if key_field == 'CreatureID' else key_field
hold(row, 'non-equivalent-source-' + noun + '-aliases',
[other for other in candidates if other['ID'] != row['ID']])
return dict(records=sorted(accepted, key=lambda row: row['ID']),
held=sorted(held, key=lambda row: row['id']),
aliases=sorted(aliases, key=lambda row: row['id']),
input_records=len(proposed), native_records=len(native),
existing_records=len(existing), effective_context_records=len(context),
effective_context_sha256=spells.canonical_sha256(
sorted(context.values(), key=lambda row: row['ID'])),
effective_context_preserved=True, unique_field=key_field)
def qualify_species_records(records, *, native_records, existing_records=()):
"""Qualify the observed native CreatureID index, preserving protected context.
Complete decoded native/accepted records are explicit inputs. Equivalent
Source-only records retain the lowest ID, independent of input order; all
fields except ID must agree. SummonSpellID is NOT a unique index. Low-level
construction/encoding stays compatible; publication must use this batch gate.
"""
return dict(_qualify_unique_records(records, native_records=native_records,
existing_records=existing_records, key_field='CreatureID', kind='species'),
summon_spell_uniqueness_required=False)
def qualify_mount_records(records, *, native_records, existing_records=()):
"""Qualify Mount.SourceSpellID, not a blanket spell-uniqueness rule.
The actual70334 fatal index, named GetMount(spellId) original consumer and
GetMountFromSpell API jointly qualify this specific table/key relationship.
Zero-key behavior is unqualified; positive keys are required rather than
guessing nullable-zero indexing rules.
"""
return _qualify_unique_records(records, native_records=native_records,
existing_records=existing_records, key_field='SourceSpellID', kind='mount')
def qualify_mount_family(mount_records, display_records, *, native_mount_records,
native_display_records, existing_mount_records=(),
existing_display_records=(), qualified_reparents=()):
"""Qualify parents plus their children without introducing new appearances.
Unchanged child definition/body proofs belong to the caller's existing
catalogue closure and are reused. An aliased parent permits dropping an
exactly equivalent existing canonical child. It does not authorize moving
a different display to that parent. Such a move needs an explicit complete
target record, provenance and canonical record SHA256 in qualified_reparents.
No MountID or CreatureDisplayInfoID uniqueness is assumed: both are many-side
relationships in the original MountXDisplay container.
"""
native = _catalogue_records(native_mount_records, 'Native mount', 'SourceSpellID')
existing = _catalogue_records(existing_mount_records, 'Existing mount', 'SourceSpellID')
parents = qualify_mount_records(mount_records, native_records=native, existing_records=existing)
parent_ids = set(native) | set(existing) | {r['ID'] for r in parents['records']}
held_parents = {r['id'] for r in parents['held']}
parent_aliases = {r['id']: r['canonical_id'] for r in parents['aliases']}
context = {**_catalogue_records(native_display_records, 'Native mount display', 'MountID'),
**_catalogue_records(existing_display_records, 'Existing mount display', 'MountID')}
proposed = _catalogue_records(display_records, 'Source mount display', 'MountID')
accepted, held, aliases, rewritten = [], [], [], []
authority = {a['record']['ID']: a for a in qualified_reparents}
def body(row):
return spells.canonical_sha256({k: v for k, v in row.items() if k != 'ID'})
equivalent = {}
for row in sorted(context.values(), key=lambda r: r['ID']):
equivalent.setdefault(body(row), row['ID'])
def hold(row, reason):
held.append(dict(id=row['ID'], MountID=row['MountID'], reason=reason,
source_record=deepcopy(row)))
# Existing canonical Source children precede alias children regardless of ID.
ordered = sorted(proposed.values(), key=lambda r: (r['MountID'] in parent_aliases, r['ID']))
for row in ordered:
ident, parent = row['ID'], row['MountID']
if parent in held_parents:
hold(row, 'parent-mount-held')
continue
canonical_parent = parent_aliases.get(parent, parent)
if canonical_parent not in parent_ids:
hold(row, 'missing-canonical-mount')
continue
if ident in context and row != context[ident]:
hold(row, 'mount-display-id-conflicts-with-effective-catalogue')
continue
target = dict(row, MountID=canonical_parent)
canonical_child = equivalent.get(body(target))
if canonical_child is not None and canonical_child != ident:
aliases.append(dict(id=ident, canonical_id=canonical_child, MountID=canonical_parent,
reason='identical-canonical-mount-display'))
continue
if target != row:
proof = authority.get(ident, {})
if (proof.get('record') != target or not proof.get('provenance') or
proof.get('sha256') != spells.canonical_sha256(target)):
hold(row, 'aliased-parent-display-body-unqualified')
continue
rewritten.append(dict(id=ident, source_record=deepcopy(row),
record=deepcopy(target), provenance=proof['provenance']))
accepted.append(target)
equivalent.setdefault(body(target), ident)
return dict(mounts=parents, displays=dict(records=sorted(accepted, key=lambda r: r['ID']),
held=sorted(held, key=lambda r: r['id']), aliases=sorted(aliases, key=lambda r: r['id']),
rewritten_records=rewritten, native_records=len(context),
unchanged_child_body_proofs_reused=True, parent_or_display_uniqueness_assumed=False))
def encode_species_rows(records, fields, *, native_records, existing_records=()):
"""Safe batch producer; qualify relationships before low-level wire encoding."""
plan = qualify_species_records(records, native_records=native_records,
existing_records=existing_records)
return dict(plan, rows=[encode_row('BattlePetSpecies', row, fields)
for row in plan['records']])
def source_record(table, spec, fields, native, *, icons, predecessors,
spell_icons, mount_environment=None):
"""Translate one reviewed spec; missing icon proof is an explicit hold.
The named native journal template supplies only the already-reviewed
classic journal defaults. Source IDs/names and summon/icon relationships
replace its identity; no raw packed field arrays are copied.
"""
ident = spec.get('ID', spec.get('id'))
template = spec.get('template_native_id')
row = deepcopy(native[table][template]) if template is not None else empty_record(fields, ident)
row['ID'] = ident
def icon(path):
if not path:
return 0
key = path.replace('\\', '/').lower()
if not key.endswith('.blp'):
key += '.blp'
value = icons.get(key)
if not value:
raise ValueError('Unresolved Source icon: ' + key)
return value
if table == 'SpellCategory':
row.update({k: spec[k] for k in ('Flags', 'UsesPerWeek', 'MaxCharges', 'ChargeRecoveryTime', 'TypeMask')})
row['Name_lang'] = spec['Name']
elif table == 'Talent':
for name in row:
if name in spec:
row[name] = deepcopy(spec[name])
elif table == 'SkillLine':
row.update(DisplayName_lang=spec['DisplayName'], Description_lang=spec['Description'],
SpellIconFileID=icon(spec['icon_path']))
for name in ('CategoryID', 'CanLink', 'ParentSkillLineID', 'ParentTierIndex', 'Flags', 'SpellBookSpellID'):
row[name] = spec[name]
elif table == 'CreatureFamily':
row.update(Name_lang=spec['Name'], IconFileID=icon(spec['icon_path']))
for name in ('MinScale', 'MinScaleLevel', 'MaxScale', 'MaxScaleLevel',
'PetFoodMask', 'PetTalentType', 'CategoryEnumID', 'SkillLine'):
row[name] = deepcopy(spec[name])
elif table == 'SkillRaceClassInfo':
for name in ('SkillID', 'ClassMask', 'Flags', 'MinLevel', 'SkillTierID'):
row[name] = spec[name]
row.update(Availability=1, ClassMask=signed32(spec['ClassMask']), RaceMasks=race_masks(spec['RaceMask']))
elif table == 'SkillLineAbility':
for name in ('SkillLine', 'Spell', 'MinSkillLineRank', 'AcquireMethod',
'TrivialSkillLineRankHigh', 'TrivialSkillLineRankLow'):
row[name] = spec[name]
row.update(ClassMask=signed32(spec['ClassMask']), RaceMasks=race_masks(spec['RaceMask']),
SupercedesSpell=predecessors.get((spec['SkillLine'], spec['Spell']), 0), NumSkillUps=1)
elif table == 'Mount':
row.update(Name_lang=spec['Name'], SourceSpellID=spec['SourceSpellID'])
# A native horse template carries foreign skill/speed requirements.
# Source collection association and mounted prototype must qualify the
# journal environment explicitly; never inherit that template's type.
from source_mount_compat import apply_source_mount_environment
row = apply_source_mount_environment(row, mount_environment)
elif table == 'MountXDisplay':
for name in ('CreatureDisplayInfoID', 'PlayerConditionID', 'MountID'):
row[name] = spec[name]
elif table == 'BattlePetSpecies':
row.update(CreatureID=spec['CreatureID'], SummonSpellID=spec['SummonSpellID'])
path = spell_icons.get(spec['SummonSpellID'])
if path is None:
raise ValueError('Missing Source companion spell/icon relationship')
row['IconFileDataID'] = icon(path)
elif table == 'Toy':
row['ItemID'] = spec['ItemID']
elif table == 'GameObjectDisplayInfo':
# Native ordinary model rows use zero optional effects/overrides. The
# raw WDC f2=589824 storage word is not a 16-bit ObjectEffectPackageID.
record = spec['record']
validate_gameobject_geometry(record['GeoBox'])
row.update(GeoBox=record['GeoBox'], FileDataID=record['FileDataID'])
else:
raise ValueError('Unreviewed catalogue table')
return row
def encode_row(table, record, fields):
"""Low-level named wire codec; Species publication needs its batch gate."""
if table == 'GameObjectDisplayInfo':
validate_gameobject_geometry(record['GeoBox'])
if spells.canonical_sha256(fields) != TABLES[table][2]:
raise ValueError('Catalogue encoder layout differs: ' + table)
wire = spells.codec.encode(record, fields)
# Independent decode also rejects trailing bytes and checks narrow arrays.
decoded = spells.decode(wire, fields, record['ID'])
for name, kind, _, _, _ in fields:
if kind != 'float' and decoded[name] != record[name]:
raise ValueError('Catalogue wire roundtrip changed ' + name)
return dict(table_name=table, table_hash=hex(TABLES[table][0]),
id=record['ID'], record=record, wire_hex=wire.hex(),
sha256=hashlib.sha256(wire).hexdigest(), policy=POLICY)
def talent_removal(baseline, fields, source_ids, source_dbc_sha256):
"""Invalidate a native-only talent relationship with both inventories pinned."""
source_ids = sorted(source_ids)
if (source_dbc_sha256 != TALENT_SOURCE_SHA256
or spells.canonical_sha256(source_ids) != TALENT_INVENTORY_SHA256
or baseline['ID'] in source_ids):
raise ValueError('Unreviewed Source talent inventory/removal')
wire = encode_row('Talent', baseline, fields)
return dict(table_name='Talent', table_hash=hex(TABLES['Talent'][0]), id=baseline['ID'],
record_status='removed', wire_hex='',
sha256=hashlib.sha256(b'').hexdigest(), policy=TALENT_REMOVAL_POLICY,
baseline_record=deepcopy(baseline), baseline_record_sha256=wire['sha256'],
source_talent_ids=source_ids, source_talent_dbc_sha256=source_dbc_sha256,
source_talent_inventory_sha256=TALENT_INVENTORY_SHA256)
def validate_talent_removal(row, fields):
ids = row.get('source_talent_ids')
if (row.get('policy') != TALENT_REMOVAL_POLICY
or row.get('table_name') != 'Talent' or int(row['table_hash'], 16) != TABLES['Talent'][0]
or not isinstance(ids, list) or not ids or any(type(v) is not int or v <= 0 for v in ids)
or ids != sorted(set(ids)) or spells.canonical_sha256(ids) != TALENT_INVENTORY_SHA256
or row.get('source_talent_inventory_sha256') != TALENT_INVENTORY_SHA256
or row.get('source_talent_dbc_sha256') != TALENT_SOURCE_SHA256
or row['id'] in ids or row.get('baseline_record', {}).get('ID') != row['id']
or row.get('record') is not None or row.get('wire_hex') != ''
or row.get('record_status') != 'removed'):
raise ValueError('Unreviewed or unpinned native talent relation removal')
wire = encode_row('Talent', row['baseline_record'], fields)
if row.get('baseline_record_sha256') != wire['sha256']:
raise ValueError('Native talent removal preimage differs')