"""Small PNG/AtlasTexture readers for art contracts, using only the standard library.""" from functools import lru_cache from hashlib import sha256 from pathlib import Path import re import struct import zlib @lru_cache(maxsize=12) def rgba_png(path: Path) -> tuple[int, int, bytes]: """Decode an ordinary non-interlaced RGBA8 PNG; reject another export format.""" data = path.read_bytes() assert data[:8] == b"\x89PNG\r\n\x1a\n", f"Not a PNG: {path}" offset = 8 payload = bytearray() width = height = 0 while offset < len(data): length = struct.unpack_from(">I", data, offset)[0] kind = data[offset + 4:offset + 8] chunk = data[offset + 8:offset + 8 + length] if kind == b"IHDR": width, height, depth, color_type, compression, filtering, interlace = struct.unpack(">IIBBBBB", chunk) assert (depth, color_type, compression, filtering, interlace) == (8, 6, 0, 0, 0), path elif kind == b"IDAT": payload.extend(chunk) elif kind == b"IEND": break offset += length + 12 stride = width * 4 raw = zlib.decompress(payload) assert width > 0 and height > 0 and len(raw) == (stride + 1) * height, path result = bytearray(stride * height) for y in range(height): start = y * (stride + 1) mode = raw[start] row = bytearray(raw[start + 1:start + 1 + stride]) previous = result[(y - 1) * stride:y * stride] if y else bytes(stride) if mode: for x in range(stride): left = row[x - 4] if x >= 4 else 0 up = previous[x] upper_left = previous[x - 4] if x >= 4 else 0 if mode == 1: prediction = left elif mode == 2: prediction = up elif mode == 3: prediction = (left + up) // 2 elif mode == 4: base = left + up - upper_left distances = (abs(base - left), abs(base - up), abs(base - upper_left)) prediction = (left, up, upper_left)[distances.index(min(distances))] else: raise AssertionError(f"Unknown PNG filter {mode}: {path}") row[x] = (row[x] + prediction) & 255 result[y * stride:(y + 1) * stride] = row return width, height, bytes(result) def atlas_path(root: Path, frames_source: str) -> Path: paths = re.findall(r'\[ext_resource type="Texture2D"[^\n]*path="res://([^\"]+)"', frames_source) assert len(paths) == 1, paths return root / paths[0] def atlas_regions(frames_source: str) -> dict[str, tuple[int, int, int, int]]: regions = {} for name, body in re.findall(r'\[sub_resource type="AtlasTexture" id="([^\"]+)"\]([^\[]+)', frames_source): match = re.search(r'region = Rect2\(([\d.]+), ([\d.]+), ([\d.]+), ([\d.]+)\)', body) assert match, name regions[name] = tuple(int(float(value)) for value in match.groups()) return regions def animation_frames(frames_source: str, name: str) -> list[str]: for frame_block, animation in re.findall( r'"frames":\s*\[(.*?)\],\s*"loop":\s*(?:true|false),\s*"name":\s*&"([^\"]+)"', frames_source, re.S, ): if animation == name: return re.findall(r'SubResource\("([^\"]+)"\)', frame_block) raise AssertionError(f"Missing animation: {name}") def region_hash(image: tuple[int, int, bytes], region: tuple[int, int, int, int]) -> str: width, height, rgba = image x, y, w, h = region assert x >= 0 and y >= 0 and x + w <= width and y + h <= height digest = sha256() for row in range(y, y + h): digest.update(rgba[(row * width + x) * 4:(row * width + x + w) * 4]) return digest.hexdigest()