"""Extract and repack the generated 4x3 front-facing bench animation.""" from __future__ import annotations import argparse from pathlib import Path from PIL import Image def bounds(length: int, index: int, count: int) -> tuple[int, int]: return round(index * length / count), round((index + 1) * length / count) def make_strip(source: Image.Image, rows: list[int], output: Path) -> None: cell_width = round(source.width / 4) cell_height = round(source.height / 3) slots: list[Image.Image] = [] for row in rows: top, bottom = bounds(source.height, row, 3) for column in range(4): left, right = bounds(source.width, column, 4) slot = source.crop((left, top, right, bottom)) canvas = Image.new("RGBA", (cell_width, cell_height), (0, 0, 0, 0)) canvas.alpha_composite(slot, ((cell_width - slot.width) // 2, cell_height - slot.height)) slots.append(canvas) strip = Image.new("RGBA", (cell_width * len(slots), cell_height), (0, 0, 0, 0)) for index, slot in enumerate(slots): strip.alpha_composite(slot, (index * cell_width, 0)) output.parent.mkdir(parents=True, exist_ok=True) strip.save(output) def extract(source_path: Path, output_dir: Path) -> None: source = Image.open(source_path).convert("RGBA") make_strip(source, [0], output_dir / "sit-front-strip.png") make_strip(source, [1, 2], output_dir / "rest-front-strip.png") def pack(frames_root: Path, output: Path, frame_size: int) -> None: atlas = Image.new("RGBA", (frame_size * 4, frame_size * 3), (0, 0, 0, 0)) rows = [("sit-front", range(1, 5)), ("rest-front", range(1, 5)), ("rest-front", range(5, 9))] for row, (folder, indices) in enumerate(rows): for column, index in enumerate(indices): frame = Image.open(frames_root / folder / f"{index:02d}.png").convert("RGBA") atlas.alpha_composite(frame, (column * frame_size, row * frame_size)) output.parent.mkdir(parents=True, exist_ok=True) atlas.save(output) def main() -> None: parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="command", required=True) extract_parser = subparsers.add_parser("extract") extract_parser.add_argument("--source", type=Path, required=True) extract_parser.add_argument("--out-dir", type=Path, required=True) pack_parser = subparsers.add_parser("pack") pack_parser.add_argument("--frames-root", type=Path, required=True) pack_parser.add_argument("--output", type=Path, required=True) pack_parser.add_argument("--frame-size", type=int, default=256) args = parser.parse_args() if args.command == "extract": extract(args.source, args.out_dir) else: pack(args.frames_root, args.output, args.frame_size) if __name__ == "__main__": main()