Files
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

724 lines
38 KiB
Python

#!/usr/bin/env python3
"""Native 70334 Map, MapDifficulty and world-map hotfix row encoding.
REA contract (runtime/continuation-20261110/map-activation/rea.private.json):
the client validates hotfixed Map rows while applying the hotfix cache at
login (Hotfix.log "Table Map RecID N VALIDATION_RESULT_VALID") and reads
Map.WdtFileDataID at "Load Map Begin"; the shared test client requested the
hotfixed Map1 WDT 8560806, never the original 782779. A Map row therefore
activates a converted WDT only when that WDT FDI is resident in the client's
ROOT. Every native Map ID has at least one MapDifficulty row, so a new Map
ID also needs one.
The world-map schemas use the native DB2Metadata layouts and the
DB2StorageBase::WriteRecord serializer; they preserve inline IDs and trailing
relationships. Client application of the UiMap replacements still requires
the separate native acceptance check.
Offline tool only. It never invents a WDT: rows that would reference a WDT
FDI absent from the supplied installed-FDI set are refused.
"""
import argparse
import copy
import hashlib
import json
import math
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'ops'))
import item_sparse_compat as composer # noqa: E402
from octo_client_data import canonical_sha256 # noqa: E402
MAP_TABLE = 0xBD84CD62
MAP_LAYOUT = 0xD43AFAC3
MAP_FIELDS_SHA256 = 'ce173e2281c3218c0068cd975376640c4feeb17c13ee8b69fa6423bf7d7757cb'
# Map.dbd LAYOUT D43AFAC3 (1.60.1.70334); noninline ID omitted from the body.
MAP_SCHEMA = (
('Directory', 'string', 32, False, 1), ('MapName_lang', 'locstring', 32, False, 1),
('MapDescription0_lang', 'locstring', 32, False, 1), ('MapDescription1_lang', 'locstring', 32, False, 1),
('PvpShortDescription_lang', 'locstring', 32, False, 1), ('PvpLongDescription_lang', 'locstring', 32, False, 1),
('Corpse', 'float', 32, False, 2), ('MapType', 'int', 8, True, 1), ('InstanceType', 'int', 8, False, 1),
('ExpansionID', 'int', 8, True, 1), ('AreaTableID', 'int', 16, True, 1), ('LoadingScreenID', 'int', 16, False, 1),
('TimeOfDayOverride', 'int', 16, False, 1), ('ParentMapID', 'int', 16, False, 1),
('CosmeticParentMapID', 'int', 16, False, 1), ('TimeOffset', 'int', 8, True, 1),
('MinimapIconScale', 'float', 32, False, 1), ('CorpseMapID', 'int', 16, False, 1),
('MaxPlayers', 'int', 8, True, 1), ('WindSettingsID', 'int', 16, False, 1),
('ZmpFileDataID', 'int', 32, False, 1), ('WdtFileDataID', 'int', 32, False, 1),
('OceanLiquidTypeID', 'int', 32, False, 1), ('NavigationMaxDistance', 'int', 32, False, 1),
('PreloadFileDataID', 'int', 32, False, 1), ('Flags', 'int', 32, False, 3),
)
MAP_DIFFICULTY_TABLE = 0x9265F70D
MAP_DIFFICULTY_LAYOUT = 0x24A16AD3
# MapDifficulty.dbd LAYOUT 24A16AD3 / DB2Metadata IndexField=1: the inline ID
# and the trailing noninline MapID relation are both part of the hotfix body
# (DB2StorageBase::WriteRecord; same framing as package SpellXSpellVisual).
MAP_DIFFICULTY_SCHEMA = (
('Message_lang', 'locstring', 32, False, 1), ('ID', 'int', 32, True, 1),
('DifficultyID', 'int', 16, False, 1), ('LockID', 'int', 32, False, 1),
('ResetInterval', 'int', 8, True, 1), ('MaxPlayers', 'int', 32, False, 1),
('ItemContext', 'int', 8, True, 1), ('ItemContextPickerID', 'int', 32, False, 1),
('Flags', 'int', 32, False, 1), ('ContentTuningID', 'int', 32, False, 1),
('WorldStateExpressionID', 'int', 32, False, 1), ('MapID', 'int', 32, True, 1),
)
# Native InstanceType -> MapDifficulty.DifficultyID observed in every native
# 70334 vanilla map: common/battleground 0, 5-player instance 1, 40 raid 9.
DEFAULT_DIFFICULTY = {0: 0, 1: 1, 2: 9, 3: 0, 4: 0}
# Native 70334 DB2Metadata / DB2StorageBase::WriteRecord contract. These are
# unpacked hotfix bodies, not WDC5 bitpacked records. UiMap and Assignment
# carry their inline ID; XMapArt omits the noninline ID and includes its
# relationship field (UiMapID) after the two file fields.
UI_MAP_SCHEMA = (
('Name', 'locstring', 32, False, 1), ('ID', 'int', 32, True, 1),
('ParentUiMapID', 'int', 32, False, 1), ('Flags', 'int', 32, False, 1),
('System', 'int', 8, True, 1), ('Type', 'int', 8, True, 1),
('BountySetID', 'int', 32, False, 1), ('BountyDisplayLocation', 'int', 32, True, 1),
('VisibilityPlayerConditionID', 'int', 32, False, 1), ('HelpTextPosition', 'int', 8, False, 1),
('BkgAtlasID', 'int', 32, False, 1), ('AlternateUiMapGroup', 'int', 32, False, 1),
('ContentTuningID', 'int', 32, False, 1), ('AdventureMapTextureKitID', 'int', 32, False, 1),
('MapArtZoneTextPosition', 'int', 8, False, 1),
)
UI_MAP_ASSIGNMENT_SCHEMA = (
('UiMin', 'float', 32, False, 2), ('UiMax', 'float', 32, False, 2),
('Region', 'float', 32, False, 6), ('ID', 'int', 32, True, 1),
('UiMapID', 'int', 32, False, 1), ('OrderIndex', 'int', 32, False, 1),
('MapID', 'int', 32, False, 1), ('AreaID', 'int', 32, False, 1),
('WmoDoodadPlacementID', 'int', 32, False, 1), ('WmoGroupID', 'int', 32, False, 1),
('Unknown1125', 'int', 32, False, 1),
)
UI_MAP_X_MAP_ART_SCHEMA = (
('PhaseID', 'int', 32, False, 1), ('UiMapArtID', 'int', 32, False, 1),
('UiMapID', 'int', 32, False, 1),
)
WORLD_MAP_TABLES = {
'UiMap': (0x89927BF7, 0xDB51D55F, UI_MAP_SCHEMA),
'UiMapAssignment': (0x5153A338, 0xC9CC8DFB, UI_MAP_ASSIGNMENT_SCHEMA),
'UiMapXMapArt': (0xADB3FC8C, 0xEAE7DA2A, UI_MAP_X_MAP_ART_SCHEMA),
}
TAXI_NODES_TABLE = 0x50D91A78
TAXI_NODES_LAYOUT = 0xE7B597F0
# Native70334 TaxiNodes DB2Metadata/LoadInfo and WriteRecord order. ID is
# inline, unlike Map's noninline identity, and the two mount slots are H/A.
TAXI_NODES_SCHEMA = (
('Name', 'locstring', 32, False, 1), ('Pos', 'float', 32, False, 3),
('MapOffset', 'float', 32, False, 2), ('FlightMapOffset', 'float', 32, False, 2),
('ID', 'int', 32, True, 1), ('ContinentID', 'int', 16, True, 1),
('ConditionID', 'int', 32, False, 1), ('CharacterBitNumber', 'int', 16, True, 1),
('Flags', 'int', 32, False, 1), ('UiTextureKitID', 'int', 32, False, 1),
('MinimapAtlasMemberID', 'int', 32, False, 1), ('Facing', 'float', 32, False, 1),
('SpecialIconConditionID', 'int', 32, True, 1),
('VisibilityConditionID', 'int', 32, True, 1),
('MountCreatureID', 'int', 32, False, 2),
)
# Native 70334 AreaTable and WMOAreaTable DB2LoadInfo/DB2Metadata order.
# AreaTable has an external ID; WMOAreaTable serializes its inline ID and
# WmoID relationship. These are unpacked WriteRecord hotfix bodies.
AREA_TABLE_LAYOUT = 0x9995B797
AREA_TABLE_SCHEMA_SHA256 = '91d8231056edfe0d0626d28c458a5e9a371b77cd2cdf7bdc616073afcd086d3e'
AREA_TABLE_SCHEMA = (
('ZoneName', 'string', 32, False, 1), ('AreaName_lang', 'locstring', 32, False, 1),
('ContinentID', 'int', 16, True, 1), ('ParentAreaID', 'int', 16, True, 1),
('AreaBit', 'int', 16, False, 1), ('SoundProviderPref', 'int', 8, True, 1),
('SoundProviderPrefUnderwater', 'int', 8, True, 1), ('AmbienceID', 'int', 16, True, 1),
('UwAmbience', 'int', 16, True, 1), ('ZoneMusic', 'int', 16, True, 1),
('UwZoneMusic', 'int', 16, True, 1), ('ExplorationLevel', 'int', 8, False, 1),
('IntroSound', 'int', 16, True, 1), ('UwIntroSound', 'int', 32, True, 1),
('FactionGroupMask', 'int', 8, True, 1), ('Ambient_multiplier', 'float', 32, False, 1),
('MountFlags', 'int', 32, False, 1), ('PvpCombatWorldStateID', 'int', 32, False, 1),
('WildBattlePetLevelMin', 'int', 8, True, 1), ('WildBattlePetLevelMax', 'int', 8, True, 1),
('WindSettingsID', 'int', 8, True, 1), ('ContentTuningID', 'int', 32, False, 1),
('Flags', 'int', 32, False, 2), ('LiquidTypeID', 'int', 16, True, 4),
)
WMO_AREA_TABLE = 0xC74FBDEB
WMO_AREA_LAYOUT = 0xC5A7B977
WMO_AREA_SCHEMA_SHA256 = '224ab9dea5197323d1d0f1d0d8da36204c27451e18f5c87af30a1507f0fcf9f7'
WMO_AREA_SCHEMA = (
('AreaName_lang', 'locstring', 32, False, 1), ('ID', 'int', 32, False, 1),
('WmoID', 'int', 16, True, 1), ('NameSetID', 'int', 8, True, 1),
('WmoGroupID', 'int', 32, False, 1), ('SoundProviderPref', 'int', 8, True, 1),
('SoundProviderPrefUnderwater', 'int', 8, True, 1), ('AmbienceID', 'int', 16, True, 1),
('UwAmbience', 'int', 16, True, 1), ('ZoneMusic', 'int', 16, True, 1),
('UwZoneMusic', 'int', 32, True, 1), ('IntroSound', 'int', 16, True, 1),
('UwIntroSound', 'int', 16, True, 1), ('AreaTableID', 'int', 16, True, 1),
('Flags', 'int', 32, False, 1),
)
if canonical_sha256([list(f) for f in MAP_SCHEMA]) != MAP_FIELDS_SHA256:
raise RuntimeError('Pinned Map field sequence changed')
if canonical_sha256([list(f) for f in AREA_TABLE_SCHEMA]) != AREA_TABLE_SCHEMA_SHA256:
raise RuntimeError('Pinned AreaTable field sequence changed')
if canonical_sha256([list(f) for f in WMO_AREA_SCHEMA]) != WMO_AREA_SCHEMA_SHA256:
raise RuntimeError('Pinned WMOAreaTable field sequence changed')
def encode(record, schema):
names = {f[0] for f in schema}
extra = set(record) - names - {'ID'}
if extra or names - set(record):
raise ValueError('Complete native row required')
for name, kind, *_ in schema:
values = record[name] if isinstance(record[name], list) else [record[name]]
if kind == 'float' and not all(math.isfinite(v) for v in values):
raise ValueError('Nonfinite native float: ' + name)
return composer.encode(record, schema)
def decode(body, schema, record_id=None):
values = {} if record_id is None else {'ID': record_id}
offset = 0
for name, kind, bits, unsigned, count in schema:
out = []
for _ in range(count):
if kind in ('string', 'locstring'):
end = body.index(b'\0', offset)
out.append(body[offset:end].decode('utf-8'))
offset = end + 1
elif kind == 'float':
out.append(struct.unpack_from('<f', body, offset)[0])
offset += 4
else:
width = bits // 8
if offset + width > len(body):
raise ValueError('Truncated native integer: ' + name)
out.append(int.from_bytes(body[offset:offset + width], 'little', signed=not unsigned))
offset += width
values[name] = out if count > 1 else out[0]
if offset != len(body):
raise ValueError('Unconsumed native body bytes')
return values
def package_row(table_name, table_hash, record_id, record, body, policy):
return {'table_name': table_name, 'table_hash': f'0x{table_hash:08X}', 'id': record_id,
'record_status': 'valid', 'record': record, 'wire_hex': body.hex(),
'sha256': hashlib.sha256(body).hexdigest(), 'policy': policy}
def worldmap_rows(spec, native_ids, art_ids):
"""Encode a complete reviewed UiMap/assignment/art spec for a native ROOT.
``native_ids`` maps each of the three table names to its original IDs;
``art_ids`` is the actual target UiMapArt ID set, including client-only
additions. An explicit replace must name an existing native row. It is
emitted as a valid hotfix with the same outer (table hash, ID), exactly as
the accepted native Map overrides; there is no separate replacement wire
opcode. Whether each new table is applied by the client remains a live
acceptance boundary.
"""
tables = spec.get('tables', {})
if set(tables) != set(WORLD_MAP_TABLES) or set(native_ids) != set(WORLD_MAP_TABLES):
raise ValueError('Complete world-map table spec and native ID sets required')
prepared, seen = [], set()
ui_ids = set(native_ids['UiMap'])
for name, entries in tables.items():
for entry in entries:
ident, op = entry.get('ID'), entry.get('op')
if type(ident) is not int or not 0 < ident <= 0x7fffffff or op not in ('add', 'replace'):
raise ValueError('Explicit world-map identity and add/replace operation required')
key = (name, ident)
if key in seen:
raise ValueError('Duplicate world-map identity')
seen.add(key)
exists = ident in native_ids[name]
if exists != (op == 'replace'):
raise ValueError('World-map add/replace differs from native identity: ' + str(key))
rec = {k: copy.deepcopy(v) for k, v in entry.items() if k != 'op'}
schema = WORLD_MAP_TABLES[name][2]
# Integer coercion would hide a malformed field in the row spec.
for field, kind, _bits, _unsigned, count in schema:
if kind == 'int' and type(rec.get(field)) is not int:
raise ValueError('Native world-map integer required: ' + field)
if name == 'UiMap':
if not isinstance(rec.get('Name'), str) or not rec['Name'].strip():
raise ValueError('World-map name required')
ui_ids.add(ident)
prepared.append((name, op, rec))
rows, audit = [], []
for name, op, rec in prepared:
if name == 'UiMap':
if rec['ParentUiMapID'] and rec['ParentUiMapID'] not in ui_ids:
raise ValueError('Undefined parent UiMap')
elif rec['UiMapID'] not in ui_ids:
raise ValueError('Undefined linked UiMap')
if name == 'UiMapXMapArt':
# The client-only overlay relation is 12-bit unsigned and the
# native XMapArt file field is 13-bit signed. Keep one usable ID
# namespace across the file and hotfix sides of this chain.
if not 0 < rec['UiMapArtID'] <= 4095:
raise ValueError('UiMapArt ID exceeds native compact reference bound')
if rec['UiMapArtID'] not in art_ids:
raise ValueError('Undefined target UiMapArt')
table, _layout, schema = WORLD_MAP_TABLES[name]
body = encode(rec, schema)
if name == 'UiMapAssignment':
if any(rec['UiMin'][i] >= rec['UiMax'][i] for i in range(2)) or \
any(rec['Region'][i] >= rec['Region'][i + 3] for i in range(3)):
raise ValueError('Unordered world-map assignment bounds')
row = package_row(name, table, rec['ID'], rec, body, 'source-worldmap-' + op + '-v1')
rows.append(row)
audit.append({'table': name, 'ID': rec['ID'], 'op': op, 'bytes': len(body),
'sha256': row['sha256']})
return rows, audit
def taxi_nodes_rows(entries, native_ids, supported_ids):
"""Encode reviewed Source node identities with explicit add/replace.
Node definitions extend the client graph; the source discovery mask is
still filtered separately and never grants discovery. Native table
admission and route display remain a distinct runtime acceptance.
"""
native_ids, supported_ids = set(native_ids), set(supported_ids)
if not supported_ids or any(type(i) is not int or not 1 <= i <= 256 for i in supported_ids):
raise ValueError('Bounded supported taxi identities required')
rows, audit, seen = [], [], set()
for entry in entries:
ident, op = entry.get('ID'), entry.get('op')
if type(ident) is not int or ident not in supported_ids or op not in ('add', 'replace'):
raise ValueError('Explicit supported taxi identity and operation required')
if ident in seen or (ident in native_ids) != (op == 'replace'):
raise ValueError('Taxi-node duplicate or native add/replace identity differs')
seen.add(ident)
rec = {k: copy.deepcopy(v) for k, v in entry.items() if k not in ('op', 'native_was')}
for field, kind, _bits, _unsigned, count in TAXI_NODES_SCHEMA:
values = rec.get(field)
values = values if count > 1 else [values]
if not isinstance(values, list) or len(values) != count or any(
type(v) is not int if kind == 'int' else
type(v) not in (int, float) if kind == 'float' else
not isinstance(v, str) for v in values):
raise ValueError('Complete native taxi field required: ' + field)
if not rec['Name'].strip() or '\0' in rec['Name']:
raise ValueError('Taxi-node name required')
if rec['ContinentID'] not in (0, 1) or rec['CharacterBitNumber'] != ident:
raise ValueError('Taxi node must preserve reviewed continent/character-bit identity')
horde, alliance = rec['MountCreatureID']
flags = 0x400 if rec['Pos'] == [0, 0, 0] else 0x400 | bool(alliance) | (bool(horde) << 1)
if horde < 0 or alliance < 0 or rec['Flags'] != flags:
raise ValueError('Taxi-node faction/mount contract differs')
body = encode(rec, TAXI_NODES_SCHEMA)
if encode(decode(body, TAXI_NODES_SCHEMA), TAXI_NODES_SCHEMA) != body:
raise ValueError('Taxi-node wire round trip differs')
row = package_row('TaxiNodes', TAXI_NODES_TABLE, ident, rec, body, 'source-taxi-node-' + op + '-v1')
rows.append(row)
audit.append({'table': 'TaxiNodes', 'ID': ident, 'op': op,
'bytes': len(body), 'sha256': row['sha256']})
if not supported_ids <= native_ids | seen:
raise ValueError('Supported taxi node lacks a native or encoded definition')
return rows, audit
def require_installed(fdi, installed):
if type(fdi) is not int or fdi <= 0:
raise ValueError('WDT FileDataID required; none is invented')
if installed is not None and fdi not in installed:
raise ValueError(f'WDT FileDataID {fdi} is not resident in the target client ROOT')
def wdt_override_row(native_record, wdt_fdi, installed=None):
"""Original native Map record with only WdtFileDataID replaced."""
require_installed(wdt_fdi, installed)
record = copy.deepcopy(native_record)
record['WdtFileDataID'] = wdt_fdi
body = encode(record, MAP_SCHEMA)
original = encode(native_record, MAP_SCHEMA)
changed = sum(a != b for a, b in zip(body, original))
if len(body) != len(original) or changed > 4:
raise ValueError('WDT override changed more than the pointer field')
return package_row('Map', MAP_TABLE, record['ID'], record, body, 'native-map-wdt-pointer-v1')
def source_only_map_row(template, source, wdt_fdi, installed=None):
"""New Map ID from Octo Map.dbc values on a native same-kind template.
`source` keys: ID, Directory, MapName_lang, InstanceType, AreaTableID,
LoadingScreenID, MaxPlayers, optional CorpseMapID/Corpse.
"""
require_installed(wdt_fdi, installed)
if source['InstanceType'] != template['InstanceType']:
raise ValueError('Template instance kind differs from source')
record = copy.deepcopy(template)
for key in ('ID', 'Directory', 'MapName_lang', 'InstanceType', 'AreaTableID',
'LoadingScreenID', 'MaxPlayers'):
record[key] = source[key]
record['CorpseMapID'] = source.get('CorpseMapID', -1)
record['Corpse'] = list(source.get('Corpse', [0.0, 0.0]))
for key in ('MapDescription0_lang', 'MapDescription1_lang', 'PvpShortDescription_lang',
'PvpLongDescription_lang'):
record[key] = ''
record.update(ZmpFileDataID=0, PreloadFileDataID=0, WdtFileDataID=wdt_fdi, ParentMapID=-1,
CosmeticParentMapID=-1)
return package_row('Map', MAP_TABLE, record['ID'], record, encode(record, MAP_SCHEMA),
'source-only-map-row-v1')
def map_difficulty_row(record_id, map_id, instance_type, max_players, message=''):
record = {'ID': record_id, 'Message_lang': message, 'DifficultyID': DEFAULT_DIFFICULTY[instance_type],
'LockID': 0, 'ResetInterval': 0, 'MaxPlayers': max_players, 'ItemContext': 0,
'ItemContextPickerID': 0, 'Flags': 0, 'ContentTuningID': 0,
'WorldStateExpressionID': 0, 'MapID': map_id}
return package_row('MapDifficulty', MAP_DIFFICULTY_TABLE, record_id, record,
encode(record, MAP_DIFFICULTY_SCHEMA), 'source-only-map-difficulty-v1')
def merge_rows(package, rows, replace=False):
"""Append/replace rows, then recompute push_id and pages once."""
key = lambda r: (int(r['table_hash'], 16), r['id'])
index = {key(r): n for n, r in enumerate(package['rows'])}
merged = list(package['rows'])
replaced = []
for row in rows:
k = key(row)
if k in index:
if not replace:
raise ValueError(f'Duplicate package identity {k}')
replaced.append(k)
merged[index[k]] = row
else:
index[k] = len(merged)
merged.append(row)
wire_baseline = composer.load_working_wire_baseline(package)
push_id, header, pages = composer._package_data(merged, wire_baseline=wire_baseline)
out = dict(package)
out.update(rows=merged, push_id=push_id, pushes=pages)
return out, header, replaced
def source_map_dbc(raw):
"""Octo/Turtle 1.12 Map.dbc rows (42 fields) keyed by ID.
Columns used: 0 ID, 1 Directory, 2 InstanceType, 4 MapName enUS,
15 MaxPlayers, 19 AreaTableID, 38 LoadingScreenID.
"""
magic, count, fields, size, strings = struct.unpack_from('<4s4I', raw)
if magic != b'WDBC' or fields != 42 or size != 168:
raise ValueError('Source 1.12 Map.dbc layout required')
table = raw[20 + count * size:]
text = lambda at: table[at:table.index(b'\0', at)].decode('utf-8')
out = {}
for n in range(count):
r = struct.unpack_from('<42I', raw, 20 + n * size)
out[r[0]] = {'ID': r[0], 'Directory': text(r[1]), 'InstanceType': r[2],
'MapName_lang': text(r[4]), 'MaxPlayers': r[15],
'AreaTableID': r[19], 'LoadingScreenID': r[38]}
return out
AREA_TABLE = 0x7253EB43
AREA_POLICY = 'owned-outdoor-area-original-native-profile-exploration-unprojected-v1'
def source_area_hotfix_rows(spec, native_records):
"""Encode the reviewed Source area additions and AreaBit-only native fixes.
Source audio fields in ``adds`` are already native ancestor values selected
by the bounded area census. Replacements retain every other native field.
"""
if set(spec) != {'source', 'contract', 'field_order', 'adds', 'bit_fixes',
'bit_clash_with_native_only_areas'}:
raise ValueError('Reviewed Source area spec required')
schema_names = [field[0] for field in AREA_TABLE_SCHEMA]
expected = [name if name not in ('AreaName_lang', 'Ambient_multiplier')
else ('AreaName' if name == 'AreaName_lang' else 'AmbientMultiplier')
for name in schema_names]
if spec['field_order'] != expected:
raise ValueError('Source area fields differ from native serialization order')
rows, audit, seen = [], [], set()
for entry in [*spec['adds'], *spec['bit_fixes']]:
ident, op = entry.get('ID'), entry.get('op')
if type(ident) is not int or not 0 < ident <= 0x7fffffff or ident in seen:
raise ValueError('Duplicate or invalid Source area identity')
seen.add(ident)
if op == 'add':
if ident in native_records or set(entry) != set(expected) | {'op', 'ID', 'template_native_area'}:
raise ValueError('Area add collides with native row or has incomplete fields')
if entry['template_native_area'] not in native_records:
raise ValueError('Source area native template absent')
record = {name: copy.deepcopy(entry[src]) for name, src in zip(schema_names, expected)}
record['ID'] = ident
elif op == 'replace':
if ident not in native_records or set(entry) != {'op', 'ID', 'AreaBit', 'native_AreaBit', 'note'}:
raise ValueError('AreaBit replacement lacks exact native row')
record = copy.deepcopy(native_records[ident])
if record['AreaBit'] != entry['native_AreaBit']:
raise ValueError('AreaBit native preimage differs')
record['AreaBit'] = entry['AreaBit']
else:
raise ValueError('Area operation must be add or replace')
body = encode(record, AREA_TABLE_SCHEMA)
if encode(decode(body, AREA_TABLE_SCHEMA, ident), AREA_TABLE_SCHEMA) != body:
raise ValueError('AreaTable body round trip differs')
if op == 'replace':
old = encode(native_records[ident], AREA_TABLE_SCHEMA)
offset = len(record['ZoneName'].encode()) + len(record['AreaName_lang'].encode()) + 6
if len(body) != len(old) or body[:offset] != old[:offset] or \
body[offset + 2:] != old[offset + 2:]:
raise ValueError('AreaBit-only replacement changed other native bytes')
row = package_row('AreaTable', AREA_TABLE, ident, record, body,
'source-area-' + op + '-v1')
rows.append(row)
audit.append({'ID': ident, 'op': op, 'bytes': len(body), 'sha256': row['sha256']})
return rows, audit
def source_wmo_area_dbc(raw):
"""Current Octo WMOAreaTable.dbc: 20 source columns and enUS at index 11."""
if len(raw) < 20:
raise ValueError('Truncated Source WMOAreaTable DBC')
magic, count, fields, size, strings = struct.unpack_from('<4s4I', raw)
if magic != b'WDBC' or fields != 20 or size != 80 or count > 100000 or \
len(raw) != 20 + count * size + strings:
raise ValueError('Source WMOAreaTable DBC layout differs')
table = raw[20 + count * size:]
out = {}
for n in range(count):
row = struct.unpack_from('<20I', raw, 20 + n * size)
offset = row[11]
if row[0] in out or offset >= len(table):
raise ValueError('Duplicate WMO area row or invalid name offset')
end = table.find(b'\0', offset)
if end < 0:
raise ValueError('Unterminated Source WMO area name')
out[row[0]] = (list(row), table[offset:end].decode('utf-8'))
return out
def source_wmo_area_copy_rows(spec, source_dbc, native_ids, area_ids,
first_id=200000):
"""Copy Source WMO identity, name and area onto fresh native hotfix IDs.
Source sound IDs have no reviewed native mapping, and some use -1 where
native fields are unsigned 8/16-bit. Zero means no audio override; this
keeps the new room's name/area relationship without guessing sounds.
"""
classes = spec.get('classes')
if classes not in (['C', 'D'], ['A', 'B']):
raise ValueError('Reviewed WMOID copy classes required')
contract = (spec.get('chained_on'), tuple(classes))
wmoid_ranges = {('-mapsZ48G', ('C', 'D')): (40000, 40073),
('-mapsZ49D', ('A', 'B')): (40000, 40148)}
if contract not in wmoid_ranges:
raise ValueError('Reviewed chained WMOID copy spec required')
first_wmoid, last_wmoid = wmoid_ranges[contract]
if 'wmoid_block' in spec and spec['wmoid_block'] != [first_wmoid, last_wmoid]:
raise ValueError('WMOID copy block differs from reviewed contract')
if spec.get('source_wmoareatable', {}).get('fields') != 20:
raise ValueError('Source WMOAreaTable width differs')
source = source_wmo_area_dbc(source_dbc)
native_ids, area_ids = set(native_ids), set(area_ids)
if first_id <= max(native_ids, default=0) or first_id + len(spec['wmoareatable_copy']) > 0xffffffff:
raise ValueError('Fresh WMOAreaTable ID range not free')
rows, audit, seen = [], [], set()
for index, entry in enumerate(sorted(spec['wmoareatable_copy'],
key=lambda e: (e['new_wmoid'], e['source_row'][0]))):
original = entry['source_row']
if len(original) != 20 or entry['old_wmoid'] != original[1] or \
not first_wmoid <= entry['new_wmoid'] <= last_wmoid or \
source.get(original[0], (None,))[0] != original:
raise ValueError('WMO source row or fresh root WMOID differs')
key = (entry['new_wmoid'], original[0])
if key in seen:
raise ValueError('Duplicate copied WMO row')
seen.add(key)
group = original[3] if original[3] < 0x80000000 else original[3] - 0x100000000
flags = original[9] if original[9] < 0x80000000 else original[9] - 0x100000000
ident = first_id + index
record = {'ID': ident, 'AreaName_lang': source[original[0]][1],
'WmoID': entry['new_wmoid'], 'NameSetID': original[2],
'WmoGroupID': group, 'AreaTableID': original[10], 'Flags': flags,
'SoundProviderPref': 0, 'SoundProviderPrefUnderwater': 0,
'AmbienceID': 0, 'UwAmbience': 0, 'ZoneMusic': 0,
'UwZoneMusic': 0, 'IntroSound': 0, 'UwIntroSound': 0}
if record['AreaTableID'] not in area_ids | {0}:
raise ValueError('WMO room has unresolved AreaTable identity')
body = encode(record, WMO_AREA_SCHEMA)
if encode(decode(body, WMO_AREA_SCHEMA), WMO_AREA_SCHEMA) != body:
raise ValueError('WMOAreaTable body round trip differs')
row = package_row('WMOAreaTable', WMO_AREA_TABLE, ident, record, body,
'source-wmo-room-name-area-neutral-audio-v1')
rows.append(row)
audit.append({'ID': ident, 'old_source_ID': original[0],
'new_wmoid': entry['new_wmoid'], 'bytes': len(body),
'sha256': row['sha256']})
return rows, audit
def source_area_dbc(raw):
"""Octo/Turtle 1.12 AreaTable.dbc (25 fields) as the Source fragments the
owned outdoor Area profile builder consumes, keyed by ID."""
magic, count, fields, size, strings = struct.unpack_from('<4s4I', raw)
if magic != b'WDBC' or fields != 25 or size != 100:
raise ValueError('Source 1.12 AreaTable.dbc layout required')
table = raw[20 + count * size:]
text = lambda at: table[at:table.index(b'\0', at)].decode('utf-8')
out = {}
for n in range(count):
r = struct.unpack_from('<25I', raw, 20 + n * size)
names = [text(x) for x in r[11:19]]
out[r[0]] = {'ID': r[0], 'ContinentID': r[1], 'ParentAreaID': r[2], 'AreaBit': r[3],
'Flags_raw': r[4], 'SoundProviderPref': r[5], 'SoundProviderPrefUnderwater': r[6],
'AmbienceID': r[7], 'ZoneMusic': r[8], 'IntroSound': r[9],
'ExplorationLevel': r[10], 'AreaName_locales': names,
'AreaName_localeFlags': r[19], 'FactionGroupMask': r[20],
'LiquidTypeID': list(r[21:25]), 'AreaName_lang': names[0]}
return out
def owned_map_area_rows(source_areas, area_ids, native_profiles, schema, map_ids):
"""AreaTable rows for Source-only map areas absent from native.
Uses the owned outdoor-Area profile builder (whole observed native records,
exploration unprojected) with the Source ID as the owned native ID. Only
areas whose Source ContinentID is one of the composed `map_ids` and whose
parent is 0 or already defined are authored; everything else is held.
"""
import map_asset_preflight as maps
import spell_passive_compat as area_encoder
rows, held = [], []
names = {r['ZoneName'] for r in native_profiles.values()}
for ident in sorted(area_ids):
if ident in native_profiles:
continue
source = source_areas.get(ident)
if source is None:
held.append({'AreaID': ident, 'reason': 'no Source AreaTable row'})
continue
parent = source['ParentAreaID']
if source['ContinentID'] not in map_ids:
held.append({'AreaID': ident, 'reason': 'Source map is not a composed Source-only map'})
continue
if parent and parent not in native_profiles and parent not in area_ids:
held.append({'AreaID': ident, 'reason': 'parent area undefined'})
continue
token = 'WoWHybridArea_' + str(ident)
if token in names:
raise ValueError('Owned ZoneName collides with native')
record, audit = maps.area_native_landscape_profile_candidate(
source, native_profiles, native_id=ident, map_id=source['ContinentID'],
parent_area_id=parent, zone_name=token, behavior_policy=AREA_POLICY)
body = area_encoder.encode(record, schema, table='AreaTable')
row = package_row('AreaTable', AREA_TABLE, ident, record, body, 'source-only-map-area-v1')
row['profile_audit'] = audit
rows.append(row)
return rows, held
def with_area_table_id(row, area_id):
"""Map row re-encoded with only AreaTableID changed."""
record = copy.deepcopy(row['record'])
record['AreaTableID'] = area_id
return package_row('Map', MAP_TABLE, record['ID'], record, encode(record, MAP_SCHEMA),
row.get('policy', 'source-only-map-row-v1'))
def source_only_rows(source, template, wdt_fdi, difficulty_id, installed=None,
known_areas=(), known_loading_screens=()):
"""Map + MapDifficulty rows for a Source-only map ID (no native row)."""
values = dict(source)
if values['AreaTableID'] not in known_areas:
values['AreaTableID'] = 0
if values['LoadingScreenID'] not in known_loading_screens:
values['LoadingScreenID'] = template['LoadingScreenID']
if not values['MaxPlayers']:
values['MaxPlayers'] = template['MaxPlayers']
row = source_only_map_row(template, values, wdt_fdi, installed)
diff = map_difficulty_row(difficulty_id, source['ID'], source['InstanceType'], values['MaxPlayers'])
return row, diff
def audit_map_rows(rows, installed, native_by_id):
"""Map rows whose WdtFileDataID differs from native and is not resident."""
result = []
for row in rows:
if int(row['table_hash'], 16) != MAP_TABLE:
continue
body = bytes.fromhex(row['wire_hex'])
wdt = decode(body, MAP_SCHEMA, row['id'])['WdtFileDataID']
native = native_by_id.get(row['id'], {}).get('WdtFileDataID')
result.append({'MapID': row['id'], 'native_wdt': native, 'wdt': wdt,
'resident': wdt == native or wdt in installed})
return result
def main():
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument('--package', type=Path, required=True)
p.add_argument('--native-map', type=Path, required=True, help='native70334 Map full JSON export')
p.add_argument('--installed-fdis', type=Path, required=True,
help='JSON with custom_fdis_ge_8500000 of the target client ROOT')
p.add_argument('--wdt', action='append', default=[], metavar='MAPID=FDI')
p.add_argument('--source-map', action='append', default=[], metavar='MAPID=FDI',
help='Source-only map ID with a composed WDT FDI (needs --source-dbc)')
p.add_argument('--source-dbc', type=Path, help='Octo effective Map.dbc')
p.add_argument('--native-difficulty', type=Path, help='native70334 MapDifficulty JSON (ID allocation floor)')
p.add_argument('--template', action='append', default=['1=33', '2=409'], metavar='INSTANCETYPE=MAPID')
p.add_argument('--output', type=Path, required=True)
p.add_argument('--report', type=Path, required=True)
a = p.parse_args()
native = {r['ID']: r for r in json.loads(a.native_map.read_text())}
installed = {int(x) for x in json.loads(a.installed_fdis.read_text())['custom_fdis_ge_8500000']}
package = json.loads(a.package.read_text())
rows, held = [], []
for item in a.wdt:
map_id, fdi = (int(x) for x in item.split('='))
if map_id not in native:
held.append({'MapID': map_id, 'reason': 'no native Map row; source-only constructor needs explicit inputs'})
continue
try:
rows.append(wdt_override_row(native[map_id], fdi, installed))
except ValueError as error:
held.append({'MapID': map_id, 'wdt': fdi, 'reason': str(error)})
if a.source_map:
dbc = source_map_dbc(a.source_dbc.read_bytes())
templates = {int(k): native[int(v)] for k, v in (t.split('=') for t in a.template)}
floor = max(r['ID'] for r in json.loads(a.native_difficulty.read_text()))
floor = max([floor] + [r['id'] for r in package['rows'] if int(r['table_hash'], 16) == MAP_DIFFICULTY_TABLE])
areas = {r['id'] for r in package['rows'] if r['table_name'] == 'AreaTable'}
screens = {r['id'] for r in package['rows'] if r['table_name'] == 'LoadingScreens'}
for n, item in enumerate(a.source_map, 1):
map_id, fdi = (int(x) for x in item.split('='))
if map_id in native or map_id not in dbc:
held.append({'MapID': map_id, 'reason': 'native row exists or no Source Map.dbc row'})
continue
try:
row, diff = source_only_rows(dbc[map_id], templates[dbc[map_id]['InstanceType']], fdi,
floor + n, installed, areas, screens)
except (KeyError, ValueError) as error:
held.append({'MapID': map_id, 'wdt': fdi, 'reason': str(error)})
continue
rows += [row, diff]
native[map_id] = {'WdtFileDataID': None}
candidate, _, replaced = merge_rows(package, rows)
for row in rows: # offline decode check of every new body (floats via f32)
if int(row['table_hash'], 16) == MAP_DIFFICULTY_TABLE:
decoded = decode(bytes.fromhex(row['wire_hex']), MAP_DIFFICULTY_SCHEMA)
if encode(decoded, MAP_DIFFICULTY_SCHEMA) != bytes.fromhex(row['wire_hex']):
raise ValueError('Decoded MapDifficulty body differs')
continue
decoded = decode(bytes.fromhex(row['wire_hex']), MAP_SCHEMA, row['id'])
if encode(decoded, MAP_SCHEMA) != bytes.fromhex(row['wire_hex']) or \
decoded['WdtFileDataID'] != row['record']['WdtFileDataID']:
raise ValueError('Decoded Map body differs')
a.output.write_text(json.dumps(candidate, separators=(',', ':')) + '\n')
report = {'input_package_sha256': hashlib.sha256(a.package.read_bytes()).hexdigest(),
'output_package_sha256': hashlib.sha256(a.output.read_bytes()).hexdigest(),
'rows': len(candidate['rows']), 'push_id': candidate['push_id'], 'pages': len(candidate['pushes']),
'added': [{'MapID': r['id'], 'wdt': r['record']['WdtFileDataID'],
'native_wdt': native[r['id']]['WdtFileDataID']} for r in rows
if int(r['table_hash'], 16) == MAP_TABLE],
'added_map_difficulty': [{'ID': r['id'], 'MapID': r['record']['MapID'],
'DifficultyID': r['record']['DifficultyID']} for r in rows
if int(r['table_hash'], 16) == MAP_DIFFICULTY_TABLE],
'replaced': replaced, 'held': held,
'package_map_audit': audit_map_rows(candidate['rows'], installed, native)}
a.report.write_text(json.dumps(report, indent=2) + '\n')
print(f"{len(rows)} rows added, {len(held)} held; push {candidate['push_id']}")
if __name__ == '__main__':
main()