|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import os |
| 6 | +from PIL import Image |
| 7 | +from glob import iglob |
| 8 | +from jsonschema import Draft7Validator, ValidationError |
| 9 | +from typing import Any, List, Optional |
| 10 | + |
| 11 | +ALLOWED_RSI_DIR_GARBAGE = { |
| 12 | + "meta.json", |
| 13 | + ".DS_Store", |
| 14 | + "thumbs.db", |
| 15 | + ".directory" |
| 16 | +} |
| 17 | + |
| 18 | +errors: List["RsiError"] = [] |
| 19 | + |
| 20 | +def main() -> int: |
| 21 | + parser = argparse.ArgumentParser("validate_rsis.py", description="Validates RSI file integrity for mistakes the engine does not catch while loading.") |
| 22 | + parser.add_argument("directories", nargs="+", help="Directories to look for RSIs in") |
| 23 | + |
| 24 | + args = parser.parse_args() |
| 25 | + schema = load_schema() |
| 26 | + |
| 27 | + for dir in args.directories: |
| 28 | + check_dir(dir, schema) |
| 29 | + |
| 30 | + for error in errors: |
| 31 | + print(f"{error.path}: {error.message}") |
| 32 | + |
| 33 | + return 1 if errors else 0 |
| 34 | + |
| 35 | + |
| 36 | +def check_dir(dir: str, schema: Draft7Validator): |
| 37 | + for rsi_rel in iglob("**/*.rsi", root_dir=dir, recursive=True): |
| 38 | + rsi_path = os.path.join(dir, rsi_rel) |
| 39 | + try: |
| 40 | + check_rsi(rsi_path, schema) |
| 41 | + except Exception as e: |
| 42 | + add_error(rsi_path, f"Failed to validate RSI (script bug): {e}") |
| 43 | + |
| 44 | + |
| 45 | +def check_rsi(rsi: str, schema: Draft7Validator): |
| 46 | + meta_path = os.path.join(rsi, "meta.json") |
| 47 | + |
| 48 | + # Try to load meta.json |
| 49 | + try: |
| 50 | + meta_json = read_json(meta_path) |
| 51 | + except Exception as e: |
| 52 | + add_error(rsi, f"Failed to read meta.json: {e}") |
| 53 | + return |
| 54 | + |
| 55 | + # Check if meta.json passes schema. |
| 56 | + schema_errors: List[ValidationError] = list(schema.iter_errors(meta_json)) |
| 57 | + if schema_errors: |
| 58 | + for error in schema_errors: |
| 59 | + add_error(rsi, f"meta.json: [{error.json_path}] {error.message}") |
| 60 | + # meta.json may be corrupt, can't safely proceed. |
| 61 | + return |
| 62 | + |
| 63 | + state_names = {state["name"] for state in meta_json["states"]} |
| 64 | + |
| 65 | + # Go over contents of RSI directory and ensure there is no extra garbage. |
| 66 | + for name in os.listdir(rsi): |
| 67 | + if name in ALLOWED_RSI_DIR_GARBAGE: |
| 68 | + continue |
| 69 | + |
| 70 | + if not name.endswith(".png"): |
| 71 | + add_error(rsi, f"Illegal file inside RSI: {name}") |
| 72 | + continue |
| 73 | + |
| 74 | + # All PNGs must be defined in the meta.json |
| 75 | + png_state_name = name[:-4] |
| 76 | + if png_state_name not in state_names: |
| 77 | + add_error(rsi, f"PNG not defined in metadata: {name}") |
| 78 | + |
| 79 | + |
| 80 | + # Validate state delays. |
| 81 | + for state in meta_json["states"]: |
| 82 | + state_name: str = state["name"] |
| 83 | + |
| 84 | + # Validate state delays. |
| 85 | + delays: Optional[List[List[float]]] = state.get("delays") |
| 86 | + if not delays: |
| 87 | + continue |
| 88 | + |
| 89 | + # Validate directions count in metadata and delays count matches. |
| 90 | + directions: int = state.get("directions", 1) |
| 91 | + if directions != len(delays): |
| 92 | + add_error(rsi, f"{state_name}: direction count ({directions}) doesn't match delay set specified ({len(delays)})") |
| 93 | + continue |
| 94 | + |
| 95 | + # Validate that each direction array has the same length. |
| 96 | + lengths: List[float] = [] |
| 97 | + for dir in delays: |
| 98 | + # Robust rounds to millisecond precision. |
| 99 | + lengths.append(round(sum(dir), 3)) |
| 100 | + |
| 101 | + if any(l != lengths[0] for l in lengths): |
| 102 | + add_error(rsi, f"{state_name}: mismatching total durations between state directions: {', '.join(map(str, lengths))}") |
| 103 | + |
| 104 | + frame_width = meta_json["size"]["x"] |
| 105 | + frame_height = meta_json["size"]["y"] |
| 106 | + |
| 107 | + # Validate state PNGs. |
| 108 | + # We only check they're the correct size and that they actually exist and load. |
| 109 | + for state in meta_json["states"]: |
| 110 | + state_name: str = state["name"] |
| 111 | + |
| 112 | + png_name = os.path.join(rsi, f"{state_name}.png") |
| 113 | + try: |
| 114 | + image = Image.open(png_name) |
| 115 | + except Exception as e: |
| 116 | + add_error(rsi, f"{state_name}: failed to open state {state_name}.png") |
| 117 | + continue |
| 118 | + |
| 119 | + # Check that size is a multiple of the metadata frame size. |
| 120 | + size = image.size |
| 121 | + if size[0] % frame_width != 0 or size[1] % frame_height != 0: |
| 122 | + add_error(rsi, f"{state_name}: sprite sheet of {size[0]}x{size[1]} is not size multiple of RSI size ({frame_width}x{frame_height}).png") |
| 123 | + continue |
| 124 | + |
| 125 | + # Check that the sprite sheet is big enough to possibly fit all the frames listed in metadata. |
| 126 | + frames_w = size[0] // frame_width |
| 127 | + frames_h = size[1] // frame_height |
| 128 | + |
| 129 | + directions: int = state.get("directions", 1) |
| 130 | + delays: Optional[List[List[float]]] = state.get("delays", [[1]] * directions) |
| 131 | + frame_count = sum(map(len, delays)) |
| 132 | + max_sheet_frames = frames_w * frames_h |
| 133 | + |
| 134 | + if frame_count > max_sheet_frames: |
| 135 | + add_error(rsi, f"{state_name}: sprite sheet of {size[0]}x{size[1]} is too small, metadata defines {frame_count} frames, but it can only fit {max_sheet_frames} at most") |
| 136 | + continue |
| 137 | + |
| 138 | + # Check if state name exists |
| 139 | + for state in meta_json["states"]: |
| 140 | + state_name: str = state["name"] |
| 141 | + if state_name == "": |
| 142 | + add_error(rsi, f"state name cannot be an empty string.") |
| 143 | + return |
| 144 | + |
| 145 | + # We're good! |
| 146 | + return |
| 147 | + |
| 148 | + |
| 149 | +def load_schema() -> Draft7Validator: |
| 150 | + base_path = os.path.dirname(os.path.realpath(__file__)) |
| 151 | + schema_path = os.path.join(base_path, "rsi-schema.json") |
| 152 | + schema_json = read_json(schema_path) |
| 153 | + |
| 154 | + return Draft7Validator(schema_json) |
| 155 | + |
| 156 | + |
| 157 | +def read_json(path: str) -> Any: |
| 158 | + with open(path, "r", encoding="utf-8-sig") as f: |
| 159 | + return json.load(f) |
| 160 | + |
| 161 | + |
| 162 | +def add_error(rsi: str, message: str): |
| 163 | + errors.append(RsiError(rsi, message)) |
| 164 | + |
| 165 | + |
| 166 | +class RsiError: |
| 167 | + def __init__(self, path: str, message: str): |
| 168 | + self.path = path |
| 169 | + self.message = message |
| 170 | + |
| 171 | + |
| 172 | +exit(main()) |
0 commit comments