133 lines
5.7 KiB
Python
133 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""21p: restore real Source tiles with lossless BC1 expansion and parent headers."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image
|
|
from booty_bay_shore import bc1_rgb, native_water
|
|
from booty_bay_minimap import opaque_bc1, replace_cells
|
|
|
|
TARGETS = {(30, 58), (31, 58)}
|
|
TOLERANCE = 1e-6 # Floating-point comparison only; no visual-error allowance.
|
|
|
|
|
|
def save(path, value):
|
|
path.write_text(json.dumps(value, indent=2) + '\n')
|
|
|
|
|
|
def digest(path):
|
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
|
|
|
|
def rgb512(blob):
|
|
return np.asarray(Image.fromarray(bc1_rgb(blob)).resize(
|
|
(512, 512), Image.Resampling.NEAREST))
|
|
|
|
|
|
def restore(source, parent):
|
|
offset = opaque_bc1(parent, 512)
|
|
expanded = replace_cells(source, parent, np.zeros((128, 128), dtype=bool))
|
|
source_offset = opaque_bc1(expanded, 512)
|
|
result = parent[:offset] + expanded[source_offset:]
|
|
verify_tile(source, parent, result)
|
|
return result
|
|
|
|
|
|
def verify_tile(source, parent, candidate):
|
|
offset = opaque_bc1(parent, 512)
|
|
opaque_bc1(candidate, 512)
|
|
if len(candidate) != len(parent) or candidate[:offset] != parent[:offset]:
|
|
raise ValueError('parent BC1 header/container changed')
|
|
if not np.array_equal(bc1_rgb(candidate), rgb512(source)):
|
|
raise ValueError('candidate is not exact real Source RGB565 pixels')
|
|
|
|
|
|
def edges(source, candidate, wet):
|
|
rows = []
|
|
for tile in sorted(TARGETS):
|
|
x, y = tile
|
|
for side, other in [('west', (x-1, y)), ('east', (x+1, y)),
|
|
('north', (x, y-1)), ('south', (x, y+1))]:
|
|
def boundary(images):
|
|
a, b = images[tile], images[other]
|
|
if side == 'west': return a[:, 0], b[:, -1]
|
|
if side == 'east': return a[:, -1], b[:, 0]
|
|
if side == 'north': return a[0, :], b[-1, :]
|
|
return a[-1, :], b[0, :]
|
|
wa, wb = boundary(wet)
|
|
sa, sb = boundary(source)
|
|
ca, cb = boundary(candidate)
|
|
geometry = wa & wb
|
|
water = (geometry & (sa[:, 0] < sa[:, 1]) & (sa[:, 0] < sa[:, 2])
|
|
& (sb[:, 0] < sb[:, 1]) & (sb[:, 0] < sb[:, 2]))
|
|
row = dict(tile=list(tile), side=side, neighbour=list(other))
|
|
for name, mask in [('water', water), ('geometry_ocean', geometry)]:
|
|
def delta(a, b):
|
|
return float(np.abs(a[mask].astype(int)-b[mask].astype(int)).mean()) if mask.any() else None
|
|
before, after = delta(sa, sb), delta(ca, cb)
|
|
if before is not None and after > before + TOLERANCE:
|
|
raise ValueError(f'{tile} {side} exceeds its real Source edge')
|
|
row[name] = dict(pairs=int(mask.sum()), source_delta=before,
|
|
candidate_delta=after, result='PASS' if mask.any() else 'N/A')
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
def stage(root, client):
|
|
manifest = json.loads((root/'inputs.json').read_text())
|
|
source, candidate, wet, assets, provenance = {}, {}, {}, [], []
|
|
for row in manifest:
|
|
tile = row['x'], row['y']
|
|
src, parent = Path(row['source']).read_bytes(), Path(row['parent']).read_bytes()
|
|
source[tile] = rgb512(src)
|
|
candidate[tile] = rgb512(parent)
|
|
try:
|
|
wet[tile] = native_water(Path(row['terrain']).read_bytes())
|
|
except StopIteration:
|
|
wet[tile] = np.zeros((512, 512), dtype=bool)
|
|
if tile not in TARGETS:
|
|
if not np.array_equal(candidate[tile], source[tile]):
|
|
raise ValueError('surrounding installed tile is not real Source')
|
|
continue
|
|
output = restore(src, parent)
|
|
candidate[tile] = bc1_rgb(output)
|
|
path = f'world/minimaps/azeroth/map{tile[0]}_{tile[1]}.blp'
|
|
dest = root/'candidate'/path
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
dest.write_bytes(output)
|
|
preimage = root/'native-minimaps'/path
|
|
preimage.parent.mkdir(parents=True, exist_ok=True)
|
|
preimage.write_bytes(parent)
|
|
assets.append(dict(path=path, file=str(dest), file_data_id=row['file_data_id'],
|
|
before_sha256=digest(preimage), after_sha256=digest(dest)))
|
|
base = rgb512(Path(row['base']).read_bytes())
|
|
changed = np.any(source[tile] != base, axis=2)
|
|
provenance.append(dict(tile=list(tile), source_archive=row['turtle_archive'],
|
|
source_pixels=512*512, turtle_changed_pixels_512=int(changed.sum()),
|
|
turtle_changed_outside_native_ocean=int((changed & ~wet[tile]).sum()),
|
|
exact_parent_header=True, lossless_bc1_expansion=True))
|
|
edge_rows = edges(source, candidate, wet)
|
|
canvas = Image.new('RGB', (2048, 1536))
|
|
for (x, y), pixels in candidate.items():
|
|
canvas.paste(Image.fromarray(pixels), ((x-29)*512, (y-57)*512))
|
|
canvas.save(root/'candidate-neighbourhood.png')
|
|
report = dict(parent_build_info_sha256=digest(client/'.build.info'),
|
|
tolerance=TOLERANCE, edges=edge_rows, provenance=provenance,
|
|
native_runtime_verified=False, installed=False,
|
|
local_capture_required=True)
|
|
save(root/'candidate-assets.json', assets)
|
|
save(root/'report.json', report)
|
|
return report
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--root', type=Path, required=True)
|
|
parser.add_argument('--client', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
result = stage(args.root, args.client)
|
|
print('Two real Source BC1 tiles; eight directed edges PASS/N/A; LOCAL capture required.')
|