#!/usr/bin/env python3 """Package an already drawn, transparent sprite sheet for Godot. This is a technical crop/nearest-neighbour packing tool, not an art generator. The game ships with the finished PNGs; Pillow is only needed to repack sources. Every frame uses one common scale, preserving crouches and adult proportions. Example: python tools/pack_ashen_atlas.py source.png output.png --columns 6 --rows 4 """ import argparse import json from pathlib import Path from PIL import Image def pack(source, destination, columns=6, rows=4, cell=192, height=128, baseline=152): image = Image.open(source).convert("RGBA") width, source_height = image.size frames = [] boxes = [] for index in range(columns * rows): x, y = index % columns, index // columns bounds = (round(x * width / columns), round(y * source_height / rows), round((x + 1) * width / columns), round((y + 1) * source_height / rows)) frame = image.crop(bounds) # Ignore faint alpha fringe only when measuring the anchor; keep the # source RGBA pixels untouched in the packed image. box = frame.getchannel("A").point(lambda value: 255 if value >= 64 else 0).getbbox() if not box: raise ValueError(f"Empty cell {index} in {source}") frames.append(frame) boxes.append(box) scale = height / (boxes[0][3] - boxes[0][1]) atlas = Image.new("RGBA", (columns * cell, rows * cell)) records = [] for index, (frame, box) in enumerate(zip(frames, boxes)): resized = frame.resize((round(frame.width * scale), round(frame.height * scale)), Image.Resampling.NEAREST) offset = (round(cell / 2 - frame.width * scale / 2), round(baseline - box[3] * scale)) target = Image.new("RGBA", (cell, cell)) target.alpha_composite(resized, offset) atlas.alpha_composite(target, (index % columns * cell, index // columns * cell)) records.append({"frame": index, "source_bounds": list(box), "offset": list(offset)}) destination = Path(destination) destination.parent.mkdir(parents=True, exist_ok=True) atlas.save(destination, optimize=True) return {"file": destination.name, "size": list(atlas.size), "columns": columns, "rows": rows, "cell": cell, "standing_height": height, "baseline": baseline, "source_size": list(image.size), "scale": scale, "frames": records} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) parser.add_argument("destination", type=Path) parser.add_argument("--columns", type=int, default=6) parser.add_argument("--rows", type=int, default=4) parser.add_argument("--cell", type=int, default=192) parser.add_argument("--height", type=int, default=128) parser.add_argument("--baseline", type=int, default=152) args = parser.parse_args() print(json.dumps(pack(**vars(args)), indent=2))