Files

140 lines
11 KiB
Python

#!/usr/bin/env python3
"""21j shoreline child: same parent BC1 container; only touched blocks recompressed."""
import hashlib,io,json,struct
from pathlib import Path
import numpy as np
from PIL import Image
import booty_bay_minimap as base
import map_asset_preflight as terrain
def bc1_rgb(blob):
width,height=struct.unpack_from('<II',blob,12);offset=base.opaque_bc1(blob,width)
body=blob[offset:];fields=[124,0x81007,height,width,len(body),0,1]+[0]*11+[32,4,int.from_bytes(b'DXT1','little'),0,0,0,0,0,0x1000,0,0,0,0]
# Independent BCn decoder expands RGB565 to full eight bits. The Pillow BLP
# decoder truncates low bits; using that for raw BGRA would darken untouched pixels.
return np.asarray(Image.open(io.BytesIO(b'DDS '+struct.pack('<31I',*fields)+body)).convert('RGB'))
def native_water(blob):
chunks=terrain._adt_split_records(blob);liquid=next(b for tag,b,z in chunks if tag=='MH2O');wet=np.zeros((512,512),bool)
triangles=[[(0,0),(1,0),(.5,.5)],[(1,0),(1,1),(.5,.5)],[(1,1),(0,1),(.5,.5)],[(0,1),(0,0),(.5,.5)]];weights=[]
for py in range(4):
for px in range(4):
x,y=(px+.5)/4,(py+.5)/4
for ti,points in enumerate(triangles):
matrix=np.array([[u for u,v in points],[v for u,v in points],[1,1,1]],float);w=np.linalg.solve(matrix,np.array([x,y,1]))
if np.all(w>=-1e-8):weights.append((py,px,ti,w));break
for tag,b,z in chunks:
if tag!='MCNK':continue
words=struct.unpack_from('<32I',b);cx,cy=words[1:3];off,count,attr=struct.unpack_from('<III',liquid,(cy*16+cx)*12)
if count!=1:continue
if off<3072 or off+24>len(liquid):raise ValueError('layer bounds')
typ,obj,lo,hi,ox,oy,width,height,bits,verts=struct.unpack_from('<HHffBBBBII',liquid,off)
if (typ,obj,lo,hi,ox,oy,width,height)!=(1250,42,0.,0.,0,0,8,8):continue
if verts<3072 or verts+405>len(liquid) or (bits and (bits<3072 or bits+8>len(liquid))):raise ValueError('liquid bounds')
if any(v!=0 for v in struct.unpack_from('<81f',liquid,verts)):raise ValueError('nonflat pinned ocean')
mask=int.from_bytes(liquid[bits:bits+8],'little')if bits else (1<<64)-1
children={k:v for k,v,z in terrain._adt_split_records(b[128:],legacy_normals=True)}
heights=np.array(struct.unpack('<145f',children['MCVT']))+struct.unpack_from('<f',b,112)[0]
for y in range(8):
for x in range(8):
if not(mask>>(y*8+x)&1) or words[15]>>(y//2*4+x//2)&1:continue
values=[heights[y*17+x],heights[y*17+x+1],heights[(y+1)*17+x+1],heights[(y+1)*17+x],heights[y*17+9+x]]
for py,px,ti,w in weights:
height=np.dot(w,[values[ti],values[(ti+1)%4],values[4]])
if np.isfinite(height) and height<0:wet[(cy*8+y)*4+py,(cx*8+x)*4+px]=True
return wet
def classify(root):
qualified=base.qualified_mask(root);q=np.repeat(np.repeat(qualified,4,0),4,1)
near=np.lib.stride_tricks.sliding_window_view(np.pad(qualified,2),(5,5)).any((-1,-2))&~qualified
near=np.repeat(np.repeat(near,4,0),4,1)
source=np.asarray(Image.open(root/'inputs/source.blp').convert('RGB').resize((512,512),Image.Resampling.NEAREST))
codes=lambda a:a[:,:,0].astype(np.uint32)*65536+a[:,:,1].astype(np.uint32)*256+a[:,:,2]
teal=(source[:,:,1]>source[:,:,2])&(source[:,:,2]>source[:,:,0]);palette=np.unique(codes(source)[q&teal])
shore=near&np.isin(codes(source),palette);wet=native_water((root/'inputs/native.adt').read_bytes())
selected,held=shore&wet,shore&~wet
if int(selected.sum())!=1178 or int(held.sum())!=74:raise ValueError('outside owner-approved shoreline counts')
if hashlib.sha256(selected.tobytes()).hexdigest()!='0b710ece43348f7383a09f5bf53f4a6cbc531cf81f708d6fdded267f56a9511e' or hashlib.sha256(held.tobytes()).hexdigest()!='708bbe67def4e45430fc97d5e689f08e2ab96f33e1458347ff594c953fc50106':raise ValueError('approved 21h mask changed')
return selected,held
from functools import lru_cache
@lru_cache(maxsize=32768)
def block_palettes(first,second):
header=bytearray(1172);header[:12]=b'BLP2\x01\0\0\0\x02\0\0\0';struct.pack_into('<II',header,12,4,4);struct.pack_into('<I',header,20,1172);struct.pack_into('<I',header,84,8)
blob=bytes(header)+struct.pack('<HHI',first,second,0xe4e4e4e4)
return bc1_rgb(blob)[0].copy(),np.asarray(Image.open(io.BytesIO(blob)).convert('RGB'))[0].copy()
def encode_touched(parent,native,selected,held):
offset=base.opaque_bc1(parent,512);native_offset=base.opaque_bc1(native,512)
before=bc1_rgb(parent);donor=bc1_rgb(native);target=before.copy();target[selected]=donor[selected]
legacy=np.asarray(Image.open(io.BytesIO(parent)).convert('RGB'))
stream=io.BytesIO();Image.fromarray(target).save(stream,'DDS',pixel_format='DXT1');dds=stream.getvalue()
if dds[:4]!=b'DDS ' or dds[84:88]!=b'DXT1' or len(dds)!=128+131072:raise ValueError('unexpected BC1 encoder output')
touched=selected.reshape(128,4,128,4).any((1,3));output=bytearray(parent);rows=[]
for by,bx in np.argwhere(touched):
by,bx=int(by),int(bx);block=(by*128+bx)*8;ys=slice(by*4,by*4+4);xs=slice(bx*4,bx*4+4)
wanted=target[ys,xs].reshape(16,3).astype(np.int32);hold=held[ys,xs].reshape(16)
old=before[ys,xs].reshape(16,3);old_legacy=legacy[ys,xs].reshape(16,3)
old_first,old_second,old_bits=struct.unpack_from('<HHI',parent,offset+block)
endpoints=set([old_first,old_second,*struct.unpack_from('<HH',native,native_offset+block),*struct.unpack_from('<HH',dds,128+block)])
# Include quantized target colors so mixed shoreline blocks can fit new endpoints.
for r,g,b in wanted:
endpoints.add((int(round(int(r)*31/255))<<11)|(int(round(int(g)*63/255))<<5)|int(round(int(b)*31/255)))
change=selected[ys,xs].reshape(16)
best=None
for first in sorted(endpoints):
for second in sorted(endpoints):
palette,legacy_palette=block_palettes(first,second)
errors=((wanted[:,None,:]-palette[None,:,:].astype(np.int32))**2).sum(2)
if first<=second:
# Never introduce transparent DXT1 index3 at a previously opaque texel.
for i in range(16):
if not(old_first<=old_second and (old_bits>>(2*i)&3)==3):errors[i,3]=10**9
if hold.any():
exact=(palette[None,:,:]==old[:,None,:]).all(2)&(legacy_palette[None,:,:]==old_legacy[:,None,:]).all(2)
errors[hold[:,None]&~exact]=10**9
unchanged=(palette[None,:,:]==old[:,None,:]).all(2)
errors[change[:,None]&unchanged]=10**9
indices=errors.argmin(1);chosen=errors[np.arange(16),indices]
if np.any(chosen>=10**9):continue
encoded=struct.pack('<HHI',first,second,sum(int(index)<<(2*i)for i,index in enumerate(indices)))
maximum=int(np.abs(wanted-palette[indices]).max());score=(int(chosen.sum()),maximum,encoded)
if best is None or score<best[0]:best=(score,encoded)
if best is None:raise ValueError('no palette preserves held pixels')
output[offset+block:offset+block+8]=best[1];rows.append(dict(x=bx,y=by,max_channel_error=best[0][1],squared_error=best[0][0]))
return bytes(output),touched,rows
def verify(parent,native,candidate,selected,held):
offset=base.opaque_bc1(parent,512);base.opaque_bc1(candidate,512)
if parent[:offset]!=candidate[:offset]:raise ValueError('parent header changed')
touched=selected.reshape(128,4,128,4).any((1,3));old_blocks=np.frombuffer(parent,dtype=np.uint8,offset=offset).reshape(128,128,8);new_blocks=np.frombuffer(candidate,dtype=np.uint8,offset=offset).reshape(128,128,8)
if not np.array_equal(old_blocks[~touched],new_blocks[~touched]):raise ValueError('untouched block changed')
before=bc1_rgb(parent);donor=bc1_rgb(native);after=bc1_rgb(candidate);target=before.copy();target[selected]=donor[selected]
legacy_before=np.asarray(Image.open(io.BytesIO(parent)).convert('RGB'));legacy_after=np.asarray(Image.open(io.BytesIO(candidate)).convert('RGB'))
if not np.array_equal(after[held],before[held]) or not np.array_equal(legacy_after[held],legacy_before[held]):raise ValueError('one of74 preserved pixels changed')
affected=np.repeat(np.repeat(touched,4,0),4,1)
if not np.array_equal(after[~affected],before[~affected]) or not np.array_equal(legacy_after[~affected],legacy_before[~affected]):raise ValueError('untouched decoded pixels changed')
error=np.abs(after.astype(np.int32)-target.astype(np.int32));changed=np.any(after!=before,axis=2)
if not changed[selected].all():raise ValueError('selected pixel unchanged')
return dict(requested_pixels=int(selected.sum()),selected_pixels_changed=int((changed&selected).sum()),preserved_pixels=int(held.sum()),touched_blocks=int(touched.sum()),untouched_blocks_byte_identical=True,held_pixels_exact_both_bc1_readers=True,changed_nonselected_pixels_in_touched_blocks=int((changed&~selected).sum()),max_channel_error=int(error[affected].max()),max_pixel_rgb_distance=float(np.sqrt((error.astype(float)**2).sum(2))[affected].max()),rms_channel_error=float(np.sqrt(np.mean(error[affected].astype(float)**2))),max_selected_channel_error=int(error[selected].max()))
def stage(root,client):
selected,held=classify(root);parent=(root/'inputs/parent.blp').read_bytes();native=(root/'inputs/native.blp').read_bytes()
candidate,touched,blocks=encode_touched(parent,native,selected,held);report=verify(parent,native,candidate,selected,held)
output=root/'candidate/map30_58.blp';output.parent.mkdir(exist_ok=True);output.write_bytes(candidate)
save=lambda name,data:(root/name).write_text(json.dumps(data,indent=2)+'\n');sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
report.update(parent_build_info_sha256=sha(client/'.build.info'),native_runtime_verified=False)
save('report.json',report);save('block-errors.json',blocks)
coords=[dict(x=int(x),y=int(y),world_x=(32-58)*1600/3-(float(y)+.5)*(1600/3)/512,world_y=(32-30)*1600/3-(float(x)+.5)*(1600/3)/512)for y,x in np.argwhere(held)]
save('preserved-74.json',dict(map=0,tile=[30,58],image=[512,512],coordinates=coords))
before=root/'native-minimaps/world/minimaps/azeroth/map30_58.blp';before.parent.mkdir(parents=True,exist_ok=True);before.write_bytes(parent)
save('candidate-assets.json',[dict(path='world/minimaps/azeroth/map30_58.blp',file=str(output),file_data_id=8704453,before_sha256=sha(before),after_sha256=sha(output))])
save('input-pins.json',{str(p):sha(p)for p in [*sorted((root/'inputs').iterdir()),root/'reconciled-ocean.json']})
return report
if __name__=='__main__':
import argparse
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--client',type=Path,required=True);a=p.parse_args();print(json.dumps(stage(a.root,a.client)))