"""Build fixed-cell 16-frame combat, enemy, and interactable atlases. AI character sheets are kept as one-strip generations. Existing four-keyframe world sprites are normalized with one shared scale and motion-warped into a seamless 16-frame loop so runtime rendering never cross-fades two silhouettes. """ from __future__ import annotations from pathlib import Path import cv2 import numpy as np from PIL import Image, ImageDraw ROOT = Path(__file__).resolve().parents[1] ASSETS = ROOT / "assets" ENEMY_RECTS = [ [(194, 66, 220, 149), (544, 46, 232, 168), (905, 63, 382, 151), (1287, 62, 284, 152)], [(156, 260, 269, 182), (535, 259, 259, 184), (906, 262, 381, 182), (1287, 262, 244, 181)], [(131, 490, 298, 197), (429, 461, 385, 226), (858, 469, 429, 218), (1287, 495, 301, 192)], [(167, 687, 173, 184), (517, 687, 341, 181), (858, 687, 429, 186), (1287, 687, 238, 186)], ] INTERACTABLE_RECTS = [ [(20, 92, 271, 187), (331, 92, 270, 187), (644, 92, 271, 187), (957, 92, 270, 187)], [(62, 353, 187, 253), (368, 353, 197, 253), (684, 353, 196, 253), (994, 353, 191, 253)], [(76, 660, 159, 233), (379, 660, 178, 233), (687, 660, 185, 233), (1000, 660, 198, 233)], [(44, 958, 237, 241), (355, 958, 237, 241), (669, 959, 237, 240), (981, 958, 237, 241)], ] def split_grid(image: Image.Image, columns: int, rows: int) -> list[Image.Image]: frames: list[Image.Image] = [] for row in range(rows): for column in range(columns): left = round(column * image.width / columns) right = round((column + 1) * image.width / columns) top = round(row * image.height / rows) bottom = round((row + 1) * image.height / rows) frames.append(image.crop((left, top, right, bottom))) return frames def pack_grid(frames: list[Image.Image], columns: int, out: Path) -> None: width, height = frames[0].size rows = (len(frames) + columns - 1) // columns atlas = Image.new("RGBA", (columns * width, rows * height), (0, 0, 0, 0)) for index, frame in enumerate(frames): atlas.alpha_composite(frame, ((index % columns) * width, (index // columns) * height)) atlas.save(out, optimize=True) def crop_rect(image: Image.Image, rect: tuple[int, int, int, int]) -> Image.Image: x, y, width, height = rect return image.crop((x, y, x + width, y + height)) def normalize_keyframes(frames: list[Image.Image], size: tuple[int, int], padding: int) -> list[Image.Image]: cropped: list[Image.Image] = [] for frame in frames: bbox = frame.getchannel("A").point(lambda value: 255 if value > 8 else 0).getbbox() if bbox is None: raise RuntimeError("Empty sprite keyframe") cropped.append(frame.crop(bbox)) max_width = max(frame.width for frame in cropped) max_height = max(frame.height for frame in cropped) scale = min((size[0] - padding * 2) / max_width, (size[1] - padding * 2) / max_height) output: list[Image.Image] = [] for frame in cropped: resized = frame.resize((round(frame.width * scale), round(frame.height * scale)), Image.Resampling.LANCZOS) canvas = Image.new("RGBA", size, (0, 0, 0, 0)) canvas.alpha_composite(resized, ((size[0] - resized.width) // 2, size[1] - padding - resized.height)) output.append(canvas) return output def rgba_array(image: Image.Image) -> np.ndarray: return np.asarray(image.convert("RGBA"), dtype=np.uint8).copy() def flow_gray(rgba: np.ndarray) -> np.ndarray: alpha = rgba[:, :, 3:4].astype(np.float32) / 255 rgb = rgba[:, :, :3].astype(np.float32) * alpha + np.array([0, 255, 0], dtype=np.float32) * (1 - alpha) return cv2.cvtColor(rgb.astype(np.uint8), cv2.COLOR_RGB2GRAY) def warp(rgba: np.ndarray, flow: np.ndarray, amount: float) -> np.ndarray: height, width = rgba.shape[:2] grid_x, grid_y = np.meshgrid(np.arange(width, dtype=np.float32), np.arange(height, dtype=np.float32)) return cv2.remap(rgba, grid_x - flow[:, :, 0] * amount, grid_y - flow[:, :, 1] * amount, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0, 0)) def motion_interpolate(first: Image.Image, second: Image.Image, amount: float) -> Image.Image: a, b = rgba_array(first), rgba_array(second) gray_a, gray_b = flow_gray(a), flow_gray(b) options = dict(pyr_scale=0.5, levels=4, winsize=25, iterations=4, poly_n=7, poly_sigma=1.5, flags=0) forward = cv2.calcOpticalFlowFarneback(gray_a, gray_b, None, **options) backward = cv2.calcOpticalFlowFarneback(gray_b, gray_a, None, **options) warped_a = warp(a, forward, amount).astype(np.float32) warped_b = warp(b, backward, 1 - amount).astype(np.float32) mixed = np.clip(warped_a * (1 - amount) + warped_b * amount, 0, 255).astype(np.uint8) mixed[:, :, 3] = np.maximum(warped_a[:, :, 3] * (1 - amount), warped_b[:, :, 3] * amount).astype(np.uint8) return Image.fromarray(mixed, "RGBA") def seamless_sixteen(keys: list[Image.Image]) -> list[Image.Image]: output: list[Image.Image] = [] for index, first in enumerate(keys): second = keys[(index + 1) % len(keys)] output.extend([first, motion_interpolate(first, second, 0.25), motion_interpolate(first, second, 0.5), motion_interpolate(first, second, 0.75)]) return output def pack_rows(rows: list[list[Image.Image]], out: Path) -> None: cell_width, cell_height = rows[0][0].size atlas = Image.new("RGBA", (cell_width * 16, cell_height * len(rows)), (0, 0, 0, 0)) for row, frames in enumerate(rows): if len(frames) != 16: raise RuntimeError(f"Row {row} has {len(frames)} frames") for column, frame in enumerate(frames): atlas.alpha_composite(frame, (column * cell_width, row * cell_height)) atlas.save(out, optimize=True) def border_alpha(frame: Image.Image) -> int: alpha = frame.getchannel("A") edges = [alpha.crop((0, 0, alpha.width, 2)), alpha.crop((0, alpha.height - 2, alpha.width, alpha.height)), alpha.crop((0, 0, 2, alpha.height)), alpha.crop((alpha.width - 2, 0, alpha.width, alpha.height))] return max(int(np.asarray(edge).max(initial=0)) for edge in edges) def remove_stray_dark_components(frame: Image.Image) -> Image.Image: """Remove detached dark body fragments while preserving bright note/frost FX.""" rgba = rgba_array(frame) count, labels, stats, _ = cv2.connectedComponentsWithStats((rgba[:, :, 3] > 12).astype(np.uint8), 8) if count <= 2: return frame main = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) for component in range(1, count): if component == main or stats[component, cv2.CC_STAT_AREA] >= 1500: continue mask = labels == component colors = rgba[mask, :3] if colors.size and float(colors.mean()) < 145: rgba[mask] = 0 return Image.fromarray(rgba, "RGBA") def inset_player_frames(frames: list[Image.Image], cell_size: int = 320, padding: int = 12) -> list[Image.Image]: """Preserve the authored cell-center anchor while guaranteeing safe gutters.""" output: list[Image.Image] = [] inner = cell_size - padding * 2 for frame in frames: resized = frame.resize((inner, inner), Image.Resampling.LANCZOS) canvas = Image.new("RGBA", (cell_size, cell_size), (0, 0, 0, 0)) canvas.alpha_composite(resized, (padding, padding)) output.append(remove_stray_dark_components(canvas)) return output def procedural_sixteen(base: Image.Image, style: int) -> list[Image.Image]: """Create a clean single-silhouette loop without alpha-blending creatures.""" source = rgba_array(base) height, width = source.shape[:2] center = (width / 2, height / 2) output: list[Image.Image] = [] for index in range(16): phase = index / 16 * np.pi * 2 angle = np.sin(phase) * (1.1 if style in (1, 3) else 0.45) scale = 1 + np.sin(phase + style * 0.7) * (0.012 if style != 2 else 0.018) matrix = cv2.getRotationMatrix2D(center, angle, scale) matrix[0, 2] += np.cos(phase) * (1.1 if style == 2 else 0.55) matrix[1, 2] += np.sin(phase) * (2.2 if style == 1 else 1.15) warped = cv2.warpAffine(source, matrix, (width, height), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0, 0)) output.append(Image.fromarray(warped, "RGBA")) return output def build_player_atlases() -> None: bow = Image.open(ASSETS / "mafuyu-ice-bow-alpha.png").convert("RGBA") release = Image.open(ASSETS / "mafuyu-ice-release-alpha.png").convert("RGBA") charge = Image.open(ASSETS / "mafuyu-ice-charge-alpha.png").convert("RGBA") attack_source = Image.open(ASSETS / "mafuyu-attack-16-alpha.png").convert("RGBA") bow_frames = inset_player_frames(split_grid(bow, 4, 4)) release_frames = inset_player_frames(split_grid(release, 4, 4)) charge_source = split_grid(charge, 4, 4) # The generated bottom row touches the canvas edge. Use the twelve complete # frames, then ease back through matching poses and finish on frame 01. charge_order = [*range(12), 8, 5, 2, 0] charge_frames = inset_player_frames([charge_source[index] for index in charge_order]) attack_frames = inset_player_frames(split_grid(attack_source, 4, 4)) pack_grid(attack_frames, 4, ASSETS / "mafuyu-attack-16.png") pack_grid(bow_frames, 4, ASSETS / "mafuyu-ice-bow.png") pack_grid(charge_frames, 4, ASSETS / "mafuyu-ice-charge.png") pack_grid(release_frames, 4, ASSETS / "mafuyu-ice-release.png") for label, frames in [("attack", attack_frames), ("bow", bow_frames), ("charge", charge_frames), ("release", release_frames)]: if any(border_alpha(frame) > 12 for frame in frames): raise RuntimeError(f"{label} atlas content touches a frame border") def build_world_atlases() -> None: enemy_source = Image.open(ASSETS / "sekai-enemies.png").convert("RGBA") enemy_rows = [] for style, rects in enumerate(ENEMY_RECTS): keys = normalize_keyframes([crop_rect(enemy_source, rect) for rect in rects], (192, 144), 8) enemy_rows.append(procedural_sixteen(keys[0], style)) pack_rows(enemy_rows, ASSETS / "sekai-enemies-16.png") object_source = Image.open(ASSETS / "sekai-interactables.png").convert("RGBA") object_rows = [] for rects in INTERACTABLE_RECTS: keys = normalize_keyframes([crop_rect(object_source, rect) for rect in rects], (192, 192), 8) object_rows.append(seamless_sixteen(keys)) pack_rows(object_rows, ASSETS / "sekai-interactables-16.png") def build_preview() -> None: sources = [ ("NOTE BLADE", Image.open(ASSETS / "mafuyu-attack-16.png").convert("RGBA"), 4, 4), ("ICE BOW", Image.open(ASSETS / "mafuyu-ice-bow.png").convert("RGBA"), 4, 4), ("CHARGED HOLD LOOP", Image.open(ASSETS / "mafuyu-ice-charge.png").convert("RGBA"), 4, 4), ("CHARGED RELEASE", Image.open(ASSETS / "mafuyu-ice-release.png").convert("RGBA"), 4, 4), ] canvas = Image.new("RGBA", (1080, 1110), (14, 12, 24, 255)) draw = ImageDraw.Draw(canvas) for row, (label, source, columns, rows) in enumerate(sources): frames = split_grid(source, columns, rows) draw.text((20, 18 + row * 270), label, fill=(217, 205, 255, 255)) for column, index in enumerate([0, 3, 6, 9, 12, 15]): frame = frames[index] thumb = frame.copy() thumb.thumbnail((160, 220), Image.Resampling.LANCZOS) canvas.alpha_composite(thumb, (20 + column * 176 + (160 - thumb.width) // 2, 44 + row * 270 + 210 - thumb.height)) canvas.save(ASSETS / "combat-animation-preview.png", optimize=True) if __name__ == "__main__": build_player_atlases() build_world_atlases() build_preview() print("Built 16-frame player, enemy, and interactable atlases.")