Fifteen 256x128 transparent PNGs (2x1 blocks at 128 px per block): Minecraft's pixel font, letters filled with the andesite texture, dark outline. tools/signs/render.py draws them from the font sheets and the block texture inside the client jar. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
6.2 KiB
Python
145 lines
6.2 KiB
Python
"""Building name signs for Immersive Paintings: Minecraft's own pixel font, letters filled with a block
|
|
texture, dark outline, transparent background. 256x128 px = 2x1 blocks at 128 px per block.
|
|
|
|
python render.py <minecraft_client.jar> <out_dir> [preview.png] [--texture andesite]
|
|
|
|
The font sheets and the block texture are read from the client jar and are not stored in this repo.
|
|
One font pixel becomes an s x s square (s chosen per sign so the text fills the plate) and takes the
|
|
colour of one texel of the block texture, so every letter is made of whole "stone pixels".
|
|
"""
|
|
import io
|
|
import json
|
|
import sys
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image
|
|
|
|
W, H = 256, 128
|
|
MARGIN = 6 # canvas px kept free on every side
|
|
MAX_SCALE = 5
|
|
LINE_PITCH = 10 # font px from one baseline to the next (7 px capitals + 3 px gap)
|
|
OUTLINE = 0.30 # outline colour = block texture's mean colour * this
|
|
|
|
SIGNS = {
|
|
'ratusha': ['РАТУША'],
|
|
'ministerstvo': ['МІНІСТЕРСТВО', 'ПРОМИСЛОВОСТІ'],
|
|
'bank': ['ДЕРЖАВНИЙ', 'БАНК'],
|
|
'centr_zainiatosti': ['ЦЕНТР', 'ЗАЙНЯТОСТІ'],
|
|
'poshta': ['ПОШТА'],
|
|
'kontora_importu': ['КОНТОРА', 'ІМПОРТУ'],
|
|
'sklad_derzhavy': ['СКЛАД', 'ДЕРЖАВИ'],
|
|
'inspekcia': ['ІНСПЕКЦІЯ', 'НАДР І ЗЕМЛІ'],
|
|
'efirna_palata': ['ЕФІРНА', 'ПАЛАТА'],
|
|
'shahta': ['ДЕРЖАВНА', 'ШАХТА'],
|
|
'zavod': ['ДЕРЖАВНИЙ', 'ЗАВОД'],
|
|
'pidstancia': ['ПІДСТАНЦІЯ'],
|
|
'bakalia': ['БАКАЛІЯ'],
|
|
'hospodarchyi_lariok': ['ГОСПОДАРЧИЙ', 'ЛАРЬОК'],
|
|
'prylady_i_tekhnika': ['ПРИЛАДИ', 'Й ТЕХНІКА'],
|
|
}
|
|
|
|
|
|
LINE_H, BASELINE = 12, 10 # every glyph sits in a 12 px high row: 3 px for accents, 7 px capitals, 2 px below
|
|
|
|
|
|
class Font:
|
|
"""Minecraft's default bitmap font. Plain glyphs are 8 px high (ascent 7), accented ones such as Й
|
|
come from a sheet with 12 px cells (ascent 10); both are placed on a common baseline."""
|
|
|
|
def __init__(self, jar: zipfile.ZipFile):
|
|
self.glyphs = {}
|
|
providers = json.loads(jar.read('assets/minecraft/font/include/default.json'))['providers']
|
|
for p in providers:
|
|
if p.get('type') != 'bitmap':
|
|
continue
|
|
sheet = np.asarray(Image.open(io.BytesIO(
|
|
jar.read('assets/minecraft/textures/' + p['file'].split(':')[1]))).convert('RGBA'))[..., 3] > 0
|
|
rows = [list(r) for r in p['chars']]
|
|
ch, cw = sheet.shape[0] // len(rows), sheet.shape[1] // len(rows[0])
|
|
top = BASELINE - p['ascent']
|
|
for y, row in enumerate(rows):
|
|
for x, c in enumerate(row):
|
|
if c in ('\u0000', ' ') or c in self.glyphs:
|
|
continue
|
|
cell = sheet[y * ch:(y + 1) * ch, x * cw:(x + 1) * cw]
|
|
cols = np.nonzero(cell.any(axis=0))[0]
|
|
if len(cols):
|
|
g = np.zeros((LINE_H, cols.max() + 1), bool)
|
|
g[top:top + ch] = cell[:LINE_H - top, :cols.max() + 1]
|
|
self.glyphs[c] = g
|
|
|
|
def line(self, text: str) -> np.ndarray:
|
|
parts = []
|
|
for c in text:
|
|
g = np.zeros((LINE_H, 3), bool) if c == ' ' else self.glyphs[c]
|
|
parts += [g, np.zeros((LINE_H, 1), bool)]
|
|
return np.hstack(parts[:-1])
|
|
|
|
|
|
def render(font: Font, lines: list[str], tile: np.ndarray) -> Image.Image:
|
|
rows = [font.line(t) for t in lines]
|
|
width = max(r.shape[1] for r in rows)
|
|
# a line with accents above the capitals (Й, Ї) needs more room, or the accent touches the line above
|
|
tops = [0]
|
|
for r in rows[1:]:
|
|
tops.append(tops[-1] + (LINE_PITCH + 2 if r[:BASELINE - 7].any() else LINE_PITCH))
|
|
mask = np.zeros((tops[-1] + LINE_H, width), bool)
|
|
for top, r in zip(tops, rows):
|
|
x = (width - r.shape[1]) // 2
|
|
mask[top:top + LINE_H, x:x + r.shape[1]] |= r
|
|
ys = np.nonzero(mask.any(axis=1))[0]
|
|
mask = np.pad(mask[ys.min():ys.max() + 1], 1) # trim empty rows, leave room for the outline
|
|
|
|
near = np.zeros_like(mask)
|
|
for dy in (-1, 0, 1):
|
|
for dx in (-1, 0, 1):
|
|
near |= np.roll(np.roll(mask, dy, 0), dx, 1)
|
|
outline = near & ~mask
|
|
|
|
h, w = mask.shape
|
|
scale = max(1, min(MAX_SCALE, (W - 2 * MARGIN) // w, (H - 2 * MARGIN) // h))
|
|
yy, xx = np.mgrid[0:h, 0:w]
|
|
dark = (tile.reshape(-1, 3).mean(axis=0) * OUTLINE).astype(np.uint8)
|
|
small = np.zeros((h, w, 4), np.uint8)
|
|
small[..., :3] = dark
|
|
small[mask, :3] = tile[yy % tile.shape[0], xx % tile.shape[1]][mask]
|
|
small[mask | outline, 3] = 255
|
|
|
|
big = np.repeat(np.repeat(small, scale, 0), scale, 1)
|
|
out = np.zeros((H, W, 4), np.uint8)
|
|
out[..., :3] = dark # no foreign colour under the transparency
|
|
oy, ox = (H - big.shape[0]) // 2, (W - big.shape[1]) // 2
|
|
out[oy:oy + big.shape[0], ox:ox + big.shape[1]] = big
|
|
return Image.fromarray(out, 'RGBA'), scale
|
|
|
|
|
|
def main() -> None:
|
|
args = [a for a in sys.argv[1:] if not a.startswith('--')]
|
|
texture = sys.argv[sys.argv.index('--texture') + 1] if '--texture' in sys.argv else 'andesite'
|
|
out_dir = Path(args[1])
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
with zipfile.ZipFile(args[0]) as jar:
|
|
font = Font(jar)
|
|
tile = np.asarray(Image.open(io.BytesIO(
|
|
jar.read(f'assets/minecraft/textures/block/{texture}.png'))).convert('RGB'))
|
|
done = []
|
|
for name, lines in SIGNS.items():
|
|
im, scale = render(font, lines, tile)
|
|
im.save(out_dir / f'{name}.png', optimize=True)
|
|
done.append(im)
|
|
print(f'{name}: {" / ".join(lines)} — font pixel {scale} px')
|
|
if len(args) > 2:
|
|
cols, z = 3, 2
|
|
rows = (len(done) + cols - 1) // cols
|
|
sheet = Image.new('RGB', (cols * (W * z + 8) + 8, rows * (H * z + 8) + 8), (110, 52, 40)) # brick red
|
|
for i, im in enumerate(done):
|
|
im = im.resize((W * z, H * z), Image.NEAREST)
|
|
sheet.paste(im, (8 + (i % cols) * (W * z + 8), 8 + (i // cols) * (H * z + 8)), im)
|
|
sheet.save(args[2])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|