367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
280 lines
19 KiB
Python
280 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Build approximate Source quest-objective point clusters from read-only data.
|
|
|
|
Capture is explicitly scoped to numeric quest IDs, and issues only SELECTs to
|
|
an existing local Docker MariaDB. Build accepts that snapshot offline. Output
|
|
is Source-world evidence, not a native QuestPOI packet or polygon.
|
|
"""
|
|
from __future__ import annotations
|
|
import argparse
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import subprocess
|
|
|
|
SCHEMA = 'source-quest-objective-locations-v2'
|
|
SNAPSHOT = 'tortoise-quest-location-snapshot-v2'
|
|
MAX_QUESTS = 128
|
|
MAX_ROWS = 50000
|
|
CELL_SIZE = 128.0
|
|
|
|
|
|
def checked_int(value, lo, hi, name):
|
|
if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
|
|
raise ValueError(f'{name} outside supported range')
|
|
return value
|
|
|
|
|
|
def _numbers(values):
|
|
for x in values:checked_int(x,1,0xffffffff,'identity')
|
|
return ','.join(str(x) for x in sorted(set(values))) or 'NULL'
|
|
|
|
|
|
def _select(container, sql, max_rows=MAX_ROWS):
|
|
# The Docker argument is never interpreted as shell. Credentials remain
|
|
# inside the existing DB container and never enter argv, output or files.
|
|
cmd = ['docker', 'exec', '-i', container, 'sh', '-c',
|
|
'export MYSQL_PWD="${MARIADB_ROOT_PASSWORD:-$MYSQL_ROOT_PASSWORD}"; '
|
|
'exec mariadb -uroot --batch --skip-column-names --raw tw_world']
|
|
result = subprocess.run(cmd, input=sql+'\n', text=True, capture_output=True, check=True)
|
|
rows = [line.split('\t') for line in result.stdout.splitlines()]
|
|
if len(rows) > max_rows:
|
|
raise ValueError('read-only capture row bound exceeded')
|
|
return rows, hashlib.sha256(result.stdout.encode()).hexdigest()
|
|
|
|
|
|
def capture(container, quest_ids):
|
|
if not quest_ids or len(set(quest_ids)) > MAX_QUESTS:
|
|
raise ValueError('quest scope must contain 1..128 distinct IDs')
|
|
for ident in quest_ids:checked_int(ident,1,0x1fffffff,'quest ID')
|
|
ids = _numbers(quest_ids)
|
|
server_rows,server_hash=_select(container,'SELECT @@server_id,VERSION(),@@hostname;')
|
|
if len(server_rows)!=1 or len(server_rows[0])!=3:raise ValueError('unexpected Source server identity')
|
|
quest_sql = ('SELECT entry,' + ','.join('ReqCreatureOrGOId%d' % i for i in range(1,5)) + ','
|
|
+ ','.join('ReqCreatureOrGOCount%d' % i for i in range(1,5)) + ','
|
|
+ ','.join('ReqSpellCast%d' % i for i in range(1,5)) + ','
|
|
+ ','.join('ReqItemId%d' % i for i in range(1,5)) + ','
|
|
+ ','.join('ReqItemCount%d' % i for i in range(1,5))
|
|
+ ' FROM quest_template WHERE entry IN ('+ids+') ORDER BY entry;')
|
|
rows, quest_hash = _select(container, quest_sql)
|
|
quests=[]
|
|
for row in rows:
|
|
if len(row)!=21: raise ValueError('unexpected quest query shape')
|
|
v=list(map(int,row));quests.append({'id':v[0], 'creature_or_go':v[1:5], 'creature_or_go_count':v[5:9],
|
|
'required_spells':v[9:13], 'items':v[13:17], 'item_count':v[17:21]})
|
|
if {q['id'] for q in quests} != set(quest_ids):
|
|
raise ValueError('requested Source quest missing or duplicated')
|
|
item_ids = [x for q in quests for x in q['items'] if x>0]
|
|
loot_sql = ('SELECT c.entry,c.loot_id,l.item,l.ChanceOrQuestChance,l.groupid,l.mincountOrRef,l.maxcount,l.condition_id '
|
|
'FROM creature_loot_template l JOIN creature_template c ON c.loot_id=l.entry '
|
|
'WHERE l.item IN ('+_numbers(item_ids)+') ORDER BY c.entry,l.item,l.groupid,l.mincountOrRef,l.condition_id LIMIT 50001;')
|
|
rows, loot_hash = _select(container, loot_sql)
|
|
loot=[]
|
|
for row in rows:
|
|
if len(row)!=8: raise ValueError('unexpected creature loot query shape')
|
|
loot.append({'creature':int(row[0]),'loot_id':int(row[1]),'item':int(row[2]),'chance':float(row[3]),
|
|
'group':int(row[4]),'min_or_ref':int(row[5]),'max':int(row[6]),'condition':int(row[7])})
|
|
entries = {x for q in quests for x in q['creature_or_go'] if x>0} | {r['creature'] for r in loot}
|
|
entry_sql = _numbers(entries)
|
|
template_sql='SELECT entry,loot_id,phase_quest_id FROM creature_template WHERE entry IN ('+entry_sql+') ORDER BY entry LIMIT 50001;'
|
|
rows,template_hash=_select(container,template_sql)
|
|
templates=[{'creature':int(r[0]),'loot_id':int(r[1]),'phase_quest_id':int(r[2])} for r in rows]
|
|
where = '('+' OR '.join('id%s IN (%s)' % ('' if i==1 else i,entry_sql) for i in range(1,5))+')'
|
|
spawn_sql = ('SELECT guid,id,id2,id3,id4,map,position_x,position_y,position_z,wander_distance,movement_type,spawn_flags,visibility_mod '
|
|
'FROM creature WHERE '+where+' ORDER BY guid LIMIT 50001;')
|
|
rows, spawn_hash = _select(container, spawn_sql)
|
|
spawns=[]
|
|
for row in rows:
|
|
if len(row)!=13: raise ValueError('unexpected creature spawn query shape')
|
|
spawns.append({'guid':int(row[0]),'entries':[int(v) for v in row[1:5]],'map':int(row[5]),
|
|
'x':float(row[6]),'y':float(row[7]),'z':float(row[8]),'wander':float(row[9]),
|
|
'movement_type':int(row[10]),'spawn_flags':int(row[11]),
|
|
'visibility_mod':None if row[12]=='NULL' else float(row[12])})
|
|
guids=_numbers([s['guid'] for s in spawns])
|
|
pool_sql='SELECT guid,pool_entry,chance,flags FROM pool_creature WHERE guid IN ('+guids+') ORDER BY guid,pool_entry LIMIT 50001;'
|
|
rows,pool_hash=_select(container,pool_sql)
|
|
pools=[{'guid':int(r[0]),'pool':int(r[1]),'chance':float(r[2]),'flags':int(r[3])} for r in rows]
|
|
template_pool_sql='SELECT id,pool_entry,chance,flags FROM pool_creature_template WHERE id IN ('+entry_sql+') ORDER BY id,pool_entry LIMIT 50001;'
|
|
rows,template_pool_hash=_select(container,template_pool_sql)
|
|
template_pools=[{'creature':int(r[0]),'pool':int(r[1]),'chance':float(r[2]),'flags':int(r[3])} for r in rows]
|
|
event_sql='SELECT guid,event FROM game_event_creature WHERE guid IN ('+guids+') ORDER BY guid,event LIMIT 50001;'
|
|
rows,event_hash=_select(container,event_sql)
|
|
events=[{'guid':int(r[0]),'event':int(r[1])} for r in rows]
|
|
return {'schema':SNAPSHOT,'capture_utc':dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
'source':{'kind':'local-docker-read-only-select','container':container,'database':'tw_world',
|
|
'server_id':server_rows[0][0],'server_version':server_rows[0][1],'server_hostname':server_rows[0][2],
|
|
'consistency':'separate SELECTs; no atomic snapshot claimed',
|
|
'queries_sha256':{'server':server_hash,'quest':quest_hash,'loot':loot_hash,'spawns':spawn_hash,
|
|
'templates':template_hash,'spawn_pools':pool_hash,'template_pools':template_pool_hash,'events':event_hash}},
|
|
'quests':quests,'direct_loot_rows':loot,'templates':templates,'spawns':spawns,'spawn_pools':pools,
|
|
'template_pools':template_pools,'events':events}
|
|
|
|
|
|
def _list4(row,key):
|
|
v=row.get(key)
|
|
if not isinstance(v,list) or len(v)!=4 or any(isinstance(x,bool) or not isinstance(x,int) for x in v):
|
|
raise ValueError('quest '+key+' must contain four integers')
|
|
return v
|
|
|
|
|
|
def build(snapshot, snapshot_sha256, *, max_quests=MAX_QUESTS, max_rows=MAX_ROWS):
|
|
checked_int(max_quests,1,10000,'quest build bound')
|
|
checked_int(max_rows,1,1000000,'row build bound')
|
|
if not isinstance(snapshot,dict) or snapshot.get('schema')!=SNAPSHOT:
|
|
raise ValueError('unrecognized Source snapshot')
|
|
quests=snapshot.get('quests');loot=snapshot.get('direct_loot_rows');spawns=snapshot.get('spawns')
|
|
templates=snapshot.get('templates');pools=snapshot.get('spawn_pools');template_pools=snapshot.get('template_pools');events=snapshot.get('events')
|
|
for rows in (quests,loot,templates,spawns,pools,template_pools,events):
|
|
if not isinstance(rows,list) or len(rows)>max_rows:raise ValueError('snapshot row bound')
|
|
if len(quests)>max_quests:raise ValueError('quest bound')
|
|
spawn_by_guid={};by_entry={}
|
|
for s in spawns:
|
|
guid=checked_int(s.get('guid'),1,0xffffffff,'spawn GUID')
|
|
if guid in spawn_by_guid:raise ValueError('duplicate Source spawn GUID')
|
|
entries=s.get('entries')
|
|
if not isinstance(entries,list) or len(entries)!=4:raise ValueError('spawn entries')
|
|
for x in entries:checked_int(x,0,0x1fffffff,'creature entry')
|
|
checked_int(s.get('map'),0,0x7fffffff,'source map')
|
|
for key in ('x','y','z','wander'):
|
|
if isinstance(s.get(key),bool) or not isinstance(s.get(key),(int,float)) or not math.isfinite(s[key]):raise ValueError('nonfinite spawn coordinate or wander')
|
|
if s['wander']<0:raise ValueError('negative wander')
|
|
for key in ('movement_type','spawn_flags'):checked_int(s.get(key),0,0xffffffff,key)
|
|
visibility=s.get('visibility_mod')
|
|
if visibility is not None and (isinstance(visibility,bool) or not isinstance(visibility,(int,float)) or not math.isfinite(visibility)):
|
|
raise ValueError('invalid visibility modifier')
|
|
spawn_by_guid[guid]=s
|
|
for e in set(entries)-{0}:by_entry.setdefault(e,[]).append(s)
|
|
def index(rows,key):
|
|
out={}
|
|
for r in rows:out.setdefault(r[key],[]).append(r)
|
|
return out
|
|
pool_by_guid=index(pools,'guid');pool_by_template=index(template_pools,'creature');event_by_guid=index(events,'guid')
|
|
templates_by_id={}
|
|
for t in templates:
|
|
ident=checked_int(t.get('creature'),1,0x1fffffff,'creature template')
|
|
if ident in templates_by_id:raise ValueError('duplicate creature template')
|
|
checked_int(t.get('loot_id'),0,0xffffffff,'template loot ID')
|
|
checked_int(t.get('phase_quest_id'),0,0xffffffff,'template phase quest')
|
|
templates_by_id[ident]=t
|
|
loot_by_item=index(loot,'item');results=[];seen=set()
|
|
for q in sorted(quests,key=lambda q:q['id']):
|
|
qid=checked_int(q.get('id'),1,0x1fffffff,'quest ID')
|
|
if qid in seen:raise ValueError('duplicate Source quest')
|
|
seen.add(qid);creatures=_list4(q,'creature_or_go');creature_counts=_list4(q,'creature_or_go_count');required_spells=_list4(q,'required_spells');items=_list4(q,'items');item_counts=_list4(q,'item_count')
|
|
objective_index=0;objectives=[]
|
|
quest_holds=[{'source_slot':i,'required_spell':spell,'reason':'spell_without_creature_or_gameobject_target_not_implemented'}
|
|
for i,spell in enumerate(required_spells) if spell and not creatures[i]]
|
|
for kind,ids,counts in [('creature_or_gameobject',creatures,creature_counts),('item',items,item_counts)]:
|
|
for source_index,(ident,count) in enumerate(zip(ids,counts)):
|
|
if not ident:continue
|
|
row={'presentation_index':objective_index,'candidate_presentation_id':(qid<<3)|objective_index,
|
|
'source_slot':source_index,'native_storage_index':source_index+(4 if kind=='item' else 0),
|
|
'kind':kind,'target':ident,'required_count':count,
|
|
'status':'partial','supported_sources':[],'holds':[],'clusters':[]}
|
|
objective_index+=1
|
|
if count<=0 or count>(32767 if kind=='item' else 0x7fffffff):
|
|
row['status']='held';row['holds'].append('invalid_or_unreviewed_objective_count');objectives.append(row);continue
|
|
if kind=='creature_or_gameobject':
|
|
row['required_spell']=required_spells[source_index]
|
|
if row['required_spell']:
|
|
row['status']='held';row['holds'].append('spell_target_objective_not_implemented');objectives.append(row);continue
|
|
if kind=='creature_or_gameobject' and ident<0:
|
|
row['status']='held';row['holds'].append('gameobject_objective_not_implemented');objectives.append(row);continue
|
|
if ident<=0 or ident>0x1fffffff:
|
|
row['status']='held';row['holds'].append('target_identity_outside_supported_range');objectives.append(row);continue
|
|
if kind=='creature_or_gameobject':
|
|
sources=[{'creature':ident,'evidence':'direct_creature_kill'}]
|
|
row['holds']+=['scripted_credit_or_other_source_unresolved']
|
|
else:
|
|
sources=[]
|
|
for l in loot_by_item.get(ident,[]):
|
|
if l['min_or_ref']<=0:
|
|
row['holds'].append('loot_reference_row_not_resolved');continue
|
|
if not math.isfinite(l['chance']):raise ValueError('nonfinite loot chance')
|
|
if l['max']<l['min_or_ref']:
|
|
row['holds'].append('invalid_direct_loot_count_range');continue
|
|
sources.append({'creature':l['creature'],'evidence':'direct_creature_loot','loot_id':l['loot_id'],
|
|
'chance_or_quest_chance':l['chance'],'group':l['group'],'min_count':l['min_or_ref'],
|
|
'max_count':l['max'],'condition_id':l['condition']})
|
|
if any(s.get('condition_id') for s in sources):row['holds'].append('source_loot_condition_not_evaluated')
|
|
row['holds']+=['reference_loot_gameobject_quest_spell_or_script_sources_not_exhaustively_resolved']
|
|
for s in sources:
|
|
template=templates_by_id.get(s['creature'])
|
|
if template is None:row['holds'].append('source_creature_template_not_captured');continue
|
|
if s['evidence']=='direct_creature_loot' and s['loot_id']!=template['loot_id']:
|
|
row['holds'].append('source_creature_loot_changed_during_capture');continue
|
|
s['phase_quest_id']=template['phase_quest_id']
|
|
if s['phase_quest_id']:row['holds'].append('source_quest_phase_condition_not_evaluated')
|
|
row['supported_sources'].append(s)
|
|
row['supported_sources'].sort(key=lambda s:(s['creature'],s.get('loot_id',0),s.get('condition_id',0)))
|
|
points={}
|
|
for source in row['supported_sources']:
|
|
entry=checked_int(source['creature'],1,0x1fffffff,'creature entry')
|
|
for spawn in by_entry.get(entry,[]):
|
|
guid=spawn['guid'];flags=spawn['spawn_flags']
|
|
if flags&0x02:row['holds'].append('disabled_source_spawns_excluded');continue
|
|
if flags&0x80:row['holds'].append('dead_by_default_source_spawns_excluded');continue
|
|
if guid not in points:
|
|
points[guid]={'guid':guid,'source_map':spawn['map'],'x':spawn['x'],'y':spawn['y'],'z':spawn['z'],
|
|
'wander_radius':spawn['wander'],'movement_type':spawn['movement_type'],'spawn_flags':flags,
|
|
'visibility_mod':spawn['visibility_mod'],'spawn_template_choices':spawn['entries'],
|
|
'possible_creature_entries':[],
|
|
'spawn_pools':pool_by_guid.get(guid,[]),'template_pools':[],
|
|
'events':event_by_guid.get(guid,[]),'runtime_presence':'not_verified','phase':'not_resolved',
|
|
'native_int16_xyz_range':all(-32768<=spawn[k]<=32767 for k in ('x','y','z'))}
|
|
p=points[guid]
|
|
if entry not in p['possible_creature_entries']:p['possible_creature_entries'].append(entry)
|
|
for pool in pool_by_template.get(entry,[]):
|
|
if pool not in p['template_pools']:p['template_pools'].append(pool)
|
|
grid={}
|
|
for p in points.values():
|
|
p['possible_creature_entries'].sort()
|
|
key=(p['source_map'],math.floor(p['x']/CELL_SIZE),math.floor(p['y']/CELL_SIZE))
|
|
grid.setdefault(key,[]).append(p)
|
|
for (source_map,gx,gy),ps in sorted(grid.items()):
|
|
ps.sort(key=lambda p:p['guid']);n=len(ps)
|
|
row['clusters'].append({'source_map':source_map,'cell':[gx,gy],'cell_size_world_units':CELL_SIZE,
|
|
'centroid_xyz':[sum(p[k] for p in ps)/n for k in ('x','y','z')],
|
|
'bounds_xy':[min(p['x'] for p in ps),min(p['y'] for p in ps),max(p['x'] for p in ps),max(p['y'] for p in ps)],
|
|
'point_count':n,'points':ps})
|
|
if any(p['spawn_pools'] or p['template_pools'] for p in points.values()):row['holds'].append('source_spawn_pool_not_resolved')
|
|
if any(p['events'] for p in points.values()):row['holds'].append('source_spawn_event_not_resolved')
|
|
if any(sum(bool(e) for e in p['spawn_template_choices'])>1 for p in points.values()):row['holds'].append('source_alternate_spawn_template_not_resolved')
|
|
if not points:row['holds'].append('no_qualified_static_creature_spawn')
|
|
if any(not p['native_int16_xyz_range'] for p in points.values()):
|
|
row['holds'].append('some_source_xyz_outside_native_int16_range')
|
|
if any(p['spawn_flags']&0x40 for p in points.values()):
|
|
row['holds'].append('some_source_spawns_flagged_not_visible')
|
|
if any(p['spawn_flags']&~(0x02|0x40|0x80) for p in points.values()):
|
|
row['holds'].append('unreviewed_source_spawn_flags')
|
|
if any(p['visibility_mod'] not in (None,0) for p in points.values()):
|
|
row['holds'].append('source_visibility_modifier_not_evaluated')
|
|
if any(p['movement_type'] not in (0,1) for p in points.values()):
|
|
row['holds'].append('source_scripted_or_waypoint_movement_not_resolved')
|
|
row['holds']+=['runtime_spawn_presence_not_verified','phase_and_native_uimap_assignment_not_resolved']
|
|
row['holds']=sorted(set(row['holds']));objectives.append(row)
|
|
results.append({'quest_id':qid,'objectives':objectives,'holds':quest_holds})
|
|
return {'schema':SCHEMA,'source_snapshot_sha256':snapshot_sha256,'source':snapshot.get('source'),
|
|
'point_semantics':'approximate Source-world static spawn anchors; deterministic grid summaries are not polygons',
|
|
'limitations':['no native POI responses','no complete quest/source catalogue claim','no gameobject objectives or indirect loot closure',
|
|
'pool/event/phase and runtime presence remain uncertain','no Source-to-native map assignment claimed'],
|
|
'quests':results}
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='mode',required=True)
|
|
cap=sub.add_parser('capture');cap.add_argument('--container',required=True);cap.add_argument('--quest',type=int,action='append',required=True);cap.add_argument('--output',type=Path,required=True)
|
|
gen=sub.add_parser('build');gen.add_argument('--snapshot',type=Path,required=True);gen.add_argument('--output',type=Path,required=True)
|
|
args=parser.parse_args()
|
|
if args.mode=='capture':value=capture(args.container,args.quest)
|
|
else:
|
|
data=args.snapshot.read_bytes();value=build(json.loads(data),hashlib.sha256(data).hexdigest())
|
|
value['source_snapshot_path']=str(args.snapshot.resolve())
|
|
args.output.parent.mkdir(parents=True,exist_ok=True)
|
|
args.output.write_text(json.dumps(value,indent=2,sort_keys=True,allow_nan=False)+'\n')
|
|
print('Source quest-location '+args.mode+' complete')
|
|
|
|
if __name__=='__main__':main()
|