Files
assets/tools/branding/fancymenu.py
T

331 lines
18 KiB
Python

"""Installs the Create RP look of the game's menus into a game folder — a profile or the client pack.
python tools/branding/fancymenu.py <config dir> <1.21.1.jar> [pack version]
<config dir> is the pack's or the profile's config/. The version is read from pack.toml next to it when not given.
Run it again after every version bump: the version label is a picture and the update check compares with it.
What it writes:
config/fancymenu/assets/ pictures: background, logo, icons, version and update labels
config/fancymenu/customization/ layouts, built here from fancymenu_template.txt:
createrp_title.txt the title screen
createrp_screens.txt connecting / loading / disconnected screens: our background and logo
createrp_pause.txt the game menu
config/fancymenu/custom_gui_screens.txt the game menu is our own screen that replaces Minecraft's one, so that
buttons other mods add to the pause screen (Mods, Create) never get into it
config/fancymenu/customizablemenus.txt, options.txt which screens are customised; window title and icon
kubejs/assets/minecraft/…/widget/ button sprites for the whole game: andesite casing, brass under the cursor
config/create-client.toml Create's own button is taken out of the title screen and the game menu
"""
import re
import shutil
import sys
import uuid
import zipfile
from pathlib import Path
import numpy as np
from PIL import Image
ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(ROOT / 'tools' / 'signs'))
from render import BASELINE, LINE_H, Font # noqa: E402 (the pixel font reader made for the building signs)
MENU, ICONS, UI = ROOT / 'branding' / 'menu', ROOT / 'branding' / 'icons', ROOT / 'branding' / 'ui'
WINDOW_TITLE = 'Create RP'
HOST = 'create.fulldroper.ks.ua'
GIT = 'https://git.fulldroper.ks.ua/Pinecraft-CreateRP/client'
LATEST_RELEASE = 'https://git.fulldroper.ks.ua/api/v1/repos/Pinecraft-CreateRP/client/releases/latest'
ASSET = '[source:local]/config/fancymenu/assets/'
SCREENS = 'net.minecraft.client.gui.screens.'
# screens that get our background and logo: (FancyMenu's name, class)
PLAIN_SCREENS = [('connect_screen', 'ConnectScreen'), ('disconnected_screen', 'DisconnectedScreen'),
('generic_dirt_message_screen', 'GenericMessageScreen'), ('receiving_level_screen', 'ReceivingLevelScreen'),
('progress_screen', 'ProgressScreen'), ('level_loading_screen', 'LevelLoadingScreen')]
PAUSE_GUI = 'createrp_pause'
# --- FancyMenu's file format: "name {", " key = value" lines, "}" -------------------------------------------------
def parse(text: str) -> list:
blocks = []
for chunk in text.replace('\r\n', '\n').strip().split('\n\n'):
lines = chunk.split('\n')
if not lines[0].endswith('{'):
continue # the "type = …" line
props = {}
for line in lines[1:-1]:
key, _, value = line[2:].partition(' =')
props[key] = value[1:] if value.startswith(' ') else value
blocks.append((lines[0][:-2], props))
return blocks
def dump(kind: str, blocks: list) -> str:
out = [f'type = {kind}']
for name, props in blocks:
out.append('\n'.join([name + ' {'] + [f' {k} = {v}' for k, v in props.items()] + ['}']))
return '\n\n'.join(out) + '\n\n'
TEMPLATE = parse(Path(__file__).with_name('fancymenu_template.txt').read_text(encoding='utf-8'))
HEAD = [b for b in TEMPLATE if b[0] not in ('element', 'vanilla_button')]
IMAGE = next(p for n, p in TEMPLATE if p.get('element_type') == 'image')
BUTTON = next(p for n, p in TEMPLATE if p.get('element_type') == 'custom_button')
VANILLA = next(p for n, p in TEMPLATE if n == 'vanilla_button')
ID = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}-\d{13}')
def uid(name: str) -> str:
"""An identifier in the shape FancyMenu gives its own, stable from run to run."""
return f'{uuid.uuid5(uuid.NAMESPACE_URL, "createrp/" + name)}-1791960000000'
# --- requirements: conditions FancyMenu checks while the screen is shown ---------------------------------------------
ONLINE, TEXT, SERVER_IP = ('fancymenu_loading_requirement_is_server_online', 'fancymenu_visibility_requirement_is_text',
'fancymenu_visibility_requirement_is_server_ip')
MULTIPLAYER = 'fancymenu_loading_requirement_is_multiplayer'
MOTD = '{"placeholder":"servermotd","values":{"ip":"%s","line":"1"}}' % HOST
LATEST = '{"placeholder":"json","values":{"source":"%s","json_path":"$.tag_name"}}' % LATEST_RELEASE
def text_is(mode: str, text: str, compare: str) -> str:
return f'["mode":"{mode}","text":"{text}","compare_with":"{compare}"]$'
def server(state: str) -> list:
"""What the server list ping says. No answer: offline. The proxy answers with its own MOTD while the game server
is stopped: maintenance. The game server's MOTD has "Create" in it: online."""
answers, ours = (ONLINE, 'if', HOST), text_is('contains', MOTD, 'Create')
return {'online': [answers, (TEXT, 'if', ours)], 'maintenance': [answers, (TEXT, 'if_not', ours)],
'offline': [(ONLINE, 'if_not', HOST)]}[state]
NEVER = [(TEXT, 'if', text_is('equals', 'a', 'b'))]
class Layout:
def __init__(self, name: str, identifier: str, background: str = '', whitelist=(), fireflies: bool = False):
self.name, self.count, self.blocks = name, 0, []
for kind, template in HEAD:
props = self._fresh(template, kind)
if kind == 'layout-meta':
props['identifier'] = identifier
if whitelist:
props['universal_layout_whitelist'] = ''.join(s + ';' for s in whitelist)
elif kind == 'menu_background':
shown = bool(background) and props['background_type'] == 'image'
props['show_background'] = str(shown).lower()
if shown:
props['image_path'] = ASSET + background
elif kind == 'decoration_overlay':
props['show_decoration_overlay'] = str(fireflies and props['overlay_type'] == 'fireflies').lower()
self.blocks.append((kind, props))
def _fresh(self, template: dict, tag: str) -> dict:
"""A copy of a template block with identifiers of its own."""
self.count += 1
seen = {}
def swap(s: str) -> str:
return ID.sub(lambda m: seen.setdefault(m.group(0), uid(f'{self.name}/{tag}/{self.count}/{len(seen)}')), s)
return {swap(k): swap(v) for k, v in template.items()}
@staticmethod
def _require(props: dict, container_key: str, reqs) -> None:
container, ids = props[container_key], []
for n, (requirement, mode, value) in enumerate(reqs):
ids.append(uid(f'{container}/{n}'))
props[f'[loading_requirement:{requirement}][requirement_mode:{mode}][req_id:{ids[-1]}]'] = value
props[f'[loading_requirement_container_meta:{container}]'] = '[groups:][instances:' + ''.join(i + ';' for i in ids) + ']'
@staticmethod
def _place(props: dict, anchor: str, x: int, y: int, w: int, h: int) -> None:
props.update(anchor_point=anchor, x=str(x), y=str(y), width=str(w), height=str(h))
def image(self, source: str, anchor: str, x: int, y: int, w: int, h: int, visible=()) -> None:
props = self._fresh(IMAGE, 'image')
props['source'] = ASSET + source
self._place(props, anchor, x, y, w, h)
self._require(props, 'element_loading_requirement_container_identifier', visible)
self.blocks.append(('element', props))
def button(self, anchor: str, x: int, y: int, w: int, h: int = 20, label: str = '', icon: str = '', tooltip: str = '',
action=None, transparent: bool = False, active=(), visible=()) -> None:
"""A button of ours. `icon` is a picture drawn over it at the button's height; `action` is (type, value)."""
props = self._fresh(BUTTON, 'button')
if label:
props['label'] = label
if icon:
props['iconnormal'] = props['iconhovered'] = props['icon_texture_inactive'] = ASSET + icon
if tooltip:
props['description'] = tooltip
if action:
act = uid(props['instance_identifier'] + '/action')
props[f'[executable_action_instance:{act}][action_type:{action[0]}]'] = action[1]
props[f"[executable_block:{props['button_element_executable_block_identifier']}][type:generic]"] = f'[executables:{act};]'
props['transparent_background'] = str(transparent).lower()
self._place(props, anchor, x, y, w, h)
self._require(props, 'widget_active_state_requirement_container_identifier', active)
self._require(props, 'element_loading_requirement_container_identifier', visible)
self.blocks.append(('element', props))
def vanilla(self, identifier: str, hidden: bool = False, anchor: str = 'vanilla', x: int = 0, y: int = 0, w: int = 0,
h: int = 20, label: str = '') -> None:
"""A widget of the screen itself: moved (any anchor but "vanilla"), renamed or hidden."""
props = self._fresh(VANILLA, 'vanilla')
props['instance_identifier'] = identifier
if label:
props['label'] = label
self._place(props, anchor, x, y, w, h)
props['is_hidden'] = str(hidden).lower()
self.blocks.append(('vanilla_button', props))
def text(self) -> str:
return dump('fancymenu_layout', self.blocks)
# --- the screens ------------------------------------------------------------------------------------------------------
def title_screen(version: str, labels: dict) -> Layout:
lay = Layout('title', 'title_screen', background='background.png', fireflies=True)
lay.image('logo.png', 'mid-centered', -110, -104, 221, 60)
# a button-high gap under the logo, then rows 24 apart
lay.button('mid-centered', -100, -24, 200, label='Грати', action=('joinserver', HOST), active=server('online'))
for state, tip in (('online', 'Сервер онлайн'), ('maintenance', 'Технічні роботи'), ('offline', 'Сервер офлайн')):
lay.button('mid-centered', 104, -24, 20, icon=f'status-{state}.png', tooltip=tip, transparent=True, visible=server(state))
lay.vanilla('mc_titlescreen_singleplayer_button', anchor='mid-centered', x=-100, y=0, w=98)
lay.vanilla('mc_titlescreen_multiplayer_button', anchor='mid-centered', x=2, y=0, w=98, label='Сервери')
# bottom right corner: language, options, quit. Anchors give the corner; offsets are the element's top left.
lay.vanilla('376388', anchor='bottom-right', x=-72, y=-24, w=20) # language
lay.button('bottom-right', -48, -24, 20, icon='settings.png', tooltip='Налаштування',
action=('opengui', SCREENS + 'options.OptionsScreen'))
lay.button('bottom-right', -24, -24, 20, icon='quit.png', tooltip='Вийти з гри', action=('quitgame', ''))
lay.vanilla('title_screen_copyright_button', anchor='bottom-centered', x=-98, y=-12, w=196, h=10)
# bottom left corner: the pack version and whether a newer release is out
vw, vh = labels['version'].size
lay.image('version.png', 'bottom-left', 2, -vh - 2, vw, vh)
tag, (w, h) = 'v' + version, labels['uptodate'].size
lay.image('uptodate.png', 'bottom-left', vw + 8, -vh - 2, w, h, visible=[(TEXT, 'if', text_is('equals', LATEST, tag))])
w, h = labels['update'].size
lay.button('bottom-left', vw + 8, -vh - 2, w, h, icon='update.png', transparent=True,
tooltip='Нова версія збірки: ' + LATEST + '. Натисни, щоб відкрити сторінку завантаження.',
action=('openlink', GIT + '/releases/latest'),
visible=[(TEXT, 'if', text_is('starts-with', LATEST, 'v')), (TEXT, 'if_not', text_is('equals', LATEST, tag))])
for gone in ('376306', '604388', # Create's button, accessibility
'forge_titlescreen_mods_button', 'mc_titlescreen_options_button', 'mc_titlescreen_quit_button',
'mc_titlescreen_realms_button', 'minecraft_branding_widget', 'minecraft_splash_widget',
'minecraft_logo_widget', 'minecraft_realms_notification_icons_widget'):
lay.vanilla(gone, hidden=True)
return lay
def plain_screens() -> Layout:
"""Connecting, loading terrain, disconnected and the like: the dimmed key art and the logo at the top."""
lay = Layout('screens', '%fancymenu:universal_layout%', background='background_dim.png',
whitelist=[name for name, _ in PLAIN_SCREENS])
lay.image('logo.png', 'top-centered', -110, 16, 221, 60)
return lay
def game_menu() -> Layout:
lay = Layout('pause', PAUSE_GUI)
lay.image('logo.png', 'mid-centered', -110, -112, 221, 60)
lay.button('mid-centered', -102, -28, 204, label='Назад до гри', action=('closegui', ''))
lay.button('mid-centered', -102, -4, 100, label='Залишити відгук', active=NEVER)
lay.button('mid-centered', 2, -4, 100, label='Знайшов баг?', action=('openlink', GIT + '/issues/new'),
tooltip='Відкриє в браузері сторінку створення задачі в нашому Git')
lay.button('mid-centered', -102, 20, 100, label='Налаштування...', action=('opengui', SCREENS + 'options.OptionsScreen'))
lay.button('mid-centered', 2, 20, 100, label='Скарги на гравців', active=NEVER)
# leaving: from our server straight to the title screen, from another one to the server list as usual
ours, online = (SERVER_IP, 'if', HOST), (MULTIPLAYER, 'if', '')
elsewhere = (SERVER_IP, 'if_not', HOST)
for label, after, when in (("Від'єднатися", 'title_screen', [ours]),
("Від'єднатися", 'join_multiplayer_screen', [elsewhere, online]),
('Зберегти й вийти в меню', 'title_screen', [elsewhere, (MULTIPLAYER, 'if_not', '')])):
lay.button('mid-centered', -102, 44, 204, label=label, action=('disconnect_server_or_world', after), visible=when)
return lay
CUSTOM_GUIS = dump('custom_gui_screens', [
('overridden_screens', {'pause_screen': PAUSE_GUI}),
('custom_gui', {'identifier': PAUSE_GUI, 'title': 'Ігрове меню', 'allow_esc': 'true',
'transparent_world_background': 'true', 'transparent_world_background_overlay': 'true',
'pause_game': 'true', 'popup_mode': 'false', 'popup_mode_background_overlay': 'true'})])
# --- pictures made here ---------------------------------------------------------------------------------------------
def label(font: Font, text: str, colour=(255, 255, 255)) -> Image.Image:
"""A line of text exactly as the game draws it: with the dark shadow one pixel down and right. Every label is
10 px high — capitals, room for descenders, the shadow — so labels put side by side share a baseline."""
mask = font.line(text)[BASELINE - 7:LINE_H]
h, w = mask.shape
px = np.zeros((h + 1, w + 1, 4), np.uint8)
px[1:, 1:][mask] = tuple(c // 4 for c in colour) + (255,)
px[:-1, :-1][mask] = colour + (255,)
return Image.fromarray(px, 'RGBA')
def option(text: str, key: str, value: str) -> str:
pattern = re.compile(r"^(\w:" + re.escape(key) + r" = ')[^']*(';)", re.M)
if not pattern.search(text):
raise SystemExit('FancyMenu option not found: ' + key)
return pattern.sub(lambda m: m.group(1) + value + m.group(2), text)
def main() -> None:
config = Path(sys.argv[1])
fm = config / 'fancymenu'
if len(sys.argv) > 3:
version = sys.argv[3]
else:
version = re.search(r'^version = "([^"]+)"', (config.parent / 'pack.toml').read_text(encoding='utf-8'), re.M).group(1)
with zipfile.ZipFile(sys.argv[2]) as jar:
font = Font(jar)
labels = {'version': label(font, f'{WINDOW_TITLE} {version}'),
'uptodate': label(font, '- остання версія', (130, 200, 120)),
'update': label(font, '- є оновлення, натисни', (255, 216, 61))}
(fm / 'assets').mkdir(parents=True, exist_ok=True)
(fm / 'customization').mkdir(parents=True, exist_ok=True)
for picture in MENU.glob('*.png'): # backgrounds, logo, button and status icons
shutil.copyfile(picture, fm / 'assets' / picture.name)
for name, picture in labels.items():
picture.save(fm / 'assets' / f'{name}.png')
for icon in ('favicon-16x16.png', 'favicon-32x32.png'):
shutil.copyfile(ICONS / icon, fm / 'assets' / icon)
(fm / 'customization' / 'title_screen_layout.txt').unlink(missing_ok=True) # the name used before the generator
for name, layout in (('title', title_screen(version, labels)), ('screens', plain_screens()), ('pause', game_menu())):
(fm / 'customization' / f'createrp_{name}.txt').write_text(layout.text(), encoding='utf-8', newline='\n')
(fm / 'custom_gui_screens.txt').write_text(CUSTOM_GUIS, encoding='utf-8', newline='\n')
(fm / 'customizablemenus.txt').write_text(
'type = customizablemenus\n\n' + ''.join(f'{SCREENS}{c} {{\n}}\n\n' for c in ['TitleScreen'] + [c for _, c in PLAIN_SCREENS]),
encoding='utf-8', newline='\n')
options = (fm / 'options.txt').read_text(encoding='utf-8')
options = option(options, 'custom_window_title', WINDOW_TITLE)
options = option(options, 'show_custom_window_icon', 'true')
options = option(options, 'custom_window_icon_16', '/config/fancymenu/assets/favicon-16x16.png')
options = option(options, 'custom_window_icon_32', '/config/fancymenu/assets/favicon-32x32.png')
options = option(options, 'custom_window_icon_macos', '')
options = option(options, 'global_background_panorama', '')
(fm / 'options.txt').write_text(options, encoding='utf-8')
sprites = config.parent / 'kubejs' / 'assets' / 'minecraft' / 'textures' / 'gui' / 'sprites' / 'widget'
sprites.mkdir(parents=True, exist_ok=True)
for sprite in UI.iterdir(): # button.png, button_highlighted.png, button_disabled.png and their .mcmeta
shutil.copyfile(sprite, sprites / sprite.name)
create = config / 'create-client.toml' # Create draws its button itself; row 0 switches it off
if create.is_file():
text = create.read_text(encoding='utf-8')
text = re.sub(r'^(\s*(?:mainMenu|ingameMenu)ConfigButtonRow = )\d+', r'\g<1>0', text, flags=re.M)
create.write_text(text, encoding='utf-8')
print('menus installed into', config.parent, '| version', version)
if __name__ == '__main__':
main()