92 lines
7.6 KiB
Python
92 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Stage the fixed Tirisfal survey and immediate neighbours using the Turtle-changed predicate."""
|
|
import argparse,collections,hashlib,json,sys,subprocess
|
|
from pathlib import Path
|
|
from PIL import Image
|
|
from minimap_neighbor_stage import Source,tile,logical,save,load,digest,write_blp
|
|
from minimap_seam_audit import edge_difference
|
|
from octo_parity.turtle_changed import classify
|
|
import octo_client_data as data
|
|
|
|
class LogicalArchive:
|
|
"""Expose a logical tile through each side's own minimap translation table."""
|
|
def __init__(self,source,name,handle,mapping):self.source=source;self.name=name;self.handle=handle;self.mapping=mapping;self.cache={}
|
|
def find(self,path):
|
|
if path not in self.cache:
|
|
name=self.mapping.get(path.lower());member='Textures\\Minimap\\'+name if name else None
|
|
if member and ('..' in name or ':' in name):raise ValueError('Minimap translation path')
|
|
raw=data.read_member(self.source.api,self.handle,member) if member else None
|
|
self.cache[path]=(raw,member)
|
|
return path if self.cache[path][0] is not None else None
|
|
def read(self,path):self.find(path);return self.cache[path][0]
|
|
def proof(self,path,root):
|
|
raw=self.read(path)
|
|
if raw is None:return None
|
|
sha=hashlib.sha256(raw).hexdigest();dest=root/'source-blobs'/sha
|
|
if not dest.exists():dest.write_bytes(raw)
|
|
return {'archive':self.name,'member':self.cache[path][1],'sha256':sha,'file':str(dest)}
|
|
def translation(raw):return {a.strip().lower():b.strip() for line in raw.decode('latin1').splitlines() for a,sep,b in [line.partition('\t')] if sep and not a.lower().startswith('dir:')}
|
|
def run(a):
|
|
root=a.root;root.mkdir(parents=True,exist_ok=True);pin=digest(a.client/'.build.info');source=Source(a.source,root)
|
|
initial=load(a.seed/'candidate-assets.json');seed={tile(r['path']):r for r in initial};survey={tuple(r['tile']) for r in load(a.seed/'geometry-variants.json')}
|
|
# One fixed survey border, not recursive seam propagation.
|
|
scope={(x+dx,y+dy) for x,y in survey for dx in (-1,0,1) for dy in (-1,0,1) if 0<=x+dx<64 and 0<=y+dy<64}
|
|
base_trs=None
|
|
for path,handle,_,_ in source.handles:
|
|
if path.name.lower().startswith('patch-'):continue
|
|
raw=data.read_member(source.api,handle,'Textures\\Minimap\\md5translate.trs')
|
|
if raw is not None:base_trs=translation(raw);break
|
|
if base_trs is None:raise ValueError('Base 1.12 minimap translation required')
|
|
adapters=[(path.name,LogicalArchive(source,path.name,handle,source.mapping if path.name.lower().startswith('patch-') else base_trs)) for path,handle,_,_ in source.handles];by_name=dict(adapters);decisions=[];wanted={}
|
|
try:
|
|
for t in sorted(scope):
|
|
name=f'azeroth\\map{t[0]:02d}_{t[1]:02d}.blp';decision=classify(name,adapters);decision['tile']=t;decision['seed']=t in seed
|
|
decision['turtle_proof']=by_name[decision['turtle']].proof(name,root) if decision['turtle'] else None
|
|
decision['base_proof']=by_name[decision['base']].proof(name,root) if decision['base'] else None
|
|
if t in seed or decision['status'] in ('turtle-new','turtle-changed'):
|
|
value=source.image(t)
|
|
if value is None:raise ValueError('Selected tile lacks effective Source image')
|
|
im,proof=value
|
|
if t in seed and proof['sha256']!=seed[t]['source_sha256']:raise ValueError('Original seed Source pin changed')
|
|
wanted[t]=(im,proof,decision)
|
|
decisions.append(decision)
|
|
finally:source.close()
|
|
save(root/'eligibility.json',decisions);save(root/'scope.json',{'survey':sorted(survey),'fixed_neighbour_scope':sorted(scope),'recursive_rings':False})
|
|
lookup={}
|
|
for line in a.listfile.open():
|
|
ident,_,name=line.rstrip().partition(';')
|
|
if name.lower().startswith('world/minimaps/azeroth/map') and name.lower().endswith('.blp'):lookup[name.lower()]=int(ident)
|
|
neighbours=set(wanted)
|
|
for x,y in wanted:neighbours.update([(x-1,y),(x+1,y),(x,y-1),(x,y+1)])
|
|
ids={lookup[logical(t)] for t in neighbours if logical(t) in lookup};req=root/'native-ids.txt';req.write_text(''.join(str(i)+'\n' for i in sorted(ids)));native=root/'native-minimaps';native.mkdir(exist_ok=True)
|
|
with (root/'native-extract.log').open('w') as log:subprocess.run([str(a.casc),'extract-batch','--from-list',str(req),str(native),'--locale','enus','--storage',str(a.client),'--listfile',str(a.listfile)],stdout=log,stderr=subprocess.STDOUT)
|
|
if digest(a.client/'.build.info')!=pin:raise ValueError('LOCAL parent changed')
|
|
rows=[];selected={}
|
|
for t,(im,proof,decision) in sorted(wanted.items()):
|
|
before=native/logical(t)
|
|
if not before.exists():raise ValueError('Selected changed tile has no native resource: '+str(t))
|
|
dest=root/'candidate-assets'/logical(t);dest.parent.mkdir(parents=True,exist_ok=True)
|
|
if t in seed:
|
|
raw=Path(seed[t]['file']).read_bytes()
|
|
if hashlib.sha256(raw).hexdigest()!=seed[t]['after_sha256']:raise ValueError('Seed candidate pin changed')
|
|
dest.write_bytes(raw)
|
|
else:write_blp(im,str(dest))
|
|
row={'file_data_id':lookup[logical(t)],'path':logical(t),'file':str(dest),'before_sha256':digest(before),'after_sha256':digest(dest),'source_sha256':proof['sha256'],'source_file':proof['file'],'source_archive':proof['archive'],'eligibility':decision['status'],'seed':t in seed,'bytes':dest.stat().st_size};rows.append(row);selected[t]=row
|
|
def read(path):
|
|
image=Image.open(path);image.load();return image.convert('RGB')
|
|
boundaries=[];internal=[];seen=set();decisions_by_tile={tuple(r['tile']):r for r in decisions}
|
|
for x,y in selected:
|
|
for left,right,axis in [((x,y),(x+1,y),'x'),((x-1,y),(x,y),'x'),((x,y),(x,y+1),'y'),((x,y-1),(x,y),'y')]:
|
|
if (left,right) in seen:continue
|
|
seen.add((left,right));lp=Path(selected[left]['file']) if left in selected else native/logical(left);rp=Path(selected[right]['file']) if right in selected else native/logical(right)
|
|
row={'a':left,'b':right,'axis':axis,'delta':edge_difference(read(lp),read(rp),axis)['mean_rgb_delta'] if lp.exists() and rp.exists() else None}
|
|
if left in selected and right in selected:internal.append(row)
|
|
else:
|
|
outside=right if left in selected else left;decision=decisions_by_tile.get(outside);row.update(retained_native=outside,outside_status=decision['status'] if decision else 'outside fixed survey',reason='base-only or unchanged Source stays native; no numerical seam gate' if decision else 'outside fixed Tirisfal/neighbour survey; retained native');boundaries.append(row)
|
|
save(root/'candidate-assets.json',rows);save(root/'boundaries.json',boundaries);save(root/'internal-source-seams.json',internal)
|
|
report={'parent_build_info_sha256':pin,'survey_tiles':len(survey),'scope_tiles':len(scope),'seed_tiles':45,'candidate_tiles':len(rows),'additional_turtle_changed':len(rows)-45,'eligibility_counts':dict(collections.Counter(r['status'] for r in decisions)),'retained_native_boundaries':len(boundaries),'unmeasurable_boundaries':sum(r['delta'] is None for r in boundaries),'worst_measured_boundary':max(r['delta'] for r in boundaries if r['delta'] is not None),'source_internal_seams_accepted':True,'numeric_seam_gate':False,'geometry_changed':False,'installed':False,'publication':'HOLD'};save(root/'report.json',report);print(json.dumps(report))
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
for name in ['root','seed','client','source','listfile','casc']:p.add_argument('--'+name,type=Path,required=True)
|
|
run(p.parse_args())
|