Verify selective HUD shape preparation and fallback (#643)

This commit is contained in:
Marjaperse committed 2026-11-17 03:58:35 +02:00
1 parent bf6ebeafa5
commit 3a9e8ea50a
14 files changed
+606 -33

No files matched your search

+171
View File
@@ -0,0 +1,171 @@
"""Synthetic HUD layout and generator CLI regressions, without game assets.
Run with .venv-py314/Scripts/python tests/hud_layout_test.py.
"""
import ast
import compression.zstd as zstd
import json
import os
import importlib.util
import math
import struct
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TOOL = ROOT / 'tools/make_romfs_patches.py'
spec = importlib.util.spec_from_file_location('ultrawide_layout', ROOT / 'tools/ultrawide_layout.py')
ui = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ui)
def archive():
"""Build shipped pane fields and animation keys; no copyrighted archive data."""
layouts = {name: {'RootPane': {}} for name in ui.KEEP_ROOT | ui.MARKER_ROOT.keys()}
for name, panes in ui.MARKER_ROOT.items():
for pane in panes: layouts[name][pane] = {}
for name, pane, field, value in ui.edits(1, None):
layouts.setdefault(name, {'RootPane': {}}).setdefault(pane, {})[field] = value
data, members = bytearray(), {}
for name, panes in sorted(layouts.items()):
blob = bytearray(20)
blob[:4] = b'FLYT'
struct.pack_into('<H', blob, 6, 20)
struct.pack_into('<H', blob, 16, len(panes))
for pane, fields in panes.items():
section = bytearray(80)
section[:4] = b'pan1'
struct.pack_into('<I', section, 4, 80)
section[12:12 + len(pane)] = pane.encode()
struct.pack_into('<2f', section, 68, 1, 1)
for field, value in fields.items(): struct.pack_into('<f', section, ui.FIELD[field], value)
blob += section
members[f'blyt/{name}.bflyt'] = (len(data), len(data) + len(blob))
data += blob
for anim in {row[0] for row in ui.anim_edits(1, None)}:
blob = bytearray(3600)
for name, offset, shipped, _ in ui.anim_edits(1, None):
if name == anim: struct.pack_into('<f', blob, offset, shipped)
members[f'anim/{anim}.bflan'] = (len(data), len(data) + len(blob))
data += blob
return data, members
def value(data, members, name, pane, field):
lo, hi = members[f'blyt/{name}.bflyt']
return struct.unpack_from('<f', data, ui.panes(data, lo, hi)[pane] + ui.FIELD[field])[0]
class HudLayoutTest(unittest.TestCase):
def test_caps_move_panes_and_animation_together(self):
for cap, extension in ((None, 960), (21 / 9, 300), (16 / 9, 0)):
with self.subTest(cap=cap):
data, members = archive()
ui.apply(data, members, 3840, 1080, cap)
self.assertAlmostEqual(value(data, members, 'PlayerStatus_00', 'N_HeartPos_00', 'x'), -extension)
self.assertAlmostEqual(value(data, members, 'EnvironmentInfo_00', 'RootPane', 'x'), extension / 2)
lo, _ = members['anim/AppMap_00_MiniMap.bflan']
for offset in (872, 880, 1628, 1636, 3264, 3272, 3468, 3476):
self.assertAlmostEqual(struct.unpack_from('<f', data, lo + offset)[0], 765 + extension)
self.assertAlmostEqual(value(data, members, 'SaveLoadIcon_00', 'RootPane', 'x'), -extension / 2)
self.assertEqual(value(data, members, 'GameOver_00', 'P_BG_00', 'scale_x'), 2)
self.assertEqual(value(data, members, 'AttentionLockOn_00', 'RootPane', 'scale_x'), 1)
self.assertEqual(value(data, members, 'AttentionLockOn_00', 'N_Offset_00', 'scale_x'), .5)
def test_unnecessary_caps_equal_full(self):
full, members = archive()
ui.apply(full, members, 3440, 1440)
for cap in (3440 / 1440, 4, 3440 / 1440 * .995):
data, members = archive()
ui.apply(data, members, 3440, 1440, cap)
self.assertEqual(data, full)
def test_invalid_parameters_do_not_mutate(self):
for width, height, cap in ((0, 1080, None), (3840, 0, None), (3840, 1080, 1), (3840, 1080, math.nan)):
data, members = archive()
before = bytes(data)
with self.assertRaises(ValueError): ui.apply(data, members, width, height, cap)
self.assertEqual(data, before)
def test_cli_rejects_invalid_before_output(self):
with tempfile.TemporaryDirectory() as folder:
out = Path(folder) / 'output'
for arguments in (['--aspect', 'bad'], ['--aspect', '0x1440'], ['--aspect', '1920x1080'],
['--hud', '16:9'], ['--aspect', '1280x800', '--hud', '16:9']):
result = subprocess.run([sys.executable, str(TOOL), '--out', str(out), *arguments], capture_output=True, text=True)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertIn('error:', result.stderr)
self.assertNotIn('Traceback', result.stderr)
self.assertFalse(out.exists())
def test_default_names_and_explicit_output(self):
# Execute only argument handling; input loading and archive generation remain untouched.
source = TOOL.read_text().split("index = json.loads", 1)[0]
old = sys.argv
try:
for style in (None, 'xbox', 'xbox-label', 'pc'):
for hud in ('full', '21:9', '16:9'):
argv = ['tool', '--aspect', '3840X1080', '--hud', hud]
if style: argv += ['--prompts', style]
sys.argv = argv
env = {'__file__': str(TOOL)}
exec(compile(source, str(TOOL), 'exec'), env)
expected = 'romfs-patches' + (f'-{style}' if style else '') + '-3840x1080'
if hud != 'full': expected += '-hud' + hud.replace(':', 'x')
self.assertEqual(env['args'].out.name, expected)
sys.argv = argv + ['--out', 'chosen']
exec(compile(source, str(TOOL), 'exec'), env)
self.assertEqual(env['args'].out, Path('chosen'))
finally: sys.argv = old
@unittest.skipUnless(os.environ.get('HUD_TEST_ROMFS'), 'set HUD_TEST_ROMFS for local archive comparisons')
class RealArchiveTest(unittest.TestCase):
def test_full_unchanged_and_caps_valid(self):
folder = Path(os.environ['HUD_TEST_ROMFS'])
index = json.loads((folder / 'index.json').read_text())
files = {entry['path']: entry for entry in index['files']}
tree = ast.parse(TOOL.read_text())
functions = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in ('sarc_nodes', 'sarc_members')]
namespace = {'struct': struct}
exec(compile(ast.Module(body=functions, type_ignores=[]), str(TOOL), 'exec'), namespace)
sarc = namespace['sarc_members']
with (folder / 'romfs.bin').open('rb') as image:
def read(path):
entry = files[path]
image.seek(entry['offset'])
return image.read(entry['size'])
pack = zstd.decompress(read('Pack/ZsDic.pack.zs'))
dictionaries = {}
for lo, hi in sarc(pack).values():
dictionary = zstd.ZstdDict(pack[lo:hi])
dictionaries[dictionary.dict_id] = dictionary
path = max(path for path in files if path.startswith('UI/LayoutArchive/Common.Product.') and path.endswith('.blarc.zs'))
raw = read(path)
original = zstd.decompress(raw, zstd_dict=dictionaries[zstd.get_frame_info(raw).dictionary_id])
members = sarc(original)
# The dev implementation before the HUD port is the full-width compatibility reference.
baseline_source = subprocess.check_output(['git', 'show', 'f85058070e955eae0e45c9adbbe903d340b05b32:tools/ultrawide_layout.py'], cwd=ROOT, text=True)
baseline = {}
exec(compile(baseline_source, '<dev layout>', 'exec'), baseline)
for width, height in ((3840, 1080), (3440, 1440), (1280, 800)):
full = bytearray(original)
ui.apply(full, members, width, height)
expected = bytearray(original)
baseline['apply'](expected, members, width, height)
self.assertEqual(full, expected)
for cap, extension in ((16 / 9, 0), (21 / 9, 300)):
data = bytearray(original)
ui.apply(data, members, 3840, 1080, cap)
self.assertAlmostEqual(value(data, members, 'PlayerStatus_00', 'N_HeartPos_00', 'x'), -extension)
self.assertAlmostEqual(value(data, members, 'SaveLoadIcon_00', 'RootPane', 'x'), -extension / 2)
for name in ui.KEEP_ROOT:
if name == 'AppMenuOverlay_00': continue
lo, hi = members[f'blyt/{name}.bflyt']
self.assertEqual(data[lo:hi], original[lo:hi])
if __name__ == '__main__': unittest.main()
+86
View File
@@ -681,6 +681,92 @@ class ShapesTest(unittest.TestCase):
str(self.dest / 'totk.ini')])
self.assertNotIn('--binds', self.calls[0])
def test_selected_hud_only_for_needed_canonical_shapes(self):
screens.displays = lambda: [(5120, 1440), (3840, 1080), (2560, 1600)]
(self.dest / 'totk.ini').write_text('output_res = 5120x2160\nhud_width = 21:9\n')
step = steps.Shapes()
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-2560x1080-hud21x9',
'romfs-patches-3840x1080', 'romfs-patches-3840x1080-hud21x9',
'romfs-patches-1280x800'])
caps = [c for c in self.calls if '--hud' in c]
self.assertEqual(len(caps), 2)
self.assertEqual(caps[0][-4:], ['--aspect', '2560x1080', '--hud', '21:9'])
self.assertEqual(caps[1][-4:], ['--aspect', '3840x1080', '--hud', '21:9'])
self.assertTrue(step.current(self.ctx, record))
(self.dest / record['folders'][3] / 'manifest.tsv').unlink()
self.assertFalse(step.current(self.ctx, record))
def test_hud_key_and_cleanup_follow_selection(self):
screens.displays = lambda: [(2560, 1080)]
ini = self.dest / 'totk.ini'
ini.write_text('hud_width = full\n')
step = steps.Shapes()
full_key = step.key(self.ctx)
for name in ('romfs-patches-3840x1080-hud21x9', 'romfs-patches-pc-2560x1080-hud16x9',
'romfs-patches-player-custom'):
(self.dest / name).mkdir()
ini.write_text('TOTK_HUD_WIDTH = 16:9\n')
self.assertNotEqual(step.key(self.ctx), full_key)
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-2560x1080-hud16x9'])
self.assertFalse((self.dest / 'romfs-patches-3840x1080-hud21x9').exists())
self.assertFalse((self.dest / 'romfs-patches-pc-2560x1080-hud16x9').exists())
self.assertTrue((self.dest / 'romfs-patches-player-custom').is_dir())
self.calls.clear()
ini.write_text('hud_width = full\n')
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080'])
self.assertTrue(all('--hud' not in c for c in self.calls))
self.assertFalse((self.dest / 'romfs-patches-2560x1080-hud16x9').exists())
def test_capped_pc_prompts_reuse_bindings(self):
screens.displays = lambda: [(3840, 1080)]
(self.dest / 'totk.ini').write_text('prompts = pc\nhud_width = 16:9\nbind_attack = key:f\n')
(self.dest / 'romfs-patches-pc').mkdir()
(self.dest / 'romfs-patches-pc' / 'manifest.tsv').write_text('#\n')
record = steps.Shapes().run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-3840x1080', 'romfs-patches-pc-3840x1080',
'romfs-patches-3840x1080-hud16x9',
'romfs-patches-pc-3840x1080-hud16x9'])
self.assertEqual(self.calls[-1][-6:], ['--hud', '16:9', '--reuse', str(self.dest / 'romfs-patches-pc'),
'--binds', str(self.dest / 'totk.ini')])
self.assertNotIn('--binds', self.calls[-2])
def test_hud_caps_ignore_equal_narrow_and_invalid_choices(self):
# Common '21:9' modes are wider than exact 21/9: a manually selected cap is meaningful.
self.assertEqual(steps.shape_hud('2560x1080', '21:9'), '21:9')
self.assertEqual(steps.shape_hud('3440x1440', '21:9'), '21:9')
self.assertIsNone(steps.shape_hud('2520x1080', '21:9'))
self.assertIsNone(steps.shape_hud('1280x800', '16:9'))
self.assertIsNone(steps.shape_hud('3840x1080', 'full'))
self.assertEqual(steps.shape_hud('3440x1440', '16:9'), '16:9')
(self.dest / 'totk.ini').write_text('hud_width = invalid\n')
self.assertEqual(steps.hud_width(self.dest), 'full')
def test_failed_capped_prompts_are_retried(self):
screens.displays = lambda: [(3840, 1080)]
(self.dest / 'totk.ini').write_text('prompts = pc\nhud_width = 16:9\n')
(self.dest / 'romfs-patches-pc').mkdir()
(self.dest / 'romfs-patches-pc/manifest.tsv').write_text('#\n')
successful = steps.run_tool
def fail_cap(ctx, step, script, args, **kwargs):
if '--prompts' in args and '--hud' in args:
return 7, self.dest / 'failed.log'
return successful(ctx, step, script, args, **kwargs)
steps.run_tool = fail_cap
step = steps.Shapes()
record = step.run(self.ctx)
self.assertTrue(record['failed'])
self.assertFalse(step.current(self.ctx, record))
steps.run_tool = successful
record = step.run(self.ctx)
self.assertFalse(record['failed'])
self.assertTrue(step.current(self.ctx, record))
self.assertIn('romfs-patches-pc-3840x1080-hud16x9', record['folders'])
def test_pc_prompts_writes_only_the_16_9_folder(self):
(self.dest / 'totk.ini').write_text('[input]\nbind_attack = key:f\n')
self.assertEqual(steps.PcPrompts().run(self.ctx), {})
+73 -1
View File
@@ -169,6 +169,64 @@ def bflyt(panes):
return b'FLYT' + struct.pack('<HHIIHH', 0xFEFF, 0x14, 0x08000000, 0x14 + len(sections), len(panes) + 1, 0) + sections
def diamond_bflyt():
"""The action prompt's bars, flashes and textured bases, in addition to its letter panes."""
original = bflyt(PANES)
sections = [original[20:]]
names = ['N_BtnA_00', 'N_BtnA_01', 'N_CompanionBtnA_00', 'N_BtnB_00', 'N_BtnX_00', 'N_BtnY_00',
'N_LoopA_03', 'P_CaptureX_00', 'P_CaptureY_00', 'W_BaseX_00', 'W_BaseY_00',
'T_GuideX_00', 'T_GuideY_00', 'T_GuideX_TW', 'T_GuideY_TW']
names += [f'P_Capture{k}_{n:02}' for k in 'ABXY' for n in (1, 2, 3)]
bases = ['P_BaseA_00', 'P_BaseA_01', 'P_BaseB_00', 'P_BaseX_00', 'P_BaseY_00']
for i, name in enumerate(names + bases):
section = bytearray(0x80)
section[:4] = b'pic1' if name in bases else b'txt1' if name.startswith('T_') else b'pan1'
struct.pack_into('<I', section, 4, len(section))
section[12:12 + len(name)] = name.encode()
section[9] = i % 9
struct.pack_into('<8f', section, 0x2c, i * 3, i * -2, 0, 0, 0, i * 10, 1, -1 if i % 2 else 1)
if name in bases: struct.pack_into('<H', section, 0x64, bases.index(name))
elif name.startswith('T_'):
struct.pack_into('<H', section, 0x56, 4)
struct.pack_into('<I', section, 0x64, 0x70)
section[0x70:0x74] = b'G\0\0\0'
sections.append(section)
material = bytearray(12 + 4 * len(bases))
material[:4] = b'mat1'
struct.pack_into('<H', material, 8, len(bases))
for i in range(len(bases)):
struct.pack_into('<I', material, 12 + 4 * i, len(material))
entry = bytearray(0x30)
entry[:8] = f'Base{i:03}'.encode() + b'\0'
struct.pack_into('<H', entry, 0x2c, i)
material += entry
struct.pack_into('<I', material, 4, len(material))
sections.append(material)
textures = bytearray(12 + 4 * len(bases))
textures[:4] = b'txl1'
struct.pack_into('<H', textures, 8, len(bases))
for i in range(len(bases)):
struct.pack_into('<I', textures, 12 + 4 * i, len(textures) - 12)
textures += f'Nt_KeyBtnSubBase{i}'.encode() + b'\0'
struct.pack_into('<I', textures, 4, len(textures))
sections.append(textures)
body = b''.join(sections)
count = len(PANES) + 1 + len(names) + len(bases) + 2
return b'FLYT' + struct.pack('<HHIIHH', 0xFEFF, 20, 0x08000000, 20 + len(body), count, 0) + body
def pane_positions(data):
"""Synthetic layout pane x/y, read independently of the generator."""
pos, out = 20, {}
while pos < len(data):
magic, size = data[pos:pos + 4], struct.unpack_from('<I', data, pos + 4)[0]
if magic in (b'pan1', b'pic1', b'txt1'):
name = data[pos + 12:pos + 36].split(b'\0')[0].decode()
out[name] = struct.unpack_from('<2f', data, pos + 0x2c)
pos += size
return out
def pane_texts(data):
pos, out = struct.unpack_from('<H', data, 6)[0], {}
while pos + 8 <= len(data):
@@ -333,7 +391,7 @@ class Romfs:
self.common: sarc({'anim/ShortCutBG_00_In.bflan': bflan(('C_CaptureBG_00', 'C_CaptureClearBG_00',
'P_CaptureClearBG_00', 'N_Other_00')),
'anim/AutoBuilder_00_In.bflan': bflan(('C_CaptureBG_00',)),
'blyt/DoCommand_00.bflyt': bflyt(PANES),
'blyt/DoCommand_00.bflyt': diamond_bflyt(),
'blyt/Title_00.bflyt': bflyt({'N_Title_00': 'Z'}),
'timg/__Combined.bntx': bntx(images)}),
DEFAULT_FONT: sarc(default),
@@ -445,6 +503,20 @@ class PromptsTest(unittest.TestCase):
self.assertEqual((texts['T_Name_00'], texts['Greeting']), ('A', 'Hello'))
self.assertEqual(sarc_files(romfs.read(out, path))['LayoutMsg/Other_00.msbt'], msbt({'T_A_00': 'A'}))
def test_xbox_label_diamond_moves_letters_bars_and_hold_flashes(self):
for romfs, _, out, _ in self.each(('xbox-label',)):
before = sarc_files(romfs.contents[romfs.common])['blyt/DoCommand_00.bflyt']
after = sarc_files(romfs.read(out, romfs.common))['blyt/DoCommand_00.bflyt']
old, new = pane_positions(before), pane_positions(after)
self.assertEqual(new['T_A_00'], (2, -39))
self.assertEqual(new['T_B_00'], (39, 1))
self.assertEqual(new['T_X_00'], (-38, 0))
self.assertEqual(new['T_Y_00'], (1, 39))
self.assertEqual(new['N_BtnA_00'], old['N_BtnB_00'])
self.assertEqual(new['N_BtnB_00'], old['N_BtnA_00'])
self.assertEqual(new['N_LoopA_03'], tuple(a + b - c for a, b, c in
zip(old['N_LoopA_03'], old['P_CaptureB_01'], old['P_CaptureA_01'])))
def test_other_buttons_are_drawn_as_xbox_icons(self):
for romfs, style, out, _ in self.each():
with self.subTest(version=romfs.version, style=style):
+175
View File
@@ -0,0 +1,175 @@
"""Exercise runtime/romfs.c shape lookup and generator commands without game data.
Usage: python tests/romfs_shapes_check.py [--cc C:/msys64/ucrt64/bin/clang.exe]
The C harness compiles function bodies read from the production implementation;
only configuration, filesystem and process boundaries are supplied here. The spawn boundary records arguments.
"""
import argparse
import os
import re
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "platform/platform.h"
#include "shape_functions.h"
const int rt_game_version = 143;
static char index_test[2400];
static const char *hud_test="16:9", *override_test;
static int spawns;
static char args_test[24][2400];
const char *cfg_get(const char *key) {
if (!strcmp(key,"TOTK_ROMFS_INDEX")) return index_test;
if (!strcmp(key,"TOTK_ROMFS_PATCHES")) return override_test;
return NULL;
}
const char *cfg_value(const char *key) { return !strcmp(key,"TOTK_HUD_WIDTH") ? hud_test : ""; }
// Fixed aliases; cfg_probe independently checks the real canonicalization algorithm.
int cfg_shape_size(unsigned w,unsigned h,unsigned out[2]) {
if (w*9ull==h*16ull) return 0;
if (w==5120 && h==2160) out[0]=2560,out[1]=1080;
else if (w==5120 && h==1440) out[0]=3840,out[1]=1080;
else out[0]=w,out[1]=h;
return 1;
}
int res_wants_wide_overlay(const unsigned out[2]) { return out[0]*9ull!=out[1]*16ull; }
int plat_file_exists(const char *p) { struct stat s; return !stat(p,&s) && S_ISREG(s.st_mode); }
uint8_t *plat_file_read(const char *p,uint64_t *size) {
FILE *f=fopen(p,"rb"); if (!f) return NULL;
fseek(f,0,SEEK_END); *size=ftell(f); rewind(f);
uint8_t *b=calloc(1,*size+1); assert(b); assert(fread(b,1,*size,f)==*size); fclose(f); return b;
}
int plat_exe_path(char *out,size_t cap) { (void)out;(void)cap;abort(); }
void rt_fatal(const char *fmt,...) { (void)fmt;abort(); }
void rt_log(const char *fmt,...) { (void)fmt; }
int plat_spawn(const char *const *args,const char *cwd) {
assert(cwd && *cwd); spawns++;
int i; for (i=0;args[i];i++) { assert(i<23); snprintf(args_test[i],sizeof args_test[i],"%s",args[i]); }
args_test[i][0]=0; return 1;
}
static const char *arg(const char *key) {
for (int i=0;args_test[i][0];i++) if (!strcmp(args_test[i],key)) return args_test[i+1];
return NULL;
}
static void output_ends(const char *suffix) {
const char *p=arg("--out"); assert(p && strlen(p)>=strlen(suffix));
assert(!strcmp(p+strlen(p)-strlen(suffix),suffix));
}
int main(int argc,char **argv) {
assert(argc==2); char base[2400],name[128];
snprintf(base,sizeof base,"%s/selection",argv[1]);
snprintf(index_test,sizeof index_test,"%s/romfs-index.bin",base);
assert(selected_shape(base,"romfs-patches",5120,2160,name,sizeof name,1));
assert(!strcmp(name,"romfs-patches-2560x1080-hud16x9")); // selected canonical beats exact full
assert(selected_shape(base,"romfs-patches-xbox",5120,2160,name,sizeof name,0));
assert(!strcmp(name,"romfs-patches-xbox-5120x2160-hud16x9")); // exact cap beats canonical cap
hud_test="21:9";
assert(selected_shape(base,"romfs-patches",5120,1440,name,sizeof name,1));
assert(!strcmp(name,"romfs-patches-3840x1080"));
assert(!selected_shape(base,"romfs-patches",5120,1440,name,sizeof name,0));
assert(romfs_shape_missing(5120,1440,NULL));
override_test="0"; assert(!romfs_shape_missing(5120,1440,NULL)); override_test=NULL;
assert(!romfs_shape_missing(1920,1080,NULL));
snprintf(index_test,sizeof index_test,"%s/generation/romfs-index.bin",argv[1]);
hud_test="16:9";
assert(romfs_shape_prepare(5120,2160,"romfs-patches-pc")); assert(spawns==2);
assert(!strcmp(arg("--aspect"),"2560x1080")); assert(!strcmp(arg("--hud"),"16:9"));
assert(!strcmp(arg("--version"),"v143")); assert(!strcmp(arg("--prompts"),"pc"));
assert(arg("--reuse") && strstr(arg("--reuse"),"/romfs-patches-pc"));
assert(arg("--binds") && strstr(arg("--binds"),"/totk.ini")); assert(!args_test[18][0]); output_ends("romfs-patches-pc-2560x1080-hud16x9");
assert(romfs_shape_prepare(5120,2160,"romfs-patches-pc")); assert(spawns==2);
hud_test="full";
assert(romfs_shape_prepare(5120,2160,"romfs-patches-xbox")); assert(spawns==4);
assert(!strcmp(arg("--hud"),"full")); assert(!strcmp(arg("--prompts"),"xbox"));
assert(arg("--reuse") && !arg("--binds")); output_ends("romfs-patches-xbox-2560x1080");
hud_test="21:9";
assert(romfs_shape_prepare(5120,1440,"romfs-patches-xbox-label")); assert(spawns==6);
assert(!strcmp(arg("--hud"),"21:9")); assert(!strcmp(arg("--prompts"),"xbox-label"));
assert(!arg("--reuse") && !arg("--binds")); output_ends("romfs-patches-xbox-label-3840x1080-hud21x9");
// A cap wider than a tall canvas becomes full, never an invalid generator request.
assert(romfs_shape_prepare(1280,800,NULL)); assert(spawns==7);
assert(!strcmp(arg("--hud"),"full")); output_ends("romfs-patches-1280x800");
// Beyond the old eight-folder limit every new folder must still be remembered.
const char *dummy[]={"python","script",NULL};
for (int i=0;i<12;i++) {
char folder[80]; snprintf(folder,sizeof folder,"additional-request-%d",i);
int before=spawns; assert(shape_spawn(dummy,argv[1],folder)); assert(spawns==before+1);
assert(shape_spawn(dummy,argv[1],folder)); assert(spawns==before+1);
}
puts("PASS production shape selection, command arguments and generation deduplication");
}
'''
def production_functions():
"""Compile the current function bodies, without duplicating their implementation.
MinGW resolves unrelated public RomFS entry points before section GC, so including
the complete unit would require fake audio, mod, decompression and filesystem APIs.
"""
source = (ROOT / 'runtime/romfs.c').read_text()
names = ('need', 'hud_suffix', 'shaped_name', 'selected_shape', 'index_path', 'index_folder',
'shaped_folder_ready', 'romfs_shaped_ready', 'romfs_shaped_prompts_ready', 'prepare_tools',
'romfs_shape_missing', 'shape_was_started', 'shape_spawn', 'romfs_shape_prepare')
state = re.findall(r'(?m)^static [^;\n]*\bshape_started[^;\n]*;', source)
assert len(state) == 2, 'update harness extraction for changed generation cache declarations'
functions = []
for name in names:
match = re.search(r'(?m)^[^\n;{}]*\b' + name + r'\([^;{}]*?\)\s*\{', source)
assert match, f'production function not found: {name}'
end = match.end()
depth = 1
while depth:
assert end < len(source), f'unclosed production function: {name}'
if source[end] == '{': depth += 1
elif source[end] == '}': depth -= 1
end += 1
functions.append(source[match.start():end])
return '\n'.join(state + functions)
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--cc', default='C:/msys64/ucrt64/bin/clang.exe' if os.name == 'nt' else 'clang')
args = ap.parse_args()
work = ROOT / 'build' / 'romfs-shapes-check'
work.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=work) as temporary:
folder = Path(temporary)
for name in ('romfs-patches-5120x2160', 'romfs-patches-2560x1080-hud16x9',
'romfs-patches-xbox-5120x2160-hud16x9', 'romfs-patches-xbox-2560x1080-hud16x9',
'romfs-patches-3840x1080'):
manifest = folder / 'selection' / name / 'manifest.tsv'
manifest.parent.mkdir(parents=True, exist_ok=True)
manifest.write_text('# synthetic\n')
generation = folder / 'generation'
for name in ('build-cache', 'romfs', 'tools', 'romfs-patches-pc', 'romfs-patches-xbox'):
(generation / name).mkdir(parents=True, exist_ok=True)
for name in ('romfs/romfs.bin', 'tools/make_romfs_patches.py', 'fake-python', 'totk.ini',
'romfs-patches-pc/manifest.tsv', 'romfs-patches-xbox/manifest.tsv'):
(generation / name).write_text('# synthetic\n')
(generation / 'build-cache/rebuild.txt').write_text(
f'{(generation / "fake-python").as_posix()}\n-c\nunused\n{generation.as_posix()}\n')
(folder / 'shape_functions.h').write_text(production_functions())
source = folder / 'harness.c'
source.write_text(HARNESS)
exe = folder / ('harness.exe' if os.name == 'nt' else 'harness')
command = [args.cc, '-O2', '-flto', '-ffunction-sections', '-fdata-sections', '-Wl,--gc-sections',
'-I', str(folder), '-I', str(ROOT / 'runtime'), str(source), '-o', str(exe)]
subprocess.run(command, check=True, cwd=ROOT)
env = os.environ.copy()
if os.name == 'nt': env['PATH'] = str(Path(args.cc).resolve().parent) + os.pathsep + env.get('PATH', '')
subprocess.run([str(exe), folder.as_posix()], check=True, cwd=ROOT, env=env)
if __name__ == '__main__': main()