367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
512 lines
41 KiB
Python
512 lines
41 KiB
Python
"""Shared source/capture and neutral-child checks for item spell definitions.
|
|
|
|
These checks do not decide which mechanic is supported, grant known spells,
|
|
install data or infer absent native records. Each caller applies its own narrow
|
|
semantic validator after the complete source/capture comparison.
|
|
"""
|
|
import struct
|
|
from spell_passive_compat import constant_server_row,integer,CONDITIONS,CHILD_NEUTRAL
|
|
|
|
REQUIRED_REFERENCE_TABLES=('SpellName','Spell','SpellMisc','SpellEffect','SpellAuraOptions',
|
|
'SpellLevels','SpellCategories','SpellCooldowns','SpellClassOptions','SpellCastingRequirements',
|
|
'SpellInterrupts','SpellAuraRestrictions','SpellTargetRestrictions','SpellShapeshift',
|
|
'SpellReagents','SpellPower','SpellEquippedItems','SpellXSpellVisual')
|
|
|
|
|
|
def checked_constant_source(dbc,raw,offsets,*,family_namespace=None,proc_namespace_proof=None,item_haste_context=None,item_resistance_context=None,scripted_aura_context=None,extra_damage_context=None,passive_proc_presentation=None,flat_modifier_namespace=None,category_context=None,incoming_harmful_proc=False,reflection_context=None,skill_category_reference=None,set_modifier_context=None):
|
|
if type(incoming_harmful_proc)is not bool or incoming_harmful_proc and proc_namespace_proof is None:raise ValueError('Explicit incoming proc namespace required')
|
|
src=constant_server_row(raw);ident=integer(src['entry'],1,0x7fffffff,'restoration source ID')
|
|
known={'entry','name','nameSubtext','description','auraDescription','nameFlags','nameSubtextFlags','descriptionFlags','auraDescriptionFlags',
|
|
'attributes','attributesEx','attributesEx2','attributesEx3','attributesEx4','school','castingTimeIndex','durationIndex','rangeIndex','speed','spellIconId',
|
|
'equippedItemClass','equippedItemSubClassMask','equippedItemInventoryTypeMask','powerType','manaCost','manCostPerLevel','manaPerSecond','manaPerSecondPerLevel','manaCostPercentage',
|
|
'recoveryTime','categoryRecoveryTime','startRecoveryCategory','startRecoveryTime','spellVisual1','spellVisual2','spellLevel','baseLevel','maxLevel','spellPriority','stanceBarOrder',*CONDITIONS}
|
|
for prefix in('effect','effectApplyAuraName','effectBasePoints','effectBaseDice','effectDieSides','effectDicePerLevel','effectRealPointsPerLevel','effectMiscValue','effectImplicitTargetA','effectImplicitTargetB','effectTriggerSpell','effectBonusCoefficient','dmgMultiplier'):
|
|
known.update(prefix+str(i)for i in range(1,4))
|
|
if reflection_context is not None:
|
|
from spell_reflection_compat import validate_namespace
|
|
validate_namespace(reflection_context)
|
|
if category_context is None or any(v is not None for v in(item_haste_context,item_resistance_context,scripted_aura_context,extra_damage_context,passive_proc_presentation,flat_modifier_namespace)):
|
|
raise ValueError('Separate reviewed school-reflection context required')
|
|
known.add('dispel')
|
|
known.update('effectMultipleValue'+str(i) for i in range(1,4))
|
|
if skill_category_reference is not None:
|
|
from spell_item_static_compat import validate_skill_category_reference
|
|
validate_skill_category_reference(skill_category_reference)
|
|
if category_context is None or any(v is not None for v in(proc_namespace_proof,item_haste_context,item_resistance_context,scripted_aura_context,extra_damage_context,passive_proc_presentation,flat_modifier_namespace,reflection_context)):
|
|
raise ValueError('Separate categorized-skill source reference required')
|
|
known.add('category')
|
|
if set_modifier_context is not None:
|
|
from spell_set_modifier_compat import validate_namespace
|
|
validate_namespace(set_modifier_context)
|
|
if any(v is not None for v in(family_namespace,proc_namespace_proof,item_haste_context,item_resistance_context,scripted_aura_context,extra_damage_context,passive_proc_presentation,flat_modifier_namespace,category_context,reflection_context,skill_category_reference)):
|
|
raise ValueError('Separate all-class set modifier source context required')
|
|
known.update(('spellFamilyName','spellFamilyFlags'))
|
|
known.update('effectItemType'+str(i)for i in range(1,4))
|
|
if family_namespace is not None:known.update(('spellFamilyName','spellFamilyFlags'))
|
|
if category_context is not None:
|
|
validate_spell_category_namespace(category_context)
|
|
if any(v is not None for v in(item_haste_context,item_resistance_context,scripted_aura_context)):
|
|
raise ValueError('Distinct source category proof required')
|
|
known.update(('dmgClass','preventionType'))
|
|
if item_haste_context is not None:
|
|
from spell_item_haste_compat import validate_namespace
|
|
validate_namespace(item_haste_context)
|
|
known.update(('dmgClass','effectMultipleValue1','effectMultipleValue2','effectMultipleValue3'))
|
|
if item_resistance_context is not None:
|
|
from spell_item_resistance_compat import validate_namespace
|
|
validate_namespace(item_resistance_context)
|
|
known.update(('dmgClass','preventionType'))
|
|
if scripted_aura_context is not None:
|
|
from spell_scripted_aura_compat import validate_namespace
|
|
validate_namespace(scripted_aura_context)
|
|
known.update(('dmgClass','preventionType','script_name'))
|
|
if extra_damage_context is not None:
|
|
from spell_timed_buff_compat import validate_extra_damage_namespace
|
|
validate_extra_damage_namespace(extra_damage_context)
|
|
if any(v is not None for v in(proc_namespace_proof,item_haste_context,item_resistance_context,scripted_aura_context)):
|
|
raise ValueError('Composite direct effect policy is distinct from proc/static contexts')
|
|
known.add('dispel')
|
|
unknown=sorted(key for key,value in raw.items()if key not in known and value not in(0,0.0,'',None))
|
|
if unknown:raise ValueError('Unreviewed nonzero server restoration metadata: '+','.join(unknown[:8]))
|
|
src['levels']={key:raw[key]for key in('spellLevel','baseLevel','maxLevel')}
|
|
disk=dbc.by_id.get(ident)
|
|
if disk is None or len(disk)!=173 or disk[0]!=ident:raise ValueError('Pinned restoration DBC row missing or identity differs')
|
|
allowed={0,1,6,7,8,9,10,18,19,20,21,25,30,36,58,59,60,115,116,117,
|
|
*(offsets[k]for k in('MaxLevel','BaseLevel','SpellLevel','SpellPriority','StanceBarOrder','StartRecoveryCategory','StartRecoveryTime'))}
|
|
if category_context is not None:
|
|
for key,field,maximum in(('dmgClass','DefenseType',3),('preventionType','PreventionType',2)):
|
|
value=integer(raw.get(key),0,maximum,'source spell category')
|
|
if value!=disk[offsets[field]]:raise ValueError('Server/captured spell category differs')
|
|
allowed.add(offsets[field])
|
|
src.update(defense_type=raw['dmgClass'],prevention_type=raw['preventionType'],spell_category_context=category_context)
|
|
if skill_category_reference is not None:
|
|
category=integer(raw.get('category'),1,65535,'source skill spell category')
|
|
if category!=disk[offsets['Category']]or category!=skill_category_reference['source_category'][0]:
|
|
raise ValueError('Server/captured skill spell category differs')
|
|
allowed.add(offsets['Category'])
|
|
src.update(category_id=category,skill_category_reference=skill_category_reference)
|
|
if reflection_context is not None:
|
|
value=integer(raw.get('dispel'),0,1,'source school-reflection dispel')
|
|
if value!=disk[offsets['DispelType']]:raise ValueError('Server/captured school-reflection dispel differs')
|
|
allowed.add(offsets['DispelType'])
|
|
multipliers=[]
|
|
for i in range(3):
|
|
value_multiplier=raw.get('effectMultipleValue'+str(i+1))
|
|
captured=struct.unpack('<f',struct.pack('<I',disk[offsets['EffectAmplitude']+i]))[0]
|
|
if type(value_multiplier)not in(int,float)or value_multiplier not in(0,1)or value_multiplier!=captured:
|
|
raise ValueError('Server/captured reflection value multiplier differs')
|
|
multipliers.append(captured)
|
|
allowed.update(range(offsets['EffectAmplitude'],offsets['EffectAmplitude']+3))
|
|
src.update(dispel_type=value,reflection_context=reflection_context,effect_value_multipliers=multipliers)
|
|
if set_modifier_context is not None:
|
|
from spell_set_modifier_compat import captured_family
|
|
src['set_modifier_context']=set_modifier_context
|
|
src['class_family']=captured_family(raw,disk,offsets,set_modifier_context)
|
|
allowed.update((offsets['SpellClassSet'],offsets['SpellClassMask'],offsets['SpellClassMask']+1))
|
|
src['source_effect_affect_fallbacks']=[]
|
|
for index in range(3):
|
|
mask=integer(raw.get('effectItemType'+str(index+1)),0,0xffffffff,'source modifier affect fallback')
|
|
if mask!=disk[offsets['EffectItemType']+index]:raise ValueError('Server/captured modifier affect fallback differs')
|
|
src['source_effect_affect_fallbacks'].append(mask)
|
|
allowed.update(range(offsets['EffectItemType'],offsets['EffectItemType']+3))
|
|
if family_namespace is not None:
|
|
from spell_family_compat import captured_family
|
|
src['class_family']=captured_family(raw,disk,offsets,family_namespace)
|
|
allowed.update((offsets['SpellClassSet'],offsets['SpellClassMask'],offsets['SpellClassMask']+1))
|
|
if proc_namespace_proof is not None:
|
|
src['proc_context']=review_proc_conditions(raw,disk,offsets,proc_namespace_proof,damage_periodic=scripted_aura_context is not None,incoming_harmful=incoming_harmful_proc)
|
|
allowed.update(offsets[k]for k in('ProcFlags','ProcChance','ProcCharges'))
|
|
allowed.update(range(offsets['EffectTriggerSpell'],offsets['EffectTriggerSpell']+3))
|
|
if item_haste_context is not None:
|
|
import math
|
|
allowed.add(offsets['DefenseType']);allowed.update(range(offsets['EffectAmplitude'],offsets['EffectAmplitude']+3))
|
|
src['defense_type']=integer(raw.get('dmgClass'),0,3,'source damage class')
|
|
if src['defense_type']!=disk[offsets['DefenseType']]:raise ValueError('Server/captured item-haste defense class differs')
|
|
multipliers=[]
|
|
for i in range(3):
|
|
value=raw.get('effectMultipleValue'+str(i+1))
|
|
captured=struct.unpack('<f',struct.pack('<I',disk[offsets['EffectAmplitude']+i]))[0]
|
|
if type(value)not in(int,float)or not math.isfinite(value)or value!=captured:raise ValueError('Server/captured item-haste value multiplier differs')
|
|
multipliers.append(captured)
|
|
src.update(effect_value_multipliers=multipliers,item_haste_context=item_haste_context)
|
|
if item_resistance_context is not None:
|
|
allowed.update(offsets[k]for k in('DefenseType','PreventionType'))
|
|
for key,field in(('dmgClass','DefenseType'),('preventionType','PreventionType')):
|
|
value=integer(raw.get(key),0,3,'item-resistance category')
|
|
if value!=disk[offsets[field]]:raise ValueError('Server/captured item-resistance category differs')
|
|
src.update(defense_type=raw['dmgClass'],prevention_type=raw['preventionType'],item_resistance_context=item_resistance_context)
|
|
if scripted_aura_context is not None:
|
|
allowed.update(offsets[k]for k in('DefenseType','PreventionType'))
|
|
for key,field in(('dmgClass','DefenseType'),('preventionType','PreventionType')):
|
|
if integer(raw.get(key),0,3,'scripted aura category')!=disk[offsets[field]]:raise ValueError('Server/captured scripted aura category differs')
|
|
src.update(defense_type=raw['dmgClass'],prevention_type=raw['preventionType'],server_script=raw['script_name'],scripted_aura_context=scripted_aura_context)
|
|
if extra_damage_context is not None:
|
|
value=integer(raw.get('dispel'),1,1,'composite source Magic dispel')
|
|
if value!=disk[offsets['DispelType']]:raise ValueError('Server/captured composite dispel differs')
|
|
allowed.add(offsets['DispelType'])
|
|
src.update(dispel_type=value,extra_damage_context=extra_damage_context,effect_chain_amplitudes=[])
|
|
allowed.update(range(120,156))
|
|
effect_fields=('Effect','EffectDieSides','EffectBaseDice','EffectBasePoints','ImplicitTargetA','ImplicitTargetB','EffectAura','EffectMiscValue','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(disk)):raise ValueError('Unreviewed source restoration dependency')
|
|
passive_attributes=([192,0,0,0,0],)
|
|
if passive_proc_presentation is not None:
|
|
from spell_item_proc_compat import validate_presentation_namespace
|
|
validate_presentation_namespace(passive_proc_presentation)
|
|
if proc_namespace_proof is None:raise ValueError('Passive presentation requires genuine proc context')
|
|
passive_attributes=tuple([192|flags,0,0,0,0]for flags in(0,16,256,272))
|
|
if src['attributes']not in passive_attributes:raise ValueError('Unreviewed passive proc presentation attributes')
|
|
src['passive_proc_presentation']=passive_proc_presentation
|
|
stance_order_ok=raw['stanceBarOrder']==-1 and disk[offsets['StanceBarOrder']]==0xffffffff
|
|
if set_modifier_context is not None and not raw['stances'] and not raw['stancesNot'] and raw['stanceBarOrder']==0 and disk[offsets['StanceBarOrder']]==0:
|
|
stance_order_ok=True;src['set_modifier_default_stance_order']=0
|
|
if reflection_context is not None and src['attributes']==[0]*5 and not raw['stances'] and not raw['stancesNot'] and raw['stanceBarOrder']==0 and disk[offsets['StanceBarOrder']]==0:
|
|
# Captured non-stance reflectors retain the source's default zero.
|
|
stance_order_ok=True;src['reflection_default_stance_order']=0
|
|
if flat_modifier_namespace is not None:
|
|
from spell_flat_modifier_compat import validate_namespace
|
|
validate_namespace(flat_modifier_namespace)
|
|
if any(v is not None for v in(proc_namespace_proof,item_haste_context,item_resistance_context,scripted_aura_context,extra_damage_context,passive_proc_presentation)):raise ValueError('Separate permanent flat modifier source capture required')
|
|
src['flat_modifier_namespace']=flat_modifier_namespace
|
|
if src['attributes']==[192,0,0,0,0] and not raw['stances'] and not raw['stancesNot'] and raw['stanceBarOrder']==0 and disk[offsets['StanceBarOrder']]==0:
|
|
stance_order_ok=True;src['flat_modifier_default_stance_order']=0
|
|
if item_resistance_context is not None and src['attributes']==[128,0,0,0,0] and not raw['stances'] and not raw['stancesNot'] and raw['stanceBarOrder']==0 and disk[offsets['StanceBarOrder']]==0:
|
|
# Reviewed permanent on-equip resistance definitions have no stance
|
|
# binding; retain their actual default zero rather than inventing -1.
|
|
stance_order_ok=True;src['item_default_stance_order']=0
|
|
if proc_namespace_proof is not None and src['attributes']in passive_attributes and not raw['stances'] and not raw['stancesNot'] and raw['stanceBarOrder']==0 and disk[offsets['StanceBarOrder']]==0:
|
|
# Passive, non-stance source records can carry the default zero order.
|
|
# Retain that evidence; this does not add a stance/action-bar binding.
|
|
stance_order_ok=True;src['passive_default_stance_order']=0
|
|
if raw['spellPriority']not in(0,50)or raw['spellPriority']!=disk[offsets['SpellPriority']]or not stance_order_ok:raise ValueError('Unreviewed restoration priority/stance-bar context')
|
|
for key,field in(('name','Name_lang'),('nameSubtext','NameSubtext_lang'),('description','Description_lang'),('auraDescription','AuraDescription_lang')):
|
|
if src[key]!=dbc.string(disk[offsets[field]]):raise ValueError('Server/captured restoration text differs')
|
|
if src['attributes']!=[disk[offsets[n]]for n in('Attributes','AttributesEx','AttributesExB','AttributesExC','AttributesExD')]:raise ValueError('Server/captured restoration attributes differ')
|
|
for key,field in(('school','School'),('castingTimeIndex','CastingTimeIndex'),('durationIndex','DurationIndex'),('rangeIndex','RangeIndex'),('spellIconId','SpellIconID')):
|
|
if src[key]!=disk[offsets[field]]:raise ValueError('Server/captured restoration scalar differs: '+key)
|
|
for key,field in(('spellLevel','SpellLevel'),('baseLevel','BaseLevel'),('maxLevel','MaxLevel')):
|
|
if raw[key]!=disk[offsets[field]]:raise ValueError('Server/captured restoration level differs')
|
|
for key,field in(('recoveryTime','RecoveryTime'),('categoryRecoveryTime','CategoryRecoveryTime'),('startRecoveryCategory','StartRecoveryCategory'),('startRecoveryTime','StartRecoveryTime')):
|
|
if src['timing'][key]!=disk[offsets[field]]:raise ValueError('Server/captured restoration GCD 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(src['conditions'][key]!=disk[offsets[field]]for key,field in condition_fields.items()):raise ValueError('Server/captured restoration conditions differ')
|
|
if src['visuals']!=[disk[115],disk[116]]:raise ValueError('Server/captured restoration visual context differs')
|
|
for index,effect in enumerate(src['effects']):
|
|
for position,field in enumerate(('Effect','EffectAura','EffectBasePoints','EffectBaseDice','EffectDieSides','EffectDicePerLevel','EffectRealPointsPerLevel','EffectMiscValue','ImplicitTargetA','ImplicitTargetB','EffectTriggerSpell')):
|
|
bits=disk[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/captured restoration effect differs')
|
|
if extra_damage_context is not None:
|
|
chain=struct.unpack('<f',struct.pack('<I',disk[offsets['EffectChainAmplitude']+index]))[0]
|
|
if type(raw['dmgMultiplier'+str(index+1)])not in(int,float)or chain!=raw['dmgMultiplier'+str(index+1)]or chain not in(0,1):
|
|
raise ValueError('Server/captured composite chain amplitude differs')
|
|
src['effect_chain_amplitudes'].append(chain)
|
|
if not effect[0]:continue
|
|
if extra_damage_context is None and (disk[offsets['EffectChainAmplitude']+index]!=0x3f800000 or raw['dmgMultiplier'+str(index+1)]!=1):raise ValueError('Unreviewed restoration chain amplitude')
|
|
return src
|
|
|
|
|
|
def review_neutral_children(native,src):
|
|
from spell_family_compat import validate_family
|
|
categories=src.get('spell_category_context')
|
|
if categories is not None:validate_spell_category_namespace(categories)
|
|
# The existing source namespace already proves generic/Warrior identity
|
|
# with zero masks. A positive Warrior binding must be present and exact;
|
|
# it is not equivalent to an absent/generic class-options row.
|
|
family=validate_family(src.get('class_family'),warrior=True)
|
|
ident=src['entry'];review=[]
|
|
for table in REQUIRED_REFERENCE_TABLES[4:]:
|
|
selected=[r for r in native[table]if r.get('SpellID')==ident]
|
|
if table=='SpellLevels':continue # Explicit same-ID level correction below.
|
|
if table=='SpellXSpellVisual':
|
|
if any(src['visuals'])and len(selected)!=1:raise ValueError('Positive same-spell visual context required')
|
|
if not any(src['visuals'])and selected:raise ValueError('Unexpected native restorative visual')
|
|
for row in selected:
|
|
if row['DifficultyID']or row['Probability']!=1 or any(row[k]for k in('Flags2','SpellIconFileID','ActiveIconFileID','ViewerUnitConditionID','ViewerPlayerConditionID','CasterUnitConditionID','CasterPlayerConditionID')):raise ValueError('Conditional native restorative visual')
|
|
elif table=='SpellEquippedItems':
|
|
if any(r['EquippedItemClass']!=-1 for r in selected):raise ValueError('Native restorative equipment restriction')
|
|
elif table in('SpellTargetRestrictions','SpellShapeshift','SpellReagents','SpellPower'):
|
|
if selected:raise ValueError('Unreviewed positive restoration child: '+table)
|
|
else:
|
|
expected=dict(CHILD_NEUTRAL[table],SpellID=ident)
|
|
if table=='SpellClassOptions':
|
|
expected['SpellClassSet']=family
|
|
if family and len(selected)!=1:raise ValueError('Positive same-family restoration context required')
|
|
if table=='SpellAuraOptions':expected['ProcChance']=src['conditions']['procChance']
|
|
if table=='SpellCategories':
|
|
expected['StartRecoveryCategory']=src['timing']['startRecoveryCategory']
|
|
if src.get('skill_category_reference') is not None:
|
|
from spell_item_static_compat import validate_skill_category_reference
|
|
expected['Category']=validate_skill_category_reference(src['skill_category_reference'])
|
|
if len(selected)!=1:raise ValueError('Positive categorized-skill category reference required')
|
|
if categories is not None:
|
|
expected.update(DefenseType=src['defense_type'],PreventionType=src['prevention_type'])
|
|
if (src['defense_type']or src['prevention_type'])and len(selected)!=1:raise ValueError('Positive same-ID spell category required')
|
|
for row in selected:
|
|
if set(row)!={'ID'}|set(expected)or any(row[k]!=v for k,v in expected.items()):raise ValueError('Native restorative child differs: '+table)
|
|
review.append(dict(table=table,ids=[r['ID']for r in selected],actual_absence_verified=False))
|
|
return review
|
|
|
|
def review_proc_override_snapshot(snapshot,source_ids):
|
|
"""Retain local execution overrides before deciding a proc is convertible.
|
|
|
|
This is a provenance/coverage check, not a PPM, hit-result or family-mask
|
|
conversion. A base Spell.dbc row alone does not establish actual proc rules.
|
|
"""
|
|
from copy import deepcopy
|
|
columns={'entry','SchoolMask','SpellFamilyName','SpellFamilyMask0','SpellFamilyMask1','SpellFamilyMask2','procFlags','procEx','ppmRate','CustomChance','Cooldown'}
|
|
if not isinstance(source_ids,(list,tuple,set))or not 1<=len(source_ids)<=100000:raise ValueError('Bounded source proc identities required')
|
|
needed={integer(i,1,0xffffffff,'source proc identity')for i in source_ids}
|
|
if not isinstance(snapshot,dict)or snapshot.get('kind')!='local-source-proc-override-snapshot'or snapshot.get('table')!='tw_world.spell_proc_event'or snapshot.get('two_reads_equal')is not True or snapshot.get('database_modified')is not False:raise ValueError('Verified read-only source proc snapshot required')
|
|
ids=snapshot.get('source_spell_ids');names=snapshot.get('columns');rows=snapshot.get('rows')
|
|
if not isinstance(ids,list)or not 1<=len(ids)<=100000 or len({integer(i,1,0xffffffff,'snapshot proc identity')for i in ids})!=len(ids)or not needed.issubset(ids):raise ValueError('Complete source proc override coverage required')
|
|
if not isinstance(names,list)or len(names)!=len(columns)or any(not isinstance(n,str)for n in names)or set(names)!=columns:raise ValueError('Reviewed source proc override columns required')
|
|
if not isinstance(rows,list)or len(rows)>len(ids):raise ValueError('Bounded source proc override rows required')
|
|
selected=[];seen=set()
|
|
for row in rows:
|
|
if not isinstance(row,dict)or set(row)!=columns or any(type(v)not in(int,float,str)or isinstance(v,str)and not 1<=len(v)<=128 for v in row.values()):raise ValueError('Complete bounded public proc override row required')
|
|
# Preserve database numeric strings (including masks wider than32bits)
|
|
# without assigning destination semantics or silently narrowing values.
|
|
try:
|
|
from decimal import Decimal,InvalidOperation
|
|
values={k:Decimal(str(v))for k,v in row.items()}
|
|
except (InvalidOperation,ValueError):raise ValueError('Numeric source proc override fields required')
|
|
if any(not v.is_finite()or v<0 or v>0xffffffffffffffff for v in values.values()):raise ValueError('Finite bounded source proc override fields required')
|
|
if any(v!=v.to_integral_value()for k,v in values.items()if k not in('ppmRate','CustomChance')):raise ValueError('Integer source proc override masks required')
|
|
ident=integer(int(values['entry']),1,0xffffffff,'override row identity')
|
|
if ident not in ids or ident in seen:raise ValueError('Unknown/duplicate source proc override identity')
|
|
seen.add(ident)
|
|
if ident in needed:selected.append(deepcopy(row))
|
|
selected.sort(key=lambda r:int(r['entry']))
|
|
return dict(source_spell_ids=sorted(needed),rows=selected,override_row_ids=[int(r['entry'])for r in selected],overrides_absent=not selected,source_rules_converted=False,server_authoritative=True)
|
|
|
|
NEW_DEFINITION_CHILD_TABLES=('SpellMisc','SpellEffect','SpellEquippedItems','SpellClassOptions','SpellLevels')
|
|
|
|
def review_effect_shape(effect):
|
|
"""Typed source effect slots; bools/NaN cannot masquerade as numeric data."""
|
|
import math
|
|
if not isinstance(effect,list)or len(effect)!=12:raise ValueError('Complete typed source effect required')
|
|
for i in(0,1,2,3,4,7,8,9,10):integer(effect[i],-0x80000000,0x7fffffff,'source effect field')
|
|
for i in(5,6,11):
|
|
if type(effect[i])not in(int,float)or not math.isfinite(effect[i]):raise ValueError('Finite source effect coefficient required')
|
|
|
|
|
|
def review_existing_effect_range(base_points,die_sides,native):
|
|
"""Prove positive source tooltip endpoints against existing native variance.
|
|
|
|
Pinned source SpellMgr's generic $s formatter uses base+1..base+die.
|
|
Pinned target SpellEffectInfo::CalcValue applies base*(1 +/- abs(v*.5))
|
|
independently of effect family. Callers must separately prove matching
|
|
effect/aura enums and reject scaling/coefficient differences. No new roll,
|
|
effect definition, server amount or range is synthesized here.
|
|
"""
|
|
import math
|
|
if (type(base_points)is not int or type(die_sides)is not int or
|
|
not 1<die_sides<=0x7fffffff or not -1<=base_points<=0x7fffffff):
|
|
raise ValueError('Existing variable effect range differs')
|
|
mean=native.get('EffectBasePointsF');variance=native.get('Variance')
|
|
if type(mean)not in(int,float)or type(variance)not in(int,float)or not math.isfinite(mean)or not math.isfinite(variance):raise ValueError('Existing variable effect range differs')
|
|
low=base_points+1;high=base_points+die_sides;delta=abs(variance*.5)
|
|
if abs(mean*(1-delta)-low)>.01 or abs(mean*(1+delta)-high)>.01:raise ValueError('Existing variable effect range differs')
|
|
return dict(source_min=low,source_max=high,native_mean=mean,native_variance=variance)
|
|
|
|
def review_duration_reference(source_duration,native_rows,ident,*,native_id=None):
|
|
"""Match signed millisecond duration semantics, without level/resource scaling.
|
|
|
|
Source DurationPerLevel and destination DurationPerResource are different
|
|
concepts. Nonzero source scaling is deliberately unsupported.
|
|
"""
|
|
from spell_passive_compat import one
|
|
integer(ident,1,0x7fffffff,'source duration reference')
|
|
if native_id is None:native_id=ident
|
|
integer(native_id,1,0x7fffffff,'native duration reference')
|
|
row=source_duration.by_id.get(ident)
|
|
if not isinstance(row,(list,tuple))or len(row)!=4 or row[0]!=ident:raise ValueError('Complete source duration reference required')
|
|
words=[integer(v,0,0xffffffff,'source duration word')for v in row[1:]]
|
|
duration,per_level,maximum=[v if v<0x80000000 else v-0x100000000 for v in words]
|
|
if per_level or (duration,maximum)!=(-1,-1)and not 0<=duration<=maximum:raise ValueError('Unreviewed level-scaled or invalid source duration')
|
|
native=one(native_rows,lambda r:r['ID']==native_id,'duration reference')
|
|
if any(type(native.get(k))is not int or native[k]!=v for k,v in dict(Duration=duration,MaxDuration=maximum,DurationPerResource=0).items()):raise ValueError('Native duration semantics differ')
|
|
return dict(source_duration_id=ident,target_duration_id=native_id,duration_ms=duration,max_duration_ms=maximum,source_duration_per_level=0,target_duration_per_resource=0,permanent=duration==-1)
|
|
|
|
|
|
def review_new_timing(source_tables,native,duration):
|
|
"""Source-backed instant/self references; infinite and instant stay distinct."""
|
|
from spell_passive_compat import one
|
|
if duration not in(0,21):raise ValueError('Unreviewed new-definition duration')
|
|
checks=[('SpellCastTimes',1,(1,0,0,0))]
|
|
if duration:
|
|
if 'SpellDuration'not in source_tables or 'SpellDuration'not in native:raise ValueError('Duration references required')
|
|
review_duration_reference(source_tables['SpellDuration'],native['SpellDuration'],duration)
|
|
for table,ident,expected in checks:
|
|
if table not in source_tables or tuple(source_tables[table].by_id.get(ident,()))!=expected:raise ValueError('Source skill timing dependency differs: '+table)
|
|
row=source_tables['SpellRange'].by_id.get(1)
|
|
if row is None or len(row)!=22 or tuple(row[:4])!=(1,0,0,0):raise ValueError('Source skill range dependency differs')
|
|
checks=[('SpellCastTimes',1,dict(Base=0,Minimum=0)),('SpellRange',1,dict(RangeMin=[0,0],RangeMax=[0,0],Flags=0))]
|
|
if duration:checks.append(('SpellDuration',21,dict(Duration=-1,MaxDuration=-1,DurationPerResource=0)))
|
|
for table,ident,expected in checks:
|
|
row=one(native[table],lambda r:r['ID']==ident,'new definition '+table)
|
|
if any(row.get(k)!=v for k,v in expected.items()):raise ValueError('Native skill timing/range dependency differs: '+table)
|
|
|
|
def new_definition_records(src,effects,fid,schemas,maxima,registry,occupied,*,allocation_prefix):
|
|
"""Encode already-reviewed effects without racial/learned-state records.
|
|
|
|
Callers own mechanic validation, explicit reference absence, icons and timing.
|
|
This shared boundary owns source parent identities and stable child allocation.
|
|
"""
|
|
from copy import deepcopy
|
|
import hashlib
|
|
from octo_client_data import canonical_sha256
|
|
from spell_family_compat import validate_family
|
|
from spell_passive_compat import (TABLES,SUPPLEMENTAL_TABLES,NEW_MISC_NEUTRAL,
|
|
encode,new_registry_values)
|
|
if not isinstance(src.get('class_family'),dict):raise ValueError('Explicit source spell-family metadata required')
|
|
if src.get('set_modifier_context') is not None:
|
|
from spell_set_modifier_compat import validate_source,validate_family as set_modifier_family
|
|
validate_source(src);family=set_modifier_family(src['class_family'])
|
|
else:family=validate_family(src['class_family'],warrior=True)
|
|
ident=integer(src['entry'],1,0x7fffffff,'new source parent');integer(fid,1,0x7fffffff,'new definition icon')
|
|
if not isinstance(effects,dict)or set(effects)!={i for i,e in enumerate(src['effects'])if e[0]}or any(type(i)is not int or not 0<=i<=2 for i in effects):raise ValueError('Complete reviewed new effect slots required')
|
|
categories=src.get('spell_category_context')
|
|
tables=NEW_DEFINITION_CHILD_TABLES
|
|
if categories is not None:
|
|
validate_spell_category_namespace(categories)
|
|
integer(src.get('defense_type'),0,3,'new definition defense type')
|
|
integer(src.get('prevention_type'),0,2,'new definition prevention type')
|
|
tables+=('SpellCategories',)
|
|
if any('SpellCategories'not in v for v in(schemas,maxima,occupied)):
|
|
raise ValueError('Explicit spell category schema/allocation/reference review required')
|
|
if canonical_sha256(schemas['SpellCategories'])!=SUPPLEMENTAL_TABLES['SpellCategories'][2]:
|
|
raise ValueError('Reviewed spell category schema required')
|
|
def child_id(table,index=None):
|
|
key=f'{ident}:{index}'if table=='SpellEffect'else str(ident);entries=registry.setdefault(table,{})
|
|
if key not in entries:entries[key]=max([maxima[table]]+list(entries.values()))+1
|
|
new_registry_values(registry,maxima,occupied,tables=tables);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,DurationIndex=src['durationIndex'],SchoolMask=1<<src['school'])),
|
|
('SpellEquippedItems',dict(ID=child_id('SpellEquippedItems'),SpellID=ident,EquippedItemClass=src['equippedItem'][0],EquippedItemSubclass=src['equippedItem'][1],EquippedItemInvTypes=src['equippedItem'][2]))]
|
|
if family:rows.append(('SpellClassOptions',dict(ID=child_id('SpellClassOptions'),SpellID=ident,ModalNextSpell=0,SpellClassSet=family,SpellClassMask=[0]*4)))
|
|
if any(src['levels'].values()):rows.append(('SpellLevels',dict(CHILD_NEUTRAL['SpellLevels'],ID=child_id('SpellLevels'),SpellID=ident,SpellLevel=src['levels']['spellLevel'],BaseLevel=src['levels']['baseLevel'],MaxLevel=src['levels']['maxLevel'])))
|
|
if categories is not None:rows.append(('SpellCategories',dict(CHILD_NEUTRAL['SpellCategories'],ID=child_id('SpellCategories'),SpellID=ident,DefenseType=src['defense_type'],PreventionType=src['prevention_type'])))
|
|
for index in sorted(effects):rows.append(('SpellEffect',dict(deepcopy(effects[index]),ID=child_id('SpellEffect',index),SpellID=ident,EffectIndex=index)))
|
|
records=[]
|
|
for table,row in rows:
|
|
wire=encode(row,schemas[table]);records.append(dict(table_name=table,table_hash=hex((TABLES|SUPPLEMENTAL_TABLES)[table][0]),id=row['ID'],record=row,wire_hex=wire.hex(),sha256=hashlib.sha256(wire).hexdigest(),source_spell_id=ident,source_effect_index=row.get('EffectIndex'),baseline_record_sha256=None,allocation_policy=allocation_prefix+('-parent'if table in('Spell','SpellName')else'-child')))
|
|
return records
|
|
|
|
SPELL_CATEGORY_HEADERS={
|
|
'source':'fd1c65c0266b77a310c066bc3ccce86fe39f73a6cd10f67192d419009f95ead1',
|
|
'target':'9b0e2ad90eea77c961b00f1fc482e9d9e521aa85c58b63863a35d3a338a31799'}
|
|
|
|
|
|
def _spell_category_contract():
|
|
mappings=[]
|
|
for group,prefix,names in(('SpellDmgClass','SPELL_DAMAGE_CLASS_',('NONE','MAGIC','MELEE','RANGED')),
|
|
('SpellPreventionType','SPELL_PREVENTION_TYPE_',('NONE','SILENCE','PACIFY'))):
|
|
for value,name in enumerate(names):
|
|
mappings.append(dict(enum=group,source_name=prefix+name,target_name=prefix+name,source_value=value,target_value=value))
|
|
return dict(policy='named-source-spell-defense-and-prevention-v1',header_sha256=dict(SPELL_CATEGORY_HEADERS),mappings=mappings)
|
|
|
|
|
|
def spell_category_namespace(source_path,target_path):
|
|
"""Prove damage/prevention categories by names, independently of effects.
|
|
|
|
DefenseType is the spell damage class, not a player's Defense skill value.
|
|
A caller must still review effect families and serialize required children.
|
|
"""
|
|
import hashlib
|
|
from pathlib import Path
|
|
from spell_result_profile import enum
|
|
proof=_spell_category_contract()
|
|
for role,path in(('source',source_path),('target',target_path)):
|
|
path=Path(path)
|
|
if hashlib.sha256(path.read_bytes()).hexdigest()!=SPELL_CATEGORY_HEADERS[role]:raise ValueError('Pinned spell category header changed')
|
|
groups={name:enum(path,name)[0]for name in('SpellDmgClass','SpellPreventionType')}
|
|
for row in proof['mappings']:
|
|
if groups[row['enum']].get(row[role+'_name'])!=row[role+'_value']:raise ValueError('Named spell category differs')
|
|
return proof
|
|
|
|
|
|
def validate_spell_category_namespace(proof):
|
|
if (not isinstance(proof,dict)or proof!=_spell_category_contract()or
|
|
any(type(r.get(k))is not int for r in proof.get('mappings',[])for k in('source_value','target_value'))):
|
|
raise ValueError('Verified named spell category namespace required')
|
|
|
|
|
|
# Source/target enum identity proof for the reviewed direct-combat event subset.
|
|
# Periodic, trap, hand-specific and kill events require separate semantics review.
|
|
PROC_HEADERS={
|
|
'source':('SpellDefines.h','fd1c65c0266b77a310c066bc3ccce86fe39f73a6cd10f67192d419009f95ead1'),
|
|
'target':('SpellMgr.h','8db29907b27b2d95adf27b92900c4f12519eb416d2cc605c49d69942b753f670')}
|
|
PROC_NAMES={f'PROC_FLAG_{name}':f'PROC_FLAG_{name}'for name in(
|
|
'DEAL_MELEE_SWING','TAKE_MELEE_SWING','DEAL_MELEE_ABILITY','TAKE_MELEE_ABILITY',
|
|
'DEAL_RANGED_ATTACK','TAKE_RANGED_ATTACK','DEAL_RANGED_ABILITY','TAKE_RANGED_ABILITY')}
|
|
PROC_NAMES['PROC_FLAG_TAKEN_ANY_DAMAGE']='PROC_FLAG_TAKE_ANY_DAMAGE'
|
|
PROC_POLICY='named-direct-combat-proc-events-v1'
|
|
PROC_BITS={name:1<<(index+2)for index,name in enumerate(list(PROC_NAMES)[:-1])}
|
|
PROC_BITS['PROC_FLAG_TAKEN_ANY_DAMAGE']=1<<20
|
|
|
|
DAMAGE_PROC_POLICY='named-direct-and-harmful-spell-periodic-proc-events-v1'
|
|
# The opt-in periodic variant also requires the caller to review source procEx
|
|
# semantics. Turtle reuses the periodic bit for heals with a positive procExtra;
|
|
# the scripted-aura caller requires no overrides and the default heal exclusion.
|
|
def _proc_contract(damage_periodic,incoming_harmful=False):
|
|
if type(damage_periodic)is not bool or type(incoming_harmful)is not bool:raise ValueError('Typed proc policy required')
|
|
names=dict(PROC_NAMES);bits=dict(PROC_BITS)
|
|
if damage_periodic:
|
|
for name,bit in(('PROC_FLAG_DEAL_HARMFUL_SPELL',1<<16),('PROC_FLAG_DEAL_HARMFUL_PERIODIC',1<<18)):
|
|
names[name]=name;bits[name]=bit
|
|
policy=DAMAGE_PROC_POLICY if damage_periodic else PROC_POLICY
|
|
if incoming_harmful:
|
|
# Match independently named source/target events. These flags describe
|
|
# event eligibility, not block/hit outcome filters or client-side rolls.
|
|
for name,bit in(('PROC_FLAG_TAKE_HARMFUL_ABILITY',1<<13),('PROC_FLAG_TAKE_HARMFUL_SPELL',1<<17)):
|
|
names[name]=name;bits[name]=bit
|
|
policy+='-incoming-harmful-v1'
|
|
return policy,names,bits
|
|
|
|
def proc_namespace(source_path,target_path,*,damage_periodic=False,incoming_harmful=False):
|
|
"""Pinned enum literals, with an explicit source/target semantic-name map."""
|
|
import hashlib,re
|
|
policy,names,bits=_proc_contract(damage_periodic,incoming_harmful)
|
|
result=dict(policy=policy,header_sha256={},mappings=[])
|
|
values={}
|
|
for role,path in(('source',source_path),('target',target_path)):
|
|
raw=path.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
|
if path.name!=PROC_HEADERS[role][0]or digest!=PROC_HEADERS[role][1]:raise ValueError('Proc namespace source changed')
|
|
text=re.sub(r'/\*.*?\*/|//[^\n]*','',raw.decode(),flags=re.S)
|
|
matches=re.findall(r'enum\s+ProcFlags\s*(?::\s*uint32\s*)?\{(.*?)\}',text,re.S)
|
|
if len(matches)!=1:raise ValueError('Ambiguous ProcFlags enum')
|
|
pairs=re.findall(r'\b(PROC_FLAG_\w+)\s*=\s*(0x[0-9a-fA-F]+|[0-9]+)\s*(?:,|$)',matches[0])
|
|
values[role]={name:int(literal,0)for name,literal in pairs}
|
|
result['header_sha256'][role]=digest
|
|
for old,new in names.items():
|
|
a=values['source'].get(old);b=values['target'].get(new)
|
|
if a!=bits[old]or b!=bits[old]:raise ValueError('Pinned named proc event value changed')
|
|
result['mappings'].append(dict(source_name=old,target_name=new,source_bit=a,target_bit=b))
|
|
return result
|
|
|
|
def review_proc_conditions(raw,disk,offsets,proof,*,damage_periodic=False,incoming_harmful=False):
|
|
"""Review event/charge metadata only; not a complete proc-spell converter.
|
|
|
|
Tortoise still executes all procs. No client-side roll or trigger is created.
|
|
"""
|
|
policy,contract,bits=_proc_contract(damage_periodic,incoming_harmful)
|
|
if not isinstance(proof,dict)or proof.get('policy')!=policy or proof.get('header_sha256')!={k:v[1]for k,v in PROC_HEADERS.items()}:raise ValueError('Pinned proc namespace proof required')
|
|
mappings=proof.get('mappings')
|
|
if not isinstance(mappings,list)or len(mappings)!=len(contract):raise ValueError('Complete named proc mapping required')
|
|
names=set();source_bits=set();target_bits=set()
|
|
for row in mappings:
|
|
old=row.get('source_name');new=row.get('target_name');a=row.get('source_bit');b=row.get('target_bit')
|
|
if old not in contract or contract[old]!=new or old in names or a!=bits.get(old)or b!=bits.get(old)or type(a)is not int or type(b)is not int or not 0<a<=0xffffffff or not 0<b<=0xffffffff or a&(a-1)or b&(b-1)or a in source_bits or b in target_bits:raise ValueError('Ambiguous named proc event')
|
|
names.add(old);source_bits.add(a);target_bits.add(b)
|
|
if not isinstance(disk,(list,tuple))or len(disk)!=173 or raw.get('entry')!=disk[0]:raise ValueError('Source proc identity differs')
|
|
for key,field,maximum in(('procFlags','ProcFlags',0xffffffff),('procChance','ProcChance',100),('procCharges','ProcCharges',255)):
|
|
value=integer(raw.get(key),0,maximum,'source '+key)
|
|
if value!=disk[offsets[field]]:raise ValueError('Server/captured proc condition differs')
|
|
mask=raw['procFlags'];known=sum(source_bits)
|
|
if not mask or mask&~known:raise ValueError('Unreviewed proc event semantics')
|
|
mapped=0;selected=[]
|
|
for row in mappings:
|
|
if mask&row['source_bit']:mapped|=row['target_bit'];selected.append(dict(row))
|
|
return dict(policy=policy,source_flags=mask,target_proc_type_mask=[mapped,0],proc_chance=raw['procChance'],proc_charges=raw['procCharges'],events=selected,server_authoritative=True,complete_definition_converted=False)
|