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

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

271 lines
21 KiB
Python

#!/usr/bin/env python3
"""Match source aura visuals to unambiguous, unconditional native visual links.
Input is reviewed local SQL plus the actual target-build SpellXSpellVisual rows.
Never equate a legacy SpellVisual ID with a native SpellXSpellVisual row ID.
Conditional, difficulty-specific, secondary and ambiguous visuals stay unknown.
"""
import argparse
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CONDITIONS = ('CasterPlayerConditionID', 'CasterUnitConditionID',
'ViewerPlayerConditionID', 'ViewerUnitConditionID')
def generate(source, native):
rows, excluded, seen = [], [], set()
if not isinstance(source, list) or not isinstance(native, list):
raise ValueError('Require source/native arrays')
# Build the shared native relation once for the entire source batch.
native_by_spell = {}
if source:
for row in native:
try:
native_by_spell.setdefault(row.get('SpellID'), []).append(row)
except TypeError:
# Unhashable values cannot equal a valid integer source ID.
continue
for s in sorted(source, key=lambda r: r['entry']):
spell = s['entry']
if type(spell) is not int or not 0 < spell <= 0x7fffffff or spell in seen:
raise ValueError('Invalid/duplicate source spell')
seen.add(spell)
for field in ('spellVisual1', 'spellVisual2'):
if type(s.get(field)) is not int or not 0 <= s[field] <= 0x7fffffff:
raise ValueError('Invalid source visual')
matches = native_by_spell.get(spell, [])
if not s['spellVisual1'] or s['spellVisual2'] or len(matches) != 1:
excluded.append(dict(spell=spell, reason='missing, secondary or ambiguous visual'))
continue
n = matches[0]
if (any(type(n.get(k)) is not int for k in ('ID', 'DifficultyID', 'Flags2', 'SpellVisualID', *CONDITIONS))
or not 0 < n['ID'] <= 0x7fffffff):
raise ValueError('Invalid native visual metadata')
if (n['SpellVisualID'] != s['spellVisual1'] or n['DifficultyID'] or n['Flags2']
or any(n[k] for k in CONDITIONS) or n.get('Probability') != 1):
excluded.append(dict(spell=spell, reason='different or conditional native visual'))
continue
rows.append(dict(spell=spell, spell_x_spell_visual=n['ID'], visual=n['SpellVisualID']))
return dict(definitions=rows, excluded=excluded,
limits=['Same-ID matching visual numbers require reviewed source/target visual data.',
'Only one unconditional default-difficulty link; script visual remains zero.',
'Packet serialization does not prove renderer behavior or asset equivalence.'])
def new_link_candidate(source,source_visual,native_visual,native_events,template,
schema,maximum,registry,occupied,*,full_lifecycle=False,present_stages=False):
"""Reuse an existing visual through a NEW source-spell-owned link.
This checks visual/event references, not complete asset/rendering parity.
Caller must pin source/target exports and independently review kits/assets.
present_stages explicitly retains every nonzero source stage and requires
the exact reviewed native roles for those stages, without inventing absent
stages. It does not relax full_lifecycle's all-four-stage contract.
"""
from copy import deepcopy
from octo_client_data import canonical_sha256
from spell_passive_compat import BUILD,SCHEMA,SUPPLEMENTAL_TABLES,encode,integer
table,layout,fieldsha=SUPPLEMENTAL_TABLES['SpellXSpellVisual']
if type(full_lifecycle)is not bool or type(present_stages)is not bool or(full_lifecycle and present_stages):raise ValueError('Explicit exclusive visual lifecycle policy required')
typed_lifecycle=full_lifecycle or present_stages
if canonical_sha256(schema)!=fieldsha:raise ValueError('Reviewed visual-link schema required')
spell=integer(source.get('entry'),1,0x7fffffff,'source visual-link spell')
visual=integer(source.get('spellVisual1'),1,0x7fffffff,'source visual ID')
if source.get('spellVisual2')!=0:raise ValueError('Secondary visual requires separate review')
if not isinstance(source_visual,(list,tuple))or len(source_visual)!=16 or source_visual[0]!=visual or any(type(v)is not int or not 0<=v<=0xffffffff for v in source_visual):raise ValueError('Complete source visual row required')
# No precast/channel/missile/area behavior is silently dropped.
excluded=(5,6,7,8,10,11,12,13,14,15)if typed_lifecycle else(1,5,6,7,8,10,11,12,13,14,15)
if any(source_visual[i]for i in excluded):raise ValueError('Unreviewed source visual behavior')
if full_lifecycle and (not all(source_visual[1:5])or source_visual[9]not in(0,1)):
raise ValueError('Complete nonmissile precast/cast/impact/state source required')
if present_stages and (not any(source_visual[1:5])or source_visual[9]not in(0,1)):
raise ValueError('Explicit nonempty nonmissile source visual stages required')
if not isinstance(native_visual,dict)or native_visual.get('ID')!=visual or native_visual.get('StateKit')!=source_visual[4]:raise ValueError('Source/native visual state identity differs')
neutral=dict(MissileCastOffset=[0,0,0],MissileImpactOffset=[0,0,0],AnimEventSoundID=0,Flags=0,MissileCastPositionerID=0,MissileImpactPositionerID=0,MissileTargetingKit=0,HostileSpellVisualID=0,CasterSpellVisualID=0,SpellVisualMissileSetID=0,DamageNumberDelay=0,LowViolenceSpellVisualID=0,RaidSpellVisualMissileSetID=0,ReducedUnexpectedCameraMovementSpellVisualID=0)
if present_stages:
offsets=('MissileCastOffset','MissileImpactOffset')
if (set(native_visual)!={*neutral,'ID','StateKit','MissileAttachment','MissileDestinationAttachment'}
or any(type(value)is not int for key,value in native_visual.items()if key not in offsets)
or any(not isinstance(native_visual[key],list)or len(native_visual[key])!=3
or any(type(value)not in(int,float)for value in native_visual[key])for key in offsets)):
raise ValueError('Complete typed native visual stage record required')
if any(native_visual.get(k)!=v for k,v in neutral.items()):raise ValueError('Conditional or additional native visual behavior')
if not isinstance(native_events,list)or not 1<=len(native_events)<=32:raise ValueError('Complete bounded visual events required')
expected={k for k in(source_visual[1:5]if typed_lifecycle else source_visual[2:5])if k};seen=set();event_ids=set()
if typed_lifecycle:
for kit in expected:integer(kit,1,0x7fffffff,'source visual lifecycle kit')
lifecycle={(1,2,1):source_visual[1],(3,13,1):source_visual[2],(6,13,1):source_visual[3],
(6,13,2):source_visual[3],(7,8,2):source_visual[4]}if typed_lifecycle else{}
if present_stages:lifecycle={role:kit for role,kit in lifecycle.items()if kit}
observed_roles=set()
offset_fields=('StartMinOffsetMs','StartMaxOffsetMs','EndMinOffsetMs','EndMaxOffsetMs','Field_10_0_0_44649_008','Field_10_0_0_44649_009')
event_fields=('ID','SpellVisualID','SpellVisualKitID','StartEvent','EndEvent','TargetType',*offset_fields)
for event in native_events:
if typed_lifecycle:
if not isinstance(event,dict)or any(type(event.get(k))is not int for k in event_fields):raise ValueError('Typed native visual lifecycle role required')
if present_stages and set(event)!=set(event_fields):raise ValueError('Complete native visual stage event required')
if event['TargetType']not in(1,2):raise ValueError('Unreviewed native visual target role: '+str(event['TargetType']))
if event.get('SpellVisualID')!=visual or event.get('ID')in event_ids or event.get('SpellVisualKitID')not in expected:raise ValueError('Visual event reference differs')
integer(event.get('ID'),1,0x7fffffff,'visual event ID');event_ids.add(event['ID']);seen.add(event['SpellVisualKitID'])
if typed_lifecycle:
role=tuple(event.get(k)for k in('StartEvent','EndEvent','TargetType'))
if role in observed_roles or lifecycle.get(role)!=event['SpellVisualKitID']:raise ValueError('Native visual lifecycle role/kit differs')
observed_roles.add(role)
if any(event.get(k)!=0 for k in offset_fields):raise ValueError('Conditional or delayed visual event')
if seen!=expected:raise ValueError('Missing source cast/impact/state kit reference')
if typed_lifecycle and observed_roles!=set(lifecycle):raise ValueError('Complete native visual lifecycle required')
# Existing source-matched native behavior is retained; only ownership and ID
# change. This never sends another spell's ID as the authoritative identity.
baseline=deepcopy(template)
if baseline.get('SpellVisualID')!=visual or baseline.get('SpellID')==spell or not generate([dict(source,entry=baseline.get('SpellID'))],[baseline])['definitions']:raise ValueError('Unconditional positive visual template required')
encode(baseline,schema)
integer(maximum,1,0x7fffffff,'visual allocation floor')
if not isinstance(occupied,set)or not isinstance(registry,dict)or registry.get('schema_version')!=1 or registry.get('build')!=BUILD or set(registry)!={'schema_version','build','SpellXSpellVisual'}or not isinstance(registry['SpellXSpellVisual'],dict):raise ValueError('Explicit visual-link registry required')
result=deepcopy(registry);entries=result['SpellXSpellVisual'];values=set()
for key,value in entries.items():
if not isinstance(key,str)or not key.isdecimal()or str(int(key))!=key or int(key)<=0:raise ValueError('Visual registry spell identity differs')
integer(value,maximum+1,0x7fffffff,'new visual link ID')
if value in values or value in occupied:raise ValueError('Visual-link allocation collision')
values.add(value)
key=str(spell)
if key not in entries:entries[key]=max([maximum,*values])+1
ident=integer(entries[key],maximum+1,0x7fffffff,'new visual link ID');row=dict(baseline,ID=ident,SpellID=spell);wire=encode(row,schema)
definition=generate([source],[row])['definitions']
if len(definition)!=1:raise ValueError('New source-owned visual link did not validate')
result=dict(kind='source-owned-visual-link-candidate',build=BUILD,schema=SCHEMA,
record=dict(table_name='SpellXSpellVisual',table_hash=hex(table),id=ident,record=row,wire_hex=wire.hex(),sha256=hashlib.sha256(wire).hexdigest(),source_spell_id=spell,baseline_record_sha256=None,allocation_policy='new-source-owned-visual-link'),
original_template_sha256=canonical_sha256(baseline),native_allocation_floor=maximum,visual_reference=dict(source_visual_id=visual,native_visual_id=visual,source_kit_ids=sorted(expected),native_event_ids=sorted(event_ids)),
profile_definition=definition[0],child_id_registry=result,installed=False,engine_accepted=False,gameplay_verified=False,asset_parity_verified=False)
if typed_lifecycle:
result['lifecycle_review']=dict(policy='source-matched-present-visual-stages-v1'if present_stages else'source-matched-precast-cast-impact-target-state-v1',
inputs=dict(source={k:source[k]for k in('entry','spellVisual1','spellVisual2')},source_visual=list(source_visual),
native_visual=deepcopy(native_visual),native_events=deepcopy(native_events),template=deepcopy(template),
occupied_above_floor=sorted(i for i in occupied if i>maximum),link_schema=[list(f)for f in schema]))
return result
def review_lifecycle_link(candidate,schema):
"""Rebuild every source stage and retained native event before publication."""
review=candidate.get('lifecycle_review',{})
policies=('source-matched-precast-cast-impact-target-state-v1','source-matched-present-visual-stages-v1')
if not isinstance(review,dict)or review.get('policy')not in policies or not isinstance(review.get('inputs'),dict):
raise ValueError('Explicit source visual lifecycle review required')
values=review['inputs']
from octo_client_data import canonical_sha256
if canonical_sha256(values.get('link_schema'))!=canonical_sha256(schema):raise ValueError('Lifecycle link schema differs')
rebuilt=new_link_candidate(values.get('source'),values.get('source_visual'),values.get('native_visual'),values.get('native_events'),
values.get('template'),schema,candidate.get('native_allocation_floor'),candidate.get('child_id_registry'),
set(values.get('occupied_above_floor',[])),full_lifecycle=review['policy']==policies[0],present_stages=review['policy']==policies[1])
if candidate!=rebuilt:raise ValueError('Visual lifecycle provenance or serialized bytes differ')
return rebuilt
def new_mapped_link_candidate(source,source_visual,native_visual,native_events,template,
schema,maximum,registry,occupied,*,visual_candidate,visual_schemas):
"""Bind a genuine source spell to a fully checked destination-only graph."""
from copy import deepcopy
from octo_client_data import canonical_sha256
from spell_visual_compat import review_candidate
from spell_passive_compat import encode
graph=review_candidate(visual_candidate,visual_schemas,{})
if (graph['kind']!='source-owned-state-visual-candidate'or graph['source_visual_id']!=source.get('spellVisual1')
or graph['source_visual_row']!=list(source_visual)or graph['native_template']!=native_visual or graph['native_events']!=native_events):
raise ValueError('Mapped state visual source/template graph differs')
result=new_link_candidate(source,source_visual,native_visual,native_events,template,schema,maximum,registry,occupied)
value=result['record']['record'];value['SpellVisualID']=graph['native_visual_id'];raw=encode(value,schema)
result['record'].update(wire_hex=raw.hex(),sha256=hashlib.sha256(raw).hexdigest(),allocation_policy='new-source-owned-mapped-state-visual-link')
result['visual_reference']['native_visual_id']=graph['native_visual_id']
result['profile_definition']['visual']=graph['native_visual_id']
result.update(visual_candidate=deepcopy(graph),visual_candidate_sha256=canonical_sha256(graph),visual_schemas=deepcopy(visual_schemas),
mapping_inputs=dict(source={k:source[k]for k in('entry','spellVisual1','spellVisual2')},source_visual=list(source_visual),
native_visual=deepcopy(native_visual),native_events=deepcopy(native_events),template=deepcopy(template),
occupied_above_floor=sorted(i for i in occupied if i>maximum),link_schema=[list(field)for field in schema]))
return result
def review_mapped_link(candidate,schema):
"""Rebuild source ownership, new graph, allocation and every link byte."""
if not isinstance(candidate,dict)or not isinstance(candidate.get('mapping_inputs'),dict):raise ValueError('Explicit mapped state visual link required')
values=candidate['mapping_inputs']
from octo_client_data import canonical_sha256
if canonical_sha256(values.get('link_schema'))!=canonical_sha256(schema):raise ValueError('Mapped link serialized schema differs')
rebuilt=new_mapped_link_candidate(values.get('source'),values.get('source_visual'),values.get('native_visual'),values.get('native_events'),
values.get('template'),schema,candidate.get('native_allocation_floor'),candidate.get('child_id_registry'),set(values.get('occupied_above_floor',[])),
visual_candidate=candidate.get('visual_candidate'),visual_schemas=candidate.get('visual_schemas'))
if any(candidate.get(k)!=v for k,v in rebuilt.items()):raise ValueError('Mapped state visual link provenance/bytes differ')
return rebuilt
def extend_with_package(base,source,package,schema,*,visual_candidates=None,visual_schemas=None):
"""Add source-owned links from a validated package without editing snapshots."""
from copy import deepcopy
from octo_client_data import canonical_sha256
from spell_passive_compat import BUILD,SCHEMA,SUPPLEMENTAL_TABLES,encode
table,_,fieldsha=SUPPLEMENTAL_TABLES['SpellXSpellVisual']
if canonical_sha256(schema)!=fieldsha or (package.get('build'),package.get('schema'))!=(BUILD,SCHEMA):raise ValueError('Reviewed package visual schema required')
if not isinstance(base,list)or not isinstance(source,list)or not 1<=len(source)<=256:raise ValueError('Bounded source-owned visual profile required')
wanted={s.get('entry')for s in source};native=[]
allocations={'new-source-owned-visual-link'}
if visual_candidates is not None:allocations.update(('new-source-extra-attack-visual-link','new-source-owned-mapped-state-visual-link'))
for row in package.get('rows',[]):
if row.get('table_name')!='SpellXSpellVisual'or row.get('source_spell_id')not in wanted:continue
record=row.get('record',{});wire=encode(record,schema)
if (row.get('allocation_policy')not in allocations or row.get('record_status','valid')!='valid'or
row.get('table_hash')!=hex(table)or row.get('id')!=record.get('ID')or row.get('source_spell_id')!=record.get('SpellID')or
row.get('wire_hex')!=wire.hex()or row.get('sha256')!=hashlib.sha256(wire).hexdigest()):raise ValueError('Source-owned package visual identity/wire differs')
if not all(any(p.get('table_name')==name and p.get('id')==record['SpellID']and p.get('record_status','valid')=='valid'for p in package['rows'])for name in('Spell','SpellName')):raise ValueError('Source visual definition parents missing')
native.append(record)
translated_source=deepcopy(source)
if visual_candidates is not None:
from spell_visual_compat import review_candidate
if not isinstance(visual_candidates,dict)or not isinstance(visual_schemas,dict):raise ValueError('Explicit source-owned visual mappings and schemas required')
needed={r['spellVisual1']for r in source if r['spellVisual1']}
# Existing same-ID links and newly mapped links can share one profile.
# Unmapped mismatches still fail the final source/native link check.
if not set(visual_candidates).issubset(needed):raise ValueError('Unrelated source-owned visual mapping')
for legacy,candidate in visual_candidates.items():
reviewed=review_candidate(candidate,visual_schemas,dict(SpellVisual=set(),SpellVisualEvent=set()))
if reviewed['source_visual_id']!=legacy:raise ValueError('Source/native visual mapping identity differs')
graph_tables={r['table_name']for r in reviewed['records']}
found=[r for r in package['rows']if r.get('table_name')in graph_tables and r.get('source_visual_id')==legacy]
if found!=reviewed['records']:raise ValueError('Mapped native visual records missing or changed')
for row in translated_source:
if row['spellVisual1']==legacy:row['spellVisual1']=reviewed['native_visual_id']
extra=generate(translated_source,native)
if extra['excluded']or len(extra['definitions'])!=len(source):raise ValueError('Complete unconditional source-owned links required')
rows=deepcopy(base);known={r['spell']:r for r in rows}
if len(known)!=len(rows):raise ValueError('Duplicate base profile identity')
for row in extra['definitions']:
if row['spell']in known:
if known[row['spell']]!=row:raise ValueError('Conflicting base visual profile')
else:rows.append(row);known[row['spell']]=row
return sorted(rows,key=lambda r:r['spell'])
def header(rows):
if not rows:
raise ValueError('No reviewed visual links')
return ('// Generated from reviewed source visuals and target-build SpellXSpellVisual rows.\n'
'#pragma once\n#include <algorithm>\n#include <cstdint>\n#include <iterator>\n'
'namespace gateway::aura_visual_profile {\n'
'struct Definition {uint32_t spell,link;};\ninline constexpr Definition Rows[]={'
+ ','.join('{'+str(r['spell'])+','+str(r['spell_x_spell_visual'])+'}' for r in rows)
+ '};\ninline uint32_t link(uint32_t spell){auto it=std::lower_bound(std::begin(Rows),std::end(Rows),spell,[](const auto& r,uint32_t s){return r.spell<s;});return it!=std::end(Rows)&&it->spell==spell?it->link:0;}\n}\n')
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
for key in ('source', 'native', 'output', 'header'):
p.add_argument('--'+key, type=Path, required=True)
a = p.parse_args()
if any(not path.resolve().is_relative_to(ROOT) for path in (a.output, a.header)) or a.output.exists():
p.error('Require workspace outputs and a new report')
result = generate(json.loads(a.source.read_text()), json.loads(a.native.read_text()))
result['input_sha256'] = {k: hashlib.sha256(getattr(a,k).read_bytes()).hexdigest() for k in ('source','native')}
a.header.write_text(header(result['definitions']))
a.output.write_text(json.dumps(result, indent=2)+'\n')
print('Generated', len(result['definitions']), 'reviewed visual links; model rendering unverified.')