chore: version Zelda 1 port and engineering records

This commit is contained in:
Nilton Constantino
2026-11-16 15:22:13 +00:00
commit 6f2fa420c2
4282 changed files with 822198 additions and 0 deletions
+137
View File
@@ -0,0 +1,137 @@
#!/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()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Extract the wooden sword and original weapon offsets, preserving Link assets."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT, ROM_SHA256, decode
from assemble_link import COLORS
def assemble():
rom = (ROOT / ".tmp/zelda-1.nes").read_bytes()
if hashlib.sha256(rom).hexdigest() != ROM_SHA256:
raise ValueError("Unverified ROM")
prg = rom[16:]
bank = ROOT / "assets/characters/link"
manifest_path = bank / "asset.json"
manifest = json.loads(manifest_path.read_text())
patterns = bytearray(4096)
patterns[:1792] = prg[32895:34687]
# Boot demo patterns remain in $0700..$08DF when level patterns load.
patterns[0x700:0x8E0] = prg[19892:19892 + 0x1E0]
def column(tile):
image = Image.new("RGBA", (8, 16))
pixels = decode(patterns[tile * 16:(tile + 1) * 16])
pixels += decode(patterns[(tile + 1) * 16:(tile + 2) * 16])
image.putdata([COLORS[n] for n in pixels])
return image
vertical = Image.new("RGBA", (16, 16))
vertical.paste(column(0x20), (4, 0)) # Narrow-item centering in Anim_WriteSpecificItemSprites.
horizontal = Image.new("RGBA", (16, 16))
horizontal.paste(column(0x82), (0, 0))
horizontal.paste(column(0x84), (8, 0))
images = {"up": vertical, "down": vertical.transpose(Image.Transpose.FLIP_TOP_BOTTOM),
"right": horizontal, "left": horizontal.transpose(Image.Transpose.FLIP_LEFT_RIGHT)}
for direction, image in images.items():
name = f"sword_{direction}"
path = bank / f"{name}.png"
image.save(path)
artifact_id = f"link-{name}"
existing = [a for a in manifest["artifacts"] if a["artifact_id"] == artifact_id]
if existing:
artifact = existing[0]
else:
artifact = {"file": path.name, "index": len(manifest["artifacts"]), "artifact_id": artifact_id}
manifest["artifacts"].append(artifact)
artifact["fingerprint"] = hashlib.sha256(path.read_bytes()).hexdigest()
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
x = prg[128841:128857]
y = prg[128857:128873]
if x.hex() != "ff0100f8ff01f50bff01f907ff01fd03" or y.hex() != "f7f2f5f5f60d0303f7090303ff050303":
raise ValueError("Weapon offset tables differ from the reference")
data = {"rom_sha256": ROM_SHA256, "offset_direction_order": ["up", "down", "left", "right"],
"offsets_x": [n if n < 128 else n - 256 for n in x],
"offsets_y": [n if n < 128 else n - 256 for n in y],
"offsets_prg": {"x": 128841, "y": 128857},
"patterns": {"vertical": [0x20, 0x21], "horizontal": [0x82, 0x83, 0x84, 0x85]},
"pattern_prg_offsets": {"vertical": 32895 + 0x200, "horizontal": 19892 + 0x120},
"timers": {"initial": 5, "extended": 8, "retract_1": 1, "retract_2": 1, "hidden": 1}}
(ROOT / "extracted/link/attack-data.json").write_text(json.dumps(data, indent=2) + "\n")
print("Added four sword glyphs and extracted original weapon offset tables")
if __name__ == "__main__":
assemble()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Extract Zelda's raw NES pattern graphics without guessing sprite composition."""
import argparse
import hashlib
import json
from pathlib import Path
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
ROM_SHA256 = "89232edf4f9b52e3cb872094bc78973de080befca2ddea893b6e936066514d4e"
SOURCE = "https://github.com/aldonunez/zelda1-disassembly/blob/master/src/bins.xml"
# Offsets are relative to PRG, excluding the 16-byte iNES header.
# PPU destinations checked against bank 1, bank 2 and bank 3 load routines.
BLOCKS = [
("demo_sprites", 19892, 2304, 0x0700),
("demo_background", 22196, 2080, 0x1700),
("common_sprites", 32895, 1792, 0x0000),
("common_background", 34687, 1792, 0x1000),
("common_misc", 36479, 224, 0x1F20),
("underworld_background", 49435, 2080, 0x1700),
("overworld_background", 51515, 2080, 0x1700),
("overworld_sprites", 53595, 1824, 0x08E0),
("underworld_sprites_358", 55419, 544, 0x09E0),
("underworld_sprites_469", 55963, 544, 0x09E0),
("underworld_sprites_common", 56507, 256, 0x08E0),
("underworld_sprites_127", 56763, 544, 0x09E0),
("bosses_1257", 57307, 1024, 0x0C00),
("bosses_3468", 58331, 1024, 0x0C00),
("boss_ganon", 59355, 1024, 0x0C00),
]
def decode(data):
"""NES 2bpp: eight low-plane bytes followed by eight high-plane bytes."""
if len(data) != 16:
raise ValueError("A pattern must contain exactly 16 bytes")
return [((data[y] >> (7 - x)) & 1) |
(((data[y + 8] >> (7 - x)) & 1) << 1)
for y in range(8) for x in range(8)]
def indexed(pixels, size):
image = Image.new("P", size)
# Neutral palette, deliberately not presented as original game colors.
image.putpalette([v for c in (0, 85, 170, 255) for v in (c, c, c)] + [0] * 756)
image.putdata(pixels)
return image
def encode(pixels):
"""Reverse decoding to verify the PNG preserves every source bit."""
return bytes(sum(((pixels[y * 8 + x] >> plane) & 1) << (7 - x)
for x in range(8)) for plane in range(2) for y in range(8))
def extract(rom_path, output):
rom = rom_path.read_bytes()
digest = hashlib.sha256(rom).hexdigest()
if digest != ROM_SHA256:
raise ValueError("ROM differs from the verified input; offsets must be validated first")
if rom[:4] != b"NES\x1a" or len(rom) != 16 + 8 * 16384:
raise ValueError("Unexpected ROM layout")
prg = rom[16:]
output.mkdir(parents=True, exist_ok=True)
manifest = {"rom_sha256": digest, "offset_basis": "PRG (file offset minus 16)",
"reference": SOURCE, "palette": "neutral grayscale indices 0..3",
"scope": "All 15 documented raw pattern blocks; not assembled scenes or animations",
"blocks": [], "ppu_sets": []}
all_tiles = []
for name, offset, length, ppu in BLOCKS:
block_dir = output / "tiles" / name
block_dir.mkdir(parents=True, exist_ok=True)
count = length // 16
sheet = Image.new("P", (128, ((count + 15) // 16) * 8))
sheet.putpalette(indexed([0] * 64, (8, 8)).getpalette())
records = []
for n in range(count):
source = prg[offset + n * 16:offset + (n + 1) * 16]
pixels = decode(source)
if encode(pixels) != source:
raise AssertionError("Tile roundtrip failed")
tile = indexed(pixels, (8, 8))
path = block_dir / f"{n:03d}.png"
tile.save(path)
# Validate the saved file, not only the in-memory decoder.
with Image.open(path) as saved:
if encode(list(saved.getdata())) != source:
raise AssertionError(f"PNG roundtrip failed: {path}")
sheet.paste(tile, ((n % 16) * 8, (n // 16) * 8))
all_tiles.append(tile)
records.append({"index": n, "prg_offset": offset + n * 16,
"file_offset": offset + 16 + n * 16,
"ppu_address": f"0x{ppu + n * 16:04X}",
"png": path.relative_to(output).as_posix(),
"sha256_2bpp": hashlib.sha256(source).hexdigest()})
sheets = output / "sheets"
sheets.mkdir(exist_ok=True)
sheet.save(sheets / f"{name}.png")
sheet.resize((sheet.width * 4, sheet.height * 4), Image.Resampling.NEAREST).save(
sheets / f"{name}@4x.png")
manifest["blocks"].append({"name": name, "prg_offset": offset,
"length": length, "tiles": records})
# Reconstruct the actual pattern memory used by each level, including gaps.
common = ["common_sprites", "common_background", "common_misc"]
sets = {"demo": common + ["demo_sprites", "demo_background"],
"overworld": common + ["demo_sprites", "overworld_background", "overworld_sprites"]}
for level in range(1, 10):
enemies = "127" if level in (1, 2, 7) else "358" if level in (3, 5, 8) else "469"
boss = "bosses_1257" if level in (1, 2, 5, 7) else "bosses_3468" if level != 9 else "boss_ganon"
sets[f"dungeon_{level}"] = common + ["underworld_background",
"underworld_sprites_common", f"underworld_sprites_{enemies}", boss]
(output / "ppu").mkdir(exist_ok=True)
for name, names in sets.items():
memory = bytearray(8192)
for block_name in names:
_, offset, length, ppu = next(b for b in BLOCKS if b[0] == block_name)
memory[ppu:ppu + length] = prg[offset:offset + length]
for table, base in (("sprites", 0), ("background", 4096)):
sheet = indexed([0] * (128 * 128), (128, 128))
for n in range(256):
tile = indexed(decode(memory[base + n * 16:base + (n + 1) * 16]), (8, 8))
sheet.paste(tile, ((n % 16) * 8, (n // 16) * 8))
sheet.save(output / "ppu" / f"{name}_{table}.png")
manifest["ppu_sets"].append({"name": name, "blocks_in_load_order": names})
width = 640
height = sum((((length // 16 + 15) // 16) * 24 + 32) for _, _, length, _ in BLOCKS)
overview = Image.new("RGB", (width, height), "#252525")
draw = ImageDraw.Draw(overview)
y = 0
for name, _, length, _ in BLOCKS:
draw.text((8, y + 8), f"{name} ({length // 16} tiles)", fill="white")
with Image.open(output / "sheets" / f"{name}.png") as sheet:
zoom = sheet.convert("RGB").resize((384, sheet.height * 3), Image.Resampling.NEAREST)
overview.paste(zoom, (8, y + 28))
y += ((length // 16 + 15) // 16) * 24 + 32
overview.save(output / "overview.png")
manifest["tile_count"] = len(all_tiles)
manifest["unique_tile_count"] = len({bytes(t.getdata()) for t in all_tiles})
manifest["png_count"] = len(list(output.rglob("*.png")))
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
print(json.dumps({k: manifest[k] for k in ("tile_count", "unique_tile_count", "png_count")}, indent=2))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rom", type=Path, default=ROOT / ".tmp/zelda-1.nes")
parser.add_argument("--output", type=Path, default=ROOT / "extracted/graphics")
args = parser.parse_args()
extract(args.rom, args.output)
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Decode the first overworld room's graphics directly from the verified ROM."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT, ROM_SHA256, decode
ROOM_ID = 0x77
# Digital RGB approximations, consistent with the Link export. NES codes remain
# authoritative; composite NES output has no single exact RGB interpretation.
RGB = {0x0F: (0, 0, 0), 0x1A: (0, 168, 0), 0x17: (172, 124, 0),
0x37: (252, 216, 168), 0x12: (0, 88, 248), 0x30: (248, 248, 248),
0x00: (124, 124, 124), 0x16: (248, 56, 0), 0x27: (252, 160, 68),
0x36: (248, 184, 160)}
def write_json(path, value):
path.write_text(json.dumps(value, indent=2) + "\n")
def extract(room_id=ROOM_ID, output_name="start"):
rom = (ROOT / ".tmp/zelda-1.nes").read_bytes()
if hashlib.sha256(rom).hexdigest() != ROM_SHA256:
raise ValueError("Unverified ROM revision")
prg = rom[16:]
if prg[103168 + 47] != ROOM_ID:
raise ValueError("Overworld starting-room metadata differs from the reference")
def locate(signature):
signature = bytes.fromhex(signature)
if prg.count(signature) != 1:
raise ValueError("Expected a unique verified table signature")
return prg.index(signature)
primary_offset = locate("246ff3fa98908f958e907476f3242689")
secondary_offset = primary_offset + 56
primary = prg[primary_offset:secondary_offset]
secondary = prg[secondary_offset:secondary_offset + 64]
assert secondary[:16] == bytes.fromhex("242424246f6f6f6ff3f3f3f3fafafafa")
directory_offset = locate("d89b0d9c3e9c809cc49cf69c329d6d9d")
directory = [int.from_bytes(prg[directory_offset + i * 2:directory_offset + i * 2 + 2], "little")
for i in range(16)]
attrs = [prg[99328 + i * 128 + room_id] for i in range(6)]
# LayoutRoomOW shifts the room descriptor four times, discarding bit 7.
# Preserve bit 6: this room uses layout $72, not layout $32.
layout_id = attrs[3] & 0x7F
layout_offset = 87064 + layout_id * 16
descriptors = prg[layout_offset:layout_offset + 16]
tilemap = [[0x24] * 32 for _ in range(30)]
palette_map = [[0] * 32 for _ in range(30)]
columns = []
object_replacements = [0xC8, 0xD8, 0xC4, 0xBC, 0xC0, 0xC0]
for x, descriptor in enumerate(descriptors):
heap = 5 * 16384 + directory[descriptor >> 4] - 0x8000
cursor, remaining = heap, descriptor & 0x0F
while True:
if prg[cursor] & 0x80:
if remaining == 0:
break
remaining -= 1
cursor += 1
if cursor >= 6 * 16384:
raise ValueError("Column descriptor crossed its bank")
start = cursor
squares = []
while len(squares) < 11:
value = prg[cursor]
index = value & 0x3F
if index >= len(primary):
raise ValueError("Unknown overworld metatile")
squares.extend([index] * (2 if value & 0x40 else 1))
cursor += 1
if len(squares) != 11:
raise ValueError("Column does not decode to eleven squares")
columns.append({"descriptor": descriptor, "prg_offset": start,
"compressed_hex": prg[start:cursor].hex(), "squares": squares})
for y, index in enumerate(squares):
base = primary[index]
if 0xE5 <= base <= 0xEA:
base = object_replacements[base - 0xE5]
tiles = list(secondary[index * 4:index * 4 + 4]) if index < 16 else list(range(base, base + 4))
palette = (attrs[1] if 2 <= x <= 13 and 2 <= y <= 8 else attrs[0]) & 3
for ordinal, (dx, dy) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
tx, ty = x * 2 + dx, 8 + y * 2 + dy
tilemap[ty][tx] = tiles[ordinal]
palette_map[ty][tx] = palette
patterns = bytearray(4096)
patterns[0:0x700] = prg[34687:34687 + 1792]
patterns[0x700:0xF20] = prg[51515:51515 + 2080]
patterns[0xF20:0x1000] = prg[36479:36479 + 224]
assert prg[103168:103171] == bytes.fromhex("3f0020")
palettes = [list(prg[103171 + n * 4:103175 + n * 4]) for n in range(4)]
output = ROOT / f"extracted/overworld/{output_name}"
output.mkdir(parents=True, exist_ok=True)
tile_dir = output / "tiles"
tile_dir.mkdir(exist_ok=True)
used = sorted({(tilemap[y][x], palette_map[y][x]) for y in range(8, 30) for x in range(32)})
canvas = Image.new("RGBA", (256, 240), (0, 0, 0, 255))
images = {}
for tile_id, palette_id in used:
indices = decode(patterns[tile_id * 16:(tile_id + 1) * 16])
image = Image.new("RGBA", (8, 8))
image.putdata([(*RGB[palettes[palette_id][index]], 255) for index in indices])
image.save(tile_dir / f"tile_{tile_id:02x}_p{palette_id}.png")
images[(tile_id, palette_id)] = image
for y in range(8, 30):
for x in range(32):
canvas.paste(images[(tilemap[y][x], palette_map[y][x])], (x * 8, y * 8))
canvas.save(output / "room.png")
canvas.resize((768, 720), Image.Resampling.NEAREST).save(output / "room@3x.png")
data = {"rom_sha256": ROM_SHA256, "room_id": room_id, "layout_id": layout_id,
"start_room_id_prg_offset": 103168 + 47,
"layout_prg_offset": layout_offset, "room_attributes": attrs,
"primary_table_prg_offset": primary_offset, "secondary_table_prg_offset": secondary_offset,
"column_directory_prg_offset": directory_offset, "columns": columns,
"background_nes_palettes": palettes, "tilemap": tilemap, "palette_map": palette_map,
"used_tiles": [{"tile_id": t, "palette_id": p, "file": f"tile_{t:02x}_p{p}.png"} for t, p in used],
"scope": "Overworld terrain only; HUD reserved, no collisions, transitions or room secrets"}
write_json(output / "room.json", data)
print(json.dumps({"room": hex(room_id), "layout": hex(layout_id),
"unique_tile_palette_pairs": len(used), "columns": len(columns)}, indent=2))
return data
if __name__ == "__main__":
extract()
+30
View File
@@ -0,0 +1,30 @@
import { Inventory } from @zelda1:inventory;
import { BombRouteLinkChecks } from @zelda1:link;
declare service BombRouteEnemyChecks {
fn combat() -> int {
let unlocked=Stage.advance(240,141,2,0,0,false,false);
Inventory.reset(); Loot.reset(); Link.start_game(); BombRouteLinkChecks.position(224,141);
let sword=Inventory.take_sword(1); e0.kind=9; e0.reset(128,141,0); e0.cloud=0; e0.direction=1;
BombRouteLinkChecks.hit(128,141); e0.update(0,255);
if e0.hp!=1 || e0.hurt_timer!=16 || e0.dying!=0 || Loot.unharmed_kills()!=0 { return 1; }
BombRouteLinkChecks.hit(e0.x,e0.y); e0.update(0,255);
if e0.hp!=1 { return 2; }
for i: int from 0 until 40 { Loot.tick(); e0.update(0,255); }
BombRouteLinkChecks.hit(e0.x,e0.y); e0.update(0,255);
if e0.hp!=0 || Loot.unharmed_kills()!=1 { return 3; }
for i: int from 0 until 18 { e0.update(0,0); }
// The native first blue cycle is 1: r=0 produces a bomb pack.
loot0.reset(); Enemies.finish(e0,loot0,0);
if loot0.id!=0 { return 4; }
loot0.lifetime=239;
let taken=loot0.update(loot0.x,loot0.y-3,true,false,0);
if !taken || Inventory.read_slot(1)!=4 { return 5; }
BombRouteLinkChecks.position(128,141); let placed=BombRouteLinkChecks.bomb();
if !placed || Inventory.read_slot(1)!=3 { return 6; }
return 0;
}
fn visual() -> void {
Inventory.reset(); Link.start_game(); BombRouteLinkChecks.position(240,141); Enemies.reset();
Enemies.spawn_north(); active_room=5;
}
}
+5
View File
@@ -0,0 +1,5 @@
declare service BombRouteLinkChecks {
fn position(x: int,y: int) -> void { controller.place_for_stage(state,x,y,2,true); vitals.reset(); }
fn hit(x: int,y: int) -> void { beam.x=x; beam.y=y; beam.phase=16; beam.direction=1; }
fn bomb() -> bool { Inventory.ensure_selection(); Link.use_b(true); return bomb0.phase==1; }
}
+25
View File
@@ -0,0 +1,25 @@
import { BombRouteStageChecks } from @zelda1:stage;
import { BombRouteEnemyChecks, Enemies } from @zelda1:enemies/octorok;
import { InventoryScreen } from @zelda1:screens/inventory;
import { Scene } from @zelda1:scene;
import { Hud } from @zelda1:hud;
import { Link } from @zelda1:link;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
import { Pad, Button } from @sdk:input;
declare global phase: int=0;
declare global failures: int=0;
declare global view: int=0;
[Init] fn init() -> void {}
[Frame] fn frame() -> void {
if phase==0 { let good=BombRouteStageChecks.check(); if !good { failures+=1; } phase=1; }
else if phase==1 { let good=BombRouteStageChecks.reverse(); if !good { failures+=2; } phase=2; }
else if phase==2 { let good=BombRouteStageChecks.check(); if !good { failures+=4; } phase=3; }
else if phase==3 { let good=BombRouteEnemyChecks.combat(); if good!=0 { failures+=8+good; } phase=4; }
else if phase==4 { BombRouteEnemyChecks.visual(); Scene.reset(); phase=5; }
if Pad.pressed(Button.Select) { view=(view+1)%2; if view==1 { InventoryScreen.open(); } else { InventoryScreen.reset(); Scene.reset(); } }
if view==1 { let closed=InventoryScreen.advance(false,0); InventoryScreen.draw(); }
else { if Scene.ensure_ready() { Hud.draw(); Link.draw(); Enemies.draw(); } }
Scene.draw_frame();
Gfx.fill_rect(0,0,3,3,if phase<5 { Color.rgb(0,0,255) } else if failures==0 { Color.rgb(0,255,0) } else { Color.rgb(failures as long,0,0) });
}
+22
View File
@@ -0,0 +1,22 @@
declare service BombRouteStageChecks {
fn enter() -> void { Stage.reset(); flow.active=2; }
fn hop(left: bool) -> bool {
let old=Stage.id(); let x=if left { 0 } else { 240 }; let dir=if left { 2 } else { 1 };
let c=Stage.advance(x,141,dir,0,0,false,false);
if !Stage.scrolling() || c!=2 { return false; }
for i: int from 0 until 63 { let command=Stage.advance(flow.x,flow.y,dir,0,0,false,false); }
if !Stage.scrolling() { return false; }
let final_command=Stage.advance(flow.x,flow.y,dir,0,0,false,false);
if Stage.scrolling() { return false; }
let id=Stage.id(); return id==old+(if left { 1 } else { -1 });
}
fn check() -> bool {
BombRouteStageChecks.enter();
for i: int from 0 until 3 { let good=BombRouteStageChecks.hop(true); if !good { return false; } }
let id=Stage.id(); let room=Stage.room_id(); return id==5 && room==100;
}
fn reverse() -> bool {
for i: int from 0 until 3 { let good=BombRouteStageChecks.hop(false); if !good { return false; } }
let id=Stage.id(); return id==2;
}
}
+67
View File
@@ -0,0 +1,67 @@
import { WorldFlags } from @zelda1:world;
import { OverworldStart } from @zelda1:stages/overworld_start;
import { Inventory } from @zelda1:inventory;
import { Stage } from @zelda1:stage;
import { Link, WallLinkChecks } from @zelda1:link;
import { Scene } from @zelda1:scene;
declare global wall_error: int=0;
declare service WallGameChecks {
fn check_phase(n: int) -> void {
if n==0 {
game.boot(); game.new_game(); for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
let tested=WallLinkChecks.phases(); if !tested { wall_error=1; }
let enter=OverworldStart.can_enter(64,77,0); let tile=OverworldStart.tile_at(8,3);
if enter || tile!=217 { wall_error=2; }
WallLinkChecks.place(120,141,1);
} else if n==1 {
for i: int from 0 until 22 { game.update(true,false,false,false,false,false,false,false); }
let bombs=Inventory.read_slot(1); if bombs!=4 { wall_error=3; }
WallLinkChecks.place(64,93,8); game.update(false,false,false,false,false,true,false,false);
let opened=WorldFlags.secret_found(119); if opened { wall_error=4; }
} else if n==2 {
for i: int from 0 until 47 { game.update(false,false,false,false,false,false,false,false); }
let opened=WorldFlags.secret_found(119); if opened { wall_error=5; }
} else if n==3 {
game.update(false,false,false,false,false,false,false,false);
let opened=WorldFlags.secret_found(119); let tile=OverworldStart.tile_at(8,3); let enter=OverworldStart.can_enter(64,77,0);
if !opened || tile!=36 || !enter { wall_error=6; }
} else if n==4 {
for i: int from 0 until 140 { game.update(false,false,false,true,false,false,false,false); }
let id=Stage.id(); if id!=1 { wall_error=7; }
} else if n==5 {
WallLinkChecks.place(120,157,8);
for i: int from 0 until 6 { game.update(false,false,false,true,false,false,false,false); }
let sword=Inventory.sword_level(); if sword!=1 { wall_error=8; }
WallLinkChecks.place(112,221,4);
for i: int from 0 until 66 { game.update(false,false,true,false,false,false,false,false); }
let id=Stage.id(); let opened=WorldFlags.secret_found(119); if id!=0 || !opened { wall_error=9; }
} else if n==6 {
game.continue_game(); for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
let opened=WorldFlags.secret_found(119); let sword=Inventory.sword_level(); if !opened || sword!=1 { wall_error=10; }
} else if n==7 {
game.new_game(); for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
let opened=WorldFlags.secret_found(119); let sword=Inventory.sword_level(); if opened || sword!=0 { wall_error=11; }
} else if n==8 {
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 35 { game.update(false,false,false,false,false,false,false,false); }
} else if n==9 {
for i: int from 0 until 32 { game.update(false,false,false,false,false,false,false,false); }
} else if n==10 {
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 59 { game.update(false,false,false,false,false,false,false,false); }
} else if n==11 {
WallLinkChecks.place(120,61,8); game.update(false,false,false,true,false,false,false,false);
for i: int from 0 until 22 { game.update(false,false,false,false,false,false,false,false); }
} else if n==12 {
for i: int from 0 until 22 { game.update(false,false,false,false,false,false,false,false); }
} else if n==13 {
WallLinkChecks.place(120,221,4); game.update(false,false,true,false,false,false,false,false);
for i: int from 0 until 22 { game.update(false,false,false,false,false,false,false,false); }
} else if n==14 {
for i: int from 0 until 22 { game.update(false,false,false,false,false,false,false,false); }
let closed=OverworldStart.wall_closed(); if !closed { wall_error=12; }
}
game.draw();
}
fn failure_code() -> int { return wall_error; }
}
+15
View File
@@ -0,0 +1,15 @@
import { WorldFlags } from @zelda1:world;
declare service WallLinkChecks {
fn place(x: int,y: int,facing: int) -> void { controller.place_for_stage(state,x,y,facing,true); vitals.reset(); }
fn phases() -> bool {
Link.start_game(); WorldFlags.reset();
for phase: int from 0 until 5 {
if phase!=3 { bomb0.x=64; bomb0.y=77; bomb0.phase=phase; bomb0.timer=10; Link.update(false,false,false,false,false); let opened=WorldFlags.secret_found(119); if opened { return false; } }
}
bomb0.x=80; bomb0.y=77; bomb0.phase=3; bomb0.timer=10;
bomb1.x=64; bomb1.y=77; bomb1.phase=3; bomb1.timer=10;
Link.update(false,false,false,false,false); let opened=WorldFlags.secret_found(119); if opened { return false; }
bomb0.reset(); Link.update(false,false,false,false,false); let opened_after=WorldFlags.secret_found(119); if !opened_after { return false; }
Link.start_game(); WorldFlags.reset(); return true;
}
}
+69
View File
@@ -0,0 +1,69 @@
import { Enemies } from @zelda1:enemies/octorok;
import { Link, LinkCombatChecks } from @zelda1:link;
import { Stage } from @zelda1:stage;
import { Inventory } from @zelda1:inventory;
import { WorldFlags } from @zelda1:world;
import { Loot } from @zelda1:loot;
declare global test_rock: Rock = new Rock(0,0,0,0,0);
declare global enemy_check_failures: int = 0;
declare global enemy_check_count: int = 0;
declare service EnemyCombatChecks {
fn check(passed: bool) -> void { enemy_check_count+=1; if !passed { enemy_check_failures+=1; } }
fn bounce_case(facing: int, incoming: int, dx: int, dy: int) -> void {
Inventory.reset(); LinkCombatChecks.place(120,141,facing);
let x=120; let y=141;
if incoming==1 { x-=6; } else if incoming==2 { x+=6; }
else if incoming==4 { y-=6; } else { y+=6; }
test_rock.launch(x,y,incoming); test_rock.update();
EnemyCombatChecks.check(test_rock.direction!=0 && test_rock.bounce==facing && test_rock.distance==0);
x=test_rock.x; y=test_rock.y; test_rock.update();
EnemyCombatChecks.check(test_rock.x==x+dx && test_rock.y==y+dy && test_rock.distance==2);
for tick: int from 0 until 14 { test_rock.update(); }
EnemyCombatChecks.check(test_rock.direction!=0 && test_rock.distance==30);
test_rock.update(); EnemyCombatChecks.check(test_rock.direction==0);
let partial=Inventory.read_slot(25); EnemyCombatChecks.check(partial==255);
}
fn run() -> int {
Stage.reset(); EnemyCombatChecks.bounce_case(8,4,1,-2); EnemyCombatChecks.bounce_case(4,8,-1,2);
EnemyCombatChecks.bounce_case(2,1,-2,-1); EnemyCombatChecks.bounce_case(1,2,2,-1);
Inventory.reset(); LinkCombatChecks.place(120,141,8);
test_rock.launch(120,147,8); test_rock.update();
let partial=Inventory.read_slot(25); EnemyCombatChecks.check(partial==127 && test_rock.direction==0);
test_rock.launch(120,147,8); test_rock.update();
partial=Inventory.read_slot(25); EnemyCombatChecks.check(partial==127 && test_rock.direction!=0);
// Visit the northern stage with the player at its actual entrance.
Inventory.reset(); WorldFlags.reset(); Enemies.reset(); Loot.reset(); Stage.reset(); Link.start_game();
let command=Stage.advance(120,61,8,0,0,false,true);
for tick: int from 0 until 44 { command=Stage.advance(120,61,8,0,0,false,false); }
command=Stage.advance(120,221,8,0,0,false,false); LinkCombatChecks.place(120,221,8);
Enemies.update(); let alive=Enemies.alive_count(); EnemyCombatChecks.check(alive==4);
EnemyCombatChecks.check(e0.x==80 && e0.y==93 && e1.x==80 && e1.y==157);
// A completed death advances room/cycle/drop; leaving clears the drop.
e0.hp=0; e0.dying=0; Loot.monster_killed(1); Enemies.update();
alive=Enemies.alive_count(); EnemyCombatChecks.check(alive==3 && room_killed==1 && loot0.id==24);
WorldFlags.mark_room_item_taken(103); Enemies.leave_room();
EnemyCombatChecks.check(loot0.id<0);
let count=WorldFlags.kill_count(103); EnemyCombatChecks.check(count==1);
Enemies.update(); alive=Enemies.alive_count(); EnemyCombatChecks.check(alive==3 && e3.hp<0 && e3.dying==0);
// Killing the remaining three keeps the room empty on immediate reentry.
e0.hp=0; e0.dying=0; e1.hp=0; e1.dying=0; e2.hp=0; e2.dying=0;
Enemies.update(); Enemies.leave_room(); count=WorldFlags.kill_count(103); EnemyCombatChecks.check(count==7);
Enemies.update(); alive=Enemies.alive_count(); EnemyCombatChecks.check(alive==0);
let taken=WorldFlags.room_item_taken(103); EnemyCombatChecks.check(taken);
WorldFlags.clear_history(); Enemies.abandon_room(); Enemies.update();
alive=Enemies.alive_count(); EnemyCombatChecks.check(alive==4);
// Death abandons this visit; it does not save its in-room kill count.
e0.hp=0; e0.dying=0; Enemies.update(); Enemies.abandon_room(); Enemies.update();
alive=Enemies.alive_count(); EnemyCombatChecks.check(alive==4);
Enemies.abandon_room(); return enemy_check_failures;
}
fn count() -> int { return enemy_check_count; }
fn draw_bounces(clock: int) -> void {
for col: int from 0 until 4 {
let facing=if col==0 { 8 } else if col==1 { 4 } else if col==2 { 2 } else { 1 };
test_rock.launch(48+col*48,208,1); test_rock.bounce=facing;
for tick: int from 0 until clock%16 { test_rock.update(); }
test_rock.draw();
}
}
}
+49
View File
@@ -0,0 +1,49 @@
import { Link } from @zelda1:link;
import { Inventory } from @zelda1:inventory;
import { Stage } from @zelda1:stage;
declare global test_beam: SwordBeam = new SwordBeam(0,0,0,0,0);
declare global link_check_failures: int = 0;
declare global link_check_count: int = 0;
declare service LinkCombatChecks {
fn check(passed: bool) -> void { link_check_count+=1; if !passed { link_check_failures+=1; } }
fn place(x: int, y: int, facing: int) -> void { controller.place_for_stage(state,x,y,facing,true); vitals.reset(); }
fn run() -> int {
Inventory.reset(); Stage.reset(); Link.start_game();
let full=Inventory.full_hearts(); LinkCombatChecks.check(full);
let damage=Inventory.damage_life(128); full=Inventory.full_hearts(); LinkCombatChecks.check(!full);
let launched=test_beam.launch(120,141,8); LinkCombatChecks.check(!launched && test_beam.phase==0);
Inventory.reset(); damage=Inventory.damage_life(127);
full=Inventory.full_hearts(); LinkCombatChecks.check(full);
launched=test_beam.launch(120,141,8); LinkCombatChecks.check(launched && test_beam.x==120 && test_beam.y==125);
launched=test_beam.launch(120,141,8); LinkCombatChecks.check(!launched);
test_beam.update(); LinkCombatChecks.check(test_beam.y==122);
let hit=test_beam.hits(160,122,8); LinkCombatChecks.check(!hit);
hit=test_beam.hits(120,122,8); LinkCombatChecks.check(hit && test_beam.phase==17 && test_beam.radius==2);
hit=test_beam.hits(120,122,8); LinkCombatChecks.check(!hit);
for tick: int from 0 until 21 { test_beam.update(); }
LinkCombatChecks.check(test_beam.phase==17 && test_beam.radius==23);
test_beam.update(); LinkCombatChecks.check(test_beam.phase==0);
Inventory.reset();
launched=test_beam.launch(120,141,1); LinkCombatChecks.check(launched && test_beam.x==136 && test_beam.y==141);
test_beam.update(); LinkCombatChecks.check(test_beam.x==139);
test_beam.reset(); launched=test_beam.launch(120,141,2); LinkCombatChecks.check(launched && test_beam.x==104);
test_beam.reset(); launched=test_beam.launch(120,141,4); LinkCombatChecks.check(launched && test_beam.y==157);
test_beam.reset(); launched=test_beam.launch(4,141,2); LinkCombatChecks.check(!launched && test_beam.phase==0);
launched=test_beam.launch(120,141,8);
for tick: int from 0 until 22 { test_beam.update(); }
LinkCombatChecks.check(test_beam.phase==17);
// Actual weapon timing: the beam begins when extended state 2 reaches 3.
Link.start_game(); let taken=Inventory.take_sword(1); LinkCombatChecks.check(taken);
for tick: int from 0 until 12 { Link.update(false,false,false,false,tick==0); Link.draw(); }
LinkCombatChecks.check(beam.phase==0 && state.sword_state==2);
Link.update(false,false,false,false,false); Link.draw();
LinkCombatChecks.check(beam.phase==16 && beam.y==125 && state.sword_state==3);
// Stage reposition invalidates the shot; a partial heart suppresses the next.
Link.start_game(); LinkCombatChecks.check(beam.phase==0);
damage=Inventory.damage_life(128);
for tick: int from 0 until 13 { Link.update(false,false,false,false,tick==0); Link.draw(); }
LinkCombatChecks.check(beam.phase==0);
Link.start_game(); return link_check_failures;
}
fn count() -> int { return link_check_count; }
}
+22
View File
@@ -0,0 +1,22 @@
import { Link, LinkInventoryChecks } from @zelda1:link;
import { Inventory } from @zelda1:inventory;
import { InventoryScreen } from @zelda1:screens/inventory;
declare service GameInventoryChecks {
fn run() -> bool {
game.boot(); game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
if game.mode!=5 { return false; }
let taken=Inventory.take_drop(0); Inventory.ensure_selection();
game.update(false,false,false,false,false,true,false,false);
let x=Link.x(); let y=Link.y(); let signature=LinkInventoryChecks.paused_signature();
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 70 { game.update(true,false,false,false,false,true,false,false); }
if !InventoryScreen.active() || Link.x()!=x || Link.y()!=y || LinkInventoryChecks.paused_signature()!=signature { return false; }
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 59 { game.update(false,false,false,false,false,false,false,false); }
if InventoryScreen.opened() { return false; }
game.update(false,false,false,false,false,false,false,false);
if LinkInventoryChecks.paused_signature()==signature { return false; }
game.boot(); return game.mode==0 && !InventoryScreen.opened();
}
}
@@ -0,0 +1,193 @@
import { LinkInventoryChecks } from @zelda1:link;
import { GameInventoryChecks } from @zelda1:game;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
import { InventoryScreen } from @zelda1:screens/inventory;
import { Stage } from @zelda1:stage;
import { Link } from @zelda1:link;
import { InventoryGraphics } from @zelda1:screens/inventory;
declare global test_extra: int=0;
declare global test_batch: int=0;
declare global test_count: int=0;
declare global test_failed: int=0;
declare global test_results: array<int> = new array<int>(2048);
declare service InventoryChecks {
fn check(value: bool) -> void { test_results[test_count]=if value { 1 } else { 0 }; test_count+=1; if !value { test_failed+=1; } }
fn selection_case(values: array<int>, start: int, direction: int, expected: int) -> void { let s=new BSelection(values,start,0); s.search(direction,start); InventoryChecks.check(s.selected==expected); }
// ORACLE_BATCHES
fn batch_138() -> void {}
fn batch_139() -> void {}
fn extra() -> int {
Inventory.reset(); Stage.reset(); Link.start_game();
inventory_slots[7]=2; inventory_slots[15]=1; Inventory.ensure_selection();
if selection.selected!=7 { return 1; }
let damage=Inventory.damage_life(300); Link.use_b(true);
let heal_active=Link.healing(); let potion_count=Inventory.read_slot(7);
if !heal_active { return 20+potion_count; } if potion_count!=1 { return 30+potion_count; }
for tick: int from 0 until 200 { if Link.healing() { Link.heal_frame(); } }
let still_healing=Link.healing(); let full=Inventory.full_hearts(); if still_healing || !full { return 3; }
Link.use_b(true); for tick: int from 0 until 200 { if Link.healing() { Link.heal_frame(); } }
Inventory.ensure_selection(); if selection.selected!=15 { return 40+selection.selected; } let remaining_potions=Inventory.read_slot(7); if remaining_potions!=0 { return 60+remaining_potions; }
inventory_slots[1]=3; inventory_slots[29]=1; selection.selected=0; selection.previous=0;
Inventory.select_direction(1); if selection.selected!=1 { return 5; }
Inventory.select_direction(1); if selection.selected!=1 { return 6; }
Inventory.select_direction(0); Inventory.select_direction(1); if selection.selected!=15 { return 7; }
Inventory.select_direction(0); Inventory.select_direction(1); if selection.selected!=0 { return 8; }
inventory_slots[30]=1; let displayed=Inventory.selected_display_slot(); if displayed!=30 { return 9; }
return 0;
}
fn frame() -> void {
if test_batch==0 { InventoryChecks.batch_0(); }
if test_batch==1 { InventoryChecks.batch_1(); }
if test_batch==2 { InventoryChecks.batch_2(); }
if test_batch==3 { InventoryChecks.batch_3(); }
if test_batch==4 { InventoryChecks.batch_4(); }
if test_batch==5 { InventoryChecks.batch_5(); }
if test_batch==6 { InventoryChecks.batch_6(); }
if test_batch==7 { InventoryChecks.batch_7(); }
if test_batch==8 { InventoryChecks.batch_8(); }
if test_batch==9 { InventoryChecks.batch_9(); }
if test_batch==10 { InventoryChecks.batch_10(); }
if test_batch==11 { InventoryChecks.batch_11(); }
if test_batch==12 { InventoryChecks.batch_12(); }
if test_batch==13 { InventoryChecks.batch_13(); }
if test_batch==14 { InventoryChecks.batch_14(); }
if test_batch==15 { InventoryChecks.batch_15(); }
if test_batch==16 { InventoryChecks.batch_16(); }
if test_batch==17 { InventoryChecks.batch_17(); }
if test_batch==18 { InventoryChecks.batch_18(); }
if test_batch==19 { InventoryChecks.batch_19(); }
if test_batch==20 { InventoryChecks.batch_20(); }
if test_batch==21 { InventoryChecks.batch_21(); }
if test_batch==22 { InventoryChecks.batch_22(); }
if test_batch==23 { InventoryChecks.batch_23(); }
if test_batch==24 { InventoryChecks.batch_24(); }
if test_batch==25 { InventoryChecks.batch_25(); }
if test_batch==26 { InventoryChecks.batch_26(); }
if test_batch==27 { InventoryChecks.batch_27(); }
if test_batch==28 { InventoryChecks.batch_28(); }
if test_batch==29 { InventoryChecks.batch_29(); }
if test_batch==30 { InventoryChecks.batch_30(); }
if test_batch==31 { InventoryChecks.batch_31(); }
if test_batch==32 { InventoryChecks.batch_32(); }
if test_batch==33 { InventoryChecks.batch_33(); }
if test_batch==34 { InventoryChecks.batch_34(); }
if test_batch==35 { InventoryChecks.batch_35(); }
if test_batch==36 { InventoryChecks.batch_36(); }
if test_batch==37 { InventoryChecks.batch_37(); }
if test_batch==38 { InventoryChecks.batch_38(); }
if test_batch==39 { InventoryChecks.batch_39(); }
if test_batch==40 { InventoryChecks.batch_40(); }
if test_batch==41 { InventoryChecks.batch_41(); }
if test_batch==42 { InventoryChecks.batch_42(); }
if test_batch==43 { InventoryChecks.batch_43(); }
if test_batch==44 { InventoryChecks.batch_44(); }
if test_batch==45 { InventoryChecks.batch_45(); }
if test_batch==46 { InventoryChecks.batch_46(); }
if test_batch==47 { InventoryChecks.batch_47(); }
if test_batch==48 { InventoryChecks.batch_48(); }
if test_batch==49 { InventoryChecks.batch_49(); }
if test_batch==50 { InventoryChecks.batch_50(); }
if test_batch==51 { InventoryChecks.batch_51(); }
if test_batch==52 { InventoryChecks.batch_52(); }
if test_batch==53 { InventoryChecks.batch_53(); }
if test_batch==54 { InventoryChecks.batch_54(); }
if test_batch==55 { InventoryChecks.batch_55(); }
if test_batch==56 { InventoryChecks.batch_56(); }
if test_batch==57 { InventoryChecks.batch_57(); }
if test_batch==58 { InventoryChecks.batch_58(); }
if test_batch==59 { InventoryChecks.batch_59(); }
if test_batch==60 { InventoryChecks.batch_60(); }
if test_batch==61 { InventoryChecks.batch_61(); }
if test_batch==62 { InventoryChecks.batch_62(); }
if test_batch==63 { InventoryChecks.batch_63(); }
if test_batch==64 { InventoryChecks.batch_64(); }
if test_batch==65 { InventoryChecks.batch_65(); }
if test_batch==66 { InventoryChecks.batch_66(); }
if test_batch==67 { InventoryChecks.batch_67(); }
if test_batch==68 { InventoryChecks.batch_68(); }
if test_batch==69 { InventoryChecks.batch_69(); }
if test_batch==70 { InventoryChecks.batch_70(); }
if test_batch==71 { InventoryChecks.batch_71(); }
if test_batch==72 { InventoryChecks.batch_72(); }
if test_batch==73 { InventoryChecks.batch_73(); }
if test_batch==74 { InventoryChecks.batch_74(); }
if test_batch==75 { InventoryChecks.batch_75(); }
if test_batch==76 { InventoryChecks.batch_76(); }
if test_batch==77 { InventoryChecks.batch_77(); }
if test_batch==78 { InventoryChecks.batch_78(); }
if test_batch==79 { InventoryChecks.batch_79(); }
if test_batch==80 { InventoryChecks.batch_80(); }
if test_batch==81 { InventoryChecks.batch_81(); }
if test_batch==82 { InventoryChecks.batch_82(); }
if test_batch==83 { InventoryChecks.batch_83(); }
if test_batch==84 { InventoryChecks.batch_84(); }
if test_batch==85 { InventoryChecks.batch_85(); }
if test_batch==86 { InventoryChecks.batch_86(); }
if test_batch==87 { InventoryChecks.batch_87(); }
if test_batch==88 { InventoryChecks.batch_88(); }
if test_batch==89 { InventoryChecks.batch_89(); }
if test_batch==90 { InventoryChecks.batch_90(); }
if test_batch==91 { InventoryChecks.batch_91(); }
if test_batch==92 { InventoryChecks.batch_92(); }
if test_batch==93 { InventoryChecks.batch_93(); }
if test_batch==94 { InventoryChecks.batch_94(); }
if test_batch==95 { InventoryChecks.batch_95(); }
if test_batch==96 { InventoryChecks.batch_96(); }
if test_batch==97 { InventoryChecks.batch_97(); }
if test_batch==98 { InventoryChecks.batch_98(); }
if test_batch==99 { InventoryChecks.batch_99(); }
if test_batch==100 { InventoryChecks.batch_100(); }
if test_batch==101 { InventoryChecks.batch_101(); }
if test_batch==102 { InventoryChecks.batch_102(); }
if test_batch==103 { InventoryChecks.batch_103(); }
if test_batch==104 { InventoryChecks.batch_104(); }
if test_batch==105 { InventoryChecks.batch_105(); }
if test_batch==106 { InventoryChecks.batch_106(); }
if test_batch==107 { InventoryChecks.batch_107(); }
if test_batch==108 { InventoryChecks.batch_108(); }
if test_batch==109 { InventoryChecks.batch_109(); }
if test_batch==110 { InventoryChecks.batch_110(); }
if test_batch==111 { InventoryChecks.batch_111(); }
if test_batch==112 { InventoryChecks.batch_112(); }
if test_batch==113 { InventoryChecks.batch_113(); }
if test_batch==114 { InventoryChecks.batch_114(); }
if test_batch==115 { InventoryChecks.batch_115(); }
if test_batch==116 { InventoryChecks.batch_116(); }
if test_batch==117 { InventoryChecks.batch_117(); }
if test_batch==118 { InventoryChecks.batch_118(); }
if test_batch==119 { InventoryChecks.batch_119(); }
if test_batch==120 { InventoryChecks.batch_120(); }
if test_batch==121 { InventoryChecks.batch_121(); }
if test_batch==122 { InventoryChecks.batch_122(); }
if test_batch==123 { InventoryChecks.batch_123(); }
if test_batch==124 { InventoryChecks.batch_124(); }
if test_batch==125 { InventoryChecks.batch_125(); }
if test_batch==126 { InventoryChecks.batch_126(); }
if test_batch==127 { InventoryChecks.batch_127(); }
if test_batch==128 { InventoryChecks.batch_128(); }
if test_batch==129 { InventoryChecks.batch_129(); }
if test_batch==130 { InventoryChecks.batch_130(); }
if test_batch==131 { InventoryChecks.batch_131(); }
if test_batch==132 { InventoryChecks.batch_132(); }
if test_batch==133 { InventoryChecks.batch_133(); }
if test_batch==134 { InventoryChecks.batch_134(); }
if test_batch==135 { InventoryChecks.batch_135(); }
if test_batch==136 { InventoryChecks.batch_136(); }
if test_batch==137 { InventoryChecks.batch_137(); }
if test_batch==138 { InventoryChecks.batch_138(); }
if test_batch==139 { InventoryChecks.batch_139(); }
if test_batch==140 { let assertion_14=LinkInventoryChecks.run(); InventoryChecks.check(assertion_14); }
if test_batch==141 { let assertion_15=GameInventoryChecks.run(); InventoryChecks.check(assertion_15); }
if test_batch==142 { let extra_result=InventoryChecks.extra(); test_extra=extra_result; InventoryChecks.check(extra_result==0); }
if test_batch<143 { test_batch+=1; }
Gfx.clear(Color.rgb(0,0,0)); Gfx.fill_rect(470,260,3,3,Color.rgb(test_extra as long,0,0));
for i: int from 0 until test_count { let v=test_results[i] else 0; Gfx.fill_rect(i%160*3,i/160*3,2,2,if v==1 { Color.rgb(0,255,0) } else { Color.rgb(255,0,0) }); }
Gfx.fill_rect(477,267,3,3,if test_batch<143 { Color.rgb(0,0,255) } else if test_failed==0 { Color.rgb(0,255,0) } else { Color.rgb(255,0,0) });
}
fn visual() -> void {
Inventory.reset(); for i: int from 0 until 40 { inventory_slots[i]=1; } inventory_slots[24]=34; inventory_slots[25]=255; inventory_slots[26]=255; inventory_slots[37]=8;
Stage.reset(); Link.start_game(); InventoryScreen.reset(); InventoryScreen.open(); for i: int from 0 until 65 { let c=InventoryScreen.advance(false,0); }
}
fn draw() -> void { InventoryScreen.draw(); }
}
+25
View File
@@ -0,0 +1,25 @@
import { Inventory } from @zelda1:inventory;
declare service LinkInventoryChecks {
fn run() -> bool {
Inventory.reset(); Stage.reset(); Link.start_game();
let taken=Inventory.take_drop(0); Inventory.ensure_selection(); Link.use_b(true);
if Inventory.read_slot(1)!=3 || bomb0.phase!=1 || bomb0.y!=125 { return false; }
bomb0.advance(); if bomb0.phase!=2 || bomb0.timer!=48 { return false; }
for i: int from 0 until 47 { bomb0.advance(); }
if bomb0.phase!=2 || bomb0.timer!=1 { return false; }
bomb0.advance(); if bomb0.phase!=3 || bomb0.timer!=24 { return false; }
if !bomb0.hits(143,148) || bomb0.hits(144,125) || bomb0.hits(120,149) { return false; }
for i: int from 0 until 24 { bomb0.advance(); }
if bomb0.phase!=4 || bomb0.timer!=12 || bomb0.hits(120,125) { return false; }
for i: int from 0 until 12 { bomb0.advance(); }
if bomb0.phase!=0 { return false; }
// Two active weapons, but never a second ticking fuse.
Link.start_game(); Link.use_b(true); state.action=0; Link.use_b(true);
if Inventory.read_slot(1)!=2 || bomb1.phase!=0 { return false; }
bomb0.phase=3; Link.use_b(true);
if Inventory.read_slot(1)!=1 || bomb1.phase!=1 { return false; }
state.action=0; Link.use_b(true); if Inventory.read_slot(1)!=1 { return false; }
Link.start_game(); return bomb0.phase==0 && bomb1.phase==0;
}
fn paused_signature() -> int { return bomb0.phase*10000+bomb0.timer*100+bomb1.phase; }
}
+8
View File
@@ -0,0 +1,8 @@
import { InventoryChecks } from @zelda1:inventory;
import { Pad, Button } from @sdk:input;
declare global visual: bool=false;
[Init] fn init() -> void {}
[Frame] fn frame() -> void {
if Pad.pressed(Button.Select) { visual=!visual; if visual { InventoryChecks.visual(); } }
if visual { InventoryChecks.draw(); } else { InventoryChecks.frame(); }
}
+28
View File
@@ -0,0 +1,28 @@
# Save guest qualification
Generate with `python3 tools/generate_save_fixture.py --action N`. It never
installs itself. Use disposable images under `.tmp`, never the user's card.
Append inventory/store/menu/game helpers to their respective module main.pbs,
export the helper services temporarily, and use the generated root entry.
Keep Init and MemcardBoot. Back up and restore all modified production files.
Actions: 0 saves a seeded profile when empty, or verifies reload when present;
1 also attempts Save after loading an existing profile (read-only test);
2 writes bad magic; 3 writes an unsupported schema; 4 commits only 12 bytes.
Actions 2..4 intentionally publish invalid game data in a valid disposable
container. A later boot must reject it, keep live game defaults, and preserve
its payload. Host metadata may change on admission; compare slot bytes rather
than equating a whole-container hash with payload preservation.
Markers after game rendering: pixel (0,0) is green on pass; pixel (3,0) encodes
phase and role; (6,0) is the SaveStore outcome. The 180 raw slot bytes can be
read from red values at (400,20+i); (401,0) contains the used length. Those
markers/columns are fixture-only and never belong in production.
A durable test must end the runtime process and reopen the same image. Check
00/7f/80/ff, native inventory/world flags, life normalization, clock clearing,
and a project-version change with stable app_id. Memory-only commits must
show NOT SAVED TO CARD. Explicitly discard only disposable memory-test RAM
when shutdown refuses dirty data. `tools/validate_save.py` verifies captures
against independent Python bytes, Adler-32 and native CHR pixel composition.
+75
View File
@@ -0,0 +1,75 @@
import { WorldFlags } from @zelda1:world;
import { SaveMenuChecks } from @zelda1:screens/continue_menu;
import { Inventory } from @zelda1:inventory;
import { Link } from @zelda1:link;
import { SaveStore, SaveStoreChecks } from @zelda1:save;
import { SaveInventoryChecks } from @zelda1:inventory;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare const SAVE_TEST_ACTION: int=0;
declare global save_test_phase: int=0;
declare global save_test_failed: int=0;
declare global save_test_role: int=0;
declare global save_test_wait: int=0;
declare service SaveGameChecks {
fn frame() -> void {
if save_test_phase==0 {
let menu=SaveMenuChecks.verify(); if !menu { save_test_failed=7; }
let available=SaveStore.available(); save_test_role=if available { 1 } else { 0 };
game.update(false,false,false,false,false,false,true,false); save_test_phase=1;
let issue=SaveStore.load_issue();
if !available && issue!=0 {
save_test_role=2; save_test_phase=9; let loaded=SaveStore.load();
let sword=Inventory.sword_level(); let taken=WorldFlags.room_item_taken(119);
if loaded || sword!=0 || taken { save_test_failed=9; }
}
} else if save_test_phase==1 {
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
if save_test_role==1 {
let inventory=SaveInventoryChecks.verify(); let world=SaveStoreChecks.verify_world();
if !inventory || !world || game.mode!=5 { save_test_failed=1; }
save_test_phase=if SAVE_TEST_ACTION==1 { 2 } else { 8 };
} else {
SaveInventoryChecks.seed(); SaveStoreChecks.seed_world();
let codec=SaveStoreChecks.codec_checks(); if codec!=0 { save_test_failed=10+codec; }
save_test_phase=2;
}
} else if save_test_phase==2 {
game.update(false,false,false,false,false,false,false,true);
if game.mode!=12 { save_test_failed=2; }
let old_x=Link.x(); let old_y=Link.y(); let old_life=Inventory.read_slot(24); let old_partial=Inventory.read_slot(25);
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 64 { game.update(false,false,false,false,false,false,false,false); }
let x=Link.x(); let y=Link.y(); let life=Inventory.read_slot(24); let partial=Inventory.read_slot(25);
if game.mode!=5 || x!=old_x || y!=old_y || life!=old_life || partial!=old_partial { save_test_failed=8; }
game.update(false,false,false,false,false,false,false,true); save_test_phase=3;
} else if save_test_phase==3 {
if SAVE_TEST_ACTION>=2 {
let injected=SaveStoreChecks.publish_bad(SAVE_TEST_ACTION); if !injected { save_test_failed=9; }
game.mode=13; save_test_phase=4;
} else {
game.update(false,false,false,false,false,false,false,true);
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 64 { game.update(false,false,false,false,false,false,false,false); }
if game.mode!=13 { save_test_failed=3; } save_test_phase=4;
}
} else if save_test_phase==4 {
game.update(false,false,false,false,false,false,false,false);
let state=SaveStore.last_state(); let pending=SaveStore.busy(); save_test_wait+=1;
if state!=1 && !pending {
if state!=2 && state!=3 && state!=4 && state!=6 { save_test_failed=4; }
if state==2 { let durable=SaveStoreChecks.durable_valid(if SAVE_TEST_ACTION==4 { 12 } else { 180 }); if !durable { save_test_failed=6; } }
save_test_phase=5;
}
if save_test_wait>500 { save_test_failed=5; }
} else if save_test_phase==5 {
// Retain the result screen for capture; test driver ends this process.
SaveStore.poll();
}
game.draw(); SaveStoreChecks.draw_raw();
Gfx.fill_rect(0,0,3,3,if save_test_failed==0 { Color.rgb(0,255,0) } else { Color.rgb(save_test_failed as long,0,0) });
Gfx.fill_rect(3,0,3,3,Color.rgb(save_test_phase as long,save_test_role as long,0));
let state=SaveStore.last_state(); Gfx.fill_rect(6,0,3,3,Color.rgb(state as long,0,0));
}
}
+15
View File
@@ -0,0 +1,15 @@
declare service SaveInventoryChecks {
fn seed() -> void {
Inventory.reset(); let sword=Inventory.take_sword(1); let bombs=Inventory.take_drop(0);
let heart=Inventory.take_life_item(26); let damage=Inventory.damage_life(128);
inventory_slots[20]=1; inventory_slots[21]=1; inventory_slots[22]=5;
inventory_slots[33]=127; inventory_slots[34]=128; inventory_slots[35]=255; inventory_slots[36]=0;
}
fn verify() -> bool {
let sword=Inventory.sword_level(); let bombs=Inventory.read_slot(1); let life=Inventory.read_slot(24); let fraction=Inventory.read_slot(25);
if sword!=1 || bombs!=4 || life!=50 || fraction!=255 { return false; }
let clock=Inventory.read_slot(21); let fairy=Inventory.read_slot(20); let rupees=Inventory.read_slot(22); if clock!=0 || fairy!=1 || rupees!=5 { return false; }
let b0=Inventory.read_slot(36); let b1=Inventory.read_slot(33); let b2=Inventory.read_slot(34); let b3=Inventory.read_slot(35);
return b0==0 && b1==127 && b2==128 && b3==255;
}
}
+11
View File
@@ -0,0 +1,11 @@
declare service SaveMenuChecks {
fn verify() -> bool {
let test=new ContinueState(new ContinueData(),0,0,false);
let choice=test.advance(true,false); if test.selection!=1 { return false; }
choice=test.advance(true,false); if test.selection!=2 { return false; }
choice=test.advance(true,false); if test.selection!=0 { return false; }
choice=test.advance(true,true); if test.selection!=0 || !test.confirming { return false; }
for i: int from 0 until 63 { let pending_choice=test.advance(true,true); if pending_choice!= -1 { return false; } }
let final_choice=test.advance(false,false); return final_choice==0;
}
}
+56
View File
@@ -0,0 +1,56 @@
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
import { Inventory } from @zelda1:inventory;
import { WorldFlags } from @zelda1:world;
declare service SaveStoreChecks {
fn codec_checks() -> int {
let bytes=new MemcardBuffer(180); save_codec.snapshot(bytes);
let good=save_codec.validate(bytes); if good!=0 { return 1; }
if bytes.read(8)!=142 || bytes.read(9)!=6 || bytes.read(10)!=246 || bytes.read(11)!=217 { return 8; }
bytes.write(0,0); let bad_magic=save_codec.validate(bytes); if bad_magic!=1 { return 2; }
bytes.write(0,90); bytes.write(4,2); let unknown=save_codec.validate(bytes); if unknown!=2 { return 3; }
bytes.write(4,1); let old=bytes.read(13); bytes.write(13,old+1); let corrupt=save_codec.validate(bytes); if corrupt!=1 { return 4; }
bytes.write(13,old); bytes.write(49,0); save_codec.checksum(bytes); let bad_bombs=save_codec.validate(bytes); if bad_bombs!=1 { return 5; }
save_codec.snapshot(bytes); bytes.write(36,255); save_codec.checksum(bytes); let full=save_codec.validate(bytes); if full!=0 { return 6; }
bytes.write(36,15); save_codec.checksum(bytes); let bad_life=save_codec.validate(bytes); if bad_life!=1 { return 7; }
return 0;
}
fn seed_world() -> void {
WorldFlags.reset(); let values=new array<int>(128);
values[119]=16; values[100]=128; values[103]=146;
values[20]=0; values[21]=127; values[22]=128; values[23]=255;
WorldFlags.restore_slots(values);
}
fn verify_world() -> bool {
let sword=WorldFlags.room_item_taken(119); let secret=WorldFlags.secret_found(100); let partial=WorldFlags.kill_count(103);
if !sword || !secret || partial!=2 { return false; }
let b0=WorldFlags.read_slot(20); let b1=WorldFlags.read_slot(21); let b2=WorldFlags.read_slot(22); let b3=WorldFlags.read_slot(23);
if b0!=0 || b1!=127 || b2!=128 || b3!=255 { return false; }
// History is absent after reload: native $07 resets on the next visit.
let count=WorldFlags.enter_room(23,4); let flags=WorldFlags.read_slot(23);
return count==4 && flags==248;
}
fn durable_valid(expected_size: int) -> bool {
let stat=Mem.slot_stat(save_context,0); if stat.status!=0 as long { return false; }
return stat.has_payload==1 as long && stat.used_bytes==expected_size as long && !stat.dirty;
}
fn publish_bad(kind: int) -> bool {
let bytes=new MemcardBuffer(180); save_codec.snapshot(bytes);
if kind==2 { bytes.write(0,0); } else if kind==3 { bytes.write(4,2); }
let count=if kind==4 { 12 } else { 180 };
for i: int from 0 until 180 { save_staging[i]=bytes.read(i); }
let write=Mem.slot_write(save_context,0,0,bytes,0,count); if write.status!=0 as long { return false; }
let commit=Mem.slot_commit(save_context,0); if commit.status!=0 as long { return false; }
save_request=commit.request; save_result=1; return true;
}
fn draw_raw() -> void {
let stat=Mem.slot_stat(save_context,0); if stat.status!=0 as long { return; }
let count=stat.used_bytes as int; if count<=0 || count>180 { return; }
let bytes=new MemcardBuffer(180); let read=Mem.slot_read(save_context,0,0,bytes,0,count); if read.status!=0 as long { return; }
Gfx.fill_rect(401,0,1,1,Color.rgb(count as long,0,0));
for i: int from 0 until count { let value=bytes.read(i); Gfx.fill_rect(400,i+20,1,1,Color.rgb(value as long,0,0)); }
}
fn cache_signature() -> int {
let sum=0; for i: int from 0 until 180 { let value=save_cache[i] else 0; sum=(sum*31+value)%65521; } return sum;
}
}
+35
View File
@@ -0,0 +1,35 @@
import { Inventory } from @zelda1:inventory;
import { Stage } from @zelda1:stage;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global check_phase: int=0;
declare global check_error: int=0;
declare service TemporaryBombChecks {
fn tick() -> void {
if check_phase==0 {
game.boot(); game.new_game(); for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
let count=Inventory.read_slot(1); if count!=0 { check_error=1; }
} else if check_phase==1 {
for i: int from 0 until 22 { game.update(true,false,false,false,false,false,false,false); }
let count=Inventory.read_slot(1); if count!=4 { check_error=2; }
} else if check_phase==2 {
game.update(false,false,false,false,false,true,false,false);
let count=Inventory.read_slot(1); if count!=3 { check_error=3; }
} else if check_phase==3 {
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 66 { game.update(false,false,false,false,false,false,false,false); }
let count=Inventory.read_slot(1); if count!=3 { check_error=4; }
} else if check_phase==4 {
game.update(false,false,false,false,false,false,true,false);
for i: int from 0 until 59 { game.update(false,false,false,false,false,false,false,false); }
Stage.return_to_start(); Stage.update_test_pickups(152,138,true);
let count=Inventory.read_slot(1); if count!=3 { check_error=5; }
} else if check_phase==5 {
game.new_game(); for i: int from 0 until 76 { game.update(false,false,false,false,false,false,false,false); }
for i: int from 0 until 22 { game.update(true,false,false,false,false,false,false,false); }
let count=Inventory.read_slot(1); if count!=4 { check_error=6; }
}
if check_phase<6 { check_phase+=1; }
game.draw(); Gfx.fill_rect(0,0,3,3,if check_error==0 { Color.rgb(0,255,0) } else { Color.rgb(check_error as long,0,0) });
}
}
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Generate isolated wall checks outside src. Installing/restoring is explicit."""
import json
from extract_graphics import ROOT
def generate():
out=ROOT/'.tmp/bomb-wall-fixture';out.mkdir(exist_ok=True,parents=True);cases=json.loads((ROOT/'extracted/bomb_wall/native-collision.json').read_text())['cases']
lines=['declare global wall_cases_failed: int=0;','declare service WallWorldChecks {',' fn one(dx: int,dy: int,expected: bool) -> void {',' WorldFlags.reset(); let wall=new BombableWall(119,64,77); let opened=wall.try_blast(64+dx,77+dy);',' if opened!=expected { wall_cases_failed+=1; }',' let saved=WorldFlags.secret_found(119); if saved!=expected { wall_cases_failed+=1; }',' }',' fn failed() -> int { return wall_cases_failed; }',' fn run(batch: int) -> void {']
for i in range(0,len(cases),8):
lines.append(f' if batch=={i//8} {{')
for dx,dy,v in cases[i:i+8]:lines.append(f' WallWorldChecks.one({dx},{dy},{str(v).lower()});')
lines.append(' }')
lines+=[' }',' fn flags() -> void {',' WorldFlags.reset(); WorldFlags.mark_room_item_taken(119); WorldFlags.mark_secret_found(119); WorldFlags.leave_room(119,4,2);',' let secret=WorldFlags.secret_found(119); let item=WorldFlags.room_item_taken(119); let kills=WorldFlags.kill_count(119);',' if !secret || !item || kills!=2 { wall_cases_failed+=1; }',' let wall=new BombableWall(119,64,77); let reopened=wall.try_blast(64,77); if reopened { wall_cases_failed+=1; }',' WorldFlags.reset(); let open=WorldFlags.secret_found(119); if open { wall_cases_failed+=1; }',' }','}']
(out/'world.pbs').write_text('\n'.join(lines)+'\n')
source=ROOT/'tools/fixtures/bomb_wall'
for f in ('link','game'):(out/f'{f}.pbs').write_bytes((source/f'{f}.pbs').read_bytes())
(out/'main.pbs').write_text('''import { WallWorldChecks } from @zelda1:world;
import { WallGameChecks } from @zelda1:game;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global batch: int=0;
[Init] fn init() -> void {}
[Frame] fn frame() -> void {
if batch<16 { WallWorldChecks.run(batch); }
else if batch==16 { WallWorldChecks.flags(); }
else if batch<32 { WallGameChecks.check_phase(batch-17); }
if batch<32 { batch+=1; }
let fail=WallWorldChecks.failed(); let game_fail=WallGameChecks.failure_code();
Gfx.fill_rect(0,0,3,3,if fail==0 && game_fail==0 { Color.rgb(0,255,0) } else { Color.rgb(game_fail as long,fail as long,0) });
}
''')
print('Generated 121 native cases and 15 game phases, outside src')
if __name__=='__main__':generate()
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Temporary composition integration entrypoint; restore production before return."""
import sys,json
from pathlib import Path
from extract_graphics import ROOT
out=ROOT/'.tmp/cave-composition-fixture';out.mkdir(exist_ok=True)
installed=out/'installed'
files=['src/main.pbs','src/stage/main.pbs','src/stage/mod.barrel']
if sys.argv[-1]=='restore':
assert installed.exists(),'No installed fixture to restore'
for f in files:(ROOT/f).write_bytes((out/f.replace('/','__')).read_bytes())
installed.unlink()
raise SystemExit
assert not installed.exists(),'Restore the installed fixture first'
for f in files:
b=out/f.replace('/','__');b.write_bytes((ROOT/f).read_bytes())
installed.write_text('Task-owned temporary fixture installed\n')
p=ROOT/'src/stage/mod.barrel';p.write_text(p.read_text()+'pub service CaveCompositionTest;\n')
p=ROOT/'src/stage/main.pbs';p.write_text(p.read_text()+'''\ndeclare service CaveCompositionTest {
fn enter() -> void { flow.reset(); flow.active=1; }
}\n''')
source='''import { SaveStore } from @zelda1:save;
import { Stage, CaveCompositionTest } from @zelda1:stage;
import { CaveStart } from @zelda1:stages/cave_start;
import { WorldFlags } from @zelda1:world;
import { Inventory } from @zelda1:inventory;
import { Scene } from @zelda1:scene;
import { Hud } from @zelda1:hud;
import { InventoryScreen } from @zelda1:screens/inventory;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global tick: int=0;
declare global failed: bool=false;
declare global menu_open: bool=false;
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
[Init] fn init() -> void { Inventory.reset(); WorldFlags.reset(); Stage.reset(); CaveCompositionTest.enter(); Scene.reset(); }
[Frame] fn frame() -> void {
if tick==1 || tick==6 { InventoryScreen.open(); for i: int from 0 until 25 { let done=InventoryScreen.advance(false,0); } menu_open=true; }
if tick==2 { menu_open=false; InventoryScreen.reset(); Scene.reset(); let taken=CaveStart.try_take_sword(119,152); if taken { failed=true; } }
if tick==3 { let taken=CaveStart.try_take_sword(120,152); if !taken || Inventory.sword_level()!=1 || !WorldFlags.room_item_taken(119) { failed=true; } }
if tick==4 || tick==5 { CaveStart.advance(1); }
if tick==7 { menu_open=false; InventoryScreen.reset(); Scene.reset(); for i: int from 0 until 62 { CaveStart.advance(1); } }
if tick==8 { CaveStart.reset(); let taken=CaveStart.try_take_sword(120,152); if taken || Inventory.sword_level()!=1 { failed=true; } }
if tick==9 { WorldFlags.reset(); Inventory.reset(); CaveStart.reset(); }
if Stage.render_revision()!=1 || Stage.menu_variant()!=1 { failed=true; }
if tick==4 || tick==7 || tick==8 { if CaveStart.visual_variant()!=2 { failed=true; } }
if tick==3 || tick==5 || tick==6 { if CaveStart.visual_variant()!=1 { failed=true; } }
Scene.set_hud_offset(0);
if menu_open { InventoryScreen.draw(); } else if Scene.ensure_ready() { Hud.draw(); Stage.draw_objects(); }
Scene.draw_frame();
let color=if failed { Color.rgb(255,0,0) } else { Color.rgb(0,255,0) }; Gfx.fill_rect(0,0,1,1,color);
tick+=1;
}
'''
(ROOT/'src/main.pbs').write_text(source)
names=['initial','menu-initial','outside-contact','collected-person','blink-hidden','blink-person','menu-collected','expired','revisit','new-game']
validation=ROOT/'extracted/cave/start/composition-validation';validation.mkdir(parents=True,exist_ok=True)
(validation/'cases.json').write_text(json.dumps([{'name':n,'frame':i+1} for i,n in enumerate(names)],indent=2)+'\n')
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Create isolated PBS checks from native 6502 cases; never install automatically."""
import json
from extract_graphics import ROOT
def generate():
out=ROOT/'.tmp/combat-fixture';out.mkdir(exist_ok=True,parents=True)
for name in ('link','enemy'):(out/f'{name}-fixture.pbs').write_text((ROOT/f'tools/fixtures/combat/{name}.pbs').read_text())
oracle=json.loads((ROOT/'extracted/combat/oracle-cases.json').read_text());calls=[];assertions=0
for flags,count,present,expected,newflags in oracle['history']:
if flags>=32:continue
calls.append(f' CombatFixture.history_case({flags},{count},{str(present).lower()},{expected},{newflags%8});');assertions+=3
for flags,spawned,killed,expected in oracle['saves']:
if flags>=32:continue
calls.append(f' CombatFixture.save_case({flags},{spawned},{killed},{expected%8});');assertions+=2
for cycle,r,kills,help_count,bomb,expected,newhelp,newbomb in oracle['drops']:
calls.append(f' CombatFixture.drop_case({cycle},{r},{kills},{help_count},{bomb},{expected},{newhelp},{newbomb});');assertions+=3
source='''import { Loot } from @zelda1:loot;
import { WorldFlags } from @zelda1:world;
import { Inventory } from @zelda1:inventory;
import { Link, LinkCombatChecks } from @zelda1:link;
import { EnemyCombatChecks } from @zelda1:enemies/octorok;
import { Scene } from @zelda1:scene;
import { CombatGraphics } from @zelda1:combat_graphics;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global fixture_rules: DropRules = new DropRules(new DropData(),0,0,0,0,0);
declare global fixture_drop: DroppedItem = new DroppedItem(new FairyFlight(0,127,0,0,0,0),-1,0,0,0);
declare global checks: array<int> = new array<int>(8192);
declare global check_count: int = 0;
declare global failed: int = 0;
declare global view: int = 0;
declare global view_clock: int = 0;
declare global batch_index: int = 0;
declare service CombatFixture {
fn check(passed: bool) -> void { checks[check_count]=if passed { 1 } else { 0 }; check_count+=1; if !passed { failed+=1; } }
fn history_case(flags: int, count: int, present: bool, expected: int, low: int) -> void {
WorldFlags.reset();
if present { let entered=WorldFlags.enter_room(103,4); }
if flags>=16 { WorldFlags.mark_room_item_taken(103); }
WorldFlags.leave_room(103,99,flags%8);
let actual=WorldFlags.enter_room(103,count); CombatFixture.check(actual==expected);
let kills=WorldFlags.kill_count(103); CombatFixture.check(kills==low);
let taken=WorldFlags.room_item_taken(103); CombatFixture.check(taken==(flags>=16));
}
fn save_case(flags: int, spawned: int, killed: int, low: int) -> void {
WorldFlags.reset(); if flags>=16 { WorldFlags.mark_room_item_taken(103); }
WorldFlags.leave_room(103,99,flags%8); WorldFlags.leave_room(103,spawned,killed);
let kills=WorldFlags.kill_count(103); CombatFixture.check(kills==low);
let taken=WorldFlags.room_item_taken(103); CombatFixture.check(taken==(flags>=16));
}
fn drop_case(cycle: int, r: int, kills: int, help: int, bomb: int, expected: int, newhelp: int, newbomb: int) -> void {
fixture_rules.cycle=(cycle+9)%10; fixture_rules.unharmed=kills; fixture_rules.help=help; fixture_rules.help_bomb=bomb;
let value=fixture_rules.choose(7,r); CombatFixture.check(value==expected);
CombatFixture.check(fixture_rules.help==newhelp); CombatFixture.check(fixture_rules.help_bomb==newbomb);
}
fn run() -> void {
'''+ '\n'.join(calls)+'''
// Six unique rooms evict; revisiting an existing room does not refresh it.
WorldFlags.reset(); let entered=WorldFlags.enter_room(103,4); WorldFlags.leave_room(103,4,4);
for room: int from 104 until 109 { entered=WorldFlags.enter_room(room,0); }
entered=WorldFlags.enter_room(103,4); CombatFixture.check(entered==0);
entered=WorldFlags.enter_room(109,0); entered=WorldFlags.enter_room(103,4); CombatFixture.check(entered==4);
WorldFlags.leave_room(103,4,2);
for room: int from 110 until 116 { entered=WorldFlags.enter_room(room,0); }
entered=WorldFlags.enter_room(103,4); CombatFixture.check(entered==2);
WorldFlags.leave_room(103,2,2); WorldFlags.clear_history(); entered=WorldFlags.enter_room(103,4); CombatFixture.check(entered==4);
// Currency uses pending-add byte and advances one rupee every other tick.
Inventory.reset(); let taken=Inventory.take_drop(15); CombatFixture.check(taken);
let value=Inventory.read_slot(22); CombatFixture.check(value==0);
value=Inventory.read_slot(38); CombatFixture.check(value==5);
Inventory.tick_money(1); value=Inventory.read_slot(22); CombatFixture.check(value==0);
Inventory.tick_money(2); value=Inventory.read_slot(22); CombatFixture.check(value==1);
for tick: int from 0 until 260 { taken=Inventory.take_drop(24); Inventory.tick_money(2); }
value=Inventory.read_slot(22); CombatFixture.check(value==255);
taken=Inventory.take_drop(0); value=Inventory.read_slot(1); CombatFixture.check(value==4);
taken=Inventory.take_drop(0); taken=Inventory.take_drop(0); value=Inventory.read_slot(1); CombatFixture.check(value==8);
// Item lifetime, flashing grace period, contact offset and off-room cleanup.
Inventory.reset(); Loot.reset(); fixture_drop.appear(24,120,144);
let collected=fixture_drop.update(120,141,true,false,0); CombatFixture.check(!collected);
for tick: int from 0 until 29 { Loot.tick(); collected=fixture_drop.update(120,141,true,false,0); }
CombatFixture.check(!collected && fixture_drop.lifetime==240);
Loot.tick(); Loot.tick(); collected=fixture_drop.update(120,141,true,false,0);
CombatFixture.check(collected && fixture_drop.id<0);
value=Inventory.read_slot(38); CombatFixture.check(value==1);
fixture_drop.appear(34,120,144);
for tick: int from 0 until 510 { Loot.tick(); collected=fixture_drop.update(0,0,false,false,0); }
CombatFixture.check(fixture_drop.id<0);
// Damage resets guaranteed-help counters, not the 10-step cycle.
Inventory.reset(); Link.start_game(); Loot.reset();
for kill: int from 0 until 9 { Loot.monster_killed(1); let item=Loot.complete_kill(7,255); }
value=Loot.help_count(); CombatFixture.check(value==9);
let hurt=Link.hurt(128,120,125); CombatFixture.check(hurt);
value=Loot.help_count(); CombatFixture.check(value==0);
value=Loot.unharmed_kills(); CombatFixture.check(value==0);
value=Loot.cycle(); CombatFixture.check(value==9);
let link_failed=LinkCombatChecks.run(); CombatFixture.check(link_failed==0);
let enemy_failed=EnemyCombatChecks.run(); CombatFixture.check(enemy_failed==0);
Inventory.reset(); Loot.reset();
}
fn frame(select_pressed: bool) -> void {
if select_pressed { view=(view+1)%3; view_clock=0; }
view_clock+=1;
if view==0 {
Gfx.clear(Color.rgb(0,0,0));
for i: int from 0 until check_count {
let value=checks[i] else 0; let color=if value==1 { Color.rgb(0,255,0) } else { Color.rgb(255,0,0) };
Gfx.fill_rect((i%160)*3,(i/160)*3,2,2,color);
}
let red_channel: int=check_count/256; let green_channel: int=check_count%256;
Gfx.fill_rect(474,267,3,3,Color.rgb(red_channel as long,green_channel as long,0));
let verdict=if failed==0 { Color.rgb(0,255,0) } else { Color.rgb(255,0,0) };
Gfx.fill_rect(477,267,3,3,verdict); return;
}
if !Scene.bind_ui(13) { return; }
if view==1 {
CombatGraphics.drop(0,0,24,96); CombatGraphics.drop(15,0,64,96);
CombatGraphics.drop(24,0,104,96); CombatGraphics.drop(24,8,144,96);
CombatGraphics.drop(34,0,184,96); CombatGraphics.drop(34,8,24,144);
CombatGraphics.drop(35,0,64,144); CombatGraphics.drop(35,4,104,144);
CombatGraphics.counter(0,24,24); CombatGraphics.counter(9,64,24);
CombatGraphics.counter(23,104,24); CombatGraphics.counter(123,144,24); CombatGraphics.counter(255,184,24);
} else {
CombatGraphics.beam(8,0,24,96); CombatGraphics.beam(4,1,72,96);
CombatGraphics.beam(2,2,120,96); CombatGraphics.beam(1,3,168,96);
CombatGraphics.spread(80,160,6,0); CombatGraphics.spread(168,160,12,2);
EnemyCombatChecks.draw_bounces(view_clock);
}
Scene.draw_frame();
}
}
'''
# Spread the oracle cases over video frames so the test itself respects the
# headless watchdog; no production timing/budget changes are required.
import re
run_start=source.index(' fn run() -> void {')
frame_start=source.index(' fn frame(select_pressed: bool)')
run_body=source[run_start:frame_start]
tail_body=run_body[run_body.index(' // Six unique rooms'):].rsplit(' }',1)[0]
batches=['\n'.join(calls[i:i+10]) for i in range(0,len(calls),10)]
batches += [part for part in re.split(r'(?= //)',tail_body) if part.strip()]
methods=[' fn begin() -> void {}',' fn run() -> void {']
for i in range(len(batches)):methods.append(f' if batch_index=={i} {{ CombatFixture.batch_{i}(); batch_index+=1; return; }}')
methods.append(' }')
for i,batch in enumerate(batches):
if 'value=' in batch and 'let value=' not in batch:batch=' let value: int=0;\n'+batch
methods += [f' fn batch_{i}() -> void {{',batch,' }']
source=source[:run_start]+'\n'.join(methods)+'\n'+source[frame_start:]
source=source.replace(' if select_pressed { view=',f' if batch_index<{len(batches)} {{ CombatFixture.run(); }}\n if select_pressed && batch_index=={len(batches)} {{ view=')
source=source.replace('let verdict=if failed==0 { Color.rgb(0,255,0) } else { Color.rgb(255,0,0) };',f'let verdict=if batch_index<{len(batches)} {{ Color.rgb(0,0,255) }} else if failed==0 {{ Color.rgb(0,255,0) }} else {{ Color.rgb(255,0,0) }};')
(out/'loot-fixture.pbs').write_text(source)
(out/'main.pbs').write_text('''import { CombatFixture } from @zelda1:loot;
import { Pad, Button } from @sdk:input;
[Init]
fn init() -> void { CombatFixture.begin(); }
[Frame]
fn frame() -> void { CombatFixture.frame(Pad.pressed(Button.Select)); }
''')
# Record generated call count; extra checks in fixture plus two subsystem verdicts.
total=source.count('CombatFixture.check(')-9 # helper bodies contain 3+2+3 calls; declaration is not a call
# Oracle calls expand to multiple checks; explicit calls outside helpers are counted below.
tail=tail_body
total=assertions+tail.count('CombatFixture.check(')
(out/'metadata.json').write_text(json.dumps({'oracle_assertions':assertions,'top_level_assertions':total,'batches':len(batches)},indent=2)+'\n')
print('Generated combat fixture:',total,'top-level assertions; not installed')
if __name__=='__main__':generate()
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Generate isolated guest checks. Never install or modify production sources."""
import json
from extract_graphics import ROOT
def generate():
out=ROOT/'.tmp/inventory-fixture';out.mkdir(exist_ok=True,parents=True)
source=ROOT/'tools/fixtures/inventory'
cases=json.loads((ROOT/'extracted/inventory_screen/selection-oracle.json').read_text())['cases'];methods=[]
for i in range(0,len(cases),8):
methods.append(f' fn batch_{i//8}() -> void {{')
for slots,start,direction,expected in cases[i:i+8]:methods.append(' InventoryChecks.selection_case(['+','.join(map(str,slots))+f'],{start},{direction},{expected});')
methods.append(' }')
template=(source/'inventory.template.pbs').read_text().replace('// ORACLE_BATCHES','\n'.join(methods))
(out/'inventory.pbs').write_text(template)
for name in ('link','game','main'):(out/f'{name}.pbs').write_bytes((source/f'{name}.pbs').read_bytes())
print('Generated',len(cases),'native selection assertions + 3 subsystem checks; 143 batches')
if __name__=='__main__':generate()
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
"""Generate an isolated saved-source Studio test entrypoint; never install it."""
import json
from extract_graphics import ROOT
from validate_life_rom import damage,heal
def generate():
cases=[]
def add(name,commands,hv,hp,code=None):cases.append((name,commands,hv,hp,code))
for ring in (0,1,2):
for amount in (1,32,64,128,255,256,257,384,512,767,768,1024,65535):
hv,hp,dead=damage(0x22,255,amount,ring)
commands=[]
if ring:commands.append(f'let equip = Inventory.take_equipment({17+ring});')
commands.append(f'let damage_code = Inventory.damage_life({amount});')
add(f'damage-r{ring}-{amount}',commands,hv,hp,2 if dead else 1)
for amount in (1,128,256,384,600,700,767):
hv,hp,_=damage(34,255,amount)
for count in (1,3,16):
after=heal(hv,hp,count)
add(f'heal-{amount}-{count}',[f'let damage_code = Inventory.damage_life({amount});',f'let healed = Inventory.heal_life({count});'],*after)
for n in range(15):
capped=min(n,13);hv=34+17*capped
add('containers-'+str(n),[f'for count: int from 0 until {n} {{ let added = Inventory.take_life_item(26); }}'],hv,255)
add('half-heart',["let damage_code = Inventory.damage_life(128);"],34,127)
add('empty-life-exact',["let damage_code = Inventory.damage_life(767);"],32,0,1)
add('heart-item',["let damage_code = Inventory.damage_life(384);","let healed = Link.take_life_item(34);"],34,127)
add('fairy-item',["let damage_code = Inventory.damage_life(700);","let healed = Link.take_life_item(35);"],34,255)
n=len(cases);d=n+95;end=d+295
lines=['import { Inventory } from @zelda1:inventory;','import { WorldFlags } from @zelda1:world;',
'import { Stage } from @zelda1:stage;','import { Scene } from @zelda1:scene;','import { Link } from @zelda1:link;',
'import { Hud } from @zelda1:hud;','import { Gfx } from @sdk:gfx;','import { Color } from @core:color;',
'declare global check_frame: int = 0;','declare global failed: bool = false;',
'[Init]','fn init() -> void { Inventory.reset(); WorldFlags.reset(); Stage.reset(); Scene.reset(); Link.reset(); }',
'[Frame]','fn frame() -> void {']
captures=[]
for i,(name,commands,hv,hp,code) in enumerate(cases):
lines+= [f' if check_frame == {i} {{',' Inventory.reset();']+[' '+c for c in commands]
if code:lines+=[f' if damage_code != {code} {{ failed = true; }}']
lines += [f' if Inventory.read_slot(24) != {hv} || Inventory.read_slot(25) != {hp} {{ failed = true; }}',' }']
if name in ('damage-r0-128','damage-r0-384','damage-r1-128','damage-r2-128','containers-13','empty-life-exact','heart-item','fairy-item'):
captures.append({'name':name,'frame':i+1,'packed':hv,'partial':hp,'palette':0})
lines += [f' if check_frame == {n} {{ Inventory.reset(); Link.reset(); let armed = Inventory.take_sword(1); WorldFlags.mark_room_item_taken(119); }}',
f' if check_frame >= {n} {{ Link.update(false, false, false, false, false); }}',
f' if check_frame == {n} {{ let accepted = Link.hurt(128, 104, 133); if !accepted || Link.invincibility_remaining() != 24 {{ failed = true; }} }}',
f' if check_frame == {n+1} {{ let accepted = Link.hurt(128, 104, 133); if accepted || Link.invincibility_remaining() != 23 {{ failed = true; }} }}',
f' if check_frame == {n+46} {{ let accepted = Link.hurt(128, 104, 133); if accepted || Link.invincibility_remaining() != 1 {{ failed = true; }} }}',
f' if check_frame == {n+47} {{ let accepted = Link.hurt(128, 104, 133); if !accepted || Inventory.read_slot(24) != 33 || Inventory.read_slot(25) != 254 {{ failed = true; }} }}',
f' if check_frame == {d} {{ let accepted = Link.hurt(65535, 104, 133); if !accepted || !Link.is_dead() {{ failed = true; }} }}',
f' if check_frame == {d+1} {{ let healed = Link.take_life_item(35); if healed {{ failed = true; }} }}',
f' if check_frame == {d+293} && Link.game_over() {{ failed = true; }}',
f' if check_frame == {d+294} && !Link.game_over() {{ failed = true; }}',
f' if check_frame == {end} {{ Link.continue_game(); Stage.return_to_start(); Scene.reset(); if Link.is_dead() || Inventory.read_slot(24) != 34 || Inventory.read_slot(25) != 255 || Inventory.sword_level() != 1 || !WorldFlags.room_item_taken(119) {{ failed = true; }} }}',
' Stage.set_death_presentation(Link.death_presentation());',
' if Scene.ensure_ready() { Hud.draw(); Link.draw(); Scene.draw_frame(); }',
' let color = if failed { Color.rgb(255, 0, 0) } else { Color.rgb(0, 255, 0) };',
' Gfx.fill_rect(0, 0, 1, 1, color);',' check_frame += 1;','}','']
for name,t in [('hurt',n),('immune',n+1),('immune_last',n+46),('hurt_again',n+47),('death_start',d),('death_spin',d+33),('death_grey',d+113),('death_spark',d+137),('death_large_spark',d+147),('death_blank',d+152),('game_over',d+198),('continue_ready',d+294),('continued',end)]:captures.append({'name':name,'frame':t+1})
out=ROOT/'.tmp/life-fixture-main.pbs';out.write_text('\n'.join(lines))
meta={'arithmetic_cases':n,'final_frame':end+1,'captures':sorted(captures,key=lambda c:c['frame'])}
(ROOT/'extracted/life/fixture-cases.json').write_text(json.dumps(meta,indent=2)+'\n')
print(json.dumps({'cases':n,'frames':end+1,'captures':len(captures)}))
if __name__=='__main__':generate()
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Generate isolated PBS assertions; caller must install and restore explicitly."""
from extract_graphics import ROOT
def generate():
out=ROOT/'.tmp/north-fixture';out.mkdir(exist_ok=True,parents=True)
(out/'main.pbs').write_text('''import { EnemyFixture } from @zelda1:enemies/octorok;
[Init]
fn init() -> void { EnemyFixture.run(); }
[Frame]
fn frame() -> void { EnemyFixture.draw(); }
''')
source='''import { Enemies } from @zelda1:enemies/octorok;
import { Stage } from @zelda1:stage;
import { Link } from @zelda1:link;
import { Inventory } from @zelda1:inventory;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global results: array<int> = new array<int>(64);
declare global cases: int = 0;
declare global actor: Octorok = new Octorok(new Rock(0,0,0,0,0),128,141,8,0,0,0,0,0,0,1,0,false,0,0,0,7);
declare global bolt: Rock = new Rock(0,0,0,0,0);
declare service EnemyFixture {
fn check(passed: bool) -> void { results[cases]=if passed { 1 } else { 0 }; cases+=1; }
fn run() -> void {
Inventory.reset(); Stage.reset(); Link.start_game(); Enemies.reset();
let command=Stage.advance(120,61,8,0,0,false,false);
EnemyFixture.check(command==0);
command=Stage.advance(120,61,8,0,0,false,true);
EnemyFixture.check(command==2);
EnemyFixture.check(Stage.scrolling());
for tick: int from 0 until 43 { command=Stage.advance(120,61,8,0,0,false,false); }
EnemyFixture.check(Stage.scrolling());
command=Stage.advance(120,61,8,0,0,false,false);
EnemyFixture.check(Stage.id()==2);
EnemyFixture.check(Stage.position_y()==221);
command=Stage.advance(120,221,8,0,0,false,false);
EnemyFixture.check(!Stage.controls_locked());
Enemies.update();
let total=Enemies.alive_count(); EnemyFixture.check(total==4);
let wall=Stage.enemy_tile(0,0); EnemyFixture.check(wall>=137);
let ground=Stage.enemy_tile(16,10); EnemyFixture.check(ground<137);
actor.reset(128,141,32); EnemyFixture.check(actor.cloud==44);
for tick: int from 0 until 44 { actor.update(0,255); }
EnemyFixture.check(actor.cloud==0 && actor.x==128 && actor.y==141);
actor.x=144; actor.direction=8; actor.turn=255;
for tick: int from 0 until 32 { actor.update(0,255); }
EnemyFixture.check(actor.y==125 && actor.x==144);
EnemyFixture.check(actor.clock==32);
// Force a pending native fire countdown without RNG dependence.
actor.shoot=17; actor.update(0,255);
let shot_dir=actor.shot_direction(); EnemyFixture.check(actor.shoot==16 && shot_dir!=0);
let shot_y=actor.shot_y(); EnemyFixture.check(shot_y==actor.y);
// Front-facing ordinary shield blocks a rock; rear contact harms Link.
Inventory.reset(); Link.start_game();
bolt.x=120; bolt.y=132; bolt.direction=4; bolt.update();
EnemyFixture.check(bolt.direction!=0 && bolt.bounce==8);
let partial=Inventory.read_slot(25); EnemyFixture.check(partial==255);
bolt.x=120; bolt.y=150; bolt.direction=8; bolt.update();
partial=Inventory.read_slot(25); EnemyFixture.check(partial==127);
EnemyFixture.check(Link.invincibility_remaining()==24);
bolt.x=120; bolt.y=150; bolt.direction=8; bolt.update();
partial=Inventory.read_slot(25); EnemyFixture.check(partial==127);
// A sword can kill only during fully extended state 2.
Inventory.reset(); Link.start_game(); let taken=Inventory.take_sword(1);
EnemyFixture.check(taken);
Link.update(false,false,false,false,true);
let hit=Link.sword_hits(120,125); EnemyFixture.check(!hit);
for tick: int from 0 until 5 { Link.draw(); }
hit=Link.sword_hits(120,125); EnemyFixture.check(hit);
hit=Link.sword_hits(160,125); EnemyFixture.check(!hit);
actor.reset(120,125,32); actor.cloud=0; actor.turn=255; actor.direction=8;
actor.update(0,255); EnemyFixture.check(actor.hp==0 && actor.dying==18);
for tick: int from 0 until 18 { actor.update(0,255); }
EnemyFixture.check(actor.dying==0 && actor.hp==0);
// Body contact uses the same half-heart damage and original immunity.
Inventory.reset(); Link.start_game();
actor.reset(120,141,32); actor.cloud=0; actor.turn=255;
actor.update(0,255); partial=Inventory.read_slot(25);
EnemyFixture.check(partial==127);
actor.update(0,255); partial=Inventory.read_slot(25);
EnemyFixture.check(partial==127);
// Return south only on explicit directional input.
command=Stage.advance(120,221,4,0,0,false,false); EnemyFixture.check(command==0);
command=Stage.advance(120,221,4,0,0,true,false); EnemyFixture.check(command==2);
for tick: int from 0 until 44 { command=Stage.advance(120,221,4,0,0,false,false); }
EnemyFixture.check(Stage.id()==0 && Stage.position_y()==61);
}
fn draw() -> void {
Gfx.clear(Color.rgb(0,0,0));
for i: int from 0 until cases {
let verdict=results[i] else 0;
let color=if verdict==1 { Color.rgb(0,255,0) } else { Color.rgb(255,0,0) };
Gfx.fill_rect((i%16)*16,(i/16)*16,14,14,color);
}
}
}
'''
import re
lines=[];counter=0
for line in source.splitlines():
if 'EnemyFixture.check(' in line:
for call in re.findall(r'(?:Stage|Link)\.[A-Za-z_]+\(\)',line):
name=f'check_local_{counter}';counter+=1
lines.append(f' let {name}={call};');line=line.replace(call,name,1)
lines.append(line)
(out/'fixture.pbs').write_text('\n'.join(lines)+'\n')
print('Generated isolated fixture, 32 assertions; not installed')
if __name__=='__main__':generate()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Install/restore an isolated integration fixture; backups live outside src."""
import json,sys
from pathlib import Path
from extract_graphics import ROOT
OUT=ROOT/'.tmp/overworld-fixture';OUT.mkdir(exist_ok=True)
marker=OUT/'installed'
files=['src/main.pbs','src/stage/main.pbs','src/stage/mod.barrel','src/enemies/octorok/main.pbs','src/enemies/octorok/mod.barrel']
if sys.argv[-1]=='restore':
assert marker.exists(),'No installed fixture to restore'
for f in files:(ROOT/f).write_bytes((OUT/f.replace('/','__')).read_bytes())
marker.unlink();print('Production sources restored');raise SystemExit
assert not marker.exists(),'Restore the installed fixture first'
for f in files:
b=OUT/f.replace('/','__');b.write_bytes((ROOT/f).read_bytes())
marker.write_text('owned fixture')
def append(f,s):
p=ROOT/f;p.write_text(p.read_text()+s)
append('src/stage/mod.barrel','pub service StageTest;\n')
append('src/stage/main.pbs','''
declare service StageTest {
fn select(id: int) -> void { flow.reset(); flow.active=id; }
}
''')
append('src/enemies/octorok/mod.barrel','pub service EnemyTest;\n')
append('src/enemies/octorok/main.pbs','''
declare service EnemyTest {
fn pending() -> int { return edge_pending; }
fn clear() -> void { e0.deactivate(); e1.deactivate(); e2.deactivate(); e3.deactivate(); e4.deactivate(); }
fn cursor() -> int { return edge.cell; }
fn cloud_free() -> bool { return e0.cloud==0 && e1.cloud==0 && e2.cloud==0 && e3.cloud==0 && e4.cloud==0; }
}
''')
lines=['import { Stage, StageTest } from @zelda1:stage;','import { Overworld } from @zelda1:overworld;','import { Enemies, EnemyTest } from @zelda1:enemies/octorok;','import { Inventory } from @zelda1:inventory;','import { WorldFlags } from @zelda1:world;','import { Link } from @zelda1:link;','import { Scene } from @zelda1:scene;','import { Hud } from @zelda1:hud;','import { InventoryScreen } from @zelda1:screens/inventory;','import { Gfx } from @sdk:gfx;','import { Color } from @core:color;','declare global tick: int=0;','declare global failed: bool=false;','declare global menu_test: bool=false;','[Init] fn init() -> void { Inventory.reset(); WorldFlags.reset(); Stage.reset(); Enemies.reset(); Link.reset(); Scene.reset(); }','[Frame] fn frame() -> void {']
cases=[];t=0
catalog=json.loads((ROOT/'extracted/overworld/expansion/catalog.json').read_text())
def case(name,code):
global t
lines.append(f' if tick=={t} {{ '+code+' }');cases.append({'name':name,'frame':t+1});t+=1
for entry in catalog['rooms']:
stage,native=entry['stage'],entry['room']
case('room-'+hex(native)[2:],f'StageTest.select({stage}); Scene.reset(); if Stage.room_id()!={native} {{ failed=true; }}')
# Menu drawing at a partial open reveals the live terrain strip.
case('menu-'+hex(native)[2:],'InventoryScreen.open(); for i: int from 0 until 25 { let done=InventoryScreen.advance(false,0); } menu_test=true;')
case('menu-close-'+hex(native)[2:],'menu_test=false; InventoryScreen.reset(); Scene.reset();')
for link in catalog['links']:
for a,b,d in [(link['a'],link['b'],link['direction']),(link['b'],link['a'],{1:2,4:8}[link['direction']])]:
pos=link['openings'][0];x=240 if d==1 else 0 if d==2 else pos;y=221 if d==4 else 61 if d==8 else pos
case(f'edge-{a}-{b}-begin',f'StageTest.select({a}); Scene.reset(); let cmd=Stage.advance({x},{y},{d},0,0,{str(d==4).lower()},{str(d==8).lower()}); if !Stage.scrolling() {{ failed=true; }}')
count=64 if d<4 else 44
for f in range(count):
check=f' if Stage.id()!={b} || Stage.scrolling() {{ failed=true; }}' if f==count-1 else ''
lines.append(f' if tick=={t} {{ let cmd=Stage.advance(0,0,0,0,0,false,false);'+check+' }');t+=1
cases.append({'name':f'edge-{a}-{b}-end','frame':t})
case('no-invented-north','StageTest.select(2); let cmd=Stage.advance(112,61,8,0,0,false,true); if Stage.scrolling() { failed=true; }')
for stage in range(6,10):
case(f'edge-spawn-{stage}-entry',f'WorldFlags.reset(); Enemies.reset(); StageTest.select({stage}); Enemies.update(); if EnemyTest.pending()!=2 || Enemies.alive_count()!=1 || !EnemyTest.cloud_free() {{ failed=true; }}')
for f in range(180):lines.append(f' if tick=={t} {{ Enemies.tick_random(); Enemies.update(); }}');t+=1
case(f'edge-spawn-{stage}-complete','if EnemyTest.pending()!= -1 || Enemies.alive_count()!=4 || !EnemyTest.cloud_free() { failed=true; }')
case('history-clean','WorldFlags.reset(); WorldFlags.mark_room_item_taken(87); let n=WorldFlags.enter_room(87,4); WorldFlags.leave_room(87,4,4); let again=WorldFlags.enter_room(87,4); if again!=0 { failed=true; }')
for room in [88,104,120,119,103,102]:case('history-visit-'+str(room),f'let n=WorldFlags.enter_room({room},4);')
case('history-eviction','let n=WorldFlags.enter_room(87,4); if n!=4 || !WorldFlags.room_item_taken(87) { failed=true; }')
lines+=[' Scene.set_hud_offset(0);',' if menu_test { InventoryScreen.draw(); } else { if Scene.ensure_ready() { Hud.draw(); Stage.draw_objects(); } }',' Scene.draw_frame();',' let color=if failed { Color.rgb(255,0,0) } else { Color.rgb(0,255,0) };',' Gfx.fill_rect(0,0,1,1,color); tick+=1;','}']
import re
source='\n'.join(lines)+'\n'
for action in ['let cmd=Stage.advance(0,0,0,0,0,false,false);','Enemies.tick_random(); Enemies.update();']:
pattern=r'(?: if tick==\d+ \{ '+re.escape(action)+r' \}\n){2,}'
def compact(m):
ticks=list(map(int,re.findall(r'tick==(\d+)',m[0])));return f' if tick>={ticks[0]} && tick<={ticks[-1]} {{ {action} }}\n'
source=re.sub(pattern,compact,source)
(ROOT/'src/main.pbs').write_text('import { SaveStore } from @zelda1:save;\n[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }\n'+source);(OUT/'cases.json').write_text(json.dumps({'cases':cases,'final_frame':t},indent=2));print('Fixture frames:',t)
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Temporary real-secret gameplay/save fixture; never use the user's card."""
import sys,json
from pathlib import Path
from extract_graphics import ROOT
out=ROOT/'.tmp/real-secret-fixture';out.mkdir(exist_ok=True);marker=out/'installed';files=['src/main.pbs','src/stage/main.pbs','src/stage/mod.barrel','src/link/main.pbs','src/link/mod.barrel']
if sys.argv[-1]=='restore':
assert marker.exists()
for f in files:(ROOT/f).write_bytes((out/f.replace('/','__')).read_bytes())
marker.unlink();raise SystemExit
assert not marker.exists()
for f in files:(out/f.replace('/','__')).write_bytes((ROOT/f).read_bytes())
marker.write_text('owned fixture')
def append(f,s):
p=ROOT/f;p.write_text(p.read_text()+s)
append('src/stage/mod.barrel','pub service RealSecretStageCheck;\n')
append('src/stage/main.pbs','\ndeclare service RealSecretStageCheck { fn select(id: int) -> void { flow.reset(); flow.active=id; } }\n')
append('src/link/mod.barrel','pub service RealSecretLinkCheck;\n')
append('src/link/main.pbs','\ndeclare service RealSecretLinkCheck { fn place(x: int,y: int,dir: int) -> void { controller.place_for_stage(state,x,y,dir,true); vitals.reset(); } }\n')
source='''import { SaveStore } from @zelda1:save;
import { Inventory } from @zelda1:inventory;
import { WorldFlags } from @zelda1:world;
import { Stage, RealSecretStageCheck } from @zelda1:stage;
import { OverworldNorth } from @zelda1:stages/overworld_north;
import { CaveSecret } from @zelda1:stages/cave_secret;
import { Link, RealSecretLinkCheck } from @zelda1:link;
import { Scene } from @zelda1:scene;
import { Hud } from @zelda1:hud;
import { InventoryScreen } from @zelda1:screens/inventory;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global tick: int=0;
declare global failed: bool=false;
declare global loaded: bool=false;
declare global menu_open: bool=false;
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
[Init] fn init() -> void {
Inventory.reset(); WorldFlags.reset(); Stage.reset(); Link.start_game(); RealSecretStageCheck.select(2); Scene.reset();
if SaveStore.available() { loaded=SaveStore.load(); }
if !loaded { let bombs=Inventory.take_drop(0); WorldFlags.leave_room(103,4,1); }
RealSecretLinkCheck.place(112,109,8);
}
[Frame] fn frame() -> void {
SaveStore.poll();
if tick==0 && SaveStore.available() { loaded=SaveStore.load(); }
if loaded {
if !WorldFlags.secret_found(103) || !WorldFlags.room_item_taken(103) || WorldFlags.kill_count(103)!=1 || Inventory.read_slot(22)!=30 || Inventory.read_slot(1)!=3 { failed=true; }
if tick==1 { RealSecretStageCheck.select(10); CaveSecret.enter(); Scene.reset(); let taken=CaveSecret.try_take(120,152); if taken { failed=true; } }
} else {
Inventory.tick_money(tick);
if tick==0 { if OverworldNorth.wall_opened() || Stage.raw_tile(14,2)!=216 { failed=true; } }
if tick==1 { OverworldNorth.blast(128,80); OverworldNorth.blast(112,96); if OverworldNorth.wall_opened() { failed=true; } }
if tick==2 { Link.use_b(true); }
if tick>=2 && tick<=51 { Link.update(false,false,false,false,false); }
if tick==49 && OverworldNorth.wall_opened() { failed=true; }
if tick==51 { if !OverworldNorth.wall_opened() || WorldFlags.read_slot(103)!=129 || Inventory.read_slot(1)!=3 || Stage.raw_tile(14,2)!=36 { failed=true; } }
if tick==53 { RealSecretLinkCheck.place(112,77,8); }
if tick>=53 && tick<=151 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==151 { if Stage.id()!=10 || Link.x()!=112 || Link.y()!=173 || Stage.controls_locked() || Stage.room_id()!=103 || Stage.hud_glyph()!=20 { failed=true; } }
if tick==153 { InventoryScreen.open(); menu_open=true; }
if tick>=154 && tick<=178 { let closed=InventoryScreen.advance(false,0); }
if tick==179 { menu_open=false; InventoryScreen.reset(); Scene.reset(); }
if tick==180 { RealSecretLinkCheck.place(120,157,8); Link.prepare_stage(false,false); Link.update(false,false,false,false,false); if WorldFlags.read_slot(103)!=145 || Inventory.read_slot(38)!=30 { failed=true; } }
if tick==181 { let duplicate=CaveSecret.try_take(120,152); if duplicate { failed=true; } }
if tick==243 { if Inventory.read_slot(22)!=30 || Inventory.read_slot(38)!=0 { failed=true; } }
if tick==245 { RealSecretLinkCheck.place(112,221,4); }
if tick>=245 && tick<=310 { Link.prepare_stage(tick==245,false); Link.update(false,false,false,false,false); }
if tick==310 { if Stage.id()!=2 || Link.x()!=112 || Link.y()!=77 || Stage.raw_tile(14,2)!=243 { failed=true; } }
if tick==311 { Link.prepare_stage(false,false); if Stage.controls_locked() { failed=true; } }
if tick==312 { RealSecretLinkCheck.place(112,85,4); Link.prepare_stage(false,false); }
if tick==313 { RealSecretLinkCheck.place(112,77,8); }
if tick>=313 && tick<=411 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==411 { if Stage.id()!=10 || Inventory.read_slot(22)!=30 { failed=true; } let taken=CaveSecret.try_take(120,152); if taken { failed=true; } }
if tick==412 { SaveStore.begin(); }
}
Scene.set_hud_offset(0);
if menu_open { InventoryScreen.draw(); } else if Scene.ensure_ready() { Hud.draw(); Stage.draw_objects(); Link.draw(); }
Scene.draw_frame();
let color=if failed { Color.rgb(255,0,0) } else { Color.rgb(0,255,0) }; Gfx.fill_rect(0,0,1,1,color);
let durable=SaveStore.last_state(); if durable==2 { Gfx.fill_rect(1,0,1,1,Color.rgb(0,255,0)); }
tick+=1;
}
'''
(ROOT/'src/main.pbs').write_text(source)
meta={'captures':[{'name':n,'frame':t+1} for t,n in [(0,'wall-closed'),(49,'before-blast'),(51,'wall-open'),(53,'door-begin'),(85,'door-mid'),(117,'cave-spawn'),(151,'cave-ready'),(178,'cave-menu'),(180,'reward-contact'),(243,'reward-credited'),(277,'exit-mid'),(310,'return-north'),(311,'warp-lock'),(411,'revisit'),(418,'save-submitted')]],'final_frame':419}
(ROOT/'extracted/real_secret/fixture-cases.json').write_text(json.dumps(meta,indent=2)+'\n');print('Real secret fixture installed')
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Generate guest validation sources outside src; use disposable cards only."""
import argparse
from extract_graphics import ROOT
def generate(action):
out=ROOT/'.tmp/save-fixture-generated';out.mkdir(exist_ok=True,parents=True);source=ROOT/'tools/fixtures/save'
for name in ('store','inventory','menu','game'):
text=(source/f'{name}.pbs').read_text()
if name=='game':text=text.replace('SAVE_TEST_ACTION: int=0',f'SAVE_TEST_ACTION: int={action}')
(out/f'{name}.pbs').write_text(text)
(out/'main.pbs').write_text('''import { Game, SaveGameChecks } from @zelda1:game;
import { SaveStore } from @zelda1:save;
[Init] fn init() -> void { Game.boot(); }
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
[Frame] fn frame() -> void { SaveGameChecks.frame(); }
''')
print('Generated disposable-card fixture, action',action,'in',out)
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--action',type=int,choices=range(5),default=0);generate(parser.parse_args().action)
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Isolated shop oracle, transitions, item lifts and disposable memcard test."""
import json,sys
from pathlib import Path
from extract_graphics import ROOT
out=ROOT/'.tmp/shop-fixture';out.mkdir(exist_ok=True);marker=out/'installed';files=['src/main.pbs','src/stage/main.pbs','src/stage/mod.barrel','src/link/main.pbs','src/link/mod.barrel','src/inventory/main.pbs','src/inventory/mod.barrel']
if sys.argv[-1]=='restore':
assert marker.exists()
for f in files:(ROOT/f).write_bytes((out/f.replace('/','__')).read_bytes())
(ROOT/'src/inventory/shop-fixture.generated.pbs').unlink();marker.unlink();raise SystemExit
assert not marker.exists()
for f in files:(out/f.replace('/','__')).write_bytes((ROOT/f).read_bytes())
marker.write_text('owned fixture')
def append(f,s):
p=ROOT/f;p.write_text(p.read_text()+s)
append('src/stage/mod.barrel','pub service ShopStageCheck;\n');append('src/stage/main.pbs','\ndeclare service ShopStageCheck { fn select(id: int) -> void { flow.reset(); flow.active=id; } }\n')
append('src/link/mod.barrel','pub service ShopLinkCheck;\n');append('src/link/main.pbs','\ndeclare service ShopLinkCheck { fn place(x: int,y: int,dir: int) -> void { controller.place_for_stage(state,x,y,dir,true); vitals.reset(); } fn lifted() -> int { return state.lift_item; } fn timer() -> int { return state.lift_counter; } }\n')
append('src/inventory/mod.barrel','pub service ShopInventoryCheck;\nmod struct ShopOracle;\n')
cases=json.loads((ROOT/'extracted/shop/native-cases.json').read_text())['cases'];flat=[v for c in cases for v in c];code='declare global shop_expected: array<int> = ['+','.join(map(str,flat))+'];\ndeclare struct ShopOracle() { fn value(t: int,i: int) -> int { return shop_expected[t*9+i] else 0; } }\n';(ROOT/'src/inventory/shop-fixture.generated.pbs').write_text(code)
append('src/inventory/main.pbs','''
import { CaveShop } from @zelda1:stages/cave_shop;
import { WorldFlags } from @zelda1:world;
declare global shop_oracle: ShopOracle = new ShopOracle();
declare service ShopInventoryCheck {
fn slot(i: int,v: int) -> void { inventory_slots[i]=v; }
fn finish_money() -> void { for i: int from 0 until 520 { Inventory.tick_money(i); } }
fn verify(t: int) -> bool {
Inventory.reset(); WorldFlags.reset(); CaveShop.enter();
let item=shop_oracle.value(t,0); let slot=shop_oracle.value(t,1); let price=shop_oracle.value(t,2); let old=shop_oracle.value(t,3); let money=shop_oracle.value(t,4); let pending=shop_oracle.value(t,5); let allowed=shop_oracle.value(t,6); let expected_value=shop_oracle.value(t,7); let queued=shop_oracle.value(t,8);
inventory_slots[slot]=old; inventory_slots[22]=money; inventory_slots[39]=pending;
let x=if item==28 { 88 } else if item==25 { 120 } else { 152 };
let acquired=CaveShop.purchase(x,152);
if (if acquired>=0 { 1 } else { 0 })!=allowed || (inventory_slots[slot] else 0)!=expected_value || (inventory_slots[39] else 0)!=queued || (inventory_slots[22] else 0)!=money { return false; }
if WorldFlags.room_item_taken(102)!=(allowed==1) { return false; }
if allowed==1 { let again=CaveShop.purchase(x,152); if again>=0 || (inventory_slots[39] else 0)!=price { return false; } }
return true;
}
}
''')
source='''import { Loot } from @zelda1:loot;
import { SaveStore } from @zelda1:save;
import { Inventory, ShopInventoryCheck } from @zelda1:inventory;
import { WorldFlags } from @zelda1:world;
import { Stage, ShopStageCheck } from @zelda1:stage;
import { CaveShop } from @zelda1:stages/cave_shop;
import { Link, ShopLinkCheck } from @zelda1:link;
import { Scene } from @zelda1:scene;
import { Hud } from @zelda1:hud;
import { InventoryScreen } from @zelda1:screens/inventory;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global tick: int=0;
declare global failed: bool=false;
declare global loaded: bool=false;
declare global menu_open: bool=false;
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
[Init] fn init() -> void { Inventory.reset(); WorldFlags.reset(); Stage.reset(); ShopStageCheck.select(11); Link.start_game(); CaveShop.enter(); Scene.reset(); }
[Frame] fn frame() -> void {
SaveStore.poll(); Loot.tick();
if tick==0 && SaveStore.available() { loaded=SaveStore.load(); ShopStageCheck.select(11); CaveShop.enter(); }
if loaded {
if tick==0 { if Inventory.read_slot(22)!=60 || Inventory.read_slot(39)!=60 { failed=true; } let again=CaveShop.purchase(152,152); if again>=0 { failed=true; } }
Inventory.tick_money(tick);
if tick>=120 && (Inventory.read_slot(22)!=0 || Inventory.read_slot(39)!=0) { failed=true; }
if Inventory.read_slot(31)!=1 || Inventory.read_slot(23)!=1 || Inventory.read_slot(4)!=1 || WorldFlags.read_slot(102)!=17 { failed=true; }
} else {
Inventory.tick_money(tick);
if tick<150 { let okay=ShopInventoryCheck.verify(tick); if !okay { failed=true; } }
if tick==150 { Inventory.reset(); WorldFlags.reset(); WorldFlags.leave_room(102,4,1); ShopInventoryCheck.slot(22,160); ShopStageCheck.select(3); ShopLinkCheck.place(112,77,8); Scene.reset(); }
if tick>=151 && tick<=250 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==250 { if Stage.id()!=11 || Link.x()!=112 || Link.y()!=173 || Stage.room_id()!=102 || Stage.hud_glyph()!=21 { failed=true; } }
if tick==251 { InventoryScreen.open(); for i: int from 0 until 25 { let done=InventoryScreen.advance(false,0); } menu_open=true; }
if tick==252 { menu_open=false; InventoryScreen.reset(); Scene.reset(); ShopInventoryCheck.slot(22,159); let acquired=CaveShop.purchase(88,152); if acquired>=0 || Inventory.read_slot(31)!=0 || Inventory.read_slot(39)!=0 { failed=true; } }
if tick==253 { ShopInventoryCheck.slot(22,160); ShopLinkCheck.place(88,157,8); }
if tick>=253 && tick<=380 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==253 { if ShopLinkCheck.lifted()!=28 || ShopLinkCheck.timer()!=127 || Inventory.read_slot(31)!=1 || Inventory.read_slot(39)!=160 || WorldFlags.read_slot(102)!=17 { failed=true; } }
if tick==380 { ShopInventoryCheck.finish_money(); if Inventory.read_slot(22)!=0 || Inventory.read_slot(39)!=0 || ShopLinkCheck.timer()!=0 { failed=true; } }
if tick==382 { ShopLinkCheck.place(112,221,4); }
if tick>=382 && tick<=450 { Link.prepare_stage(tick==382,false); Link.update(false,false,false,false,false); }
if tick==450 { if Stage.id()!=3 || Link.x()!=112 || Link.y()!=77 { failed=true; } }
if tick==451 { ShopLinkCheck.place(112,85,4); Link.prepare_stage(false,false); }
if tick==452 { ShopLinkCheck.place(112,77,8); }
if tick>=452 && tick<=550 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==550 { if Stage.id()!=11 { failed=true; } }
if tick==551 { ShopInventoryCheck.slot(22,100); ShopLinkCheck.place(120,157,8); }
if tick>=551 && tick<=620 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==551 { if ShopLinkCheck.lifted()!=25 || Inventory.read_slot(23)!=1 || Inventory.read_slot(39)!=100 { failed=true; } }
if tick==621 { ShopInventoryCheck.finish_money(); CaveShop.enter(); ShopInventoryCheck.slot(22,60); ShopLinkCheck.place(152,157,8); }
if tick>=621 && tick<=750 { Link.prepare_stage(false,false); Link.update(false,false,false,false,false); }
if tick==621 { if ShopLinkCheck.lifted()!=6 || Inventory.read_slot(4)!=1 || Inventory.read_slot(39)!=60 { failed=true; } }
if tick==750 { ShopInventoryCheck.finish_money(); if Inventory.read_slot(31)!=1 || Inventory.read_slot(23)!=1 || Inventory.read_slot(4)!=1 || Inventory.read_slot(22)!=0 || Inventory.read_slot(39)!=0 { failed=true; } }
if tick==621 { SaveStore.begin(); }
}
Scene.set_hud_offset(0);
if menu_open { InventoryScreen.draw(); } else if Scene.ensure_ready() { Hud.draw(); Stage.draw_objects(); Link.draw(); }
Scene.draw_frame();
let color=if failed { Color.rgb(255,0,0) } else { Color.rgb(0,255,0) }; Gfx.fill_rect(0,0,1,1,color);
if SaveStore.last_state()==2 { Gfx.fill_rect(1,0,1,1,Color.rgb(0,255,0)); }
if loaded { Gfx.fill_rect(2,0,1,1,Color.rgb(0,0,255)); }
tick+=1;
}
''';(ROOT/'src/main.pbs').write_text(source)
meta={'captures':[{'name':n,'frame':t+1} for t,n in [(149,'oracle-complete'),(150,'entrance'),(183,'door-mid'),(250,'available'),(251,'menu'),(252,'insufficient'),(253,'lift-shield'),(254,'blink-shown'),(255,'blink-even'),(256,'blink-hidden'),(317,'keeper-gone'),(380,'debit-complete'),(450,'exit'),(550,'restock'),(551,'lift-key'),(621,'lift-candle'),(750,'all-purchases'),(755,'save-submitted')]],'final_frame':756}
(ROOT/'extracted/shop/fixture-cases.json').write_text(json.dumps(meta,indent=2)+'\n');print('Shop fixture:',len(cases),'native oracle cases; gameplay/persistence frames 756')
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Isolated native cases, complete Game frame, restock and durable-save fixture."""
import json,sys
from extract_graphics import ROOT
out=ROOT/'.tmp/supply-shop-fixture';out.mkdir(exist_ok=True);marker=out/'installed'
files=['src/main.pbs','src/game/main.pbs','src/game/mod.barrel','src/stage/main.pbs','src/stage/mod.barrel','src/link/main.pbs','src/link/mod.barrel','src/inventory/main.pbs','src/inventory/mod.barrel']
if sys.argv[-1]=='restore':
assert marker.exists()
for f in files:(ROOT/f).write_bytes((out/f.replace('/','__')).read_bytes())
(ROOT/'src/inventory/supply-fixture.generated.pbs').unlink();marker.unlink();raise SystemExit
assert not marker.exists()
for f in files:(out/f.replace('/','__')).write_bytes((ROOT/f).read_bytes())
marker.write_text('owned fixture')
def append(f,s):
p=ROOT/f;p.write_text(p.read_text()+s)
append('src/game/mod.barrel','pub service SupplyGameCheck;\n');append('src/game/main.pbs','\ndeclare service SupplyGameCheck { fn play() -> void { game.mode=5; game.timer=0; } }\n')
append('src/stage/mod.barrel','pub service SupplyStageCheck;\n');append('src/stage/main.pbs','\ndeclare service SupplyStageCheck { fn select(id: int) -> void { flow.reset(); flow.active=id; } }\n')
append('src/link/mod.barrel','pub service SupplyLinkCheck;\n');append('src/link/main.pbs','\ndeclare service SupplyLinkCheck { fn place(x: int,y: int,d: int) -> void { controller.place_for_stage(state,x,y,d,true); vitals.reset(); } fn timer() -> int { return state.lift_counter; } fn item() -> int { return state.lift_item; } }\n')
cases=json.loads((ROOT/'extracted/supply_shop/native-cases.json').read_text())['cases'];flat=[v for c in cases for v in c]
(ROOT/'src/inventory/supply-fixture.generated.pbs').write_text('declare global supply_cases: array<int> = ['+','.join(map(str,flat))+'];\ndeclare struct SupplyOracle() { fn get(t: int,i: int) -> int { return supply_cases[t*10+i] else 0; } }\n')
old_cases=json.loads((ROOT/'extracted/shop/native-cases.json').read_text())['cases']
append('src/inventory/supply-fixture.generated.pbs','declare global old_shop_cases: array<int> = ['+','.join(map(str,[v for c in old_cases for v in c]))+'];\ndeclare struct OldShopOracle() { fn get(t: int,i: int) -> int { return old_shop_cases[t*9+i] else 0; } }\n')
append('src/inventory/mod.barrel','pub service SupplyInventoryCheck;\nmod struct SupplyOracle;\nmod struct OldShopOracle;\n')
append('src/inventory/main.pbs','''
import { CaveSupplyShop } from @zelda1:stages/cave_supply_shop;
import { CaveShop } from @zelda1:stages/cave_shop;
import { WorldFlags } from @zelda1:world;
declare global supply_oracle: SupplyOracle = new SupplyOracle();
declare global old_shop_oracle: OldShopOracle = new OldShopOracle();
declare service SupplyInventoryCheck {
fn slot(i: int,v: int) -> void { inventory_slots[i]=v; }
fn finish_money() -> void { for i: int from 0 until 520 { Inventory.tick_money(i); } }
fn verify_old(t: int) -> bool {
Inventory.reset(); WorldFlags.reset(); CaveShop.enter();
let item=old_shop_oracle.get(t,0); let slot=old_shop_oracle.get(t,1);
inventory_slots[slot]=old_shop_oracle.get(t,3); inventory_slots[22]=old_shop_oracle.get(t,4); inventory_slots[39]=old_shop_oracle.get(t,5);
let x=if item==28 { 88 } else if item==25 { 120 } else { 152 }; let acquired=CaveShop.purchase(x,152); let allowed=old_shop_oracle.get(t,6);
if (if acquired>=0 { 1 } else { 0 })!=allowed || (inventory_slots[slot] else 0)!=old_shop_oracle.get(t,7) || (inventory_slots[39] else 0)!=old_shop_oracle.get(t,8) { return false; }
return WorldFlags.room_item_taken(102)==(allowed==1);
}
fn verify(t: int) -> bool {
Inventory.reset(); WorldFlags.reset(); CaveSupplyShop.enter();
let item=supply_oracle.get(t,0); let slot=supply_oracle.get(t,1); let price=supply_oracle.get(t,2);
inventory_slots[slot]=supply_oracle.get(t,3); inventory_slots[37]=supply_oracle.get(t,4); inventory_slots[22]=supply_oracle.get(t,5); inventory_slots[39]=supply_oracle.get(t,6);
let x=if item==28 { 88 } else if item==0 { 120 } else { 152 }; let acquired=CaveSupplyShop.purchase(x,152); let allowed=supply_oracle.get(t,7);
if (if acquired>=0 { 1 } else { 0 })!=allowed || (inventory_slots[slot] else 0)!=supply_oracle.get(t,8) || (inventory_slots[39] else 0)!=supply_oracle.get(t,9) || (inventory_slots[22] else 0)!=supply_oracle.get(t,5) { return false; }
if WorldFlags.room_item_taken(68)!=(allowed==1) { return false; }
if allowed==1 { let again=CaveSupplyShop.purchase(x,152); if again>=0 || (inventory_slots[39] else 0)!=price { return false; } }
return true;
}
}
''')
source='''import { Game, SupplyGameCheck } from @zelda1:game;
import { SaveStore } from @zelda1:save;
import { Inventory, SupplyInventoryCheck } from @zelda1:inventory;
import { WorldFlags } from @zelda1:world;
import { Stage, SupplyStageCheck } from @zelda1:stage;
import { Link, SupplyLinkCheck } from @zelda1:link;
import { CaveSupplyShop } from @zelda1:stages/cave_supply_shop;
import { Scene } from @zelda1:scene;
import { InventoryScreen } from @zelda1:screens/inventory;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global tick: int=0;
declare global failed: bool=false;
declare global loaded: bool=false;
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
[Init] fn init() -> void { Game.boot(); }
[Frame] fn frame() -> void {
if tick==0 && SaveStore.available() {
loaded=SaveStore.load(); SupplyGameCheck.play(); SupplyStageCheck.select(16); SupplyLinkCheck.place(112,173,8); CaveSupplyShop.enter(); Scene.reset();
}
if loaded {
if Inventory.read_slot(1)!=8 || Inventory.read_slot(2)!=1 || Inventory.read_slot(31)!=1 || WorldFlags.read_slot(68)!=17 { failed=true; }
if tick==0 && (Inventory.read_slot(22)!=130 || Inventory.read_slot(39)!=130) { failed=true; }
if tick>=270 && (Inventory.read_slot(22)!=0 || Inventory.read_slot(39)!=0) { failed=true; }
Game.frame();
} else {
if tick<400 { if !SupplyInventoryCheck.verify(tick) { failed=true; } if tick<150 { if !SupplyInventoryCheck.verify_old(tick) { failed=true; } } }
if tick==400 {
Game.boot(); SupplyGameCheck.play(); SupplyStageCheck.select(15); SupplyLinkCheck.place(64,77,8);
WorldFlags.leave_room(68,4,1); SupplyInventoryCheck.slot(22,20); Scene.reset();
}
if tick==502 && (Stage.id()!=16 || Link.x()!=112 || Link.y()!=173) { failed=true; }
if tick==575 && !InventoryScreen.active() { failed=true; }
if tick==639 && InventoryScreen.opened() { failed=true; }
if tick==640 { SupplyLinkCheck.place(120,157,8); }
if tick>=400 { Game.frame(); }
if tick==640 && (Inventory.read_slot(1)!=4 || Inventory.read_slot(39)!=20 || SupplyLinkCheck.timer()!=0 || WorldFlags.read_slot(68)!=17) { failed=true; }
if tick==641 && Inventory.read_slot(1)!=4 { failed=true; }
if tick==642 { SupplyLinkCheck.place(112,221,4); }
if tick==714 && (Stage.id()!=15 || Link.x()!=64) { failed=true; }
if tick==715 { SupplyLinkCheck.place(64,85,4); Link.prepare_stage(false,false); }
if tick==716 { SupplyLinkCheck.place(64,77,8); }
if tick==815 && Stage.id()!=16 { failed=true; }
if tick==816 { SupplyInventoryCheck.finish_money(); SupplyInventoryCheck.slot(22,20); SupplyLinkCheck.place(120,157,8); }
if tick==817 && Inventory.read_slot(1)!=8 { failed=true; }
if tick==818 { CaveSupplyShop.enter(); let acquired=CaveSupplyShop.purchase(152,152); if acquired>=0 { failed=true; } }
if tick==860 { SupplyInventoryCheck.finish_money(); SupplyInventoryCheck.slot(22,80); CaveSupplyShop.enter(); SupplyLinkCheck.place(152,157,8); }
if tick==861 && (Inventory.read_slot(2)!=1 || SupplyLinkCheck.item()!=8 || SupplyLinkCheck.timer()!=127) { failed=true; }
if tick==1041 { SupplyInventoryCheck.finish_money(); SupplyInventoryCheck.slot(22,130); CaveSupplyShop.enter(); SupplyLinkCheck.place(88,157,8); }
if tick==1042 {
if Inventory.read_slot(31)!=1 || Inventory.read_slot(1)!=8 || Inventory.read_slot(2)!=1 || Inventory.read_slot(39)!=130 || SupplyLinkCheck.timer()!=127 { failed=true; }
SaveStore.begin();
}
if tick==1310 { SupplyInventoryCheck.finish_money(); if Inventory.read_slot(22)!=0 || Inventory.read_slot(39)!=0 { failed=true; } }
}
let color=if failed { Color.rgb(255,0,0) } else { Color.rgb(0,255,0) }; Gfx.fill_rect(0,0,1,1,color);
if SaveStore.last_state()==2 { Gfx.fill_rect(1,0,1,1,Color.rgb(0,255,0)); }
if loaded { Gfx.fill_rect(2,0,1,1,Color.rgb(0,0,255)); }
tick+=1;
}
'''
(ROOT/'src/main.pbs').write_text(source)
report={'cases':[{'name':n,'frame':f} for n,f in [('oracle',400),('available',503),('menu-full',576),('menu-closed',640),('buy-bombs',641),('bomb-duplicate',642),('exit',715),('restock',816),('buy-bombs-again',818),('pending-blocks',820),('lift-arrows',862),('lift-shield',1043),('durable-save',1320)]],'final_frame':1320,'input':'Start press logical frames504-505; release to576; press577-578; release to643; Down frames644-645 then release. New reload needs 300 frames.'}
(out/'cases.json').write_text(json.dumps(report,indent=2)+'\n');print('Supply fixture installed; 400 native cases and Game frame integration')
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Install an isolated native-oracle fixture, or restore production."""
import json,sys
from pathlib import Path
from extract_graphics import ROOT
out=ROOT/'.tmp/zora-fixture';out.mkdir(exist_ok=True);marker=out/'installed';files=['src/main.pbs','src/stage/main.pbs','src/stage/mod.barrel','src/enemies/zora/main.pbs','src/enemies/zora/mod.barrel','src/link/main.pbs','src/link/mod.barrel','src/inventory/main.pbs','src/inventory/mod.barrel']
if sys.argv[-1]=='restore':
assert marker.exists()
for f in files:(ROOT/f).write_bytes((out/f.replace('/','__')).read_bytes())
(ROOT/'src/enemies/zora/fixture.generated.pbs').unlink();marker.unlink();raise SystemExit
assert not marker.exists()
for f in files:(out/f.replace('/','__')).write_bytes((ROOT/f).read_bytes())
marker.write_text('owned fixture')
def append(f,s):
p=ROOT/f;p.write_text(p.read_text()+s)
append('src/stage/mod.barrel','pub service ZoraStageCheck;\n');append('src/stage/main.pbs','\ndeclare service ZoraStageCheck { fn enter(id: int) -> void { flow.reset(); flow.active=id; } }\n')
append('src/link/mod.barrel','pub service ZoraLinkCheck;\n');append('src/link/main.pbs','\ndeclare service ZoraLinkCheck { fn place(x: int,y: int,facing: int) -> void { state.x=x; state.y=y; state.facing=facing; vitals.reset(); } fn blast(x: int,y: int) -> void { bomb0.x=x; bomb0.y=y; bomb0.phase=3; } fn clear_blast() -> void { bomb0.reset(); } }\n')
append('src/inventory/mod.barrel','pub service ZoraInventoryCheck;\n');append('src/inventory/main.pbs','\ndeclare service ZoraInventoryCheck { fn slot(i: int,v: int) -> void { inventory_slots[i]=v; } }\n')
append('src/enemies/zora/mod.barrel','pub service ZoraCheck;\nmod struct ZoraOracle;\n')
cases=json.loads((ROOT/'extracted/zora/native-cases.json').read_text());rows=[r for c in cases['cycles'] for r in c['frames']];length=len(cases['cycles'][0]['frames']);vals=[v for r in rows for v in r[:7]]
code='declare global zora_expected: array<int> = ['+','.join(map(str,vals))+'];\ndeclare struct ZoraOracle() { fn value(t: int,i: int) -> int { return zora_expected[t*7+i] else -1; } }\n';(ROOT/'src/enemies/zora/fixture.generated.pbs').write_text(code)
code='''
import { ZoraLinkCheck } from @zelda1:link;
import { ZoraInventoryCheck } from @zelda1:inventory;
import { Inventory } from @zelda1:inventory;
import { ZoraStageCheck } from @zelda1:stage;
import { Scene } from @zelda1:scene;
declare global oracle: ZoraOracle = new ZoraOracle();
declare global random_test: array<int> = [0,85,0,0,0,0,0,0,0,0,0,0,0];
declare service ZoraCheck {
fn tick(t: int) -> bool {
if t==0 || t==LENGTH { actor.reset(); actor.appear(80,if t==0 { 125 } else { 157 }); actor.life=2; }
if t<CYCLES {
let fire=actor.update(data); if fire { Zora.shoot(0); }
let e0=oracle.value(t,0); let e1=oracle.value(t,1); let e2=oracle.value(t,2); let e3=oracle.value(t,3); let e4=oracle.value(t,4); let e5=oracle.value(t,5); let e6=oracle.value(t,6);
if actor.state!=e0 || actor.timer!=e1 || actor.anim_timer!=e2 || actor.frame!=e3 || (actor.state>=2 && actor.state<=5 && actor.facing_frame!=e4) || (if fire { 1 } else { 0 })!=e5 || (if actor.life==0 { 1 } else { 0 })!=e6 { return false; }
}
if t==CYCLES { Zora.reset(); Zora.update(random_test,11); if actor.life!=0 { return false; } }
if t==CYCLES+1 { Zora.update(random_test,0); if actor.life!=1 || actor.x!=80 || actor.y!=93 { return false; } }
if t==CYCLES+2 { actor.state=1; actor.timer=12; actor.life=2; ZoraLinkCheck.blast(actor.x,actor.y); let fired=actor.update(data); if actor.hp!=2 { return false; } }
if t==CYCLES+3 { actor.state=2; let fired=actor.update(data); ZoraLinkCheck.clear_blast(); if actor.life!=3 { return false; } }
if t>=CYCLES+4 && t<CYCLES+22 { Zora.update(random_test,0); }
if t==CYCLES+22 { if actor.life!=4 { return false; } Zora.update(random_test,0); if actor.life!=4 { return false; } }
if t==CYCLES+23 { Zora.reset(); Zora.update(random_test,0); if actor.life!=1 { return false; } }
if t==CYCLES+24 { actor.life=2; actor.state=3; actor.timer=90; ZoraInventoryCheck.slot(21,1); let fired=actor.update(data); if actor.timer!=89 || actor.state!=3 { return false; } ZoraInventoryCheck.slot(21,0); }
if t==CYCLES+25 { Zora.reset(); ZoraStageCheck.enter(2); Zora.update(random_test,0); if actor.life!=0 { return false; } }
if t==CYCLES+26 { ZoraStageCheck.enter(4); Zora.reset(); ZoraLinkCheck.place(120,141,2); Inventory.reset(); f0.launch(84,141,data); f0.timer=0; f0.qx=0; f0.qy=0; f0.x=124; f0.y=141; f0.dx=1; f0.dy=1; f0.update(data); if Inventory.read_slot(25)!=127 || f0.active { return false; } }
if t==CYCLES+27 { Inventory.reset(); ZoraLinkCheck.place(120,141,2); ZoraInventoryCheck.slot(31,1); f0.active=true; f0.timer=0; f0.x=124; f0.y=141; f0.update(data); if Inventory.read_slot(25)!=255 || f0.active { return false; } }
if t==CYCLES+28 { Zora.reset(); actor.appear(80,125); actor.life=2; actor.state=2; actor.timer=10; f0.launch(80,125,data); }
if t==CYCLES+29 { f0.update(data); }
if t>=CYCLES+30 && t<CYCLES+50 { f0.update(data); }
return true;
}
fn draw() -> void { Zora.draw(); }
}
'''.replace('LENGTH',str(length)).replace('CYCLES',str(len(rows)))
append('src/enemies/zora/main.pbs',code)
source='''import { SaveStore } from @zelda1:save;
import { Zora, ZoraCheck } from @zelda1:enemies/zora;
import { Stage, ZoraStageCheck } from @zelda1:stage;
import { WorldFlags } from @zelda1:world;
import { Inventory } from @zelda1:inventory;
import { Link } from @zelda1:link;
import { Scene } from @zelda1:scene;
import { Hud } from @zelda1:hud;
import { Gfx } from @sdk:gfx;
import { Color } from @core:color;
declare global tick: int=0;
declare global failed: bool=false;
[MemcardBoot] fn memcard_boot(context: long) -> int { return SaveStore.boot(context); }
[Init] fn init() -> void { Inventory.reset(); WorldFlags.reset(); Stage.reset(); ZoraStageCheck.enter(4); Link.start_game(); Scene.reset(); }
[Frame] fn frame() -> void {
let okay=ZoraCheck.tick(tick); if !okay { failed=true; }
if Scene.ensure_ready() { Hud.draw(); ZoraCheck.draw(); Scene.draw_frame(); }
let color=if failed { Color.rgb(255,0,0) } else { Color.rgb(0,255,0) }; Gfx.fill_rect(0,0,1,1,color); tick+=1;
}
''';(ROOT/'src/main.pbs').write_text(source)
captures=[{'name':f'cycle-{t}','frame':t+1} for t in [0,31,32,47,49,81,97,length-1,length,len(rows)-1]]+[{'name':f'integration-{i}','frame':len(rows)+i+1} for i in [0,1,2,3,22,23,24,25,26,27,28,29,30,49]]
captures += [{'name':'back-exposed','frame':227},{'name':'back-fire','frame':244}]
captures.sort(key=lambda c:c['frame'])
(ROOT/'extracted/zora/fixture-cases.json').write_text(json.dumps({'captures':captures,'final_frame':len(rows)+50},indent=2)+'\n');print('Native cycles:',len(rows),'fixture frames:',len(rows)+50)
+86
View File
@@ -0,0 +1,86 @@
"""Bounded execution of this ROM's object descriptor routine (not a NES emulator)."""
from extract_graphics import ROOT, ROM_SHA256
import hashlib
P=(ROOT/'.tmp/zelda-1.nes').read_bytes()[16:]
assert hashlib.sha256((ROOT/'.tmp/zelda-1.nes').read_bytes()).hexdigest()==ROM_SHA256
DELTA=0x790
ATTR=P.index(bytes([255]+[0]*6+[5]*4+[129]*4+[1]*2),7*16384)
ENTRY=P.index(bytes.fromhex('a001d002a000840cbc4f03c8'))+DELTA
HALF=P.index(bytes.fromhex('c6074c'),ENTRY-DELTA,0x7770)
STOP=int.from_bytes(P[HALF+3:HALF+5],'little')
def descriptor(object_type,frame=0,mirrored=False,flip_x=False,item_slot=None,attribute=0,object_attribute=None):
"""Execute through DrawObjectWithType until Anim_WriteSpritePair begins."""
m=bytearray(65536);m[0x6c90:0x7f00]=P[0x6500:0x7770]
x=1;y=0;a=frame;pc=ENTRY+(0 if mirrored else 4);sp=253;c=z=n=False
assert item_slot is not None or object_type in (7,8,9,0x11,0x53,0x55,0x77,0x78,0x7b),'Only verified Octorok, Zora, rock, fireball and item descriptor paths are covered'
m[0x34f+x]=object_type;m[0x4bf+x]=P[ATTR+object_type] if object_attribute is None else object_attribute
m[0x0f]=int(flip_x)
if item_slot is not None:
pc=P.index(bytes.fromhex('8608a9018507a908850ab9'),0x6500,0x7770)+DELTA
x=15;y=item_slot;m[12]=frame;m[4]=m[5]=attribute
def nz(v):
nonlocal z,n
v &=255;z=v==0;n=v>=128;return v
def byte():
nonlocal pc
v=m[pc];pc+=1;return v
def word():return byte()|byte()<<8
def push(v):
nonlocal sp
m[256+sp]=v&255;sp=(sp-1)&255
def pop():
nonlocal sp
sp=(sp+1)&255;return m[256+sp]
for _ in range(500):
if pc==STOP:
return {'tiles':[m[2],m[3]],'attributes':[m[4],m[5]],'sides':m[7]+1,'x_separation':m[10],'animation_index':m[14],'frame':m[13]}
at=pc;op=byte()
if op==0xa9:a=nz(byte())
elif op==0xa0:y=nz(byte())
elif op==0xa4:y=nz(m[byte()])
elif op==0xac:y=nz(m[word()])
elif op==0xbc:y=nz(m[word()+x])
elif op==0xa5:a=nz(m[byte()])
elif op==0xad:a=nz(m[word()])
elif op==0xb9:a=nz(m[word()+y])
elif op==0xbd:a=nz(m[word()+x])
elif op==0x85:m[byte()]=a
elif op==0x84:m[byte()]=y
elif op==0x86:m[byte()]=x
elif op==0x8d:m[word()]=a
elif op==0xc8:y=nz(y+1)
elif op in (0xc6,0xe6):
q=byte();m[q]=nz(m[q]+(1 if op==0xe6 else -1))
elif op==0xa8:y=nz(a)
elif op==0x18:c=False
elif op in (0x69,0x65):
v=byte();v=m[v] if op==0x65 else v;v=a+v+c;c=v>255;a=nz(v)
elif op in (0xe0,0xc9):
v=byte();lhs=x if op==0xe0 else a;c=lhs>=v;nz(lhs-v)
elif op==0x29:a=nz(a&byte())
elif op==0x49:a=nz(a^byte())
elif op in (0xf0,0xd0,0xb0,0x90):
d=byte();take={0xf0:z,0xd0:not z,0xb0:c,0x90:not c}[op]
if take:pc+=d if d<128 else d-256
elif op==0x4c:pc=word()
elif op==0x20:
target=word();push((pc-1)>>8);push(pc-1);pc=target
elif op==0x60:pc=(pop()|pop()<<8)+1
elif op==0x48:push(a)
elif op==0x68:a=nz(pop())
else:raise AssertionError(f'Unsupported opcode ${op:02x} at ${at:04x}')
raise AssertionError('Descriptor routine did not reach sprite emission')
def item(slot,frame=0,attribute=0,flip_x=False):
return descriptor(0,frame,False,flip_x,slot,attribute)
def octorok(direction,phase):
offset={'left':0,'right':0,'up':1,'down':2}[direction]
return descriptor(7,phase*3+offset,direction in ('up','down'),direction=='right')
if __name__=='__main__':
for phase in range(2):
for direction in ('left','up','down','right'):print(direction,phase,octorok(direction,phase))
print('rock',descriptor(0x53))
+24
View File
@@ -0,0 +1,24 @@
"""Verified ROM metadata shared by generation and independent route checks."""
from nes_object_graphics import P
from extract_start_room import extract
from extract_graphics import ROOT
import json
def metadata(room):
attrs=[P[99328+i*128+room] for i in range(6)];c=attrs[2];list_id=(c&63)+(64 if attrs[3]&128 else 0);count=P[103204+(c>>6)]
if 0x32<=list_id<0x62:count=1
code=P.index(bytes.fromhex('a50238e9620aa8b9'),81920,98304);directory=81920+int.from_bytes(P[code+8:code+10],'little')-0x8000
offset=None
if list_id>=0x62:
ptr=int.from_bytes(P[directory+(list_id-0x62)*2:directory+(list_id-0x62)*2+2],'little');offset=81920+ptr-0x8000;foes=list(P[offset:offset+count])
else:foes=[list_id]*count if list_id else []
return {'attrs':attrs,'list_id':list_id,'list_directory_prg':directory,'object_list_prg':offset,'foes':foes,'edge_spawns':bool(attrs[5]&8),'zora':bool(attrs[0]&8)}
def manifest():return json.loads((ROOT/'tools/overworld_manifest.json').read_text())['rooms']
def step_edge(cell):
if cell%16==0:cell=(cell+16)&255
elif cell%16==15:cell=(cell-16)&255
if cell&240==224:cell=(cell+1)&255
elif cell&240==64:cell=(cell-1)&255
return cell
+122
View File
@@ -0,0 +1,122 @@
{
"schema_version": 1,
"rooms": [
{
"stage": 0,
"room": 119,
"name": "start",
"module": "overworld_start",
"service": "OverworldStart",
"data_type": "StartRoomData",
"managed": false
},
{
"stage": 2,
"room": 103,
"name": "north",
"module": "overworld_north",
"service": "OverworldNorth",
"data_type": "Room67Data",
"managed": true
},
{
"stage": 3,
"room": 102,
"name": "northwest",
"module": "overworld_northwest",
"service": "OverworldNorthwest",
"data_type": "Room66Data",
"managed": true
},
{
"stage": 4,
"room": 101,
"name": "northwest_2",
"module": "overworld_northwest_2",
"service": "OverworldNorthwest2",
"data_type": "Room65Data",
"managed": true
},
{
"stage": 5,
"room": 100,
"name": "bomb_field",
"module": "overworld_bomb_field",
"service": "OverworldBombField",
"data_type": "Room64Data",
"managed": true
},
{
"stage": 6,
"room": 87,
"name": "north_upper",
"module": "overworld_north_upper",
"service": "OverworldNorthUpper",
"data_type": "Room57Data",
"managed": true
},
{
"stage": 7,
"room": 88,
"name": "northeast_upper",
"module": "overworld_northeast_upper",
"service": "OverworldNortheastUpper",
"data_type": "Room58Data",
"managed": true
},
{
"stage": 8,
"room": 104,
"name": "east",
"module": "overworld_east",
"service": "OverworldEast",
"data_type": "Room68Data",
"managed": true
},
{
"stage": 9,
"room": 120,
"name": "start_east",
"module": "overworld_start_east",
"service": "OverworldStartEast",
"data_type": "Room78Data",
"managed": true
},
{
"stage": 12,
"room": 86,
"name": "west_1",
"module": "overworld_west_1",
"service": "OverworldWest1",
"data_type": "Room56Data",
"managed": true
},
{
"stage": 13,
"room": 85,
"name": "west_2",
"module": "overworld_west_2",
"service": "OverworldWest2",
"data_type": "Room55Data",
"managed": true
},
{
"stage": 14,
"room": 84,
"name": "west_3",
"module": "overworld_west_3",
"service": "OverworldWest3",
"data_type": "Room54Data",
"managed": true
},
{
"stage": 15,
"room": 68,
"name": "shop_west",
"module": "overworld_shop_west",
"service": "OverworldShopWest",
"data_type": "Room44Data",
"managed": true
}
]
}
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Publish native room $66 by extending existing banks, without extra scenes."""
import json,hashlib
from PIL import Image
from extract_graphics import ROOT
from extract_start_room import extract,write_json,RGB
from nes_object_graphics import P,descriptor
def prepare():
rooms=[extract(i,name) for i,name in [(0x66,'northwest'),(0x65,'northwest_2'),(0x64,'bomb_field')]];d=rooms[0];north=json.loads((ROOT/'extracted/overworld/north/room.json').read_text());start=json.loads((ROOT/'extracted/overworld/start/room.json').read_text())
assert d['room_attributes'][2]==0x69
count=P[103168+36+(0x69>>6)];assert count==4
# Type $09 uses the same native frame graphics as $07, with blue palette.
for frame in range(6):
assert descriptor(9,frame)['tiles']==descriptor(7,frame)['tiles']
folder=ROOT/'assets/tilesets/north';doc=json.loads((folder/'asset.json').read_text());glyph={a['artifact_id']:a['index'] for a in doc['artifacts']}
for r,name in zip(rooms,['northwest','northwest_2','bomb_field']):
for used in r['used_tiles']:
t=used['tile_id'];pal=used['palette_id'];assert pal in (2,3)
key=f'tile_{t:02x}_p{pal}'
if key not in glyph:
path=folder/(key+'.png');im=Image.open(ROOT/f'extracted/overworld/{name}/tiles/{key}.png');
if pal==3:
original=[(*RGB[c],255) for c in d['background_nes_palettes'][3]];canonical=[(*RGB[c],255) for c in d['background_nes_palettes'][2]];lut=dict(zip(original,canonical));im=im.convert('RGBA');im.putdata([lut[c] for c in im.getdata()])
im.save(path);idx=len(doc['artifacts']);glyph[key]=idx;doc['artifacts'].append({'file':path.name,'index':idx,'artifact_id':key,'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
doc['output']['pipeline']['palettes']=[doc['output']['pipeline']['palettes'][0],{'index':1,'palette':{'rgba8888':[int.from_bytes(bytes((*RGB[c],255)),'big',signed=True) for c in d['background_nes_palettes'][3]]}}];write_json(folder/'asset.json',doc)
blank={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False}
def room(r):return [{'active':True,'glyph_id':glyph[f"tile_{r['tilemap'][y][x]:02x}_p{r['palette_map'][y][x]}"],'palette_id':int(r['palette_map'][y][x]==3),'flip_x':False,'flip_y':False} for y in range(8,30) for x in range(32)]
n=room(north);w=room(d);s=room(start);western=[room(r) for r in rooms]
def publish(root,width,tiles):
f=ROOT/f'assets/scenes/{root}/scene-bank.pack-request.json';v=json.loads(f.read_text());v['layers'][0].update(width=width,height=len(tiles)//width,tiles=tiles);write_json(f,v)
publish('overworld_north',32,[dict(blank)]*256+n+sum(([dict(blank)]*256+r for r in western),[]))
# Existing vertical strip occupies y=0..415. Horizontal strip starts at y=416.
vertical=[dict(blank)]*256+n+s;tiles=[]
for row in range(52):tiles+=vertical[row*32:(row+1)*32]+[dict(blank)]*32
for index,left in enumerate(western):
right=n if index==0 else western[index-1]
tiles += [dict(blank)]*(8*64)
for row in range(22):tiles+=left[row*32:(row+1)*32]+right[row*32:(row+1)*32]
publish('overworld_north_scroll',64,tiles)
src=(ROOT/'src/stages/overworld_north/room.generated.pbs').read_text();a=src.index('[');b=src.index('];',a);values=[v for row in d['tilemap'][8:] for v in row];src=src[:a]+'['+','.join(map(str,values))+src[b:]
f=ROOT/'src/stages/overworld_northwest';f.mkdir(parents=True,exist_ok=True);(f/'room.generated.pbs').write_text(src)
(f/'mod.barrel').write_text('pub service OverworldNorthwest;\nmod struct RoomData;\n')
(f/'main.pbs').write_text('import { Composer } from @sdk:composer;\ndeclare global room: RoomData = new RoomData();\ndeclare service OverworldNorthwest {\n fn render() -> bool { let status=Composer.bind_scene(13); return status==0; }\n fn tile_at(column: int, row: int) -> int { return room.tile_at(column,row); }\n fn contains_player(x: int,y: int) -> bool { return room.contains_player(x,y); }\n}\n')
hud=ROOT/'assets/ui/hud';v=json.loads((hud/'asset.json').read_text());im=Image.open(hud/'hud-north-marker.png').convert('RGBA');green=(56,184,0,255);gray=(124,124,124,255);pixels=[(x,y) for y in range(32) for x in range(32) if im.getpixel((x,y))==green]
for x,y in pixels:im.putpixel((x,y),gray)
for x,y in pixels:im.putpixel((x-2,y),green)
path=hud/'hud-northwest-marker.png';im.save(path);v['artifacts']=[a for a in v['artifacts'] if a['index']!=21]+[{'file':path.name,'index':21,'artifact_id':'hud-northwest-marker','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}];write_json(hud/'asset.json',v)
hp=P.index(bytes.fromhex('0643253112248114224200a98f20003f'),7*16384)
assert P[hp+4]&15==2
# Full object list IDs include the high bit in attribute D.
directory=83775;route=[]
for r in rooms:
c=r['room_attributes'][2];attr_d=r['room_attributes'][3];list_id=(c&63)+(64 if attr_d&128 else 0);nfoes=P[103204+(c>>6)]
ptr=int.from_bytes(P[directory+(list_id-98)*2:directory+(list_id-98)*2+2],'little');off=81920+ptr-32768;types=list(P[off:off+nfoes]);route.append({'room':r['room_id'],'list_id':list_id,'object_list_prg':off,'types':types})
assert [r['types'] for r in route]==[[8,7,8,7],[8,7,8,7],[8,9,8,9,8]]
write_json(ROOT/'extracted/overworld/northwest/bomb-route.json',{'route':route,'from_start':['north','west','west','west'],'hp_pairs_prg':hp,'web_source':'https://www.zeldadungeon.net/the-legend-of-zelda-walkthrough/the-gathering/','bomb_item_id':0,'bomb_quantity':4})
# Individual stages own their collision data, while their scenes share one atlas.
for index,(r,name) in enumerate(zip(rooms,['overworld_northwest','overworld_northwest_2','overworld_bomb_field'])):
folder=ROOT/'src/stages'/name;folder.mkdir(exist_ok=True,parents=True);service=['OverworldNorthwest','OverworldNorthwest2','OverworldBombField'][index]
source=(ROOT/'src/stages/overworld_north/room.generated.pbs').read_text();a=source.index('[');b=source.index('];',a);values=[v for row in r['tilemap'][8:] for v in row];source=source[:a]+'['+','.join(map(str,values))+source[b:];(folder/'room.generated.pbs').write_text(source)
(folder/'mod.barrel').write_text(f'pub service {service};\nmod struct RoomData;\n');(folder/'main.pbs').write_text(f'import {{ Composer }} from @sdk:composer;\ndeclare global room: RoomData = new RoomData();\ndeclare service {service} {{\n fn render() -> bool {{ let status=Composer.bind_scene(13); return status==0; }}\n fn tile_at(column: int,row: int) -> int {{ return room.tile_at(column,row); }}\n fn contains_player(x: int,y: int) -> bool {{ return room.contains_player(x,y); }}\n}}\n')
# HUD marker for each native column.
base=Image.open(hud/'hud-north-marker.png').convert('RGBA')
for index in range(3):
im=base.copy()
for x,y in pixels:im.putpixel((x,y),gray)
for x,y in pixels:im.putpixel((x-2*(index+1),y),green)
path=hud/f'hud-west-{index}.png';im.save(path);idx=21+index;v['artifacts']=[a for a in v['artifacts'] if a['index']!=idx]+[{'file':path.name,'index':idx,'artifact_id':path.stem,'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}]
write_json(hud/'asset.json',v)
print('Published rooms $66/$65/$64 and native mixed lists; existing scenes reused')
if __name__=='__main__':
prepare()
from prepare_overworld import prepare as prepare_world
prepare_world()
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env python3
"""Build the starting cave and doorway masks from verified NES bytes."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT, ROM_SHA256, decode
from extract_start_room import RGB, write_json
TILES_UUID = 'dd893d16-0bd4-4569-a0c5-dcd67d504f39'
SCENE_UUID = 'd692272f-18be-4db1-be6f-70b40145ae2c'
DOOR_UUID = '5a67354c-de25-4c39-adfd-d0adac83f464'
def prepare():
rom = (ROOT / '.tmp/zelda-1.nes').read_bytes()
assert hashlib.sha256(rom).hexdigest() == ROM_SHA256
prg = rom[16:]
source = json.loads((ROOT / 'extracted/overworld/start/room.json').read_text())
primary_offset, secondary_offset = source['primary_table_prg_offset'], source['secondary_table_prg_offset']
primary = prg[primary_offset:primary_offset + 56]
secondary = prg[secondary_offset:secondary_offset + 64]
directory_offset = source['column_directory_prg_offset']
directory = [int.from_bytes(prg[directory_offset + i*2:directory_offset + i*2+2], 'little') for i in range(16)]
# Confirm the room-specific coordinates and cave selector used by StageFlow.
attrs77 = [prg[99328+i*128+0x77] for i in range(6)]
assert attrs77[0] & 0xF0 == 64 and ((attrs77[5] & 7)*16+77) == 77
assert attrs77[1] & 0xFC == 0x40
assert source['tilemap'][11][8] == 0x24
assert prg[99328+0x44] & 3 == 3 and prg[99328+128+0x44] & 3 == 2
layout_offset = prg.index(bytes.fromhex('00009595959595c2c295959595950000'))
descriptors = prg[layout_offset:layout_offset+16]
tilemap = [[36]*32 for _ in range(30)]
palette_map = [[0]*32 for _ in range(30)]
columns = []
for x, descriptor in enumerate(descriptors):
cursor = 5*16384 + directory[descriptor >> 4] - 0x8000
remaining = descriptor & 15
while True:
if prg[cursor] & 128:
if remaining == 0: break
remaining -= 1
cursor += 1
start, squares = cursor, []
while len(squares) < 11:
value = prg[cursor]
squares.extend([value & 63] * (2 if value & 64 else 1))
cursor += 1
assert len(squares) == 11
columns.append({'descriptor': descriptor, 'prg_offset': start, 'squares': squares})
for y, index in enumerate(squares):
base = primary[index]
values = list(secondary[index*4:index*4+4]) if index < 16 else list(range(base,base+4))
# InitModeB uses room $44's outer palette 3, inner palette 2.
palette = 2 if 2 <= x <= 13 and 2 <= y <= 8 else 3
for n,(dx,dy) in enumerate(((0,0),(0,1),(1,0),(1,1))):
tilemap[8+y*2+dy][x*2+dx] = values[n]
palette_map[8+y*2+dy][x*2+dx] = palette
bg = bytearray(4096)
bg[:1792] = prg[34687:34687+1792]
bg[1792:0xF20] = prg[51515:51515+2080]
bg[0xF20:] = prg[36479:36479+224]
sprites = bytearray(4096)
sprites[:1792] = prg[32895:32895+1792]
sprites[0x8E0:0x1000] = prg[53595:53595+1824]
palettes = [list(prg[103171+i*4:103175+i*4]) for i in range(8)]
cave_palette_offset = prg.index(bytes.fromhex('3f08080f3000120f070f17'))
palettes[2] = list(prg[cave_palette_offset+3:cave_palette_offset+7])
palettes[3] = list(prg[cave_palette_offset+7:cave_palette_offset+11])
rgb = dict(RGB)
rgb.update({7:(136,20,0),0x29:(56,184,0),0x02:(0,0,188),0x22:(104,136,252),
0x0C:(0,64,88),0x1C:(0,136,136),0x2C:(88,248,216)})
def tile_image(tile, palette, transparent=False, patterns=bg):
result = Image.new('RGBA',(8,8))
result.putdata([(*rgb[palettes[palette][v]],255) if v or not transparent else (0,0,0,0)
for v in decode(patterns[tile*16:(tile+1)*16])])
return result
terrain = Image.new('RGBA',(256,240),(0,0,0,255))
for y in range(8,30):
for x in range(32): terrain.paste(tile_image(tilemap[y][x],palette_map[y][x]),(x*8,y*8))
canvas = terrain.copy()
fires = terrain.copy()
# Independent reference composites; gameplay renders these objects as sprites.
animations = prg.index(bytes.fromhex('00080b0f13175c60'))
heap = prg.index(bytes.fromhex('0004080c101014185c9e44ce'))
attr_signature = bytes.fromhex('00000000000000000200000101010102')
attr_heap = prg.index(attr_signature, heap)
decorations = []
overlays = []
for obj,x in ((0x6A,120),(0x40,72),(0x40,168)):
index = prg[animations+obj+1]
tile = prg[heap+index]
palette = 4 + (prg[attr_heap+index] & 3)
left = Image.new('RGBA',(8,16))
left.paste(tile_image(tile,palette,True,sprites),(0,0))
left.paste(tile_image(tile+1,palette,True,sprites),(0,8))
canvas.alpha_composite(left,(x,129))
canvas.alpha_composite(left.transpose(Image.Transpose.FLIP_LEFT_RIGHT),(x+8,129))
if obj == 0x40:
fires.alpha_composite(left,(x,129))
fires.alpha_composite(left.transpose(Image.Transpose.FLIP_LEFT_RIGHT),(x+8,129))
whole=Image.new('RGBA',(16,16));whole.alpha_composite(left,(0,0));whole.alpha_composite(left.transpose(Image.Transpose.FLIP_LEFT_RIGHT),(8,0))
overlays.append((1 if obj==0x6A else 0,x,129,whole))
decorations.append({'object_type':obj,'tile':tile,'palette':palette,'x':x,'y':129})
person_only = canvas.copy()
canvas.alpha_composite(tile_image(32,4,True,sprites),(124,153))
canvas.alpha_composite(tile_image(33,4,True,sprites),(124,161))
sword=Image.new('RGBA',(8,16));sword.alpha_composite(tile_image(32,4,True,sprites),(0,0));sword.alpha_composite(tile_image(33,4,True,sprites),(0,8));overlays.append((2,124,153,sword))
text_offset = 16384 + int.from_bytes(prg[16384:16386],'little') - 0x8000
cursor, address, text_tiles = text_offset, 0x21A4, []
while True:
encoded = prg[cursor];cursor+=1
tile = encoded & 63
if tile != 0x25:
px,py = ((address-0x2000)%32)*8,((address-0x2000)//32)*8
canvas.paste(tile_image(tile,2),(px,py))
overlays.append((2,px,py,tile_image(tile,2,True)))
text_tiles.append({'tile':tile,'x':px,'y':py})
address += 1
control = encoded & 0xC0
if control == 0xC0: break
if control: address = 0x21C4 if control == 0x80 else 0x21E4
out = ROOT / 'extracted/cave/start';out.mkdir(parents=True,exist_ok=True)
terrain.save(out/'terrain.png');canvas.save(out/'room.png')
person_only.save(out/'room_taken_person.png');fires.save(out/'room_taken.png')
canvas.resize((768,720),Image.Resampling.NEAREST).save(out/'room@3x.png')
registry_path=ROOT/'assets/.prometeu/index.json';registry=json.loads(registry_path.read_text())
def register(root,uuid):
matches=[a for a in registry['assets'] if a['root']==root or a['asset_uuid']==uuid]
if matches:
assert len(matches)==1 and matches[0]['asset_uuid']==uuid and matches[0]['root']==root
matches[0]['included_in_build']=True
return matches[0]['asset_id']
index=registry['next_asset_id'];registry['next_asset_id']+=1
registry['assets'].append({'asset_id':index,'asset_uuid':uuid,'root':root,'included_in_build':True})
return index
tiles_id=register('tilesets/cave_start',TILES_UUID)
register('scenes/cave_start',SCENE_UUID)
register('characters/link_door',DOOR_UUID)
bank=ROOT/'assets/tilesets/cave_start';bank.mkdir(parents=True,exist_ok=True)
colors=sorted(set(canvas.getdata())|{(0,0,0,0)});assert len(colors)<=16
artifacts=[];glyphs={};variant_tiles=[]
for visual in (canvas, person_only, fires, terrain):
map_tiles=[]
for y in range(30):
for x in range(32):
crop=visual.crop((x*8,y*8,x*8+8,y*8+8));key=crop.tobytes()
if key not in glyphs:
index=len(glyphs);glyphs[key]=index
path=bank/f'tile_{index:03d}.png';crop.save(path)
artifacts.append({'file':path.name,'index':index,'artifact_id':f'cave-tile-{index:03d}',
'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
map_tiles.append({'active':y>=8,'glyph_id':glyphs[key],'palette_id':0,'flip_x':False,'flip_y':False})
variant_tiles.append(map_tiles)
placements=[]
for kind,x,y,image in overlays:
for yy in range(0,image.height,8):
for xx in range(0,image.width,8):
crop=image.crop((xx,yy,xx+8,yy+8));key=crop.tobytes()
if not crop.getbbox():continue
if key not in glyphs:
index=len(glyphs);glyphs[key]=index;path=bank/f'tile_{index:03d}.png';crop.save(path)
artifacts.append({'file':path.name,'index':index,'artifact_id':f'cave-tile-{index:03d}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
placements.append((kind,x+xx,y+yy,glyphs[key]))
module=ROOT/'src/stages/cave_start'
flat=[v for row in placements for v in row]
code='// Generated independent sprites: kind (fire/person/ware+text), x, y, glyph.\n'
code+='import { Scene } from @zelda1:scene;\n'
code+='declare global cave_parts: array<int> = ['+','.join(map(str,flat))+'];\n'
code+='declare struct CaveArt() {\n fn draw(variant: int,offset: int) -> void {\n'
code+=f' for i: int from 0 until {len(placements)} {{\n'
code+=' let kind=cave_parts[i*4] else 0;\n'
code+=' if kind==0 || (kind==1 && variant!=2) || (kind==2 && variant==0) {\n'
code+=' let x=cave_parts[i*4+1] else 0; let y=cave_parts[i*4+2] else 0; let glyph=cave_parts[i*4+3] else 0;\n'
code+=' Scene.emit_sprite(glyph,0,x,y+offset,3,0);\n }\n }\n }\n}\n'
(module/'art.generated.pbs').write_text(code)
write_json(out/'composition.json',{'bank':3,'terrain_scene':1,'parts':[{'kind':k,'x':x,'y':y,'glyph':g} for k,x,y,g in placements],'legacy_scenes_reserved':[2,3]})
write_json(bank/'asset.json',{'schema_version':1,'asset_uuid':TILES_UUID,'name':'Starting cave NES',
'type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},
'pipeline':{'palettes':[{'index':0,'palette':{'rgba8888':[int.from_bytes(bytes(c),'big',signed=True) for c in colors]}}]}},
'preload':{'enabled':True},'artifacts':artifacts})
write_json(bank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'})
def layer(active,w,h,values):return {'active':active,'glyph_asset_id':tiles_id,'tile_size':8,
'parallax_factor_x':1.0,'parallax_factor_y':1.0,'width':w,'height':h,'tiles':values}
empty={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False}
scene_variants=[('cave_start',SCENE_UUID),
('cave_taken_person','787f596f-a349-43f2-9e1a-028331ed5bea'),
('cave_taken','edc6ec17-3963-47c4-afab-d390541f4a37')]
for i,(name,uuid) in enumerate(scene_variants):
register('scenes/'+name,uuid)
scene=ROOT/'assets/scenes'/name;scene.mkdir(parents=True,exist_ok=True)
write_json(scene/'asset.json',{'schema_version':1,'asset_uuid':uuid,'name':name,
'type':'scene_bank','output':{'format':'SCENE/tilemap_v1','codec':'NONE','pipeline':{}},'preload':{'enabled':True}})
write_json(scene/'scene-bank.pack-request.json',{'schema_version':1,'format':'SCENE/tilemap_v1','version':1,
'layers':[layer(True,32,30,variant_tiles[3])]+[layer(False,1,1,[empty]) for _ in range(3)]})
# Terrain collision stays independent from dynamic text and actors.
values=[tile for row in tilemap[8:] for tile in row]
module=ROOT/'src/stages/cave_start';module.mkdir(parents=True,exist_ok=True)
lines=['// Generated from RoomLayoutOWCave0; decorative art is not collision data.',
'declare global terrain: array<int> = [']
lines += [' '+', '.join(map(str,values[r*32:(r+1)*32]))+(',' if r<21 else '') for r in range(22)]
lines += ['];','','declare struct CaveData() {',' fn tile_at(column: int, row: int) -> int {',
' if column < 0 || column >= 32 || row < 0 || row >= 22 { return 255; }',
' return terrain[row * 32 + column] else 255;',' }','}','']
(module/'room.generated.pbs').write_text('\n'.join(lines))
# Reproduce NES behind-background sprite priority at this doorway, using
# original pattern indices (not RGB: a black background pixel may be solid).
door=ROOT/'assets/characters/link_door';door.mkdir(parents=True,exist_ok=True)
door_artifacts=[]
for step in range(17):
for direction in ('up','down'):
for phase in range(2):
image=Image.open(ROOT/f'assets/characters/link/walk_{direction}_{phase}.png').convert('RGBA')
for yy in range(16):
for xx in range(16):
sx,sy=64+xx,77+step+3+yy
tile=source['tilemap'][sy//8][sx//8]
index=decode(bg[tile*16:(tile+1)*16])[(sy%8)*8+sx%8]
if index: image.putpixel((xx,yy),(0,0,0,0))
index=len(door_artifacts);path=door/f'door_{step:02d}_{direction}_{phase}.png';image.save(path)
door_artifacts.append({'file':path.name,'index':index,'artifact_id':f'door-{step}-{direction}-{phase}',
'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
link=json.loads((ROOT/'assets/characters/link/asset.json').read_text())
write_json(door/'asset.json',{'schema_version':1,'asset_uuid':DOOR_UUID,'name':'Link NES doorway priority',
'type':'glyph_bank','output':link['output'],'preload':{'enabled':True},'artifacts':door_artifacts})
write_json(door/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'sprites'})
if json.loads(registry_path.read_text())!=registry: write_json(registry_path,registry)
write_json(out/'room.json',{'rom_sha256':ROM_SHA256,'layout_prg_offset':layout_offset,'columns':columns,
'tilemap':tilemap,'palette_map':palette_map,'nes_palettes':palettes,'palette_prg_offset':cave_palette_offset,
'decorations':decorations,'text_prg_offset':text_offset,'text_tiles':text_tiles,
'entrance':{'overworld_x':64,'overworld_y':77,'cave_x':112,'cave_y':221,'walk_pixels':48},
'scope':'Terrain scene plus independent sprites for fires, person, sword and text. Runtime inventory and room flags control visibility without scene rebinding.'})
print(f'Cave: {len(artifacts)} glyphs, {len(colors)} colors; doorway: {len(door_artifacts)} masked Link poses')
from prepare_real_secret import prepare as prepare_secret
prepare_secret()
if __name__=='__main__':prepare()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Extract drop tables, native item descriptors and combat/HUD patterns."""
import hashlib,json,uuid
from PIL import Image
from extract_graphics import ROOT,decode
from extract_start_room import RGB,write_json
from nes_object_graphics import P,item
def prepare():
out=ROOT/'extracted/combat';out.mkdir(exist_ok=True,parents=True)
group_sig=bytes.fromhex('5d14151b1c1d1707080e040f2321220d1013282a2716090a030112060b2430')
groups=P.index(group_sig);rate=groups+len(group_sig)+4;assert list(P[rate:rate+4])==[80,152,104,104]
table=list(P[rate+4:rate+44]);assert table[:10]==[34,24,34,24,35,24,34,34,24,24]
no_drop=list(P[groups:groups+7]);sets=[list(P[groups+7:groups+13]),list(P[groups+13:groups+22]),list(P[groups+22:groups+31])]
spawn_sig=bytes.fromhex('55b578987a9a6cac8d8263a3759577975abaa375b59687997abaac6355957688795a9a6c')
spawn_at=P.index(spawn_sig,5*16384,6*16384)
spawn_lines=['// Native spawn spots for right, left, down, up entries.', 'declare global spawn_spots: array<int> = ['+', '.join(map(str,P[spawn_at:spawn_at+36]))+'];', 'declare struct SpawnData() {',' fn cell(direction: int, cycle: int) -> int {',' let row=if direction==1 { 0 } else if direction==2 { 1 } else if direction==4 { 2 } else { 3 };',' return spawn_spots[row*9+cycle] else 0;',' }','}','']
(ROOT/'src/enemies/octorok/spawns.generated.pbs').write_text('\n'.join(spawn_lines))
# Explicitly derive group membership and cycle results from ROM bytes.
lines=['// Generated native monster drop data.','declare global drop_table: array<int> = ['+', '.join(map(str,table))+'];','declare global drop_rates: array<int> = ['+', '.join(map(str,P[rate:rate+4]))+'];','declare struct DropData() {',' fn group(monster: int) -> int {',' if '+' || '.join(f'monster=={n}' for n in no_drop)+' { return -1; }']
for i,values in enumerate(sets):lines.append(' if '+' || '.join(f'monster=={n}' for n in values)+f' {{ return {i}; }}')
lines+=[' return 3;',' }',' fn item(group: int, cycle: int) -> int { return drop_table[group*10+cycle] else -1; }',' fn rate(group: int) -> int { return drop_rates[group] else 0; }','}','']
(ROOT/'src/loot/data.generated.pbs').write_text('\n'.join(lines))
patterns=bytearray(8192)
for offset,length,address in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[address:address+length]=P[offset:offset+length]
rows=[list(P[103187+i*4:103191+i*4]) for i in range(4)]+[list(P[103171:103175])]
rgb=dict(RGB);rgb.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
colors=[[(0,0,0,0) if i==0 and row_id<4 else (*rgb[c],255) for i,c in enumerate(row)] for row_id,row in enumerate(rows)]
specs={0:item(1),15:item(28),24:item(22),34:item(25),35:item(20),135:item(20,1),200:item(34),201:item(34,1),202:item(35,2)}
assert specs[34]['tiles'][0]==243 and specs[201]['tiles']==[130,132]
keys=set()
for info in specs.values():
for tile in info['tiles'][:info['sides']]:keys.update(((tile&1)*256+(tile&254),(tile&1)*256+(tile&254)+1))
digit_codes=list(range(10))+[33,36];keys.update(256+n for n in digit_codes)
root='characters/combat';folder=ROOT/'assets'/root;folder.mkdir(exist_ok=True,parents=True);u=str(uuid.uuid5(uuid.NAMESPACE_URL,'zelda1/'+root));artifacts=[];glyphs={}
for key in sorted(keys):
im=Image.new('RGBA',(8,8));im.putdata([colors[0][v] for v in decode(patterns[key*16:(key+1)*16])]);path=folder/f'ppu_{key*16:04x}.png';im.save(path);index=len(artifacts);glyphs[key]=index
artifacts.append({'file':path.name,'index':index,'artifact_id':f'combat-ppu-{key*16:04x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
write_json(folder/'asset.json',{'schema_version':1,'asset_uuid':u,'name':'NES combat and counter patterns','type':'glyph_bank','preload':{'enabled':True},'output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':[int.from_bytes(bytes(c),'big',signed=True) for c in row]}} for i,row in enumerate(colors)]}},'artifacts':artifacts})
write_json(folder/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'sprites'})
registry_path=ROOT/'assets/.prometeu/index.json';reg=json.loads(registry_path.read_text());matches=[a for a in reg['assets'] if a['root']==root]
if matches:assert len(matches)==1 and matches[0]['asset_uuid']==u
else:
n=reg['next_asset_id'];reg['next_asset_id']+=1;reg['assets'].append({'asset_id':n,'asset_uuid':u,'root':root,'included_in_build':True});write_json(registry_path,reg)
top=[glyphs.get((t&1)*256+(t&254),0) for t in range(256)];bottom=[glyphs.get((t&1)*256+(t&254)+1,0) for t in range(256)]
lines=['// Generated PPU mappings; odd 8x16 sprite IDs select the background table.', 'declare global combat_top: array<int> = ['+', '.join(map(str,top))+'];','declare global combat_bottom: array<int> = ['+', '.join(map(str,bottom))+'];','declare struct CombatData() {',' fn top(tile: int) -> int { return combat_top[tile] else 0; }',' fn bottom(tile: int) -> int { return combat_bottom[tile] else 0; }',' fn digit(code: int) -> int {']
for code in digit_codes:lines.append(f' if code=={code} {{ return {glyphs[256+code]}; }}')
lines+=[' return 0;',' }',' fn drop_tile(item: int, phase: int) -> int {']
for n in (0,15,24,34):lines.append(f' if item=={n} {{ return {specs[n]["tiles"][0]}; }}')
lines+=[' return if phase==0 { 80 } else { 82 };',' }','}',''];(ROOT/'src/combat_graphics/data.generated.pbs').write_text('\n'.join(lines))
write_json(out/'rom-data.json',{'rom_sha256':hashlib.sha256((ROOT/'.tmp/zelda-1.nes').read_bytes()).hexdigest(),'drop_tables_prg':groups,'rates':list(P[rate:rate+4]),'groups':sets,'no_drop':no_drop,'items':table,'item_descriptors':specs,'glyph_keys':glyphs,'native_palettes':rows,'bounce_table_prg':P.index(bytes.fromhex('01fffe02ffff')),'scope':'Native red Octorok combat, consumable drops, sword beam and HUD counters; no audio.'})
print('Published combat bank:',len(artifacts),'8x8 patterns; native drop tables and item descriptors')
if __name__=='__main__':prepare()
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Decode the verified ROM's title PPU records, palettes and OAM; publish UI."""
import hashlib,json
from PIL import Image
from extract_graphics import ROOT,ROM_SHA256,decode
from extract_start_room import write_json,RGB
TITLE_UUID='73c07dc9-f2a6-48ce-a221-2949ad10be36'
MENU_UUID='8a4283fe-9532-46db-868b-852ca9914730'
def prepare():
rom=(ROOT/'.tmp/zelda-1.nes').read_bytes();assert hashlib.sha256(rom).hexdigest()==ROM_SHA256
p=rom[16:];rgb=dict(RGB);rgb.update({0x10:(188,188,188),0x08:(80,48,0),0x28:(248,216,120),0x3b:(160,252,224),0x22:(104,136,252),0x07:(136,20,0)})
registry_path=ROOT/'assets/.prometeu/index.json';registry=json.loads(registry_path.read_text())
def register(root,uuid):
matches=[a for a in registry['assets'] if a['asset_uuid']==uuid or a['root']==root]
if matches:
assert len(matches)==1 and matches[0]['asset_uuid']==uuid and matches[0]['root']==root
matches[0]['included_in_build']=True;return matches[0]['asset_id']
n=registry['next_asset_id'];registry['next_asset_id']+=1;registry['assets'].append({'asset_id':n,'asset_uuid':uuid,'root':root,'included_in_build':True});return n
def rgba(colors):return [int.from_bytes(bytes(c),'big',signed=True) for c in colors]
# Use authoritative pointers in this ROM, not stale .dat offsets in bins.xml.
table=next(i for i in range(105830,107300) if p[i+6:i+8]==bytes.fromhex('1468') and p[i+12:i+14]==bytes.fromhex('1c68'))
def record_offset(index):
ptr=int.from_bytes(p[table+index*2:table+index*2+2],'little')
assert 0x8000<=ptr<0xc000
return 6*16384+ptr-0x8000
def transfer(offset,memory):
start=offset;records=[]
while p[offset]<128:
address=p[offset]*256+p[offset+1];control=p[offset+2];count=control&63 or 64;stride=32 if control&128 else 1;offset+=3
assert 0x2000<=address<0x4000
for i in range(count):memory[address+i*stride]=p[offset if control&64 else offset+i]
records.append({'address':address,'control':control,'count':count})
offset+=1 if control&64 else count
return {'prg_offset':start,'length':offset+1-start,'records':records}
memory=bytearray(0x4000);memory[0x2000:0x2800]=bytes([36])*0x800
title_record=transfer(record_offset(8),memory)
palette_offset=p.index(bytes.fromhex('3f0020360f00103617270f36081a2836303b22'))
palettes=[list(p[palette_offset+3+i*4:palette_offset+7+i*4]) for i in range(8)]
glow=[0x27,0x37,0x37,0x27,0x17,0x07,0x07,0x17]
runtime_colors=[]
for i,row in enumerate(palettes):runtime_colors.append([(*rgb[c],255) if j or i<4 else (0,0,0,0) for j,c in enumerate(row)])
for value in glow:runtime_colors.append([(*rgb[c],255) for c in (0x36,0x17,value,0x0f)])
canonical=runtime_colors[0]
patterns=bytearray(8192)
for offset,length,address in [(32895,1792,0),(34687,1792,0x1000),(36479,224,0x1f20),(19892,2304,0x700),(22196,2080,0x1700)]:patterns[address:address+length]=p[offset:offset+length]
oam_offset=p.index(bytes.fromhex('77cac2d077ccc2c877ca8228'))
oam=[list(p[oam_offset+i:oam_offset+i+4]) for i in range(0,112,4)]
title_id=register('ui/title',TITLE_UUID)
bank=ROOT/'assets/ui/title';bank.mkdir(parents=True,exist_ok=True)
artifacts=[];glyphs={}
used_bg=sorted({memory[0x2000+y*32+x] for y in range(30) for x in range(32)})
used_sp={tile+dy for y,tile,attr,x in oam for dy in (0,1)}
for base in (0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae,0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe,0xc0,0xc2,0xc4,0xc6,0xc8):used_sp.update((base,base+1))
# Include the shared heart cursor, rendered with the native menu sprite row.
used_sp.update((0xf3,0xf2))
for base,used,label in [(4096,used_bg,'bg'),(0,sorted(used_sp),'sp')]:
for tile in used:
image=Image.new('RGBA',(8,8));image.putdata([canonical[v] for v in decode(patterns[base+tile*16:base+(tile+1)*16])])
path=bank/f'{label}_{tile:02x}.png';image.save(path);index=len(artifacts);glyphs[(label,tile)]=index
artifacts.append({'file':path.name,'index':index,'artifact_id':f'title-{label}-{tile:02x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
write_json(bank/'asset.json',{'schema_version':1,'asset_uuid':TITLE_UUID,'name':'NES title patterns','type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':rgba(row)}} for i,row in enumerate(runtime_colors)]}},'preload':{'enabled':True},'artifacts':artifacts})
write_json(bank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'})
def palette_at(x,y):
attr=memory[0x23c0+(y//4)*8+x//4];return (attr>>(((y%4)//2)*4+((x%4)//2)*2))&3
def publish_scene(root,uuid,asset,tiles):
register(root,uuid);path=ROOT/'assets'/root;path.mkdir(parents=True,exist_ok=True)
write_json(path/'asset.json',{'schema_version':1,'asset_uuid':uuid,'name':root.split('/')[-1],'type':'scene_bank','output':{'format':'SCENE/tilemap_v1','codec':'NONE','pipeline':{}},'preload':{'enabled':True}})
empty={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False}
def layer(active,w,h,t):return {'active':active,'glyph_asset_id':asset,'tile_size':8,'parallax_factor_x':1.0,'parallax_factor_y':1.0,'width':w,'height':h,'tiles':t}
write_json(path/'scene-bank.pack-request.json',{'schema_version':1,'format':'SCENE/tilemap_v1','version':1,'layers':[layer(True,32,30,tiles)]+[layer(False,1,1,[empty]) for _ in range(3)]})
for cycle in (0,1,4,5):
tiles=[]
for y in range(30):
for x in range(32):
palette=palette_at(x,y);palette=8+cycle if palette==1 else palette
tiles.append({'active':True,'glyph_id':glyphs[('bg',memory[0x2000+y*32+x])],'palette_id':palette,'flip_x':False,'flip_y':False})
publish_scene(f'scenes/title_{cycle}',f'be91004{cycle}-f99b-44e3-bd00-48850f27f000',title_id,tiles)
# Generate the full title image independently with its actual NES palettes/OAM.
out=ROOT/'extracted/game_flow';out.mkdir(exist_ok=True,parents=True)
canvas=Image.new('RGBA',(256,240))
for y in range(30):
for x in range(32):
tile=memory[0x2000+y*32+x];row=runtime_colors[palette_at(x,y)];im=Image.new('RGBA',(8,8));im.putdata([row[v] for v in decode(patterns[4096+tile*16:4096+(tile+1)*16])]);canvas.paste(im,(x*8,y*8))
def sprite(canvas,tile,x,y,attrs):
im=Image.new('RGBA',(8,16));row=runtime_colors[4+(attrs&3)]
im.putdata([row[v] for n in (tile,tile+1) for v in decode(patterns[n*16:(n+1)*16])])
if attrs&64:im=im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if attrs&128:im=im.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
canvas.alpha_composite(im,(x,y+1))
initial_sprites=list(oam)
for y in (184,202,218):
offset=0 if y<185 else 8 if y<194 else 16
initial_sprites += [[y,tile+offset,0,x] for x,tile in zip((80,88,96,104),(0xb2,0xb4,0xb6,0xb8))]
initial_sprites += [[168,tile,0,x] for x,tile in zip((80,88,96,104),(0xa2,0xa4,0xa6,0xa8))]
# Lower OAM index wins over later sprites; compose back-to-front.
for y,tile,attrs,x in reversed(initial_sprites):sprite(canvas,tile,x,y,attrs)
canvas.save(out/'title.png');canvas.resize((768,720),Image.Resampling.NEAREST).save(out/'title@3x.png')
# Native post-death text, limited to implemented CONTINUE / RETRY (SAVE omitted).
menu_memory=bytearray(0x4000);menu_memory[0x2000:0x23c0]=bytes([36])*960
menu_record=transfer(record_offset(2),menu_memory)
label_codes=[bytes([12,24,23,29,18,23,30,14]),bytes([27,14,29,27,34])]
label_positions=[menu_memory.find(code,0x2000,0x23c0) for code in label_codes]
assert all(address>=0x2000 for address in label_positions)
# Preserve native label positions, but do not display SAVE or its caution box
# while storage is outside this iteration.
clean_menu=bytearray(0x4000);clean_menu[0x2000:0x23c0]=bytes([36])*960
for address,code in zip(label_positions,label_codes):clean_menu[address:address+len(code)]=code
menu_memory=clean_menu
selection_modes=p.index(bytes.fromhex('f30250273747030d00'),5*16384,6*16384)+6
cursor_data=list(p[selection_modes-6:selection_modes])
menu_rows_y=[(address-0x2000)//32 for address in label_positions]
assert p[selection_modes+74:selection_modes+78]==bytes.fromhex('a9408529')
menu_palette_offset=p.index(bytes.fromhex('3f00200f3000120f1627360f0c1c2c0f121c2c0f2927070f2227070f2627070f152730ff'))
menu_rows=[list(p[menu_palette_offset+3+i*4:menu_palette_offset+7+i*4]) for i in range(8)]
menu_rgb=dict(rgb);menu_rgb.update({0x0c:(0,64,88),0x1c:(0,136,136),0x2c:(88,248,216),0x12:(0,88,248),0x29:(56,184,0),0x26:(248,120,88),0x15:(164,0,164)})
menu_colors=[[(0,0,0,0) if j==0 and i>=4 else (*menu_rgb[c],255) for j,c in enumerate(row)] for i,row in enumerate(menu_rows)]
mbank=ROOT/'assets/ui/continue';mbank.mkdir(parents=True,exist_ok=True);menu_id=register('ui/continue',MENU_UUID);marts=[];mids={}
for label,base,used in [('bg',4096,sorted(set(menu_memory[0x2000:0x23c0]))),('sp',4096,[0xf3])]:
for tile in used:
image=Image.new('RGBA',(8,8));pattern_tile = tile - 1 if label == 'sp' else tile
image.putdata([menu_colors[0][v] for v in decode(patterns[base+pattern_tile*16:base+(pattern_tile+1)*16])]);path=mbank/f'{label}_{tile:02x}.png';image.save(path);n=len(marts);mids[(label,tile)]=n
marts.append({'file':path.name,'index':n,'artifact_id':f'continue-{label}-{tile:02x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
write_json(mbank/'asset.json',{'schema_version':1,'asset_uuid':MENU_UUID,'name':'NES continue menu','type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':rgba(row)}} for i,row in enumerate(menu_colors)]}},'preload':{'enabled':True},'artifacts':marts})
write_json(mbank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'})
for flash in (0,1,2):
tiles=[]
for y in range(30):
for x in range(32):tiles.append({'active':True,'glyph_id':mids[('bg',menu_memory[0x2000+y*32+x])],'palette_id':1 if (flash==1 and y==menu_rows_y[0]) or (flash==2 and y==menu_rows_y[1]) else 0,'flip_x':False,'flip_y':False})
publish_scene(f'scenes/continue_{flash}',f'be92000{flash}-f99b-44e3-bd00-48850f27f000',menu_id,tiles)
menu_module=ROOT/'src/screens/continue_menu';menu_module.mkdir(parents=True,exist_ok=True)
menu_lines=['// Generated from the verified ROM menu labels and cursor table.',
'declare struct ContinueData() {',
f' fn cursor_glyph() -> int {{ return {mids[("sp",0xf3)]}; }}',
f' fn cursor_x() -> int {{ return {cursor_data[2]}; }}',
' fn cursor_y(selection: int) -> int {',
f' return if selection == 0 {{ {cursor_data[3]+1} }} else {{ {cursor_data[5]+1} }};',
' }','}','']
(menu_module/'graphics.generated.pbs').write_text('\n'.join(menu_lines))
# Generate native glyph map and OAM records for runtime authoring.
module=ROOT/'src/screens/title';module.mkdir(parents=True,exist_ok=True)
mapping=[glyphs.get(('sp',tile),0) for tile in range(256)]
lines=['// Generated from verified title OAM and CHR patterns.',
'declare global title_glyphs: array<int> = ['+', '.join(map(str,mapping))+'];',
'declare struct TitleData() {',' fn glyph(tile: int) -> int {',
' if tile < 0 || tile >= 256 { return 0; }',
' return title_glyphs[tile] else 0;',' }',
' fn draw_pair(tile: int, x: int, y: int, attr: int, priority: int) -> void {',
' let flip_x = attr % 128 >= 64;',
' let flip_y = attr >= 128;',
' let top = if flip_y { tile + 1 } else { tile };',
' let bottom = if flip_y { tile } else { tile + 1 };',
' Scene.emit_ui_sprite(this.glyph(top), 4 + attr % 4, x, y + 1, 8, flip_x, flip_y, priority);',
' Scene.emit_ui_sprite(this.glyph(bottom), 4 + attr % 4, x, y + 9, 8, flip_x, flip_y, priority);',
' }',' fn draw_static() -> void {']
lines += [f' this.draw_pair({tile}, {x}, {y}, {attrs}, {128-i});' for i,(y,tile,attrs,x) in enumerate(oam)]
lines += [' }','}','']
(module/'graphics.generated.pbs').write_text('import { Scene } from @zelda1:scene;\n\n'+'\n'.join(lines))
write_json(out/'rom-data.json',{'rom_sha256':ROM_SHA256,'transfer_directory_prg_offset':table,'title':title_record,'palette_prg_offset':palette_offset,'native_palettes':palettes,'glow_colors':glow,'oam_prg_offset':oam_offset,'initial_oam':oam,'sprite_glyphs':{str(t):g for (l,t),g in glyphs.items() if l=='sp'},'continue':menu_record,'continue_cursor_glyph':mids[('sp',0xf3)],'continue_label_addresses':label_positions,'continue_cursor_data':cursor_data,'scope':'Title scene, native glow/waterfall/OAM and reduced CONTINUE/RETRY menu. Save slots, registration and save not in this iteration.'})
for item in registry['assets']:
if item['root'] in ('scenes/title_2','scenes/title_3','scenes/title_6','scenes/title_7'):
item['included_in_build']=False
write_json(registry_path,registry)
print(f'Title: {len(artifacts)} glyphs, 4 unique glow scenes; continue menu: {len(marts)} glyphs, 3 scenes')
if __name__=='__main__':
prepare()
from prepare_save_ui import prepare as prepare_save_ui
prepare_save_ui()
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Extract a fixed overworld HUD from the verified ROM and publish its render."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT, ROM_SHA256, decode
from extract_start_room import RGB, write_json
UUID = '3cd67989-7c68-458a-a414-b551203eaee5'
OUT = ROOT / 'extracted/hud'
BANK = ROOT / 'assets/ui/hud'
def prepare():
rom = (ROOT / '.tmp/zelda-1.nes').read_bytes()
assert hashlib.sha256(rom).hexdigest() == ROM_SHA256
prg = rom[16:]
memory = bytearray(0x4000)
memory[0x2000:0x23C0] = bytes([0x24]) * 960
transfers = []
def transfer(offset):
start = offset
while prg[offset] != 0xFF:
address = prg[offset] << 8 | prg[offset + 1]
control = prg[offset + 2]
offset += 3
count, stride = control & 0x3F, 32 if control & 0x80 else 1
for i in range(count):
memory[address + i * stride] = prg[offset if control & 0x40 else offset + i]
offset += 1 if control & 0x40 else count
transfers.append({'prg_offset': start, 'hex': prg[start:offset + 1].hex()})
# Original PPU update records: static boxes/labels/icons, OW minimap, counts.
static = prg.index(bytes.fromhex('23c20e4000004455550000040000445555'))
text = prg.index(bytes.fromhex('20b608242424242424242420d608'))
transfer(static)
transfer(103247)
transfer(text)
# Fixed presentation fixture: zero rupees/keys/bombs, 3 full containers.
for i in range(3): memory[0x20D6 + i] = 0xF2
bg = bytearray(4096)
bg[:0x700] = prg[34687:34687 + 1792]
bg[0x700:0xF20] = prg[51515:51515 + 2080]
bg[0xF20:] = prg[36479:36479 + 224]
palettes = [list(prg[103171 + i * 4:103175 + i * 4]) for i in range(8)]
# Same explicit digital palette approximations as the terrain/Link exports.
rgb = dict(RGB)
rgb.update({0x29: (56, 184, 0), 0x02: (0, 0, 188), 0x22: (104, 136, 252),
0x0C: (0, 64, 88), 0x1C: (0, 136, 136), 0x2C: (88, 248, 216)})
canvas = Image.new('RGBA', (256, 64), (0, 0, 0, 255))
tiles = []
for y in range(8):
for x in range(32):
tile = memory[0x2000 + y * 32 + x]
attr = memory[0x23C0 + (y // 4) * 8 + x // 4]
shift = ((y % 4) // 2) * 4 + ((x % 4) // 2) * 2
palette = (attr >> shift) & 3
pixels = decode(bg[tile * 16:(tile + 1) * 16])
image = Image.new('RGBA', (8, 8))
image.putdata([(*rgb[palettes[palette][v]], 255) for v in pixels])
canvas.paste(image, (x * 8, y * 8))
tiles.append({'x': x, 'y': y, 'tile_id': tile, 'palette_id': palette})
def sprite(tile, x, y, palette):
image = Image.new('RGBA', (8, 8))
values = decode(prg[32895 + tile * 16:32895 + (tile + 1) * 16])
image.putdata([(*rgb[palettes[palette][v]], 255) if v else (0, 0, 0, 0) for v in values])
canvas.alpha_composite(image, (x, y))
# UpdatePositionMarker: room $77 -> OAM ($2D,$33), visible Y=$34.
sprite(0x3E, 45, 52, 4)
unarmed = canvas.copy()
# Wooden sword slot 0, frame tile $20; narrow item adds 4 to $94.
# DrawStatusBarSword OAM Y=$1F, visible Y=$20; 8x16 sprite uses $20/$21.
sprite(0x20, 152, 32, 4)
sprite(0x21, 152, 40, 4)
OUT.mkdir(parents=True, exist_ok=True)
BANK.mkdir(parents=True, exist_ok=True)
canvas.save(OUT / 'hud.png')
unarmed.save(OUT / 'hud_unarmed.png')
canvas.resize((768, 192), Image.Resampling.NEAREST).save(OUT / 'hud@3x.png')
colors = sorted(set(canvas.getdata()))
assert len(colors) <= 16
rgba = [int.from_bytes(bytes(c), 'big', signed=True) for c in colors]
artifacts = []
for y in range(2):
for x in range(8):
index = y * 8 + x
path = BANK / f'hud_{index:02d}.png'
canvas.crop((x * 32, y * 32, (x + 1) * 32, (y + 1) * 32)).save(path)
artifacts.append({'file': path.name, 'index': index, 'artifact_id': f'hud-{index:02d}',
'fingerprint': hashlib.sha256(path.read_bytes()).hexdigest()})
# Keep glyphs 0..15 stable; only tile 12 changes when Items[0] is zero.
path = BANK / 'hud_16_unarmed.png'
unarmed.crop((128, 32, 160, 64)).save(path)
artifacts.append({'file': path.name, 'index': 16, 'artifact_id': 'hud-unarmed-slot-a',
'fingerprint': hashlib.sha256(path.read_bytes()).hexdigest()})
# Runtime life is emitted separately as 8x8 glyphs; retain the A-box edge.
heartless = canvas.copy()
for y in range(40, 56):
for x in range(176, 240): heartless.putpixel((x, y), (0, 0, 0, 255))
for i in range(3):
path = BANK / f'hud-life-base-{i}.png'
heartless.crop((160 + i * 32, 32, 192 + i * 32, 64)).save(path)
artifacts.append({'file': path.name, 'index': 17 + i, 'artifact_id': f'hud-life-base-{i}',
'fingerprint': hashlib.sha256(path.read_bytes()).hexdigest()})
write_json(BANK / 'asset.json', {'schema_version': 1, 'asset_uuid': UUID,
'name': 'NES overworld HUD', 'type': 'glyph_bank',
'output': {'format': 'GLYPH/indexed_v1', 'codec': 'NONE',
'pipeline': {'palettes': [{'index': 0, 'palette': {'rgba8888': rgba}}]},
'metadata': {'tile_size': '32x32'}},
'preload': {'enabled': True}, 'artifacts': artifacts})
write_json(BANK / 'studio.asset.json', {'schema_version': 1, 'glyph_bank_specialization': 'tileset'})
registry_path = ROOT / 'assets/.prometeu/index.json'
registry = json.loads(registry_path.read_text())
found = [a for a in registry['assets'] if a['asset_uuid'] == UUID or a['root'] == 'ui/hud']
if found:
assert len(found) == 1 and found[0]['asset_uuid'] == UUID and found[0]['root'] == 'ui/hud'
found[0]['included_in_build'] = True
else:
registry['assets'].append({'asset_id': registry['next_asset_id'], 'asset_uuid': UUID,
'root': 'ui/hud', 'included_in_build': True})
registry['next_asset_id'] += 1
write_json(registry_path, registry)
write_json(OUT / 'provenance.json', {'rom_sha256': ROM_SHA256, 'transfers': transfers,
'background_tiles': tiles, 'nes_palettes': palettes,
'fixture': {'room_id': 119, 'hearts': 3, 'rupees': 0, 'keys': 0, 'bombs': 0,
'item_a': 'wooden sword', 'item_b': None},
'sprites': [{'tile': 62, 'x': 45, 'y': 52, 'palette': 4},
{'tile': 32, 'x': 152, 'y': 32, 'palette': 4},
{'tile': 33, 'x': 152, 'y': 40, 'palette': 4}],
'rgb_approximations': {hex(k): v for k, v in rgb.items()},
'variants': {'unarmed': 'hud_unarmed.png', 'wooden_sword': 'hud.png'},
'live_inventory_slots': [0, 24, 25],
'scope': 'ROM-derived HUD; Items[0] chooses slot A and Items[24/25] drive runtime heart glyphs. Other counters remain fixed.'})
print(f'HUD extracted: {len(colors)} colors, 20 tiles, ROM PPU records at {static}, 103247, {text}')
if __name__ == '__main__': prepare()
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Extract Items tables, new-game defaults and sword-lift graphics from the ROM."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT, ROM_SHA256, decode
from assemble_link import COLORS
from extract_start_room import write_json
UUID='6cc0a4cb-5d87-4dbf-bbb0-721f52256ade'
def prepare():
rom=(ROOT/'.tmp/zelda-1.nes').read_bytes();assert hashlib.sha256(rom).hexdigest()==ROM_SHA256
p=rom[16:]
slot_at=p.index(bytes.fromhex('01000000060504040202030d090c1b1c'))
descriptor_at=p.index(bytes.fromhex('14212223010121222122010101010115'))
slots=list(p[slot_at:slot_at+36]);descriptors=list(p[descriptor_at:descriptor_at+36])
# New-game code proves Items=$0657, HeartValues=$066F, HeartPartial=$0670,
# MaxBombs=$067C; keep the complete original $28-byte layout.
signature=bytes.fromhex('a0279957068810faa9228d6f06ce7006a9088d7c06')
init_at=p.index(signature)
initial=[0]*40;initial[0x18]=0x22;initial[0x19]=255;initial[0x25]=8
module=ROOT/'src/inventory';module.mkdir(parents=True,exist_ok=True)
lines=['// Generated from verified ItemIdToSlot / ItemIdToDescriptor and new-game defaults.',
'declare global item_slots: array<int> = ['+', '.join(map(str,slots))+'];',
'declare global item_descriptors: array<int> = ['+', '.join(map(str,descriptors))+'];',
'declare global new_game_items: array<int> = ['+', '.join(map(str,initial))+'];','',
'declare struct ItemData() {',
' fn slot_for(item: int) -> int {',
' if item < 0 || item >= 36 { return -1; }',
' return item_slots[item] else -1;',' }',
' fn descriptor_for(item: int) -> int {',
' if item < 0 || item >= 36 { return 0; }',
' return item_descriptors[item] else 0;',' }',
' fn initial_value(slot: int) -> int { return new_game_items[slot] else 0; }','}','']
(module/'items.generated.pbs').write_text('\n'.join(lines))
def column(tile):
# Demo CHR survives in $0700..$08DF when OW CHR overwrites $08E0+.
offset=32895+tile*16 if tile<0x70 else 19892+(tile*16-0x700)
result=Image.new('RGBA',(8,16))
result.putdata([COLORS[v] for n in (0,16) for v in decode(p[offset+n:offset+n+16])])
return result
offsets_at=p.index(bytes.fromhex('0003070a0b0c0d0e0f11121314151617'))
frames_at=p.index(bytes.fromhex('20823c3470727428863c2a262422404a'))
lift_tile=p[frames_at+p[offsets_at+0x21]];assert lift_tile==0x78
# Anim_WriteMirroredSpritePair sets right OAM attribute $40.
# DrawLinkLiftingItem replaces its tile with $08 but preserves that flip.
body=Image.new('RGBA',(16,16))
body.paste(column(lift_tile),(0,0))
body.paste(column(8).transpose(Image.Transpose.FLIP_LEFT_RIGHT),(8,0))
item=Image.new('RGBA',(16,16));item.paste(column(0x20),(0,0))
bank=ROOT/'assets/characters/link_pickup';bank.mkdir(parents=True,exist_ok=True)
artifacts=[]
for index,(name,image) in enumerate([('lift_sword',body),('wooden_sword',item)]):
path=bank/(name+'.png');image.save(path)
artifacts.append({'file':path.name,'index':index,'artifact_id':'pickup-'+name,
'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
output=json.loads((ROOT/'assets/characters/link/asset.json').read_text())['output']
write_json(bank/'asset.json',{'schema_version':1,'asset_uuid':UUID,'name':'Link NES sword pickup',
'type':'glyph_bank','output':output,'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())
matches=[a for a in registry['assets'] if a['asset_uuid']==UUID or a['root']=='characters/link_pickup']
if matches:assert len(matches)==1 and matches[0]['asset_uuid']==UUID
else:
registry['assets'].append({'asset_id':registry['next_asset_id'],'asset_uuid':UUID,
'root':'characters/link_pickup','included_in_build':True});registry['next_asset_id']+=1
write_json(registry_path,registry)
out=ROOT/'extracted/inventory';out.mkdir(parents=True,exist_ok=True)
body.resize((128,128),Image.Resampling.NEAREST).save(out/'lift_sword@8x.png')
write_json(out/'rom-data.json',{'rom_sha256':ROM_SHA256,'items_length':40,'item_slots':slots,
'item_descriptors':descriptors,'new_game_items':initial,'prg_offsets':{'item_slots':slot_at,
'item_descriptors':descriptor_at,'new_game':init_at},'lift':{'body_left_tile':120,
'body_right_tile':8,'body_left_flip_x':False,'body_right_flip_x':True,'item_tile':32,'timer':128,'residual_chr_source':'demo_sprites',
'left_tile_prg_offset':19892+128},'cave_pickup':{'room_id':119,'room_item_mask':16,
'x':120,'item_y':152,'vertical_distance_exclusive':6,'person_disappear_timer':64},
'scope':'NES Items layout/tables, sword grades 0..3, OW room flags and wooden sword acquisition. Other item effects and disk persistence are not implemented.'})
print('Generated NES Items tables (36 IDs / 40 slots), initial bytes and sword lift')
if __name__=='__main__':prepare()
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Decode native submenu transfers/items and publish the final scene-bank slot."""
import hashlib,json,uuid
from PIL import Image
from extract_graphics import ROOT,decode,ROM_SHA256
from extract_start_room import RGB,write_json
from nes_object_graphics import P,item
def prepare():
assert hashlib.sha256((ROOT/'.tmp/zelda-1.nes').read_bytes()).hexdigest()==ROM_SHA256
out=ROOT/'extracted/inventory_screen';out.mkdir(exist_ok=True,parents=True)
directory=json.loads((ROOT/'extracted/game_flow/rom-data.json').read_text())['transfer_directory_prg_offset']
common=P.index(bytes.fromhex('3f00200f3000120f1627360f0c1c2c0f121c2c0f2927070f2227070f2627070f152730ff'))
ram=bytearray(65536);ram[0x67f0:0x687e]=P[common:common+142];ram[0x687e:0x6b7e]=P[99328:100096]
patch_sig=bytes.fromhex('000809010a0b121e1f172425131421132021151622162223');patch=P.index(patch_sig,5*16384,6*16384)
offsets=list(P[patch:patch+24]);replacements=list(P[patch+24:patch+48]);empty=list(P[patch+48:patch+72])
for i,o in enumerate(offsets):ram[0x6847+4+o]=empty[i]
memory=bytearray(0x4000);memory[0x2800:0x2bc0]=bytes([36])*960
records=[]
def transfer(selector):
ptr=int.from_bytes(P[directory+selector:directory+selector+2],'little')
source=ram if ptr<0x8000 else P;start=ptr if ptr<0x8000 else 6*16384+ptr-0x8000;pos=start;events=[]
while 0x20<=source[pos]<0x40:
address=source[pos]*256+source[pos+1];control=source[pos+2];count=control&63 or 64;pos+=3
for i in range(count):memory[address+i*(32 if control&128 else 1)]=source[pos if control&64 else pos+i]
events.append({'address':address,'control':control,'count':count});pos+=1 if control&64 else count
records.append({'selector':selector,'pointer_cpu':ptr,'source':'RAM' if ptr<0x8000 else 'PRG','source_offset':start,'events':events})
for selector in (0x30,0x32,0x34,0x38,0x3a,0x3c,0x48,0x4a,0x4c,0x50,0x52,0x54,0x56,0x58,0x5a,0x5c):transfer(selector)
patterns=bytearray(8192)
for pos,size,dest in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[dest:dest+size]=P[pos:pos+size]
rgb=dict(RGB);rgb.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
rows=[list(P[103171+i*4:103175+i*4]) for i in range(8)]
cave_asset=json.loads((ROOT/'assets/tilesets/cave_start/asset.json').read_text());cv=cave_asset['output']['pipeline']['palettes'][0]['palette']['rgba8888'];cave_colors=[tuple((v&0xffffffff)>>s&255 for s in (24,16,8,0)) for v in cv]
canonical=[(*rgb[c],255) for c in rows[0]]
for c in cave_colors:
if c not in canonical:canonical.append(c)
while len(canonical)<16:
c=(len(canonical),0,1,255)
if c not in canonical:canonical.append(c)
assert len(canonical)==16
palettes=[]
for n,row in enumerate(rows):
colors=[(0,0,0,0) if i==0 and n>=4 else (*rgb[c],255) for i,c in enumerate(row)]
palettes.append(colors+[canonical[i] for i in range(4,16)])
palettes[0]=canonical
palettes.append(cave_colors+[(0,0,0,255)]*(16-len(cave_colors)))
regpath=ROOT/'assets/.prometeu/index.json';reg=json.loads(regpath.read_text())
def register(root):
u=str(uuid.uuid5(uuid.NAMESPACE_URL,'zelda1/'+root))
for a in reg['assets']:
if a['root']==root:assert a['asset_uuid']==u;return a['asset_id'],u
n=reg['next_asset_id'];reg['next_asset_id']+=1;reg['assets'].append({'asset_id':n,'asset_uuid':u,'root':root,'included_in_build':True});return n,u
bank_root='ui/inventory';bank=ROOT/'assets'/bank_root;bank.mkdir(exist_ok=True,parents=True);bank_id,bank_uuid=register(bank_root);arts=[];keys={};native={}
def glyph(indices,key):
indices=tuple(indices)
if key in keys:return keys[key]
im=Image.new('RGBA',(8,8));im.putdata([canonical[i] for i in indices]);n=len(arts);path=bank/(key+'.png');im.save(path);keys[key]=n;arts.append({'file':path.name,'index':n,'artifact_id':key,'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()});return n
def pattern(key):
if key not in native:native[key]=glyph(decode(patterns[key*16:(key+1)*16]),f'ppu_{key*16:04x}')
return native[key]
def pal(x,y):
attr=memory[0x2bc0+(y//4)*8+x//4];return (attr>>(((y%4)//2)*4+((x%4)//2)*2))&3
panel=[];image=Image.new('RGBA',(256,176))
for y in range(8,30):
for x in range(32):
t=memory[0x2800+y*32+x];pa=pal(x,y);g=pattern(256+t);panel.append({'active':True,'glyph_id':g,'palette_id':pa,'flip_x':False,'flip_y':False})
im=Image.new('RGBA',(8,8));im.putdata([palettes[pa][v] for v in decode(patterns[4096+t*16:4096+(t+1)*16])]);image.paste(im,(x*8,(y-8)*8))
image.crop((0,1,256,176)).save(out/'panel.png')
# Native item frame heaps/attributes; encode all grades without baking sprites.
for slot in range(32):
for phase in range(4 if slot==1 else 2):
info=item(slot,phase)
for t in info['tiles'][:info['sides']]:pattern((t&1)*256+(t&254));pattern((t&1)*256+(t&254)+1)
pattern(0x1e);pattern(0x1f)
for t in set(replacements+empty+[0xe5,0xe6,0xf5]):pattern(256+t)
# Frozen-room strips come from the generated catalog when available.
catalog_path=ROOT/'extracted/overworld/expansion/catalog.json'
if catalog_path.exists():
catalog=json.loads(catalog_path.read_text());strips=catalog['menu_strips'];world_palette=catalog['world_palette_to_native']
else:
roots=['overworld_start','cave_start','cave_start','cave_start','overworld_north','overworld_north','overworld_north','overworld_north']
strips=[{'root':root,'row':8+30*(i-4) if i>=5 else 8,'palette':'cave' if i in (1,2,3) else 'world' if i>=4 else 'start'} for i,root in enumerate(roots)];world_palette=[2,3,0,1]
scene_roots=[r['root'] for r in strips];world_tiles=[]
for variant,strip in enumerate(strips):
root=strip['root'];request=json.loads((ROOT/f'assets/scenes/{root}/scene-bank.pack-request.json').read_text());layer=request['layers'][0]
asset_row=next(a for a in reg['assets'] if a['asset_id']==layer['glyph_asset_id']);folder=ROOT/'assets'/asset_row['root'];doc=json.loads((folder/'asset.json').read_text());cols=doc['output']['pipeline']['palettes'][0]['palette']['rgba8888'];cols=[tuple((v&0xffffffff)>>s&255 for s in (24,16,8,0)) for v in cols];lut={c:i for i,c in enumerate(cols)};files={a['index']:a['file'] for a in doc['artifacts']};cached={}
blank={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False}
world_tiles+=panel+[dict(blank) for _ in range(32*8)]
for cell in layer['tiles'][strip['row']*32:(strip['row']+22)*32]:
gid=cell['glyph_id']
if gid not in cached:
im=Image.open(folder/files[gid]).convert('RGBA');cached[gid]=glyph([lut[v] for v in im.getdata()],f'world_{variant}_{gid}')
palette=8 if strip['palette']=='cave' else 2 if strip['palette']=='start' else world_palette[cell['palette_id']]
world_tiles.append({'active':cell['active'],'glyph_id':cached[gid],'palette_id':palette,'flip_x':cell['flip_x'],'flip_y':cell['flip_y']})
write_json(bank/'asset.json',{'schema_version':1,'asset_uuid':bank_uuid,'name':'NES inventory and frozen-room strips','type':'glyph_bank','preload':{'enabled':True},'output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':[int.from_bytes(bytes(c),'big',signed=True) for c in row]}} for i,row in enumerate(palettes)]}},'artifacts':arts});write_json(bank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'sprites'})
scene_root='scenes/inventory';scene_id,scene_uuid=register(scene_root);folder=ROOT/'assets'/scene_root;folder.mkdir(exist_ok=True,parents=True)
write_json(folder/'asset.json',{'schema_version':1,'asset_uuid':scene_uuid,'name':'NES inventory scroll strips','type':'scene_bank','preload':{'enabled':True},'output':{'format':'SCENE/tilemap_v1','codec':'NONE','pipeline':{}}})
def layer(active,w,h,tiles):return {'active':active,'glyph_asset_id':bank_id,'tile_size':8,'parallax_factor_x':1.0,'parallax_factor_y':1.0,'width':w,'height':h,'tiles':tiles}
write_json(folder/'scene-bank.pack-request.json',{'schema_version':1,'format':'SCENE/tilemap_v1','version':1,'layers':[layer(True,32,len(world_tiles)//32,world_tiles)]+[layer(False,1,1,[blank]) for _ in range(3)]})
if json.loads(regpath.read_text())!=reg:write_json(regpath,reg)
offsets_at=P.index(bytes.fromhex('0003070a0b0c0d0e0f11121314151617'));frames_at=P.index(bytes.fromhex('20823c3470727428863c2a262422404a'));attrs_at=P.index(bytes.fromhex('ff01ff00000202000100020000020201'))
xs_at=P.index(bytes.fromhex('8098acb4c88098b0c88094a0b0c0ccb0'),5*16384,6*16384);cursor_at=P.index(bytes.fromhex('8098b0b0c88098b0c8'),xs_at,6*16384)
top=[native.get((t&1)*256+(t&254),0) for t in range(256)];bottom=[native.get((t&1)*256+(t&254)+1,0) for t in range(256)]
# Item frame offsets can address tile heap through grade/animation.
lines=['// Generated from verified native menu/item tables.', 'declare global menu_top: array<int> = ['+', '.join(map(str,top))+'];','declare global menu_bottom: array<int> = ['+', '.join(map(str,bottom))+'];']
for name,vals in [('item_offsets',P[offsets_at:offsets_at+37]),('item_frames',P[frames_at:frames_at+48]),('item_attrs',P[attrs_at:attrs_at+32]),('item_xs',P[xs_at:xs_at+16]),('cursor_xs',P[cursor_at:cursor_at+16])]:lines.append(f'declare global menu_{name}: array<int> = ['+', '.join(map(str,vals))+'];')
# Map patched transfer-buffer bytes to nametable cells, preserving overlapping halves.
cells={}
for record in records:
if record['source']=='RAM':
ev=record['events'][0]
for i in range(ev['count']):cells[record['pointer_cpu']+3+i-0x684b]=ev['address']+i
positions=sorted(set(offsets)); states=[]
for mask in range(256):
buf={o:ram[0x684b+o] for o in positions}
for i,o in enumerate(offsets):
if mask&(1<<(i//3)):buf[o]=0xf5 if buf[o] in (0xe5,0xe6) else replacements[i]
states += [native[256+buf[o]] for o in positions]
for name,vals in [('triforce_tiles',states),('triforce_x',[(cells[o]-0x2800)%32*8 for o in positions]),('triforce_y',[(cells[o]-0x2800)//32*8-240 for o in positions]),('triforce_palette',[pal((cells[o]-0x2800)%32,(cells[o]-0x2800)//32) for o in positions])]:
lines.append(f'declare global menu_{name}: array<int> = ['+', '.join(map(str,vals))+'];')
lines += ['declare struct TriforceData() {',f' fn count() -> int {{ return {len(positions)}; }}',f' fn tile(mask: int, i: int) -> int {{ return menu_triforce_tiles[(mask%256)*{len(positions)}+i] else 0; }}',' fn x(i: int) -> int { return menu_triforce_x[i] else 0; }',' fn y(i: int) -> int { return menu_triforce_y[i] else 0; }',' fn palette(i: int) -> int { return menu_triforce_palette[i] else 0; }','}']
lines+=['declare struct MenuData() {',' fn top(tile: int) -> int { return menu_top[tile] else 0; }',' fn bottom(tile: int) -> int { return menu_bottom[tile] else 0; }',' fn tile(slot: int, frame: int) -> int { let base=menu_item_offsets[slot] else 0; return menu_item_frames[base+frame] else 0; }',' fn attributes(slot: int) -> int { return menu_item_attrs[slot] else 0; }',' fn x(slot: int) -> int { return menu_item_xs[slot] else 176; }',' fn cursor_x(slot: int) -> int { return menu_cursor_xs[slot] else 128; }','}','']
(ROOT/'src/screens/inventory/data.generated.pbs').write_text('\n'.join(lines))
write_json(out/'rom-data.json',{'rom_sha256':ROM_SHA256,'common_data_prg':common,'transfer_directory_prg':directory,'transfers':records,'menu_memory_hex':memory[0x2800:0x2c00].hex(),'triforce_offsets':offsets,'triforce_empty_tiles':empty,'triforce_replacements':replacements,'glyph_native':native,'item_offsets_prg':offsets_at,'item_frames_prg':frames_at,'item_attrs_prg':attrs_at,'item_xs_prg':xs_at,'cursor_xs_prg':cursor_at,'scene_variants':scene_roots,'strip_height':416,'palettes':rows,'scope':'Overworld/cave submenu. Static transfers and item tables from local ROM. No starting inventory is granted.'})
print('Published inventory:',len(arts),'glyphs,',len(strips),'strips in scene slot 15')
if __name__=='__main__':prepare()
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Publish original heart tiles, damage palettes, death sparks and GAME OVER."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT,ROM_SHA256,decode
from extract_start_room import RGB,write_json
from prepare_hud import prepare as prepare_hud
LIFE_UUID='8ad788e0-bc32-44f4-90cf-72a017f9b785'
BLANK_UUID='9ae973a9-2004-4e4a-8467-b9911731d631'
OVER_UUID='55d7d709-132a-477e-a89d-6940f6c24e90'
SPARK_UUID='c64d63c9-fbff-4dd0-9c4b-8f456498d635'
def prepare():
prepare_hud()
rom=(ROOT/'.tmp/zelda-1.nes').read_bytes();assert hashlib.sha256(rom).hexdigest()==ROM_SHA256
p=rom[16:];rgb=dict(RGB);rgb.update({0x29:(56,184,0),0x02:(0,0,188),0x22:(104,136,252),0x0c:(0,64,88),0x1c:(0,136,136),0x2c:(88,248,216),0x32:(60,188,252),0x10:(188,188,188)})
def rgba(colors):return [int.from_bytes(bytes(c),'big',signed=True) for c in colors]
nes=[list(p[103187+i*4:103191+i*4]) for i in range(4)]
colors=[[(0,0,0,0)]+[(*rgb[c],255) for c in row[1:]] for row in nes]
colors += [[(0,0,0,0),(*rgb[0x32],255),(*rgb[0x27],255),(*rgb[0x17],255)],
[(0,0,0,0),(*rgb[0x16],255),(*rgb[0x27],255),(*rgb[0x17],255)],
[(0,0,0,0),(*rgb[0x10],255),(*rgb[0x30],255),(*rgb[0],255)]]
palettes=[{'index':i,'palette':{'rgba8888':rgba(c)}} for i,c in enumerate(colors)]
for root in ('characters/link','characters/link_door','characters/link_pickup'):
path=ROOT/'assets'/root/'asset.json';asset=json.loads(path.read_text());asset['output']['pipeline']['palettes']=palettes;write_json(path,asset)
bg=bytearray(4096);bg[:1792]=p[34687:34687+1792];bg[1792:0xf20]=p[51515:51515+2080];bg[0xf20:]=p[36479:36479+224]
def tile(n,colors,patterns=bg):
im=Image.new('RGBA',(8,8));im.putdata([colors[v] for v in decode(patterns[n*16:(n+1)*16])]);return im
out=ROOT/'extracted/life';out.mkdir(parents=True,exist_ok=True)
registry_path=ROOT/'assets/.prometeu/index.json';registry=json.loads(registry_path.read_text())
def register(root,uuid):
found=[a for a in registry['assets'] if a['asset_uuid']==uuid or a['root']==root]
if found:
assert len(found)==1 and found[0]['asset_uuid']==uuid and found[0]['root']==root
found[0]['included_in_build']=True;return found[0]['asset_id']
n=registry['next_asset_id'];registry['next_asset_id']+=1;registry['assets'].append({'asset_id':n,'asset_uuid':uuid,'root':root,'included_in_build':True});return n
life_id=register('ui/life',LIFE_UUID)
register('scenes/death_blank',BLANK_UUID);register('scenes/game_over',OVER_UUID)
register('characters/death_sparks',SPARK_UUID)
bank=ROOT/'assets/ui/life';bank.mkdir(parents=True,exist_ok=True)
heart_colors=[(*rgb[c],255) for c in [15,22,39,54]]
# One shared palette also includes white letters, black background and life red.
sheet_colors=[(0,0,0,255),(*rgb[22],255),(*rgb[39],255),(*rgb[54],255),(*rgb[48],255)]
arts=[]
def artifact(root,name,image,items):
path=root/(name+'.png');image.save(path);n=len(items);items.append({'file':path.name,'index':n,'artifact_id':name,'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()});return n
for n,name in [(242,'full'),(101,'half'),(102,'empty'),(36,'blank')]:artifact(bank,'heart-'+name,tile(n,heart_colors),arts)
letters=[16,10,22,14,36,24,31,14,27]
for i,n in enumerate(letters):artifact(bank,'game-over-'+str(i),tile(n,[(0,0,0,255),(*rgb[48],255),(*rgb[0],255),(*rgb[18],255)]),arts)
write_json(bank/'asset.json',{'schema_version':1,'asset_uuid':LIFE_UUID,'name':'NES hearts and GAME OVER','type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','pipeline':{'palettes':[{'index':0,'palette':{'rgba8888':rgba(sheet_colors)}}]},'metadata':{'tile_size':'8x8'}},'preload':{'enabled':True},'artifacts':arts})
write_json(bank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'})
for name,uuid,show in [('death_blank',BLANK_UUID,False),('game_over',OVER_UUID,True)]:
root=ROOT/'assets/scenes'/name;root.mkdir(parents=True,exist_ok=True)
tiles=[];canvas=Image.new('RGBA',(256,240),(0,0,0,255))
for y in range(30):
for x in range(32):
glyph=4+x-12 if show and y==18 and 12<=x<=20 else 3
tiles.append({'active':y>=8,'glyph_id':glyph,'palette_id':0,'flip_x':False,'flip_y':False})
if show and y==18 and 12<=x<=20:canvas.paste(Image.open(bank/('game-over-'+str(x-12)+'.png')),(x*8,y*8))
canvas.save(out/(name+'.png'))
empty={'active':False,'glyph_id':3,'palette_id':0,'flip_x':False,'flip_y':False}
def layer(active,w,h,t):return {'active':active,'glyph_asset_id':life_id,'tile_size':8,'parallax_factor_x':1.0,'parallax_factor_y':1.0,'width':w,'height':h,'tiles':t}
write_json(root/'asset.json',{'schema_version':1,'asset_uuid':uuid,'name':name,'type':'scene_bank','output':{'format':'SCENE/tilemap_v1','codec':'NONE','pipeline':{}},'preload':{'enabled':True}})
write_json(root/'scene-bank.pack-request.json',{'schema_version':1,'format':'SCENE/tilemap_v1','version':1,'layers':[layer(True,32,30,tiles)]+[layer(False,1,1,[empty]) for _ in range(3)]})
spark=ROOT/'assets/characters/death_sparks';spark.mkdir(parents=True,exist_ok=True);spark_arts=[]
for n in (98,100):
im=Image.new('RGBA',(16,16));left=Image.new('RGBA',(8,16))
for dy in (0,8):left.paste(tile(n+dy//8,colors[1],p[32895:32895+1792]),(0,dy))
im.paste(left,(0,0));im.paste(left.transpose(Image.Transpose.FLIP_LEFT_RIGHT),(8,0));artifact(spark,'spark-'+str(n),im,spark_arts)
write_json(spark/'asset.json',{'schema_version':1,'asset_uuid':SPARK_UUID,'name':'NES death sparks','type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','pipeline':{'palettes':[{'index':0,'palette':{'rgba8888':rgba(colors[1])}}]},'metadata':{'tile_size':'16x16'}},'preload':{'enabled':True},'artifacts':spark_arts})
write_json(spark/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'sprites'})
write_json(registry_path,registry)
write_json(out/'rom-data.json',{'rom_sha256':ROM_SHA256,'heart_tiles':[242,101,102,36],'invincibility_counter':24,'invincibility_tick_divisor':2,'damage_palettes':nes,'ring_link_colors':[41,50,22],'life_slots':[24,25],'damage_fire':128,'source':'Link_BeHarmed, FormatHeartsInTextBuf, TakeHeartsNoSound, DecrementInvincibilityTimer, UpdateMode11Death in local disassembly.'})
print('Published dynamic hearts, seven Link palettes, death scenes and sparks')
if __name__=='__main__':prepare()
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""Prepare an empty composed scene; original room data will replace it later."""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
registry_path = ROOT / "assets/.prometeu/index.json"
registry = json.loads(registry_path.read_text())
link = next(a for a in registry["assets"] if a["asset_uuid"] == "9bc59c58-4f6b-4b48-bffb-9dfc16ee44d8")
scene_uuid = "43b397da-4416-488e-85b1-d3bad43abbc0"
scene_root = "scenes/movement"
layers = [{"active": True, "glyph_asset_id": link["asset_id"], "tile_size": 16,
"parallax_factor_x": 1.0, "parallax_factor_y": 1.0,
"width": 1, "height": 1,
"tiles": [{"active": False, "glyph_id": 0, "palette_id": 0,
"flip_x": False, "flip_y": False}]} for _ in range(4)]
request = {"schema_version": 1, "format": "SCENE/tilemap_v1", "version": 1, "layers": layers}
(ROOT / "assets" / scene_root / "scene-bank.pack-request.json").write_text(json.dumps(request, indent=2) + "\n")
if not any(a["asset_uuid"] == scene_uuid for a in registry["assets"]):
if any(a["root"] == scene_root for a in registry["assets"]):
raise ValueError("Scene root already registered with a different identity")
registry["assets"].append({"asset_id": registry["next_asset_id"], "asset_uuid": scene_uuid,
"root": scene_root, "included_in_build": True})
registry["next_asset_id"] += 1
registry_path.write_text(json.dumps(registry, indent=2) + "\n")
print("Prepared empty movement scene with Link glyph-bank dependency")
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Publish room $67 and native Octorok patterns from the verified NES ROM."""
import hashlib,json,uuid
from PIL import Image
from extract_graphics import ROOT,decode
from nes_object_graphics import descriptor,octorok,ENTRY as DESCRIPTOR_ENTRY
from extract_start_room import extract,write_json,RGB
def prepare():
d=extract(0x67,'north');start=json.loads((ROOT/'extracted/overworld/start/room.json').read_text());p=(ROOT/'.tmp/zelda-1.nes').read_bytes()[16:]
regpath=ROOT/'assets/.prometeu/index.json';reg=json.loads(regpath.read_text())
def register(root):
for a in reg['assets']:
if a['root']==root:a['included_in_build']=True;return a['asset_id'],a['asset_uuid']
n=reg['next_asset_id'];reg['next_asset_id']+=1;u=str(uuid.uuid5(uuid.NAMESPACE_URL,'zelda1/'+root));reg['assets'].append({'asset_id':n,'asset_uuid':u,'root':root,'included_in_build':True});return n,u
def bank(root,images,colors,size):
n,u=register(root);folder=ROOT/'assets'/root;folder.mkdir(parents=True,exist_ok=True);arts=[]
for k,(name,im) in enumerate(images):
path=folder/(name+'.png');im.save(path);arts.append({'file':path.name,'index':k,'artifact_id':name,'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
write_json(folder/'asset.json',{'schema_version':1,'asset_uuid':u,'name':root,'type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':size},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':[int.from_bytes(bytes(c),'big',signed=True) for c in row]}} for i,row in enumerate(colors)]}},'preload':{'enabled':True},'artifacts':arts});write_json(folder/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'});return n
pairs=sorted({(r['tilemap'][y][x],r['palette_map'][y][x]) for r in (d,start) for y in range(8,30) for x in range(32)})
ims=[]
for t,pal in pairs:
source='north' if any(i['tile_id']==t and i['palette_id']==pal for i in d['used_tiles']) else 'start';ims.append((f'tile_{t:02x}_p{pal}',Image.open(ROOT/f'extracted/overworld/{source}/tiles/tile_{t:02x}_p{pal}.png').convert('RGBA')))
assert {pal for t,pal in pairs}=={2};bid=bank('tilesets/north',ims,[[(*RGB[c],255) for c in d['background_nes_palettes'][2]]],'8x8');g={pair:i for i,pair in enumerate(pairs)}
def scene(root,rooms):
_,u=register(root);f=ROOT/'assets'/root;f.mkdir(parents=True,exist_ok=True);write_json(f/'asset.json',{'schema_version':1,'asset_uuid':u,'name':root,'type':'scene_bank','output':{'format':'SCENE/tilemap_v1','codec':'NONE','pipeline':{}},'preload':{'enabled':True}})
empty={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False};tiles=[dict(empty) for _ in range(256)]
for r in rooms:
for y in range(8,30):
for x in range(32):tiles.append({'active':True,'glyph_id':g[(r['tilemap'][y][x],r['palette_map'][y][x])],'palette_id':0,'flip_x':False,'flip_y':False})
def layer(active,w,h,t):return {'active':active,'glyph_asset_id':bid,'tile_size':8,'parallax_factor_x':1.0,'parallax_factor_y':1.0,'width':w,'height':h,'tiles':t}
write_json(f/'scene-bank.pack-request.json',{'schema_version':1,'format':'SCENE/tilemap_v1','version':1,'layers':[layer(True,32,8+22*len(rooms),tiles)]+[layer(False,1,1,[empty]) for _ in range(3)]})
scene('scenes/overworld_north',[d]);scene('scenes/overworld_north_scroll',[d,start])
# Same raw tile semantics as the starting stage, separate room-owned array.
source=(ROOT/'src/stages/overworld_start/room.generated.pbs').read_text().replace('StartRoomData','RoomData');a=source.index('[');b=source.index('];',a)
values=[v for row in d['tilemap'][8:] for v in row];source=source[:a]+'[\n'+',\n'.join(' '+', '.join(map(str,values[i:i+32])) for i in range(0,704,32))+'\n'+source[b:]
f=ROOT/'src/stages/overworld_north';f.mkdir(parents=True,exist_ok=True);(f/'room.generated.pbs').write_text(source.replace('python3 tools/sync_start_stage.py','python3 tools/prepare_north.py'))
# DrawObjectWithType increments object type before indexing ObjAnimations.
heap=p.index(bytes.fromhex('0004080c101014185c9e44ced2d6dace'));anim=p.index(bytes.fromhex('00080b0f13175c601b1b2121'));frames=list(p[heap+p[anim+8]:heap+p[anim+8]+6]);assert frames==[0xb4,0xb0,0xb0,0xb8,0xb2,0xb2],frames
patterns=bytearray(4096);patterns[:1792]=p[32895:34687];patterns[0x700:0x1000]=p[19892:22196];patterns[0x8e0:]=p[53595:55419]
rows=[list(p[103171+16+i*4:103175+16+i*4]) for i in range(4)];rgb=dict(RGB);rgb.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
colors=[[(0,0,0,0) if i==0 else (*rgb[c],255) for i,c in enumerate(row)] for row in rows]
def column(t,flip=False,flip_y=False):
im=Image.new('RGBA',(8,16));im.putdata([colors[0][v] for k in (t,t+1) for v in decode(patterns[k*16:(k+1)*16])])
if flip:im=im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if flip_y:im=im.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
return im
def compose(info,offset=0):
im=Image.new('RGBA',(16,16))
for side in range(info['sides']):
attr=info['attributes'][side];im.paste(column(info['tiles'][side],bool(attr&64),bool(attr&128)),(offset+side*info['x_separation'],0))
return im
images=[];records=[]
for phase in range(2):
for direction in ('left','up','down','right'):
info=octorok(direction,phase);im=compose(info)
images.append((f'octorok_{direction}_{phase}',im));records.append({'direction':direction,'phase':phase,**info})
# The same original descriptor path handles a half-width rock at X + 4.
rock_info=descriptor(0x53);rocktile=rock_info['tiles'][0]
assert rock_info['animation_index']==0x54 and rocktile==0x9e and rock_info['sides']==1
images.append(('rock',compose(rock_info,4)))
# Cloud graphic is native monster metastate animation ($5F).
for t in (0x70,0x72,0x74):
im=Image.new('RGBA',(16,16));im.paste(column(t),(0,0));im.paste(column(t,True),(8,0));images.append((f'cloud_{t:02x}',im))
bank('characters/octorok',images,colors,'16x16')
# Source-room C=$47: count index 1, type $07. FoeCounts starts after palette terminator.
count=p[103168+36+1];assert count==4
spawn_sig=bytes.fromhex('6355957688795a9a6c');spawn_offset=p.index(spawn_sig,81920,98304);spawn=list(p[spawn_offset:spawn_offset+9]);safe=[]
for cell in spawn:
x=(cell&15)*16;y=(cell&240)|13;row=(y+11-64)//8;col=x//8
tile=d['tilemap'][row+8][col]
if tile in (141,145,156,172,173,204,210,213,223):tile=38
if tile<137:safe.append([x,y])
assert len(safe)>=4
write_json(ROOT/'extracted/overworld/north/enemies.json',{'type':7,'name':'Red slow Octorok','count':count,'spawn_list_prg_offset':spawn_offset,'up_entry_spawn_list':spawn,'first_safe_positions':safe[:4],'animation_heap_prg_offset':heap,'frame_tiles':frames,'frames':records,'descriptor_entry_cpu':DESCRIPTOR_ENTRY,'rock_descriptor':rock_info,'rock_tile':rocktile,'speed_q':32,'animation_ticks':6,'turn_rate':112,'monster_bounds':[17,224,78,205],'retained_demo_patterns_prg_offset':19892,'cloud_tiles':[112,114,116],'body_damage':128,'shot_damage':128,'scope':'Native room enemy and graphics extraction. Combat, history and drop rules are documented in extracted/combat.'})
# Minimap marker moves one overworld row (4 NES pixels) north.
hud=ROOT/'assets/ui/hud';doc=json.loads((hud/'asset.json').read_text());im=Image.open(hud/'hud_09.png').convert('RGBA');green=(56,184,0,255);gray=(124,124,124,255)
pixels=[(x,y) for y in range(32) for x in range(32) if im.getpixel((x,y))==green]
assert pixels
for x,y in pixels:im.putpixel((x,y),gray)
for x,y in pixels:im.putpixel((x,y-4),green)
path=hud/'hud-north-marker.png';im.save(path);artifact={'file':path.name,'index':20,'artifact_id':'hud-north-marker','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}
doc['artifacts']=[a for a in doc['artifacts'] if a['index']!=20]+[artifact];write_json(hud/'asset.json',doc)
if json.loads(regpath.read_text())!=reg:write_json(regpath,reg)
print('North and scroll scenes published; 4 red Octoroks:',safe[:4])
if __name__=='__main__':
prepare()
from prepare_overworld import prepare as prepare_world
prepare_world()
from prepare_zora import prepare as prepare_zora
prepare_zora()
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Generate room-owned stages, shared atlases, native foes and route tables."""
import hashlib,json
from PIL import Image
from extract_graphics import ROOT,decode
from extract_start_room import extract,write_json,RGB
from overworld_data import manifest,metadata
from nes_object_graphics import P
PALETTE_NATIVE=[2,3,0,1]
def prepare():
entries=manifest();assert len({e['stage'] for e in entries})==len(entries)
size=max(17,max(e['stage'] for e in entries)+1);rooms={};meta={};by_native={e['room']:e for e in entries};by_stage={e['stage']:e for e in entries}
for e in entries:
d=extract(e['room'],e['name']);rooms[e['stage']]=d;m=metadata(e['room']);meta[e['stage']]=m
assert len(m['foes'])<=5 and set(m['foes'])<={7,8,9},(e,m)
# Opaque CHR indices share one canonical green palette; cells select NES colors.
bank=ROOT/'assets/tilesets/north';doc=json.loads((bank/'asset.json').read_text());patterns=bytearray(4096)
for offset,chunk_size,dest in [(34687,1792,0),(51515,2080,1792),(36479,224,3872)]:patterns[dest:dest+chunk_size]=P[offset:offset+chunk_size]
nes_palettes=rooms[0]['background_nes_palettes'];colors=[(*RGB[c],255) for c in nes_palettes[2]]
native_tiles=sorted({t for d in rooms.values() for row in d['tilemap'][8:] for t in row});glyph={};arts=[]
for tile in native_tiles:
im=Image.new('RGBA',(8,8));im.putdata([colors[v] for v in decode(patterns[tile*16:(tile+1)*16])]);path=bank/f'tile_{tile:02x}.png';im.save(path);gid=len(arts);glyph[tile]=gid;arts.append({'file':path.name,'index':gid,'artifact_id':f'world-tile-{tile:02x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
doc['artifacts']=arts;doc['name']='Shared NES overworld terrain';doc['output']['pipeline']['palettes']=[{'index':i,'palette':{'rgba8888':[int.from_bytes(bytes((*RGB[c],255)),'big',signed=True) for c in nes_palettes[n]]}} for i,n in enumerate(PALETTE_NATIVE)];write_json(bank/'asset.json',doc)
blank={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False}
def cells(stage):
d=rooms[stage];return [{'active':True,'glyph_id':glyph[(243 if y==10 else 36) if stage==2 and 14<=x<=15 and 10<=y<=11 else d['tilemap'][y][x]],'palette_id':PALETTE_NATIVE.index(d['palette_map'][y][x]),'flip_x':False,'flip_y':False} for y in range(8,30) for x in range(32)]
def publish(root,width,tiles):
p=ROOT/f'assets/scenes/{root}/scene-bank.pack-request.json';v=json.loads(p.read_text());v['layers'][0].update(width=width,height=len(tiles)//width,tiles=tiles);write_json(p,v)
atlas=[];atlas_index={}
for e in entries:atlas_index[e['stage']]=len(atlas)//960;atlas += [dict(blank) for _ in range(256)]+cells(e['stage'])
publish('overworld_north',32,atlas)
# Connections require both native adjacency and an actual shared walkable opening.
exceptions=(141,145,156,172,173,204,210,213,223)
def walk(t):return t<137 or t in exceptions
def witnesses(left,right,vertical):
a=rooms[left]['tilemap'];b=rooms[right]['tilemap']
if vertical:return [x*8 for x in range(0,31,2) if all(walk(v) for v in (a[29][x],a[29][x+1],b[8][x],b[8][x+1]))]
return [61+i*16 for i in range(11) if walk(a[9+i*2][30]) and walk(b[9+i*2][0])]
links=[];transition_tiles=[];neighbors=[-1]*(size*4);transition_y=[0]*(size*4)
for e in entries:
for delta,vertical in [(1,False),(16,True)]:
if not vertical and e['room']%16==15:continue
other=by_native.get(e['room']+delta)
if not other:continue
points=witnesses(e['stage'],other['stage'],vertical)
if not points:continue
a=e['stage'];b=other['stage'];base=len(transition_tiles)//64*8
transition_tiles += [dict(blank) for _ in range(8*64)]
ac=cells(a);bc=cells(b)
if vertical:
for chunk in (ac,bc):
for y in range(22):transition_tiles += chunk[y*32:(y+1)*32]+[dict(blank) for _ in range(32)]
da,db=4,8
else:
for y in range(22):transition_tiles += ac[y*32:(y+1)*32]+bc[y*32:(y+1)*32]
da,db=1,2
idx=lambda stage,d:stage*4+{1:0,2:1,4:2,8:3}[d]
neighbors[idx(a,da)]=b;neighbors[idx(b,db)]=a;transition_y[idx(a,da)]=base;transition_y[idx(b,db)]=base
links.append({'a':a,'b':b,'room_a':e['room'],'room_b':other['room'],'direction':da,'atlas_y':base,'openings':points})
publish('overworld_north_scroll',64,transition_tiles)
# Each screen still owns its tile array and stage API, generated from its ROM room.
for e in entries:
if not e['managed']:continue
folder=ROOT/'src/stages'/e['module'];folder.mkdir(parents=True,exist_ok=True);typ=e['data_type'];service=e['service'];tiles=[v for row in rooms[e['stage']]['tilemap'][8:] for v in row]
source='// Generated by prepare_overworld.py from the verified native room.\n'
source+='declare global terrain: array<int> = ['+','.join(map(str,tiles))+'];\n'
source+=f'''declare struct {typ}() {{
fn tile_at(column: int,row: int) -> int {{ if column<0 || column>=32 || row<0 || row>=22 {{ return 255; }} return terrain[row*32+column] else 255; }}
fn contains_player(x: int,y: int) -> bool {{ return x>=0 && x<=240 && y>=61 && y<=221; }}
}}
'''
(folder/'room.generated.pbs').write_text(source)
(folder/'mod.barrel').write_text(f'pub service {service};\nmod struct {typ};\n')
(folder/'main.pbs').write_text(f'''import {{ Composer }} from @sdk:composer;
declare global room: {typ} = new {typ}();
declare service {service} {{
fn render() -> bool {{ let status=Composer.bind_scene(13); return status==0; }}
fn tile_at(column: int,row: int) -> int {{ return room.tile_at(column,row); }}
fn contains_player(x: int,y: int) -> bool {{ return room.contains_player(x,y); }}
}}
''')
# Room $66 has the native open doorway of shop $78.
shop_room=ROOT/'src/stages/overworld_northwest/main.pbs'
wrapper=shop_room.read_text().replace(' fn render()', ' fn can_enter(x: int,y: int,grid: int) -> bool { return x==112 && y==77 && grid==0; }\n fn render()')
shop_room.write_text(wrapper)
supply_room=ROOT/'src/stages/overworld_shop_west/main.pbs'
supply_room.write_text(supply_room.read_text().replace(' fn render()', ' fn can_enter(x: int,y: int,grid: int) -> bool { return x==64 && y==77 && grid==0; }\n fn render()'))
# Room $67 has a real rock-wall tile object; terrain stores its revealed passage.
north=ROOT/'src/stages/overworld_north'
source=(north/'main.pbs').read_text();source='import { BombableWall } from @zelda1:world;\nimport { Scene } from @zelda1:scene;\n'+source
source=source.replace('declare global room:', 'declare global wall_fresh: bool=false;\ndeclare global rock_wall: BombableWall = new BombableWall(103,112,80);\ndeclare global room:')
source=source.replace(' fn tile_at(column: int,row: int) -> int { return room.tile_at(column,row); }', ' fn tile_at(column: int,row: int) -> int { if column>=14 && column<=15 && row>=2 && row<=3 { if rock_wall.opened() { if row==2 && !wall_fresh { return 243; } return 36; } } return room.tile_at(column,row); }')
source=source.replace(' fn render()', ' fn wall_opened() -> bool { return rock_wall.opened(); }\n fn finish_visit() -> void { wall_fresh=false; }\n fn blast(x: int,y: int) -> void { let opened=rock_wall.try_blast(x,y); if opened { wall_fresh=true; } }\n fn can_enter(x: int,y: int,grid: int) -> bool { let opened=rock_wall.opened(); return opened && x==112 && y==77 && grid==0; }\n fn draw_wall(dx: int,dy: int) -> void { if rock_wall.opened() { return; }\n'+''.join(f' Scene.emit_sprite({glyph[t]},0,{112+x}+dx,{80+y}+dy,10,0);\n' for t,x,y in [(216,0,0),(218,8,0),(217,0,8),(219,8,8)])+' }\n fn render()')
(north/'main.pbs').write_text(source)
# Marker positions follow the original 16x8 overworld grid.
hud=ROOT/'assets/ui/hud';hdoc=json.loads((hud/'asset.json').read_text());base=Image.open(hud/'hud_09.png').convert('RGBA');green=(56,184,0,255);gray=(124,124,124,255);dots=[(x,y) for y in range(32) for x in range(32) if base.getpixel((x,y))==green];hud_ids=[9]*size
for e in entries:
if e['stage']==0:continue
marker_id=f'world-marker-{e["room"]:02x}';existing=next((a for a in hdoc['artifacts'] if a['artifact_id']==marker_id),None)
idx=existing['index'] if existing else max(a['index'] for a in hdoc['artifacts'])+1;im=base.copy()
for x,y in dots:im.putpixel((x,y),gray)
dx=(e['room']%16-7)*2;dy=(e['room']//16-7)*4
for x,y in dots:im.putpixel((x+dx,y+dy),green)
path=hud/f'world-marker-{e["room"]:02x}.png';im.save(path);hdoc['artifacts']=[a for a in hdoc['artifacts'] if a['index']!=idx and a['artifact_id']!=f'world-marker-{e["room"]:02x}']+[{'file':path.name,'index':idx,'artifact_id':path.stem,'fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}];hud_ids[e['stage']]=idx
write_json(hud/'asset.json',hdoc)
ids=[119]*size;camera=[0]*size;counts=[0]*size;kinds=[0]*(size*5);edge=[0]*size;menu=[0]*size;menu[1]=1
ids[10]=103;hud_ids[10]=hud_ids[2];menu[10]=1
ids[11]=102;hud_ids[11]=hud_ids[3];menu[11]=1
ids[16]=68;hud_ids[16]=hud_ids[15];menu[16]=1
for e in entries:
i=e['stage'];menu[i]=0 if i==0 else atlas_index[i]+3;ids[i]=e['room'];camera[i]=atlas_index[i]*240;counts[i]=len(meta[i]['foes']);edge[i]=int(meta[i]['edge_spawns']);kinds[i*5:i*5+len(meta[i]['foes'])]=meta[i]['foes']
folder=ROOT/'src/overworld';folder.mkdir(parents=True,exist_ok=True);(folder/'mod.barrel').write_text('pub service Overworld;\nmod struct WorldData;\n')
data=['// Generated overworld catalog: room identity, foes, UI and directed edges.']
for name,values in [('ids',ids),('camera',camera),('counts',counts),('kinds',kinds),('edges',edge),('menu',menu),('hud',hud_ids),('zora',[int(meta[i]['zora']) if i in meta else 0 for i in range(size)]),('neighbors',neighbors),('transition_y',transition_y)]:data.append(f'declare global world_{name}: array<int> = ['+','.join(map(str,values))+'];')
data+=['declare struct WorldData() {']
for name,default in [('ids',119),('camera',0),('counts',0),('edges',0),('zora',0),('menu',0),('hud',9)]:data.append(f' fn {name}(i: int) -> int {{ return world_{name}[i] else {default}; }}')
data+=[' fn kind(stage: int,slot: int) -> int { return world_kinds[stage*5+slot] else 0; }',' fn index(stage: int,direction: int) -> int { let d=if direction==1 { 0 } else if direction==2 { 1 } else if direction==4 { 2 } else { 3 }; return stage*4+d; }',' fn neighbor(stage: int,direction: int) -> int { let i=this.index(stage,direction); return world_neighbors[i] else -1; }',' fn transition_y(stage: int,direction: int) -> int { let i=this.index(stage,direction); return world_transition_y[i] else 0; }','}']
(folder/'data.generated.pbs').write_text('\n'.join(data)+'\n')
code=['import { CaveStart } from @zelda1:stages/cave_start;','import { CaveSecret } from @zelda1:stages/cave_secret;','import { CaveShop } from @zelda1:stages/cave_shop;','import { CaveSupplyShop } from @zelda1:stages/cave_supply_shop;']+[f'import {{ {e["service"]} }} from @zelda1:stages/{e["module"]};' for e in entries]
code+=['declare global data: WorldData = new WorldData();','declare service Overworld {',' fn is_cave(stage: int) -> bool { return stage==1 || stage==10 || stage==11 || stage==16; }',' fn has_zora(stage: int) -> bool { let value=data.zora(stage); return value!=0; }',' fn native_id(stage: int) -> int { return data.ids(stage); }',' fn camera_y(stage: int) -> int { return data.camera(stage); }',' fn foe_count(stage: int) -> int { return data.counts(stage); }',' fn foe_kind(stage: int,slot: int) -> int { return data.kind(stage,slot); }',' fn from_edges(stage: int) -> bool { let value=data.edges(stage); return value!=0; }',' fn hud_glyph(stage: int) -> int { return data.hud(stage); }',' fn menu_variant(stage: int) -> int { if stage==1 || stage==10 || stage==11 || stage==16 { return 1; } return data.menu(stage); }',' fn neighbor(stage: int,direction: int) -> int { return data.neighbor(stage,direction); }',' fn transition_y(stage: int,direction: int) -> int { return data.transition_y(stage,direction); }']
for method,args,ret,fallback in [('tile_at','column: int,row: int','int','255'),('contains_player','x: int,y: int','bool','false'),('render','','bool','false')]:
tail='column,row' if method=='tile_at' else 'x,y' if method=='contains_player' else ''
code.append(f' fn {method}(stage: int'+(','+args if args else '')+f') -> {ret} {{')
code.append(f' if stage==1 {{ return CaveStart.{method}({tail}); }}')
code.append(f' if stage==10 {{ return CaveSecret.{method}({tail}); }}')
code.append(f' if stage==11 {{ return CaveShop.{method}({tail}); }}')
code.append(f' if stage==16 {{ return CaveSupplyShop.{method}({tail}); }}')
for e in entries:code.append(f' if stage=={e["stage"]} {{ return {e["service"]}.{method}({tail}); }}')
code+=[' return '+fallback+';',' }']
code+=['}'];(folder/'main.pbs').write_text('\n'.join(code)+'\n')
strips=[{'root':'overworld_start','row':8,'palette':'start'}]+[{'root':r,'row':8,'palette':'cave'} for r in ('cave_start','cave_start','cave_start')]
strips += [{'root':'overworld_north','row':atlas_index[e['stage']]*30+8,'palette':'world'} for e in entries if e['stage']!=0]
report={'rooms':[dict(e,**meta[e['stage']],atlas_index=atlas_index[e['stage']]) for e in entries],'links':links,'menu_strips':strips,'world_palette_to_native':PALETTE_NATIVE,'limits':{'actor_pool':5,'scene_slots':16},'legacy_gaps':[]}
write_json(ROOT/'extracted/overworld/expansion/catalog.json',report)
from prepare_inventory_screen import prepare as inventory
inventory()
print('Overworld:',len(entries),'rooms,',len(links),'bidirectional links,',len(arts),'glyphs; no new scene slots')
if __name__=='__main__':prepare()
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""ROM room $67 rock wall and its actual $7B / 30-rupee Moblin cave."""
import hashlib,json
from PIL import Image
from extract_graphics import ROOT,decode
from extract_start_room import RGB,write_json
from nes_object_graphics import P,descriptor
from validate_octorok_graphics import native_image
def metadata():
d=json.loads((ROOT/'extracted/overworld/north/room.json').read_text());primary=P[d['primary_table_prg_offset']:d['primary_table_prg_offset']+56]
walls=[(x*16,y*16+64) for x,c in enumerate(d['columns']) for y,i in enumerate(c['squares']) if primary[i]==230];assert walls==[(112,80)]
attrs=d['room_attributes'];cave_index=((attrs[1]&252)-64)//4;assert cave_index==17;assert attrs[0]&240==112 and ((attrs[5]&7)*16+77)==77
selectors=P.index(bytes.fromhex('406042420406480a4c0ed0d2d2dcdc dede626262'.replace(' ','')));ware_offset=99328+512+cave_index*3;ware=list(P[ware_offset:ware_offset+3]);prices=list(P[ware_offset+60:ware_offset+63]);assert ware==[63,152,127] and prices==[0,30,0]
selector=P[selectors+cave_index]&63;text_offset=16384+int.from_bytes(P[16384+selector:16386+selector],'little')-0x8000
return {'source_stage':2,'source_room':103,'stage':10,'wall_x':112,'wall_y':80,'entrance_x':112,'entrance_y':77,'cave_index':cave_index,'object_type':106+cave_index,'text_selector':selector,'text_prg_offset':text_offset,'ware_prg_offset':ware_offset,'wares':ware,'prices':prices,'reward':prices[1],'secret_quest':attrs[5]>>6,'first_quest':True}
def prepare():
out=ROOT/'extracted/real_secret';out.mkdir(exist_ok=True,parents=True);meta=metadata();folder=ROOT/'assets/tilesets/cave_start';p=folder/'asset.json';doc=json.loads(p.read_text());arts=[a for a in doc['artifacts'] if not a['artifact_id'].startswith(('secret-cave-','shop-','supply-shop-'))];start=max(a['index'] for a in arts)+1
palettes=doc['output']['pipeline']['palettes'];colors=[tuple((c&0xffffffff)>>s&255 for s in (24,16,8,0)) for c in palettes[0]['palette']['rgba8888']]
patterns=bytearray(8192)
for offset,length,dest in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[dest:dest+length]=P[offset:offset+length]
def glyph_image(tile):
row=json.loads((ROOT/'extracted/cave/start/room.json').read_text())['nes_palettes'][2];im=Image.new('RGBA',(8,8));im.putdata([(0,0,0,0) if v==0 else (*RGB[row[v]],255) for v in decode(patterns[4096+tile*16:4096+(tile+1)*16])]);return im
parts=[]
def add(im,x,y,kind):
for yy in range(0,im.height,8):
for xx in range(0,im.width,8):
crop=im.crop((xx,yy,xx+8,yy+8));assert set(crop.getdata())<=set(colors)
path=folder/f'secret_cave_{len(arts)-start:03d}.png';crop.save(path);index=len(arts);arts.append({'file':path.name,'index':index,'artifact_id':f'secret-cave-{index-start}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()});parts.append([kind,x+xx,y+yy,index])
info=descriptor(meta['object_type'],object_attribute=129);add(native_image(info),120,129,1)
address=0x21a4;cursor=meta['text_prg_offset'];text=[]
while True:
v=P[cursor];cursor+=1;tile=v&63;x=(address-0x2000)%32*8;y=(address-0x2000)//32*8
if tile!=37:add(glyph_image(tile),x,y,2);text.append({'tile':tile,'x':x,'y':y})
address+=1;control=v&192
if control==192:break
if control:address=0x21c4 if control==128 else 0x21e4
add(glyph_image(3),120,176,4);add(glyph_image(0),128,176,4)
doc['artifacts']=arts;write_json(p,doc)
module=ROOT/'src/stages/cave_secret';module.mkdir(parents=True,exist_ok=True)
flat=[v for part in parts for v in part]
code='// Generated Moblin, native message and 30-rupee receipt; fire/ware use shared APIs.\nimport { Scene } from @zelda1:scene;\n'
code+='declare global secret_parts: array<int> = ['+','.join(map(str,flat))+'];\ndeclare struct SecretCaveArt() {\n fn draw(show_person: bool,claimed: bool,offset: int) -> void {\n'
code+=f' for i: int from 0 until {len(parts)} {{\n'
code+=' let kind=secret_parts[i*4] else 0;\n if show_person && (kind!=4 || claimed) { let x=secret_parts[i*4+1] else 0; let y=secret_parts[i*4+2] else 0; let glyph=secret_parts[i*4+3] else 0; Scene.emit_sprite(glyph,0,x,y+offset,3,0); }\n }\n }\n}\n'
(module/'art.generated.pbs').write_text(code)
terrain=(ROOT/'src/stages/cave_start/room.generated.pbs').read_text().replace('CaveData','SecretCaveData').replace('terrain','secret_terrain');(module/'room.generated.pbs').write_text(terrain)
reference=Image.open(ROOT/'extracted/cave/start/room_taken.png').convert('RGBA')
for kind,x,y,g in parts:
if kind!=4:reference.alpha_composite(Image.open(folder/next(a['file'] for a in arts if a['index']==g)).convert('RGBA'),(x,y))
meta.update(moblin_descriptor=info,text_tiles=text,parts=parts,first_glyph=start,art_bank=3)
# Rupee uses native item descriptor/color in the runtime; independent reference.
from nes_object_graphics import item
rupee=native_image(item(22));reference.alpha_composite(rupee,(120,153));reference.save(out/'cave_available.png')
receipt=reference.copy()
for kind,x,y,g in parts:
if kind==4:receipt.alpha_composite(Image.open(folder/next(a['file'] for a in arts if a['index']==g)).convert('RGBA'),(x,y))
receipt.save(out/'cave_claimed.png');Image.open(ROOT/'extracted/cave/start/room_taken.png').save(out/'cave_revisit.png')
write_json(out/'rom-data.json',meta)
print('Real wall $67 at (112,80), cave $7B, reward 30; appended',len(parts),'glyphs')
from prepare_shop import prepare as shop
shop()
if __name__=='__main__':prepare()
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Publish native font labels and a Link memcard icon, reusing current banks."""
import json,hashlib
from PIL import Image
from extract_graphics import ROOT,decode
from nes_object_graphics import P
from extract_start_room import write_json
def prepare():
folder=ROOT/'assets/ui/continue';doc=json.loads((folder/'asset.json').read_text());palette=doc['output']['pipeline']['palettes'][0]['palette']['rgba8888'];colors=[tuple((v&0xffffffff)>>s&255 for s in (24,16,8,0)) for v in palette];ids={a['file']:a['index'] for a in doc['artifacts']}
patterns=P[34687:34687+1792]
for tile in range(37):
name=f'bg_{tile:02x}.png'
if name in ids:continue
im=Image.new('RGBA',(8,8));im.putdata([colors[v] for v in decode(patterns[tile*16:(tile+1)*16])]);path=folder/name;im.save(path);index=len(doc['artifacts']);ids[name]=index;doc['artifacts'].append({'file':name,'index':index,'artifact_id':f'continue-bg-{tile:02x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
write_json(folder/'asset.json',doc)
# One existing menu scene becomes the reusable black UI background.
for n in range(3):
p=ROOT/f'assets/scenes/continue_{n}/scene-bank.pack-request.json';s=json.loads(p.read_text())
for cell in s['layers'][0]['tiles']:cell.update(glyph_id=ids['bg_24.png'],palette_id=0)
write_json(p,s)
labels={'heading':'SELECT GAME','continue_game':'CONTINUE','new_game':'NEW GAME','save':'SAVE','retry':'RETRY','empty':'NO SAVE FOUND','invalid':'SAVE DATA INVALID','version':'SAVE VERSION UNSUPPORTED','read_error':'CANNOT READ SAVE','hint':'SELECT OPENS SAVE MENU','saving':'SAVING','saved':'GAME SAVED','memory':'MEMORY ONLY','not_saved':'NOT SAVED TO CARD','failed':'SAVE FAILED','unknown':'SAVE STATUS UNKNOWN','blocked':'CARD NOT WRITABLE','start':'PRESS START','retry_hint':'START RETURNS TO MENU','no_change':'PREVIOUS SAVE KEPT'}
def codes(text):return [36 if c==' ' else ord(c)-ord('A')+10 if c.isalpha() else int(c) for c in text]
lines=['import { Scene } from @zelda1:scene;']
for name,label in labels.items():lines.append(f'declare global text_{name}: array<int> = ['+','.join(map(str,codes(label)))+'];')
lines+=['declare global save_font: array<int> = ['+','.join(str(ids[f'bg_{i:02x}.png']) for i in range(37))+'];','declare service SaveGraphics {',' fn line(chars: array<int>, count: int, x: int,y: int,palette: int) -> void {',' for i: int from 0 until count { let code=chars[i] else 36; let glyph=save_font[code] else 9; Scene.emit_ui_sprite(glyph,palette,x+i*8,y,9,false,false,1); }',' }']
for name,label in labels.items():lines.append(f' fn {name}(x: int,y: int,palette: int) -> void {{ SaveGraphics.line(text_{name},{len(label)},x,y,palette); }}')
lines+=[' fn cursor(x: int,y: int) -> void { Scene.emit_ui_sprite(10,6,x,y,9,false,false,2); }','}']
(ROOT/'src/screens/save/graphics.generated.pbs').write_text('\n'.join(lines)+'\n')
# 32x32 4bpp icon, native Link sprite enlarged solely for memcard metadata.
asset=ROOT/'assets/characters/link';art=json.loads((asset/'asset.json').read_text())['artifacts'][0];im=Image.open(asset/art['file']).convert('RGBA').crop((0,0,16,16)).resize((32,32),Image.Resampling.NEAREST)
colors=[(0,0,0)];indices=[]
for r,g,b,a in im.getdata():
c=(r,g,b) if a else (0,0,0)
if c not in colors:colors.append(c)
indices.append(colors.index(c))
assert len(colors)<=16
colors += [(0,0,0)]*(16-len(colors));data=[v for c in colors for v in c]+[(indices[i]<<4)|indices[i+1] for i in range(0,1024,2)];assert len(data)==560
lines=['declare global save_icon_bytes: array<int> = ['+','.join(map(str,data))+'];','declare struct SaveIcon() {',' fn byte_at(i: int) -> int { return save_icon_bytes[i] else 0; }','}'];(ROOT/'src/save/icon.generated.pbs').write_text('\n'.join(lines)+'\n');print('Native save font and 560-byte memcard icon published')
if __name__=='__main__':prepare()
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Native room $66 shop $78, keeping actors/text/prices outside the terrain."""
import json,hashlib
from PIL import Image
from extract_graphics import ROOT,decode
from extract_start_room import RGB,write_json
from nes_object_graphics import P,descriptor,item
from validate_octorok_graphics import native_image
def metadata(source_room=102,source_stage=3,stage=11):
attrs=list(P[99328+i*128+source_room] for i in range(6));index=((attrs[1]&252)-64)//4;assert index in (13,14)
at=99328+512+index*3;wares=list(P[at:at+3]);prices=list(P[at+60:at+63]);assert ([v&63 for v in wares],prices)==(([28,25,6],[160,100,60]) if index==14 else ([28,0,8],[130,20,80]))
selectors=P.index(bytes.fromhex('406042420406480a4c0ed0d2d2dcdc dede626262'.replace(' ','')));select=P[selectors+index];flags=(select&192)>>6|(wares[0]&192)|((wares[2]&192)>>4)|((wares[1]&192)>>2);assert flags==15
ptr=16384+int.from_bytes(P[16384+(select&63):16386+(select&63)],'little')-32768
return {'source_stage':source_stage,'source_room':source_room,'stage':stage,'object_type':106+index,'cave_index':index,'entry_x':attrs[0]&240,'entry_y':(attrs[5]&7)*16+77,'wares':[v&63 for v in wares],'raw_wares':wares,'prices':prices,'ware_prg_offset':at,'text_selector':select&63,'text_prg_offset':ptr,'flags':flags}
def prepare_one(supply=False):
m=metadata(68,15,16) if supply else metadata();prefix='supply-shop-' if supply else 'shop-';file_prefix='supply_shop_' if supply else 'shop_';out=ROOT/('extracted/supply_shop' if supply else 'extracted/shop');out.mkdir(parents=True,exist_ok=True);folder=ROOT/'assets/tilesets/cave_start';path=folder/'asset.json';doc=json.loads(path.read_text());arts=[a for a in doc['artifacts'] if not a['artifact_id'].startswith(prefix if supply else ('shop-','supply-shop-'))];start=max(a['index'] for a in arts)+1;assert len(arts)==start
colors=[tuple((c&0xffffffff)>>s&255 for s in (24,16,8,0)) for c in doc['output']['pipeline']['palettes'][0]['palette']['rgba8888']];parts=[]
def add(im,x,y,kind):
for c in sorted(set(im.getdata())):
if c not in colors:colors.append(c)
assert len(colors)<=16
for yy in range(0,im.height,8):
for xx in range(0,im.width,8):
crop=im.crop((xx,yy,xx+8,yy+8));p=folder/f'{file_prefix}{len(arts)-start:03d}.png';crop.save(p);i=len(arts);arts.append({'file':p.name,'index':i,'artifact_id':f'{prefix}{i-start}','fingerprint':hashlib.sha256(p.read_bytes()).hexdigest()});parts.append([kind,x+xx,y+yy,i])
patterns=bytearray(8192)
for off,length,dest in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[dest:dest+length]=P[off:off+length]
row=json.loads((ROOT/'extracted/cave/start/room.json').read_text())['nes_palettes'][2]
def font(t):
im=Image.new('RGBA',(8,8));im.putdata([(0,0,0,0) if v==0 else (*RGB[row[v]],255) for v in decode(patterns[4096+t*16:4096+(t+1)*16])]);return im
info=descriptor(m['object_type'],mirrored=True,object_attribute=129);add(native_image(info),120,129,0)
address=0x21a4;cursor=m['text_prg_offset'];text=[]
while True:
v=P[cursor];cursor+=1;t=v&63;x=(address-8192)%32*8;y=(address-8192)//32*8
if t!=37:add(font(t),x,y,1);text.append({'tile':t,'x':x,'y':y})
address+=1;control=v&192
if control==192:break
if control:address=0x21c4 if control==128 else 0x21e4
# Native price transfer $22C8: X and 3 fields, each 4 characters wide.
add(font(33),64,176,2)
for i,price in enumerate(m['prices']):
digits=f'{price:3d}'
for j,c in enumerate(digits):
if c!=' ':add(font(int(c)),80+i*32+j*8,176,2)
doc['artifacts']=arts;doc['output']['pipeline']['palettes'][0]['palette']['rgba8888']=[int.from_bytes(bytes(c),'big',signed=True) for c in colors];write_json(path,doc)
module=ROOT/('src/stages/cave_supply_shop' if supply else 'src/stages/cave_shop');module.mkdir(parents=True,exist_ok=True)
flat=[v for row in parts for v in row]
code='// Generated merchant, message, price transfer and ROM wares.\nimport { Scene } from @zelda1:scene;\n'
code+='declare global shop_parts: array<int> = ['+','.join(map(str,flat))+'];\n'
code+='declare global shop_items: array<int> = ['+','.join(map(str,m['wares']))+'];\n'
code+='declare global shop_prices: array<int> = ['+','.join(map(str,m['prices']))+'];\n'
code+='declare struct ShopArt() {\n fn item(i: int) -> int { return shop_items[i] else -1; }\n fn price(i: int) -> int { return shop_prices[i] else 0; }\n fn draw(visible: bool,bought: bool,offset: int) -> void {\n'
code+=f' for i: int from 0 until {len(parts)} {{\n'
code+=' let kind=shop_parts[i*4] else 0;\n if kind==2 || (kind==0 && visible) || (kind==1 && !bought) { let x=shop_parts[i*4+1] else 0; let y=shop_parts[i*4+2] else 0; let glyph=shop_parts[i*4+3] else 0; Scene.emit_sprite(glyph,0,x,y+offset,3,0); }\n }\n }\n}\n'
if supply:code=code.replace('ShopArt','SupplyShopArt')
(module/'art.generated.pbs').write_text(code);source=(ROOT/'src/stages/cave_start/room.generated.pbs').read_text().replace('CaveData','SupplyShopData' if supply else 'ShopCaveData').replace('terrain','shop_terrain');(module/'room.generated.pbs').write_text(source)
ref=Image.open(ROOT/'extracted/cave/start/room_taken.png').convert('RGBA')
for kind,x,y,g in parts:ref.alpha_composite(Image.open(folder/next(a['file'] for a in arts if a['index']==g)).convert('RGBA'),(x,y))
# Exact native item palettes: shield 0, key 2, blue candle 1; price rupee flashes.
slots_at=P.index(bytes.fromhex('01000000060504040202030d090c1b1c'));desc_at=P.index(bytes.fromhex('14212223010121222122010101010115'));attrs_at=P.index(bytes.fromhex('ff01ff00000202000100020000020201'))
slots=[P[slots_at+ware] for ware in m['wares']];palettes=[(P[attrs_at+slot]+(P[desc_at+ware]%16 if slot in (0,2,4,7,11) else 0))%4 for ware,slot in zip(m['wares'],slots)]
assert palettes==([0,1,0] if supply else [0,2,1])
m['item_palette_sources']={'slots_prg':slots_at,'descriptors_prg':desc_at,'attributes_prg':attrs_at}
for i,(slot,pal) in enumerate(zip(slots,palettes)):
spec=item(slot,attribute=pal);ref.alpha_composite(native_image(spec),(88+i*32,153))
ref.alpha_composite(native_image(item(22,attribute=1)),(48,172));ref.save(out/'shop_available.png')
m.update(parts=parts,text_tiles=text,keeper_descriptor=info,first_glyph=start,colors=len(colors),item_slots=slots,item_palettes=palettes);write_json(out/'rom-data.json',m)
print('Native shop',hex(m['source_room']),m['prices'],'; appended',len(parts),'glyphs; scene slots unchanged')
def prepare():
prepare_one();prepare_one(True)
if __name__=='__main__':prepare()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Publish the extracted starting-room terrain as a glyph bank and scene bank."""
import hashlib
import json
import shutil
from extract_graphics import ROOT
from extract_start_room import RGB, extract, write_json
from sync_start_stage import sync
TILES_UUID = "54de385e-42b8-40be-8337-cf9b93950ae4"
SCENE_UUID = "c4bb08fb-07aa-4cd6-a001-0ac93f4e32ea"
def prepare():
data = extract()
registry_path = ROOT / "assets/.prometeu/index.json"
registry = json.loads(registry_path.read_text())
def register(relative_root, uuid):
matches = [a for a in registry["assets"] if a["root"] == relative_root or a["asset_uuid"] == uuid]
if matches:
if len(matches) != 1 or matches[0]["root"] != relative_root or matches[0]["asset_uuid"] != uuid:
raise ValueError("Asset registry identity collision")
matches[0]["included_in_build"] = True
return matches[0]["asset_id"]
asset_id = registry["next_asset_id"]
registry["assets"].append({"asset_id": asset_id, "asset_uuid": uuid,
"root": relative_root, "included_in_build": True})
registry["next_asset_id"] += 1
return asset_id
tiles_id = register("tilesets/overworld", TILES_UUID)
register("scenes/overworld_start", SCENE_UUID)
# Preserve the empty test bank for reference, but only preload the real room.
for asset in registry["assets"]:
if asset["asset_uuid"] == "43b397da-4416-488e-85b1-d3bad43abbc0":
asset["included_in_build"] = False
bank = ROOT / "assets/tilesets/overworld"
scene = ROOT / "assets/scenes/overworld_start"
bank.mkdir(parents=True, exist_ok=True)
scene.mkdir(parents=True, exist_ok=True)
artifacts = []
glyphs = {}
# The initial room's outer and inner palette are both NES background row 2.
# Keep this explicit rather than silently baking other room palettes.
if {t["palette_id"] for t in data["used_tiles"]} != {2}:
raise ValueError("Starting-room palette assumption no longer holds")
for tile in data["used_tiles"]:
path = bank / tile["file"]
shutil.copyfile(ROOT / "extracted/overworld/start/tiles" / tile["file"], path)
index = len(artifacts)
glyphs[(tile["tile_id"], tile["palette_id"])] = index
artifacts.append({"file": path.name, "index": index,
"artifact_id": f"ow-tile-{tile['tile_id']:02x}-p{tile['palette_id']}",
"fingerprint": hashlib.sha256(path.read_bytes()).hexdigest()})
palette = [int.from_bytes(bytes((*RGB[code], 255)), "big", signed=True)
for code in data["background_nes_palettes"][2]]
write_json(bank / "asset.json", {
"schema_version": 1, "asset_uuid": TILES_UUID, "name": "Overworld NES terrain",
"type": "glyph_bank", "output": {"format": "GLYPH/indexed_v1", "codec": "NONE",
"pipeline": {"palettes": [{"index": 0, "palette": {"rgba8888": palette}}]},
"metadata": {"tile_size": "8x8"}}, "preload": {"enabled": True}, "artifacts": artifacts})
write_json(bank / "studio.asset.json", {"schema_version": 1, "glyph_bank_specialization": "tileset"})
write_json(scene / "asset.json", {
"schema_version": 1, "asset_uuid": SCENE_UUID, "name": "Overworld starting room 77",
"type": "scene_bank", "output": {"format": "SCENE/tilemap_v1", "codec": "NONE", "pipeline": {}},
"preload": {"enabled": True}})
tiles = []
for y in range(30):
for x in range(32):
active = y >= 8
glyph = glyphs[(data["tilemap"][y][x], data["palette_map"][y][x])] if active else 0
tiles.append({"active": active, "glyph_id": glyph, "palette_id": 0,
"flip_x": False, "flip_y": False})
def layer(active, width, height, values):
return {"active": active, "glyph_asset_id": tiles_id, "tile_size": 8,
"parallax_factor_x": 1.0, "parallax_factor_y": 1.0,
"width": width, "height": height, "tiles": values}
empty = {"active": False, "glyph_id": 0, "palette_id": 0, "flip_x": False, "flip_y": False}
layers = [layer(True, 32, 30, tiles)] + [layer(False, 1, 1, [empty]) for _ in range(3)]
write_json(scene / "scene-bank.pack-request.json", {
"schema_version": 1, "format": "SCENE/tilemap_v1", "version": 1, "layers": layers})
write_json(registry_path, registry)
sync()
print(f"Registered {len(artifacts)} terrain glyphs and starting-room scene; glyph asset {tiles_id}")
if __name__ == "__main__":
prepare()
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Append native Zora/fireball art to the existing actor bank, preserving IDs."""
import hashlib,json
from extract_graphics import ROOT
from extract_start_room import write_json
from nes_object_graphics import descriptor,P
from validate_octorok_graphics import native_image
def prepare():
folder=ROOT/'assets/characters/octorok';p=folder/'asset.json';doc=json.loads(p.read_text());arts=[a for a in doc['artifacts'] if not a['artifact_id'].startswith('zora-')];start=max(a['index'] for a in arts)+1;specs={}
for i,frame in enumerate([0,1,2,3,8,9]):
info=descriptor(17,frame,True);specs[str(frame)]=info;im=native_image(info,True);path=folder/f'zora_{frame}.png';im.save(path);arts.append({'file':path.name,'index':start+i,'artifact_id':f'zora-{frame}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()})
info=descriptor(85);specs['fireball']=info;path=folder/'zora_fireball.png';native_image(info,True).save(path);arts.append({'file':path.name,'index':start+6,'artifact_id':'zora-fireball','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()});doc['artifacts']=arts;write_json(p,doc)
hp=P.index(bytes.fromhex('06432531122481142242'));at=P.index(bytes.fromhex('080a1020100a80200fff1060100b0105010b'),65536,81920);times=list(P[at+6:at+12]);anim=list(P[at+12:at+18]);speeds=P.index(bytes.fromhex('70686058503c26100010263c5058606870'),65536,81920);qx=list(P[speeds:speeds+8])+[0];qy=list(P[speeds+8:speeds+17]);assert P[hp+8]&15==2
code='// Generated from native burrower timers, fireball speeds and executed descriptors.\n'
for name,values in [('z_times',times),('z_anim',anim),('z_qx',qx),('z_qy',qy)]:code+=f'declare global {name}: array<int> = ['+','.join(map(str,values))+'];\n'
code+='declare struct ZoraData() {\n fn timer(s: int) -> int { return z_times[s] else 0; }\n fn anim(s: int) -> int { return z_anim[s] else 1; }\n fn qx(s: int) -> int { return z_qx[s] else 0; }\n fn qy(s: int) -> int { return z_qy[s] else 0; }\n'
code+=f' fn glyph(frame: int) -> int {{ if frame==8 {{ return {start+4}; }} if frame==9 {{ return {start+5}; }} return {start}+frame; }}\n fn fireball() -> int {{ return {start+6}; }}\n}}\n'
(ROOT/'src/enemies/zora/data.generated.pbs').write_text(code)
write_json(ROOT/'extracted/zora/rom-data.json',{'descriptors':specs,'hp':2,'hp_table_prg':hp,'timers':times,'animation_timers':anim,'state_tables_prg':at,'qx':qx,'qy':qy,'fireball_table_prg':speeds,'actor_bank':11,'first_glyph':start,'water_tiles':[141,152],'fireball_damage':128,'magic_shield_slot':31,'room_kill_count':False,'scope':'First Zora encounter; no sound.'})
print('Zora art appended:',start,'through',start+6)
if __name__=='__main__':prepare()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Generate Link's NES-phase lookup from Studio bindings and verified ROM tables."""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def sync():
bank = ROOT / "assets/characters/link"
document = json.loads((bank / "animations.studio.json").read_text())
asset = json.loads((bank / "asset.json").read_text())
if document["bank_asset_uuid"] != asset["asset_uuid"]:
raise ValueError("Animation bank mismatch")
selected = {a["artifact_id"]: a for a in asset["artifacts"]}
import hashlib
for binding in document["bindings"]:
artifact = selected[binding["artifact_id"]]
if (binding["glyph_id"] != artifact["index"] or
binding["fingerprint"] != hashlib.sha256((bank / artifact["file"]).read_bytes()).hexdigest()):
raise ValueError("Animation bindings drifted; rebind explicitly in Studio first")
bindings = {b["artifact_id"]: b["glyph_id"] for b in document["bindings"]}
animator = next(a for a in document["animators"] if a["id"] == "link")
lines = ["// Generated from assets/characters/link/animations.studio.json.",
"// Regenerate with: python3 tools/sync_link_animation.py",
"// Internal Link-module lookup; shared through mod.barrel.",
"// Use direct glyph lookup so the NES owns the shared animation phase.",
"fn link_walk_glyph(direction: int, phase: int) -> int {"]
clips = {clip["name"]: clip for clip in animator["clips"]}
for name, direction in (("right", 1), ("left", 2), ("down", 4), ("up", 8)):
frames = clips[f"walk_{name}"]["frames"]
if len(frames) != 2 or any(f["duration_ticks"] != 6 for f in frames):
raise ValueError("NES movement requires two frames of 6 ticks per direction")
glyphs = [bindings[f["artifact_id"]] for f in frames]
lines.extend([f" if direction == {direction} {{",
f" return if phase == 0 {{ {glyphs[0]} }} else {{ {glyphs[1]} }};",
" }"])
lines.extend([" return 0;", "}", ""])
lines.append("fn link_attack_glyph(direction: int, phase: int) -> int {")
for name, direction in (("right", 1), ("left", 2), ("down", 4), ("up", 8)):
frames = clips[f"attack_{name}"]["frames"]
glyphs = [bindings[f["artifact_id"]] for f in frames]
lines.extend([f" if direction == {direction} {{",
f" return if phase == 0 {{ {glyphs[0]} }} else {{ {glyphs[1]} }};", " }"])
lines.extend([" return 0;", "}", ""])
data_path = ROOT / "extracted/link/attack-data.json"
if data_path.exists():
data = json.loads(data_path.read_text())
lines.append("fn sword_glyph(direction: int) -> int {")
for name, direction in (("right", 1), ("left", 2), ("down", 4), ("up", 8)):
lines.append(f" if direction == {direction} {{ return {bindings['link-sword_' + name]}; }}")
lines.extend([" return 0;", "}", ""])
for axis in ("x", "y"):
lines.append(f"fn sword_offset_{axis}(direction: int, weapon_state: int) -> int {{")
for state in range(1, 5):
lines.append(f" if weapon_state == {state} {{")
for name, direction in (("right", 1), ("left", 2), ("down", 4), ("up", 8)):
index = (state - 1) * 4 + data["offset_direction_order"].index(name)
lines.append(f" if direction == {direction} {{ return {data['offsets_' + axis][index]}; }}")
lines.append(" }")
lines.extend([" return 0;", "}", ""])
path = ROOT / "src/link/graphics.generated.pbs"
path.write_text("// Generated from Studio bindings and verified ROM tables.\n"
"// Regenerate with: python3 tools/sync_link_animation.py\n"
"declare struct LinkGraphics() {\n" +
"\n".join(" " + line if line else "" for line in lines) + "}\n")
print("Synchronized Link frame lookup from the saved Studio definition")
if __name__ == "__main__":
sync()
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Generate the starting stage's raw NES collision map and verified ROM rules."""
import hashlib
import json
from extract_graphics import ROOT, ROM_SHA256
def sync():
rom = (ROOT / ".tmp/zelda-1.nes").read_bytes()
if hashlib.sha256(rom).hexdigest() != ROM_SHA256:
raise ValueError("Unverified ROM")
prg = rom[16:]
source = ROOT / "extracted/overworld/start/room.json"
room = json.loads(source.read_text())
if room["rom_sha256"] != ROM_SHA256 or room["room_id"] != 0x77:
raise ValueError("Wrong stage source")
exceptions = list(prg[126443:126452])
if exceptions != [0x8D, 0x91, 0x9C, 0xAC, 0xAD, 0xCC, 0xD2, 0xD5, 0xDF]:
raise ValueError("Walkable-tile table differs from the reference")
threshold = prg[94296]
edges = list(prg[127199:127203]) # up, down, left, right
if threshold != 0x89 or edges != [0x3D, 0xDD, 0, 0xF0]:
raise ValueError("Room bounds differ from the reference")
tiles = [tile for row in room["tilemap"][8:30] for tile in row]
lines = ["// Generated from the original NES tile IDs, not packed glyph indices.",
"// Regenerate with: python3 tools/sync_start_stage.py",
"declare global terrain: array<int> = ["]
for row in range(22):
lines.append(" " + ", ".join(str(v) for v in tiles[row * 32:(row + 1) * 32]) + ("," if row < 21 else ""))
lines.extend([
"];", "", "declare struct StartRoomData() {",
" fn tile_at(column: int, row: int) -> int {",
" if column < 0 || column >= 32 || row < 0 || row >= 22 { return 255; }",
" return terrain[row * 32 + column] else 255;", " }", "",
" fn normalize_tile(tile: int) -> int {",
" if " + " || ".join(f"tile == {tile}" for tile in exceptions) + " { return 38; }",
" return tile;", " }", "",
f" fn first_unwalkable() -> int {{ return {threshold}; }}", "",
" fn contains_player(x: int, y: int) -> bool {",
f" return x >= {edges[2]} && x <= {edges[3]} && y >= {edges[0]} && y <= {edges[1]};",
" }", "}", ""])
target = ROOT / "src/stages/overworld_start/room.generated.pbs"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("\n".join(lines))
(ROOT / "extracted/overworld/start/collision-data.json").write_text(json.dumps({
"rom_sha256": ROM_SHA256, "room_id": 0x77, "tiles": tiles,
"width": 32, "height": 22, "play_area_y": 64,
"walkable_exceptions": exceptions, "first_unwalkable": threshold,
"closed_screen_bounds": {"up": edges[0], "down": edges[1], "left": edges[2], "right": edges[3]},
"prg_offsets": {"walkable_exceptions": 126443, "first_unwalkable": 94296, "screen_edges": 127199}
}, indent=2) + "\n")
print("Generated starting-stage collision data: 704 raw NES tiles and verified walkability rules")
if __name__ == "__main__":
sync()
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Check route metadata and blue drops against the local native 6502 routine."""
import json,re
from extract_graphics import ROOT
from validate_combat_rom import drop
from nes_object_graphics import P,descriptor
def validate():
route=json.loads((ROOT/'extracted/overworld/northwest/bomb-route.json').read_text())
assert [r['room'] for r in route['route']]==[0x66,0x65,0x64]
assert [r['types'] for r in route['route']]==[[8,7,8,7],[8,7,8,7],[8,9,8,9,8]]
text=(ROOT/'src/loot/data.generated.pbs').read_text();items=list(map(int,re.search(r'drop_table: array<int> = \[([^]]+)\]',text)[1].split(',')));rates=list(map(int,re.search(r'drop_rates: array<int> = \[([^]]+)\]',text)[1].split(',')))
cases=0;bomb_cases=0
for cycle in range(10):
for random in range(256):
got=drop(9,cycle,random,0,0,0);expected=items[20+cycle] if random<rates[2] else -1
assert got==(expected,0,0),(cycle,random,got,expected);cases+=1;bomb_cases+=got[0]==0
# Types 7/8/9 share patterns and H/V flips; color is the native palette row.
for frame in range(6):
red=descriptor(7,frame);blue=descriptor(9,frame);fast=descriptor(8,frame)
for key in ('tiles','attributes','sides','x_separation'):assert red[key]==fast[key]
for key in ('tiles','sides','x_separation'):assert red[key]==blue[key]
assert [a&252 for a in red['attributes']]==[a&252 for a in blue['attributes']]
assert all(a%4==1 for a in blue['attributes'])
report={'native_blue_drop_cases':cases,'mismatches':0,'bomb_cases':bomb_cases,'route':route['route'],'descriptor_frame_cases':6,'scope':'Bounded native descriptor/drop execution; no full-game frame-lockstep claim.'}
(ROOT/'extracted/overworld/northwest/native-validation.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':validate()
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""Compare wall overlay and restored entrance against existing native tile PNGs."""
from PIL import Image,ImageChops
from extract_graphics import ROOT
def validate():
out=ROOT/'extracted/bomb_wall/validation';source=ROOT/'assets/tilesets/overworld';wall=Image.new('RGB',(16,16))
for name,x,y in [('d8',0,0),('da',8,0),('d9',0,8),('db',8,8)]:wall.paste(Image.open(source/f'tile_{name}_p2.png').convert('RGB'),(x,y))
checks=[('closed',80),('menu_mid',168),('scroll_north_mid',168),('scroll_south_mid',168)]
for name,y in checks:
image=Image.open(out/(name+'.png')).convert('RGB');actual=image.crop((112+64,15+y,112+80,15+y+16));assert ImageChops.difference(actual,wall).getbbox() is None,name
opened=Image.open(out/'continue.png').convert('RGB').crop((176,95,192,111));original=Image.open(ROOT/'extracted/overworld/start/room.png').convert('RGB').crop((64,80,80,96));assert ImageChops.difference(opened,original).getbbox() is None,'opened entrance'
print('Five terrain patches match native pixels: closed, menu, both scrolls, restored entrance')
if __name__=='__main__':validate()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Execute the ROM's collision leaf, with native tile-object threshold $10."""
import json
from extract_graphics import ROOT
from nes_object_graphics import P,DELTA
ENTRY=P.index(bytes.fromhex('850d850ea9008506a400a50238e50420'))
def collide(dx,dy):
m=bytearray(65536);m[0x6c90:0x7f00]=P[0x6500:0x7770];m[2]=72;m[3]=85;m[4]=(72+dx)&255;m[5]=(85+dy)&255
a=16;y=0;c=z=n=False;pc=ENTRY+DELTA;stack=[]
def nz(v):
nonlocal z,n
v &=255;z=v==0;n=v>=128;return v
def byte():
nonlocal pc
v=m[pc];pc+=1;return v
def word():return byte()|byte()<<8
for _ in range(200):
at=pc;op=byte()
if op==0x85:m[byte()]=a
elif op==0xa9:a=nz(byte())
elif op==0xa5:a=nz(m[byte()])
elif op==0xa4:y=nz(m[byte()])
elif op==0x38:c=True
elif op==0x18:c=False
elif op==0xe5:
v=a-m[byte()]-(not c);c=v>=0;a=nz(v)
elif op in (0xc5,0xc9):
v=m[byte()] if op==0xc5 else byte();c=a>=v;nz(a-v)
elif op==0xe6:q=byte();m[q]=nz(m[q]+1)
elif op==0x49:a=nz(a^byte())
elif op==0x69:
v=a+byte()+c;c=v>255;a=nz(v)
elif op==0x20:
target=word();stack.append(pc);pc=target
elif op==0x60:
if not stack:return bool(a)
pc=stack.pop()
elif op in (0x10,0x30,0x90,0xb0,0xf0,0xd0):
d=byte();take={0x10:not n,0x30:n,0x90:not c,0xb0:c,0xf0:z,0xd0:not z}[op]
if take:pc+=d if d<128 else d-256
else:raise AssertionError(f'Unsupported {op:02x} at {at:04x}')
raise AssertionError('Native routine did not return')
def validate():
cases=[]
for dx in (-24,-17,-16,-15,-1,0,1,15,16,17,24):
for dy in (-24,-17,-16,-15,-1,0,1,15,16,17,24):
actual=collide(dx,dy);assert actual==(abs(dx)<16 and abs(dy)<16);cases.append([dx,dy,actual])
out=ROOT/'extracted/bomb_wall';out.mkdir(exist_ok=True,parents=True);(out/'native-collision.json').write_text(json.dumps({'entry_prg':ENTRY,'threshold':16,'cases':cases,'mismatches':0},indent=2)+'\n');print('Native wall collision:',len(cases),'cases matched')
if __name__=='__main__':validate()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Check the cave's terrain probes against original 6502 and saved Studio frames."""
import json
import re
from PIL import Image, ImageChops
import validate_collision_rom as collision
from extract_graphics import ROOT
OUT = ROOT / 'extracted/cave/start'
# One continuous Studio session, starting with no input and a fresh build.
# Explicit checkpoints come from the ROM doorway/spawn coordinates and movement.
CHECKPOINTS = [
('initial',1,{},0,120,133,'down',0,-1),
('approach_left',40,{'left':True},0,65,133,'left',1,-1),
('door_ready',43,{'up':True},0,64,77,'up',0,-1),
('door_start',1,{},0,64,77,'up',0,0),
('door_middle',32,{},0,64,85,'up',1,8),
('cave_spawn',31,{},1,112,221,'up',0,-1),
('cave_walk_done',32,{},1,112,173,'up',1,-1),
('cave_idle',12,{},1,112,173,'up',1,-1),
('cave_left_wall',200,{'left':True},1,32,173,'left',1,-1),
('cave_right_wall',200,{'right':True},1,208,173,'right',0,-1),
('cave_center',72,{'left':True},1,111,173,'left',0,-1),
('cave_exit_ready',36,{'down':True},1,112,221,'down',0,-1),
('exit_start',1,{'down':True},0,64,93,'down',0,16),
('exit_middle',32,{},0,64,85,'down',1,8),
('exit_done',32,{},0,64,77,'down',1,-1),
('exit_idle',24,{},0,64,77,'down',1,-1),
('walk_away',6,{'down':True},0,64,85,'down',0,-1),
('return_to_door',6,{'up':True},0,64,77,'up',0,0),
('reenter_start',1,{},0,64,77,'up',0,0),
('cave_again',96,{},1,112,173,'up',1,-1),
]
def validate_probes():
room=json.loads((OUT/'room.json').read_text())
tiles=[t for row in room['tilemap'][8:] for t in row]
generated=(ROOT/'src/stages/cave_start/room.generated.pbs').read_text()
literal=generated.split('= [',1)[1].split('];',1)[0]
assert [int(v) for v in re.findall(r'\d+',literal)]==tiles
# Reuse the bounded original CPU routine, supplying this cave's column RAM.
collision.DATA['tiles']=tiles
for col in range(32):
ptr=collision.BASE[0xE400+col*2] | collision.BASE[0xE401+col*2]<<8
for row in range(22):collision.BASE[ptr+row]=tiles[row*32+col]
checked=0
for x in range(0,241,8):
for y in range(61,222,8):
for direction in (1,2,4,8):
if y==61 and direction==8:continue
expected=collision.rom_probe(x,y,direction)
actual=collision.port_probe(x,y,direction)
assert actual==expected,(x,y,direction,actual,expected)
checked+=1
return checked
def validate_frames():
hud=Image.open(ROOT/'extracted/hud/hud.png').convert('RGBA')
backgrounds=[Image.open(ROOT/'extracted/overworld/start/room.png').convert('RGBA'),
Image.open(OUT/'room.png').convert('RGBA')]
template=Image.open(ROOT/'extracted/hud/runtime_initial.png').convert('RGBA')
results=[]
for name,frames,buttons,stage,x,y,direction,phase,door in CHECKPOINTS:
expected=template.copy();expected.paste(backgrounds[stage],(112,15));expected.paste(hud,(112,15))
path=ROOT/f'assets/characters/link/walk_{direction}_{phase}.png'
if door>=0:path=ROOT/f'assets/characters/link_door/door_{door:02d}_{direction}_{phase}.png'
expected.alpha_composite(Image.open(path).convert('RGBA'),(112+x,15+y+3))
actual=Image.open(OUT/f'validation/{name}.png').convert('RGBA')
different=sum(p!=(0,0,0,0) for p in ImageChops.difference(actual,expected).getdata())
result={'checkpoint':name,'frames':frames,'input':buttons,'stage':stage,'x':x,'y':y,
'direction':direction,'animation_phase':phase,'door_step':door,'different_pixels':different}
results.append(result)
if different:
expected.save(OUT/f'validation/{name}.expected.png')
raise AssertionError(result)
return results
def main():
checked=validate_probes()
frames=validate_frames()
report={'rom_sha256':collision.ROM_SHA256,'cave_probes_compared':checked,'probe_mismatches':0,
'runtime_frames_compared':len(frames),'checkpoints':frames,
'scope':'Original collision leaf routine with cave column RAM; full-frame checkpoints of entry, cave walls, exit, idle without reentry and a second visit. Excludes full-game NES execution, video-copy waits and cave object interactions.'}
(OUT/'validation/results.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({'cave_probes_compared':checked,'runtime_frames_compared':len(frames),'different_pixels':0}))
if __name__=='__main__':main()
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Check dynamic composition against independent NES reference composites."""
import json
from PIL import Image
from extract_graphics import ROOT
from validate_cave import validate_probes
out=ROOT/'extracted/cave/start/composition-validation';checks=[]
expected={'initial':'room','outside-contact':'room','collected-person':'room_taken_person','blink-hidden':'room_taken','blink-person':'room_taken_person','expired':'room_taken','revisit':'room_taken','new-game':'room'}
for name,reference in expected.items():
actual=Image.open(out/(name+'.png')).convert('RGBA');assert actual.getpixel((0,0))==(0,255,0,255),name
target=Image.open(ROOT/f'extracted/cave/start/{reference}.png').convert('RGBA').crop((0,64,256,240));actual=actual.crop((112,79,368,255));diff=sum(a!=b for a,b in zip(actual.getdata(),target.getdata()));assert diff==0,(name,diff);checks.append({'name':name,'different_pixels':diff})
for name,reference in [('menu-initial','room'),('menu-collected','room_taken_person')]:
actual=Image.open(out/(name+'.png')).convert('RGBA');assert actual.getpixel((0,0))==(0,255,0,255)
# 25 menu advances yield offset 58: visible terrain starts at NES Y122.
target=Image.open(ROOT/f'extracted/cave/start/{reference}.png').convert('RGBA').crop((0,64,256,182));actual=actual.crop((112,137,368,255));diff=sum(a!=b for a,b in zip(actual.getdata(),target.getdata()));assert diff==0,(name,diff);checks.append({'name':name,'different_pixels':diff})
# None of the authored cave scenes contains actors or text, including reserved IDs.
for scene in ['cave_start','cave_taken_person','cave_taken']:
req=json.loads((ROOT/f'assets/scenes/{scene}/scene-bank.pack-request.json').read_text());assert req['layers'][0]['tiles']==json.loads((ROOT/'assets/scenes/cave_start/scene-bank.pack-request.json').read_text())['layers'][0]['tiles']
report={'pixel_checks':checks,'native_collision_probes':validate_probes(),'gameplay_assertions':['contact','sword ownership','room pickup bit','64-frame disappearance','menu pause','revisit','constant scene revision','constant inventory variant']}
(out/'report.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Execute the ROM's leaf collision routine with a bounded 6502 subset.
Not a NES emulator: only the opcodes reached by GetCollidingTileMoving for
player 0 in overworld room $77. Unsupported instructions fail explicitly.
"""
import hashlib
import json
import re
from extract_graphics import ROOT, ROM_SHA256
DATA = json.loads((ROOT / 'extracted/overworld/start/collision-data.json').read_text())
ROM = (ROOT / '.tmp/zelda-1.nes').read_bytes()
assert hashlib.sha256(ROM).hexdigest() == ROM_SHA256
BASE = bytearray(65536)
BASE[0xC000:] = ROM[16 + 7 * 16384:16 + 8 * 16384]
for col in range(32):
p = BASE[0xE400 + col * 2] | BASE[0xE401 + col * 2] << 8
for row in range(22):
BASE[p + row] = DATA['tiles'][row * 32 + col]
def rom_probe(x, y, direction, slot=0, room_id=0x77):
m = BASE.copy()
m[0x70+slot], m[0x84+slot], m[0x0F], m[0xEB] = x, y, direction, room_id
a, index = 0, slot
iy, sp, pc = 0, 0xFD, 0xEDFA
carry = zero = negative = False
def nz(v):
nonlocal zero, negative
v &= 255
zero, negative = v == 0, bool(v & 128)
return v
def byte():
nonlocal pc
v = m[pc]
pc += 1
return v
def word():
lo = byte()
return lo | byte() << 8
for _ in range(1000):
at = pc
op = byte()
if op == 0x60:
return a
if op in (0xF0, 0xD0, 0xB0, 0x90, 0x30):
offset = byte()
condition = {0xF0: zero, 0xD0: not zero, 0xB0: carry, 0x90: not carry, 0x30: negative}[op]
if condition:
pc += offset if offset < 128 else offset - 256
elif op == 0x4C: pc = word()
elif op == 0xA0: iy = nz(byte())
elif op == 0xA4: iy = nz(m[byte()])
elif op == 0xB4: iy = nz(m[(byte() + index) & 255])
elif op == 0xA9: a = nz(byte())
elif op == 0xA5: a = nz(m[byte()])
elif op == 0xB5: a = nz(m[(byte() + index) & 255])
elif op == 0xBD: a = nz(m[word() + index])
elif op == 0xB9: a = nz(m[word() + iy])
elif op == 0xB1:
p = byte()
a = nz(m[(m[p] | m[(p + 1) & 255] << 8) + iy])
elif op == 0x84: m[byte()] = iy
elif op == 0x85: m[byte()] = a
elif op == 0x8D: m[word()] = a
elif op == 0x9D: m[word() + index] = a
elif op == 0xA8: iy = nz(a)
elif op == 0x98: a = nz(iy)
elif op == 0x88: iy = nz(iy - 1)
elif op == 0x48:
m[0x100 + sp] = a
sp = (sp - 1) & 255
elif op == 0x68:
sp = (sp + 1) & 255
a = nz(m[0x100 + sp])
elif op == 0x18: carry = False
elif op == 0x38: carry = True
elif op == 0x29: a = nz(a & byte())
elif op == 0x25: a = nz(a & m[byte()])
elif op == 0x4A:
carry = bool(a & 1)
a = nz(a >> 1)
elif op in (0x69, 0x65, 0xE9):
v = m[byte()] if op == 0x65 else byte()
result = a + v + carry if op != 0xE9 else a - v - (not carry)
carry = result > 255 if op != 0xE9 else result >= 0
a = nz(result)
elif op in (0xE0, 0xC0, 0xC9, 0xD9, 0xDD):
lhs = index if op == 0xE0 else iy if op == 0xC0 else a
rhs = m[word() + iy] if op == 0xD9 else m[word() + index] if op == 0xDD else byte()
carry = lhs >= rhs
nz(lhs - rhs)
else:
raise AssertionError(f'Unsupported opcode ${op:02X} at ${at:04X}')
raise AssertionError('Collision routine did not return')
def port_probe(x, y, direction):
offset = {1: 16, 2: -8, 4: 8, 8: -8}[direction]
sx, sy = x, (y + 11) % 256
if direction in (4, 8):
if direction == 8 or sy < 221: sy = (sy + offset) % 256
elif (direction == 1 and x < 240) or (direction == 2 and x >= 16):
sx = (sx + offset) % 256
col, row = sx // 8, ((sy - 64) % 256) // 8
def tile(c, r):
return DATA['tiles'][r * 32 + c] if 0 <= c < 32 and 0 <= r < 22 else 255
value = tile(col, row)
if direction in (4, 8): value = max(value, tile(col + 1, row))
return 38 if value in DATA['walkable_exceptions'] else value
def main():
generated = (ROOT / "src/stages/overworld_start/room.generated.pbs").read_text()
literal = generated.split("= [", 1)[1].split("];", 1)[0]
assert [int(v) for v in re.findall(r"\d+", literal)] == DATA["tiles"]
checked = 0
# Only valid interior probes. The port closes exits, whereas the ROM can
# read adjacent column buffers there and then initiate a room transition.
for x in range(0, 241, 8):
for y in range(61, 222, 8):
for direction in (1, 2, 4, 8):
# At y=61, upward reads the HUD/buffer before the play area;
# that position is an exit, not a terrain query in this wave.
if y == 61 and direction == 8: continue
actual, expected = port_probe(x, y, direction), rom_probe(x, y, direction)
assert actual == expected, (x, y, direction, actual, expected)
checked += 1
report = {'rom_sha256': ROM_SHA256, 'room_id': 119,
'entrypoint': 'GetCollidingTileMoving ($EDFA)',
'probes_compared': checked, 'mismatches': 0,
'generated_pbs_tile_array_matches': True,
'scope': 'Leaf 6502 collision routine versus port model, interior grid probes; excludes screen transitions, cave triggers and whole-game execution.'}
(ROOT / 'extracted/overworld/start/collision-rom-validation.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report))
if __name__ == '__main__': main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Check Studio assertion output and visible combat states against ROM patterns."""
import json
from PIL import Image,ImageChops
from extract_graphics import ROOT,decode
from extract_start_room import RGB
from nes_object_graphics import P,item,descriptor,octorok
OUT=ROOT/'extracted/combat/validation'
RGB=dict(RGB);RGB.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
PPU=bytearray(8192)
for offset,length,address in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:PPU[address:address+length]=P[offset:offset+length]
ROWS=[list(P[103171+i*4:103175+i*4]) for i in range(8)]
def blank():
im=Image.open(ROOT/'extracted/hud/runtime_initial.png').convert('RGBA');im.paste(Image.open(ROOT/'extracted/overworld/north/room.png').convert('RGBA'),(112,15));return im
def sprite(info):
im=Image.new('RGBA',(16,16));offset=4 if info['sides']==1 else 0
for side in range(info['sides']):
t=info['tiles'][side];attr=info['attributes'][side];pal=ROWS[4+(attr&3)];start=(t&1)*4096+(t&254)*16
col=Image.new('RGBA',(8,16));col.putdata([(0,0,0,0) if v==0 else (*RGB[pal[v]],255) for n in (start,start+16) for v in decode(PPU[n:n+16])])
if attr&64:col=col.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if attr&128:col=col.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
im.paste(col,(offset+side*info['x_separation'],0))
return im
def place(im,slot,frame,palette,x,y,flip_x=False,flip_y=False):
info=item(slot,frame,palette+(128 if flip_y else 0),flip_x);im.alpha_composite(sprite(info),(112+x,16+y))
def counter(im,value,x,y):
# FormatDecimalCountByte: native HUD triplets, including leading X and space.
codes=[value//100,value//10%10,value%10] if value>=100 else [33,value//10,value%10] if value>=10 else [33,value,36]
for i,code in enumerate(codes):
glyph=Image.new('RGBA',(8,8));glyph.putdata([(*RGB[ROWS[0][v]],255) for v in decode(PPU[4096+code*16:4096+(code+1)*16])]);im.paste(glyph,(112+x+i*8,15+y))
def compare(name,expected):
actual=Image.open(OUT/(name+'.png')).convert('RGBA');diff=sum(v!=(0,0,0,0) for v in ImageChops.difference(actual,expected).getdata());assert diff==0,(name,diff);return {'capture':name,'different_pixels':diff}
def beams(clock):
im=blank()
for direction,pal,x in [(8,0,24),(4,1,72),(2,2,120),(1,3,168)]:place(im,34,0 if direction in (4,8) else 1,pal,x,96+(3 if direction in (1,2) else 0),direction==2,direction==4)
for x,y,radius,pal in [(80,160,6,0),(168,160,12,2)]:
# Native spread corner attributes: 0, V, HV, H in drawing order.
for right,bottom in [(False,False),(False,True),(True,True),(True,False)]:
place(im,35,2,pal+(64 if right else 0),x+(radius if right else -radius),y+(radius if bottom else -radius),False,bottom)
table=P.index(bytes.fromhex('01fffe02ffff'));width=[v if v<128 else v-256 for v in P[table:table+4]];height=[v if v<128 else v-256 for v in P[table+2:table+6]]
for col in range(4):
x=48+col*48+width[col]*clock;y=208+height[col]*clock
im.alpha_composite(sprite(descriptor(0x53)),(112+x,16+y))
return im
def find_sprite(actual,template):
a=actual.crop((112,79,368,255)).convert('RGBA');pixels=a.load()
support=[(x,y,c) for y in range(16) for x in range(16) if (c:=template.getpixel((x,y)))[3]]
x0,y0,color=support[0]
return [(x,y+64) for y in range(161) for x in range(241) if pixels[x+x0,y+y0]==color and all(pixels[x+dx,y+dy]==c for dx,dy,c in support)]
def verify_live():
evidence=[]
for name,count in [('three_enemies_return',3),('third_enemy_down',1),('collect_heart',1),('room_cleared_confirm',0),('cleared_room_stays_empty',0)]:
actual=Image.open(OUT/(name+'.png')).convert('RGBA');actors=set()
for phase in range(2):
for direction in ('left','up','down','right'):actors.update(find_sprite(actual,sprite(octorok(direction,phase))))
assert len(actors)==count,(name,actors,count)
hearts=set();fairies=set()
for palette in (1,2):hearts.update(find_sprite(actual,sprite(item(25,0,palette))))
for phase in (0,1):fairies.update(find_sprite(actual,sprite(item(20,phase,2))))
if name=='third_enemy_down':assert len(hearts)==1
if name=='collect_heart':assert not hearts
if name=='room_cleared_confirm':assert len(fairies)==1
if name=='cleared_room_stays_empty':assert not hearts and not fairies
evidence.append({'capture':name,'octoroks':len(actors),'hearts':len(hearts),'fairies':len(fairies)})
return evidence
def main():
meta=json.loads((OUT/'fixture-metadata.json').read_text());a=Image.open(OUT/'fixture_assertions.png').convert('RGB');encoded=a.getpixel((475,268));count=encoded[0]*256+encoded[1];assert count==meta['top_level_assertions'],(count,meta)
failures=[i+1 for i in range(count) if a.getpixel((i%160*3,i//160*3))!=(0,255,0)];assert not failures,failures;assert a.getpixel((478,268))==(0,255,0)
im=blank()
for slot,phase,palette,x,y in [(1,0,1,24,96),(28,0,1,64,96),(22,0,1,104,96),(22,0,2,144,96),(25,0,1,184,96),(25,0,2,24,144),(20,0,2,64,144),(20,1,2,104,144)]:place(im,slot,phase,palette,x,y)
for value,x in [(0,24),(9,64),(23,104),(123,144),(255,184)]:counter(im,value,x,24)
checks=[compare('fixture_items',im),compare('fixture_beams',beams(1)),compare('fixture_bounces_8',beams(8))]
before=Image.open(ROOT/'extracted/game_flow/validation/new_game_ready.png').convert('RGBA');checks.append(compare('initial',before))
live=verify_live()
report={'live_session':live,'guest_assertions':count,'failures':0,'visual_comparisons':checks,'scope':'Saved Studio fixture and production initial frame, composed using original item descriptor code, CHR, palettes and bounce table; no complete NES timing-equivalence claim.'};(OUT/'results.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':main()
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Execute bounded original 6502 history/drop routines; emit PBS oracle cases."""
import json
from extract_graphics import ROOT
from nes_object_graphics import P
MOD=P.index(bytes.fromhex('a005a5ebd92106f013'))
SAVE=P.index(bytes.fromhex('20cee629078502b10029f8'),MOD)
DROP=P.index(bytes.fromhex('a9008501bd1204a006'))
END=P.index(bytes.fromhex('a50095acc923d0034c'),DROP)
FAIRY=int.from_bytes(P[END+9:END+11],'little')
DESTROY=int.from_bytes(P[END+13:END+15],'little')
def cpu_addr(offset):return 0x8000+offset%16384
class CPU:
def __init__(self,bank):
self.m=bytearray(65536);self.m[0x8000:0xc000]=P[bank*16384:(bank+1)*16384];self.m[0xc000:]=P[7*16384:]
self.a=self.y=0;self.x=1;self.c=self.z=self.n=False;self.pc=0;self.sp=253;self.depth=0
def nz(self,v):v &=255;self.z=v==0;self.n=v>=128;return v
def byte(self):v=self.m[self.pc];self.pc+=1;return v
def word(self):return self.byte()|self.byte()<<8
def push(self,v):self.m[256+self.sp]=v&255;self.sp=(self.sp-1)&255
def pop(self):self.sp=(self.sp+1)&255;return self.m[256+self.sp]
def run(self,entry,drop=False):
self.pc=cpu_addr(entry)
for _ in range(1000):
if drop and self.pc==DESTROY:return -1
if drop and self.pc==FAIRY:return 35
at=self.pc;op=self.byte()
if op==0x60:
if self.depth==0:return self.m[0xac+self.x] if drop else None
self.pc=(self.pop()|self.pop()<<8)+1;self.depth-=1
elif op==0x20:
target=self.word()
if target==0xe6ce:
self.m[0]=0;self.m[1]=16;self.y=self.m[0xeb];self.a=self.nz(self.m[0x1000+self.y])
else:raise AssertionError(f'Unstubbed external call {target:04x}')
elif op==0x4c:self.pc=self.word()
elif op in (0xf0,0xd0,0x90,0xb0,0x10,0x30):
d=self.byte();take={0xf0:self.z,0xd0:not self.z,0x90:not self.c,0xb0:self.c,0x10:not self.n,0x30:self.n}[op]
if take:self.pc+=d if d<128 else d-256
elif op in (0xa9,0xa5,0xad,0xb5,0xbd,0xb9,0xb1):
if op==0xa9:v=self.byte()
elif op==0xa5:v=self.m[self.byte()]
elif op==0xad:v=self.m[self.word()]
elif op==0xb5:v=self.m[(self.byte()+self.x)&255]
elif op==0xbd:v=self.m[self.word()+self.x]
elif op==0xb9:v=self.m[self.word()+self.y]
else:q=self.byte();v=self.m[(self.m[q]|self.m[(q+1)&255]<<8)+self.y]
self.a=self.nz(v)
elif op in (0xa0,0xa4,0xac):self.y=self.nz(self.byte() if op==0xa0 else self.m[self.byte() if op==0xa4 else self.word()])
elif op in (0x85,0x95,0x9d,0x91):
if op==0x85:q=self.byte()
elif op==0x95:q=(self.byte()+self.x)&255
elif op==0x9d:q=self.word()+self.x
else:v=self.byte();q=(self.m[v]|self.m[(v+1)&255]<<8)+self.y
self.m[q]=self.a
elif op in (0xc9,0xc0,0xe0,0xd9,0xcd):
lhs=self.y if op==0xc0 else self.x if op==0xe0 else self.a
rhs=self.m[self.word()+self.y] if op==0xd9 else self.m[self.word()] if op==0xcd else self.byte()
self.c=lhs>=rhs;self.nz(lhs-rhs)
elif op==0x29:self.a=self.nz(self.a&self.byte())
elif op==0x11:
q=self.byte();self.a=self.nz(self.a|self.m[(self.m[q]|self.m[(q+1)&255]<<8)+self.y])
elif op in (0x65,0x6d):
v=self.m[self.byte() if op==0x65 else self.word()]+self.a+self.c;self.c=v>255;self.a=self.nz(v)
elif op==0xe5:
v=self.a-self.m[self.byte()]-(not self.c);self.c=v>=0;self.a=self.nz(v)
elif op==0xe6:q=self.byte();self.m[q]=self.nz(self.m[q]+1)
elif op==0x88:self.y=self.nz(self.y-1)
elif op==0x18:self.c=False
elif op==0x38:self.c=True
elif op==0xa8:self.y=self.nz(self.a)
else:raise AssertionError(f'Unsupported ${op:02X} at ${at:04X}')
raise AssertionError('Routine did not return')
def remaining(flags,count,present):
c=CPU(5);c.m[0xeb]=103;c.m[0x1000+103]=flags;c.m[3]=count
if present:c.m[0x621]=103
c.run(MOD);return c.m[3],c.m[0x1000+103]
def save(flags,spawned,killed):
c=CPU(5);c.m[0xeb]=103;c.m[0x1000+103]=flags;c.m[0x34e]=spawned;c.m[0x34f]=killed
c.run(SAVE);return c.m[0x1000+103]
def drop(monster,cycle,r,kills,help_count,help_bomb):
c=CPU(4);c.m[0x412+1]=monster;c.m[0x52a]=cycle;c.m[0x19]=r;c.m[0x627]=kills;c.m[0x50]=help_count;c.m[0x51]=help_bomb
value=c.run(DROP,True);return value,c.m[0x50],c.m[0x51]
def main():
meta=json.loads((ROOT/'extracted/combat/rom-data.json').read_text());history=[];saves=[];drops=[]
for flag_high in (0,16,168):
for low in range(8):
flags=flag_high+low
for count in range(5):
for present in (False,True):
result=remaining(flags,count,present);k=low
if not present and k==7:k=0
expected=(max(0,count-k) if k!=7 else 0,flag_high+k)
assert result==expected,(flags,count,present,result,expected)
history.append([flags,count,present,*result])
for spawned in range(5):
for killed in range(6):
result=save(flags,spawned,killed);expected=flag_high+(7 if killed>=spawned or low+killed>=7 else low+killed)
assert result==expected;saves.append([flags,spawned,killed,result])
for cycle in range(10):
for r in range(256):
for kills,help_count,help_bomb in [(0,0,0),(9,9,0),(10,10,0),(10,10,1),(16,0,0)]:
result=drop(7,cycle,r,kills,help_count,help_bomb)
value=meta['items'][cycle];h=help_count;b=help_bomb
if kills==16:value=35;h=b=0
elif h>=10:value=0 if b else 15;h=b=0
elif r>=80:value=-1
assert result==(value,h,b),(cycle,r,kills,result,(value,h,b))
if r in (0,79,80,247,255):drops.append([cycle,r,kills,help_count,help_bomb,*result])
out=ROOT/'extracted/combat';report={'history_cases':len(history),'save_cases':len(saves),'drop_cases':10*256*5,'mismatches':0,'entrypoints':{'modify':hex(cpu_addr(MOD)),'save':hex(cpu_addr(SAVE)),'drop':hex(cpu_addr(DROP))},'scope':'Bounded original 6502 routines. GetRoomFlags supplies a test world-flags buffer; fairy setup and object destruction are exit boundaries. No full-game lockstep claim.'}
(out/'rom-validation.json').write_text(json.dumps(report,indent=2)+'\n');(out/'oracle-cases.json').write_text(json.dumps({'history':history,'saves':saves,'drops':drops},indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':main()
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Compare Studio captures with ROM patterns/OAM and existing gameplay assets."""
import json
from PIL import Image,ImageChops,ImageDraw
from extract_graphics import ROOT,decode
from extract_start_room import RGB
from validate_life_captures import canvas,body
OUT=ROOT/'extracted/game_flow'
META=json.loads((OUT/'rom-data.json').read_text())
P=(ROOT/'.tmp/zelda-1.nes').read_bytes()[16:]
RGB=dict(RGB);RGB.update({16:(188,188,188),8:(80,48,0),40:(248,216,120),59:(160,252,224),34:(104,136,252),7:(136,20,0),12:(0,64,88),28:(0,136,136),44:(88,248,216),41:(56,184,0),38:(248,120,88),21:(164,0,164)})
patterns=bytearray(8192)
for offset,length,address in [(32895,1792,0),(34687,1792,4096),(36479,224,7968),(19892,2304,1792),(22196,2080,5888)]:patterns[address:address+length]=P[offset:offset+length]
def tile(n,row,base=4096,transparent=False):
im=Image.new('RGBA',(8,8));im.putdata([(0,0,0,0) if transparent and v==0 else (*RGB[row[v]],255) for v in decode(patterns[base+n*16:base+(n+1)*16])]);return im
def frame(im):
out=Image.open(ROOT/'extracted/hud/runtime_initial.png').convert('RGBA');out.paste(im,(112,15));return out
def title(clock):
memory=bytearray(16384);memory[8192:10240]=bytes([36])*2048;o=META['title']['prg_offset']
while P[o]<128:
a=P[o]*256+P[o+1];c=P[o+2];n=c&63 or 64;o+=3
for i in range(n):memory[a+i*(32 if c&128 else 1)]=P[o if c&64 else o+i]
o+=1 if c&64 else n
glow=timer=nxt=0;waves=[182,200,216]
for _ in range(clock):
if timer==0:
glow=nxt;nxt+=1;timer=6
if nxt==8:nxt=0;timer=16
timer-=1;waves=[178 if y+2>=227 else y+2 for y in waves]
rows=[list(r) for r in META['native_palettes']];rows[1][2]=META['glow_colors'][glow]
im=Image.new('RGBA',(256,240))
for y in range(30):
for x in range(32):
attr=memory[9152+(y//4)*8+x//4];pal=(attr>>(((y%4)//2)*4+((x%4)//2)*2))&3
im.paste(tile(memory[8192+y*32+x],rows[pal]),(x*8,y*8))
sprites=list(META['initial_oam'])
for y in waves:
offset=0 if y<185 else 8 if y<194 else 16
sprites.extend([y,t+offset,0,x] for t,x in zip((178,180,182,184),(80,88,96,104)))
sprites.extend([168,t+(clock//8%2)*8,0,x] for t,x in zip((162,164,166,168),(80,88,96,104)))
for y,t,a,x in reversed(sprites):
s=Image.new('RGBA',(8,16));s.paste(tile(t,rows[4+(a&3)],0,True),(0,0));s.paste(tile(t+1,rows[4+(a&3)],0,True),(0,8))
if a&64:s=s.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if a&128:s=s.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
im.alpha_composite(s,(x,y+1))
return frame(im)
def menu(selection=0,flash=False):
o=P.index(bytes.fromhex('3f00200f3000120f1627360f0c1c2c0f121c2c0f2927070f2227070f2627070f152730ff'))+3
rows=[list(P[o+i*4:o+i*4+4]) for i in range(8)];im=Image.new('RGBA',(256,240),(0,0,0,255))
for k,(word,address) in enumerate(zip(('CONTINUE','RETRY'),META['continue_label_addresses'])):
for i,c in enumerate(word):im.paste(tile(ord(c)-ord('A')+10,rows[1 if flash and selection==k else 0]),(((address-8192)%32+i)*8,(address-8192)//32*8))
im.alpha_composite(tile(242,rows[6],transparent=True),(80,40 if selection==0 else 72));return frame(im)
def game(owned=False,width=256,cave=False):
bg=ROOT/('extracted/cave/start/room_taken.png' if cave and owned else 'extracted/cave/start/room.png' if cave else 'extracted/overworld/start/room.png')
im=canvas(bg,34,255,owned,False);body(im,'up',1 if cave else 0,112 if cave else 120,176 if cave else 144,0)
if width<256:
n=(256-width)//2;d=ImageDraw.Draw(im);d.rectangle((112,79,112+n-1,254),fill=(0,0,0,255));d.rectangle((368-n,79,367,254),fill=(0,0,0,255))
return im
checks=[]
def check(name,expected):
actual=Image.open(OUT/f'validation/{name}.png').convert('RGBA');diff=sum(v!=(0,0,0,0) for v in ImageChops.difference(actual,expected).getdata());assert diff==0,(name,diff);checks.append({'capture':name,'different_pixels':diff})
for n in (6,7,8,13,25,31,43,58,59,64,512):check(f'title_{n}',title(n))
for name,n in [('title_first',1),('title_ignored_controls',542),('play_title',1),('return_title',0),('title_after_retry',1)]:check(name,title(n))
for name,s,f in [('continue_menu',0,False),('confirm_continue',0,False),('continue_flash',0,True),('continue_wait_last',0,False),('retry_menu',0,False),('select_retry',1,False),('hold_select',1,False),('confirm_retry',1,False),('retry_flash',1,True)]:check(name,menu(s,f))
for name,owned,width in [('unfurl_first',False,16),('unfurl_mid',False,128),('unfurl_ready',False,256),('new_game_curtain',False,16),('new_game_ready',False,256),('continue_curtain',True,16),('continue_ready',True,256),('retry_new_curtain',False,16),('retry_new_ready',False,256)]:check(name,game(owned,width))
for name,owned in [('cave_ready',False),('cave_owned_again',True),('new_game_cave',False)]:check(name,game(owned,cave=True))
(OUT/'validation/results.json').write_text(json.dumps({'pixel_comparisons':checks,'scope':'Saved Studio captures; independent ROM title/menu composition, gameplay composition from previously verified assets. No complete NES emulator equivalence claim.'},indent=2)+'\n')
print(f'{len(checks)} captures match pixel-for-pixel')
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Compare saved Studio frames against extracted HUD and existing stage renders."""
import json
from PIL import Image, ImageChops
from extract_graphics import ROOT
def main():
output = ROOT / 'extracted/hud'
hud = Image.open(output / 'hud.png').convert('RGBA')
baseline = ROOT / 'extracted/overworld/start/collision-validation'
results = []
for name, original in [('initial', 'initial'), ('down_wall', 'down_wall'), ('up_edge', 'up_exit_closed')]:
expected = Image.open(baseline / f'{original}.png').convert('RGBA')
expected.paste(hud, (112, 15))
actual = Image.open(output / f'runtime_{name}.png').convert('RGBA')
differences = sum(p != (0, 0, 0, 0) for p in ImageChops.difference(actual, expected).getdata())
results.append({'case': name, 'different_pixels': differences})
assert differences == 0, results[-1]
expected = Image.open(baseline / 'initial.png').convert('RGBA')
expected.paste(Image.open(ROOT / 'extracted/overworld/start/room.png').convert('RGBA'), (112, 15))
expected.paste(hud, (112, 15))
# 200 up ticks reach (120,61). Five attack ticks: body phase 0, extended sword.
sword = Image.open(ROOT / 'assets/characters/link/sword_up.png').convert('RGBA')
body = Image.open(ROOT / 'assets/characters/link/attack_up_0.png').convert('RGBA')
expected.alpha_composite(sword, (112 + 119, 15 + 52))
expected.alpha_composite(body, (112 + 120, 15 + 64))
actual = Image.open(output / 'runtime_up_attack.png').convert('RGBA')
differences = sum(p != (0, 0, 0, 0) for p in ImageChops.difference(actual, expected).getdata())
results.append({'case': 'up_attack_over_hud', 'different_pixels': differences})
assert differences == 0, results[-1]
report = {'compared': len(results), 'results': results,
'scope': 'Full Prometeu frames versus ROM-derived HUD plus prior stage renders; includes sword above HUD background. Not a comparison with whole-game NES execution.'}
(output / 'runtime-validation.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report))
if __name__ == '__main__': main()
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Compare the complete first-sword playthrough to ROM-derived render states."""
import json
import re
from PIL import Image, ImageChops
from extract_graphics import ROOT, ROM_SHA256
# name, room variant (OW/full cave/person/fires), x, y, direction, phase,
# owned sword, action, doorway step
CHECKPOINTS=[
('initial',0,120,133,'down',0,False,'walk',-1),
('unarmed_a',0,120,133,'down',0,False,'walk',-1),
('release_initial',0,120,133,'down',0,False,'walk',-1),
('approach_left',0,65,133,'left',1,False,'walk',-1),
('door_ready',0,64,77,'up',0,False,'walk',-1),
('cave_ready',1,112,173,'up',1,False,'walk',-1),
('cave_unarmed_a',1,112,173,'up',1,False,'walk',-1),
('cave_release',1,112,173,'up',1,False,'walk',-1),
('align_sword',1,120,173,'right',0,False,'walk',-1),
('outside_pickup',1,120,158,'up',0,False,'walk',-1),
('pickup_first',2,120,157,'up',0,True,'lift',-1),
('lift_input_lock',2,120,157,'up',0,True,'lift',-1),
('lift_tick127',3,120,157,'up',0,True,'lift',-1),
('lift_tick128',3,120,157,'up',0,True,'walk',-1),
('held_a_after_lift',3,120,157,'up',0,True,'walk',-1),
('release_lift',3,120,157,'up',0,True,'walk',-1),
('armed_attack',3,120,157,'up',0,True,'attack',-1),
('attack_recovered',3,120,157,'up',1,True,'walk',-1),
('exit_ready',0,64,93,'down',0,True,'walk',16),
('exit_start',0,64,92,'down',0,True,'walk',15),
('overworld_owned',0,64,77,'down',0,True,'walk',-1),
('walk_away',0,64,85,'down',1,True,'walk',-1),
('return_door',0,64,77,'up',0,True,'walk',0),
('cave_revisited',3,112,173,'up',1,True,'walk',-1),
('realign',3,120,173,'right',0,True,'walk',-1),
('no_second_pickup',3,120,157,'up',0,True,'walk',-1),
('new_game',0,120,133,'down',0,False,'walk',-1),
('new_game_cave',1,112,173,'up',1,False,'walk',-1),
]
def validate_grade_leaf(prg):
# Execute HandleClass2 for Y=0 (sword), including its real branch to RTS.
entry=prg.index(bytes.fromhex('a50ad957069020995706c00bd019'))
results=[]
for current in range(4):
for grade in (1,2,3):
pc,a,value,carry,zero=entry,0,current,False,False
for _ in range(16):
op=prg[pc];pc+=1
if op==0x60: break
if op==0xA5:
assert prg[pc]==10;pc+=1;a=grade
elif op==0xD9:
assert prg[pc:pc+2]==bytes.fromhex('5706');pc+=2
carry,zero=a>=value,a==value
elif op==0x99:
assert prg[pc:pc+2]==bytes.fromhex('5706');pc+=2;value=a
elif op==0xC0:
rhs=prg[pc];pc+=1;carry,zero=0>=rhs,0==rhs
elif op in (0x90,0xD0):
offset=prg[pc];pc+=1
if (op==0x90 and not carry) or (op==0xD0 and not zero):
pc+=offset if offset<128 else offset-256
else: raise AssertionError((hex(op),pc-1))
else: raise AssertionError('HandleClass2 did not return')
assert value==max(current,grade)
results.append({'before':current,'taken_grade':grade,'after':value})
return results
def main():
out=ROOT/'extracted/inventory';metadata=json.loads((out/'rom-data.json').read_text())
assert metadata['rom_sha256']==ROM_SHA256
prg=(ROOT/'.tmp/zelda-1.nes').read_bytes()[16:]
grade_cases=validate_grade_leaf(prg)
for key in ('item_slots','item_descriptors'):
offset=metadata['prg_offsets'][key]
assert list(prg[offset:offset+36])==metadata[key]
assert metadata['item_slots'][1:4]==[0,0,0]
assert metadata['item_descriptors'][1:4]==[0x21,0x22,0x23]
assert metadata['new_game_items'][0]==0 and len(metadata['new_game_items'])==40
generated=(ROOT/'src/inventory/items.generated.pbs').read_text()
for name,values in [('item_slots',metadata['item_slots']),('item_descriptors',metadata['item_descriptors']),('new_game_items',metadata['new_game_items'])]:
literal=re.search(name+r': array<int> = \[([^]]*)\]',generated).group(1)
assert list(map(int,re.findall(r'\d+',literal)))==values
backgrounds=[ROOT/'extracted/overworld/start/room.png',ROOT/'extracted/cave/start/room.png',
ROOT/'extracted/cave/start/room_taken_person.png',ROOT/'extracted/cave/start/room_taken.png']
backgrounds=[Image.open(p).convert('RGBA') for p in backgrounds]
armed=Image.open(ROOT/'extracted/hud/hud.png').convert('RGBA')
unarmed=Image.open(ROOT/'extracted/hud/hud_unarmed.png').convert('RGBA')
template=Image.open(ROOT/'extracted/hud/runtime_initial.png').convert('RGBA')
results=[]
for name,room,x,y,direction,phase,owned,action,door in CHECKPOINTS:
expected=template.copy();expected.paste(backgrounds[room],(112,15));expected.paste(armed if owned else unarmed,(112,15))
def sprite(path,sx,sy):expected.alpha_composite(Image.open(ROOT/path).convert('RGBA'),(112+sx,15+sy))
if action=='lift':
sprite('assets/characters/link_pickup/lift_sword.png',x,y+1)
sprite('assets/characters/link_pickup/wooden_sword.png',x,y-15)
else:
if action=='attack':sprite('assets/characters/link/sword_up.png',x-1,y-9)
path=f'assets/characters/link/{action}_{direction}_{phase}.png'
if door>=0:path=f'assets/characters/link_door/door_{door:02d}_{direction}_{phase}.png'
sprite(path,x,y+3)
actual=Image.open(out/f'validation/{name}.png').convert('RGBA')
differences=sum(v!=(0,0,0,0) for v in ImageChops.difference(actual,expected).getdata())
result={'checkpoint':name,'room_variant':room,'x':x,'y':y,'direction':direction,'phase':phase,
'sword_level':1 if owned else 0,'action':action,'different_pixels':differences}
assert differences==0,result
results.append(result)
report={'rom_sha256':ROM_SHA256,'rom_tables_verified':True,'items_slots':40,'room_item_mask':16,
'captures_compared':len(results),'equipment_grade_rom_cases':grade_cases,'checkpoints':results,
'scope':'Live guest path: unarmed inputs, exact pickup threshold, lift at ticks 1/127/128, input lock, held-A edge, armed attack, room-flag persistence on reentry. Inventory tables/defaults checked against ROM; other item effects and full NES execution excluded.'}
(out/'validation/results.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({'captures_compared':len(results),'different_pixels':0,'rom_tables_verified':True,'equipment_grade_rom_cases':len(grade_cases)}))
if __name__=='__main__':main()
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Compare owned item pixels against descriptors executed from the native ROM."""
from PIL import Image
from extract_graphics import ROOT,decode
from nes_object_graphics import P,item
import json
meta=json.loads((ROOT/'extracted/inventory_screen/rom-data.json').read_text())
# Native graphics transfers, separate from the generated glyph-bank mapping.
patterns=bytearray(8192)
for pos,size,dest in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[dest:dest+size]=P[pos:pos+size]
from extract_start_room import RGB
colors=dict(RGB);colors.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
# Read the NES palette indices, never generated runtime palette values.
palettes=meta['palettes'][4:8]
def sprite(slot,x,y,grade=1):
attr=P[meta['item_attrs_prg']+slot]
if slot in (0,2,4,7,11):attr=(attr+grade)&255
if slot==15:attr=1
d=item(slot,0,attr); pixels={}
for side in range(d['sides']):
tile=d['tiles'][side];flags=d['attributes'][side];base=(tile&1)*4096+(tile&254)*16
values=decode(patterns[base:base+16])+decode(patterns[base+16:base+32])
for py in range(16):
for px in range(8):
v=values[(15-py if flags&128 else py)*8+(7-px if flags&64 else px)]
if v:
sx=x+(4 if d['sides']==1 else side*d['x_separation'])+px;sy=y+1+py
pixels[sx,sy]=colors[palettes[flags%4][v]]
return pixels
if __name__=='__main__':
import sys
path=ROOT/'extracted/inventory_screen/validation'/ (sys.argv[1] if len(sys.argv)>1 else 'owned.png')
actual=Image.open(path).convert('RGB').crop((112,15,368,255));expected={}
xs=[128,152,172,180,200,128,152,176,200,128,148,160,176,192,204,176]
expected.update(sprite(30,128,54));expected.update(sprite(30,64,54))
for slot in range(1,15):expected.update(sprite(slot,xs[slot],54 if slot<5 else 70 if slot<9 else 30))
# Cursor overlays the boomerang at 128,55; skip its rectangle only.
errors=[(p,v,actual.getpixel(p)) for p,v in expected.items() if not(128<=p[0]<144 and 55<=p[1]<71) and actual.getpixel(p)!=v]
assert not errors,errors[:15]
print('Native item descriptor pixels match:',len(expected),'opaque samples (cursor excluded)')
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Bounded native selection oracle; uses the actual ROM instruction stream."""
import json,random
from nes_object_graphics import P
from extract_graphics import ROOT
ENTRY=P.index(bytes.fromhex('85efa20920'),5*16384,6*16384)
def select(slots,start,direction):
m=bytearray(65536);m[0x8000:0xc000]=P[5*16384:6*16384];m[0x657:0x67f]=bytes(slots)
pc=0x8000+ENTRY%16384;a=direction;x=0;y=start;z=n=c=False;stack=[]
def nz(v):
nonlocal z,n
v &=255;z=v==0;n=v>=128;return v
def byte():
nonlocal pc
v=m[pc];pc+=1;return v
def word():return byte()|byte()<<8
for _ in range(1000):
at=pc;op=byte()
if op==0x60:
if not stack:return m[0x656]
pc=stack.pop()
elif op==0x20:
target=word();stack.append(pc);pc=target
elif op==0x4c:pc=word()
elif op==0x85:m[byte()]=a
elif op==0x8c:m[word()]=y
elif op==0xa2:x=nz(byte())
elif op==0xa0:y=nz(byte())
elif op==0xa5:a=nz(m[byte()])
elif op==0xad:a=nz(m[word()])
elif op==0xb9:a=nz(m[word()+y])
elif op==0xc0:
v=byte();c=y>=v;nz(y-v)
elif op==0x29:a=nz(a&byte())
elif op==0x4a:c=bool(a&1);a=nz(a>>1)
elif op==0xca:x=nz(x-1)
elif op==0x88:y=nz(y-1)
elif op==0xc8:y=nz(y+1)
elif op in (0xf0,0xd0,0x10,0x90,0xb0):
d=byte();take={0xf0:z,0xd0:not z,0x10:not n,0x90:not c,0xb0:c}[op]
if take:pc+=d if d<128 else d-256
else:raise AssertionError(f'Unsupported {op:02x} at {at:04x}')
raise AssertionError('Unbounded native selection')
def main():
cases=[];rng=random.Random(1986)
inventories=[[0]*40]
for slot in (1,2,3,7,15,29,30):
s=[0]*40;s[slot]=1;inventories.append(s)
for _ in range(24):
s=[0]*40
for slot in (1,2,3,4,5,6,7,8,15,29,30):s[slot]=rng.randrange(2)
inventories.append(s)
for s in inventories:
for start in (0,1,2,3,6,7,8):
for direction in (1,2,3,4,8):
# Native arrow without bow and direction 0 loops forever. Avoid that invalid cursor state.
if direction>=4 and start==2 and s[2] and not s[3]:continue
cases.append([s,start,direction,select(s,start,direction)])
out=ROOT/'extracted/inventory_screen/selection-oracle.json';out.write_text(json.dumps({'entry_prg':ENTRY,'cases':cases},indent=2)+'\n')
print(len(cases),'native selection cases')
if __name__=='__main__':main()
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Validate guest assertions, original heart placement, palettes and gameplay."""
import json
from PIL import Image,ImageChops
from extract_graphics import ROOT
from assemble_link import COLORS
OUT=ROOT/'extracted/life'
def canvas(background,packed,partial,owned,fixture=True):
expected=Image.open(ROOT/'extracted/hud/runtime_initial.png').convert('RGBA')
expected.paste(Image.open(background).convert('RGBA'),(112,15))
hud=Image.open(ROOT/('extracted/hud/hud.png' if owned else 'extracted/hud/hud_unarmed.png')).convert('RGBA')
# Original formatter emits top row backwards, then bottom row backwards.
for y in range(40,56):
for x in range(176,240):hud.putpixel((x,y),(0,0,0,255))
full=packed%16;containers=packed//16
for ordinal in range(16):
status='blank'
if packed and ordinal>=15-containers:
if ordinal<15-full:status='empty'
elif ordinal>15-full or partial>=128:status='full'
elif partial:status='half'
else:status='empty'
x=(7-ordinal if ordinal<8 else 15-ordinal)*8+176
y=40 if ordinal<8 else 48
hud.paste(Image.open(ROOT/f'assets/ui/life/heart-{status}.png').convert('RGBA'),(x,y))
expected.paste(hud,(112,15))
if fixture:expected.putpixel((0,0),(0,255,0,255))
return expected
def body(expected,direction,phase,x,y,palette):
im=Image.open(ROOT/f'assets/characters/link/walk_{direction}_{phase}.png').convert('RGBA')
entries=json.loads((ROOT/'assets/characters/link/asset.json').read_text())['output']['pipeline']['palettes']
colors=entries[palette]['palette']['rgba8888']
colors=[tuple(((c&0xffffffff)>>shift)&255 for shift in (24,16,8,0)) for c in colors]
lookup={color:colors[i] for i,color in enumerate(COLORS)}
im.putdata([lookup[v] for v in im.getdata()]);expected.alpha_composite(im,(112+x,15+y))
def compare(name,expected,path):
actual=Image.open(path).convert('RGBA')
differences=sum(v!=(0,0,0,0) for v in ImageChops.difference(actual,expected).getdata())
assert differences==0,(name,differences)
return {'name':name,'different_pixels':differences}
def main():
meta=json.loads((OUT/'fixture-cases.json').read_text());checks=[]
for item in meta['captures']:
name=item['name'];path=OUT/f'validation/fixture_{name}.png'
assert Image.open(path).convert('RGB').getpixel((0,0))==(0,255,0),name
if 'packed' in item:
expected=canvas(ROOT/'extracted/overworld/start/room.png',item['packed'],item['partial'],False)
palette=4 if '-r1-' in name else 5 if '-r2-' in name else 0
body(expected,'down',0,120,136,palette)
checks.append(compare(name,expected,path))
states={
'hurt':(120,34,127,1,'down','body'),
'immune':(120,34,127,2,'down','body'),
'immune_last':(152,34,127,3,'down','body'),
'hurt_again':(152,33,254,0,'down','body'),
'death_start':(184,32,0,0,'down','body'),
'death_spin':(184,32,0,0,'right','body'),
'death_grey':(184,32,0,6,'down','body'),
'death_spark':(184,32,0,0,'down','small'),
'death_large_spark':(184,32,0,0,'down','large'),
'death_blank':(184,32,0,0,'down','blank'),
'game_over':(184,32,0,0,'down','over'),
'continue_ready':(184,32,0,0,'down','over'),
'continued':(120,34,255,0,'up','continued')}
for name,(x,hv,hp,palette,direction,kind) in states.items():
bg=ROOT/'extracted/overworld/start/room.png'
if kind=='blank':bg=OUT/'death_blank.png'
elif kind=='over':bg=OUT/'game_over.png'
expected=canvas(bg,hv,hp,True)
if kind in ('body','continued'):body(expected,direction,0,x,144 if kind=='continued' else 136,palette)
elif kind in ('small','large'):
glyph='spark-98' if kind=='small' else 'spark-100'
expected.alpha_composite(Image.open(ROOT/f'assets/characters/death_sparks/{glyph}.png').convert('RGBA'),(112+x,149))
checks.append(compare(name,expected,OUT/f'validation/fixture_{name}.png'))
fire_checks=[]
for n in range(1,7):
path=OUT/('validation/play_first_fire_damage.png' if n==1 else f'validation/play_fire_hit_{n}.png')
actual=Image.open(path).convert('RGBA')
expected_status=[['full','full','half'],['full','full','empty'],['full','half','empty'],['full','empty','empty'],['half','empty','empty'],['empty','empty','empty']][n-1]
for i,status in enumerate(expected_status):
assert actual.crop((288+i*8,63,296+i*8,71)).tobytes()==Image.open(ROOT/f'assets/ui/life/heart-{status}.png').convert('RGBA').tobytes(),(n,status)
fire_checks.append({'hit':n,'hearts':expected_status})
expected=canvas(OUT/'game_over.png',32,0,False,False)
compare('natural-game-over',expected,OUT/'validation/play_game_over.png')
expected=canvas(ROOT/'extracted/overworld/start/room.png',34,255,False,False)
body(expected,'up',0,120,144,0)
compare('natural-continue',expected,OUT/'validation/play_continue.png')
report={'guest_arithmetic_cases':meta['arithmetic_cases'],'guest_final_frame':meta['final_frame'],
'fixture_captures':len(checks),'fixture_full_frame_differences':0,'checks':checks,
'natural_fire_hits':fire_checks,'natural_death_continue':True,'healthy_inventory_regression_frames':28,
'scope':'Fixture checks and full frames; real cave fire contacts and Start continue. Other heart/fairy world drops and full NES death fade/menu are outside this wave.'}
(OUT/'validation/results.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:report[k] for k in ('guest_arithmetic_cases','fixture_captures','fixture_full_frame_differences','natural_death_continue','healthy_inventory_regression_frames')}))
if __name__=='__main__':main()
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Bounded 6502 execution of original life arithmetic; generate PBS fixture cases."""
import hashlib,json
from pathlib import Path
from extract_graphics import ROOT,ROM_SHA256
P=(ROOT/'.tmp/zelda-1.nes').read_bytes()[16:]
assert hashlib.sha256((ROOT/'.tmp/zelda-1.nes').read_bytes()).hexdigest()==ROM_SHA256
DELTA=0x790
DAMAGE=P.index(bytes.fromhex('ac6206f007460d660e'))+DELTA
HEAL=P.index(bytes.fromhex('8501206c74d007ae7006'))+DELTA
class CPU:
def __init__(self,hv,hp,ring=0):
self.m=bytearray(65536);self.m[0x6c90:0x7f00]=P[0x6500:0x7770];self.m[0xc000:]=P[7*16384:]
self.m[0x66f]=hv;self.m[0x670]=hp;self.m[0x662]=ring
self.a=0;self.x=0;self.y=0;self.c=False;self.z=False;self.n=False;self.sp=253;self.depth=0;self.died=False
def nz(self,v):
v&=255;self.z=v==0;self.n=bool(v&128);return v
def byte(self):v=self.m[self.pc];self.pc+=1;return v
def word(self):lo=self.byte();return lo|self.byte()<<8
def push(self,v):self.m[256+self.sp]=v&255;self.sp=(self.sp-1)&255
def pop(self):self.sp=(self.sp+1)&255;return self.m[256+self.sp]
def run(self,entry):
self.pc=entry
for _ in range(3000):
at=self.pc;op=self.byte()
if op==0x60:
if self.depth==0:return self.m[0x66f],self.m[0x670],self.died
self.pc=(self.pop()|self.pop()<<8)+1;self.depth-=1
elif op==0x20:
target=self.word()
if not 0x6c90<=target<0x7f00:
# Damage's sole external call is EndGameMode; it returns A=0.
assert entry==DAMAGE
self.died=True;self.a=self.nz(0)
else:
self.push((self.pc-1)>>8);self.push(self.pc-1);self.pc=target;self.depth+=1
elif op in (0xf0,0xd0,0x90,0xb0,0x10,0x30):
d=self.byte();take={0xf0:self.z,0xd0:not self.z,0x90:not self.c,0xb0:self.c,0x10:not self.n,0x30:self.n}[op]
if take:self.pc+=d if d<128 else d-256
elif op==0xa9:self.a=self.nz(self.byte())
elif op==0xa5:self.a=self.nz(self.m[self.byte()])
elif op==0xad:self.a=self.nz(self.m[self.word()])
elif op==0xac:self.y=self.nz(self.m[self.word()])
elif op==0xae:self.x=self.nz(self.m[self.word()])
elif op==0x85:self.m[self.byte()]=self.a
elif op==0x8d:self.m[self.word()]=self.a
elif op==0x29:self.a=self.nz(self.a&self.byte())
elif op==0x38:self.c=True
elif op in (0xe5,0xed):
rhs=self.m[self.byte() if op==0xe5 else self.word()];v=self.a-rhs-(not self.c);self.c=v>=0;self.a=self.nz(v)
elif op==0xc5:
rhs=self.m[self.byte()];self.c=self.a>=rhs;self.nz(self.a-rhs)
elif op==0x46:
q=self.byte();v=self.m[q];self.c=bool(v&1);self.m[q]=self.nz(v>>1)
elif op==0x66:
q=self.byte();v=self.m[q];v2=(v>>1)|(128 if self.c else 0);self.c=bool(v&1);self.m[q]=self.nz(v2)
elif op==0x4a:self.c=bool(self.a&1);self.a=self.nz(self.a>>1)
elif op in (0xce,0xee,0xc6):
q=self.byte() if op==0xc6 else self.word();self.m[q]=self.nz(self.m[q]+(1 if op==0xee else -1))
elif op==0x88:self.y=self.nz(self.y-1)
elif op==0xe8:self.x=self.nz(self.x+1)
elif op==0x48:self.push(self.a)
elif op==0x68:self.a=self.nz(self.pop())
else:raise AssertionError(f'Unsupported ${op:02X} at ${at:04X}')
raise AssertionError('Routine did not return')
def damage(hv,hp,amount,ring=0):
cpu=CPU(hv,hp,ring);cpu.m[13]=amount//256;cpu.m[14]=amount%256;return cpu.run(DAMAGE)
def heal(hv,hp,hearts):
cpu=CPU(hv,hp);cpu.a=hearts-1;return cpu.run(HEAL)[:2]
def model_damage(hv,hp,amount,ring):
amount//=2**ring;full=hv%16;low=amount%256;high=amount//256
while hp<low:
low-=hp
if full==0:return hv&240,0,True
full-=1;hp=255
hp-=low
if full<high:return hv&240,0,True
return (hv&240)+full-high,hp,False
def main():
count=0;heals=0
for capacity in (3,5,8,16):
for full in range(capacity):
for fraction in (0,1,63,127,128,254,255):
hv=(capacity-1)*16+full
for amount in (1,32,64,128,255,256,257,384,512,1024,65535):
for ring in (0,1,2):
assert damage(hv,fraction,amount,ring)==model_damage(hv,fraction,amount,ring),(hv,fraction,amount,ring)
count+=1
for amount in (1,3,16):
f=full;hp=fraction
for _ in range(amount):
if f==capacity-1:hp=255;break
f+=1
assert heal(hv,fraction,amount)==((capacity-1)*16+f,hp)
heals+=1
out=ROOT/'extracted/life';out.mkdir(exist_ok=True)
(out/'rom-validation.json').write_text(json.dumps({'rom_sha256':ROM_SHA256,'damage_cases':count,'healing_cases':heals,'mismatches':0,'damage_entry':hex(DAMAGE),'heal_entry':hex(HEAL),'ram_copy':{'prg':0x6500,'cpu':0x6c90,'length':0x1270},'scope':'Bounded original 6502 life routines versus port arithmetic model; EndGameMode side effects outside life bytes are stubbed.'},indent=2)+'\n')
print(json.dumps({'damage_cases':count,'healing_cases':heals,'mismatches':0}))
if __name__=='__main__':main()
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Check the northern room and non-player probes against the ROM's 6502 leaf."""
import json,re
from extract_graphics import decode
from extract_start_room import RGB
from validate_life_captures import canvas,body
from PIL import Image,ImageChops
from extract_graphics import ROOT
import validate_collision_rom as leaf
from nes_object_graphics import descriptor,octorok
from validate_octorok_graphics import native_image
def verify_captures():
p=(ROOT/'.tmp/zelda-1.nes').read_bytes()[16:];patterns=bytearray(4096)
patterns[:1792]=p[32895:34687];patterns[1792:4096]=p[19892:22196];patterns[2272:4096]=p[53595:55419]
rgb=dict(RGB);rgb.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
rows=[list(p[103187+i*4:103191+i*4]) for i in range(4)]
def column(t,pal,flip=False):
im=Image.new('RGBA',(8,16));im.putdata([(0,0,0,0) if v==0 else (*rgb[rows[pal][v]],255) for n in (t,t+1) for v in decode(patterns[n*16:(n+1)*16])]);return im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) if flip else im
frames=[]
for phase in range(2):
for direction in ('left','up','down','right'):
frames.append((f'{direction}_{phase}',native_image(octorok(direction,phase))))
for i,t in enumerate((112,114,116)):
im=Image.new('RGBA',(16,16));im.paste(column(t,1),(0,0));im.paste(column(t,1,True),(8,0));frames.append((f'cloud_{i}',im))
frames.append(('rock',native_image(descriptor(0x53))))
checks=[]
for name in ('fixed_cloud_visible','fixed_north_actors','fixed_encounter_4'):
actual=Image.open(ROOT/f'extracted/overworld/north/validation/{name}.png').convert('RGBA');a=actual.crop((112,79,368,255)).convert('RGB');ap=a.load();found={}
for label,im in frames:
support=[(x,y,c[:3]) for y in range(16) for x in range(16) if (c:=im.getpixel((x,y)))[3]]
assert support,label
x0,y0,c0=support[0]
for y in range(161):
for x in range(241):
if ap[x+x0,y+y0]==c0 and all(ap[x+dx,y+dy]==color for dx,dy,color in support):found[(x,y+64)]=(label,im)
actors=[k for k,v in found.items() if v[0]!='rock'];assert len(actors)==4,(name,len(actors))
expected=canvas(ROOT/'extracted/overworld/north/room.png',34,255,False,False)
expected.paste(Image.open(ROOT/'assets/ui/hud/hud-north-marker.png').convert('RGBA'),(144,47))
body(expected,'up',0,120,224,0)
for (x,y),(label,im) in found.items():expected.alpha_composite(im,(112+x,15+y))
diff=sum(v!=(0,0,0,0) for v in ImageChops.difference(actual,expected).getdata());assert diff==0,(name,diff)
checks.append({'capture':name,'native_sprites':[{ 'x':x,'y':y,'frame':v[0]} for (x,y),v in found.items()],'different_pixels':diff})
return checks
def main():
room=json.loads((ROOT/'extracted/overworld/north/room.json').read_text())
tiles=[t for row in room['tilemap'][8:] for t in row]
leaf.DATA=dict(leaf.DATA,tiles=tiles,room_id=103)
for col in range(32):
addr=leaf.BASE[0xe400+col*2]|leaf.BASE[0xe401+col*2]<<8
for row in range(22):leaf.BASE[addr+row]=tiles[row*32+col]
source=(ROOT/'src/stages/overworld_north/room.generated.pbs').read_text()
assert list(map(int,re.findall(r'\d+',source.split('= [',1)[1].split('];',1)[0])))==tiles
def model(x,y,d,monster):
offset={1:16,2:-16 if monster else -8,4:8,8:-16 if monster else -8}[d]
sx=x;sy=(y+11)%256
if d in (4,8):
if d==8 or sy<221:sy=(sy+offset)%256
elif (d==1 and x<240) or (d==2 and x>=16):sx=(sx+offset)%256
col=sx//8;row=((sy-64)%256)//8
def tile(c,r):return tiles[r*32+c] if 0<=c<32 and 0<=r<22 else 255
value=tile(col,row)
if d in (4,8):value=max(value,tile(col+1,row))
return 38 if value in leaf.DATA['walkable_exceptions'] else value
counts={}
for slot in (0,1):
checked=0
for x in range(16,225,8):
for y in range(77,206,8):
for d in (1,2,4,8):
a=leaf.rom_probe(x,y,d,slot,103);b=model(x,y,d,slot!=0)
assert a==b,(slot,x,y,d,a,b);checked+=1
counts['player' if slot==0 else 'enemy']=checked
enemies=json.loads((ROOT/'extracted/overworld/north/enemies.json').read_text())
assert room['room_attributes']==[0x72,0x86,0x47,0x62,0x64,0x40]
assert enemies['type']==7 and enemies['count']==4
fixture=Image.open(ROOT/'extracted/overworld/north/validation/fixture.png').convert('RGB')
for i in range(32):assert fixture.getpixel((i%16*16+5,i//16*16+5))==(0,255,0),i+1
visual=verify_captures()
report={'visual_comparisons':visual,'room_id':103,'collision_probes':counts,'mismatches':0,'guest_assertions':32,'scope':'Leaf collision routine, raw room data and saved guest fixture; not full-game lockstep equivalence.'}
(ROOT/'extracted/overworld/north/validation/results.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':main()
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Validate all poses and a visible projectile against executed ROM descriptors."""
import json
from PIL import Image,ImageChops
from extract_graphics import ROOT,decode
from extract_start_room import RGB
from nes_object_graphics import P,ENTRY,STOP,descriptor,octorok
OUT=ROOT/'extracted/overworld/north/validation/graphics_fix'
def native_image(info,canonical=False):
patterns=bytearray(4096);patterns[:1792]=P[32895:34687];patterns[1792:4096]=P[19892:22196];patterns[2272:4096]=P[53595:55419]
rgb=dict(RGB);rgb.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)})
image=Image.new('RGBA',(16,16));offset=4 if info['sides']==1 else 0
for side in range(info['sides']):
attr=info['attributes'][side];pal=0 if canonical else attr&3
row=P[103187+pal*4:103191+pal*4];tile=info['tiles'][side]
column=Image.new('RGBA',(8,16));column.putdata([(0,0,0,0) if v==0 else (*rgb[row[v]],255) for n in (tile,tile+1) for v in decode(patterns[n*16:(n+1)*16])])
if attr&128:column=column.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
if attr&64:column=column.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
image.paste(column,(offset+side*info['x_separation'],0))
return image
def difference(a,b):
assert a.size==b.size
return sum(v!=(0,0,0,0) for v in ImageChops.difference(a,b).getdata())
def main():
OUT.mkdir(exist_ok=True,parents=True);checks=[];sheet=Image.new('RGBA',(256,176),(18,22,28,255))
expected=Image.open(ROOT/'extracted/hud/runtime_initial.png').convert('RGBA')
expected.paste(Image.open(ROOT/'extracted/overworld/north/room.png').convert('RGBA'),(112,15))
# Fixed regressions from the ROM descriptors, not a copied animation-heap offset.
native_tiles=[[180,176,176],[184,178,178]]
for phase in range(2):
for col,direction in enumerate(('left','up','down','right')):
info=octorok(direction,phase)
assert info['animation_index']==8
off={'left':0,'up':1,'down':2,'right':0}[direction]
assert info['tiles'][0]==native_tiles[phase][off]+(2 if direction=='right' else 0)
assert bool(info['attributes'][0]&128)==(direction=='up')
assert info['attributes'][0]&3==2
path=ROOT/f'assets/characters/octorok/octorok_{direction}_{phase}.png'
actual=Image.open(path).convert('RGBA');diff=difference(actual,native_image(info,True));assert diff==0,(path,diff)
im=native_image(info);expected.alpha_composite(im,(112+40+col*48,15+97+phase*48));sheet.alpha_composite(im.resize((48,48),Image.Resampling.NEAREST),(col*64,phase*64))
checks.append({'direction':direction,'phase':phase,'descriptor':info,'different_pixels':diff})
rock=descriptor(0x53);assert rock['animation_index']==84 and rock['tiles'][0]==158 and rock['sides']==1
diff=difference(Image.open(ROOT/'assets/characters/octorok/rock.png').convert('RGBA'),native_image(rock,True));assert diff==0
expected.alpha_composite(native_image(rock),(224,200));sheet.alpha_composite(native_image(rock).resize((48,48),Image.Resampling.NEAREST),(104,128));sheet.save(OUT/'preview.png')
actual=Image.open(OUT/'studio_fixture.png').convert('RGBA');runtime_diff=difference(actual,expected);assert runtime_diff==0,runtime_diff
report={'descriptor_entry_cpu':hex(ENTRY),'stop_before_sprite_emission_cpu':hex(STOP),'method':'Bounded original 6502 descriptor execution, including INY, native per-frame attributes, horizontal/vertical flips and half-width handling. All eight poses and an actually visible rock are rendered in the Studio fixture.','poses':checks,'rock':rock,'asset_comparisons':9,'runtime_different_pixels':runtime_diff}
(OUT/'results.json').write_text(json.dumps(report,indent=2)+'\n');print('9 native asset comparisons and full Studio fixture: 0 differing pixels')
if __name__=='__main__':main()
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Native edge-search oracle plus generated terrain/collision regression."""
import json,re
from pathlib import Path
from PIL import Image,ImageChops
from overworld_data import manifest,step_edge
from nes_object_graphics import P
from extract_graphics import ROOT
import validate_collision_rom as leaf
def native_edge(tiles,cell):
m=bytearray(65536);m[0x8000:0xc000]=P[5*16384:6*16384];m[0xc000:]=P[7*16384:8*16384];m[0x525]=cell
sig=bytes.fromhex('ad2505850aa010a50a290f');pc=0x8000+P[5*16384:6*16384].index(sig)
# Real code, with only the two address helpers substituted against a synthetic tilemap.
for col in range(32):
for row in range(22):m[0x1000+col*22+row]=tiles[row*32+col]
a=y=0;c=z=False
def nz(v):
nonlocal z
v&=255;z=v==0;return v
def byte():
nonlocal pc
v=m[pc];pc+=1;return v
def word():return byte()|byte()<<8
for _ in range(20000):
at=pc;op=byte()
if op==0x60:return m[0x525]
if op==0xad:a=nz(m[word()])
elif op==0xa5:a=nz(m[byte()])
elif op==0xa9:a=nz(byte())
elif op==0xa0:y=nz(byte())
elif op==0x85:m[byte()]=a
elif op==0x8d:m[word()]=a
elif op==0x29:a=nz(a&byte())
elif op in (0xc9,0xcd):
v=byte() if op==0xc9 else m[word()];c=a>=v;nz(a-v)
elif op in (0xf0,0xd0,0x90):
off=byte();yes=z if op==0xf0 else not z if op==0xd0 else not c
if yes:pc+=off if off<128 else off-256
elif op==0x98:a=nz(y)
elif op==0xa8:y=nz(a)
elif op==0x88:y=nz(y-1)
elif op==0x18:c=False
elif op==0x38:c=True
elif op in (0x65,0xe9):
v=m[byte()] if op==0x65 else byte();r=a+v+c if op==0x65 else a-v-(not c);c=r>255 if op==0x65 else r>=0;a=nz(r)
elif op in (0xe6,0xc6):
addr=byte();m[addr]=nz(m[addr]+(1 if op==0xe6 else -1))
elif op==0x4a:c=bool(a&1);a=nz(a>>1)
elif op==0x4c:pc=word()
elif op==0xb1:
p=byte();a=nz(m[(m[p]|m[(p+1)&255]<<8)+y])
elif op==0x20:
target=word()
if m[target:target+3]==bytes.fromhex('a5eb29') or target==fetch:
m[0]=0;m[1]=16
elif target==add:
value=(m[0]|m[1]<<8)+a;m[0]=value&255;m[1]=value>>8
else:raise AssertionError(hex(target))
else:raise AssertionError((hex(op),hex(at)))
raise AssertionError('Native edge search did not terminate')
# Native JSR operands from this exact verified routine, rather than recalled addresses.
start=P[5*16384:6*16384].index(bytes.fromhex('ad2505850aa010a50a290f'));code=P[5*16384+start:5*16384+start+150]
calls=[code[i+1]|code[i+2]<<8 for i in range(len(code)-2) if code[i]==0x20];fetch,add=calls[:2]
def main():
result={'rooms':[],'native_edge_cases':0,'collision_cases':0}
for e in manifest():
room=json.loads((ROOT/f'extracted/overworld/{e["name"]}/room.json').read_text());tiles=[v for row in room['tilemap'][8:] for v in row]
if e['managed']:
source=(ROOT/f'src/stages/{e["module"]}/room.generated.pbs').read_text();assert list(map(int,re.findall(r'\d+',source.split('= [')[1].split('];')[0])))==tiles
for col in range(32):
addr=leaf.BASE[0xe400+col*2]|leaf.BASE[0xe401+col*2]<<8
for row in range(22):leaf.BASE[addr+row]=tiles[row*32+col]
leaf.DATA=dict(leaf.DATA,tiles=tiles)
for y in range(77,206,8):
for x in range(16,225,8):
for d in (1,2,4,8):
actual=leaf.rom_probe(x,y,d,room_id=e['room']);expected=leaf.port_probe(x,y,d);assert actual==expected,(e,x,y,d,actual,expected);result['collision_cases']+=1
if e['stage']>=6:
cells={64};cell=64
for _ in range(80):cell=step_edge(cell);cells.add(cell)
for origin in cells:
cell=origin
for _ in range(64):
cell=step_edge(cell);col=cell%16*2;row=(cell//16*16-64)//8
if tiles[row*32+col]<132 or cell==origin:break
assert native_edge(tiles,origin)==cell,(e,origin);result['native_edge_cases']+=1
result['rooms'].append(e['room'])
(ROOT/'extracted/overworld/expansion/native-validation.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result))
if __name__=='__main__':main()
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
"""Compare native terrain to runtime output, including menu and both link ends."""
import json
from PIL import Image,ImageChops
from extract_graphics import ROOT
from overworld_data import manifest
OUT=ROOT/'extracted/overworld/expansion';caps=OUT/'validation';rooms={e['stage']:e for e in manifest()};checks=[]
def compare(name,actual,expected):
diff=sum(a!=b for a,b in zip(actual.convert('RGB').getdata(),expected.convert('RGB').getdata()));assert diff==0,(name,diff);checks.append({'capture':name,'different_pixels':diff})
def native(stage):return Image.open(ROOT/f'extracted/overworld/{rooms[stage]["name"]}/room.png').convert('RGB')
for p in caps.glob('*.png'):
if p.name.startswith('prod-'):continue
assert Image.open(p).getpixel((0,0))==(0,255,0,255),p.name
for i,(stage,e) in enumerate(rooms.items()):
name=f'room-{e["room"]:02x}';actual=Image.open(caps/(name+'.png'));compare(name,actual.crop((112,79,368,255)),native(stage).crop((0,64,256,240)))
actual=Image.open(caps/f'menu-{e["room"]:02x}.png');compare(f'menu-{i}',actual.crop((112,137,368,255)),native(stage).crop((0,64,256,182)))
marker=Image.open(ROOT/f'assets/ui/hud/world-marker-{e["room"]:02x}.png') if stage else Image.open(ROOT/'assets/ui/hud/hud_09.png')
# The map itself occupies the top-left HUD block; compare marker bank output.
compare(name+'-marker',Image.open(caps/(name+'.png')).crop((144,47,176,79)),marker)
for link in json.loads((OUT/'catalog.json').read_text())['links']:
for a,b in [(link['a'],link['b']),(link['b'],link['a'])]:
name=f'edge-{a}-{b}-end';actual=Image.open(caps/(name+'.png'));compare(name,actual.crop((112,79,368,255)),native(b).crop((0,64,256,240)))
report={'green_assertion_captures':len(list(caps.glob('*.png'))),'pixel_checks':checks};(OUT/'capture-validation.json').write_text(json.dumps(report,indent=2)+'\n');print('Native pixel checks:',len(checks),'all exact')
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Native wall/secret-cave pixels, including submenu and persistent reload."""
import json
from PIL import Image
from extract_graphics import ROOT
from nes_object_graphics import item
from validate_octorok_graphics import native_image
out=ROOT/'extracted/real_secret';caps=out/'validation';checks=[]
def validate(name,ref,ignore=(),offset=0,rupee=False):
actual=Image.open(caps/(name+'.png')).convert('RGBA');assert actual.getpixel((0,0))==(0,255,0,255),name
expected=Image.open(ref).convert('RGBA')
if rupee:
# Fixture clock is zero: the existing item animator selects blue palette 1.
info=item(22);info=dict(info,attributes=[(a&252)|1 for a in info['attributes']]);expected.paste((0,0,0,255),(120,153,136,169));expected.alpha_composite(native_image(info),(120,153))
bad=[]
for y in range(64+offset,240):
for x in range(256):
if any(x0<=x<x1 and y0<=y<y1 for x0,y0,x1,y1 in ignore):continue
if actual.getpixel((112+x,15+y))!=expected.getpixel((x,y-offset)):bad.append((x,y))
assert not bad,(name,len(bad),bad[:4]);checks.append({'capture':name,'different_pixels':0})
validate('wall-closed',ROOT/'extracted/overworld/north/room.png',[(112,109,128,129)])
validate('wall-open',out/'north-open.png',[(80,80,160,140)]) # Live bomb/effect around the portal; tested closed/open via raw tile assertions.
validate('cave-ready',out/'cave_available.png',[(112,173,128,193)],rupee=True)
validate('reward-credited',out/'cave_claimed.png',[(120,157,136,177)],rupee=True)
validate('cave-menu',out/'cave_available.png',offset=58,rupee=True)
validate('revisit',out/'cave_revisit.png',[(112,173,128,193)])
validate('reload-north',out/'north-open.png',[(112,109,128,129)])
validate('reload-cave',out/'cave_revisit.png',[(112,109,128,129)])
for p in caps.glob('*.png'):
if p.name.startswith(('production-','prod-')):continue
assert Image.open(p).getpixel((0,0))==(0,255,0,255),p.name
assert Image.open(caps/'save-durable.png').getpixel((1,0))==(0,255,0,255)
(out/'capture-report.json').write_text(json.dumps({'checks':checks,'durable_commit':True,'reload':True},indent=2)+'\n');print('Native pixel checks:',len(checks),'all exact; commit/reload assertions green')
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Verify the chosen native secret, doorway mask, threshold and saved payload."""
import json,zlib,sys
from PIL import Image
from extract_graphics import ROOT,decode
from nes_object_graphics import P,descriptor
from prepare_real_secret import metadata
from validate_bomb_wall_rom import collide
def main():
m=metadata();assert m['source_room']==103 and m['wall_x']==112 and m['wall_y']==80 and m['object_type']==123 and m['reward']==30 and m['secret_quest']==1
# Quest index 1 belongs to quest number zero in the native [0,0,1] table.
assert descriptor(123,object_attribute=129)['sides']==2
a=json.loads((ROOT/'extracted/overworld/start/room.json').read_text())['tilemap'];b=json.loads((ROOT/'extracted/overworld/north/room.json').read_text())['tilemap'];closed=[b[y][x] for x in (14,15) for y in (10,11)];assert closed==[216,217,218,219]
for y in (10,11):
for x in (14,15):b[y][x]=36
patterns=bytearray(4096)
for off,length,dest in [(34687,1792,0),(51515,2080,1792),(36479,224,3872)]:patterns[dest:dest+length]=P[off:off+length]
support=0
for step in range(17):
for y in range(16):
for x in range(16):
sy=80+step+y;ta=a[sy//8][(64+x)//8];tb=b[sy//8][(112+x)//8];ia=decode(patterns[ta*16:(ta+1)*16])[(sy%8)*8+x%8];ib=decode(patterns[tb*16:(tb+1)*16])[(sy%8)*8+x%8];assert bool(ia)==bool(ib);support+=1
# Native re-layout uses secondary square $0C (top $F3, bottom $24).
room=json.loads((ROOT/'extracted/overworld/start/room.json').read_text());sec=room['secondary_table_prg_offset'];assert list(P[sec+48:sec+52])==[243,36,243,36];assert set(decode(patterns[243*16:244*16]))=={0}
threshold=0
for dx in [-24,-17,-16,-15,-1,0,1,15,16,17,24]:
for dy in [-24,-17,-16,-15,-1,0,1,15,16,17,24]:assert collide(dx,dy)==(abs(dx)<16 and abs(dy)<16);threshold+=1
result={'room':103,'wall':[112,80],'cave_type':123,'reward':30,'native_wall_threshold_cases':threshold,'doorway_support_pixels':support,'revisit_metatile':[243,36,243,36]}
if len(sys.argv)>1:
raw=(ROOT/sys.argv[1]).read_bytes();at=raw.find(b'ZL1S');assert at>=0;payload=raw[at:at+180];assert zlib.adler32(payload[4:8]+payload[12:])==int.from_bytes(payload[8:12],'little');assert payload[13]==3 and payload[34]==30 and payload[155]==145;result['persistent_payload']={'bombs':payload[13],'rupees':payload[34],'room67_flags':payload[155],'checksum':'valid','schema':payload[4]}
(ROOT/'extracted/real_secret/native-report.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result))
if __name__=='__main__':main()
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Closed mutable rock cover must track camera in every connected direction."""
import json
from PIL import Image
from extract_graphics import ROOT
from validate_octorok_graphics import difference
from overworld_data import manifest
rooms={e['stage']:e for e in manifest()}
def room(stage):return Image.open(ROOT/f'extracted/overworld/{rooms[stage]["name"]}/room.png').convert('RGBA').crop((0,64,256,240))
def validate():
checks=[]
for link in json.loads((ROOT/'extracted/overworld/expansion/catalog.json').read_text())['links']:
if 2 not in (link['a'],link['b']):continue
for a,b in [(link['a'],link['b']),(link['b'],link['a'])]:
name=f'wall-scroll-{a}-{b}-mid';cap=Image.open(ROOT/f'extracted/overworld/expansion/validation/{name}.png').convert('RGBA');assert cap.getpixel((0,0))==(0,255,0,255)
if link['direction']==1:
expected=Image.new('RGBA',(512,176));expected.paste(room(link['a']),(0,0));expected.paste(room(link['b']),(256,0));expected=expected.crop((128,0,384,176))
else:
expected=Image.new('RGBA',(256,352));expected.paste(room(link['a']),(0,0));expected.paste(room(link['b']),(0,176));expected=expected.crop((0,88,256,264))
diff=difference(cap.crop((112,79,368,255)),expected);assert diff==0,(name,diff);checks.append({'capture':name,'different_pixels':0})
(ROOT/'extracted/real_secret/scroll-report.json').write_text(json.dumps({'checks':checks},indent=2)+'\n');print('Mutable wall scroll pixel checks:',len(checks),'all exact')
if __name__=='__main__':validate()
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Validate saved guest evidence against independent Python bytes and native CHR."""
import json,zlib
from pathlib import Path
from PIL import Image,ImageChops
from extract_graphics import ROOT,decode
from extract_start_room import RGB
from nes_object_graphics import P
OUT=ROOT/'extracted/save/validation'
def capture(name):
im=Image.open(OUT/(name+'.png')).convert('RGB');assert im.getpixel((0,0))==(0,255,0),name;return im
def raw(name):
im=capture(name);count=im.getpixel((401,0))[0];return bytes(im.getpixel((400,i+20))[0] for i in range(count))
def validate():
items=[0]*40
for k,v in {0:1,1:4,20:1,21:1,22:5,24:51,25:127,33:127,34:128,35:255,37:8}.items():items[k]=v
rooms=[0]*128
for k,v in {119:16,100:128,103:146,21:127,22:128,23:255}.items():rooms[k]=v
header=bytearray([90,76,49,83,1,0,168,0,0,0,0,0]);body=bytes(items+rooms);header[8:12]=zlib.adler32(header[4:8]+body).to_bytes(4,'little');expected=bytes(header)+body
assert len(expected)==180
for name in ('canonical_save','canonical_reopened'):assert raw(name)==expected,name
assert capture('canonical_save').getpixel((6,0))==(2,0,0)
assert capture('canonical_reopened').getpixel((3,0))==(8,1,0)
assert capture('memory_only_save').getpixel((6,0))==(3,0,0)
assert capture('readonly_save').getpixel((6,0))==(6,0,0)
# Schema failure is distinct from malformed/truncated data, without publication.
bad=bytearray(expected);bad[4]=2
assert raw('schema_writer')==bad and raw('schema_rejected')==bad
truncated=raw('truncated_writer');assert len(truncated)==12 and raw('truncated_rejected')==truncated
old=bytearray(expected);old[33]=0;old[8:12]=zlib.adler32(old[4:8]+old[12:]).to_bytes(4,'little');old[0]=0
assert raw('invalid_payload_unchanged')==old
# Compose the new three-option menu directly from NES patterns/palette indices.
patterns=bytearray(4096);patterns[:1792]=P[34687:34687+1792];patterns[0xf20:]=P[36479:36479+224]
off=P.index(bytes.fromhex('3f00200f3000120f1627360f0c1c2c0f121c2c0f2927070f2227070f2627070f152730ff'))+3
palettes=[list(P[off+i*4:off+i*4+4]) for i in range(8)];colors=dict(RGB);colors.update({38:(248,120,88)})
def glyph(code,palette):
im=Image.new('RGB',(8,8));im.putdata([colors[palettes[palette][v]] for v in decode(patterns[code*16:(code+1)*16])]);return im
def text(im,value,x,y,palette=0):
for i,c in enumerate(value):im.paste(glyph(36 if c==' ' else ord(c)-65+10,palette),(x+i*8,y))
menu=Image.new('RGB',(256,240))
for word,y in [('CONTINUE',40),('SAVE',56),('RETRY',72)]:text(menu,word,96,y)
menu.paste(glyph(242,6),(80,40))
actual=capture('pause_menu').crop((112,15,368,255));assert ImageChops.difference(menu,actual).getbbox() is None,'native menu pixels'
saved=Image.new('RGB',(256,240));text(saved,'GAME SAVED',88,88);text(saved,'PRESS START',80,136)
actual=capture('canonical_save').crop((112,15,368,255));assert ImageChops.difference(saved,actual).getbbox() is None,'saved message pixels'
report={'payload_bytes_compared':180,'independent_adler32':True,'separate_process_roundtrip':True,'byte_sentinels':[0,127,128,255],'memory_only_not_durable':True,'read_only_blocked':True,'invalid_magic_preserved':True,'unknown_schema_preserved':True,'truncated_payload_preserved':True,'native_ui_pixel_comparisons':2,'different_pixels':0,'scope':'Isolated guest fixtures and SDK processes; no power-loss fault injection or full NES emulation claim.'}
(OUT/'validation.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':validate()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Compare runtime shop composition with native descriptors and extracted CHR."""
import json
from PIL import Image
from extract_graphics import ROOT
from nes_object_graphics import item
from validate_octorok_graphics import native_image
out=ROOT/'extracted/shop';m=json.loads((out/'rom-data.json').read_text())
asset=ROOT/'assets/tilesets/cave_start';arts=json.loads((asset/'asset.json').read_text())['artifacts'];files={a['index']:a['file'] for a in arts}
checks=[]
for name,chosen,visible,offset,frame in [('available',-1,True,0,250),('menu',-1,True,58,251),('lift-shield',0,True,0,253),('blink-shown',0,True,0,254),('blink-even',0,True,0,255),('blink-hidden',0,False,0,256),('keeper-gone',0,False,0,317),('restock',-1,True,0,550),('lift-key',1,True,0,551),('lift-candle',2,True,0,621)]:
ref=Image.open(ROOT/'extracted/cave/start/room_taken.png').convert('RGBA')
for kind,x,y,g in m['parts']:
if kind==2 or kind==0 and visible or kind==1 and chosen<0:ref.alpha_composite(Image.open(asset/files[g]).convert('RGBA'),(x,y))
for i,(slot,pal) in enumerate(zip(m['item_slots'],m['item_palettes'])):
if visible and i!=chosen:ref.alpha_composite(native_image(item(slot,attribute=pal)),(88+i*32,153))
actual=Image.open(out/'validation'/f'{name}.png').convert('RGBA');different=0;pixels=0
for y in range(112,min(192,240-offset)):
for x in range(32,224):
# Fires animate; Link and the price rupee have separate clocks/poses.
if 64<=x<96 and 120<=y<152 or 160<=x<192 and 120<=y<152:continue
if chosen<0 and 48<=x<64 and 171<=y<189:continue
if chosen<0 and offset==0 and 112<=x<128 and 170<=y<194:continue
if chosen>=0 and 88+chosen*32<=x<104+chosen*32 and 140<=y<180:continue
pixels+=1;different+=actual.getpixel((112+x,15+y+offset))!=ref.getpixel((x,y))
assert different==0,(name,different)
checks.append(dict(name=name,pixels=pixels,different_pixels=different))
for name,i in [('lift-shield',0),('lift-key',1),('lift-candle',2)]:
actual=Image.open(out/'validation'/f'{name}.png').convert('RGBA');ref=Image.new('RGBA',(16,32),(0,0,0,255));
for kind,x,y,g in m['parts']:
if kind==0:ref.alpha_composite(Image.open(asset/files[g]).convert('RGBA'),(x-(88+i*32),y-142))
ref.alpha_composite(native_image(item(m['item_slots'][i],attribute=m['item_palettes'][i])),(-4,0));ref.alpha_composite(Image.open(ROOT/'assets/characters/link_pickup/lift_sword.png').convert('RGBA'),(0,16))
crop=actual.crop((112+88+i*32,15+142,112+104+i*32,15+174));diff=sum(a!=b for a,b in zip(ref.getdata(),crop.getdata()));assert diff==0,(name,'pose',diff);checks.append(dict(name=name+'-pose',pixels=512,different_pixels=diff))
for p in (out/'validation').glob('*.png'):
if p.stem.startswith('prod-'):continue
assert Image.open(p).getpixel((0,0))[:3]==(0,255,0),p
(out/'capture-comparison.json').write_text(json.dumps(checks,indent=2)+'\n');print(len(checks),'native composition/pose comparisons passed')
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Execute native TakeItem/PostDebit leaves; emit shop purchase oracle cases."""
import json
from extract_graphics import ROOT
from nes_object_graphics import P,DELTA
from validate_life_rom import CPU
from prepare_shop import metadata
TAKE=P.index(bytes.fromhex('a2088e0206c90ed005a2028e0206a612e005'))+DELTA
DEBIT=0x8000+P.index(bytes.fromhex('186d7e068d7e0660'))%16384
class Native(CPU):
def __init__(self):
super().__init__(34,255);self.m[0x8000:0xc000]=P[16384:32768]
def execute(self,entry):
self.pc=entry
for _ in range(2000):
at=self.pc;op=self.byte()
if op==0x60:
if self.depth==0:return
self.pc=(self.pop()|self.pop()<<8)+1;self.depth-=1
elif op==0x20:
target=self.word();self.push((self.pc-1)>>8);self.push(self.pc-1);self.depth+=1;self.pc=target
elif op==0x4c:self.pc=self.word()
elif op in [0xf0,0xd0,0xb0,0x90,0x30,0x10]:
d=self.byte();take={0xf0:self.z,0xd0:not self.z,0xb0:self.c,0x90:not self.c,0x30:self.n,0x10:not self.n}[op]
if take:self.pc+=d if d<128 else d-256
elif op in [0xa9,0xa5,0xad,0xbd,0xb9]:
v=self.byte() if op==0xa9 else self.m[self.byte()] if op==0xa5 else self.m[self.word()+(self.x if op==0xbd else self.y if op==0xb9 else 0)];self.a=self.nz(v)
elif op in [0xa2,0xa6,0xae]:self.x=self.nz(self.byte() if op==0xa2 else self.m[self.byte() if op==0xa6 else self.word()])
elif op==0xa0:self.y=self.nz(self.byte())
elif op in [0x85,0x8d,0x99]:
q=self.byte() if op==0x85 else self.word()+(self.y if op==0x99 else 0);self.m[q]=self.a
elif op in [0x86,0x8e]:self.m[self.byte() if op==0x86 else self.word()]=self.x
elif op in [0xc9,0xc0,0xe0,0xd9,0xcd]:
lhs=self.y if op==0xc0 else self.x if op==0xe0 else self.a;rhs=self.m[self.word()+self.y] if op==0xd9 else self.m[self.word()] if op==0xcd else self.byte();self.c=lhs>=rhs;self.nz(lhs-rhs)
elif op in [0x69,0x79,0x6d]:
v=self.byte() if op==0x69 else self.m[self.word()+(self.y if op==0x79 else 0)];r=self.a+v+self.c;self.c=r>255;self.a=self.nz(r)
elif op==0x29:self.a=self.nz(self.a&self.byte())
elif op==0xaa:self.x=self.nz(self.a)
elif op==0xa8:self.y=self.nz(self.a)
elif op==0x8a:self.a=self.nz(self.x)
elif op==0x48:self.push(self.a)
elif op==0x68:self.a=self.nz(self.pop())
elif op==0x18:self.c=False
else:raise AssertionError(f'Unsupported {op:02x} at {at:04x}')
raise AssertionError('Native leaf did not return')
def take(item,old):
slots={28:31,25:23,6:4};c=Native();c.m[0x12]=11;c.m[0x657+slots[item]]=old;c.a=item;c.execute(TAKE);return c.m[0x657+slots[item]],c.m[0x505],c.m[0x506]
def debit(price,pending=0):
c=Native();c.m[0x67e]=pending;c.a=price;c.execute(DEBIT);return c.m[0x67e]
def main():
m=metadata();cases=[]
for item,slot,price in zip(m['wares'],[31,23,4],m['prices']):
for old in [0,1,2,254,255]:
value,lift,duration=take(item,old);assert lift==item and duration==128
expected=1 if item==28 else min(255,old+1) if item==25 else max(1,old);assert value==expected
for money in sorted({0,price-1,price,price+1,255}):
for pending in [0,1]:
allowed=pending==0 and money>=price;result=value if allowed else old;queued=debit(price,pending) if allowed else pending
cases.append([item,slot,price,old,money,pending,int(allowed),result,queued])
(ROOT/'extracted/shop/native-cases.json').write_text(json.dumps({'take_entry_cpu':TAKE,'debit_entry_cpu':DEBIT,'cases':cases},indent=2)+'\n');print('Native item/debit shop cases:',len(cases))
if __name__=='__main__':main()
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Reference paths and pixel comparisons for captures obtained through Studio."""
import json
from PIL import Image, ImageChops
from validate_collision_rom import ROOT, port_probe
OUT = ROOT / 'extracted/overworld/start/collision-validation'
CASES = {
'initial': [(1, {})],
'left_wall': [(200, {'left': True})],
'right_wall': [(200, {'right': True})],
'down_wall': [(200, {'down': True})],
'up_exit_closed': [(200, {'up': True})],
'up_right_slide': [(120, {'up': True, 'right': True})],
'down_left_corner': [(200, {'down': True, 'left': True})],
'blocked_idle': [(200, {'left': True}), (12, {})],
'blocked_reverse': [(200, {'left': True}), (12, {'right': True})],
'midcell_reverse': [(3, {'right': True}), (12, {'left': True})],
'cave_approach': [(40, {'left': True}), (100, {'up': True})],
'right_short': [(12, {'right': True})],
'left_upper_wall': [(12, {'up': True}), (200, {'left': True})],
'right_upper_wall': [(12, {'up': True}), (200, {'right': True})],
}
def reference(sequence):
x, y, facing, grid, fraction = 120, 133, 4, 0, 0
straight, phase, timer = False, 0, 4
opposite = {1: 2, 2: 1, 4: 8, 8: 4}
for frames, buttons in sequence:
for _ in range(frames):
dirs = [d for d, key in ((1, 'right'), (2, 'left'), (4, 'down'), (8, 'up')) if buttons.get(key)]
moving = bool(dirs)
if grid == 0:
straight = False
requested = dirs[-1] if dirs else 0
if len(dirs) > 1:
allowed = [d for d in dirs if port_probe(x, y, d) < 137]
if not allowed: moving = False
else: straight, requested = True, allowed[-1]
if moving: facing = requested
elif dirs:
requested = dirs[0]
if requested == opposite[facing]: facing = requested
elif requested != facing and not straight:
if abs(grid) < 4 and ((facing in (2, 8) and grid < 0) or (facing in (1, 4) and grid > 0)):
facing = opposite[facing]
grid += 8 if grid < 0 else -8
if moving and (grid != 0 or port_probe(x, y, facing) < 137):
for _ in range(4):
value = fraction + (96 if facing in (1, 4) else -96)
delta, fraction = value // 256, value % 256
if abs(grid) == 8: continue
nx, ny = x + (delta if facing in (1, 2) else 0), y + (delta if facing in (4, 8) else 0)
if not (0 <= nx <= 240 and 61 <= ny <= 221): continue
x, y, grid = nx, ny, grid + delta
if abs(grid) == 8: grid = 0
if moving:
timer -= 1
if timer == 0: timer, phase = 6, 1 - phase
return {'x': x, 'y': y, 'facing': facing, 'phase': phase}
def main():
OUT.mkdir(exist_ok=True)
results = []
for name, sequence in CASES.items():
state = reference(sequence)
actual_path = OUT / f'{name}.png'
if not actual_path.exists():
print(name, state, '(capture pending)')
continue
expected = Image.open(ROOT / 'extracted/link/viewport-preview.png').convert('RGBA')
expected.paste(Image.open(ROOT / 'extracted/overworld/start/room.png').convert('RGBA'), (112, 15))
direction = {1: 'right', 2: 'left', 4: 'down', 8: 'up'}[state['facing']]
sprite = Image.open(ROOT / f"assets/characters/link/walk_{direction}_{state['phase']}.png").convert('RGBA')
expected.alpha_composite(sprite, (112 + state['x'], 15 + state['y'] + 3))
actual = Image.open(actual_path).convert('RGBA')
different = sum(pixel != (0, 0, 0, 0) for pixel in ImageChops.difference(actual, expected).getdata())
results.append({'case': name, 'sequence': sequence, 'expected_state': state, 'different_pixels': different})
assert different == 0, results[-1]
report = {'compared': len(results), 'planned': len(CASES), 'results': results,
'scope': 'Actual Prometeu full frames versus extracted terrain and sprite at reference movement coordinates; collision model independently checked against ROM leaf routine.'}
(OUT / 'results.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report))
if __name__ == '__main__': main()
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Native CHR/descriptor composition checks for the west supplies shop."""
import json
from PIL import Image
from extract_graphics import ROOT
from nes_object_graphics import item
from validate_octorok_graphics import native_image
out=ROOT/'extracted/supply_shop';m=json.loads((out/'rom-data.json').read_text());asset=ROOT/'assets/tilesets/cave_start';arts=json.loads((asset/'asset.json').read_text())['artifacts'];files={a['index']:a['file'] for a in arts};checks=[]
def background(chosen,visible):
ref=Image.open(ROOT/'extracted/cave/start/room_taken.png').convert('RGBA')
for kind,x,y,g in m['parts']:
if kind==2 or kind==0 and visible or kind==1 and chosen<0:ref.alpha_composite(Image.open(asset/files[g]).convert('RGBA'),(x,y))
for i,(slot,pal) in enumerate(zip(m['item_slots'],m['item_palettes'])):
if visible and i!=chosen:ref.alpha_composite(native_image(item(slot,attribute=pal)),(88+i*32,153))
return ref
for name,chosen,visible,hero_x,hero_y in [('available',-1,True,112,173),('menu-closed',-1,True,112,173),('buy-bombs',1,True,120,157),('bomb-duplicate',1,True,120,157),('restock',-1,True,112,173),('lift-arrows',2,True,152,157),('lift-shield',0,True,88,157),('durable-save',0,False,88,157),('reload-drained',-1,True,112,173)]:
ref=background(chosen,visible);actual=Image.open(out/'validation'/f'{name}.png').convert('RGBA');diff=0;pixels=0
for y in range(112,192):
for x in range(32,224):
if 64<=x<96 and 120<=y<152 or 160<=x<192 and 120<=y<152:continue
if chosen<0 and 48<=x<64 and 171<=y<189:continue
if hero_x<=x<hero_x+16 and hero_y-16<=y<hero_y+22:continue
pixels+=1;diff+=actual.getpixel((112+x,15+y))!=ref.getpixel((x,y))
assert diff==0,(name,diff);checks.append(dict(name=name,pixels=pixels,different_pixels=diff))
for name,i in [('lift-arrows',2),('lift-shield',0)]:
ref=background(i,True).crop((88+i*32,142,104+i*32,174));ref.alpha_composite(native_image(item(m['item_slots'][i],attribute=m['item_palettes'][i])),(-4,0));ref.alpha_composite(Image.open(ROOT/'assets/characters/link_pickup/lift_sword.png').convert('RGBA'),(0,16));actual=Image.open(out/'validation'/f'{name}.png').convert('RGBA').crop((200+i*32,157,216+i*32,189));diff=sum(a!=b for a,b in zip(ref.getdata(),actual.getdata()));assert diff==0,(name,'pose',diff);checks.append(dict(name=name+'-pose',pixels=512,different_pixels=diff))
# A bomb has ID zero: CheckLiftItem skips it. Compare a normal walking pose.
ref=background(1,True).crop((120,142,136,180));ref.alpha_composite(Image.open(ROOT/'assets/characters/link/walk_up_0.png').convert('RGBA'),(0,18));actual=Image.open(out/'validation/buy-bombs.png').convert('RGBA').crop((232,157,248,195));diff=sum(a!=b for a,b in zip(ref.getdata(),actual.getdata()));assert diff==0,('bomb-no-lift',diff);checks.append(dict(name='bomb-no-lift',pixels=608,different_pixels=diff))
for p in (out/'validation').glob('*.png'):
assert Image.open(p).getpixel((0,0))[:3]==(0,255,0),p
(out/'capture-comparison.json').write_text(json.dumps(checks,indent=2)+'\n');print(len(checks),'native shop composition/pose checks passed')
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Native acquisition/debit oracle for the supplies shop; guards read from ROM code."""
import json
from extract_graphics import ROOT
from validate_shop_rom import Native,TAKE,debit
from prepare_shop import metadata
def main():
m=metadata(68,15,16);cases=[]
for item,slot,price in zip(m['wares'],[31,1,2],m['prices']):
for maximum in ([8,12,255] if item==0 else [8]):
for old in [0,1,4,7,8,12,254,255]:
c=Native();c.m[0x12]=11;c.m[0x657+slot]=old;c.m[0x657+37]=maximum;c.a=item;c.execute(TAKE)
value=c.m[0x657+slot];expected=1 if item==28 else min(maximum,old+4) if item==0 else max(1,old)
assert value==expected and c.m[0x505]==item and c.m[0x506]==128
for money in sorted({0,price-1,price,price+1,255}):
for pending in [0,1]:
allowed=pending==0 and money>=price
cases.append([item,slot,price,old,maximum,money,pending,int(allowed),value if allowed else old,debit(price,pending) if allowed else pending])
out=ROOT/'extracted/supply_shop';out.mkdir(exist_ok=True,parents=True)
(out/'native-cases.json').write_text(json.dumps({'take_entry_cpu':TAKE,'cases':cases,'bomb_lift_sentinel':0,'bomb_effective_lift_ticks':0},indent=2)+'\n');print(len(cases),'native supply cases passed')
if __name__=='__main__':main()
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Native descriptor pixels versus generated art and live composition."""
import json
from PIL import Image
from extract_graphics import ROOT
from nes_object_graphics import descriptor
from validate_octorok_graphics import native_image,difference
out=ROOT/'extracted/zora';checks=[]
for frame in [0,1,2,3,8,9]:
info=descriptor(17,frame,True);im=Image.open(ROOT/f'assets/characters/octorok/zora_{frame}.png').convert('RGBA');assert difference(im,native_image(info,True))==0;checks.append({'asset':frame,'different_pixels':0})
assert difference(Image.open(ROOT/'assets/characters/octorok/zora_fireball.png').convert('RGBA'),native_image(descriptor(85),True))==0
native=json.loads((out/'native-cases.json').read_text());rows=[r for c in native['cycles'] for r in c['frames']]
for t in [0,31,32,47,49,81,97,193,194,387,226,243]:
name=f'cycle-{t}' if t not in [226,243] else 'back-exposed' if t==226 else 'back-fire';cap=Image.open(out/f'validation/{name}.png').convert('RGBA');assert cap.getpixel((0,0))==(0,255,0,255)
expected=Image.open(ROOT/'extracted/overworld/northwest_2/room.png').convert('RGBA');s,timer,anim,frame,facing,shot,dead,drawn=rows[t]
if drawn is not None:expected.alpha_composite(native_image(descriptor(17,drawn,True)),(80,(125 if t<194 else 157)+1))
diff=difference(cap.crop((112,79,368,255)),expected.crop((0,64,256,240)));assert diff==0,(name,diff);checks.append({'capture':name,'different_pixels':diff})
for p in (out/'validation').glob('integration-*.png'):assert Image.open(p).getpixel((0,0))==(0,255,0,255),p
(out/'capture-report.json').write_text(json.dumps({'checks':checks,'asset_checks':7,'live_pixel_checks':12,'integration_captures':14},indent=2)+'\n');print('7 native asset comparisons; 12 live pixel comparisons; integration assertions green')
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Bounded original Zora state/angle execution; calls outside each leaf are explicit."""
import json
from extract_graphics import ROOT
from nes_object_graphics import P
from validate_combat_rom import CPU
ANGLE=P.index(bytes.fromhex('8400a9ff8501a503c504'))+0x790
ZORA=P.index(bytes.fromhex('ad6c06d0fa206d8ab5acc903'))-65536+0x8000
class Native(CPU):
def __init__(self):
super().__init__(4);self.m[0x6c90:0x7f00]=P[0x6500:0x7770];self.shot=False;self.destroyed=False;self.drawn=None
def run_leaf(self,entry):
self.pc=entry;self.depth=0
for _ in range(3000):
if self.pc==0xfeb1:self.destroyed=True;return
at=self.pc;op=self.byte()
if op==0x60:
if not self.depth:return
self.pc=(self.pop()|self.pop()<<8)+1;self.depth-=1
elif op==0x20:
target=self.word()
if target==0x77db:self.drawn=self.a
elif target==0x79d0:pass # Weapon/contact collisions are tested separately in the guest.
elif target==0x82af:self.shot=True
else:self.push((self.pc-1)>>8);self.push(self.pc-1);self.depth+=1;self.pc=target
elif op==0x4c:self.pc=self.word()
elif op in [0xf0,0xd0,0xb0,0x90,0x30,0x10]:
d=self.byte();yes={0xf0:self.z,0xd0:not self.z,0xb0:self.c,0x90:not self.c,0x30:self.n,0x10:not self.n}[op]
if yes:self.pc+=d if d<128 else d-256
elif op in [0xa9,0xa5,0xad,0xb5,0xbd,0xb9]:
if op==0xa9:v=self.byte()
elif op==0xa5:v=self.m[self.byte()]
elif op==0xad:v=self.m[self.word()]
elif op==0xb5:v=self.m[(self.byte()+self.x)&255]
elif op==0xbd:v=self.m[self.word()+self.x]
else:v=self.m[self.word()+self.y]
self.a=self.nz(v)
elif op in [0xa0,0xa4,0xb4,0xbc]:
v=self.byte() if op==0xa0 else self.m[self.byte()] if op==0xa4 else self.m[(self.byte()+self.x)&255] if op==0xb4 else self.m[self.word()+self.x];self.y=self.nz(v)
elif op in [0x85,0x95,0x9d,0x84,0x94]:
q=self.word()+self.x if op==0x9d else (self.byte()+self.x)&255 if op in [0x95,0x94] else self.byte();self.m[q]=self.y if op in [0x84,0x94] else self.a
elif op in [0xc9,0xc0,0xc5,0xcd]:
v=self.m[self.byte()] if op==0xc5 else self.m[self.word()] if op==0xcd else self.byte();lhs=self.y if op==0xc0 else self.a;self.c=lhs>=v;self.nz(lhs-v)
elif op in [0x69,0x65,0xe9,0xe5,0x7d]:
v=self.m[self.byte()] if op in [0x65,0xe5] else self.m[self.word()+self.x] if op==0x7d else self.byte();r=self.a-v-(not self.c) if op in [0xe9,0xe5] else self.a+v+self.c;self.c=r>=0 if op in [0xe9,0xe5] else r>255;self.a=self.nz(r)
elif op in [0xde,0xce]:
q=self.word()+(self.x if op==0xde else 0);self.m[q]=self.nz(self.m[q]-1)
elif op==0x88:self.y=self.nz(self.y-1)
elif op==0xa8:self.y=self.nz(self.a)
elif op==0x48:self.push(self.a)
elif op==0x68:self.a=self.nz(self.pop())
elif op==0x18:self.c=False
elif op==0x38:self.c=True
elif op==0x0a:self.c=self.a>=128;self.a=self.nz(self.a*2)
elif op==0x49:self.a=self.nz(self.a^self.byte())
else:raise AssertionError(f'Unsupported opcode {op:02x} at {at:04x}')
raise AssertionError('Leaf did not return')
def angle(x,y):
c=Native();c.m[3]=x;c.m[4]=y;c.y=4;c.run_leaf(ANGLE);return c.y
def main():
cases=[];angles=[]
for x in range(0,256,7):
for y in range(0,256,7):
native=angle(x,y);a,b=max(x,y),min(x,y);i=4;delta= -1 if x>=y else 1
if a-b>=8:
while True:
i+=delta
if i in (0,8):break
a-=b
if a<b:break
assert i==native,(x,y,i,native);angles.append([x,y,native])
for zy,ly in [(125,141),(157,141)]:
c=Native();c.m[0x34f+1]=17;c.m[0x84+1]=zy;c.m[0x84]=ly
rows=[]
for tick in range(210):
if c.m[0x28+1]:c.m[0x28+1]-=1
c.shot=False;c.drawn=None;c.run_leaf(ZORA)
rows.append([c.m[0xac+1],c.m[0x28+1],c.m[0x3d0+1],c.m[0x3e4+1],c.m[0x98+1],int(c.shot),int(c.destroyed),c.drawn])
if c.destroyed:break
cases.append({'y':zy,'link_y':ly,'frames':rows})
out=ROOT/'extracted/zora';(out/'native-cases.json').write_text(json.dumps({'angles':angles,'cycles':cases,'entry_cpu':ZORA,'angle_entry_cpu':ANGLE},indent=2)+'\n');print('Native angle cases:',len(angles),'cycle ticks:',sum(len(c['frames']) for c in cases))
if __name__=='__main__':main()