367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
181 lines
13 KiB
Python
181 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""Build held, source-derived quest-map candidates from pinned map evidence.
|
|
|
|
This is an offline lookup for reviewing the existing POI response shape, not a
|
|
runtime provider. A zone rectangle does not prove the Source area, floor, WMO,
|
|
installed client cache, scripted/indirect objective coverage, or original POI
|
|
polygons. No generated candidate is authorized for native publication.
|
|
"""
|
|
import argparse
|
|
from collections import Counter
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import struct
|
|
from map_row_compat import encode, WORLD_MAP_TABLES
|
|
|
|
VERSION='quest-poi-source-lookup-v1'
|
|
|
|
def load_pinned(path,expected):
|
|
data=path.read_bytes();digest=hashlib.sha256(data).hexdigest()
|
|
if digest!=expected:raise ValueError('input SHA-256 differs: '+str(path))
|
|
return json.loads(data)
|
|
|
|
def physical_assignments(physical,decoded):
|
|
raw=physical['UiMapAssignment'];rows=decoded['UiMapAssignment']
|
|
if raw['skipped'] or rows['skipped']:raise ValueError('unreadable physical UiMapAssignment sections')
|
|
dr={r['ID']:r for r in rows['rows']}
|
|
if len(dr)!=len(rows['rows']) or len(dr)!=len(raw['rows']):raise ValueError('assignment identity mismatch')
|
|
fields=('UiMapID','OrderIndex','MapID','AreaID','WmoDoodadPlacementID','WmoGroupID','Unknown1125')
|
|
def fl(x):return struct.unpack('<f',struct.pack('<I',x))[0]
|
|
for record in raw['rows']:
|
|
r=dr.get(record['id']); f=record['f']
|
|
if not r or f[3]!=record['id'] or [fl(x) for x in f[0]]!=r['UiMin'] or [fl(x) for x in f[1]]!=r['UiMax'] or [fl(x) for x in f[2]]!=r['Region'] or f[4:]!=[r[k] for k in fields]:
|
|
raise ValueError('physical and decoded assignment differ')
|
|
return dr
|
|
|
|
def map_index(physical,decoded,package):
|
|
base=physical_assignments(physical,decoded)
|
|
physical_maps=physical['UiMap'];decoded_maps=decoded['UiMap']
|
|
if physical_maps['skipped'] or decoded_maps['skipped']:raise ValueError('unreadable physical UiMap sections')
|
|
maps={r['ID']:r for r in decoded_maps['rows']}
|
|
if len(maps)!=len(decoded_maps['rows']) or len(maps)!=len(physical_maps['rows']):raise ValueError('UiMap identity mismatch')
|
|
for entry in physical_maps['rows']:
|
|
r=maps.get(entry['id']);f=entry['f']
|
|
if not r or f[1]!=entry['id'] or entry['Name']!=r['Name'] or f[2:6]!=[r[k] for k in ('ParentUiMapID','Flags','System','Type')]:
|
|
raise ValueError('physical and decoded UiMap differ')
|
|
assignments=dict(base);replaced=set();seen=set()
|
|
for row in package['rows']:
|
|
if row.get('table_name') not in ('UiMap','UiMapAssignment'):continue
|
|
table=row['table_name'];ident=row['id'];key=(table,ident)
|
|
if key in seen:raise ValueError('duplicate package map row')
|
|
seen.add(key)
|
|
if row.get('record_status')!='valid' or row.get('record',{}).get('ID')!=ident:raise ValueError('invalid package map row')
|
|
wire=bytes.fromhex(row['wire_hex'])
|
|
if hashlib.sha256(wire).hexdigest()!=row['sha256']:raise ValueError('package map row wire hash differs')
|
|
if encode(row['record'],WORLD_MAP_TABLES[table][2])!=wire:raise ValueError('package map row record/wire mismatch')
|
|
if table=='UiMap':maps[ident]=row['record']
|
|
else:
|
|
if ident in base and row['record']!=base[ident]:replaced.add(ident)
|
|
assignments[ident]=row['record']
|
|
by_map={}
|
|
# Until the client's effective overlay is independently read back, a
|
|
# replaced physical row remains a competing map assignment witness.
|
|
variants=[(ident,r,False) for ident,r in assignments.items()]
|
|
variants.extend((ident,base[ident],True) for ident in replaced)
|
|
for ident,r,old_physical in variants:
|
|
meta=maps.get(r['UiMapID'])
|
|
if not meta or meta.get('Type')!=3:continue # Zone maps only; floor/dungeon rules are unproved.
|
|
region=r['Region'];ui_min=r['UiMin'];ui_max=r['UiMax']
|
|
if len(region)!=6 or len(ui_min)!=2 or len(ui_max)!=2 or not all(isinstance(x,(int,float)) and not isinstance(x,bool) and math.isfinite(x) for x in region+ui_min+ui_max):raise ValueError('invalid map region')
|
|
if any(region[i]>=region[i+3] for i in range(3)):raise ValueError('degenerate map region')
|
|
by_map.setdefault(r['MapID'],[]).append({'assignment':ident,'uimap':r['UiMapID'],'area':r['AreaID'],
|
|
'region':region,'wmo_doodad':r['WmoDoodadPlacementID'],'wmo_group':r['WmoGroupID'],
|
|
'physical_replaced':ident in replaced,'old_physical_variant':old_physical})
|
|
for rows in by_map.values():rows.sort(key=lambda r:(r['assignment'],r['old_physical_variant']))
|
|
return by_map
|
|
|
|
def point_qualification(spawn,by_map,pooled,evented,template_pooled):
|
|
entries=[e for e in spawn['entries'] if e]
|
|
if len(entries)!=1:return None,'alternate_or_missing_creature'
|
|
if spawn['guid'] in pooled or spawn['guid'] in evented or entries[0] in template_pooled:return None,'pool_or_event'
|
|
if spawn['spawn_flags'] or spawn['visibility_mod']!=0:return None,'flags_or_visibility'
|
|
if spawn['movement_type'] not in (0,1):return None,'movement'
|
|
x,y,z,w=(spawn[k] for k in ('x','y','z','wander'))
|
|
if not all(isinstance(v,(int,float)) and not isinstance(v,bool) and math.isfinite(v) for v in (x,y,z,w)) or w<0:return None,'invalid_geometry'
|
|
box=(math.floor(x-w),math.floor(y-w),math.ceil(x+w),math.ceil(y+w),round(z))
|
|
if any(v < -32768 or v > 32767 for v in box):return None,'outside_int16'
|
|
# Include WMO-constrained matches in ambiguity rather than pretending a
|
|
# missing WMO context excludes them. A partial intersection is ambiguous.
|
|
matches=[];partial=False
|
|
for a in by_map.get(spawn['map'],[]):
|
|
r=a['region'];inside=(r[0]<=box[0] and box[2]<=r[3] and r[1]<=box[1] and box[3]<=r[4] and r[2]<=z<=r[5])
|
|
overlaps=(box[2]>=r[0] and box[0]<=r[3] and box[3]>=r[1] and box[1]<=r[4] and r[2]<=z<=r[5])
|
|
if inside:matches.append(a)
|
|
elif overlaps:partial=True
|
|
if partial:return None,'crosses_assignment_boundary'
|
|
if not matches:return None,'no_zone_assignment'
|
|
if len(matches)!=1:return None,'overlapping_zone_assignments'
|
|
a=matches[0]
|
|
if a['wmo_doodad'] or a['wmo_group']:return None,'unresolved_wmo'
|
|
return {'entry':entries[0],'box':box,'source_map':spawn['map'],'assignment':a['assignment'],
|
|
'uimap':a['uimap'],'assignment_area_id':a['area'],'physical_replaced':a['physical_replaced']},None
|
|
|
|
def build(snapshot,dataset,physical,decoded,package,provenance):
|
|
if snapshot.get('schema')!='tortoise-quest-location-snapshot-v2' or dataset.get('schema')!='source-quest-objective-locations-v2':raise ValueError('source schema differs')
|
|
if dataset.get('source_snapshot_sha256')!=provenance['source_snapshot_sha256']:raise ValueError('dataset/source snapshot identity differs')
|
|
by_map=map_index(physical,decoded,package)
|
|
pools={v['guid'] for v in snapshot['spawn_pools']};events={v['guid'] for v in snapshot['events']};tpools={v['creature'] for v in snapshot['template_pools']}
|
|
indexed={};point_holds=Counter()
|
|
for spawn in snapshot['spawns']:
|
|
guid=spawn['guid']
|
|
if guid in indexed:raise ValueError('duplicate Source spawn GUID')
|
|
value,hold=point_qualification(spawn,by_map,pools,events,tpools);indexed[guid]=(spawn,value,hold)
|
|
quests=[];obj_total=0;candidate_total=0;refs_total=0;candidate_quests=0
|
|
for quest in dataset['quests']:
|
|
out=[];quest_has_candidate=False
|
|
for obj in quest['objectives']:
|
|
obj_total+=1;allowed={s['creature'] for s in obj['supported_sources'] if not s.get('phase_quest_id') and not s.get('condition_id')}
|
|
grouped={};holds=Counter();nrefs=0;seen_guids=set()
|
|
for cluster in obj['clusters']:
|
|
if 'point_refs' not in cluster:raise ValueError('expected compact source point references')
|
|
for guid,possible in cluster['point_refs']:
|
|
if guid in seen_guids:raise ValueError('duplicate objective spawn reference')
|
|
seen_guids.add(guid);nrefs+=1;row=indexed.get(guid)
|
|
if row is None:raise ValueError('missing snapshot spawn reference')
|
|
spawn,value,hold=row
|
|
if hold:holds[hold]+=1;continue
|
|
if value['entry'] not in allowed or value['entry'] not in possible:
|
|
holds['conditioned_or_uncaptured_source']+=1;continue
|
|
key=(value['source_map'],value['assignment'],value['uimap'],value['assignment_area_id'],tuple(cluster['cell']))
|
|
group=grouped.setdefault(key,[]);group.append((guid,value['box']))
|
|
point_holds.update(holds)
|
|
regions=[]
|
|
for (source_map,assignment,uimap,area,cell),points in sorted(grouped.items()):
|
|
boxes=[b for _,b in points];n=len(boxes)
|
|
regions.append({'source_map':source_map,'candidate_uimap':uimap,'assignment_area_id':area,'assignment_id':assignment,
|
|
'cell':cell,'bounds_xy':[min(b[0] for b in boxes),min(b[1] for b in boxes),max(b[2] for b in boxes),max(b[3] for b in boxes)],
|
|
'mean_z':round(sum(b[4] for b in boxes)/n),'spawn_guids':sorted(g for g,_ in points),
|
|
'physical_replaced':any(indexed[g][1]['physical_replaced'] for g,_ in points)})
|
|
ref_count=sum(len(r['spawn_guids']) for r in regions);refs_total+=ref_count
|
|
if regions:candidate_total+=1;quest_has_candidate=True
|
|
out.append({'presentation_index':obj['presentation_index'],'candidate_presentation_id':obj['candidate_presentation_id'],
|
|
'source_slot':obj['source_slot'],'native_storage_index':obj['native_storage_index'],'kind':obj['kind'],
|
|
'target':obj['target'],'required_count':obj['required_count'],'required_spell':obj.get('required_spell',0),'source_status':obj['status'],'source_holds':obj['holds'],
|
|
'candidate_holds':['source_area_and_ancestry_not_verified','native_effective_assignment_not_verified',
|
|
'runtime_spawn_phase_script_and_indirect_sources_not_closed','native_poi_semantics_not_generalized'],
|
|
'status':'held_not_for_native_publication' if regions else 'held_no_area_candidates','input_spawn_refs':nrefs,'candidate_spawn_refs':ref_count,
|
|
'excluded_ref_counts':dict(sorted(holds.items())),'regions':regions})
|
|
if quest_has_candidate:candidate_quests+=1
|
|
if out or quest['holds']:quests.append({'quest_id':quest['quest_id'],'objectives':out,'quest_holds':quest['holds']})
|
|
report={'source_quests':len(dataset['quests']),'source_objectives':obj_total,'quests_with_held_candidates':candidate_quests,
|
|
'objectives_with_held_candidates':candidate_total,'candidate_spawn_references':refs_total,
|
|
'excluded_reference_counts_all_objectives':dict(sorted(point_holds.items())),
|
|
'native_publishable_objectives':0}
|
|
return {'schema':VERSION,'provenance':provenance,'semantics':'held Source-world spawn envelopes; not original quest polygons',
|
|
'native_publication_allowed':False,'quests':quests,'coverage':report}
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
for name in ('snapshot','dataset','physical','decoded','package'):
|
|
p.add_argument('--'+name,type=Path,required=True);p.add_argument('--'+name+'-sha256',required=True)
|
|
p.add_argument('--physical-uimap-db2',type=Path,required=True);p.add_argument('--physical-assignment-db2',type=Path,required=True)
|
|
p.add_argument('--output',type=Path,required=True);p.add_argument('--report',type=Path,required=True)
|
|
a=p.parse_args();values={name:load_pinned(getattr(a,name),getattr(a,name+'_sha256')) for name in ('snapshot','dataset','physical','decoded','package')}
|
|
provenance={name+'_sha256':getattr(a,name+'_sha256') for name in values};provenance['source_snapshot_sha256']=provenance['snapshot_sha256']
|
|
for name,path in (('UiMap',a.physical_uimap_db2),('UiMapAssignment',a.physical_assignment_db2)):
|
|
with path.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
|
|
if digest!=values['physical'][name]['sha256']:raise ValueError('physical DB2 hash differs: '+name)
|
|
provenance['physical_'+name+'_db2_sha256']=digest
|
|
provenance['installed_state']='package and physical witnesses pinned; effective running client map rows unverified'
|
|
value=build(**values,provenance=provenance)
|
|
a.output.parent.mkdir(parents=True,exist_ok=True);tmp=a.output.with_name(a.output.name+'.tmp')
|
|
with tmp.open('w') as f:json.dump(value,f,separators=(',',':'),sort_keys=True,allow_nan=False);f.write('\n')
|
|
tmp.replace(a.output)
|
|
with a.output.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest()
|
|
report={'lookup_sha256':digest,**value['coverage'],'provenance':provenance}
|
|
a.report.parent.mkdir(parents=True,exist_ok=True);a.report.write_text(json.dumps(report,indent=2,sort_keys=True)+'\n')
|
|
print('Held quest map lookup generated')
|
|
if __name__=='__main__':main()
|