551 lines
39 KiB
Python
551 lines
39 KiB
Python
#!/usr/bin/env python3
|
|
"""Source-backed Create Item / Learn Spell components for the existing pipeline.
|
|
|
|
Pure conversion only: no client, database, spell grants or installation. Native
|
|
child IDs are representation IDs; source spell/item/skill IDs stay authoritative.
|
|
"""
|
|
from copy import deepcopy
|
|
import re
|
|
import math
|
|
import struct
|
|
import hashlib
|
|
|
|
import spell_passive_compat as shared
|
|
|
|
POLICY='new-source-crafting-v2'
|
|
TABLES={k:(shared.TABLES|shared.SUPPLEMENTAL_TABLES)[k]for k in(
|
|
'Spell','SpellName','SpellMisc','SpellEffect','SpellEquippedItems',
|
|
'SkillLineAbility','SpellReagents','SpellTotems','SpellCastingRequirements',
|
|
'SpellInterrupts','SpellLevels','SpellCategories','SpellXSpellVisual')}
|
|
SCALARS=('entry school category castUI dispel mechanic attributes attributesEx '
|
|
'attributesEx2 attributesEx3 attributesEx4 stances stancesNot targets '
|
|
'targetCreatureType requiresSpellFocus casterAuraState targetAuraState '
|
|
'castingTimeIndex recoveryTime categoryRecoveryTime interruptFlags '
|
|
'auraInterruptFlags channelInterruptFlags procFlags procChance procCharges '
|
|
'maxLevel baseLevel spellLevel durationIndex powerType manaCost '
|
|
'manCostPerLevel manaPerSecond manaPerSecondPerLevel rangeIndex speed '
|
|
'modelNextSpell stackAmount').split()
|
|
ARRAYS=(('totem','Totem',2,'uint'),('reagent','Reagent',8,'int'),
|
|
('reagentCount','ReagentCount',8,'uint'))
|
|
EFFECTS=(('effect','Effect','uint'),('effectDieSides','EffectDieSides','int'),
|
|
('effectBaseDice','EffectBaseDice','uint'),('effectDicePerLevel','EffectDicePerLevel','float'),
|
|
('effectRealPointsPerLevel','EffectRealPointsPerLevel','float'),
|
|
('effectBasePoints','EffectBasePoints','int'),('effectMechanic','EffectMechanic','uint'),
|
|
('effectImplicitTargetA','ImplicitTargetA','uint'),('effectImplicitTargetB','ImplicitTargetB','uint'),
|
|
('effectRadiusIndex','EffectRadiusIndex','uint'),('effectApplyAuraName','EffectAura','uint'),
|
|
('effectAmplitude','EffectAuraPeriod','uint'),('effectMultipleValue','EffectAmplitude','float'),
|
|
('effectChainTarget','EffectChainTargets','uint'),('effectItemType','EffectItemType','uint'),
|
|
('effectMiscValue','EffectMiscValue','int'),('effectTriggerSpell','EffectTriggerSpell','uint'),
|
|
('effectPointsPerComboPoint','EffectPointsPerCombo','float'),
|
|
('dmgMultiplier','EffectChainAmplitude','float'))
|
|
TEXTS=(('name','Name_lang'),('nameSubtext','NameSubtext_lang'),
|
|
('description','Description_lang'),('auraDescription','AuraDescription_lang'))
|
|
TAIL=(('manaCostPercentage','ManaCostPct'),('startRecoveryCategory','StartRecoveryCategory'),
|
|
('startRecoveryTime','StartRecoveryTime'),('maxTargetLevel','MaxTargetLevel'),
|
|
('spellFamilyName','SpellClassSet'),('maxAffectedTargets','MaxTargets'),
|
|
('dmgClass','DefenseType'),('preventionType','PreventionType'),
|
|
('stanceBarOrder','StanceBarOrder'),('minFactionId','MinFactionID'),
|
|
('minReputation','MinReputation'),('requiredAuraVision','RequiredAuraVision'))
|
|
|
|
def bits_value(value,kind):
|
|
return struct.unpack('<f' if kind=='float' else '<i',struct.pack('<I',value))[0] if kind!='uint' else value
|
|
|
|
def disk_fields(dbc,ident,offsets):
|
|
"""Represent all150 SQL columns from the reviewed173-column disk row.
|
|
|
|
SQL-only bonus coefficients/custom scripts have explicit neutral rules.
|
|
Locale flags are compared as metadata, never mistaken for gameplay flags.
|
|
"""
|
|
if dbc.fields!=173:raise ValueError('Reviewed source spell schema required')
|
|
shared.integer(ident,1,0x7fffffff,'source spell');raw=dbc.by_id.get(ident)
|
|
if raw is None:raise ValueError('Source spell absent from pinned capture')
|
|
expected={name:bits_value(raw[i],'float'if i==37 else'uint')for i,name in enumerate(SCALARS)}
|
|
for prefix,field,count,kind in ARRAYS:
|
|
for i in range(count):expected[prefix+str(i+1)]=bits_value(raw[offsets[field]+i],kind)
|
|
for key,index in (('equippedItemClass',58),('equippedItemSubClassMask',59),('equippedItemInventoryTypeMask',60)):
|
|
expected[key]=bits_value(raw[index],'int')
|
|
for prefix,field,kind in EFFECTS:
|
|
for i in range(3):expected[prefix+str(i+1)]=bits_value(raw[offsets[field]+i],kind)
|
|
for key,field in TEXTS:
|
|
expected[key]=dbc.string(raw[offsets[field]]);expected[key+'Flags']=raw[offsets[field]+8]
|
|
for key,field in TAIL:expected[key]=bits_value(raw[offsets[field]],'int'if key=='stanceBarOrder'else'uint')
|
|
expected.update(spellVisual1=raw[115],spellVisual2=raw[116],spellIconId=raw[117],
|
|
activeIconId=raw[118],spellPriority=raw[119],
|
|
spellFamilyFlags=raw[offsets['SpellClassMask']]|(raw[offsets['SpellClassMask']+1]<<32),
|
|
minTargetLevel=0,customFlags=0,script_name='')
|
|
for i in range(1,4):expected['effectBonusCoefficient'+str(i)]=-1
|
|
return expected
|
|
|
|
def source_spell(dbc,server,offsets,*,allow_server_tools=False,allow_server_nondamage_coefficients=False):
|
|
if not isinstance(server,dict):raise ValueError('Complete source SQL row required')
|
|
if type(allow_server_tools)is not bool:raise ValueError('Explicit server tool policy required')
|
|
if type(allow_server_nondamage_coefficients)is not bool:raise ValueError('Explicit noncombat coefficient policy required')
|
|
expected=disk_fields(dbc,server.get('entry'),offsets)
|
|
if len(expected)!=150 or set(server)!=set(expected):raise ValueError('Source SQL columns changed')
|
|
differences=[]
|
|
for key,value in expected.items():
|
|
actual=server[key]
|
|
if isinstance(value,str):
|
|
if not isinstance(actual,str)or actual!=value or '\0'in actual or len(actual.encode())>4096:raise ValueError('Server/source text differs: '+key)
|
|
elif isinstance(value,float):
|
|
if type(actual)not in(int,float)or not math.isfinite(actual)or struct.pack('<f',actual)!=struct.pack('<f',value):raise ValueError('Server/source float differs: '+key)
|
|
elif type(actual)is not int or actual!=value:
|
|
if (allow_server_tools and key in('totem1','totem2')and type(actual)is int
|
|
and 0<=actual<=0x7fffffff and 0<=value<=0x7fffffff):
|
|
differences.append(dict(field=key,source_client=value,local_server=actual,
|
|
policy='explicit-source-server-required-tool-override'))
|
|
elif (allow_server_nondamage_coefficients and key in('effectBonusCoefficient1','effectBonusCoefficient2','effectBonusCoefficient3')and
|
|
value==-1 and type(actual)in(int,float)and actual in(-1,0)and
|
|
expected['effect1']in(24,36)and not expected['effect2']and not expected['effect3']):
|
|
differences.append(dict(field=key,source_client=value,local_server=actual,
|
|
policy='explicit-nondamage-crafting-coefficient-default'))
|
|
else:raise ValueError('Server/source field differs: '+key)
|
|
return deepcopy(server),differences
|
|
|
|
def create_item_quantity(source):
|
|
"""Keep raw Source calculation separate from the CreateItem minimum.
|
|
|
|
This describes the requested count before stack/inventory limits, never
|
|
an award. Negative damage becomes uint32 in Source and is not a zero.
|
|
"""
|
|
# Object::CalculateSpellDamage adds signed BaseDice without an RNG call
|
|
# when die sides are zero or one. Only the unmodified base count is static.
|
|
sides = shared.integer(source['effectDieSides1'], -0x80000000, 0x7fffffff, 'die sides')
|
|
if sides not in (0, 1) or any(source.get(field, 0) for field in
|
|
('effectDicePerLevel1', 'effectRealPointsPerLevel1', 'effectPointsPerComboPoint1')):
|
|
raise ValueError('Nonconstant crafting output count requires review')
|
|
base = shared.integer(source['effectBasePoints1'], -0x80000000, 0x7fffffff, 'base points')
|
|
dice = shared.integer(source['effectBaseDice1'], 0, 0xffffffff, 'base dice')
|
|
if dice >= 0x80000000:
|
|
dice -= 0x100000000
|
|
raw = base + dice
|
|
if not 0 <= raw <= 0x7fffffff or struct.unpack('<f', struct.pack('<f', raw))[0] != raw:
|
|
raise ValueError('Crafting output count is outside the exact native effect range')
|
|
return dict(source_raw_count=raw,native_count_before_stack_limit=max(1,raw),
|
|
policy='source-create-item-minimum-one'if raw==0 else'source-constant-create-item-count')
|
|
|
|
def family(source):
|
|
"""Bounded resource-free deterministic self craft / recipe teaching family."""
|
|
if source['effect1']not in(24,36)or source['effect2']or source['effect3']:raise ValueError('Only a single Create Item or Learn Spell effect is reviewed')
|
|
craft=source['effect1']==24
|
|
allowed={'entry','name','nameFlags','nameSubtext','nameSubtextFlags','description',
|
|
'descriptionFlags','auraDescription','auraDescriptionFlags','attributes','castingTimeIndex',
|
|
'rangeIndex','procChance','equippedItemClass','equippedItemSubClassMask','interruptFlags',
|
|
'spellIconId','spellVisual1','stanceBarOrder','effect1','effectImplicitTargetA1',
|
|
'dmgClass','preventionType',*[f'effectBonusCoefficient{i}'for i in range(1,4)],
|
|
*[f'dmgMultiplier{i}'for i in range(1,4)]}
|
|
allowed|={'requiresSpellFocus','totem1','totem2',*[f'reagent{i}'for i in range(1,9)],
|
|
*[f'reagentCount{i}'for i in range(1,9)],'effectDieSides1','effectBaseDice1',
|
|
'effectBasePoints1','effectItemType1'}if craft else {'effectTriggerSpell1'}
|
|
if any(v not in(0,'')for k,v in source.items()if k not in allowed):raise ValueError('Unreviewed crafting dependency')
|
|
# Original 70334 Create Item rows also use Tradeskill without IsAbility,
|
|
# and Tradeskill|DoNotLog. Preserve the actual Source word; never add an
|
|
# ability bit merely to satisfy the older narrow classifier.
|
|
if (source['attributes']not in((0x10020,0x10030,0x10120)if craft else(0x40100,))or source['school']!=0 or
|
|
source['equippedItemClass']!=-1 or source['equippedItemSubClassMask']not in(0,-1)or
|
|
source['effectImplicitTargetA1']!=1 or source['procChance']not in(0,101)or
|
|
source['interruptFlags']not in(0,15)or source['stanceBarOrder']!=-1 or
|
|
(source['dmgClass'],source['preventionType'])!=((0,0)if craft else(1,1))or
|
|
any(source[f'effectBonusCoefficient{i}']not in(-1,0)or source[f'dmgMultiplier{i}']not in((0,1)if craft and i>1 else(1,)) for i in range(1,4))):
|
|
raise ValueError('Unreviewed crafting flags/target/scaling semantics')
|
|
if craft:
|
|
# Absent effects have no multiplier consumer; the active effect still
|
|
# requires1. Keep raw zero and the server's minimum-one distinct.
|
|
create_item_quantity(source)
|
|
shared.integer(source['effectItemType1'],1,0x7fffffff,'created item')
|
|
for i in range(1,9):
|
|
reagent=shared.integer(source[f'reagent{i}'],0,0x7fffffff,'reagent')
|
|
count=shared.integer(source[f'reagentCount{i}'],0,32767,'reagent count')
|
|
# Source validation/consumption ignores an empty item slot. The
|
|
# observed unused count1 is represented by native (0,0), without
|
|
# changing the raw Source row or inventing a consumed reagent.
|
|
if (reagent and not count)or(not reagent and count not in(0,1)):raise ValueError('Incomplete reagent pair')
|
|
else:shared.integer(source['effectTriggerSpell1'],1,0x7fffffff,'learned spell')
|
|
return 'create-item'if craft else'learn-spell'
|
|
|
|
def dependency_edges(source):
|
|
craft=family(source)=='create-item';ident=source['entry'];edges=[]
|
|
def add(table,value,role,slot=None,count=None):
|
|
if value:edges.append(dict(source=['Spell',ident],target=[table,value],role=role,slot=slot,count=count))
|
|
add('SpellCastTimes',source['castingTimeIndex'],'casting-time')
|
|
add('SpellRange',source['rangeIndex'],'range')
|
|
add('SpellIcon',source['spellIconId'],'icon')
|
|
add('SpellVisual',source['spellVisual1'],'visual')
|
|
add('SpellFocusObject',source['requiresSpellFocus'],'required-focus')
|
|
for i in range(1,3):add('Item',source[f'totem{i}'],'required-tool',i-1)
|
|
for i in range(1,9):add('Item',source[f'reagent{i}'],'consumed-reagent',i-1,source[f'reagentCount{i}'])
|
|
add('Item'if craft else'Spell',source['effectItemType1']if craft else source['effectTriggerSpell1'],
|
|
'created-item'if craft else'learned-spell')
|
|
return edges
|
|
|
|
def visual_link(source,native,events):
|
|
"""Validate existing nonmissile precast/cast kits, not just equal IDs.
|
|
|
|
Source SpellVisual's16 words split into native SpellVisual+SpellVisualEvent.
|
|
Missile/area/channel/impact/state families deliberately require other rules.
|
|
"""
|
|
native_keys={'ID','MissileCastOffset','MissileImpactOffset','StateKit','AnimEventSoundID','Flags',
|
|
'MissileAttachment','MissileDestinationAttachment','MissileCastPositionerID','MissileImpactPositionerID',
|
|
'MissileTargetingKit','HostileSpellVisualID','CasterSpellVisualID','SpellVisualMissileSetID',
|
|
'DamageNumberDelay','LowViolenceSpellVisualID','RaidSpellVisualMissileSetID',
|
|
'ReducedUnexpectedCameraMovementSpellVisualID'}
|
|
if (not isinstance(native,dict)or set(native)!=native_keys or
|
|
any(type(v)is not int for k,v in native.items()if k not in('MissileCastOffset','MissileImpactOffset'))or
|
|
not isinstance(source,(tuple,list))or len(source)!=16 or
|
|
any(type(v)is not int or not 0<=v<=0xffffffff for v in source)or
|
|
source[0]!=native.get('ID')or any(source[i]for i in(3,4,5,6,7,8,11,12,13,15))or
|
|
native.get('StateKit')or native.get('Flags')or native.get('AnimEventSoundID')!=source[14]or
|
|
any(native.get(k)for k in('CasterSpellVisualID','HostileSpellVisualID','SpellVisualMissileSetID',
|
|
'RaidSpellVisualMissileSetID','MissileTargetingKit','MissileCastPositionerID','MissileImpactPositionerID',
|
|
'DamageNumberDelay','LowViolenceSpellVisualID','ReducedUnexpectedCameraMovementSpellVisualID'))or
|
|
native.get('MissileCastOffset')!=[0,0,0]or native.get('MissileImpactOffset')!=[0,0,0]):
|
|
raise ValueError('Unreviewed source/native crafting visual family')
|
|
expected={(start,end,kit)for start,end,kit in((1,2,source[1]),(3,13,source[2]))if kit}
|
|
found=set();selected=[r for r in events if r.get('SpellVisualID')==source[0]]
|
|
for row in selected:
|
|
if any(type(v)is not int for v in row.values()):raise ValueError('Native visual event field type differs')
|
|
key=(row.get('StartEvent'),row.get('EndEvent'),row.get('SpellVisualKitID'))
|
|
if (key in found or key not in expected or row.get('TargetType')!=1 or
|
|
any(row.get(k)!=0 for k in('StartMinOffsetMs','StartMaxOffsetMs','EndMinOffsetMs',
|
|
'EndMaxOffsetMs','Field_10_0_0_44649_008','Field_10_0_0_44649_009'))):
|
|
raise ValueError('Native crafting visual events differ')
|
|
found.add(key)
|
|
if found!=expected:raise ValueError('Native crafting precast/cast kits missing')
|
|
return dict(DifficultyID=0,SpellVisualID=source[0],Probability=1,Flags2=0,Priority=1,
|
|
SpellIconFileID=0,ActiveIconFileID=0,ViewerUnitConditionID=0,ViewerPlayerConditionID=0,
|
|
CasterUnitConditionID=0,CasterPlayerConditionID=0,SpellID=0)
|
|
|
|
class _SkillLineContext:
|
|
def __init__(self, raw):
|
|
magic,count,fields,width,strings=struct.unpack_from('<4s4I',raw)
|
|
if (magic!=b'WDBC' or fields!=15 or width!=60 or not 1<=count<=100000 or
|
|
len(raw)!=20+count*width+strings):
|
|
raise ValueError('Complete reviewed Source SkillLineAbility context required')
|
|
rows=tuple(struct.iter_unpack('<15I',raw[20:20+count*width]))
|
|
if len({r[0]for r in rows})!=len(rows):
|
|
raise ValueError('Duplicate Source SkillLineAbility row identity')
|
|
self._rows=frozenset(rows)
|
|
self._previous={}
|
|
for row in rows:
|
|
if row[8]:self._previous.setdefault((row[1],row[8]),set()).add(row[2])
|
|
self.source_sha256=hashlib.sha256(raw).hexdigest()
|
|
|
|
def predecessor(self, source_row):
|
|
if (not isinstance(source_row,(list,tuple)) or len(source_row)!=15 or
|
|
any(type(v)is not int for v in source_row) or tuple(source_row)not in self._rows):
|
|
raise ValueError('Crafting association differs from complete Source context')
|
|
previous=self._previous.get((source_row[1],source_row[2]),set())
|
|
if len(previous)>1:
|
|
raise ValueError('Source crafting predecessor is ambiguous')
|
|
return next(iter(previous))if previous else 0
|
|
|
|
|
|
def skill_line_context(source):
|
|
"""Pin the complete physical15-column DBC, retaining duplicate variants.
|
|
|
|
Source column8 points FORWARD to the successor. Native SupercedesSpell
|
|
points backward; never copy that source column or infer a chain from a
|
|
selected-row subset. Callers retain/reverify this complete file's digest.
|
|
"""
|
|
from turtle_data import DBC
|
|
if not isinstance(source,DBC) or source.fields!=15:
|
|
raise ValueError('Complete reviewed Source SkillLineAbility DBC required')
|
|
return _SkillLineContext(source.bytes)
|
|
|
|
|
|
def component_rows(source,*,ids,icon,visual,skill_link=None,child_skill=None,category=None,skill_context=None):
|
|
"""Reviewed scalar rows, prior to schema encoding and package closure checks.
|
|
|
|
The caller must verify icons/visuals, timing/range/focus definitions, actual
|
|
native skill/category records and stable allocations. This never installs.
|
|
"""
|
|
craft=family(source)=='create-item';ident=source['entry'];rows=[]
|
|
shared.integer(icon,1,0x7fffffff,'icon FileDataID')
|
|
def row(table,**values):
|
|
result=dict(ID=ident if table in('Spell','SpellName')else ids[table],**values)
|
|
shared.integer(result['ID'],1,0x7fffffff,'native row ID');rows.append((table,result))
|
|
row('SpellName',Name_lang=source['name'])
|
|
row('Spell',NameSubtext_lang=source['nameSubtext'],Description_lang=source['description'],AuraDescription_lang=source['auraDescription'])
|
|
misc=deepcopy(shared.NEW_MISC_NEUTRAL)
|
|
misc.update(Attributes=[source['attributes']]+[0]*16,CastingTimeIndex=source['castingTimeIndex'],
|
|
DurationIndex=0,RangeIndex=source['rangeIndex'],SpellIconFileDataID=icon,SpellID=ident)
|
|
row('SpellMisc',**misc)
|
|
row('SpellEquippedItems',SpellID=ident,EquippedItemClass=-1,
|
|
EquippedItemSubclass=source['equippedItemSubClassMask'],EquippedItemInvTypes=0)
|
|
effect=deepcopy(shared.NEW_EFFECT_NEUTRAL)
|
|
effect.update(SpellID=ident,EffectIndex=0,Effect=24 if craft else 36,EffectAura=0,
|
|
EffectBasePointsF=create_item_quantity(source)['native_count_before_stack_limit'] if craft else 0,EffectMiscValue=[0,0],
|
|
EffectItemType=source['effectItemType1'],EffectTriggerSpell=source['effectTriggerSpell1'])
|
|
row('SpellEffect',**effect)
|
|
if source['interruptFlags']:
|
|
# Canonical player-crafting mask matches the positive native16654
|
|
# reference. No general cross-version interrupt-bit equivalence claim.
|
|
row('SpellInterrupts',SpellID=ident,DifficultyID=0,InterruptFlags=source['interruptFlags'],
|
|
AuraInterruptFlags=[0,0],ChannelInterruptFlags=[0,0])
|
|
if source['requiresSpellFocus']:
|
|
row('SpellCastingRequirements',SpellID=ident,**dict(shared.CHILD_NEUTRAL['SpellCastingRequirements'],RequiresSpellFocus=source['requiresSpellFocus']))
|
|
if craft:
|
|
if skill_link is None or child_skill is None or category is None:raise ValueError('Genuine profession link/child/category required')
|
|
if not isinstance(skill_context,_SkillLineContext):raise ValueError('Complete Source crafting skill context required')
|
|
values=shared.skill_link_fields(skill_link)
|
|
if values['Spell']!=ident:raise ValueError('SkillLineAbility source spell differs')
|
|
values['SupercedesSpell']=skill_context.predecessor(skill_link)
|
|
if (child_skill.get('ParentSkillLineID')!=values['SkillLine']or child_skill.get('ParentTierIndex')!=4 or
|
|
category.get('SkillLineID')!=child_skill.get('ID')or category.get('Flags')!=0):raise ValueError('Native profession category/child differs')
|
|
values.update(SkillupSkillLineID=child_skill['ID'],TradeSkillCategoryID=category['ID'])
|
|
row('SkillLineAbility',**values)
|
|
if any(source[f'reagent{i}']for i in range(1,9)):
|
|
row('SpellReagents',SpellID=ident,Reagent=[source[f'reagent{i}']for i in range(1,9)],
|
|
ReagentCount=[source[f'reagentCount{i}']if source[f'reagent{i}']else 0 for i in range(1,9)],ReagentReCraftCount=[0]*8,ReagentSource=[0]*8)
|
|
if source['totem1']or source['totem2']:
|
|
row('SpellTotems',SpellID=ident,RequiredTotemCategoryID=[0,0],Totem=[source['totem1'],source['totem2']])
|
|
else:
|
|
row('SpellCategories',SpellID=ident,**dict(shared.CHILD_NEUTRAL['SpellCategories'],DefenseType=1,PreventionType=1))
|
|
if visual is None or visual.get('SpellVisualID')!=source['spellVisual1']or visual.get('Probability')!=1 or any(visual.get(k)for k in('DifficultyID','Flags2','ViewerUnitConditionID','ViewerPlayerConditionID','CasterUnitConditionID','CasterPlayerConditionID')):
|
|
raise ValueError('Verified unconditional source-compatible visual reference required')
|
|
v={k:v for k,v in visual.items()if k!='ID'};v['SpellID']=ident
|
|
row('SpellXSpellVisual',**v)
|
|
return rows
|
|
|
|
def required_child_tables(source):
|
|
names={'SpellMisc','SpellEquippedItems','SpellEffect','SpellXSpellVisual'}
|
|
if source['interruptFlags']:names.add('SpellInterrupts')
|
|
if source['requiresSpellFocus']:names.add('SpellCastingRequirements')
|
|
if family(source)=='create-item':
|
|
names.add('SkillLineAbility')
|
|
if any(source[f'reagent{i}']for i in range(1,9)):names.add('SpellReagents')
|
|
if source['totem1']or source['totem2']:names.add('SpellTotems')
|
|
else:names.add('SpellCategories')
|
|
return names
|
|
|
|
|
|
def profession_category_name(skill,item):
|
|
"""Source ItemPrototype enums -> existing native profession group labels.
|
|
|
|
Presentation only: keep source class/subclass/slot and gameplay identity.
|
|
The caller must find the exact category under the verified native child.
|
|
Unknown combinations remain unsupported instead of guessing by item name.
|
|
"""
|
|
cls,sub,slot=(item[k]for k in('class','subclass','inventory_type'))
|
|
armor_slots={1:'Helmets',3:'Pauldrons',5:'Chestguards',6:'Belts',7:'Legguards',8:'Boots',9:'Bracers',10:'Gauntlets'}
|
|
if skill==186 and (cls,sub,slot)==(7,0,0):return 'Smelted Bars'
|
|
if skill==164:
|
|
if cls==4 and sub in(3,4)and slot in armor_slots:return ('Mail'if sub==3 else'Plate')+' '+armor_slots[slot]
|
|
if (cls,sub,slot)==(4,6,14):return 'Shields'
|
|
if cls==2:
|
|
label={(0,13):'One-Handed Axes',(5,17):'Two-Handed Maces',(7,13):'One-Handed Swords',(8,17):'Two-Handed Swords'}.get((sub,slot))
|
|
if label:return label
|
|
if (cls,sub,slot)==(0,0,0):return 'Miscellaneous'
|
|
if skill==165 and cls==4 and sub in(2,3)and slot in armor_slots:
|
|
return ('Leather'if sub==2 else'Mail')+' '+armor_slots[slot]
|
|
if skill==202 and cls==4 and sub in(1,2,3,4)and slot==1:
|
|
return {1:'Cloth',2:'Leather',3:'Mail',4:'Plate'}[sub]+' Headgear'
|
|
# Original crafting rows give these slot families a single category.
|
|
# Cloth chest/legs also have a costume category and remain unclassified.
|
|
if skill==197 and (cls,sub)==(4,1):
|
|
label={1:'Hoods',3:'Spaulders',6:'Belts',8:'Shoes',9:'Bracers',10:'Gloves',16:'Cloaks'}.get(slot)
|
|
if label:return label
|
|
if skill==202 and (cls,sub,slot)==(4,0,12):return 'Devices'
|
|
if skill in(164,165,197)and (cls,sub,slot)==(7,0,0):return 'Reagents'
|
|
raise ValueError('Unreviewed source item/profession category')
|
|
|
|
def allocate_children(sources,registry,maxima,occupied):
|
|
"""Stable per-component IDs above native and preserved-package identities."""
|
|
registry=deepcopy(registry)
|
|
if (registry.get('schema_version')!=1 or registry.get('build')!=shared.BUILD or
|
|
set(registry)!={'schema_version','build','tables'}or not isinstance(registry['tables'],dict)or
|
|
set(registry['tables'])-(TABLES.keys()-{'Spell','SpellName'})):
|
|
raise ValueError('Explicit crafting child registry required')
|
|
if set(maxima)!=set(TABLES)or set(occupied)!=set(TABLES):raise ValueError('Complete native/occupied table bounds required')
|
|
sources=sorted(sources,key=lambda r:r['entry'])
|
|
if not sources or len(sources)>128 or len({s['entry']for s in sources})!=len(sources):raise ValueError('Bounded unique crafting source selection required')
|
|
result={s['entry']:{}for s in sources};used={}
|
|
for table in sorted(TABLES.keys()-{'Spell','SpellName'}):
|
|
maximum=shared.integer(maxima[table],1,0x7fffffff,'native maximum')
|
|
if not isinstance(occupied[table],set):raise ValueError('Explicit occupied native ID set required')
|
|
for ident in occupied[table]:shared.integer(ident,1,0x7fffffff,'occupied child')
|
|
entries=registry['tables'].setdefault(table,{})
|
|
if not isinstance(entries,dict):raise ValueError('Registry table schema')
|
|
found=set()
|
|
for key,ident in entries.items():
|
|
if not isinstance(key,str)or not re.fullmatch('[1-9][0-9]*',key):raise ValueError('Registry source identity')
|
|
shared.integer(ident,maximum+1,0x7fffffff,'native child')
|
|
if ident in found or ident in occupied[table]:raise ValueError('Registry/native/package collision; explicit migration required')
|
|
found.add(ident)
|
|
next_id=max({maximum,*found,*occupied[table]})
|
|
used[table]=set()
|
|
for src in sources:
|
|
if table not in required_child_tables(src):continue
|
|
key=str(src['entry']);used[table].add(key)
|
|
if key not in entries:
|
|
next_id+=1;shared.integer(next_id,maximum+1,0x7fffffff,'allocated child');entries[key]=next_id
|
|
result[src['entry']][table]=entries[key]
|
|
if set(entries)-used[table]:raise ValueError('Previously owned crafting child removed; explicit migration required')
|
|
return result,registry
|
|
|
|
def main():
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
from item_icon_preflight import normalize_icon
|
|
from item_sparse_compat import package_payloads
|
|
from spell_content_compare import read_input,_observed_context
|
|
from turtle_data import DBC,spell_layout,inventory_item_snapshot
|
|
from octo_client_data import canonical_sha256
|
|
root=Path(__file__).resolve().parents[1]
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
for key in('context','registry','output'):p.add_argument('--'+key,type=Path,required=True)
|
|
p.add_argument('--ids',required=True);p.add_argument('--allow-server-tools',action='store_true')
|
|
p.add_argument('--allow-server-nondamage-coefficients',action='store_true');a=p.parse_args()
|
|
for path in(a.registry,a.output):
|
|
if path.is_symlink()or not path.resolve().is_relative_to(root/'runtime'):p.error('Keep candidate/registry outputs in runtime')
|
|
if a.output.exists():p.error('Preserve existing component; use a new output')
|
|
pins={}
|
|
def unique(pairs):
|
|
result={}
|
|
for key,value in pairs:
|
|
if key in result:raise ValueError('Duplicate JSON field in component input')
|
|
result[key]=value
|
|
return result
|
|
def load(path,bound=134217728,binary=False):
|
|
path=Path(path);path=path if path.is_absolute()else root/path
|
|
actual,raw,digest=read_input(path,bound);pins[str(actual)]=digest
|
|
return raw if binary else json.loads(raw,object_pairs_hook=unique,
|
|
parse_constant=lambda _:(_ for _ in ()).throw(ValueError('Nonfinite component input')))
|
|
def dbc(path,width):
|
|
raw=load(path,67108864,True);value=DBC(Path(path),width)
|
|
if value.bytes!=raw:raise ValueError('DBC changed while parsing')
|
|
return value
|
|
ctx=load(a.context,1048576)
|
|
if ctx.get('build')!=shared.BUILD:raise ValueError('Native context build differs')
|
|
selected=sorted({shared.integer(int(i),1,0x7fffffff,'selected spell')for i in a.ids.split(',')})
|
|
if not 1<=len(selected)<=128 or len(selected)!=len(a.ids.split(',')):raise ValueError('Bounded unique source selection required')
|
|
source=dbc(ctx['source_spell'],173);offsets=spell_layout()
|
|
observed=_observed_context(source,load(ctx['observed_inventory']),'enUS')
|
|
server=load(ctx['server_spells']);provenance=load(ctx['server_provenance'])
|
|
if provenance.get('sha256')!=pins[str(Path(ctx['server_spells']).resolve())]or provenance.get('count')!=len(server):raise ValueError('Server snapshot provenance differs')
|
|
by_server={r['entry']:r for r in server}
|
|
if len(by_server)!=len(server):raise ValueError('Duplicate server spell')
|
|
sources=[];differences={}
|
|
for ident in selected:
|
|
src,diff=source_spell(source,by_server[ident],offsets,allow_server_tools=a.allow_server_tools,
|
|
allow_server_nondamage_coefficients=a.allow_server_nondamage_coefficients)
|
|
family(src);sources.append(src);differences[str(ident)]=diff
|
|
before=load(ctx['before_api'],1048576)
|
|
if any(any(before.get(str(i),{}).get(k)!='nil'for k in('infoStatus','nameStatus','descriptionStatus'))for i in selected):raise ValueError('Require original unavailable APIs for new definitions')
|
|
base=load(ctx['package']);occupied={table:set()for table in TABLES}
|
|
if base.get('build')!=shared.BUILD or base.get('id_remapping')is not False:raise ValueError('Preserved package identity differs')
|
|
if package_payloads(base['rows'])[0]!=base.get('push_id'):raise ValueError('Preserved package payload identity differs')
|
|
for row in base['rows']:
|
|
if row.get('table_name')in occupied:occupied[row['table_name']].add(row['id'])
|
|
native={};schemas={};maxima={};metadata={}
|
|
for table,(th,layout,field_sha)in TABLES.items():
|
|
definitions=Path(ctx['native_dbd'])/(table+'.dbd');data=Path(ctx['native_db2'])/(table+'.db2')
|
|
native[table]=load(ctx['native_references'][table]);load(definitions,1048576,True);load(data,134217728,True)
|
|
schemas[table]=shared.fields(definitions,table);maxima[table]=shared.db2_header(data,th,layout)
|
|
if len({r['ID']for r in native[table]})!=len(native[table]):raise ValueError('Duplicate native reference ID: '+table)
|
|
for row in native[table]:shared.integer(row['ID'],1,maxima[table],'native reference '+table)
|
|
if any(row.get('SpellID',row.get('Spell',row['ID']))in selected for row in native[table]):raise ValueError('Positive native definition requires a correction policy: '+table)
|
|
metadata[table]=dict(table_hash=hex(th),layout_hash=hex(layout),serialized_field_sha256=field_sha,
|
|
max_id=maxima[table],dbd_sha256=pins[str(definitions.resolve())],db2_sha256=pins[str(data.resolve())],baseline_sha256=pins[str(Path(ctx['native_references'][table]).resolve())])
|
|
registry=load(a.registry,1048576)if a.registry.exists()else dict(schema_version=1,build=shared.BUILD,tables={})
|
|
allocated,registry=allocate_children(sources,registry,maxima,occupied)
|
|
source_root=Path(ctx['source_dbc']);skills=dbc(source_root/'SkillLine.dbc',22)
|
|
abilities=dbc(source_root/'SkillLineAbility.dbc',15);icons=dbc(source_root/'SpellIcon.dbc',2)
|
|
skills_context=skill_line_context(abilities)
|
|
visuals=dbc(source_root/'SpellVisual.dbc',16);times=dbc(source_root/'SpellCastTimes.dbc',4)
|
|
ranges=dbc(source_root/'SpellRange.dbc',22);focus=dbc(source_root/'SpellFocusObject.dbc',10)
|
|
parents=load(ctx['native_skill_parents']);children=load(ctx['native_skill_children']);categories=load(ctx['native_categories'])
|
|
native_visuals=load(ctx['native_visuals']);events=load(ctx['native_events'])
|
|
native_times=load(ctx['native_times']);native_ranges=load(ctx['native_ranges']);native_focus=load(ctx['native_focus'])
|
|
snapshot=inventory_item_snapshot(Path(ctx['source_items']))
|
|
source_items={row['identity'][1]:row['raw_fields']for row in snapshot['records']}
|
|
manifest=load(Path(ctx['source_items'])/'manifest.json',4194304)
|
|
for chunk in manifest['chunks']:load(Path(ctx['source_items'])/chunk['path'],134217728,True)
|
|
available_items={r['ID']for r in load(ctx['native_items'])}&{r['ID']for r in load(ctx['native_sparse'])}
|
|
basic={r['id']for r in base['rows']if r.get('table_name')=='Item'}
|
|
sparse={r['id']for r in base['rows']if r.get('table_name')=='ItemSparse'};available_items|=basic&sparse
|
|
listfile=load(ctx['listfile'],268435456,True).decode()
|
|
def one(rows,predicate,label):return shared.one(rows,predicate,label)
|
|
records=[];spell_rows=[];edges=[];unresolved=set()
|
|
for src in sources:
|
|
ident=src['entry'];kind=family(src);e=dependency_edges(src);edges+=e
|
|
for edge in e:
|
|
table,value=edge['target']
|
|
if table=='Item'and value not in available_items:unresolved.add((table,value))
|
|
if table=='Spell'and value not in selected and not any(r['ID']==value for r in native['SpellName']):unresolved.add((table,value))
|
|
icon_row=icons.by_id[src['spellIconId']];icon_source=normalize_icon(icons.string(icon_row[1]),source=True)
|
|
icon=ctx['icons'][str(src['spellIconId'])];path=normalize_icon(icon['path'])
|
|
if icon_source['stem']!=path['stem']or not any(line==str(icon['file_id'])+';'+path['path']for line in listfile.splitlines()):raise ValueError('Source/native icon identity differs')
|
|
raw=load(icon['asset'],4194304,True)
|
|
if raw[:4]not in(b'BLP1',b'BLP2'):raise ValueError('Actual icon asset unavailable')
|
|
v=visuals.by_id[src['spellVisual1']]
|
|
visual=visual_link(v,one(native_visuals,lambda r:r['ID']==v[0],'native visual'),events)
|
|
# Tortoise SpellEntry::CalculateCastTime returns zero for no index;
|
|
# zero is a nullable reference, not a fabricated CastTimes row.
|
|
ct=times.by_id[src['castingTimeIndex']]if src['castingTimeIndex']else(0,0,0,0)
|
|
if ct[0]:
|
|
nt=one(native_times,lambda r:r['ID']==ct[0],'native cast time')
|
|
if (nt['Base'],nt['Minimum'])!=(bits_value(ct[1],'int'),bits_value(ct[3],'int')):raise ValueError('Source/native cast-time base/minimum differ')
|
|
rg=ranges.by_id[src['rangeIndex']];nr=one(native_ranges,lambda r:r['ID']==rg[0],'native range')
|
|
if nr['RangeMin']!=[bits_value(rg[1],'float')]*2 or nr['RangeMax']!=[bits_value(rg[2],'float')]*2 or nr['Flags']!=rg[3]:raise ValueError('Source/native range semantics differ')
|
|
if src['requiresSpellFocus']:
|
|
f=focus.by_id[src['requiresSpellFocus']];nf=one(native_focus,lambda r:r['ID']==f[0],'native focus')
|
|
if nf['Name_lang']!=focus.string(f[1]):raise ValueError('Source/native required focus differs')
|
|
link=child=category=None
|
|
if kind=='create-item':
|
|
link=list(one(abilities.rows,lambda r:r[2]==ident,'source profession link'));skill=skills.by_id[link[1]]
|
|
parent=one(parents,lambda r:r['ID']==skill[0],'native profession parent')
|
|
if skill[1]not in(9,11)or parent['CategoryID']!=skill[1]or parent['DisplayName_lang']!=skills.string(skill[3])or any(link[3:7])or any(link[12:]):raise ValueError('Unreviewed profession identity/restrictions')
|
|
child=one(children,lambda r:r['ParentSkillLineID']==skill[0]and r['ParentTierIndex']==4,'native profession child')
|
|
product=source_items[src['effectItemType1']]
|
|
label=profession_category_name(skill[0],product)
|
|
category=one(categories,lambda r:r['Name_lang']==label and r['SkillLineID']==child['ID'],'native item category')
|
|
for table,row in component_rows(src,ids=allocated[ident],icon=icon['file_id'],visual=visual,
|
|
skill_link=link,child_skill=child,category=category,skill_context=skills_context if kind=='create-item'else None):
|
|
wire=shared.encode(row,schemas[table]);records.append(dict(table_name=table,table_hash=hex(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='new-source-spell-definition'if table in('Spell','SpellName')else'new-source-crafting-child'))
|
|
spell_rows.append(dict(spell_id=ident,family=kind,source_record_sha256=canonical_sha256(src),
|
|
source_client_server_differences=differences[str(ident)],
|
|
native_created_item_count=create_item_quantity(src)['native_count_before_stack_limit']if kind=='create-item'else None,
|
|
created_item_quantity=create_item_quantity(src)if kind=='create-item'else None,
|
|
ignored_inactive_multiplier_fields=[dict(effect_index=i-1,source_multiplier=src[f'dmgMultiplier{i}'],reason='absent-source-effect-no-native-effect-row')
|
|
for i in(2,3)if kind=='create-item'and src[f'dmgMultiplier{i}']==0],
|
|
empty_reagent_slot_canonicalizations=[dict(slot=i-1,source_item=0,source_count=src[f'reagentCount{i}'],native_item=0,native_count=0)
|
|
for i in range(1,9)if not src[f'reagent{i}']and src[f'reagentCount{i}']],
|
|
icon_asset_bytes_verified=True,icon_file_data_id=icon['file_id'],icon_sha256=hashlib.sha256(raw).hexdigest(),
|
|
source_cast_time_slope=bits_value(ct[2],'int'),native_static_cast_time_equivalent=ct[2]==0,
|
|
cast_duration_authority='genuine server START packet; native prediction/tooltip parity unverified',
|
|
native_attribute_defaults='source0..4 retained; target5..16 zero candidates, not copied unknown flags',
|
|
engine_accepted=False,gameplay_verified=False))
|
|
for name in('spell_crafting_compat.py','spell_passive_compat.py','spell_content_compare.py','turtle_data.py','item_icon_preflight.py','octo_client_data.py'):
|
|
load(Path(__file__).with_name(name),1048576,True)
|
|
result=dict(kind='source-crafting-spell-component',schema_version=1,build=shared.BUILD,schema=shared.SCHEMA,
|
|
definition_policy=POLICY,id_remapping=False,records=records,spells=spell_rows,source_context=observed,
|
|
source_roles=dict(spell='observed Octo file content; context scope retained',
|
|
server='pinned authorized local spell_template snapshot, not live Octo equivalence',
|
|
ancillary='pinned local Tortoise DBC references; effective Octo precedence not asserted'),
|
|
source_server_provenance=provenance,
|
|
source_item_identity=snapshot['source_identity'],native_tables=metadata,child_id_registry=registry,
|
|
dependency_edges=edges,unresolved_dependencies=[list(r)for r in sorted(unresolved)],
|
|
direct_dependency_checks_passed=not unresolved,dependency_closure_verified=False,
|
|
engine_accepted=False,gameplay_verified=False,
|
|
preinstallation_native_api=dict(input_sha256=pins[str(Path(ctx['before_api']).resolve())],observed_unavailable=selected),
|
|
input_sha256=dict(sorted(pins.items())),limitations=['Static definitions do not grant or teach spells.',
|
|
'Required tools are distinct from consumed reagents; source/server differences are explicit.',
|
|
'Cast-time slope and unknown target attributes need actual-engine acceptance; not silently assumed equivalent.',
|
|
'Only single deterministic self CreateItem and teaching effects; no arbitrary spell/effect support.',
|
|
'Dependency checks cover direct component references; transitive item/spell/asset closure belongs to the complete package.',
|
|
'Component is not installed; unresolved item/spell dependencies prohibit complete-batch acceptance.'])
|
|
for name,digest in pins.items():
|
|
if read_input(Path(name),268435456)[2]!=digest:raise ValueError('Input changed before publication')
|
|
result['second_input_pass_verified']=True
|
|
a.output.parent.mkdir(parents=True,exist_ok=True);a.registry.parent.mkdir(parents=True,exist_ok=True)
|
|
a.registry.write_text(json.dumps(registry,indent=2)+'\n');a.output.write_text(json.dumps(result,indent=2)+'\n')
|
|
print(json.dumps(dict(records=len(records),spells=selected,unresolved_dependencies=result['unresolved_dependencies'],installed=False)))
|
|
|
|
if __name__=='__main__':main()
|