Files
LihonT/scripts/build_frames_catalog.py
cheb0chik d40c17b083 LihonT 2 Serena beta
Avatar frames that follow the outline of the avatar (ring and parts hung on it), packs of frames that arrive from a catalog on the
site by themselves, the frame shown to other members through the members service, save an avatar by user name, the diary of the
mod, the seek bar on every video, the beta version line and its what is new, plus tests, the catalog builder, the sprites and the
scripts that draw them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 10:30:22 +03:00

108 lines
4.6 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Builds the catalog of avatar frames that the mod downloads: frames/index.json, from every frames/<pack>/pack.json and the sprites
(PNG files) next to it. The catalog lists each sprite with its checksum, size and picture size, and each frame with its ring and its
parts; the mod refuses anything that does not match, so a pack is only ever what was built here.
To add a pack: make frames/<pack>/ with pack.json (see frames/basic/pack.json) and the sprites, run this script, and put the
frames/ folder on the site (scripts/stage_site.py takes it along). Phones pick the new pack up by themselves.
usage (from the repository root):
py -X utf8 -B scripts/build_frames_catalog.py # writes frames/index.json
py -X utf8 -B scripts/build_frames_catalog.py --check # exits 1 if frames/index.json is out of date
"""
from __future__ import annotations
import hashlib
import json
import re
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FRAMES = ROOT / "frames"
INDEX = FRAMES / "index.json"
ID = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\Z")
SPRITE = re.compile(r"[a-z0-9][a-z0-9_.-]{0,47}\.png\Z")
COLOR = re.compile(r"#[0-9a-f]{6}\Z")
MAX_SPRITE_BYTES = 150 * 1024
MAX_PARTS = 80
def png_size(data: bytes) -> tuple[int, int]:
if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":
raise SystemExit("not a PNG")
return struct.unpack(">II", data[16:24])
def build_pack(folder: Path) -> dict:
pack = json.loads((folder / "pack.json").read_text(encoding="utf-8"))
pack_id = pack["id"]
if not ID.match(pack_id) or pack_id != folder.name:
raise SystemExit("%s: the pack id must be the folder name, lower case" % folder)
sprites = {}
frames = []
for frame in pack["frames"]:
if not ID.match(frame["id"]):
raise SystemExit("%s: bad frame id %r" % (pack_id, frame["id"]))
ring = frame["ring"]
if not all(COLOR.match(c) for c in ring["fill"] + [ring["ink"]]):
raise SystemExit("%s.%s: colours must be #rrggbb in lower case" % (pack_id, frame["id"]))
if len(frame["parts"]) > MAX_PARTS:
raise SystemExit("%s.%s: too many parts" % (pack_id, frame["id"]))
parts = []
for part in frame["parts"]:
name = part["sprite"]
if not SPRITE.match(name) or ".." in name:
raise SystemExit("%s.%s: bad sprite name %r" % (pack_id, frame["id"], name))
if name not in sprites:
data = (folder / name).read_bytes()
if len(data) > MAX_SPRITE_BYTES:
raise SystemExit("%s: %s is %d bytes, at most %d" % (pack_id, name, len(data), MAX_SPRITE_BYTES))
width, height = png_size(data)
sprites[name] = {"file": "%s/%s" % (pack_id, name), "sha256": hashlib.sha256(data).hexdigest(),
"bytes": len(data), "w": width, "h": height}
entry = {"file": sprites[name]["file"]}
for key in ("ax", "ay", "at", "size", "turn", "radial"):
if key in part:
entry[key] = part[key]
if part.get("flip"):
entry["flip"] = True
if part.get("layer") == "front":
entry["layer"] = "front"
parts.append(entry)
frames.append({"id": frame["id"], "name": frame["name"], "ring": ring, "parts": parts})
return {"id": pack_id, "name": pack["name"], "version": pack["version"],
"sprites": list(sprites.values()), "frames": frames}
def build() -> str:
packs = [build_pack(folder) for folder in sorted(FRAMES.iterdir()) if (folder / "pack.json").is_file()]
catalog = {"version": 1, "packs": packs}
return json.dumps(catalog, ensure_ascii=False, indent=1) + "\n"
def main() -> None:
text = build()
if len(text.encode("utf-8")) > 262144:
raise SystemExit("the catalog is larger than the 256 KB the mod accepts")
if "--check" in sys.argv:
current = INDEX.read_text(encoding="utf-8") if INDEX.is_file() else ""
if current.replace("\r\n", "\n") != text:
print("frames/index.json is out of date: run scripts/build_frames_catalog.py")
raise SystemExit(1)
print("frames/index.json is up to date")
return
INDEX.write_text(text, encoding="utf-8", newline="\n")
catalog = json.loads(text)
print("frames/index.json: %d packs, %d frames, %d sprites, %d bytes" % (
len(catalog["packs"]), sum(len(p["frames"]) for p in catalog["packs"]),
sum(len(p["sprites"]) for p in catalog["packs"]), len(text.encode("utf-8"))))
if __name__ == "__main__":
main()