from __future__ import annotations import argparse import json from pathlib import Path from PIL import Image, ImageDraw, ImageFont ROOT = Path(__file__).resolve().parent.parent PREVIEW_DIR = ROOT / "assets/images/2d-game-characters/02-xinyin/previews/playback" BOARD_SIZE = (1200, 430) PANEL_CENTERS = (220, 600, 980) TARGETS = ( {"label": "100%", "height": 176, "cell": (128, 64)}, {"label": "75%", "height": 132, "cell": (96, 48)}, {"label": "50%", "height": 88, "cell": (64, 32)}, ) FOOT_BASELINE = 352 BACKGROUND = (16, 20, 29) PANEL = (24, 30, 42) PANEL_LINE = (65, 82, 112) GRID_FILL = (39, 60, 84) GRID_LINE = (87, 160, 222) TEXT = (241, 245, 252) MUTED = (151, 171, 201) def load_font(size: int, semibold: bool = False) -> ImageFont.ImageFont: font_name = "seguisb.ttf" if semibold else "segoeui.ttf" path = Path("C:/Windows/Fonts") / font_name if path.exists(): return ImageFont.truetype(str(path), size) return ImageFont.load_default() def alpha_bounds(image: Image.Image) -> tuple[int, int, int, int]: bounds = image.getchannel("A").getbbox() if bounds is None: raise ValueError("Transparent frame has no visible pixels") return bounds def union_bounds(bounds_list: list[tuple[int, int, int, int]], size: tuple[int, int]) -> tuple[int, int, int, int]: left = max(0, min(b[0] for b in bounds_list) - 8) top = max(0, min(b[1] for b in bounds_list) - 8) right = min(size[0], max(b[2] for b in bounds_list) + 8) bottom = min(size[1], max(b[3] for b in bounds_list) + 8) return left, top, right, bottom def draw_diamond(draw: ImageDraw.ImageDraw, center_x: int, center_y: int, width: int, height: int) -> None: points = [ (center_x, center_y - height // 2), (center_x + width // 2, center_y), (center_x, center_y + height // 2), (center_x - width // 2, center_y), ] draw.polygon(points, fill=GRID_FILL, outline=GRID_LINE, width=2) def build_board( title: str, source: Image.Image, crop: tuple[int, int, int, int], fonts: dict[str, ImageFont.ImageFont], ) -> Image.Image: board = Image.new("RGB", BOARD_SIZE, BACKGROUND) draw = ImageDraw.Draw(board) draw.text((38, 22), title, font=fonts["title"], fill=TEXT) draw.text((40, 57), "fixed crop · fixed foot baseline · real frame timing", font=fonts["small"], fill=MUTED) cropped = source.crop(crop) crop_width, crop_height = cropped.size for center_x, target in zip(PANEL_CENTERS, TARGETS): panel_box = (center_x - 170, 92, center_x + 170, 402) draw.rounded_rectangle(panel_box, radius=10, fill=PANEL, outline=PANEL_LINE, width=2) draw.text((center_x - 145, 106), target["label"], font=fonts["label"], fill=TEXT) draw.text( (center_x - 145, 137), f"character {target['height']} px · cell {target['cell'][0]}×{target['cell'][1]}", font=fonts["small"], fill=MUTED, ) draw_diamond(draw, center_x, FOOT_BASELINE, target["cell"][0], target["cell"][1]) scale = target["height"] / crop_height output_width = max(1, round(crop_width * scale)) resized = cropped.resize((output_width, target["height"]), Image.Resampling.LANCZOS) paste_x = round(center_x - output_width / 2) paste_y = FOOT_BASELINE - target["height"] board.paste(resized, (paste_x, paste_y), resized) draw.line((center_x - 7, FOOT_BASELINE, center_x + 7, FOOT_BASELINE), fill=(255, 88, 116), width=2) return board def save_gif(frames: list[Image.Image], durations: list[int], path: Path) -> None: palette_source = Image.new("RGB", (BOARD_SIZE[0], BOARD_SIZE[1] * len(frames)), BACKGROUND) for index, frame in enumerate(frames): palette_source.paste(frame, (0, index * BOARD_SIZE[1])) palette = palette_source.quantize(colors=256, method=Image.Quantize.MEDIANCUT) paletted = [ frame.quantize(palette=palette, dither=Image.Dither.FLOYDSTEINBERG) for frame in frames ] paletted[0].save( path, save_all=True, append_images=paletted[1:], duration=durations, loop=0, disposal=2, optimize=False, ) def main() -> None: parser = argparse.ArgumentParser(description="Build fixed-baseline motion playback previews for Xinyin.") parser.add_argument("--direction", choices=("front-right", "front-left", "down", "up"), default="front-right") parser.add_argument("--motion-version", type=int) args = parser.parse_args() motion_version = args.motion_version or (3 if args.direction == "front-right" else 1) runtime_direction = {"front-right": "left", "front-left": "right", "down": "down", "up": "up"}[args.direction] motion_dir = ROOT / f"assets/images/2d-game-characters/02-xinyin/motion/{args.direction}/v{motion_version}" manifest_path = motion_dir / "motion-manifest.json" report_path = motion_dir / "playback-report.json" PREVIEW_DIR.mkdir(parents=True, exist_ok=True) manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig")) definitions = {frame["name"]: frame for frame in manifest["frames"]} images = { name: Image.open(motion_dir / frame["file"]).convert("RGBA") for name, frame in definitions.items() } source_size = next(iter(images.values())).size if any(image.size != source_size for image in images.values()): raise ValueError("Motion frames do not share a common canvas") bounds_by_name = {name: alpha_bounds(image) for name, image in images.items()} crop = union_bounds(list(bounds_by_name.values()), source_size) crop_height = crop[3] - crop[1] fonts = { "title": load_font(25, semibold=True), "label": load_font(20, semibold=True), "small": load_font(13), } sequences = { "idle": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral"], "throw": ["throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"], } outputs: dict[str, dict[str, object]] = {} for sequence_name, names in sequences.items(): title = f"XIN YIN — {runtime_direction.upper()} {sequence_name.upper()} · 100 / 75 / 50%" boards = [build_board(title, images[name], crop, fonts) for name in names] durations = [int(definitions[name]["durationMs"]) for name in names] output_path = PREVIEW_DIR / f"xinyin-{args.direction}-{sequence_name}-scale-loop-v1.gif" save_gif(boards, durations, output_path) outputs[sequence_name] = { "file": output_path.relative_to(ROOT).as_posix(), "frames": names, "durationsMs": durations, "cycleMs": sum(durations), } bottoms = [bounds[3] for bounds in bounds_by_name.values()] report = { "characterId": "02-xinyin", "direction": args.direction, "runtimeDirection": runtime_direction, "version": 1, "status": "playback-preview-validated", "sourceManifest": manifest_path.relative_to(ROOT).as_posix(), "sourceCanvas": {"width": source_size[0], "height": source_size[1]}, "fixedCrop": {"x": crop[0], "y": crop[1], "width": crop[2] - crop[0], "height": crop_height}, "footBaseline": FOOT_BASELINE, "sourceVisibleBottomRange": {"min": min(bottoms), "max": max(bottoms), "delta": max(bottoms) - min(bottoms)}, "targets": list(TARGETS), "outputs": outputs, "notes": [ "All playback frames use one union crop and one foot baseline; no per-frame recentering is applied.", "GIF timing uses the authored millisecond durations from motion-manifest.json.", "The board background is diagnostic only; source motion PNG files remain transparent.", ], } report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") for image in images.values(): image.close() print(f"Created {len(outputs)} animated playback previews.") print(PREVIEW_DIR) print(report_path) if __name__ == "__main__": main()