Files
assets/tools/branding/build.py
T

409 lines
17 KiB
Python

"""Brand files of Create RP: wordmark, icons, banners and the FancyMenu title-screen assets.
python tools/branding/build.py <minecraft_client.jar> <create_mod.jar> <key_art.png> [emblem_raw.png]
Everything is drawn from three sources: Minecraft's own pixel font and block textures (read from the jars, not
stored here), the key art illustration (branding/art/keyart.png) and, if given, a raw emblem picture that is
snapped to a coarse pixel grid. Output goes to branding/ next to this repo's images.
"""
import io
import math
import sys
import zipfile
from pathlib import Path
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(ROOT / 'tools' / 'signs'))
from render import Font # noqa: E402 (the pixel font reader made for the building signs)
OUT = ROOT / 'branding'
NAME = 'CREATE RP'
TAGLINE = 'ДЕРЖАВА ПАРИ Й ШЕСТЕРЕНЬ'
ADDRESS = 'create.fulldroper.ks.ua'
# palette: brass and brick, as the state quarter is built
INK = (38, 24, 16) # outlines
CREAM = (243, 229, 196) # small text
BRICK = (176, 78, 58) # the red of the state's brick buildings
BRASS = [(104, 68, 26), (168, 116, 42), (217, 164, 65), (245, 205, 110)] # dark → light
def texture(jar: zipfile.ZipFile, path: str) -> np.ndarray:
return np.asarray(Image.open(io.BytesIO(jar.read(path))).convert('RGB'))[:16, :16]
def mask_of(font: Font, text: str, bold: bool) -> np.ndarray:
"""The text as font pixels; bold is Minecraft's own bold: the glyph drawn twice, one pixel apart."""
parts = []
for c in text:
g = np.zeros((12, 3), bool) if c == ' ' else font.glyphs[c]
if bold and c != ' ':
g = np.pad(g, ((0, 0), (0, 1))) | np.pad(g, ((0, 0), (1, 0)))
parts += [g, np.zeros((12, 1), bool)]
m = np.hstack(parts[:-1])
rows = np.nonzero(m.any(axis=1))[0]
return m[rows.min():rows.max() + 1]
def shift(m: np.ndarray, dy: int, dx: int) -> np.ndarray:
out = np.zeros_like(m)
h, w = m.shape
out[max(dy, 0):h + min(dy, 0), max(dx, 0):w + min(dx, 0)] = m[max(-dy, 0):h + min(-dy, 0), max(-dx, 0):w + min(-dx, 0)]
return out
def lettering(mask: np.ndarray, fill, scale: int, depth: int = 1, outline: bool = True) -> Image.Image:
"""Letters made of whole texels: lit from the top left, a dark side `depth` font pixels deep, an ink outline."""
pad = 1 + depth
m = np.pad(mask, pad)
h, w = m.shape
yy, xx = np.mgrid[0:h, 0:w]
if isinstance(fill, np.ndarray):
colour = fill[yy % fill.shape[0], xx % fill.shape[1]].astype(np.float32)
else:
colour = np.broadcast_to(np.array(fill, np.float32), (h, w, 3)).copy()
colour[m & ~shift(m, 1, 0)] *= 1.18 # top edge catches the light
colour[m & ~shift(m, 0, 1)] *= 1.08 # left edge a little
colour[m & ~shift(m, -1, 0)] *= 0.80 # bottom edge in shade
side = np.zeros_like(m)
for d in range(1, depth + 1):
side |= shift(m, d, d)
side &= ~m
body = m | side
edge = np.zeros_like(m)
if outline:
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
edge |= shift(body, dy, dx)
edge &= ~body
out = np.zeros((h, w, 4), np.float32)
out[..., :3] = INK
out[side, :3] = np.array(fill.reshape(-1, 3).mean(axis=0) if isinstance(fill, np.ndarray) else fill, np.float32) * 0.45
out[m, :3] = colour[m]
out[body | edge, 3] = 255
img = np.clip(out, 0, 255).astype(np.uint8)
return Image.fromarray(np.repeat(np.repeat(img, scale, 0), scale, 1), 'RGBA')
def stack(images, gap: int, align: str = 'center') -> Image.Image:
w = max(i.width for i in images)
h = sum(i.height for i in images) + gap * (len(images) - 1)
out = Image.new('RGBA', (w, h), (0, 0, 0, 0))
y = 0
for i in images:
out.alpha_composite(i, ((w - i.width) // 2 if align == 'center' else 0, y))
y += i.height + gap
return out
def beside(images, gap: int) -> Image.Image:
h = max(i.height for i in images)
out = Image.new('RGBA', (sum(i.width for i in images) + gap * (len(images) - 1), h), (0, 0, 0, 0))
x = 0
for i in images:
out.alpha_composite(i, (x, h - i.height))
x += i.width + gap
return out
def gear(n: int, teeth: int = 8) -> Image.Image:
"""A brass cogwheel on an n x n pixel grid: the simple mark for icons too small for the emblem."""
ss = 8
c = (n * ss - 1) / 2
yy, xx = np.mgrid[0:n * ss, 0:n * ss]
x, y = (xx - c) / (n * ss / 2), (yy - c) / (n * ss / 2)
r = np.hypot(x, y)
shape = r < 0.70
for k in range(teeth): # straight-sided teeth: the same width on the axes and on the diagonals
t = 2 * math.pi * k / teeth
along, across = x * math.cos(t) + y * math.sin(t), -x * math.sin(t) + y * math.cos(t)
shape |= (np.abs(across) < 0.15) & (along > 0.5) & (along < 0.96)
shape &= r > 0.30
cover = shape.reshape(n, ss, n, ss).mean(axis=(1, 3))
m = cover >= 0.5
light = ((xx - c) * -0.7 + (yy - c) * -0.7).reshape(n, ss, n, ss).mean(axis=(1, 3)) / (n * ss / 2) # lit from the top left
tone = np.clip(np.round(1.6 + light * 1.6), 0, 3).astype(int)
rim = m & ~(shift(m, 1, 0) & shift(m, -1, 0) & shift(m, 0, 1) & shift(m, 0, -1))
out = np.zeros((n, n, 4), np.uint8)
out[m, :3] = np.array(BRASS)[tone][m]
out[rim, :3] = BRASS[0] if n > 16 else BRASS[1]
out[m, 3] = 255
return Image.fromarray(out, 'RGBA')
def on_plate(mark: Image.Image, size: int, plate=(110, 52, 40)) -> Image.Image:
"""An icon: the mark on a brick-red square with a dark frame (for places that show no transparency)."""
n = mark.width
grid = n + 4
out = np.zeros((grid, grid, 4), np.uint8)
out[..., :3] = plate
out[..., 3] = 255
out[0, :, :3] = out[-1, :, :3] = out[:, 0, :3] = out[:, -1, :3] = INK
base = Image.fromarray(out, 'RGBA')
base.alpha_composite(mark, (2, 2))
return base.resize((size, size), Image.NEAREST)
def pixelate(raw: Image.Image, grid: int) -> Image.Image:
"""A generated emblem snapped to a grid x grid picture with a hard alpha edge, so it sits beside pixel lettering."""
im = raw.convert('RGBA')
a = np.asarray(im)[..., 3]
ys, xs = np.nonzero(a > 40)
im = im.crop((xs.min(), ys.min(), xs.max() + 1, ys.max() + 1))
side = max(im.size)
sq = Image.new('RGBA', (side, side), (0, 0, 0, 0))
sq.alpha_composite(im, ((side - im.width) // 2, (side - im.height) // 2))
small = np.asarray(sq.resize((grid, grid), Image.BOX)).copy()
solid = small[..., 3] >= 128
rgb = Image.fromarray(small[..., :3], 'RGB').quantize(64, method=Image.MEDIANCUT).convert('RGB')
small[..., :3] = np.asarray(rgb)
small[..., 3] = np.where(solid, 255, 0)
small[~solid, :3] = INK
return Image.fromarray(small, 'RGBA')
def cover(im: Image.Image, w: int, h: int, focus_y: float = 0.5) -> Image.Image:
s = max(w / im.width, h / im.height)
big = im.resize((round(im.width * s), round(im.height * s)), Image.LANCZOS)
x = (big.width - w) // 2
y = round((big.height - h) * focus_y)
return big.crop((x, y, x + w, y + h))
def shade(im: Image.Image, top: float, bottom: float) -> Image.Image:
"""Darkens the picture with a vertical gradient (1 = untouched), so light lettering reads on it."""
a = np.asarray(im.convert('RGB')).astype(np.float32)
g = np.linspace(top, bottom, a.shape[0], dtype=np.float32)[:, None, None]
return Image.fromarray(np.clip(a * g, 0, 255).astype(np.uint8), 'RGB').convert('RGBA')
def fit(im: Image.Image, max_w: int, max_h: int) -> Image.Image:
"""Pixel art is only ever resized by whole factors."""
k = max(1, min(max_w // im.width, max_h // im.height))
return im.resize((im.width * k, im.height * k), Image.NEAREST)
# Icons of the title screen, drawn on the 13 px grid of Minecraft's own button icons. Each one redraws an icon of the
# FD Icons library (named in the comment). '.' is empty; the other letters are colours from ICON_COLOURS.
ICON_COLOURS = {
'#': (255, 255, 255), '+': (208, 208, 208), # white and the light grey Minecraft shades its icons with
'G': (58, 200, 18), 'g': (0, 150, 0), # server is online
'R': (224, 64, 58), 'r': (160, 38, 32), # server is offline
'A': (249, 168, 37), 'a': (190, 110, 20), # maintenance
}
QUIT_ICON = '''
#######......
#++++++......
#+...........
#+.......#...
#+.......##..
#+..########.
#+..#########
#+..+++++##+.
#+.......#+..
#+.......+...
#+...........
#######......
+++++++......
''' # sign-out: a door frame with an arrow going out
SETTINGS_ICON = '''
.....###.....
..#..###..#..
.###########.
..#########..
..###+++###..
#####...#####
#####...#####
#####...#####
++###...###++
..#########..
.###########.
.+#++###++#+.
.....+++.....
''' # settings: a gear
ONLINE_ICON = '''
....GGGGG....
..GGGGGGGGG..
.GGGGGGGGGGG.
.GGGGGGGG##G.
GGGGGGGG###GG
GGGGGGG###GGG
GG##GG###GGGG
GG######GGGGG
GGg####GGGGGg
.Ggg##GGGGGg.
.gGGGGGGGGgg.
..ggGGGGGgg..
....ggggg....
''' # check-circle
OFFLINE_ICON = '''
....RRRRR....
..RRRRRRRRR..
.RRRRRRRRRRR.
.RR##RRR##RR.
RRR###R###RRR
RRRR#####RRRR
RRRRR###RRRRR
RRRR#####RRRR
RRr###R###RRr
.Rr##RRR##Rr.
.rRRRRRRRRrr.
..rrRRRRRrr..
....rrrrr....
''' # close-circle
MAINTENANCE_ICON = '''
........AAA..
.......AAA...
......AAA....
......AAA...A
......AAAA.AA
......AAAAAAa
.....AAAAAAa.
....AAAAaaa..
...AAAAa.....
..AAAAa......
.AAAAa.......
AAAAa........
AAAa.........
''' # wrench
def button_icon(rows: str, outline: bool = False) -> Image.Image:
"""A 20x20 picture for a 20x20 button; the drawing starts at (4, 4), where Minecraft puts its own icons.
An icon shown without a button behind it gets a dark outline, so it reads on any background."""
im = Image.new('RGBA', (20, 20), (0, 0, 0, 0))
for y, row in enumerate(rows.split()):
for x, c in enumerate(row):
if c != '.':
im.putpixel((4 + x, 4 + y), ICON_COLOURS[c] + (255,))
if outline:
solid = np.asarray(im)[..., 3] > 0
near = np.zeros_like(solid)
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
near |= shift(solid, dy, dx)
edge = Image.new('RGBA', im.size, INK + (255,))
edge.putalpha(Image.fromarray(((near & ~solid) * 255).astype(np.uint8)))
im = Image.alpha_composite(edge, im)
return im
def casing_button(jar: zipfile.ZipFile, casing: str, tone: float = 1.0, grey: float = 0.0) -> Image.Image:
"""A 200x20 button sprite built from a Create casing: black outline, the casing's 3 px metal frame, its wood
inside. The wood is tiled with the block's own 16 px period and the sprite is nine-sliced with a 4 px border,
so the 192 px middle (12 tiles) repeats without a seam on buttons of any width."""
tile = texture(jar, f'assets/create/textures/block/{casing}.png')[..., :3].astype(int)
sheet = np.asarray(Image.open(io.BytesIO(
jar.read(f'assets/create/textures/block/{casing}_connected.png'))).convert('RGBA')).astype(int)
cells = [sheet[ty:ty + 16, tx:tx + 16] for ty in range(0, sheet.shape[0], 16) for tx in range(0, sheet.shape[1], 16)]
# the plain wood is the opaque tile of the connected sheet with the least contrast: every other one has frame in it
wood = min((c for c in cells if c[..., 3].min() == 255), key=lambda c: c[..., :3].std())[..., :3]
px = np.zeros((20, 200, 3), int)
px[1:19, 1:199] = np.tile(wood, (2, 13, 1))[2:20, :198] # wood everywhere inside the outline
for i in range(3): # frame rows and columns, taken from the block's edges
px[1 + i, 1:199] = np.tile(tile[i, 3:13], (20, 1))[:198]
px[18 - i, 1:199] = np.tile(tile[15 - i, 3:13], (20, 1))[:198]
px[1:19, 1 + i] = np.tile(tile[3:13, i], (2, 1))[:18]
px[1:19, 198 - i] = np.tile(tile[3:13, 15 - i], (2, 1))[:18]
for (y, x), (ty, tx) in (((1, 1), (0, 0)), ((1, 196), (0, 13)), ((16, 1), (13, 0)), ((16, 196), (13, 13))):
px[y:y + 3, x:x + 3] = tile[ty:ty + 3, tx:tx + 3] # the four corners
px[1:19, 1:199] = px[1:19, 1:199] * tone
mean = px.mean(axis=2, keepdims=True)
px = np.clip(px * (1 - grey) + mean * grey, 0, 255)
return Image.fromarray(px.astype(np.uint8), 'RGB').convert('RGBA')
BUTTON_META = '{"gui": {"scaling": {"type": "nine_slice", "width": 200, "height": 20, "border": 4}}}\n'
def main() -> None:
mc_jar, create_jar, key_art = sys.argv[1], sys.argv[2], Path(sys.argv[3])
emblem_raw = Path(sys.argv[4]) if len(sys.argv) > 4 else None
with zipfile.ZipFile(mc_jar) as mc, zipfile.ZipFile(create_jar) as cr:
font = Font(mc)
brass = texture(cr, 'assets/create/textures/block/brass_block.png')
buttons = {'button': casing_button(cr, 'andesite_casing', tone=0.82),
'button_highlighted': casing_button(cr, 'brass_casing', tone=1.12),
'button_disabled': casing_button(cr, 'andesite_casing', tone=0.42, grey=0.6)}
for d in ('logo', 'icons', 'banners', 'menu', 'ui'):
(OUT / d).mkdir(parents=True, exist_ok=True)
# --- wordmark: CREATE in brass, RP in brick red, the motto underneath -------------------------
def wordmark(s: int) -> Image.Image:
return beside([lettering(mask_of(font, 'CREATE', True), brass, s, depth=1),
lettering(mask_of(font, 'RP', True), BRICK, s, depth=1)], gap=s * 2)
def motto(s: int, colour=CREAM) -> Image.Image:
return lettering(mask_of(font, TAGLINE, False), colour, s, depth=0)
def mono(s: int, colour) -> Image.Image:
return lettering(mask_of(font, NAME, True), colour, s, depth=0, outline=False)
wordmark(12).save(OUT / 'logo' / 'wordmark.png')
stack([wordmark(12), motto(4)], gap=20).save(OUT / 'logo' / 'logo.png')
mono(12, (255, 255, 255)).save(OUT / 'logo' / 'wordmark-white.png')
mono(12, INK).save(OUT / 'logo' / 'wordmark-dark.png')
# --- marks and icons --------------------------------------------------------------------------
emblem = pixelate(Image.open(emblem_raw), 128) if emblem_raw and emblem_raw.exists() else None
if emblem:
emblem.resize((512, 512), Image.NEAREST).save(OUT / 'logo' / 'emblem.png')
gear(32).resize((512, 512), Image.NEAREST).save(OUT / 'logo' / 'gear.png')
on_plate(gear(28), 64).save(OUT / 'icons' / 'server-icon.png') # Minecraft server list: exactly 64x64
on_plate(gear(28), 512).save(OUT / 'icons' / 'avatar-512.png') # Gitea, Discord, the modpack
gear(16).save(OUT / 'icons' / 'favicon-16x16.png') # game window icon
gear(32).save(OUT / 'icons' / 'favicon-32x32.png')
# --- banners ----------------------------------------------------------------------------------
art = Image.open(key_art).convert('RGB')
night = np.asarray(art.resize((64, 36))).mean() < 70 # a night frame is dark enough: shade it only a little
mark = emblem if emblem else gear(32)
def banner(w: int, h: int, name: str, extra: str = '', focus_y: float = 0.5) -> None:
base = shade(cover(art, w, h, focus_y), *((0.80, 1.0) if night else (0.55, 0.85)))
logo = fit(wordmark(1), int(w * 0.62), int(h * 0.26))
s = logo.width // wordmark(1).width
lines = [logo, fit(motto(1), int(w * 0.62), max(8, s * 4))]
if extra:
lines.append(fit(lettering(mask_of(font, extra, False), BRASS[3], 1, depth=0), int(w * 0.5), max(8, s * 4)))
block = stack(lines, gap=max(6, s * 2))
base.alpha_composite(block, ((w - block.width) // 2, int(h * 0.10)))
addr = fit(lettering(mask_of(font, ADDRESS, False), CREAM, 1, depth=0), int(w * 0.45), max(8, s * 3))
base.alpha_composite(addr, ((w - addr.width) // 2, h - addr.height - int(h * 0.06)))
base.convert('RGB').save(OUT / 'banners' / name, quality=92)
banner(960, 540, 'discord-banner.png')
banner(1280, 720, 'launch.png', extra='ВІДКРИТТЯ СЕРВЕРА')
banner(1200, 630, 'invite.png', extra='ПРИЄДНУЙСЯ')
banner(1280, 320, 'wiki-cover.png', focus_y=0.55)
# --- FancyMenu: title screen background, the logo it shows, window icons -------------------------
shade(cover(art, 1920, 1080), *((0.95, 1.0) if night else (0.80, 0.92))).convert('RGB').save(OUT / 'menu' / 'background.png')
shade(cover(art, 1920, 1080), 0.42, 0.42).convert('RGB').save(OUT / 'menu' / 'background_dim.png') # behind "Connecting…"
stack([wordmark(8), motto(3)], gap=12).save(OUT / 'menu' / 'logo.png')
# --- every button of the game: andesite casing, brass casing under the cursor ---------------------------------
for name, sprite in buttons.items():
sprite.save(OUT / 'ui' / f'{name}.png')
(OUT / 'ui' / f'{name}.png.mcmeta').write_text(BUTTON_META, encoding='utf-8', newline='\n')
button_icon(QUIT_ICON).save(OUT / 'menu' / 'quit.png')
button_icon(SETTINGS_ICON).save(OUT / 'menu' / 'settings.png')
for name, rows in (('online', ONLINE_ICON), ('offline', OFFLINE_ICON), ('maintenance', MAINTENANCE_ICON)):
button_icon(rows, outline=True).save(OUT / 'menu' / f'status-{name}.png')
print('done:', ', '.join(sorted(str(p.relative_to(OUT)).replace('\\', '/') for p in OUT.rglob('*.png'))))
if __name__ == '__main__':
main()