#!/usr/bin/env python3 """Compose Link's basic-shield body frames directly from verified NES patterns.""" import hashlib import json from pathlib import Path from PIL import Image, ImageDraw from extract_graphics import ROOT, ROM_SHA256, decode BANK_UUID = "9bc59c58-4f6b-4b48-bffb-9dfc16ee44d8" BANK_ROOT = "characters/link" # RGB approximation for NES codes $29, $27, $17; NES codes are recorded too. COLORS = [(0, 0, 0, 0), (56, 184, 0, 255), (252, 160, 68, 255), (172, 124, 0, 255)] def write_json(path, value): path.write_text(json.dumps(value, indent=2) + "\n") def assemble(): rom = (ROOT / ".tmp/zelda-1.nes").read_bytes() if hashlib.sha256(rom).hexdigest() != ROM_SHA256: raise ValueError("Unverified ROM revision") prg = rom[16:] # These are the first eight frame descriptors of Link animation zero. frames = bytes.fromhex("00 04 08 0c 10 10 14 18") if prg.count(frames + bytes.fromhex("5c 9e 44 ce")) != 1: raise ValueError("Link animation descriptor signature not found uniquely") frame_offset = prg.index(frames + bytes.fromhex("5c 9e 44 ce")) if prg[103168:103171] != bytes.fromhex("3f0020"): raise ValueError("Level palette transfer record not found") nes_palette = list(prg[103168 + 3 + 16:103168 + 3 + 20]) if nes_palette != [0x0F, 0x29, 0x27, 0x17]: raise ValueError("Unexpected Link palette") patterns = prg[32895:32895 + 1792] bank = ROOT / "assets" / BANK_ROOT bank.mkdir(parents=True, exist_ok=True) asset_path = bank / "asset.json" if asset_path.exists() and json.loads(asset_path.read_text())["asset_uuid"] != BANK_UUID: raise ValueError("Refusing to replace an unrelated bank") def column(tile, flip): pixels = [] for index in (tile, tile + 1): pixels.extend(decode(patterns[index * 16:(index + 1) * 16])) image = Image.new("RGBA", (8, 16)) image.putdata([COLORS[n] for n in pixels]) return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) if flip else image artifacts, provenance = [], [] clips = [] images = {} for action in ("walk", "attack"): for direction in ("down", "up", "left", "right"): clip_frames = [] for phase in range(2): frame = (phase if direction in ("left", "right") else 2 if direction == "down" else 3) if action == "attack": frame += 4 base = frames[frame] flip = direction == "left" or (phase == 1 and direction in ("up", "down")) tiles = [base + 2, base] if flip else [base, base + 2] flips = [flip, flip] # Reproduce Link_EndMoveAndAnimate's basic-shield patch AFTER H flip. if direction == "down" and tiles[0] < 0x0B: original = tiles[0] tiles[0] += 0x50 if original == 0x0A: flips[0] = False image = Image.new("RGBA", (16, 16)) for side in range(2): image.paste(column(tiles[side], flips[side]), (side * 8, 0)) name = f"{action}_{direction}_{phase}" path = bank / f"{name}.png" image.save(path) fingerprint = hashlib.sha256(path.read_bytes()).hexdigest() artifact_id = f"link-{name}" artifacts.append({"file": path.name, "index": len(artifacts), "artifact_id": artifact_id, "fingerprint": fingerprint}) provenance.append({"name": name, "frame_descriptor_prg_offset": frame_offset + frame, "descriptor": base, "tiles_8x16": tiles, "horizontal_flips": flips, "tile_prg_offsets": [32895 + n * 16 for n in tiles]}) images[name] = image clip_frames.append({"artifact_id": artifact_id, "duration_ticks": 6}) clips.append({"name": f"{action}_{direction}", "mode": "loop" if action == "walk" else "once", "frames": clip_frames}) if action == "walk": clips.append({"name": f"idle_{direction}", "mode": "loop", "frames": [clip_frames[0]]}) rgba = [int.from_bytes(bytes(c), "big", signed=True) for c in COLORS] write_json(asset_path, {"schema_version": 1, "asset_uuid": BANK_UUID, "name": "Link NES", "type": "glyph_bank", "output": {"format": "GLYPH/indexed_v1", "codec": "NONE", "pipeline": {"palettes": [{"index": 0, "palette": {"rgba8888": rgba}}]}, "codec_configuration": {}, "metadata": {"tile_size": "16x16"}}, "preload": {"enabled": True}, "artifacts": artifacts}) write_json(bank / "studio.asset.json", {"schema_version": 1, "glyph_bank_specialization": "sprites"}) registry_path = ROOT / "assets/.prometeu/index.json" registry = json.loads(registry_path.read_text()) existing = [a for a in registry["assets"] if a["asset_uuid"] == BANK_UUID or a["root"] == BANK_ROOT] if not existing: asset_id = registry["next_asset_id"] registry["assets"].append({"asset_id": asset_id, "asset_uuid": BANK_UUID, "root": BANK_ROOT, "included_in_build": True}) registry["next_asset_id"] = asset_id + 1 write_json(registry_path, registry) elif len(existing) != 1 or existing[0]["asset_uuid"] != BANK_UUID or existing[0]["root"] != BANK_ROOT: raise ValueError("Asset registry identity collision") output = ROOT / "extracted/link" output.mkdir(parents=True, exist_ok=True) write_json(output / "provenance.json", {"rom_sha256": ROM_SHA256, "palette_nes": nes_palette, "palette_rgba": COLORS, "rgb_note": "RGB approximation; NES color codes are authoritative", "shield": "basic", "frames": provenance}) # Reviewed and persisted through studio_animation_update, not written as a sidecar here. definition = {"schema_version": 1, "bank_asset_uuid": BANK_UUID, "bindings": [{"artifact_id": a["artifact_id"], "glyph_id": a["index"], "fingerprint": a["fingerprint"]} for a in artifacts], "animators": [{"id": "link", "initial_clip": "idle_down", "clips": clips}]} write_json(output / "animation-proposal.json", definition) preview = Image.new("RGB", (480, 8 * 104), "#202932") draw = ImageDraw.Draw(preview) for row, (action, direction) in enumerate((a, d) for a in ("walk", "attack") for d in ("down", "up", "left", "right")): draw.text((12, row * 104 + 38), f"{action}_{direction}", fill="white") for phase in range(2): image = images[f"{action}_{direction}_{phase}"].resize((80, 80), Image.Resampling.NEAREST) preview.paste(image, (180 + phase * 120, row * 104 + 8), image) preview.save(output / "preview.png") print(f"Created {len(artifacts)} frames and proposal with {len(clips)} clips; bank {BANK_UUID}") if __name__ == "__main__": assemble()