Files
LihonT/scripts/frame_render.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

178 lines
6.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Draws a frame on an avatar of any shape exactly as the application does (FrameDraw.java): the ring follows the outline of the
shape, and every part hangs on a point of that outline given by an angle, turned to look away from the avatar there.
usage (from the repository root):
py -X utf8 -B scripts/frame_render.py [shape] # work/frames/frames_on_<shape>.png: all frames on one shape
py -X utf8 -B scripts/frame_render.py --grid # work/frames/frames_grid.png: every frame on every shape
"""
from __future__ import annotations
import json
import math
import sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageChops, ImageDraw, ImageFont
from scipy import ndimage
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_frame_on_shape as S # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
PACK = ROOT / "frames" / "basic"
OUT = ROOT / "work" / "frames"
SS = 2
def hexcolor(text):
return tuple(int(text[i:i + 2], 16) for i in (1, 3, 5)) + (255,)
def outline_table(mask, d):
"""r(theta) for theta = 0..359 degrees clockwise from the top: how far the shape reaches from its middle."""
px = mask.load()
table = []
for deg in range(360):
a = math.radians(deg)
r = d / 2.0
while r > 0:
x, y = d / 2 + r * math.sin(a), d / 2 - r * math.cos(a)
if 0 <= x < mask.width and 0 <= y < mask.height and px[int(x), int(y)] > 127:
break
r -= 0.5
table.append(r)
return table
def at(table, deg, d):
deg %= 360
i = int(math.floor(deg))
f = deg - i
r = table[i % 360] * (1 - f) + table[(i + 1) % 360] * f
a = math.radians(deg)
return d / 2 + r * math.sin(a), d / 2 - r * math.cos(a)
def normal_degrees(table, deg, d):
"""The direction away from the avatar at that point: the turn (degrees clockwise from up) that points a sprite outwards."""
p0, p1 = at(table, deg - 3, d), at(table, deg + 3, d)
tx, ty = p1[0] - p0[0], p1[1] - p0[1]
nx, ny = ty, -tx
return math.degrees(math.atan2(nx, -ny))
def sprite(name, cache={}): # noqa: B006
if name not in cache:
cache[name] = Image.open(PACK / name).convert("RGBA")
return cache[name]
def draw_part(canvas, part, table, d, cx, cy):
img = sprite(part["sprite"])
deg = part["at"]
px, py = at(table, deg, d)
nx, ny = px - d / 2, py - d / 2
ln = math.hypot(nx, ny) or 1.0
radial = part.get("radial", 0.0) * d
px, py = px + nx / ln * radial, py + ny / ln * radial
turn = normal_degrees(table, deg, d) + part.get("turn", 0)
width = part["size"] * d
scale = width / img.width
sp = img.resize((max(1, int(img.width * scale * SS)), max(1, int(img.height * scale * SS))), Image.LANCZOS)
if part.get("flip"):
sp = sp.transpose(Image.FLIP_LEFT_RIGHT)
ax = part["ax"] if not part.get("flip") else 1 - part["ax"]
pad = int(math.hypot(sp.width, sp.height)) + 2
holder = Image.new("RGBA", (pad * 2, pad * 2), (0, 0, 0, 0))
holder.alpha_composite(sp, (pad - int(ax * sp.width), pad - int(part["ay"] * sp.height)))
holder = holder.rotate(-turn, resample=Image.BICUBIC, center=(pad, pad))
canvas.alpha_composite(holder, (int(cx + (px - d / 2) * SS - pad), int(cy + (py - d / 2) * SS - pad)))
def render(frame, shape, size=1000, d=520):
"""The frame on an avatar of `shape`; the avatar box is d pixels wide, in the middle of a size-by-size picture."""
s = d * SS
cx = cy = size * SS / 2
cy += 40 * SS
canvas = Image.new("RGBA", (size * SS, size * SS), (0, 0, 0, 0))
mask = S.shape_mask(shape, d)
big = mask.resize((s, s), Image.LANCZOS)
table = outline_table(big, s)
table = [r / SS for r in table]
ring = frame["ring"]
rw, lw = ring["width"] * d * SS, ring["line"] * d * SS
holder = Image.new("L", canvas.size, 0)
holder.paste(big, (int(cx - s / 2), int(cy - s / 2)))
for part in frame["parts"]:
if part.get("layer", "back") == "back":
draw_part(canvas, part, table, d, cx, cy)
outer = grow(holder, rw + lw)
mid = grow(holder, rw)
canvas.paste(Image.new("RGBA", canvas.size, hexcolor(ring["ink"])), (0, 0), outer)
top, bottom = hexcolor(ring["fill"][0]), hexcolor(ring["fill"][1])
g = Image.linear_gradient("L").resize(canvas.size)
fill = Image.merge("RGBA", [g.point(lambda v, a=top[i], b=bottom[i]: a + (b - a) * v // 255) for i in range(3)]
+ [Image.new("L", canvas.size, 255)])
canvas.paste(fill, (0, 0), mid)
av = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
avatar = S.avatar(d).resize((s, s), Image.LANCZOS)
av.paste(avatar, (int(cx - s / 2), int(cy - s / 2)), holder.crop((int(cx - s / 2), int(cy - s / 2), int(cx + s / 2), int(cy + s / 2))))
canvas.alpha_composite(av)
edge = ImageChops.subtract(grow(holder, lw), holder)
canvas.paste(Image.new("RGBA", canvas.size, hexcolor(ring["ink"])), (0, 0), edge)
for part in frame["parts"]:
if part.get("layer") == "front":
draw_part(canvas, part, table, d, cx, cy)
return canvas.resize((size, size), Image.LANCZOS)
def grow(mask, radius):
"""The mask grown by `radius` pixels in every direction (a real distance, so the corners are round like a stroke's join)."""
inside = np.asarray(mask) > 127
reach = ndimage.distance_transform_edt(~inside) <= radius
return Image.fromarray((reach * 255).astype("uint8"), "L")
def font(n):
for name in ("C:/Windows/Fonts/arialbd.ttf", "C:/Windows/Fonts/segoeuib.ttf"):
try:
return ImageFont.truetype(name, n)
except OSError:
pass
return None
def main() -> None:
pack = json.loads((PACK / "pack.json").read_text(encoding="utf-8"))
OUT.mkdir(parents=True, exist_ok=True)
frames = pack["frames"]
if "--grid" in sys.argv:
shapes = ("circle", "flower", "squircle", "hexagon", "heart", "triangle")
tile = 300
sheet = S.background(tile * len(shapes), tile * len(frames) + 30)
for row, frame in enumerate(frames):
for col, shape in enumerate(shapes):
sheet.alpha_composite(render(frame, shape, 1000, 520).resize((tile, tile), Image.LANCZOS), (col * tile, row * tile))
sheet.convert("RGB").save(OUT / "frames_grid.png")
print(OUT / "frames_grid.png")
return
shape = sys.argv[1] if len(sys.argv) > 1 else "flower"
tile = 540
sheet = S.background(tile * 3, tile * 2 + 60)
d = ImageDraw.Draw(sheet)
for i, frame in enumerate(frames):
x, y = (i % 3) * tile, (i // 3) * tile
sheet.alpha_composite(render(frame, shape, 1000, 520).resize((tile, tile), Image.LANCZOS), (x, y))
d.text((x + tile / 2, y + tile - 14), frame["name"], font=font(34), fill=(40, 30, 40, 255), anchor="mm")
sheet.convert("RGB").save(OUT / ("frames_on_" + shape + ".png"))
print(OUT / ("frames_on_" + shape + ".png"))
if __name__ == "__main__":
main()