Files
Dreierpack-Manager/tools/modern_ui/prepare_gui_assets.py
T

219 lines
12 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Prepare a separate private GUI resource directory from the approved HTML mockup.
Never modifies the source study or an OBW world. Original reference directories,
club catalogues and player databases are not copied into the GUI resource set.
"""
import argparse
import ast
import hashlib
import json
import math
from pathlib import Path
import re
import shutil
import subprocess
import struct
def silver_highscore_svg(source):
"""Apply the Gold CSS brightness(.44)/saturate(1.2) to vector colours only."""
def colour(match):
raw = match[2][1:]
if len(raw) not in (3, 4, 6, 8):
raise ValueError('Unsupported SVG colour length')
if len(raw) in (3, 4):
raw = ''.join(c * 2 for c in raw)
rgb = [int(raw[i:i + 2], 16) * .44 for i in (0, 2, 4)]
luminance = sum(a * b for a, b in zip(rgb, (.213, .715, .072), strict=True))
result = ''.join(f'{max(0, min(255, round(luminance + 1.2 * (c - luminance)))):02x}'
for c in rgb)
return match[1] + '#' + result + raw[6:] + match[3]
return re.sub(r'''((?:fill|stroke|stop-color|color)\s*=\s*["'])(\#[0-9a-fA-F]{3,8})(["'])''',
colour, source)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--mockup', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
source = args.mockup.resolve(strict=True)
output = args.output.resolve()
if output == source or source in output.parents or output in source.parents:
parser.error('Source and output must be independent directories.')
output.mkdir(parents=True, exist_ok=True)
items = {}
def add(key, relative, crop=None):
path = (source / relative).resolve(strict=True)
if not path.is_relative_to(source):
raise ValueError('GUI source escapes the supplied mockup directory.')
relative = path.relative_to(source).as_posix()
destination = output / relative
if not destination.resolve().is_relative_to(output):
raise ValueError("GUI output escapes the supplied output directory.")
destination.parent.mkdir(parents=True, exist_ok=True)
if not destination.exists() or destination.read_bytes() != path.read_bytes():
shutil.copyfile(path, destination)
item = {'file': relative, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
if crop:
item['crop'] = crop
items[key] = item
add('background', 'assets/vendor/stadium-night.png')
data = (source / 'desktop/assets.js').read_text()
buttons = json.loads(data[data.index('{'):data.rfind('}') + 1])['buttons']
routes = ['tables', 'league', 'strengths', 'lineup', 'achievements', 'other',
'friendlies', 'postpone', 'calendar', 'indoor', 'load', 'save',
'kickoff', 'toto', 'bank', 'camp', 'training', 'transfer', 'tactics',
'settings', 'scorers', 'advertising', 'stadium', 'statistics',
'environment', 'fairplay', 'highscore', 'contracts', 'balance', 'newplayer']
for route, button in zip(routes, buttons, strict=True):
add('button.' + route, button['src'].removeprefix('../'))
add('button.news', 'assets/vector/desktop-news.svg')
add('button.almanac', 'assets/vector/desktop-almanac.svg')
# User-supplied career illustrations stay in this external private GUI pack.
for key, file in [('career.club','club.png'),('career.international','international.png')]:
if (source / 'assets/studies/career' / file).exists():
add(key, 'assets/studies/career/' + file)
sheet = 'assets/studies/career/manager-menu.png'
if (source / sheet).exists():
for key, rect in [('manager.resign',[0,0,714,568]),('manager.search',[726,0,722,568]),('manager.add',[0,578,1448,508])]:
x,y,w,h=rect
add(key,sheet,[x/1448,y/1086,w/1448,h/1086])
items[key]['source_rect']=rect
for code in ('de','fr','it','es','en','nl','pl','se','at'):
file='assets/vector/career-national-'+code+'.svg'
if (source/file).exists():add('career.national-'+code,file)
for key, file in [('menu.club-office','menu-studies/club-office/assets/club-office.png'),('menu.trophy-office','menu-studies/trophy-office/assets/manager-office.png')]:
if (source/file).exists():add(key,file)
add('news.cash', 'assets/studies/desktop-objects/cash-v2.png')
# Prototype trophy fallbacks; competition pictures prefer world asset keys.
for trophy in ('championship', 'dfb-cup', 'supercup', 'champions-league',
'cup-winners', 'uefa-cup', 'indoor-masters', 'world-cup',
'european-championship', 'es-la-liga', 'es-copa-del-rey',
'en-premier-league', 'en-fa-cup', 'fr-ligue-1',
'fr-coupe-de-france', 'it-serie-a', 'it-coppa-italia'):
version = 2 if trophy == 'fr-coupe-de-france' else 1
add('trophy.' + trophy, f'assets/studies/trophies/{trophy}-v{version}.png')
for key, crop in [('normal', [0, 0, .5, .5]),
('selected', [.5, .5, .5, .5]),
('ghost', [.5, 0, .5, .5])]:
add('lineup.player.' + key, 'assets/studies/submenus/lineup-players-v2.png', crop)
for i in range(4):
add('advertising.panel.' + str(i), 'assets/studies/submenus/advertising-panels-v1.png',
[(i % 2) / 2, (i // 2) / 2, .5, .5])
for group in ['staff', 'youth']:
for i in range(3):
add('environment.' + group + '.' + str(i), 'assets/studies/submenus/environment-' + group + '-v1.png',
[(i % 2) / 2, (i // 2) / 2, .5, .5])
for i in range(6):
add('bank.property.' + str(i), 'assets/studies/submenus/bank-properties-v1.png',
[(i % 2) / 2, (i // 2) / 3, .5, 1 / 3])
for i in range(2):
add('contracts.scene.' + str(i), 'assets/studies/submenus/management-negotiations-v1.png',
[0, i / 2, 1, .5])
for i in range(9):
add('training.skill.' + str(i), 'assets/studies/submenus/training-icons-v2.png',
[(i % 3) / 3, (i // 3) / 3, 1 / 3, 1 / 3])
add('training.ball', 'assets/studies/submenus/training-ball-v1.png')
for i in range(12):
add('manager.' + str(i), 'assets/studies/submenus/manager-portraits-photo-v1.png',
[(i % 4) / 4, (i // 4) / 3, 1 / 4, 1 / 3])
add('manager-painted.' + str(i), 'assets/studies/submenus/manager-portraits-v1.png',
[(i % 4) / 4, (i // 4) / 3, 1 / 4, 1 / 3])
for folder in ['assets/studies/submenus', 'assets/vector']:
for path in sorted((source / folder).rglob('*')):
if path.is_file() and path.suffix.lower() in ('.png', '.svg', '.jpg', '.webp'):
add('art.' + path.relative_to(source / folder).as_posix(), path.relative_to(source).as_posix())
# Exact approved panel bounds exclude tier-atlas seams. These are GUI
# references only; they never become world assets or periphery actions.
stadium_source = (source / 'desktop/stadium-menus.js').read_text()
tier_match = re.search(r'const tierArtwork=(\{.*?\});', stadium_source, re.S)
if not tier_match:
raise ValueError('Missing measured stadium tier artwork')
tiers = json.loads(tier_match[1])
tier_kinds = {0: 'floodlights', 1: 'scoreboards', 4: 'pitch',
6: 'condition', 7: 'safety'}
for index in range(8):
cap = 2 if index in (2, 3) else 4
for level in range(1, cap + 1):
key = f'stadium.facility.{index}.level.{level}'
if index in tier_kinds:
sheet = tiers[tier_kinds[index]]
sw, sh = sheet['size']
header = (source / sheet['file']).read_bytes()[:24]
if header[:8] != b'\x89PNG\r\n\x1a\n' or struct.unpack('>II', header[16:24]) != (sw, sh):
raise ValueError('Stadium tier dimensions differ from measured reference')
x, y, width, height = sheet['rects'][level - 1]
if min(x, y) < 0 or min(width, height) <= 0 or x + width > sw or y + height > sh:
raise ValueError('Invalid measured stadium tier rectangle')
add(key, sheet['file'], [x / sw, y / sh, width / sw, height / sh])
items[key]['source_rect'] = [x, y, width, height]
else:
atlas = 'a' if index < 4 else 'b'
cell = index % 4
add(key, f'assets/studies/submenus/stadium-facilities-{atlas}-v1.png',
[(cell % 2) / 2, (cell // 2) / 2, .5, .5])
# The native compatibility renderer has no CSS image-filter implementation.
# Keep the approved original untouched; supply its exact colour-only variant.
logo_source = source / 'assets/vector/highscore-mark-v1.svg'
logo_relative = 'generated/highscore-mark-silver.svg'
logo_destination = output / logo_relative
if not logo_destination.resolve().is_relative_to(output):
raise ValueError('Derived GUI output escapes resource directory')
logo_destination.parent.mkdir(parents=True, exist_ok=True)
logo_bytes = silver_highscore_svg(logo_source.read_text()).encode()
if not logo_destination.exists() or logo_destination.read_bytes() != logo_bytes:
logo_destination.write_bytes(logo_bytes)
items['art.highscore-mark-silver.svg'] = {
'file': logo_relative, 'sha256': hashlib.sha256(logo_bytes).hexdigest(),
'derived_from': 'assets/vector/highscore-mark-v1.svg',
'transform': 'brightness(0.44) saturate(1.2); alpha unchanged',
}
map_source = (source / 'desktop/camp-map-data.js').read_text()
maps = json.loads(re.search(r'Object.freeze\((.*)\);', map_source).group(1))
regions = {'germany': 'de', 'europe': 'eu', 'gulf': 'me'}
map_rows = []
for key, value in maps.items():
add('map.' + regions[key], value['file'])
map_rows.append({'id': 'map:' + regions[key], 'name': value['label'],
'width': value['view_box'][2], 'height': value['view_box'][3]})
camp_source = (source / 'desktop/camp-menu.js').read_text()
block = re.search(r'const resorts=\[(.*?)\n\];', camp_source, re.S).group(1)
camps = ast.literal_eval('[' + re.sub(r'\b(\w+):', r'"\1":', block) + ']')
camp_rows = []
for index, camp in enumerate(camps):
crop = None
if 'image' in camp:
image = camp['image']
elif camp['region'] == 'gulf':
image = 'camp-gulf-resort-v1.png'
else:
photo = camp['photo']
image = 'camp-resorts-a-v1.png' if photo < 4 else 'camp-resorts-b-v2.png'
cell = photo % 4
crop = [(cell % 2) / 2, (cell // 2) / 2, .5, .5]
add('camp.' + str(index), 'assets/studies/submenus/' + image, crop)
projection = maps[camp['region']]['project']
x = (projection['ox'] + (math.radians(camp['lon']) - projection['xmin']) * projection['scale'])
y = projection['oy'] + (projection['ymax'] - math.log(math.tan(math.pi / 4 + math.radians(camp['lat']) / 2))) * projection['scale']
camp_rows.append({'id': 'resort:' + str(index), 'name': camp['name'], 'place': camp['city'],
'map': 'map:' + regions[camp['region']], 'x': round(x), 'y': round(y),
'quality': camp['quality'], 'price': camp['price'], 'gui_image': 'camp.' + str(index)})
try:
revision = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip()
except subprocess.CalledProcessError:
revision = 'unversioned'
document = {'schema': 'openbmh-gui-assets@1', 'source_revision': revision,
'distribution': 'private-reference-assets', 'items': items,
'demo': {'maps': map_rows, 'training_camps': camp_rows}}
(output / 'gui-assets.json').write_text(json.dumps(document, ensure_ascii=False, indent=2) + '\n')
print(f'Prepared {len(items)} GUI entries, {len(map_rows)} maps and {len(camp_rows)} demo camps.')
if __name__ == '__main__':
main()