"""Turn a picture into a Galaga sprite family: 8 drawings of 16 x 16 pixels in the 3 colours of one colour code, written into a copy of the sprite ROM (colours by nearest match, colour regions or brightness bands: --map). A family is 8 consecutive codes: six rotation steps from facing sideways to nearly up, then the upright pose and its wing-flap frame (the bee family is 0x18-0x1f in colour 3). For each rotation step the angle is fitted against the original drawing's silhouette, the full-size picture is rotated to it and only then shrunk, which keeps the small drawings clean. The flap frame is the upright picture with its wings narrowed. Usage: python3 tools/sprite_convert.py IMAGE --family 18 --colour 3 \ --rom-in target/sprites.bin --rom-out target/sprites-remix.bin \ --preview target/bee-new.png target/sprites.bin is the original sprite ROM pair (galaga-sprite-rom dumps it) and target/palette.json the colours (same tool). """ import argparse, json import numpy as np from PIL import Image ap = argparse.ArgumentParser() ap.add_argument("image") ap.add_argument("--family", required=True, help="first code, hex") ap.add_argument("--colour", type=int, required=True) ap.add_argument("--rom-in", required=True) ap.add_argument("--rom-out", required=True) ap.add_argument("--preview", required=True) ap.add_argument("--mod-lines", help="also write the family as `sprite CODE HEX` lines for a path mod") ap.add_argument("--size", type=float, default=0, help="the picture's longest side in pixels (default: match the original)") ap.add_argument("--key-tolerance", type=float, default=60.0) ap.add_argument("--coverage", type=float, default=0.35) ap.add_argument("--map", choices=["nearest", "regions", "luma"], default="nearest", help="nearest: each pixel takes the nearest of the three colours; regions: the " "picture's colours are grouped into three regions (k-means) and the three " "colours assigned to them in the best-matching order (for pictures in one hue); " "luma: the subject's brightness split at --luma-cuts, dark to bright taking " "the pixel values in --luma-order") ap.add_argument("--luma-order", default="2,1,3", help="pixel values (1-3) for the dark, middle and bright bands") ap.add_argument("--luma-cuts", default="0.4,0.8", help="the bands' boundaries as quantiles of the subject's brightness") ap.add_argument("--dark", type=float, default=0.0, help="pixels darker than this (0-255 brightness) count as background (see-through)") ap.add_argument("--angles", default="90,75,60,45,30,15", help="the six rotation steps, degrees counter-clockwise from facing up " "(measured from the original bee family; 'fit' fits them to the originals)") ap.add_argument("--frames", type=int, choices=[7, 8], default=8, help="7 for a family without a flap frame (the transforming specials, 0x50-0x66): " "the 8th code is left alone (0x6f, after 0x68's family, is the '150' score)") args = ap.parse_args() first = int(args.family, 16) rom = bytearray(open(args.rom_in, "rb").read()) pal = json.load(open("target/palette.json")) rgb16 = np.array(pal["sprite_rgb"], dtype=np.float32) # 16 sprite colours lookup = pal["sprite_lookup"][args.colour * 4: args.colour * 4 + 4] # pixel value -> colour index colours = {p: rgb16[lookup[p]] for p in (1, 2, 3)} def pixel(byte, k): return 2 * ((byte >> (7 - k)) & 1) + ((byte >> (3 - k)) & 1) # Screen orientation: screen (u, v) shows raster (x, y) = (v, 15 - u). def decode(code): out = np.zeros((16, 16), np.uint8) for y in range(16): for x in range(16): out[x, 15 - y] = pixel(rom[64 * code + 32 * (y // 8) + 8 * (x // 4) + (y % 8)], x % 4) return out # out[v][u] def encode(code, img): # img[v][u], values 0-3 for i in range(64): rom[64 * code + i] = 0 for y in range(16): for x in range(16): p = int(img[x, 15 - y]) k = x % 4 o = 64 * code + 32 * (y // 8) + 8 * (x // 4) + (y % 8) rom[o] |= ((p >> 1) & 1) << (7 - k) | (p & 1) << (3 - k) # The picture, its background keyed out, cropped square around the subject. src = np.asarray(Image.open(args.image).convert("RGB"), dtype=np.float32) border = np.concatenate([src[0], src[-1], src[:, 0], src[:, -1]]) key = np.median(border, axis=0) alpha = (np.sqrt(((src - key) ** 2).sum(axis=2)) > args.key_tolerance).astype(np.float32) if args.dark > 0: alpha[src.mean(axis=2) < args.dark] = 0 # For --map regions: three colour regions of the subject, matched to the # colour code's three colours in the best order. if args.map == "regions": pts = src[alpha > 0][:: max(1, int((alpha > 0).sum() // 20000))] rng = np.random.default_rng(0) centres = pts[rng.choice(len(pts), 3, replace=False)] for _ in range(30): lab = ((pts[:, None] - centres[None]) ** 2).sum(axis=2).argmin(axis=1) centres = np.array([pts[lab == k].mean(axis=0) if (lab == k).any() else centres[k] for k in range(3)]) import itertools pal3 = [colours[1], colours[2], colours[3]] best = min(itertools.permutations(range(3)), key=lambda perm: sum(((centres[k] - pal3[perm[k]]) ** 2).sum() for k in range(3))) region_centres, region_values = centres, [best[k] + 1 for k in range(3)] if args.map == "luma": luma = src @ np.array([0.299, 0.587, 0.114], dtype=np.float32) cuts = np.quantile(luma[alpha > 0], [float(q) for q in args.luma_cuts.split(",")]) luma_order = np.array([int(v) for v in args.luma_order.split(",")]) ys, xs = np.nonzero(alpha) cy, cx = (ys.min() + ys.max()) / 2, (xs.min() + xs.max()) / 2 half = max(ys.max() - ys.min(), xs.max() - xs.min()) / 2 * 1.15 box = (int(cx - half), int(cy - half), int(cx + half), int(cy + half)) rgba = np.dstack([src, alpha * 255]).astype(np.uint8) subject = Image.fromarray(rgba, "RGBA").crop(box) orig = [decode(first + i) for i in range(args.frames)] extent = max(max(np.ptp(np.nonzero(o)[0]), np.ptp(np.nonzero(o)[1])) + 1 for o in orig[6:7]) size = args.size or extent def shrink(img, angle, squash=1.0): """Rotate the full-size subject, then shrink by majority: each 16 x 16 pixel is part of the creature when at least `coverage` of its block is, and takes the most common of the three colours in that block (each full-size pixel snapped to the nearest colour first).""" im = img if squash != 1.0: w, h = im.size narrow = im.resize((int(w * squash), h), Image.LANCZOS) canvas = Image.new("RGBA", (w, h)) canvas.paste(narrow, ((w - narrow.width) // 2, 0)) im = canvas im = im.rotate(angle, resample=Image.BICUBIC, expand=False) # Work at 8 samples per output pixel. scale = size / (subject.size[0] / 1.15) n = 16 * 8 small = im.resize((round(im.width * scale * 8), round(im.height * scale * 8)), Image.LANCZOS) canvas = Image.new("RGBA", (n, n)) canvas.paste(small, ((n - small.width) // 2, (n - small.height) // 2), small) a = np.asarray(canvas, dtype=np.float32) opaque = a[..., 3] >= 128 # Close small gaps (thin wings, outlines) in the silhouette. from scipy import ndimage opaque = ndimage.binary_closing(opaque, structure=np.ones((5, 5))) if args.map == "luma": l = a[..., :3] @ np.array([0.299, 0.587, 0.114], dtype=np.float32) snapped = luma_order[np.searchsorted(cuts, l)] elif args.map == "regions": dist = ((a[..., None, :3] - region_centres[None, None]) ** 2).sum(axis=3) snapped = np.array(region_values)[dist.argmin(axis=2)] else: pal = np.array([colours[1], colours[2], colours[3]]) dist = ((a[..., None, :3] - pal[None, None]) ** 2).sum(axis=3) snapped = dist.argmin(axis=2) + 1 out = np.zeros((16, 16), np.uint8) for v in range(16): for u in range(16): blk = opaque[v * 8:(v + 1) * 8, u * 8:(u + 1) * 8] if blk.mean() >= args.coverage: vals = snapped[v * 8:(v + 1) * 8, u * 8:(u + 1) * 8][blk] out[v, u] = np.bincount(vals, minlength=4)[1:].argmax() + 1 return out # Fit each rotation step's angle to the original's silhouette (IoU). angles = [int(a) for a in args.angles.split(",")] if args.angles != "fit" else [] for i in range(6 if args.angles == "fit" else 0): target = orig[i] > 0 best = max(range(0, 100, 3), key=lambda ang: ((shrink(subject, ang) > 0) & target).sum() / max(1, ((shrink(subject, ang) > 0) | target).sum())) angles.append(best) new = ([shrink(subject, a) for a in angles] + [shrink(subject, 0), shrink(subject, 0, squash=0.78)])[:args.frames] for i, img in enumerate(new): encode(first + i, img) open(args.rom_out, "wb").write(rom) if args.mod_lines: with open(args.mod_lines, "w") as f: for i in range(args.frames): code = first + i f.write(f"sprite {code:02x} {bytes(rom[64 * code:64 * code + 64]).hex()}\n") # Preview: originals above, new below, 8x. def show(img): out = np.zeros((16, 16, 3), np.uint8) for p in (1, 2, 3): out[img == p] = colours[p] return out row1 = np.concatenate([np.pad(show(o), ((2, 2), (2, 2), (0, 0))) for o in orig], axis=1) row2 = np.concatenate([np.pad(show(n), ((2, 2), (2, 2), (0, 0))) for n in new], axis=1) Image.fromarray(np.concatenate([row1, row2])).resize((row1.shape[1] * 8, row1.shape[0] * 16), Image.NEAREST).save(args.preview) print("rotation angles fitted:", angles, "size", size)