Load standalone community data without DOS programs and match Original crest backgrounds (by Codex)
Prepare verified release / draft (push) Canceled after 0s

This commit is contained in:
Codex committed 2026-10-31 11:43:25 +01:00
1 parent 3044b95b44
commit 1771cb5599
22 files changed
+454 -19

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Prepare a compact data-only community directory from private supplied content."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import zipfile
def build(source, destination, exporter):
if destination.exists():
raise ValueError('Destination must not exist')
source=source.resolve();destination.mkdir(parents=True)
runtime=destination/'RUNTIME.DAT'
try:
exe=next(p for p in source.iterdir() if p.name.upper()=='BMH.EXE')
subprocess.run([str(exporter.resolve()),str(exe),str(runtime)],check=True)
data=runtime.read_bytes()
if data[:8]!=b'OBMHDAT1':raise ValueError('Exporter did not produce a data-only runtime')
# Only resources actually used by OpenBMH; no DOS programs, manuals, backups or unused original graphics formats.
names=('M3D.MAN','TEXTD.BLK','M3.DAT','M3.MEN','M3PC.COL','OBMHPROF.INI')
entries={'RUNTIME.DAT':data}
for name in names:
file=next(p for p in source.iterdir() if p.name.upper()==name)
entries[name]=file.read_bytes()
for directory in ('KB','W','F','S'):
root=next(p for p in source.iterdir() if p.name.upper()==directory)
for file in sorted(root.iterdir()):
if not file.is_file():continue
if directory in ('KB','W') and file.suffix.upper()!='.VGA':continue
if directory=='F' and file.name.upper() not in ('BMH2.FNT','BMH3.FNT'):continue
if directory=='S' and file.name not in ('2000','2001','2002','2003'):continue
entries[directory+'/'+file.name.upper()]=file.read_bytes()
receipt={'format':'openbmh-community-1','files':{name:hashlib.sha256(value).hexdigest() for name,value in entries.items()},
'executable_code_included':False,'profile':'classic-plus-1'}
entries['PACKAGE.json']=(json.dumps(receipt,indent=2)+'\n').encode()
archive=destination/'COMMUNITY.OBD'
with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
for name,value in entries.items():z.writestr(name,value)
report=source/'IMPORT-REPORT.json'
if report.exists():(destination/report.name).write_bytes(report.read_bytes())
print(json.dumps({'bundle_bytes':archive.stat().st_size,'uncompressed_resource_bytes':sum(map(len,entries.values())),
'resource_count':len(entries),'runtime_bytes':len(data),'bundle_sha256':hashlib.sha256(archive.read_bytes()).hexdigest()}))
finally:runtime.unlink(missing_ok=True)
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--exporter',type=Path,required=True);a=p.parse_args();build(a.source,a.out,a.exporter)
+18
View File
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/le.hpp"
#include "formats/executable_layout.hpp"
#include "formats/badge_policy.hpp"
#include "game/calendar.hpp"
#include "game/environment.hpp"
#include <iostream>
int main(int argc,char**argv)try {
if(argc!=3)throw std::runtime_error("usage: export_community_runtime <supplied executable> <output runtime.dat>");
const auto image=bmh::load_le(argv[1]);
const auto epoch=bmh::calendar_epoch_from_executable(image);
bmh::install_environment_rules(image);
bmh::RuntimePolicy policy{uint32_t(epoch.year),uint32_t(epoch.weekday),uint32_t(bmh::original_badge_gate(image)),uint32_t(bmh::environment_rules_supported()),{}};
for(auto address:{bmh::layout::FreeKickTakerLabel,bmh::layout::PenaltyTakerLabel,bmh::layout::CornerTakerLabel,bmh::layout::AutomaticTakersLabel})
policy.labels.emplace(address,image.cstring(address));
bmh::save_runtime_image(image,policy,argv[2]);
std::cout<<"Data-only runtime exported; no DOS header, loader or code objects\n";return 0;
}catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 1;}
+35 -8
View File
@@ -95,6 +95,33 @@ def encode_vga(width, height, pixels):
def find_file(root, name):
return next(p for p in root.iterdir() if p.name.upper() == name.upper())
def original_crest_background(source):
"""Recover the shared bright crest texture from the supplied domestic sheets."""
sheets = {}
samples = []
directory = find_file(source, 'W')
for cell in range(90):
page = cell // 8
if page not in sheets:
sheets[page] = decode_vga(find_file(directory, str(page) + '.VGA').read_bytes())
width, height, pixels = sheets[page]
if (width, height) != (304, 38):
raise ValueError('Unexpected Original crest-sheet dimensions')
samples.append(bytes(pixels[y*width+(cell%8)*38+x] for y in range(38) for x in range(38)))
return crest_background_from_samples(samples)
def crest_background_from_samples(samples):
if not samples or any(len(s) != 38*38 for s in samples):
raise ValueError('Invalid crest background samples')
# The Original bright paper texture uses these four adjacent palette entries.
background = bytearray()
for pos in range(38*38):
counts = collections.Counter(s[pos] for s in samples if 92 <= s[pos] <= 95)
background.append(counts.most_common(1)[0][0] if counts else 94)
return bytes(background)
def repeated_native_images(clubs, assets, read):
"""Detect shared Original fallback images without baking in game pixels/hashes."""
counts = collections.Counter()
@@ -214,6 +241,10 @@ def build(source, donor, output):
palette=find_file(source,'M3PC.COL').read_bytes()
rgb=[tuple(((v&63)*255+31)//63 for v in palette[i:i+3]) for i in range(0,768,3)]
sheets={}; crest_report=[]; cache={}
backdrop = original_crest_background(source)
backdrop_image = Image.frombytes('P',(38,38),backdrop)
backdrop_image.putpalette([value for color in rgb for value in color])
backdrop_image = backdrop_image.convert('RGBA')
w_dir=find_file(source,'W')
def sheet(n):
if n not in sheets:
@@ -250,22 +281,18 @@ def build(source, donor, output):
color = '#%02x%02x%02x' % rgb[64 + index % 16]
svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="38" height="38"><path d="M5 3H33L31 24L19 35L7 24Z" fill="{color}" stroke="#f0f5f3" stroke-width="2"/><path d="M8 9H30" stroke="#f0f5f3"/><text x="19" y="23" text-anchor="middle" font-family="sans-serif" font-size="10" font-weight="bold" fill="white">{html.escape(initials)}</text></svg>'
image=Image.open(io.BytesIO(cairosvg.svg2png(bytestring=svg.encode()))).convert('RGBA')
foreground = [(r,g,b) for r,g,b,a in image.getdata() if a >= 128]
contrast_adjusted = bool(foreground) and sum(max(pixel) for pixel in foreground)/len(foreground) < 60
if contrast_adjusted:
alpha=image.getchannel('A');image=Image.new('RGBA',image.size,(238,244,240,0));image.putalpha(alpha)
contrast_adjusted = False # Black silhouettes remain readable on the Original bright background.
image=ImageOps.contain(image,(36,36),method=Image.Resampling.LANCZOS)
canvas=Image.new('RGBA',(38,38));canvas.alpha_composite(image,((38-image.width)//2,(38-image.height)//2))
canvas=backdrop_image.copy();canvas.alpha_composite(image,((38-image.width)//2,(38-image.height)//2))
pixels=bytearray()
for r,g,b,a in canvas.getdata():
if a<128:pixels.append(0);continue
key=(r,g,b)
if key not in cache:cache[key]=min(range(1,256),key=lambda n:sum((x-y)**2 for x,y in zip(rgb[n],key)))
if key not in cache:cache[key]=min(range(256),key=lambda n:sum((x-y)**2 for x,y in zip(rgb[n],key)))
pixels.append(cache[key])
dst=sheet(cell//8)
for y in range(38):dst[y*304+(cell%8)*38:y*304+(cell%8)*38+38]=pixels[y*38:(y+1)*38]
badges[index]=(badges[index]&~511)|cell
crest_report.append({'club':club['id'],'runtime_team':index,'cell':cell,'asset':club.get('crest'),'source':asset.get('source'),'license':asset.get('license'),'fictional':fictional,'contrast_adjusted':contrast_adjusted,'last_decode_error':error})
crest_report.append({'club':club['id'],'runtime_team':index,'cell':cell,'asset':club.get('crest'),'source':asset.get('source'),'license':asset.get('license'),'fictional':fictional,'contrast_adjusted':contrast_adjusted,'background':'original-crest-texture','last_decode_error':error})
db['badges']=words(badges)
# Every Original player word and all German starting rosters remain unchanged.
original_db = read_master(master)
+9 -1
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: GPL-3.0-only
"""Synthetic encoder/reader tests; no Original game content required."""
import unittest
from prepare_international import decode_vga, encode_vga, legacy_name, read_master, write_master, words, repeated_native_images
from prepare_international import decode_vga, encode_vga, legacy_name, read_master, write_master, words, repeated_native_images, crest_background_from_samples
class ProfileDataTests(unittest.TestCase):
def test_master_identity_and_sizes(self):
@@ -37,6 +37,14 @@ class ProfileDataTests(unittest.TestCase):
found=repeated_native_images(clubs,assets,lambda path: {'shared':b'placeholder','real':b'individual-crest'}[path])
self.assertEqual(found,{hashlib.sha256(b'placeholder').hexdigest()})
def test_original_background_recovers_texture(self):
texture=bytes(92+(i%4) for i in range(38*38))
samples=[bytearray(texture) for _ in range(7)]
for j, sample in enumerate(samples):
for i in range(j*100,j*100+80):sample[i]=0
self.assertEqual(crest_background_from_samples(samples),texture)
self.assertNotIn(0,crest_background_from_samples(samples))
def test_original_encoding(self):
self.assertEqual(legacy_name('Müller'),b'M}LLER')
self.assertEqual(legacy_name('Sørloth'),b'SORLOTH')