367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1182 lines
84 KiB
Python
1182 lines
84 KiB
Python
#!/usr/bin/env python3
|
|
"""Offline, source-backed passive spell component for the pinned 70334 client.
|
|
|
|
This first policy requires positive same-spell native definitions. It supports
|
|
only constant, unconditional self APPLY_AURA skill/reputation bonuses. It never
|
|
installs content, grants spells, changes server rules or claims engine acceptance.
|
|
"""
|
|
import argparse
|
|
from copy import deepcopy
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import re
|
|
import struct
|
|
|
|
from item_icon_preflight import normalize_icon
|
|
from octo_client_data import canonical_sha256
|
|
from spell_content_compare import _observed_context, reviewed_columns, read_input
|
|
from turtle_data import DBC, spell_layout
|
|
from item_batch_stage import available_index
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
BUILD = '1.60.1.70334'
|
|
SCHEMA = 'wowstatic_camelot_1_60_1'
|
|
# Reviewed DBD layout, and canonical hash of the serialized field sequence.
|
|
TABLES = {
|
|
'Spell': (0xe111669e, 0xe3d134fb, '9d3296ad5f44364e1e01de63f5e88f0a8e41f892c414e916d5175fd263249ca0'),
|
|
'SpellName': (0x46c66698, 0x782ee721, 'c6e4541fcac84bcc59be8e8f67825008f1d595730d02351c0d400bf1bce378bf'),
|
|
'SpellMisc': (0xc603ee28, 0x434b3607, 'a86dc2bf5c536dcbf41455f1bbb02b1788f449628e59333af544b123fd4f54d2'),
|
|
'SpellEffect': (0xf04238a5, 0x5362e3d4, '8e9ecaaa72ba615698d19c940c4d5d2e7c96d0df60eb5b282444fd0fdbe87468'),
|
|
'SpellEquippedItems': (0xe44abbd4, 0xd9177916, 'f12a9089fd6cd175e042064f3177bba256b8f87c56c0450f4314d08d72e6c9fa'),
|
|
'SkillLineAbility': (0xff4446f6, 0x224f7ea0, 'd66e6b0eb5a030752f757cbf67dd05f6bae1946118f63695e2136634a137dace'),
|
|
}
|
|
# Additional reviewed component layouts for the crafting/proc dependency batch.
|
|
# Keep these separate from TABLES: existing passive policies must not acquire
|
|
# new semantics merely because the shared encoder understands their wire form.
|
|
SUPPLEMENTAL_TABLES = {
|
|
# Original70334 neutral category38; new Concussion grouping constructor.
|
|
'SpellCategory': (0xd0c3d18e, 0xb79b78e1, '7993ebdc6b4766b88163ebf24e141cdef4ecaf2c5c4de336b1b891ba58b0e68f'),
|
|
# Original 70334 map/area row encoding only. Registration does not grant
|
|
# source-row constructor defaults, preworld activation or publication.
|
|
'Map': (0xBD84CD62, 0xD43AFAC3, 'ce173e2281c3218c0068cd975376640c4feeb17c13ee8b69fa6423bf7d7757cb'),
|
|
'AreaTable': (0x7253EB43, 0x9995B797, '91d8231056edfe0d0626d28c458a5e9a371b77cd2cdf7bdc616073afcd086d3e'),
|
|
# Original static-trigger wire form only; no Source ID/action/listener admission.
|
|
'AreaTrigger': (0x1A5081E1, 0xB97D2FC5, '20f87db72436446fa18c3745d7f6fa9a36f9d4b6678db40857c901e08e2d29e5'),
|
|
# Complete original70334 Flags-only row; owned primitive-volume references
|
|
# and runtime/static-listener activation require their separate proof.
|
|
'AreaTriggerActionSet': (0x5C4BBB1F, 0x6D5EB3BD, '378b71a2adb1756e492d348b7dc44e15281584cc2c42bdc20d22617f09aaba1f'),
|
|
# Original loading-screen wire form; source profile/resource admission is separate.
|
|
'LoadingScreens': (0xEF9DC6FF, 0xF6E51D7F, '9e1c8c47888c5a9140b05accbac0afd523d47aa303000507b970fdf73fc3282d'),
|
|
'CreatureDisplayInfo': (0xbfdaf9f1, 0x7275f5f6, '5a962093c6d95f05c87721c9b38cac478adede5585c11fe90d3e8151735dc49c'),
|
|
'SpellItemEnchantment': (0xe05ac589, 0x952b72b2, 'e50d622dadf5cb90b6846e143ede51e623e2f9fa6fe1b56c40f4dac2da279015'),
|
|
'SpellReagents': (0xab66c99f, 0xff40d202, '0ac5279b7d8470fb2494f325daa56bdf4d472e4b6c6a6cedf90ae4bd51e04bb9'),
|
|
'SpellTotems': (0xa50f8a31, 0x03b23619, '1e22570da1a1287a1bc6eb3aee9a712d622ec599aa725cc6daf68d29ba3c59b8'),
|
|
'SpellCastingRequirements': (0x61025756, 0x02074290, 'cfcfce2fe8b888a0f5ab9c8a7e9827bd5437a29957b700983e2d7b7159322394'),
|
|
'SpellInterrupts': (0x668fae03, 0x6ffc0306, '06604b309f2352172afa783e6150f8a908ef040916780dba3fcf1131c409aa95'),
|
|
'SpellLevels': (0x1ddec5e6, 0x7eb86fdc, '4a4764154cad0f0625d68d6f905e41c819b2daa76122fdc7f8e21a0359892222'),
|
|
'SpellAuraOptions': (0xf42fc065, 0x95f4d5e1, '260166ce8b63ac1d31b50823739988170e68cd296b380db2a84d85f4c98f8d70'),
|
|
'SpellClassOptions': (0x288eab81, 0x1f8e4fd7, 'fee2a0a1be5c8cf6d707d54f7595642d31b7a59b8edf36f0ccade68654a0a8c8'),
|
|
'SpellCategories': (0xdbe7f829, 0x679ef94c, '10773126db4887b8e5dc7ad1cfe191cc558f2df93d42f9bf67a1278aa154e86e'),
|
|
'SpellXSpellVisual': (0x27b7a01a, 0x7994a890, 'e7a8eb69c9d99d7670b7de54f13208c72977ccc9326a636baff49d23d862f194'),
|
|
'SpellVisual': (0xf72496d9, 0x4b85c90f, '037246a68ccbf495bb927a2fadfab18fd4779b69a78af8645375f78f98a16cbe'),
|
|
'SpellVisualEvent': (0xcc284d0f, 0x865f512e, 'b50470cb67a8aafbf9b74426e2fcae1757eb5e46ed5198efd67cc4268a6f92e1'),
|
|
'SpellVisualKit': (0xf483eadb, 0xc069d9c4, '63d6a36526ae21423f2f12701174e1f1dcdd82c741cff3446eae37b16d56dc10'),
|
|
'SpellVisualKitModelAttach': (0xf07194c3, 0x02cf8554, '81c89dcd3ab3e255a27bd42a319c0560c1d91e9c21ae45c326a8f13294ba3dba'),
|
|
'SpellVisualKitEffect': (0x4666ed42, 0xe3206ca2, '14303b87e87462461ccc728b9dc1981e73dd78233c22132a142edd53465c277b'),
|
|
'SoundKit': (0x36237731, 0xa7fb0451, '5c3ea8ea21924e416dfd10b1cad91b2912dc36dc1f73e0aed4880f436714dfc9'),
|
|
'SoundKitEntry': (0xc2b150c7, 0x8f82ff7d, '12fdc44e555226036b0dc4f1498b9f4303cc75b8f79071d81b36dbfc3719ae05'),
|
|
}
|
|
DEPENDENCIES = {
|
|
'SpellCastTimes': (0xfdba5a66, 0x75b6bd3a),
|
|
'SpellDuration': (0xb423fa7a, 0xa931bd2b),
|
|
'SpellRange': (0xe051a69c, 0xada13705),
|
|
}
|
|
EFFECT_COLUMNS = ('effect', 'aura', 'basePoints', 'baseDice', 'dieSides',
|
|
'dicePerLevel', 'realPointsPerLevel', 'miscValue',
|
|
'targetA', 'targetB', 'triggerSpell', 'bonusCoefficient')
|
|
CONDITIONS = ('stances', 'stancesNot', 'targets', 'targetCreatureType', 'requiresSpellFocus',
|
|
'casterAuraState', 'targetAuraState', 'procFlags', 'procCharges', 'procChance',
|
|
'customFlags', 'interruptFlags', 'auraInterruptFlags', 'channelInterruptFlags')
|
|
# Positive rows may add independent restrictions even when the six converted
|
|
# tables look compatible. Missing/empty exports never prove actual absence.
|
|
CHILD_NEUTRAL = {
|
|
'SpellAuraOptions': dict(DifficultyID=0, CumulativeAura=0, ProcCategoryRecovery=0,
|
|
ProcCharges=0, SpellProcsPerMinuteID=0, ProcTypeMask=[0, 0]),
|
|
'SpellAuraRestrictions': dict(DifficultyID=0, CasterAuraState=0, TargetAuraState=0,
|
|
ExcludeCasterAuraState=0, ExcludeTargetAuraState=0, CasterAuraSpell=0,
|
|
TargetAuraSpell=0, ExcludeCasterAuraSpell=0, ExcludeTargetAuraSpell=0),
|
|
'SpellCastingRequirements': dict(FacingCasterFlags=0, MinFactionID=0, MinReputation=0,
|
|
RequiredAreasID=0, RequiredAuraVision=0, RequiresSpellFocus=0),
|
|
'SpellCategories': dict(DifficultyID=0, Category=0, DefenseType=0, DiminishType=0,
|
|
DispelType=0, Mechanic=0, PreventionType=0, StartRecoveryCategory=0, ChargeCategory=0),
|
|
'SpellInterrupts': dict(DifficultyID=0, InterruptFlags=0, AuraInterruptFlags=[0, 0],
|
|
ChannelInterruptFlags=[0, 0]),
|
|
'SpellCooldowns': dict(DifficultyID=0, CategoryRecoveryTime=0, RecoveryTime=0,
|
|
StartRecoveryTime=0, AuraSpellID=0),
|
|
'SpellLevels': dict(DifficultyID=0, MaxLevel=0, MaxPassiveAuraLevel=0, BaseLevel=0, SpellLevel=0),
|
|
'SpellClassOptions': dict(ModalNextSpell=0, SpellClassSet=0, SpellClassMask=[0, 0, 0, 0]),
|
|
}
|
|
CHILD_UNREVIEWED = ('SpellTargetRestrictions', 'SpellShapeshift', 'SpellReagents', 'SpellPower')
|
|
NEW_POLICY = 'new-unconditional-passive-neutral-v1'
|
|
CONSTANT_POLICY = 'positive-constant-self-aura-v1'
|
|
CONSTANT_AURAS = {17: 'stealth-detection', 52: 'weapon-critical-chance',
|
|
57: 'spell-critical-chance', 134: 'casting-mana-regeneration', 137: 'total-stat-percent'}
|
|
NEW_CHILD_TABLES = ('SpellMisc', 'SpellEffect', 'SpellEquippedItems', 'SkillLineAbility')
|
|
# Explicit reviewed scalar candidates, never a copied unrelated spell. The
|
|
# server reference defaults AttributesEx5..16 to0; actual client requirements
|
|
# (including UNKNOWN Attributes15 bit0x2000) remain unverified until tested.
|
|
NEW_MISC_NEUTRAL = dict(Attributes=[80] + [0] * 16, DifficultyID=0,
|
|
CastingTimeIndex=1, DurationIndex=21, PvPDurationIndex=0, RangeIndex=1,
|
|
SchoolMask=1, Speed=0, LaunchDelay=0, MinDuration=0, ActiveIconFileDataID=0,
|
|
ContentTuningID=0, ShowFutureSpellPlayerConditionID=0,
|
|
SpellVisualScript=0, ActiveSpellVisualScript=0)
|
|
NEW_EFFECT_NEUTRAL = dict(Effect=6, DifficultyID=0, EffectAmplitude=0,
|
|
EffectAttributes=0, EffectAuraPeriod=0, EffectBonusCoefficient=0,
|
|
EffectChainAmplitude=1, EffectChainTargets=0, EffectItemType=0,
|
|
EffectMechanic=0, EffectPointsPerResource=0, EffectPos_facing=0,
|
|
EffectRealPointsPerLevel=0, EffectTriggerSpell=0, BonusCoefficientFromAP=0,
|
|
PvpMultiplier=1, Coefficient=0, Variance=0, ResourceCoefficient=0,
|
|
GroupSizeBasePointsCoefficient=1, ScalingClass=0,
|
|
Node__Field_12_0_0_63534_001=0, EffectRadiusIndex=[0, 0],
|
|
EffectSpellClassMask=[0, 0, 0, 0], ImplicitTarget=[1, 0])
|
|
|
|
|
|
def integer(value, low, high, label):
|
|
if type(value) is not int or not low <= value <= high:
|
|
raise ValueError('Integer bound: ' + label)
|
|
return value
|
|
|
|
|
|
def fields(path, table):
|
|
"""Keep inline IDs/relations in the body; omit only a noninline ID.
|
|
|
|
The hotfix body includes noninline relationship values too, as in the
|
|
existing item components. SkillLineAbility's inline ID is not stripped.
|
|
"""
|
|
raw = path.read_bytes()
|
|
text = raw.decode('utf-8')
|
|
kinds = {}
|
|
for line in text.split('LAYOUT', 1)[0].splitlines():
|
|
match = re.match(r'(int(?:<[^>]+>)?|float|locstring|string)\s+(\w+)\??', line)
|
|
if match:
|
|
kinds[match[2]] = match[1].split('<')[0]
|
|
metadata = (TABLES | SUPPLEMENTAL_TABLES)[table]
|
|
layout = metadata[1]
|
|
marker = f'LAYOUT {layout:08X}\n'
|
|
if text.count(marker) != 1:
|
|
raise ValueError('Missing reviewed native layout: ' + table)
|
|
# DBD blocks can be followed by a BUILD-only definition. Stop at the
|
|
# grammar's blank separator, rather than collecting its unrelated fields.
|
|
block = re.split(r'\r?\n[ \t]*\r?\n', text.split(marker, 1)[1], maxsplit=1)[0]
|
|
if BUILD not in block:
|
|
raise ValueError('Native build differs: ' + table)
|
|
result = []
|
|
for line in block.splitlines():
|
|
if not line or line.startswith(('BUILD', 'COMMENT')):
|
|
continue
|
|
if line.startswith('$noninline,id$ID'):
|
|
continue
|
|
line = re.sub(r'^\$[^$]+\$', '', line)
|
|
match = re.fullmatch(r'(\w+)(?:<(u?)(8|16|32|64)>)?(?:\[(\d+)\])?', line)
|
|
if not match:
|
|
raise ValueError('Unreviewed native field syntax')
|
|
name, unsigned, bits, count = match.groups()
|
|
kind = kinds[name]
|
|
if kind == 'int' and bits is None:
|
|
raise ValueError('Missing native integer width')
|
|
result.append((name, kind, int(bits or 32), bool(unsigned), int(count or 1)))
|
|
if canonical_sha256(result) != metadata[2]:
|
|
raise ValueError('Reviewed native field sequence changed: ' + table)
|
|
return result
|
|
|
|
|
|
def encode(row, schema, *, table=None):
|
|
if not isinstance(row, dict) or set(row) != {'ID'} | {field[0] for field in schema}:
|
|
raise ValueError('Complete native row required')
|
|
minimum_id = 1
|
|
if table is not None:
|
|
metadata = (TABLES | SUPPLEMENTAL_TABLES).get(table)
|
|
if metadata is None or canonical_sha256(schema) != metadata[2]:
|
|
raise ValueError('Native table/schema identity differs')
|
|
if table == 'Map':
|
|
minimum_id = 0
|
|
integer(row['ID'], minimum_id, 0x7fffffff, 'ID')
|
|
out = bytearray()
|
|
for name, kind, bits, unsigned, count in schema:
|
|
values = row[name] if count > 1 else [row[name]]
|
|
if not isinstance(values, list) or len(values) != count:
|
|
raise ValueError('Native array bound: ' + name)
|
|
for value in values:
|
|
if kind in ('string', 'locstring'):
|
|
if not isinstance(value, str) or '\0' in value or len(value.encode()) > 4096:
|
|
raise ValueError('Native string bound')
|
|
out.extend(value.encode('utf-8') + b'\0')
|
|
elif kind == 'float':
|
|
if type(value) not in (int, float) or not math.isfinite(value):
|
|
raise ValueError('Native float bound')
|
|
try:
|
|
out.extend(struct.pack('<f', value))
|
|
except (OverflowError, struct.error):
|
|
raise ValueError('Native float overflow') from None
|
|
else:
|
|
integer(value, 0 if unsigned else -(1 << (bits - 1)),
|
|
(1 << bits) - 1 if unsigned else (1 << (bits - 1)) - 1, name)
|
|
out.extend(value.to_bytes(bits // 8, 'little', signed=not unsigned))
|
|
if not out or len(out) > 65535:
|
|
raise ValueError('Native record bound')
|
|
return bytes(out)
|
|
|
|
|
|
# Source 1.12 Area25 uses ZoneId==0 for a zone; native 70334 requires a
|
|
# separate IsSubzone tag before ParentAreaID becomes the zone result.
|
|
# This profile grants no source/native ID alias or complete-row defaults.
|
|
AREA_CLASSIC_PROFILE = 'source-1.12-area25-native70334-v1'
|
|
AREA_NATIVE_IS_SUBZONE = 0x40000000
|
|
|
|
|
|
def area_parent_projection(source_parent_id, resolved_native_parent_id,
|
|
reviewed_native_flags, *, profile):
|
|
"""Project the parent/tag relationship using an explicit native binding.
|
|
|
|
All unrelated native flags are preserved. The caller must independently
|
|
establish the parent definition and the other native flag meanings; raw
|
|
Source flags and numeric ID equality are not such authority.
|
|
"""
|
|
if profile != AREA_CLASSIC_PROFILE:
|
|
raise ValueError('Unreviewed source/native Area hierarchy profile')
|
|
integer(source_parent_id, 0, 0xffffffff, 'Source Area parent')
|
|
integer(resolved_native_parent_id, 0, 0xffff, 'Resolved native Area parent')
|
|
if bool(source_parent_id) != bool(resolved_native_parent_id):
|
|
raise ValueError('Missing or inconsistent explicit native Area parent binding')
|
|
if not isinstance(reviewed_native_flags, list) or len(reviewed_native_flags) != 2:
|
|
raise ValueError('Complete reviewed native Area flags required')
|
|
for value in reviewed_native_flags:
|
|
integer(value, 0, 0xffffffff, 'Reviewed native Area flags')
|
|
flags = list(reviewed_native_flags)
|
|
flags[0] = ((flags[0] & ~AREA_NATIVE_IS_SUBZONE) |
|
|
(AREA_NATIVE_IS_SUBZONE if source_parent_id else 0))
|
|
return dict(ParentAreaID=resolved_native_parent_id, Flags=flags)
|
|
|
|
|
|
def area_classic_optional_none_fields(*, profile):
|
|
"""Explicit classic absence profile, corroborated by all 1373 originals.
|
|
|
|
-1 disables the conditional PvP world-state lookup. A zero wild-pet minimum
|
|
skips the area's level override; it does not disable wild pets or their
|
|
default level. No other native-only field receives an invented zero.
|
|
"""
|
|
if profile != AREA_CLASSIC_PROFILE:
|
|
raise ValueError('Unreviewed classic Area optional-relation profile')
|
|
return dict(PvpCombatWorldStateID=-1,
|
|
WildBattlePetLevelMin=0, WildBattlePetLevelMax=0)
|
|
|
|
|
|
def db2_header(path, table, layout):
|
|
with path.open('rb') as stream:
|
|
head = stream.read(208)
|
|
if (len(head) != 208 or head[:4] != b'WDC5' or
|
|
head[8:136].split(b'\0', 1)[0] != SCHEMA.encode() or
|
|
struct.unpack_from('<II', head, 152) != (table, layout)):
|
|
raise ValueError('Native DB2 schema/layout differs')
|
|
# WDC5 header: 8-byte version prefix + 128-byte schema + ordinary header.
|
|
return struct.unpack_from('<I', head, 164)[0]
|
|
|
|
|
|
def one(rows, predicate, label):
|
|
found = [row for row in rows if predicate(row)]
|
|
if len(found) != 1:
|
|
raise ValueError('Require one positive native/source definition: ' + label)
|
|
return found[0]
|
|
|
|
|
|
def validate_source(row):
|
|
"""The pure component also validates its normalized source input."""
|
|
integer(row.get('entry'), 1, 0x7fffffff, 'source spell')
|
|
conditions = row.get('unconditional')
|
|
if not isinstance(conditions, dict) or set(conditions) != set(CONDITIONS):
|
|
raise ValueError('Complete authoritative condition/proc metadata required')
|
|
for key, value in conditions.items():
|
|
integer(value, 0, 255 if key == 'procChance' else 0, 'source condition ' + key)
|
|
if (row.get('attributes') != [80, 0, 0, 0, 0] or
|
|
any(type(value) is not int for value in row['attributes']) or
|
|
row.get('school') != 0 or row.get('speed') != 0 or
|
|
(row.get('castingTimeIndex'), row.get('durationIndex'), row.get('rangeIndex')) != (1, 21, 1) or
|
|
row.get('equippedItem') != [-1, 0, 0]):
|
|
raise ValueError('Only reviewed unconditional passive metadata is supported')
|
|
for key in ('name', 'nameSubtext', 'description', 'auraDescription'):
|
|
if not isinstance(row.get(key), str) or '\0' in row[key] or len(row[key].encode()) > 4096:
|
|
raise ValueError('Source text bound')
|
|
if not row['name'] or not row['description']:
|
|
raise ValueError('Source name/description is missing')
|
|
if not isinstance(row.get('effects'), list) or len(row['effects']) != 3:
|
|
raise ValueError('Require all three source effect slots')
|
|
indices = []
|
|
for index, effect in enumerate(row['effects']):
|
|
if not isinstance(effect, list) or len(effect) != 12:
|
|
raise ValueError('Source effect shape differs')
|
|
if any(type(effect[column]) is not int for column in (0, 1, 2, 3, 4, 7, 8, 9, 10)):
|
|
raise ValueError('Source effect integer type differs')
|
|
if any(type(effect[column]) not in (int, float) or not math.isfinite(effect[column]) for column in (5, 6, 11)):
|
|
raise ValueError('Source effect numeric type differs')
|
|
if not effect[0]:
|
|
if effect[:11] != [0] * 11 or effect[11] != -1:
|
|
raise ValueError('Unreviewed empty source effect')
|
|
continue
|
|
if (effect[0] != 6 or effect[1] not in (98, 156) or effect[3:7] != [1, 1, 0, 0] or
|
|
effect[8:11] != [1, 0, 0] or effect[11] not in (0, 1)):
|
|
raise ValueError('Only reviewed constant self APPLY_AURA98/156 is supported')
|
|
integer(effect[2], -0x1000000, 0xffffff, 'constant base points')
|
|
integer(effect[7], 0, 0x7fffffff, 'aura misc value')
|
|
if (effect[1] == 98 and not effect[7]) or (effect[1] == 156 and effect[7] != 0):
|
|
raise ValueError('Unreviewed passive aura parameter')
|
|
indices.append(index)
|
|
if not indices:
|
|
raise ValueError('Passive has no supported effects')
|
|
for key in ('description', 'auraDescription'):
|
|
for token in re.findall(r'\$[^\s.,%;:!?()]*', row[key]):
|
|
if not re.fullmatch(r'\$s[123]', token) or int(token[2]) - 1 not in indices:
|
|
raise ValueError('Unsupported source description token')
|
|
return row
|
|
|
|
|
|
def source_spell(dbc, row, offsets):
|
|
"""Check current server metadata against the actual 173-column source.
|
|
|
|
A whitelist of nonzero disk columns makes unreviewed conditional, proc,
|
|
resource, visual, radius and scaling dependencies fail closed.
|
|
"""
|
|
validate_source(row)
|
|
ident = integer(row.get('entry'), 1, 0x7fffffff, 'source spell')
|
|
raw = dbc.by_id.get(ident)
|
|
if raw is None:
|
|
raise ValueError('Source spell is absent from pinned capture')
|
|
allowed = {0, 1, 6, 18, 25, 30, 36, 58, 59, 60, 117}
|
|
allowed.update(range(120, 156)) # Eight original localized slots + flags.
|
|
effect_names = ('Effect', 'EffectDieSides', 'EffectBaseDice', 'EffectDicePerLevel',
|
|
'EffectRealPointsPerLevel', 'EffectBasePoints', 'ImplicitTargetA',
|
|
'ImplicitTargetB', 'EffectAura', 'EffectMiscValue',
|
|
'EffectTriggerSpell', 'EffectChainAmplitude')
|
|
for name in effect_names:
|
|
allowed.update(range(offsets[name], offsets[name] + 3))
|
|
if any(value and index not in allowed for index, value in enumerate(raw)):
|
|
raise ValueError('Unreviewed source passive dependency')
|
|
text_names = [('name', 'Name_lang'), ('nameSubtext', 'NameSubtext_lang'),
|
|
('description', 'Description_lang'), ('auraDescription', 'AuraDescription_lang')]
|
|
for name, disk in text_names:
|
|
if row.get(name) != dbc.string(raw[offsets[disk]]):
|
|
raise ValueError('Server/source text differs: ' + name)
|
|
attrs = [raw[offsets[name]] for name in ('Attributes', 'AttributesEx', 'AttributesExB', 'AttributesExC', 'AttributesExD')]
|
|
expected = dict(attributes=attrs, school=raw[1], castingTimeIndex=raw[18],
|
|
durationIndex=raw[30], rangeIndex=raw[36], speed=0,
|
|
equippedItem=[struct.unpack('<i', struct.pack('<I', raw[58]))[0], raw[59], raw[60]],
|
|
spellIconId=raw[117])
|
|
if any(row.get(key) != value for key, value in expected.items()):
|
|
raise ValueError('Server/source passive metadata differs')
|
|
condition_offsets = dict(stances='ShapeshiftMask', stancesNot='ShapeshiftExclude',
|
|
targets='Targets', targetCreatureType='TargetCreatureType', requiresSpellFocus='RequiresSpellFocus',
|
|
casterAuraState='CasterAuraState', targetAuraState='TargetAuraState', procFlags='ProcFlags',
|
|
procCharges='ProcCharges', procChance='ProcChance', interruptFlags='InterruptFlags',
|
|
auraInterruptFlags='AuraInterruptFlags', channelInterruptFlags='ChannelInterruptFlags')
|
|
if any(row['unconditional'][key] != raw[offsets[field]] for key, field in condition_offsets.items()):
|
|
raise ValueError('Authoritative conditions differ from source capture')
|
|
if (attrs != [80, 0, 0, 0, 0] or row['school'] != 0 or
|
|
(row['castingTimeIndex'], row['durationIndex'], row['rangeIndex']) != (1, 21, 1) or
|
|
row['equippedItem'] != [-1, 0, 0] or raw[25] not in (0, 101)):
|
|
raise ValueError('Only reviewed unconditional passive metadata is supported')
|
|
if not isinstance(row.get('effects'), list) or len(row['effects']) != 3:
|
|
raise ValueError('Require all three source effect slots')
|
|
for index, effect in enumerate(row['effects']):
|
|
if not isinstance(effect, list) or len(effect) != len(EFFECT_COLUMNS):
|
|
raise ValueError('Source effect shape differs')
|
|
for position, field in enumerate(('Effect', 'EffectAura', 'EffectBasePoints', 'EffectBaseDice',
|
|
'EffectDieSides', 'EffectDicePerLevel', 'EffectRealPointsPerLevel',
|
|
'EffectMiscValue', 'ImplicitTargetA', 'ImplicitTargetB', 'EffectTriggerSpell')):
|
|
bits = raw[offsets[field] + index]
|
|
value = struct.unpack('<f' if position in (5, 6) else '<i', struct.pack('<I', bits))[0]
|
|
if effect[position] != value:
|
|
raise ValueError('Server/source effect differs')
|
|
active = effect[0] != 0
|
|
chain = struct.unpack('<f', struct.pack('<I', raw[offsets['EffectChainAmplitude'] + index]))[0]
|
|
if not active:
|
|
if effect[:11] != [0] * 11 or effect[11] != -1 or chain != 0:
|
|
raise ValueError('Unreviewed empty source effect')
|
|
continue
|
|
if (effect[0] != 6 or effect[1] not in (98, 156) or effect[3:7] != [1, 1, 0, 0] or
|
|
effect[8:11] != [1, 0, 0] or effect[11] not in (0, 1) or chain != 1):
|
|
raise ValueError('Only reviewed constant self APPLY_AURA98/156 is supported')
|
|
integer(effect[2], -0x1000000, 0xffffff, 'constant base points')
|
|
integer(effect[7], 0, 0x7fffffff, 'aura misc value')
|
|
if effect[1] == 98 and not effect[7] or effect[1] == 156 and effect[7] != 0:
|
|
raise ValueError('Unreviewed passive aura parameter')
|
|
indices = [index for index, effect in enumerate(row['effects']) if effect[0]]
|
|
if not indices:
|
|
raise ValueError('Passive has no supported effects')
|
|
for name in ('description', 'auraDescription'):
|
|
# Resolve only the original constant effect tokens supported by this
|
|
# component. Never rewrite unsupported modern/conditional expressions.
|
|
tokens = re.findall(r'\$[^\s.,%;:!?()]*', row[name])
|
|
if any(not re.fullmatch(r'\$s[123]', token) or int(token[2]) - 1 not in indices for token in tokens):
|
|
raise ValueError('Unsupported source description token')
|
|
return deepcopy(validate_source(row))
|
|
|
|
|
|
def racial_link(abilities, skills, ident, race, cls):
|
|
race_bit, class_bit = 1 << (race - 1), 1 << (cls - 1)
|
|
matches = []
|
|
for raw in abilities.rows:
|
|
skill = skills.by_id.get(raw[1])
|
|
if raw[2] != ident or skill is None or skill[1] != 9:
|
|
continue
|
|
if (raw[3] and not raw[3] & race_bit) or (raw[4] and not raw[4] & class_bit):
|
|
continue
|
|
if raw[5] & race_bit or raw[6] & class_bit:
|
|
continue
|
|
if raw[5] or raw[6] or any(raw[12:]):
|
|
raise ValueError('Unreviewed racial skill-line restrictions')
|
|
matches.append(raw)
|
|
return one(matches, lambda _: True, 'genuine applicable racial link')
|
|
|
|
|
|
def verify_skill_link(source, native, source_skills, native_skills):
|
|
row = one(native['SkillLineAbility'], lambda r: r['Spell'] == source[2], 'racial SkillLineAbility')
|
|
expected = skill_link_fields(source)
|
|
if any(row.get(key) != value for key, value in expected.items()):
|
|
raise ValueError('Native racial spellbook restrictions differ')
|
|
verify_racial_skill(source, native['SkillLine'], source_skills)
|
|
return row
|
|
|
|
|
|
def skill_link_fields(source):
|
|
return dict(SkillLine=source[1], Spell=source[2], MinSkillLineRank=source[7],
|
|
ClassMask=source[4], SupercedesSpell=source[8], AcquireMethod=source[9],
|
|
TrivialSkillLineRankHigh=source[10], TrivialSkillLineRankLow=source[11],
|
|
RaceMasks=[source[3], 0], AbilityVerb_lang='', AbilityAllVerb_lang='',
|
|
Flags=0, NumSkillUps=1, UniqueBit=0, TradeSkillCategoryID=0,
|
|
SkillupSkillLineID=0, Field_5_5_4_67090_014=[0, 0])
|
|
|
|
|
|
def verify_racial_skill(source, native_skills, source_skills):
|
|
source_skill = source_skills.by_id[source[1]]
|
|
target = one(native_skills, lambda r: r['ID'] == source[1], 'racial SkillLine')
|
|
if target['CategoryID'] != 9 or target['DisplayName_lang'] != source_skills.string(source_skill[3]):
|
|
raise ValueError('Racial skill identity differs')
|
|
|
|
|
|
def new_registry_values(registry, maxima, occupied, *, tables=NEW_CHILD_TABLES):
|
|
if not isinstance(tables,tuple) or not 1<=len(tables)<=16 or len(set(tables))!=len(tables) or any(t not in (TABLES|SUPPLEMENTAL_TABLES) for t in tables):
|
|
raise ValueError('Explicit reviewed child allocation tables required')
|
|
if (not isinstance(registry, dict) or registry.get('schema_version') != 1 or
|
|
registry.get('build') != BUILD or
|
|
set(registry) - {'schema_version', 'build', *tables} or
|
|
('SpellEffect' in tables and not isinstance(registry.get('SpellEffect'), dict))):
|
|
raise ValueError('Explicit new-definition child registry required')
|
|
for table in tables:
|
|
entries = registry.get(table, {})
|
|
if not isinstance(entries, dict) or len(entries) > 4096:
|
|
raise ValueError('Child registry bound: ' + table)
|
|
seen = set()
|
|
for key, value in entries.items():
|
|
pattern = r'[1-9][0-9]*:[012]' if table == 'SpellEffect' else r'[1-9][0-9]*'
|
|
if not isinstance(key, str) or not re.fullmatch(pattern, key):
|
|
raise ValueError('Invalid child registry key')
|
|
integer(int(key.split(':')[0]), 1, 0x7fffffff, 'registry source spell')
|
|
integer(value, maxima[table] + 1, 0x7fffffff, 'new native child ID')
|
|
if value in seen or value in occupied.get(table, set()):
|
|
raise ValueError('Child registry collision: ' + table)
|
|
seen.add(value)
|
|
|
|
|
|
def verified_spell_icon(src, new_icon_ids, source_icons, target_icon_names, available, read_icon):
|
|
"""Verify original icon identity and actual local bytes for any spell policy."""
|
|
ident = src['entry']
|
|
fid = integer(new_icon_ids[str(ident)], 1, 0x7fffffff, 'explicit icon FileDataID')
|
|
names = target_icon_names.get(fid, [])
|
|
icon = source_icons.by_id.get(src['spellIconId'])
|
|
if icon is None or not isinstance(names, list) or not 1 <= len(names) <= 16:
|
|
raise ValueError('Actual source/target icon reference required')
|
|
source_icon = normalize_icon(source_icons.string(icon[1]), source=True)
|
|
paths = {normalize_icon(name)['path'] for name in names}
|
|
if len(paths) != 1:
|
|
raise ValueError('Ambiguous explicit icon reference')
|
|
path = next(iter(paths)); target_icon = normalize_icon(path)
|
|
if (source_icon['stem'] != target_icon['stem'] or
|
|
source_icon['extension'] is not None and source_icon['path'] != path):
|
|
raise ValueError('Source/target icon reference differs')
|
|
asset = available.get(path)
|
|
if asset is None:
|
|
raise ValueError('Actual target icon asset is unavailable')
|
|
raw = read_icon(path)
|
|
if (not isinstance(raw, bytes) or len(raw) != asset['bytes'] or
|
|
hashlib.sha256(raw).hexdigest() != asset['sha256'] or
|
|
raw[:4].hex() != asset['magic_hex'] or raw[:4] not in (b'BLP1', b'BLP2')):
|
|
raise ValueError('Actual target icon bytes/hash/magic differs')
|
|
return fid, asset
|
|
|
|
|
|
def new_component(sources, native, schemas, maxima, registry, *, known, race, cls,
|
|
source_abilities, source_skills, source_icons, target_icon_names,
|
|
new_icon_ids, icon_assets, read_icon):
|
|
"""Explicit NEW candidate; empty references never prove installed absence."""
|
|
registry = deepcopy(registry)
|
|
all_ids = {}
|
|
for table in TABLES:
|
|
rows = native.get(table)
|
|
if not isinstance(rows, list) or len(rows) > 2000000:
|
|
raise ValueError('Bounded native reference rows required: ' + table)
|
|
ids = []
|
|
for row in rows:
|
|
if not isinstance(row, dict):
|
|
raise ValueError('Malformed native reference row')
|
|
ids.append(integer(row.get('ID'), 1, maxima[table], 'native reference ID'))
|
|
if len(set(ids)) != len(ids):
|
|
raise ValueError('Duplicate native reference identity')
|
|
all_ids[table] = set(ids)
|
|
occupied = {table: all_ids[table] for table in NEW_CHILD_TABLES}
|
|
new_registry_values(registry, maxima, occupied)
|
|
if (not isinstance(new_icon_ids, dict) or set(new_icon_ids) != {str(row['entry']) for row in sources} or
|
|
not callable(read_icon)):
|
|
raise ValueError('Explicit source-spell icon IDs and actual asset reader required')
|
|
available = available_index(icon_assets)
|
|
records, verification = [], []
|
|
for src in sorted(sources, key=lambda row: row['entry']):
|
|
validate_source(src); ident = src['entry']
|
|
if ident not in known:
|
|
raise ValueError('Selected spell is not genuinely known')
|
|
for table in TABLES:
|
|
if any((row.get('SpellID') if table in NEW_CHILD_TABLES[:3] else
|
|
row.get('Spell') if table == 'SkillLineAbility' else row['ID']) == ident
|
|
for row in native[table]):
|
|
raise ValueError('New-definition policy has a positive native reference: ' + table)
|
|
child_review = review_children(native, ident)
|
|
link = racial_link(source_abilities, source_skills, ident, race, cls)
|
|
verify_racial_skill(link, native['SkillLine'], source_skills)
|
|
for effect in src['effects']:
|
|
if effect[0] and effect[1] == 98:
|
|
skill = source_skills.by_id.get(effect[7])
|
|
target = one(native['SkillLine'], lambda row: row['ID'] == effect[7], 'effect SkillLine')
|
|
if skill is None or target['CategoryID'] != skill[1] or target['DisplayName_lang'] != source_skills.string(skill[3]):
|
|
raise ValueError('Aura skill identity differs')
|
|
fid, asset = verified_spell_icon(src, new_icon_ids, source_icons,
|
|
target_icon_names, available, read_icon)
|
|
|
|
def child_id(table, index=None):
|
|
entries = registry.setdefault(table, {})
|
|
key = f'{ident}:{index}' if table == 'SpellEffect' else str(ident)
|
|
if key not in entries:
|
|
entries[key] = max([maxima[table]] + list(entries.values())) + 1
|
|
new_registry_values(registry, maxima, occupied)
|
|
return entries[key]
|
|
|
|
rows = [('SpellName', dict(ID=ident, Name_lang=src['name'])),
|
|
('Spell', dict(ID=ident, NameSubtext_lang=src['nameSubtext'],
|
|
Description_lang=src['description'], AuraDescription_lang=src['auraDescription'])),
|
|
('SpellMisc', dict(deepcopy(NEW_MISC_NEUTRAL), ID=child_id('SpellMisc'),
|
|
SpellID=ident, Attributes=src['attributes'] + [0] * 12,
|
|
SpellIconFileDataID=fid)),
|
|
('SpellEquippedItems', dict(ID=child_id('SpellEquippedItems'), SpellID=ident,
|
|
EquippedItemClass=src['equippedItem'][0], EquippedItemSubclass=src['equippedItem'][1],
|
|
EquippedItemInvTypes=src['equippedItem'][2])),
|
|
('SkillLineAbility', dict(skill_link_fields(link), ID=child_id('SkillLineAbility')))]
|
|
for index, effect in enumerate(src['effects']):
|
|
if effect[0]:
|
|
rows.append(('SpellEffect', dict(deepcopy(NEW_EFFECT_NEUTRAL),
|
|
ID=child_id('SpellEffect', index), SpellID=ident, EffectIndex=index,
|
|
EffectAura=effect[1], EffectBasePointsF=effect[2] + effect[3],
|
|
EffectMiscValue=[effect[7], 0])))
|
|
for table, row in rows:
|
|
raw = encode(row, schemas[table])
|
|
records.append(dict(table_name=table, table_hash=hex(TABLES[table][0]), id=row['ID'],
|
|
record=row, wire_hex=raw.hex(), sha256=hashlib.sha256(raw).hexdigest(),
|
|
source_spell_id=ident, source_effect_index=row.get('EffectIndex'),
|
|
baseline_record_sha256=None, changed_fields=sorted(row), preserved_native_fields=[],
|
|
allocation_policy='new-source-passive-child' if table in NEW_CHILD_TABLES else 'new-source-spell-definition'))
|
|
verification.append(dict(spell_id=ident, source_record_sha256=canonical_sha256(src),
|
|
source_skill_line_ability_id=link[0], source_effect_indices=[i for i,e in enumerate(src['effects']) if e[0]],
|
|
authoritative_conditions=deepcopy(src['unconditional']), native_child_reference_review=child_review,
|
|
native_reference_status='no-positive-definition-in-supplied-six-table-references',
|
|
installed_definition_absence_verified=False, icon_asset_bytes_verified=True,
|
|
icon_asset=dict(file_data_id=fid, **asset), engine_accepted=False, gameplay_verified=False))
|
|
return dict(kind='source-passive-spell-component', schema_version=1, build=BUILD, schema=SCHEMA,
|
|
id_remapping=False, records=records, spells=verification, child_id_registry=registry,
|
|
definition_policy=NEW_POLICY, engine_accepted=False, gameplay_verified=False,
|
|
complete_native_dependency_absence_verified=False,
|
|
limitations=['Explicit new unconditional passive candidate; no unrelated spell is cloned.',
|
|
'Source attributes0..4 are preserved; native attributes5..16 are zero server-default candidates, not verified client requirements.',
|
|
'The unknown native Attributes15 bit0x2000 is not synthesized.',
|
|
'Supplied reference absence is not proof of absence in the installed client; verify before installation.',
|
|
'Verified icon bytes and encoded records do not prove native engine acceptance or server gameplay effects.'])
|
|
|
|
|
|
def registry_values(registry, max_id, occupied):
|
|
if registry.get('schema_version') != 1 or registry.get('build') != BUILD or not isinstance(registry.get('SpellEffect'), dict):
|
|
raise ValueError('Explicit destination child-ID registry required')
|
|
entries = registry['SpellEffect']
|
|
values = []
|
|
for key, value in entries.items():
|
|
if not re.fullmatch(r'[1-9][0-9]*:[012]', key):
|
|
raise ValueError('Invalid child-ID registry key')
|
|
integer(value, max_id + 1, 0x7fffffff, 'new native child ID')
|
|
if value in values or value in occupied:
|
|
raise ValueError('Child-ID registry collision')
|
|
values.append(value)
|
|
return values
|
|
|
|
|
|
def allocate(registry, spell_id, index, max_id, occupied):
|
|
values = registry_values(registry, max_id, occupied)
|
|
entries = registry['SpellEffect']
|
|
key = f'{spell_id}:{index}'
|
|
if key not in entries:
|
|
entries[key] = max([max_id] + values) + 1
|
|
integer(entries[key], max_id + 1, 0x7fffffff, 'allocated native child ID')
|
|
return entries[key]
|
|
|
|
|
|
def review_children(native, ident):
|
|
review = []
|
|
for table in tuple(CHILD_NEUTRAL) + CHILD_UNREVIEWED:
|
|
rows = native.get(table)
|
|
if rows is None:
|
|
review.append(dict(table=table, status='reference-not-exported', actual_absence_verified=False))
|
|
continue
|
|
selected = [row for row in rows if row.get('SpellID') == ident]
|
|
if selected:
|
|
if table in CHILD_UNREVIEWED:
|
|
raise ValueError('Positive native child requires semantic review: ' + table)
|
|
expected = dict(CHILD_NEUTRAL[table])
|
|
if table == 'SpellAuraOptions':
|
|
# With no proc type mask, this component has no proc trigger;
|
|
# do not assign a meaning to the separate source chance101.
|
|
expected['ProcChance'] = selected[0].get('ProcChance')
|
|
integer(expected['ProcChance'], 0, 255, 'native nontriggered ProcChance')
|
|
for row in selected:
|
|
if (set(row) != {'ID', 'SpellID'} | set(expected) or
|
|
any(row[key] != value for key, value in expected.items())):
|
|
raise ValueError('Positive native child contradicts passive policy: ' + table)
|
|
integer(row['ID'], 1, 0x7fffffff, 'positive native child ID')
|
|
review.append(dict(table=table, status='positive-neutral-rows-retained',
|
|
ids=[row['ID'] for row in selected], records_sha256=canonical_sha256(selected)))
|
|
else:
|
|
review.append(dict(table=table, status='no-positive-row-in-reference-export',
|
|
actual_absence_verified=False))
|
|
return review
|
|
|
|
|
|
def component(sources, native, schemas, maxima, registry, *, known, race, cls,
|
|
source_abilities, source_skills, source_icons, target_icon_names,
|
|
new_definitions=False, new_icon_ids=None, icon_assets=None, read_icon=None,
|
|
constant_self_auras=False):
|
|
"""Pure batch transformation. Inputs and the allocation registry are copied."""
|
|
integer(race, 1, 32, 'source race'); integer(cls, 1, 32, 'source class')
|
|
if not isinstance(known, list) or any(type(i) is not int or i <= 0 for i in known) or len(set(known)) != len(known):
|
|
raise ValueError('Genuine known-spell ID snapshot required')
|
|
if not isinstance(sources, list) or not 1 <= len(sources) <= 128 or len({s['entry'] for s in sources}) != len(sources):
|
|
raise ValueError('Bounded unique source selection required')
|
|
if constant_self_auras:
|
|
if new_definitions:
|
|
raise ValueError('Definition policies are mutually exclusive')
|
|
return constant_component(sources, native, schemas, maxima, registry, known=known,
|
|
race=race, cls=cls, source_abilities=source_abilities, source_skills=source_skills,
|
|
source_icons=source_icons, target_icon_names=target_icon_names)
|
|
if new_definitions:
|
|
return new_component(sources, native, schemas, maxima, registry, known=known, race=race, cls=cls,
|
|
source_abilities=source_abilities, source_skills=source_skills, source_icons=source_icons,
|
|
target_icon_names=target_icon_names, new_icon_ids=new_icon_ids, icon_assets=icon_assets, read_icon=read_icon)
|
|
registry = deepcopy(registry)
|
|
records, verification = [], []
|
|
occupied = {r['ID'] for r in native['SpellEffect']}
|
|
registry_values(registry, maxima['SpellEffect'], occupied)
|
|
for src in sorted(sources, key=lambda s: s['entry']):
|
|
validate_source(src)
|
|
ident = src['entry']
|
|
child_review = review_children(native, ident)
|
|
if ident not in known:
|
|
raise ValueError('Selected spell is not genuinely known')
|
|
link = racial_link(source_abilities, source_skills, ident, race, cls)
|
|
sla = verify_skill_link(link, native, source_skills, native['SkillLine'])
|
|
name = one(native['SpellName'], lambda r: r['ID'] == ident, 'SpellName')
|
|
text = one(native['Spell'], lambda r: r['ID'] == ident, 'Spell')
|
|
misc = one(native['SpellMisc'], lambda r: r['SpellID'] == ident, 'SpellMisc')
|
|
equipped = one(native['SpellEquippedItems'], lambda r: r['SpellID'] == ident, 'SpellEquippedItems')
|
|
effects = [r for r in native['SpellEffect'] if r['SpellID'] == ident]
|
|
for table, rows in [('SpellName', [name]), ('Spell', [text]), ('SpellMisc', [misc]),
|
|
('SpellEquippedItems', [equipped]), ('SpellEffect', effects), ('SkillLineAbility', [sla])]:
|
|
for row in rows:
|
|
encode(row, schemas[table])
|
|
if row['ID'] > maxima[table]:
|
|
raise ValueError('Native baseline exceeds pinned full-table maximum')
|
|
if name['Name_lang'] != src['name']:
|
|
raise ValueError('Same-ID spell name collision')
|
|
attrs = misc['Attributes']
|
|
if (misc['DifficultyID'] != 0 or attrs[:5] != src['attributes'] or
|
|
any(value for index, value in enumerate(attrs[5:], 5) if index != 15) or
|
|
attrs[15] & ~0x2000 or misc['SchoolMask'] != 1 or misc['Speed'] != 0 or
|
|
any(misc[key] for key in ('PvPDurationIndex', 'LaunchDelay', 'MinDuration',
|
|
'ActiveIconFileDataID', 'ContentTuningID', 'ShowFutureSpellPlayerConditionID',
|
|
'SpellVisualScript', 'ActiveSpellVisualScript')) or
|
|
(misc['CastingTimeIndex'], misc['RangeIndex']) != (1, 1) or misc['DurationIndex'] not in (0, 21)):
|
|
raise ValueError('Unreviewed same-ID native Misc dependency')
|
|
icon = source_icons.by_id.get(src['spellIconId'])
|
|
native_names = target_icon_names.get(misc['SpellIconFileDataID'], [])
|
|
if icon is None or not native_names:
|
|
raise ValueError('Require positive same-spell source/target icon naming evidence')
|
|
source_icon = normalize_icon(source_icons.string(icon[1]), source=True)
|
|
if not all(normalize_icon(value)['stem'] == source_icon['stem'] for value in native_names):
|
|
raise ValueError('Same-spell icon reference differs')
|
|
for effect in src['effects']:
|
|
if effect[0] and effect[1] == 98:
|
|
skill = source_skills.by_id.get(effect[7])
|
|
target = one(native['SkillLine'], lambda r: r['ID'] == effect[7], 'effect SkillLine')
|
|
if skill is None or target['DisplayName_lang'] != source_skills.string(skill[3]) or target['CategoryID'] != skill[1]:
|
|
raise ValueError('Aura skill identity differs')
|
|
if not effects or len({r['EffectIndex'] for r in effects}) != len(effects):
|
|
raise ValueError('Positive unambiguous native effect definitions required')
|
|
active_indices = {i for i, effect in enumerate(src['effects']) if effect[0]}
|
|
neutral = dict(Effect=6, DifficultyID=0, EffectAmplitude=0, EffectAttributes=0,
|
|
EffectAuraPeriod=0, EffectChainAmplitude=1, EffectChainTargets=0, EffectItemType=0,
|
|
EffectMechanic=0, EffectPointsPerResource=0, EffectPos_facing=0, EffectRealPointsPerLevel=0,
|
|
EffectTriggerSpell=0, BonusCoefficientFromAP=0, PvpMultiplier=1, Coefficient=0,
|
|
Variance=0, ResourceCoefficient=0, GroupSizeBasePointsCoefficient=1, ScalingClass=0,
|
|
Node__Field_12_0_0_63534_001=0, EffectRadiusIndex=[0, 0],
|
|
EffectSpellClassMask=[0, 0, 0, 0], ImplicitTarget=[1, 0])
|
|
for row in effects:
|
|
if (row['EffectIndex'] not in active_indices or row['EffectAura'] not in (98, 156, 290) or
|
|
row['EffectBonusCoefficient'] not in (0, 1) or row['EffectMiscValue'][1] != 0 or
|
|
any(row[key] != value for key, value in neutral.items())):
|
|
raise ValueError('Unreviewed native effect dependency or surplus effect')
|
|
changes = [('Spell', text, dict(text, NameSubtext_lang=src['nameSubtext'],
|
|
Description_lang=src['description'], AuraDescription_lang=src['auraDescription'])),
|
|
('SpellMisc', misc, dict(misc, DurationIndex=src['durationIndex'])),
|
|
('SpellEquippedItems', equipped, dict(equipped, EquippedItemClass=src['equippedItem'][0],
|
|
EquippedItemSubclass=src['equippedItem'][1], EquippedItemInvTypes=src['equippedItem'][2]))]
|
|
for index in sorted(active_indices):
|
|
old = next((row for row in effects if row['EffectIndex'] == index), None)
|
|
new = deepcopy(old if old is not None else min(effects, key=lambda r: r['EffectIndex']))
|
|
if old is None:
|
|
new['ID'] = allocate(registry, ident, index, maxima['SpellEffect'], occupied)
|
|
effect = src['effects'][index]
|
|
# Tortoise Aura -> CalculateSpellDamage uses BasePoints+BaseDice
|
|
# for these constant types, not SpellBonusWithCoeffs. Do not map
|
|
# the server's unused coefficient1 into modern spell-power bonus.
|
|
new.update(EffectIndex=index, EffectAura=effect[1], EffectBasePointsF=effect[2] + effect[3],
|
|
EffectMiscValue=[effect[7], 0], EffectBonusCoefficient=0)
|
|
changes.append(('SpellEffect', old, new))
|
|
preserved = []
|
|
for table, old, new in changes:
|
|
wire = encode(new, schemas[table])
|
|
if old == new:
|
|
preserved.append(dict(table=table, id=new['ID'], reason='already-source-equivalent'))
|
|
continue
|
|
records.append(dict(table_name=table, table_hash=hex(TABLES[table][0]), id=new['ID'],
|
|
record=new, wire_hex=wire.hex(), sha256=hashlib.sha256(wire).hexdigest(),
|
|
source_spell_id=ident, source_effect_index=new.get('EffectIndex'),
|
|
baseline_record_sha256=canonical_sha256(old) if old is not None else None,
|
|
changed_fields=sorted(key for key in new if old is None or old[key] != new[key]),
|
|
preserved_native_fields=sorted(key for key in new if old is not None and old[key] == new[key]),
|
|
allocation_policy='same-spell-positive-native-effect-clone' if old is None else 'same-ID-source-authoritative-override'))
|
|
verification.append(dict(spell_id=ident, source_record_sha256=canonical_sha256(src),
|
|
retained_spell_name_id=name['ID'], retained_skill_line_ability_id=sla['ID'],
|
|
retained_rows=preserved, source_effect_indices=sorted(active_indices),
|
|
preserved_misc_attributes=deepcopy(attrs), icon_reference_names=native_names,
|
|
source_bonus_coefficients=[effect[11] for effect in src['effects']],
|
|
amount_policy='source-BasePoints-plus-BaseDice; passive-bonus-coefficient-neutral-zero',
|
|
authoritative_conditions=deepcopy(src['unconditional']),
|
|
proc_chance_policy='source value recorded; zero source procFlags required; no proc-chance meaning or trigger is synthesized',
|
|
native_child_reference_review=child_review,
|
|
icon_asset_bytes_verified=False, engine_accepted=False, gameplay_verified=False))
|
|
return dict(kind='source-passive-spell-component', schema_version=1, build=BUILD, schema=SCHEMA,
|
|
id_remapping=False, records=records, spells=verification, child_id_registry=registry,
|
|
engine_accepted=False, gameplay_verified=False, complete_native_dependency_absence_verified=False,
|
|
limitations=['Only positive existing same-spell native definitions are supported; export absence never becomes an absent-definition assertion.',
|
|
'Only reviewed unconditional constant self APPLY_AURA98/156 effects are converted; arbitrary spells/procs are rejected.',
|
|
'New effect indices clone a validated neutral same-spell native effect and reserve only a destination child ID above the pinned full-table maximum.',
|
|
'Unknown native Misc Attributes[15] bit0x2000 is preserved exactly; its meaning is not invented.',
|
|
'Retained racial spellbook membership, source IDs and current known-spell selection are verified from supplied snapshots, not granted by this tool.',
|
|
'Icon evidence compares names and preserves existing references; decoded assets and actual client acceptance remain separate tests.',
|
|
'This offline package does not implement server passive rules or prove a learned passive effect in the client.'])
|
|
|
|
|
|
def constant_server_row(raw):
|
|
"""Normalize the pinned public server subset; no runtime database access."""
|
|
try:
|
|
row={key:raw[key] for key in ('entry','name','nameSubtext','description','auraDescription','school','castingTimeIndex','durationIndex','rangeIndex','speed','spellIconId')}
|
|
row.update(attributes=[raw[key] for key in ('attributes','attributesEx','attributesEx2','attributesEx3','attributesEx4')],
|
|
equippedItem=[raw[key] for key in ('equippedItemClass','equippedItemSubClassMask','equippedItemInventoryTypeMask')],
|
|
conditions={key:raw[key] for key in CONDITIONS},
|
|
timing={key:raw[key] for key in ('recoveryTime','categoryRecoveryTime','startRecoveryCategory','startRecoveryTime')},
|
|
power=[raw[key] for key in ('powerType','manaCost','manCostPerLevel','manaPerSecond','manaPerSecondPerLevel','manaCostPercentage')],
|
|
visuals=[raw['spellVisual1'],raw['spellVisual2']],
|
|
effects=[[raw[prefix+str(i)] for prefix in ('effect','effectApplyAuraName','effectBasePoints','effectBaseDice','effectDieSides','effectDicePerLevel','effectRealPointsPerLevel','effectMiscValue','effectImplicitTargetA','effectImplicitTargetB','effectTriggerSpell','effectBonusCoefficient')] for i in range(1,4)])
|
|
except (KeyError,TypeError):raise ValueError('Complete reviewed current server subset required') from None
|
|
return row
|
|
|
|
|
|
def validate_constant_source(row):
|
|
"""A separate reviewed family; never broadens the unconditional policy."""
|
|
integer(row.get('entry'), 1, 0x7fffffff, 'source spell')
|
|
if not isinstance(row.get('attributes'),list) or len(row['attributes'])!=5 or any(type(value) is not int for value in row['attributes']):raise ValueError('Source attribute type/shape')
|
|
passive = row.get('attributes') == [80, 0, 0, 0, 0]
|
|
if not passive and row.get('attributes') != [262160, 32, 524288, 0, 0]:
|
|
raise ValueError('Unreviewed constant-self attribute family')
|
|
if (row.get('school'), row.get('speed'), row.get('castingTimeIndex'), row.get('rangeIndex')) != (0, 0, 1, 1) or row.get('equippedItem') != [-1, 0, 0]:
|
|
raise ValueError('Unreviewed constant-self school/cast/range/equipment')
|
|
if row.get('power') != [0] * 6 or any(type(value) is not int for value in row['power']):
|
|
raise ValueError('Only genuinely resource-free self auras are reviewed')
|
|
if any(type(value) is not int for value in row['equippedItem']):raise ValueError('Source equipment type')
|
|
conditions = row.get('conditions'); timing = row.get('timing')
|
|
if not isinstance(conditions, dict) or set(conditions) != set(CONDITIONS):
|
|
raise ValueError('Complete authoritative self-aura conditions required')
|
|
for key, value in conditions.items():
|
|
integer(value, 0, 255 if key == 'procChance' else 0xffffffff if key == 'stances' else 0, key)
|
|
if (passive and conditions['stances']) or not isinstance(timing, dict) or set(timing) != {'recoveryTime','categoryRecoveryTime','startRecoveryCategory','startRecoveryTime'}:
|
|
raise ValueError('Unreviewed constant-self timing/stance family')
|
|
for value in timing.values():integer(value, 0, 0x7fffffff, 'source timing')
|
|
if passive and (row.get('durationIndex') != 21 or any(timing.values())):
|
|
raise ValueError('Passive timing is not genuinely permanent/uncooldowned')
|
|
if not passive and (row.get('durationIndex') != 18 or timing != dict(recoveryTime=180000, categoryRecoveryTime=0, startRecoveryCategory=133, startRecoveryTime=1500)):
|
|
raise ValueError('Active self-aura timing requires its reviewed20s/3min/GCD profile')
|
|
if not isinstance(row.get('visuals'), list) or len(row['visuals']) != 2:
|
|
raise ValueError('Complete source visual references required')
|
|
for value in row['visuals']:integer(value, 0, 0x7fffffff, 'source visual')
|
|
for key in ('name','nameSubtext','description','auraDescription'):
|
|
if not isinstance(row.get(key), str) or '\0' in row[key] or len(row[key].encode()) > 4096:
|
|
raise ValueError('Source constant-self text bound')
|
|
if not row['name'] or not row['description'] or not isinstance(row.get('effects'), list) or len(row['effects']) != 3:
|
|
raise ValueError('Complete source constant-self text/effects required')
|
|
active = []
|
|
for index,effect in enumerate(row['effects']):
|
|
if not isinstance(effect,list) or len(effect)!=12 or any(type(value) not in (int,float) or not math.isfinite(value) for value in effect):raise ValueError('Constant source effect shape/type')
|
|
if not effect[0]:
|
|
if effect != [0]*11+[-1]:raise ValueError('Unreviewed empty source effect')
|
|
continue
|
|
if (any(type(effect[i]) is not int for i in (0,1,2,3,4,7,8,9,10)) or effect[0]!=6 or
|
|
effect[1] not in ((134,137) if passive else (17,52,57)) or
|
|
effect[3:7]!=[1,1,0,0] or effect[8:11]!=[1,0,0] or effect[11] not in (-1,0,1)):
|
|
raise ValueError('Unreviewed constant self APPLY_AURA semantics')
|
|
integer(effect[2],-0x1000000,0xffffff,'source amount')
|
|
integer(effect[7],0,4 if effect[1]==137 else 0,'source aura parameter')
|
|
active.append(index)
|
|
if not active:raise ValueError('No reviewed constant self aura')
|
|
for key in ('description','auraDescription'):
|
|
for token in re.findall(r'\$[^\s.,%;:!?()]*',row[key]):
|
|
if token=='$d' and not passive:continue
|
|
if not re.fullmatch(r'\$s[123]',token) or int(token[2])-1 not in active:raise ValueError('Unsupported source description token')
|
|
return passive
|
|
|
|
|
|
def constant_source_spell(dbc,row,offsets):
|
|
validate_constant_source(row);raw=dbc.by_id.get(row['entry'])
|
|
if raw is None:raise ValueError('Source constant-self spell absent')
|
|
allowed={0,1,6,7,8,9,10,11,18,19,20,25,30,36,58,59,60,115,116,117,
|
|
offsets['StartRecoveryCategory'],offsets['StartRecoveryTime']}
|
|
allowed.update(range(120,156))
|
|
effect_fields=('Effect','EffectDieSides','EffectBaseDice','EffectDicePerLevel',
|
|
'EffectRealPointsPerLevel','EffectBasePoints','ImplicitTargetA','ImplicitTargetB',
|
|
'EffectAura','EffectMiscValue','EffectTriggerSpell','EffectChainAmplitude')
|
|
for name in effect_fields:allowed.update(range(offsets[name],offsets[name]+3))
|
|
if any(value and index not in allowed for index,value in enumerate(raw)):raise ValueError('Unreviewed constant-self source dependency')
|
|
for key,field in [('name','Name_lang'),('nameSubtext','NameSubtext_lang'),('description','Description_lang'),('auraDescription','AuraDescription_lang')]:
|
|
if row[key]!=dbc.string(raw[offsets[field]]):raise ValueError('Server/source text differs')
|
|
expected=dict(attributes=[raw[offsets[key]] for key in ('Attributes','AttributesEx','AttributesExB','AttributesExC','AttributesExD')],
|
|
school=raw[1],castingTimeIndex=raw[18],durationIndex=raw[30],rangeIndex=raw[36],speed=0,
|
|
equippedItem=[struct.unpack('<i',struct.pack('<I',raw[58]))[0],raw[59],raw[60]],spellIconId=raw[117],visuals=[raw[115],raw[116]])
|
|
if any(row.get(key)!=value for key,value in expected.items()):raise ValueError('Server/source constant-self metadata differs')
|
|
condition_fields=dict(stances='ShapeshiftMask',stancesNot='ShapeshiftExclude',targets='Targets',targetCreatureType='TargetCreatureType',requiresSpellFocus='RequiresSpellFocus',casterAuraState='CasterAuraState',targetAuraState='TargetAuraState',procFlags='ProcFlags',procChance='ProcChance',procCharges='ProcCharges',interruptFlags='InterruptFlags',auraInterruptFlags='AuraInterruptFlags',channelInterruptFlags='ChannelInterruptFlags')
|
|
if any(row['conditions'][key]!=raw[offsets[field]] for key,field in condition_fields.items()):raise ValueError('Server/source self-aura conditions differ')
|
|
for key,field in [('recoveryTime','RecoveryTime'),('categoryRecoveryTime','CategoryRecoveryTime'),('startRecoveryCategory','StartRecoveryCategory'),('startRecoveryTime','StartRecoveryTime')]:
|
|
if row['timing'][key]!=raw[offsets[field]]:raise ValueError('Server/source cooldown/GCD differs')
|
|
for index,effect in enumerate(row['effects']):
|
|
for position,field in enumerate(('Effect','EffectAura','EffectBasePoints','EffectBaseDice','EffectDieSides','EffectDicePerLevel','EffectRealPointsPerLevel','EffectMiscValue','ImplicitTargetA','ImplicitTargetB','EffectTriggerSpell')):
|
|
bits=raw[offsets[field]+index];value=struct.unpack('<f' if position in (5,6) else '<i',struct.pack('<I',bits))[0]
|
|
if effect[position]!=value:raise ValueError('Server/source constant aura effect differs')
|
|
chain=struct.unpack('<f',struct.pack('<I',raw[offsets['EffectChainAmplitude']+index]))[0]
|
|
# This family has no chain targets or triggered effects. The source
|
|
# constant critical auras use zero here; their flat aura magnitude is
|
|
# BasePoints + BaseDice, not a chained damage multiplier.
|
|
if chain not in ((0,1) if effect[0] else (0,)):raise ValueError('Unreviewed source chain amplitude')
|
|
return deepcopy(row)
|
|
|
|
|
|
def constant_children(native,src):
|
|
review=[];ident=src['entry']
|
|
for table in tuple(CHILD_NEUTRAL)+CHILD_UNREVIEWED:
|
|
rows=native.get(table)
|
|
selected=[] if rows is None else [row for row in rows if row.get('SpellID')==ident]
|
|
if table=='SpellShapeshift':
|
|
expected=dict(SpellID=ident,StanceBarOrder=0,ShapeshiftExclude=[src['conditions']['stancesNot'],0],ShapeshiftMask=[src['conditions']['stances'],0])
|
|
if src['conditions']['stances'] and len(selected)!=1:raise ValueError('Positive native stance constraint required')
|
|
elif table in CHILD_UNREVIEWED:
|
|
if selected:raise ValueError('Positive native child requires semantic review: '+table)
|
|
expected={}
|
|
else:
|
|
expected=dict(CHILD_NEUTRAL[table],SpellID=ident)
|
|
if table=='SpellCooldowns':expected.update(RecoveryTime=src['timing']['recoveryTime'],CategoryRecoveryTime=src['timing']['categoryRecoveryTime'],StartRecoveryTime=src['timing']['startRecoveryTime'])
|
|
if table=='SpellCategories':expected['StartRecoveryCategory']=src['timing']['startRecoveryCategory']
|
|
if table=='SpellAuraOptions' and selected:expected['ProcChance']=selected[0].get('ProcChance');integer(expected['ProcChance'],0,255,'native chance')
|
|
if table in ('SpellCooldowns','SpellCategories') and any(src['timing'].values()) and len(selected)!=1:raise ValueError('Positive native cooldown/GCD context required')
|
|
for row in selected:
|
|
if set(row)!={'ID'}|set(expected) or any(row[key]!=value for key,value in expected.items()):raise ValueError('Native conditional/timing child differs: '+table)
|
|
review.append(dict(table=table,status='positive-source-equivalent-retained' if selected else 'reference-not-exported' if rows is None else 'no-positive-row-in-reference-export',ids=[row['ID'] for row in selected],actual_absence_verified=False))
|
|
visuals=[row for row in native.get('SpellXSpellVisual',[]) if row.get('SpellID')==ident]
|
|
if any(src['visuals']):
|
|
if len(visuals)!=1 or visuals[0].get('SpellVisualID',0)<=0 or any(visuals[0].get(key)!=0 for key in ('DifficultyID','Flags2','SpellIconFileID','ActiveIconFileID','ViewerUnitConditionID','ViewerPlayerConditionID','CasterUnitConditionID','CasterPlayerConditionID')) or visuals[0].get('Probability')!=1:raise ValueError('Positive unconditional same-spell visual link required')
|
|
elif visuals:raise ValueError('Unreviewed native visual on visual-free source')
|
|
return review,deepcopy(visuals)
|
|
|
|
|
|
def constant_component(sources,native,schemas,maxima,registry,*,known,race,cls,source_abilities,source_skills,source_icons,target_icon_names):
|
|
registry=deepcopy(registry);occupied={row['ID'] for row in native['SpellEffect']};registry_values(registry,maxima['SpellEffect'],occupied)
|
|
records=[];verification=[]
|
|
for src in sorted(sources,key=lambda row:row['entry']):
|
|
passive=validate_constant_source(src);ident=src['entry']
|
|
if ident not in known:raise ValueError('Selected spell is not genuinely known')
|
|
link=racial_link(source_abilities,source_skills,ident,race,cls);sla=verify_skill_link(link,native,source_skills,native['SkillLine'])
|
|
name=one(native['SpellName'],lambda row:row['ID']==ident,'SpellName');text=one(native['Spell'],lambda row:row['ID']==ident,'Spell');misc=one(native['SpellMisc'],lambda row:row['SpellID']==ident,'SpellMisc')
|
|
if name['Name_lang']!=src['name']:raise ValueError('Same-ID spell name collision')
|
|
attrs=misc['Attributes']
|
|
if (attrs[:5]!=src['attributes'] or any(value for i,value in enumerate(attrs[5:],5) if i!=15) or attrs[15]&~0x2000 or
|
|
misc['DifficultyID']!=0 or misc['SchoolMask']!=1 or misc['CastingTimeIndex']!=1 or misc['RangeIndex']!=1 or
|
|
misc['DurationIndex'] not in ((0,21) if passive else (18,)) or any(misc[key] for key in ('Speed','PvPDurationIndex','LaunchDelay','MinDuration','ActiveIconFileDataID','ContentTuningID','ShowFutureSpellPlayerConditionID','SpellVisualScript','ActiveSpellVisualScript'))):raise ValueError('Unreviewed native constant-self Misc dependency')
|
|
icon=source_icons.by_id.get(src['spellIconId']);names=target_icon_names.get(misc['SpellIconFileDataID'],[])
|
|
if icon is None or not names or any(normalize_icon(value)['stem']!=normalize_icon(source_icons.string(icon[1]),source=True)['stem'] for value in names):raise ValueError('Same-spell icon reference differs')
|
|
child_review,visuals=constant_children(native,src)
|
|
equipment=[row for row in native['SpellEquippedItems'] if row['SpellID']==ident]
|
|
if any((row['EquippedItemClass'],row['EquippedItemSubclass'],row['EquippedItemInvTypes'])!=(-1,0,0) for row in equipment):raise ValueError('Native equipment restriction differs')
|
|
effects=[row for row in native['SpellEffect'] if row['SpellID']==ident];indices={i for i,effect in enumerate(src['effects']) if effect[0]}
|
|
if not effects or len({row['EffectIndex'] for row in effects})!=len(effects):raise ValueError('Positive unambiguous native effect definitions required')
|
|
for table,rows in [('SpellName',[name]),('Spell',[text]),('SpellMisc',[misc]),('SpellEffect',effects),('SpellEquippedItems',equipment),('SkillLineAbility',[sla])]:
|
|
for row in rows:
|
|
encode(row,schemas[table])
|
|
integer(row['ID'],1,maxima[table],'positive native baseline ID')
|
|
neutral={key:value for key,value in NEW_EFFECT_NEUTRAL.items() if key!='EffectBonusCoefficient'}
|
|
for row in effects:
|
|
index=row['EffectIndex']
|
|
if index not in indices or row['EffectAura']!=src['effects'][index][1] or row['EffectBonusCoefficient'] not in (0,1) or any(row[key]!=value for key,value in neutral.items()):raise ValueError('Native constant-self effect context differs')
|
|
source_misc=src['effects'][index][7];expected_misc=[source_misc,(1<<source_misc) if row['EffectAura']==137 else 0]
|
|
if row['EffectMiscValue']!=expected_misc:raise ValueError('Native aura parameter semantics differ')
|
|
changes=[('Spell',text,dict(text,NameSubtext_lang=src['nameSubtext'],Description_lang=src['description'],AuraDescription_lang=src['auraDescription'])),('SpellMisc',misc,dict(misc,DurationIndex=src['durationIndex']))]
|
|
for index in sorted(indices):
|
|
old=next((row for row in effects if row['EffectIndex']==index),None);new=deepcopy(old if old is not None else min(effects,key=lambda row:row['EffectIndex']));effect=src['effects'][index]
|
|
if old is None:new['ID']=allocate(registry,ident,index,maxima['SpellEffect'],occupied)
|
|
new.update(EffectIndex=index,EffectAura=effect[1],EffectBasePointsF=effect[2]+effect[3],EffectBonusCoefficient=0,EffectMiscValue=[effect[7],1<<effect[7] if effect[1]==137 else 0])
|
|
changes.append(('SpellEffect',old,new))
|
|
for table,old,new in changes:
|
|
wire=encode(new,schemas[table])
|
|
if old==new:continue
|
|
records.append(dict(table_name=table,table_hash=hex(TABLES[table][0]),id=new['ID'],record=new,wire_hex=wire.hex(),sha256=hashlib.sha256(wire).hexdigest(),source_spell_id=ident,source_effect_index=new.get('EffectIndex'),baseline_record_sha256=canonical_sha256(old) if old else None,changed_fields=sorted(key for key in new if old is None or old[key]!=new[key]),preserved_native_fields=sorted(key for key in new if old and old[key]==new[key]),allocation_policy='same-spell-positive-native-effect-clone' if old is None else 'same-ID-source-authoritative-override'))
|
|
verification.append(dict(spell_id=ident,source_record_sha256=canonical_sha256(src),retained_spell_name_id=ident,retained_skill_line_ability_id=sla['ID'],source_effect_indices=sorted(indices),source_aura_semantics=[CONSTANT_AURAS[src['effects'][i][1]] for i in sorted(indices)],authoritative_conditions=deepcopy(src['conditions']),authoritative_timing=deepcopy(src['timing']),source_legacy_visual_ids=src['visuals'],retained_native_visual_links=visuals,native_child_reference_review=child_review,preserved_misc_attributes=attrs,engine_accepted=False,gameplay_verified=False))
|
|
return dict(kind='source-passive-spell-component',schema_version=1,build=BUILD,schema=SCHEMA,id_remapping=False,definition_policy=CONSTANT_POLICY,records=records,spells=verification,child_id_registry=registry,engine_accepted=False,gameplay_verified=False,complete_native_dependency_absence_verified=False,mechanic_classification=CONSTANT_AURAS,coverage_scope='Selected genuine known-spell IDs and authoritative racial links; no race-specific ID allowlist and no all-race gameplay verification.',limitations=['Separate reviewed resource-free constant self-aura family; does not broaden the unconditional passive policy.','Positive same-spell cooldown, GCD, stance and visual contexts are retained; no raw legacy visual is written into another namespace.','Source137 stat index is represented by native MiscValueB bitmask; zero would incorrectly mean all native stats.','Source server remains authoritative; metadata encoding does not attest aura application, critical results or UI statistics.'])
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
for name in ('source', 'known', 'observed-inventory', 'source-spell', 'source-abilities',
|
|
'source-skills', 'source-icons', 'listfile', 'registry', 'output'):
|
|
parser.add_argument('--' + name, type=Path, required=True)
|
|
parser.add_argument('--ids', required=True, help='Explicit comma-separated subset of genuinely known racial spells')
|
|
parser.add_argument('--race', type=int, required=True); parser.add_argument('--class', dest='cls', type=int, required=True)
|
|
parser.add_argument('--native', type=Path, default=ROOT / 'build/data-comparison')
|
|
parser.add_argument('--child-native', type=Path, help='Optional additional filtered child reference exports')
|
|
parser.add_argument('--new-definitions', action='store_true', help='Explicit unverified neutral new-passive candidate policy')
|
|
parser.add_argument('--constant-self-auras', action='store_true', help='Separate positive same-spell constant active/stat/regen aura policy')
|
|
parser.add_argument('--server-raw', type=Path, help='Pinned current spell_template rows for the constant-self policy')
|
|
parser.add_argument('--new-icon-ids', type=Path, help='Explicit JSON source spell ID to reviewed icon FileDataID map')
|
|
parser.add_argument('--icon-assets', type=Path, help='Existing actual CASC asset manifest; required for new definitions')
|
|
parser.add_argument('--icon-root', type=Path, help='Existing private runtime asset root; required for new definitions')
|
|
parser.add_argument('--before-api', type=Path, help='Recorded original native spell API availability before new definitions')
|
|
parser.add_argument('--equipped', type=Path, required=True)
|
|
parser.add_argument('--db2', type=Path, default=ROOT.parent / 'servers/trinity-forever/install/bin/dbc/enUS')
|
|
parser.add_argument('--dbd', type=Path, default=ROOT.parent / 'tools/WoWDBDefs/definitions')
|
|
args = parser.parse_args()
|
|
inputs = {}
|
|
def load(path, limit=128 * 1024 * 1024, decode=True):
|
|
path, raw, digest = read_input(path, limit)
|
|
inputs[str(path)] = (path, limit, digest)
|
|
return json.loads(raw) if decode else raw
|
|
try:
|
|
if args.new_definitions and args.constant_self_auras:
|
|
raise ValueError('Definition policies are mutually exclusive')
|
|
if bool(args.server_raw) != args.constant_self_auras:
|
|
raise ValueError('Constant self auras require current server raw evidence')
|
|
implementations = {name: load(Path(__file__).with_name(name), 1048576, False)
|
|
for name in ('spell_passive_compat.py', 'spell_content_compare.py', 'turtle_data.py',
|
|
'octo_client_data.py', 'item_icon_preflight.py')}
|
|
new_options = {}
|
|
if args.new_definitions:
|
|
if not args.new_icon_ids or not args.icon_assets or not args.icon_root or not args.before_api:
|
|
raise ValueError('New definitions require explicit icon IDs, assets and recorded before API evidence')
|
|
if args.icon_root.is_symlink() or not args.icon_root.is_dir() or not args.icon_root.resolve().is_relative_to(ROOT / 'runtime'):
|
|
raise ValueError('Require an existing private runtime icon root')
|
|
asset_root = args.icon_root.resolve()
|
|
def read_icon(path):
|
|
relative = normalize_icon(path)['path']
|
|
selected_path = asset_root / relative
|
|
if (selected_path.resolve() != selected_path or
|
|
not selected_path.resolve().is_relative_to(asset_root)):
|
|
raise ValueError('Linked/escaped icon asset is unsupported')
|
|
return load(selected_path, 4194304, False)
|
|
new_options = dict(new_definitions=True,
|
|
new_icon_ids=load(args.new_icon_ids, 1048576),
|
|
icon_assets=load(args.icon_assets, 1048576), read_icon=read_icon)
|
|
if (not isinstance(new_options['new_icon_ids'], dict) or
|
|
not 1 <= len(new_options['new_icon_ids']) <= 128 or
|
|
any(not isinstance(key, str) or not re.fullmatch(r'[1-9][0-9]*', key)
|
|
for key in new_options['new_icon_ids'])):
|
|
raise ValueError('Bounded source-spell icon mapping required')
|
|
implementations['item_batch_stage.py'] = load(Path(__file__).with_name('item_batch_stage.py'), 1048576, False)
|
|
elif args.new_icon_ids or args.icon_assets or args.icon_root or args.before_api:
|
|
raise ValueError('New-definition icon arguments require explicit --new-definitions')
|
|
if args.constant_self_auras:
|
|
new_options['constant_self_auras'] = True
|
|
inventory = load(args.observed_inventory)
|
|
dbc = DBC(args.source_spell, 173); load(args.source_spell, 64 * 1024 * 1024, False)
|
|
context = _observed_context(dbc, inventory, 'enUS')
|
|
source_dbd = load(args.dbd / 'Spell.dbd', 1048576, False)
|
|
offsets = spell_layout()
|
|
reviewed_columns(source_dbd, hashlib.sha256(source_dbd).hexdigest(), offsets)
|
|
abilities = DBC(args.source_abilities, 15); skills = DBC(args.source_skills, 22); icons = DBC(args.source_icons, 2)
|
|
for path in (args.source_abilities, args.source_skills, args.source_icons):
|
|
load(path, 64 * 1024 * 1024, False)
|
|
source = load(args.source, 1048576)
|
|
known = load(args.known, 1048576)
|
|
if not isinstance(known, list) or len(known) != 1 or not isinstance(known[0].get('known'), list):
|
|
raise ValueError('Require one recorded genuine known-spell snapshot')
|
|
if known[0].get('cls') != args.cls:
|
|
raise ValueError('Source class differs from genuine known-spell snapshot')
|
|
selected = [integer(int(value), 1, 0x7fffffff, 'selected spell') for value in args.ids.split(',')]
|
|
if len(set(selected)) != len(selected):
|
|
raise ValueError('Duplicate selected spell')
|
|
before_api = load(args.before_api, 1048576) if args.new_definitions else None
|
|
if args.new_definitions and (not isinstance(before_api, dict) or any(
|
|
not isinstance(before_api.get(str(ident)), dict) or any(
|
|
before_api[str(ident)].get(key) != 'nil'
|
|
for key in ('infoStatus', 'nameStatus', 'descriptionStatus')) for ident in selected)):
|
|
raise ValueError('Require observed unavailable original native APIs for selected new spells')
|
|
source = [(constant_source_spell if args.constant_self_auras else source_spell)(dbc, one(source, lambda r: r['entry'] == ident, 'server spell'), offsets) for ident in selected]
|
|
if args.constant_self_auras:
|
|
server_raw = load(args.server_raw, 1048576)
|
|
for src in source:
|
|
raw = one(server_raw, lambda row: row['entry'] == src['entry'], 'current server raw row')
|
|
if constant_server_row(raw) != src:
|
|
raise ValueError('Current server evidence differs from normalized source')
|
|
native, schemas, maxima, metadata = {}, {}, {}, {}
|
|
for table, (table_hash, layout, _) in TABLES.items():
|
|
path = args.equipped if table == 'SpellEquippedItems' else args.native / (table + '.json')
|
|
native[table] = load(path)
|
|
schemas[table] = fields(args.dbd / (table + '.dbd'), table)
|
|
maxima[table] = db2_header(args.db2 / (table + '.db2'), table_hash, layout)
|
|
for pinned in (args.dbd / (table + '.dbd'), args.db2 / (table + '.db2')):
|
|
load(pinned, 128 * 1024 * 1024, False)
|
|
metadata[table] = dict(table_hash=hex(table_hash), layout_hash=hex(layout), max_id=maxima[table],
|
|
dbd_sha256=inputs[str(args.dbd / (table + '.dbd'))][2], db2_sha256=inputs[str(args.db2 / (table + '.db2'))][2],
|
|
baseline_sha256=inputs[str(path)][2], serialized_field_sha256=TABLES[table][2])
|
|
native['SkillLine'] = load(args.native / 'SkillLine.json')
|
|
for table in tuple(CHILD_NEUTRAL) + CHILD_UNREVIEWED:
|
|
filtered = args.child_native / (table + '.json') if args.child_native else None
|
|
path = filtered if filtered is not None and filtered.exists() else args.native / (table + '.json')
|
|
if path.exists():
|
|
native[table] = load(path)
|
|
# These rows are reference evidence only, not serialized by
|
|
# this component. Preserve exact definition/data provenance.
|
|
load(args.db2 / (table + '.db2'), 128 * 1024 * 1024, False)
|
|
load(args.dbd / (table + '.dbd'), 1048576, False)
|
|
if args.constant_self_auras:
|
|
path = (args.child_native or args.native) / 'SpellXSpellVisual.json'
|
|
native['SpellXSpellVisual'] = load(path)
|
|
load(args.db2 / 'SpellXSpellVisual.db2', 128 * 1024 * 1024, False)
|
|
load(args.dbd / 'SpellXSpellVisual.dbd', 1048576, False)
|
|
for table, (table_hash, layout) in DEPENDENCIES.items():
|
|
rows = load(args.native / (table + '.json'))
|
|
db2_header(args.db2 / (table + '.db2'), table_hash, layout)
|
|
load(args.db2 / (table + '.db2'), 128 * 1024 * 1024, False)
|
|
ids = sorted({src['durationIndex'] for src in source}) if table == 'SpellDuration' else [1]
|
|
for ident in ids:
|
|
row = one(rows, lambda r: r['ID'] == ident, table)
|
|
expected = {'SpellCastTimes': dict(Base=0, Minimum=0),
|
|
'SpellDuration': dict(Duration=20000 if ident == 18 else -1, MaxDuration=20000 if ident == 18 else -1, DurationPerResource=0),
|
|
'SpellRange': dict(RangeMin=[0, 0], RangeMax=[0, 0], Flags=0)}[table]
|
|
if any(row.get(key) != value for key, value in expected.items()):
|
|
raise ValueError('Reviewed source/native dependency differs: ' + table)
|
|
listfile = load(args.listfile, 256 * 1024 * 1024, False).decode('utf-8')
|
|
wanted = (set(new_options['new_icon_ids'].values()) if args.new_definitions else
|
|
{r['SpellIconFileDataID'] for r in native['SpellMisc'] if r['SpellID'] in selected})
|
|
for fid in wanted:
|
|
integer(fid, 1, 0x7fffffff, 'explicit icon FileDataID')
|
|
names = {}
|
|
for line in listfile.splitlines():
|
|
match = re.fullmatch(r'(\d+);(.+)', line)
|
|
if match and int(match[1]) in wanted and match[2].lower().endswith('.blp'):
|
|
names.setdefault(int(match[1]), []).append(match[2])
|
|
result = component(source, native, schemas, maxima, load(args.registry, 1048576),
|
|
known=known[0]['known'], race=args.race, cls=args.cls, source_abilities=abilities,
|
|
source_skills=skills, source_icons=icons, target_icon_names=names, **new_options)
|
|
result.update(source_context=context, native_tables=metadata,
|
|
selected_source_snapshot=dict(guid=known[0].get('guid'), seq=known[0].get('seq'),
|
|
active_at_save=known[0].get('active_at_save'), race=args.race, cls=args.cls),
|
|
input_sha256={path: pin[2] for path, pin in sorted(inputs.items())},
|
|
tool_sha256=hashlib.sha256(implementations['spell_passive_compat.py']).hexdigest(),
|
|
implementation_sha256={name: hashlib.sha256(raw).hexdigest() for name, raw in implementations.items()},
|
|
source_roles=dict(spell='observed-Octo-file-content; loader-profile scope retained in source_context',
|
|
server='recorded-current-local-spell_template metadata and complete reviewed condition/proc subset; exported fields verified',
|
|
racial_links_skills_icons='pinned-installed-Turtle-reference; effective-Octo-selection not asserted'),
|
|
semantic_evidence=dict(
|
|
source_amount='tortoise-wow/src/game/Objects/Object.cpp WorldObject::CalculateSpellDamage:4389-4471',
|
|
source_skill='tortoise-wow/src/game/Spells/SpellAuras.cpp Aura::HandleAuraModSkill:2716',
|
|
source_reputation='tortoise-wow/src/game/Objects/Player.cpp Player::CalculateReputationGain:7846',
|
|
unused_source_damage_coefficient='tortoise-wow/src/game/Objects/Object.cpp WorldObject::SpellBonusWithCoeffs:5094',
|
|
target_constant_value='trinity-forever/src/server/game/Spells/SpellInfo.cpp SpellEffectInfo::CalcValue:521'))
|
|
if args.new_definitions:
|
|
result['preinstallation_native_api'] = dict(
|
|
input_sha256=inputs[str(args.before_api)][2], observed_unavailable=sorted(selected),
|
|
actual_record_absence_proven=False)
|
|
if args.constant_self_auras:
|
|
result['semantic_evidence'].update(
|
|
source_stealth_detection='tortoise-wow/src/game/Objects/Unit.cpp Unit::IsVisibleForOrDetect:7222; SPELL_AURA_MOD_STEALTH_DETECT17',
|
|
source_physical_critical='tortoise-wow/src/game/Spells/SpellAuras.cpp Aura::HandleAuraModCritPercent:5036; unrestricted equipment applies melee and ranged',
|
|
source_spell_critical='tortoise-wow/src/game/Spells/SpellAuras.cpp Aura::HandleModSpellCritChance:5093; private server spell-critical calculation',
|
|
source_total_stat='tortoise-wow/src/game/Spells/SpellAuras.cpp Aura::HandleModTotalPercentStat:4748; source MiscValue is stat index',
|
|
target_total_stat='trinity-forever/src/server/game/Spells/Auras/SpellAuraEffects.cpp AuraEffect::HandleModTotalPercentStat:3894; MiscValueB is bitmask, zero means all stats',
|
|
target_critical='trinity-forever/src/server/game/Spells/Auras/SpellAuraEffects.cpp:4411-4436; weapon and spell critical handlers',
|
|
source_target_mana_regen='source and destination SpellAuraDefines/SpellAuras handlers retain SPELL_AURA_MOD_MANA_REGEN_INTERRUPT134',
|
|
retained_constraints='positive same-ID SpellCategories, SpellCooldowns, SpellShapeshift and SpellXSpellVisual reference exports; no source visual-ID namespace conversion')
|
|
for path, limit, digest in inputs.values():
|
|
if read_input(path, limit)[2] != digest:
|
|
raise ValueError('Input changed before publication')
|
|
result['second_input_pass_verified'] = True
|
|
absolute = args.output.absolute()
|
|
if (not absolute.is_relative_to(ROOT / 'runtime') or args.output.exists() or
|
|
args.output.is_symlink() or absolute.parent.resolve() != absolute.parent):
|
|
raise ValueError('Require new workspace runtime output')
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
with args.output.open('x') as stream:
|
|
json.dump(result, stream, sort_keys=True, indent=2, allow_nan=False); stream.write('\n')
|
|
print(json.dumps(dict(kind=result['kind'], spells=len(result['spells']), records=len(result['records']),
|
|
engine_accepted=False, gameplay_verified=False)))
|
|
return 0
|
|
except (ValueError, KeyError, TypeError, OSError, UnicodeError) as error:
|
|
print(json.dumps(dict(status='passive-component-rejected', reason=str(error))))
|
|
return 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|
|
|
|
|
|
def source_profession_link_removals(source_abilities,source_spells,native,published,skill_lines,schema):
|
|
"""Cull only profession associations whose spell is absent from source data.
|
|
|
|
Preserve every shared Spell definition and all source-positive associations.
|
|
A missing source-only recipe remains a dependency, never a fabricated spell.
|
|
"""
|
|
if source_abilities.fields!=15 or source_spells.fields!=173 or canonical_sha256(schema)!=TABLES['SkillLineAbility'][2]:raise ValueError('Reviewed source/native profession ability schemas required')
|
|
skills={integer(v,1,32767,'source profession skill')for v in skill_lines}
|
|
if not 1<=len(skills)<=32:raise ValueError('Bounded explicit profession family required')
|
|
pairs={(r[1],r[2])for r in source_abilities.rows if r[1]in skills and r[2]}
|
|
source_ids=set(source_spells.by_id)
|
|
if any(not any(skill==v for skill,_ in pairs)for v in skills):raise ValueError('Source profession coverage missing')
|
|
effective={r['ID']:deepcopy(r)for r in native}
|
|
if len(effective)!=len(native):raise ValueError('Duplicate native profession association')
|
|
protected=set()
|
|
for row in published:
|
|
if row.get('table_name')!='SkillLineAbility':continue
|
|
if row.get('record_status','valid')=='valid':protected.add(row['id'])
|
|
if row.get('record_status','valid')=='removed':effective.pop(row['id'],None)
|
|
elif row['id']in effective:effective[row['id']]=dict(row['record'])
|
|
rows=[];counts={};deferred=[]
|
|
for skill in sorted(skills):
|
|
entries=[r for r in effective.values()if r['SkillLine']==skill]
|
|
foreign=[];retained=[]
|
|
for r in entries:
|
|
raw=encode(r,schema)
|
|
if r['ID']in protected or not r['Spell']or (skill,r['Spell'])in pairs or r['Spell']in source_ids:retained.append(r['ID']);continue
|
|
foreign.append(r['ID'])
|
|
rows.append(dict(table_name='SkillLineAbility',table_hash=hex(TABLES['SkillLineAbility'][0]),id=r['ID'],record_status='removed',record=None,wire_hex='',sha256=hashlib.sha256(b'').hexdigest(),baseline_record=r,baseline_record_sha256=hashlib.sha256(raw).hexdigest(),policy='source-owned-profession-ability-link-replacement-v1',source_skill_line=skill,source_spell_inventory_sha256=source_spells.digest(),source_ability_inventory_sha256=source_abilities.digest(),reason='destination-spell-absent-from-source-inventory'))
|
|
target_spells={r['Spell']for r in entries}
|
|
missing=sorted(spell for s,spell in pairs if s==skill and spell not in target_spells)
|
|
counts[str(skill)]=dict(source_associations=sum(s==skill for s,_ in pairs),native_associations=len(entries),foreign_removed=len(foreign),retained=len(retained),protected_published_associations=sum(r['ID']in protected for r in entries),source_only_associations=len(missing))
|
|
deferred.extend(dict(skill=skill,spell=spell,reason='source association lacks accessible native relationship; definition/requirements conversion still required')for spell in missing)
|
|
return dict(kind='source-profession-relationship-candidates',rows=rows,counts=counts,deferred=deferred,source_spell_inventory_sha256=source_spells.digest(),source_ability_inventory_sha256=source_abilities.digest(),installed=False,engine_accepted=False,gameplay_verified=False,
|
|
limits=['Only selected source snapshot membership; full archive precedence/live Octo equivalence unverified.','Remove associations, never shared spells or learned character state. Source-positive IDs retained even when their profession association differs.','Source-only abilities, recipe categories, reagents and requirements need their own conversion and real-client tests.'])
|