340 lines
15 KiB
Python
340 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Survey live Azeroth/Kalimdor minimap water and stage lossless BC1 edits."""
|
|
import argparse
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import struct
|
|
import subprocess
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image
|
|
|
|
from booty_bay_minimap import opaque_bc1, replace_cells
|
|
from booty_bay_shore import bc1_rgb
|
|
from minimap_neighbor_stage import Source
|
|
import map_asset_preflight as terrain
|
|
|
|
MAPS = (('azeroth', 8560809), ('kalimdor', 8560806))
|
|
|
|
|
|
def chunks(raw):
|
|
at = 0
|
|
while at < len(raw):
|
|
if at + 8 > len(raw):
|
|
raise ValueError('truncated chunk')
|
|
tag = raw[at:at+4][::-1].decode('ascii')
|
|
size = struct.unpack_from('<I', raw, at+4)[0]
|
|
if at + 8 + size > len(raw):
|
|
raise ValueError('unbounded chunk')
|
|
yield tag, raw[at+8:at+8+size]
|
|
at += size + 8
|
|
|
|
|
|
def wdt_rows(raw):
|
|
sections = dict(chunks(raw))
|
|
maid = sections['MAID']
|
|
if len(maid) != 4096*32:
|
|
raise ValueError('unexpected WDT MAID')
|
|
return [(i%64, i//64, row[0], row[7])
|
|
for i, row in enumerate(struct.iter_unpack('<8I', maid)) if row[7]]
|
|
|
|
|
|
def wet_cells(raw):
|
|
"""MH2O occupied 8x8 terrain cells, expanded to minimap pixels."""
|
|
sections = dict(chunks(raw))
|
|
result = np.zeros((128, 128), dtype=bool)
|
|
liquid = sections.get('MH2O')
|
|
if liquid is None:
|
|
return result
|
|
if len(liquid) < 256*12:
|
|
raise ValueError('short MH2O')
|
|
for cy in range(16):
|
|
for cx in range(16):
|
|
off, count, _ = struct.unpack_from('<III', liquid, (cy*16+cx)*12)
|
|
if not count:
|
|
continue
|
|
if not off or off + count*24 > len(liquid):
|
|
raise ValueError('unbounded MH2O layers')
|
|
for layer in range(count):
|
|
pos = off + layer*24
|
|
typ, obj, lo, hi, ox, oy, width, height, bits, verts = struct.unpack_from('<HHffBBBBII', liquid, pos)
|
|
if width > 8 or height > 8 or ox+width > 8 or oy+height > 8:
|
|
raise ValueError('unbounded MH2O footprint')
|
|
if not width or not height:
|
|
continue
|
|
nbytes = (width*height+7)//8
|
|
if bits and (bits < 256*12 or bits+nbytes > len(liquid)):
|
|
raise ValueError('unbounded MH2O bitmap')
|
|
mask = int.from_bytes(liquid[bits:bits+nbytes], 'little') if bits else (1 << (width*height))-1
|
|
for y in range(height):
|
|
for x in range(width):
|
|
if mask >> (y*width+x) & 1:
|
|
result[cy*8+oy+y, cx*8+ox+x] = True
|
|
return result
|
|
|
|
|
|
def source_water(rgb):
|
|
a = rgb.astype(np.int16)
|
|
return (a[:,:,0]+12 < a[:,:,1]) & (a[:,:,0]+12 < a[:,:,2])
|
|
|
|
|
|
def true_water_loss(source_rgb, live_rgb):
|
|
"""Count Source water with no nearby live water, across colour styles."""
|
|
from PIL import ImageFilter
|
|
source_hsv=np.asarray(Image.fromarray(source_rgb).convert('HSV'))
|
|
live_hsv=np.asarray(Image.fromarray(live_rgb).convert('HSV'))
|
|
# Pale blue snow satisfies the simple RGB water test. Require colour.
|
|
source=source_water(source_rgb) & (source_hsv[:,:,1]>=38)
|
|
hue=live_hsv[:,:,0].astype(float)*360/255
|
|
# Retail water may be dark green/teal, as on the 32_53 river.
|
|
live=(hue>=60)&(hue<=220)&(live_hsv[:,:,1]>=38)&(live_hsv[:,:,2]<190)
|
|
nearby=np.asarray(Image.fromarray((live*255).astype('uint8')).filter(ImageFilter.MaxFilter(17)))>0
|
|
return int((source&~nearby).sum())
|
|
|
|
|
|
def source_water_coloured(rgb, wet):
|
|
"""Accept teal sea or water brighter in blue than the tile's dry land."""
|
|
teal=source_water(rgb)
|
|
dry=rgb[~wet]
|
|
if len(dry)<10000:
|
|
return wet & teal
|
|
blue_floor=float(np.median(dry[:,2]))+8
|
|
return wet & (teal | (rgb[:,:,2].astype(float)>blue_floor))
|
|
|
|
|
|
def rgb_any(raw):
|
|
image=Image.open(io.BytesIO(raw)).convert('RGB')
|
|
if image.size == (256,256):image=image.resize((512,512),Image.Resampling.NEAREST)
|
|
if image.size != (512,512):raise ValueError('unexpected minimap dimensions')
|
|
return np.asarray(image)
|
|
|
|
|
|
def candidate(source, parent, terrain_raw):
|
|
if source == parent:
|
|
return parent, {'lost_pixels': 0, 'eligible_blocks': 0, 'changed_pixels': 0}
|
|
sw = bc1_rgb(source)
|
|
nw = bc1_rgb(parent)
|
|
if sw.shape == (256, 256, 3):
|
|
sw = np.repeat(np.repeat(sw, 2, axis=0), 2, axis=1)
|
|
expanded = replace_cells(source, parent, np.zeros((128,128), dtype=bool))
|
|
elif sw.shape == (512, 512, 3):
|
|
off = opaque_bc1(parent,512)
|
|
so = opaque_bc1(source,512)
|
|
expanded = parent[:off] + source[so:]
|
|
else:
|
|
raise ValueError('unexpected Source tile size')
|
|
if nw.shape != (512, 512, 3):
|
|
raise ValueError('unexpected native tile size')
|
|
wet = np.repeat(np.repeat(wet_cells(terrain_raw),4,axis=0),4,axis=1)
|
|
dry_mae=float(np.abs(sw.astype(np.int16)-nw.astype(np.int16))[~wet].mean()) if (~wet).any() else 0.0
|
|
if int(wet.sum())<2000:
|
|
raise ValueError('native wet footprint below 2000 pixels')
|
|
water = source_water_coloured(sw,wet)
|
|
loss = water & ~source_water(nw)
|
|
# BC1 copies whole 4px blocks. Select blocks that touch the Source's
|
|
# water contour, including its mixed shoreline blocks; the native MH2O
|
|
# cell outline is too coarse and leaves a stair-stepped bank.
|
|
source_contour = source_water(sw)
|
|
shore_blocks = source_contour.reshape(128,4,128,4).any(axis=(1,3))
|
|
different = np.any(sw != nw,axis=2).reshape(128,4,128,4).any(axis=(1,3))
|
|
selected = shore_blocks & different
|
|
off = opaque_bc1(parent,512)
|
|
so = opaque_bc1(expanded,512)
|
|
out = bytearray(parent)
|
|
for y,x in zip(*np.where(selected)):
|
|
at = (y*128+x)*8
|
|
out[off+at:off+at+8] = expanded[so+at:so+at+8]
|
|
result = bytes(out)
|
|
rgb = bc1_rgb(result)
|
|
protected = ~np.repeat(np.repeat(shore_blocks,4,axis=0),4,axis=1)
|
|
if np.any(rgb[protected] != nw[protected]):
|
|
raise ValueError('land beyond Source shoreline changed')
|
|
return result, {'lost_pixels': int(loss.sum()), 'eligible_blocks': int(selected.sum()),
|
|
'changed_pixels': int(np.any(rgb != nw,axis=2).sum()),
|
|
'wet_pixels': int(wet.sum()), 'source_water_pixels': int(water.sum()),
|
|
'dry_mae': round(dry_mae,3)}
|
|
|
|
|
|
def digest(raw):
|
|
return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def extract(casc, client, listfile, ids, output):
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
request = output.parent/(output.name+'-ids.txt')
|
|
request.write_text(''.join(f'{n}\n' for n in sorted(ids)))
|
|
log = output.parent/(output.name+'-extract.log')
|
|
with log.open('w') as handle:
|
|
subprocess.run([str(casc), 'extract-batch', '--from-list', str(request), str(output),
|
|
'--locale', 'enus', '--storage', str(client), '--listfile', str(listfile)],
|
|
stdout=handle, stderr=subprocess.STDOUT, check=True)
|
|
|
|
|
|
def stage(args):
|
|
root = args.root
|
|
root.mkdir(parents=True,exist_ok=True)
|
|
wdt_dir = root/'wdt'
|
|
extract(args.casc,args.client,args.listfile,[fdid for _,fdid in MAPS],wdt_dir)
|
|
names = {}
|
|
for line in args.listfile.open():
|
|
ident,sep,name = line.rstrip().partition(';')
|
|
if sep:
|
|
names[int(ident)] = name.lower()
|
|
rows=[]
|
|
for zone,fdid in MAPS:
|
|
raw = (wdt_dir/'_unresolved'/f'FILE{fdid:08X}.dat').read_bytes()
|
|
for x,y,adt,tile in wdt_rows(raw):
|
|
path=f'world/minimaps/{zone}/map{x:02d}_{y:02d}.blp'
|
|
if names.get(tile) is not None and names[tile] != path:
|
|
raise ValueError(f'WDT minimap binding mismatch: {zone} {x},{y} {tile} {names.get(tile)}')
|
|
rows.append(dict(zone=zone,x=x,y=y,adt=adt,fdid=tile,path=path))
|
|
live_count=len(rows)
|
|
external={}
|
|
force={tuple(row) for row in json.loads(args.force_tiles.read_text())} if args.force_tiles else set()
|
|
if args.external_audit:
|
|
external={(r['c'],r['x'],r['y']):r for r in json.loads(args.external_audit.read_text())}
|
|
wanted={key for key,r in external.items() if r.get('lost_water',0)>args.minimum_loss}|force
|
|
scoped=set(wanted)
|
|
for zone,x,y in wanted:
|
|
scoped.update(((zone,x+1,y),(zone,x-1,y),(zone,x,y+1),(zone,x,y-1)))
|
|
rows=[r for r in rows if (r['zone'],r['x'],r['y']) in scoped]
|
|
extract(args.casc,args.client,args.listfile,[r['fdid'] for r in rows],root/'native')
|
|
for row in rows:
|
|
path=root/'native'/row['path']
|
|
if not path.exists():
|
|
unresolved=root/'native'/'_unresolved'/f"FILE{row['fdid']:08X}.dat"
|
|
if not unresolved.exists():raise ValueError('missing live minimap '+str(row['fdid']))
|
|
path.parent.mkdir(parents=True,exist_ok=True)
|
|
path.write_bytes(unresolved.read_bytes())
|
|
survey_path=root/'survey.json'
|
|
if survey_path.exists():
|
|
survey=json.loads(survey_path.read_text())
|
|
if {(r['zone'],r['x'],r['y'],r['fdid']) for r in survey} - {(r['zone'],r['x'],r['y'],r['fdid']) for r in rows}:
|
|
raise ValueError('cached survey has stale WDT row')
|
|
for row in survey:
|
|
if digest((root/'native'/row['path']).read_bytes()) != row['native_sha256']:
|
|
raise ValueError('cached survey native pin changed')
|
|
else:
|
|
source = Source(args.source,root)
|
|
survey=[]
|
|
try:
|
|
for row in rows:
|
|
key=f"{row['zone']}\\map{row['x']:02d}_{row['y']:02d}.blp"
|
|
translated = source.mapping.get(key)
|
|
if not translated:
|
|
continue
|
|
value = source.read('Textures\\Minimap\\'+translated)
|
|
if value is None:
|
|
continue
|
|
raw,proof = value
|
|
current = (root/'native'/row['path']).read_bytes()
|
|
sr = rgb_any(raw)
|
|
nr = rgb_any(current)
|
|
audited=external.get((row['zone'],row['x'],row['y']))
|
|
loss = int(audited['lost_water']) if audited else int((source_water(sr) & ~source_water(nr)).sum())
|
|
survey.append(dict(row,source=proof,source_water_loss=loss,
|
|
native_sha256=digest(current)))
|
|
finally:
|
|
source.close()
|
|
survey_path.write_text(json.dumps(survey,indent=2)+'\n')
|
|
for row in survey:
|
|
source_rgb=rgb_any(Path(row['source']['file']).read_bytes())
|
|
live_rgb=rgb_any((root/'native'/row['path']).read_bytes())
|
|
row['true_water_loss']=true_water_loss(source_rgb,live_rgb)
|
|
survey_path.write_text(json.dumps(survey,indent=2)+'\n')
|
|
selected=[r for r in survey if r['true_water_loss'] > max(2000,args.minimum_loss) or (r['zone'],r['x'],r['y']) in force]
|
|
extract(args.casc,args.client,args.listfile,[r['adt'] for r in survey],root/'terrain')
|
|
assets=[]
|
|
for row in selected:
|
|
for key in ('hold','changed_pixels','eligible_blocks','wet_pixels','source_water_pixels','dry_mae','lost_pixels'):
|
|
row.pop(key,None)
|
|
source_raw=Path(row['source']['file']).read_bytes()
|
|
current_path=root/'native'/row['path']
|
|
parent=current_path.read_bytes()
|
|
terrain_path=root/'terrain'/names[row['adt']] if row['adt'] in names else root/'terrain'/'_unresolved'/f"FILE{row['adt']:08X}.dat"
|
|
if not terrain_path.exists():
|
|
raise ValueError('Missing selected ADT '+str(row['adt']))
|
|
try: output,stats=candidate(source_raw,parent,terrain_path.read_bytes())
|
|
except ValueError as error:
|
|
row['hold']=str(error)
|
|
continue
|
|
row.update(stats)
|
|
if output==parent:
|
|
continue
|
|
target=root/'candidate'/row['path']
|
|
target.parent.mkdir(parents=True,exist_ok=True)
|
|
target.write_bytes(output)
|
|
assets.append(dict(file_data_id=row['fdid'],path=row['path'],file=str(target),
|
|
before_sha256=digest(parent),after_sha256=digest(output)))
|
|
(root/'survey.json').write_text(json.dumps(survey,indent=2)+'\n')
|
|
(root/'candidate-assets.json').write_text(json.dumps(assets,indent=2)+'\n')
|
|
return {'live_tiles':live_count,'source_tiles':len(survey),'selected':len(selected),'changed':len(assets),
|
|
'water_loss_pixels':sum(r['source_water_loss'] for r in survey),
|
|
'restored_pixels':sum(r.get('changed_pixels',0) for r in selected)}
|
|
|
|
|
|
def seam_audit(root):
|
|
survey=json.loads((root/'survey.json').read_text())
|
|
by_tile={(r['zone'],r['x'],r['y']):r for r in survey}
|
|
assets=json.loads((root/'candidate-assets.json').read_text())
|
|
changed={r['path'] for r in assets}
|
|
@lru_cache(maxsize=256)
|
|
def images(zone,x,y):
|
|
row=by_tile[(zone,x,y)]
|
|
native=rgb_any((root/'native'/row['path']).read_bytes())
|
|
source=rgb_any(Path(row['source']['file']).read_bytes())
|
|
path=root/'candidate'/row['path']
|
|
after=rgb_any(path.read_bytes()) if row['path'] in changed else native
|
|
adt=root/'terrain'/'_unresolved'/f"FILE{row['adt']:08X}.dat"
|
|
if not adt.exists():
|
|
found=list((root/'terrain'/'world'/'maps'/zone).glob(f'*_{x}_{y}.adt'))
|
|
if len(found)!=1:raise ValueError('missing seam ADT '+str((zone,x,y)))
|
|
adt=found[0]
|
|
wet=np.repeat(np.repeat(wet_cells(adt.read_bytes()),4,axis=0),4,axis=1)
|
|
water=source_water_coloured(source,wet)
|
|
return source,native,after,water
|
|
edges=[]
|
|
for zone,x,y in sorted(by_tile):
|
|
if not any((by_tile[(zone,x,y)]['path'] in changed,
|
|
by_tile.get((zone,x+1,y),{}).get('path') in changed,
|
|
by_tile.get((zone,x,y+1),{}).get('path') in changed)):
|
|
continue
|
|
for side,other in [('east',(zone,x+1,y)),('south',(zone,x,y+1))]:
|
|
if other not in by_tile:continue
|
|
first=images(zone,x,y);second=images(*other)
|
|
if side=='east':
|
|
take=lambda a,b:(a[:,-1],b[:,0])
|
|
else:
|
|
take=lambda a,b:(a[-1,:],b[0,:])
|
|
mask_a,mask_b=take(first[3],second[3]);mask=mask_a&mask_b
|
|
if not mask.any():continue
|
|
def delta(index):
|
|
a,b=take(first[index],second[index])
|
|
return float(np.abs(a[mask].astype(np.int16)-b[mask].astype(np.int16)).mean())
|
|
source,before,after=delta(0),delta(1),delta(2)
|
|
edges.append(dict(zone=zone,x=x,y=y,side=side,pairs=int(mask.sum()),
|
|
source=round(source,4),before=round(before,4),after=round(after,4),
|
|
excess=round(after-max(source,before),4)))
|
|
report={'edges':edges,'regressions':[e for e in edges if e['excess']>1.0],
|
|
'edge_count':len(edges),'regression_count':sum(e['excess']>1.0 for e in edges)}
|
|
(root/'seams.json').write_text(json.dumps(report,indent=2)+'\n')
|
|
return {k:v for k,v in report.items() if k not in ('edges','regressions')}
|
|
|
|
|
|
if __name__=='__main__':
|
|
parser=argparse.ArgumentParser()
|
|
parser.add_argument('--root',type=Path,required=True)
|
|
parser.add_argument('--client',type=Path,required=True)
|
|
parser.add_argument('--source',type=Path,required=True)
|
|
parser.add_argument('--listfile',type=Path,required=True)
|
|
parser.add_argument('--casc',type=Path,required=True)
|
|
parser.add_argument('--minimum-loss',type=int,default=-1)
|
|
parser.add_argument('--external-audit',type=Path)
|
|
parser.add_argument('--force-tiles',type=Path)
|
|
parser.add_argument('--audit-only',action='store_true')
|
|
args=parser.parse_args()
|
|
print(json.dumps(seam_audit(args.root) if args.audit_only else stage(args)))
|