Write RomFS layout folders only for the screen shapes and prompts this player uses

The setup wrote 64 patch folders: every prompts style for all 15 shaped game resolutions. The new shapes step
(installer/screens.py) writes romfs-patches-<w>x<h> only for the shapes of the connected displays, the output_res the
game defaults to on each and the totk.ini output_res, and the prompts' shaped folder only for the style totk.ini
selects. One folder per shape: the runtime maps the game resolution to its shape's size (cfg.c cfg_shape_size, the
closest ratio within 1%), and an exact-size folder from an older install still wins. The settings menu marks a game
resolution whose shape has no folder and can start the generator for it in the background, for the next start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-12 19:02:31 +03:00
1 parent df3e90dc4c
commit bc578148ab
18 files changed
+624 -101

No files matched your search

+19 -8
View File
@@ -72,23 +72,34 @@ loads the saves 1.4.3 wrote.
`totk.exe --prepare-shaders`) in the install folder, then fold the shader cache's loose files (four per shader, about
117,000) into `shader-cache/shader-cache.pack` (`tools/pack_shader_cache.py`). totk.exe reads the pack first and
writes the translations it makes in play as loose files; running the tool again with the game closed folds those in.
The patches are written four times: `romfs-patches`, `romfs-patches-xbox` and `romfs-patches-xbox-label`
The patches are written three times: `romfs-patches`, `romfs-patches-xbox` and `romfs-patches-xbox-label`
(`--prompts`: Xbox button prompts for `prompts = xbox`, the first for `pad_layout = nintendo`, the second for `xbox`
and `auto`), and `romfs-patches-pc` (keyboard and mouse prompts for `prompts = pc`). Each of the three prompt
folders is then laid out once more for each game resolution of another shape, `romfs-patches-<style>-<w>x<h>`
(`--prompts <style> --aspect`). Those differ from `romfs-patches-<style>` in the UI archive only, and `--reuse`
hard-links the other files from it, so the forty-five folders take seconds and a few MiB each. The prompt folders are optional: when one cannot be made, the
setup warns and finishes.
and `auto`). The prompt folders are optional: when one cannot be made, the setup warns and finishes.
**PC prompts** (step `pc_prompts`): `romfs-patches-pc`, the keyboard and mouse prompts for `prompts = pc`, drawn
from the `bind_` lines of `totk.ini` (`--binds`). Its key holds those lines, so a setup run after a change of the
bindings draws only these again. Optional like the Xbox prompts. All four 16:9 folders are always written, so a
switch of the prompts style at 16:9 needs no setup run.
When the graphics driver crashes while building the shaders, `prepare_shaders.py` runs that part again without the
variants it was building ([building.md](building.md), step 6), and the setup finishes with a warning that names how
many were left out.
7. **DLSS** (the window's tick box, on by default, or `--dlss`; Windows with an NVIDIA RTX GPU): download
7. **Shapes**: the UI laid out for each screen shape this player needs, `romfs-patches-<w>x<h>`
(`--aspect`), and with Xbox or PC prompts in `totk.ini` that layout with those prompts too,
`romfs-patches-<style>-<w>x<h>` (`--prompts <style> --aspect --reuse romfs-patches-<style>`, which hard-links every
file but the UI archive; for `pc` with the same `--binds` as the PC prompts step, whose key the step follows). The shapes are those of every connected display (Windows: `EnumDisplayDevices`; Linux:
`xrandr`, else the DRM connectors), of the `output_res` the game defaults to on each, and of the `totk.ini`
`output_res` (`installer/screens.py`). One folder per shape, named after the shape's size in `ASPECT_SIZES` (the
closest within 1%; `5120x2160` uses `2560x1080`); `runtime/romfs.c` `overlay_init` maps the game resolution the
same way, and a folder of the exact size from an older setup still wins. A 16:9 player gets none. The step runs
again when the displays, the prompts or the patches change; at a game resolution whose shape has no folder the
game draws 16:9 with bars, and the settings menu marks such sizes and can write the shape's folders in the
background for the next start.
8. **DLSS** (the window's tick box, on by default, or `--dlss`; Windows with an NVIDIA RTX GPU): download
`nvngx_dlss.dll` from NVIDIA's own DLSS SDK repository (github.com/NVIDIA/DLSS, a pinned tag, NVIDIA RTX SDK
license) into the install folder and check its size and SHA-256 (`steps.py`, `Dlss`). The release does not ship
the library; NGX loads it from the folder of totk.exe for `dlaa` and the DLSS modes. A DLSS library already in the
folder (a newer one the player put there) is kept. Without an RTX GPU the step only logs and does nothing; a failed
download warns, the game runs without DLSS, and the next run of the setup tries again.
8. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write
9. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write
`build-cache/rebuild.txt` in the install folder.
A cancelled or failed setup resumes from the last finished step (`totk-install.json`).
+1 -1
View File
@@ -619,7 +619,7 @@ class App:
# ---- self test ---------------------------------------------------------------------------------------------------
SAMPLE_START = {'type': 'start', 'release': 'selftest', 'mode': 'install', 'dest': 'Z:/selftest/TotK', 'log': 'D:\\log.txt',
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'dlss', 'cleanup']}
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup']}
SAMPLE_RUN = [
SAMPLE_START,
{'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}},
+1 -1
View File
@@ -27,7 +27,7 @@ TEXT = Path(__file__).resolve().parent / 'text'
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans')
# what the language switch in the window's corner shows for each
UI_LANGUAGE_LABELS = {'en': 'English', 'ru': 'Русский', 'pt-BR': 'Português (Brasil)', 'zh-Hans': '简体中文'}
STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'dlss', 'cleanup')
STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup')
# message parameter -> catalog id prefix of the names that replace its raw values
PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'}
LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID
+174
View File
@@ -0,0 +1,174 @@
"""The screen shapes and button prompts this player needs RomFS patch folders for (steps.Shapes).
A game resolution of another shape than 16:9 takes romfs-patches-<w>x<h>, the UI laid out for that shape
(tools/make_romfs_patches.py --aspect), and the prompts' folder of that shape (romfs-patches-<style>-<w>x<h>). The
layout depends only on the aspect ratio (tools/ultrawide_layout.py apply), so the setup writes one folder per shape,
named after the shape's size in ASPECT_SIZES (shape_size); runtime/romfs.c overlay_init maps the game resolution the
same way (cfg.c cfg_shape_size). It writes them only for the shapes of the connected displays and the totk.ini
output_res, and the prompts' ones only for the style totk.ini selects (prompts_style).
"""
import ctypes
import os
import re
import shutil
import subprocess
from pathlib import Path
# The game resolutions of another shape than 16:9 that runtime/ui/menu.cpp row_output_res lists, in the order of
# runtime/cfg.c SHAPED: 21:9 and 32:9 monitors, 16:10 screens (the Steam Deck's 1280x800, handhelds and laptops) and 3:2
# screens (Surface and Framework laptops and tablets)
ASPECT_SIZES = ('2560x1080', '3440x1440', '3840x1600', '5120x2160', '3840x1080', '5120x1440',
'1280x800', '1680x1050', '1920x1200', '2560x1600',
'1920x1280', '2160x1440', '2256x1504', '2880x1920', '3000x2000')
SHAPED = tuple(tuple(int(v) for v in s.split('x')) for s in ASPECT_SIZES)
TOLERANCE = 0.01 # cfg.c and resolution.c res_is_16x9: shapes within 1% are the same
def is_16x9(w, h):
return abs((w / h) / (16 / 9) - 1) <= TOLERANCE
def shape_size(w, h):
"""The folder size of w x h's shape: of ASPECT_SIZES within 1% of its aspect ratio, the closest, the first of equal
ones (5120x2160 is 2560x1080's shape). None for 16:9 and for a shape the setup has no layout for. The same rule as
runtime/cfg.c cfg_shape_size."""
if not w or not h or is_16x9(w, h):
return None
r, best, err = w / h, None, None
for sw, sh in SHAPED:
e = abs(sw / sh / r - 1)
if e <= TOLERANCE and (err is None or e < err):
best, err = f'{sw}x{sh}', e
return best
def default_size(w, h):
"""The output_res the game picks on a display of w x h while totk.ini sets none (runtime/cfg.c screen_default): of
ASPECT_SIZES within 1% of its shape, the smallest at least 1080 high that fits, else the largest that fits."""
if not w or not h or is_16x9(w, h):
return None
r, best, fit = w / h, None, None
for sw, sh in SHAPED:
if abs(sw / sh / r - 1) > TOLERANCE or sw > w or sh > h:
continue
if fit is None or sw > fit[0]:
fit = (sw, sh)
if sh >= 1080 and (best is None or sw < best[0]):
best = (sw, sh)
best = best or fit
return f'{best[0]}x{best[1]}' if best else None
# ---- the connected displays, as (width, height) of their current mode, the long side first (a portrait monitor or
# the Steam Deck's panel reports its height first; the game window is landscape)
class DISPLAY_DEVICEW(ctypes.Structure):
_fields_ = [('cb', ctypes.c_uint32), ('DeviceName', ctypes.c_wchar * 32), ('DeviceString', ctypes.c_wchar * 128),
('StateFlags', ctypes.c_uint32), ('DeviceID', ctypes.c_wchar * 128), ('DeviceKey', ctypes.c_wchar * 128)]
ATTACHED_TO_DESKTOP = 0x1
ENUM_CURRENT_SETTINGS = -1
DEVMODEW_SIZE = 220 # DEVMODEW: dmSize at 68, dmPelsWidth at 172, dmPelsHeight at 176
DEVMODE_PELS = 172
def windows_displays():
"""Every display attached to the desktop: EnumDisplayDevicesW over the adapters, EnumDisplaySettingsW for the
current mode, which is in pixels whatever the DPI awareness of this process."""
user32 = ctypes.WinDLL('user32')
out, i = [], 0
while True:
dev = DISPLAY_DEVICEW()
dev.cb = ctypes.sizeof(dev)
if not user32.EnumDisplayDevicesW(None, i, ctypes.byref(dev), 0):
break
i += 1
if not dev.StateFlags & ATTACHED_TO_DESKTOP:
continue
mode = ctypes.create_string_buffer(DEVMODEW_SIZE)
ctypes.c_uint16.from_buffer(mode, 68).value = DEVMODEW_SIZE
if user32.EnumDisplaySettingsW(dev.DeviceName, ENUM_CURRENT_SETTINGS, mode):
out.append((ctypes.c_uint32.from_buffer(mode, DEVMODE_PELS).value,
ctypes.c_uint32.from_buffer(mode, DEVMODE_PELS + 4).value))
return out
XRANDR = re.compile(r'\sconnected\s+(?:primary\s+)?(\d+)x(\d+)\+')
def linux_displays():
"""xrandr's connected outputs (X11 and XWayland); without xrandr the preferred mode of each connected DRM
connector."""
if shutil.which('xrandr'):
try:
text = subprocess.run(['xrandr', '--current'], capture_output=True, text=True, timeout=10).stdout
found = [(int(w), int(h)) for w, h in XRANDR.findall(text)]
if found:
return found
except (OSError, subprocess.SubprocessError):
pass
out = []
for conn in sorted(Path('/sys/class/drm').glob('card*-*')):
try:
if (conn / 'status').read_text().strip() != 'connected':
continue
m = re.match(r'(\d+)x(\d+)', (conn / 'modes').read_text())
except OSError:
continue
if m:
out.append((int(m.group(1)), int(m.group(2))))
return out
def displays():
try:
found = windows_displays() if os.name == 'nt' else linux_displays()
except (OSError, AttributeError, ValueError):
found = []
return sorted({(max(w, h), min(w, h)) for w, h in found if w and h})
# ---- totk.ini (runtime/cfg.c reads the same keys, in any section, with or without the totk_ prefix)
def ini_value(text, name):
value = None
for line in text.splitlines():
m = re.match(rf'^\s*(?:totk_)?{name}\s*=\s*([^\s#;]*)', line, re.IGNORECASE)
if m:
value = m.group(1)
return value
def prompts_style(text):
"""The prompts' folder suffix the settings select, as runtime/input_map.c input_prompts_pick and
input_prompts_folder pick it at start: 'pc', 'xbox' (Nintendo pad layout), 'xbox-label' (any other) or None for the
game's own prompts, the default without a totk.ini."""
p, layout = ini_value(text, 'prompts'), (ini_value(text, 'pad_layout') or '').lower()
if p and p.lower() == 'pc':
return 'pc'
if not (p.lower() == 'xbox' if p else layout == 'xbox_prompts'):
return None
return 'xbox' if layout in ('nintendo', 'xbox_prompts') else 'xbox-label'
def wanted(dest, screens=None):
"""(sizes, style): the shape sizes to write layouts for, sorted, and the prompts style. A shape is wanted for each
display's own size and for the output_res the game defaults to there, and for the totk.ini output_res."""
screens = displays() if screens is None else screens
try:
text = (Path(dest) / 'totk.ini').read_text(encoding='utf-8-sig', errors='replace')
except OSError:
text = ''
sizes = set()
for w, h in screens:
w, h = max(w, h), min(w, h)
sizes.add(shape_size(w, h))
d = default_size(w, h)
if d:
sizes.add(shape_size(*(int(v) for v in d.split('x'))))
m = re.fullmatch(r'(\d+)x(\d+)', (ini_value(text, 'output_res') or '').lower())
if m:
sizes.add(shape_size(int(m.group(1)), int(m.group(2))))
sizes.discard(None)
return sorted(sizes, key=ASPECT_SIZES.index), prompts_style(text)
+87 -62
View File
@@ -1,4 +1,5 @@
"""The eight setup steps of docs/installer.md: check, fonts, extract, lift, compile, prepare, dlss, cleanup.
"""The ten setup steps of docs/installer.md: check, fonts, extract, lift, compile, prepare, pc_prompts, shapes, dlss,
cleanup.
Extraction runs in this process through tools/extract.py (the package's sibling tools/, which ships with it); fonts
runs the vendored extract_shared_fonts.py on the firmware folder; lift, compile and prepare run the bundled Python on
@@ -8,8 +9,8 @@ with the bundled clang (hostcheck.c).
Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ (Chinese and Korean text), totk.exe
and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/,
romfs-patches-xbox-label/, romfs-patches-pc/, romfs-patches-<style>-<w>x<h>/ (each of the three for each shaped size),
totk_xlate.exe, the
romfs-patches-xbox-label/, romfs-patches-pc/, romfs-patches-<w>x<h>/ and romfs-patches-<style>-<w>x<h>/ (for the
screen shapes and the prompts style this player needs, installer/screens.py), totk_xlate.exe, the
shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json.
Temp folder (<temp>/<dest name>-<hash>): check/ (ExeFS of both inputs, the host check), unpacked/ (the NSP of an NSZ
or XCZ input until the extraction is done), gen/ (C), build/ (objects), logs/. The cleanup keeps gen/, build/ and
@@ -36,7 +37,7 @@ import time
import urllib.request
from pathlib import Path
from . import ini
from . import ini, screens
from .layout import EXE, SUPPORTED, version_tag
from .runner import InstallError, Step
@@ -1042,12 +1043,7 @@ TRANSLATED = re.compile(r'gfx_shader: prepare: (\d+) of (\d+) pairs')
SKIPPED = re.compile(r'prepare-shaders: (\d+) variants skipped: the graphics driver crashed')
# The game resolutions of another shape than 16:9 that runtime/ui/menu.cpp row_output_res lists: 21:9 and 32:9 monitors,
# 16:10 screens (the Steam Deck's 1280x800, handhelds and laptops) and 3:2 screens (Surface and Framework laptops and
# tablets)
ASPECT_SIZES = ('2560x1080', '3440x1440', '3840x1600', '5120x2160', '3840x1080', '5120x1440',
'1280x800', '1680x1050', '1920x1200', '2560x1600',
'1920x1280', '2160x1440', '2256x1504', '2880x1920', '3000x2000')
ASPECT_SIZES = screens.ASPECT_SIZES
class Prepare(Step):
@@ -1097,16 +1093,6 @@ class Prepare(Step):
dest / 'romfs-patches'])
if code:
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
# The same overlay with the UI laid out for each game resolution of another shape the settings menu offers
# (runtime/romfs.c overlay_init picks the one that matches; the camera's side is the patch set aspect,
# recomp/patches-v<ver>.txt).
for size in ASPECT_SIZES:
remove(dest / f'romfs-patches-{size}')
code, log = run_tool(ctx, 'prepare', layout.tools / 'make_romfs_patches.py',
['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out',
dest / f'romfs-patches-{size}', '--aspect', size])
if code:
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
# The same with Xbox button icons in the prompts, for prompts = xbox (make_romfs_patches.py --prompts):
# romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label for xbox and auto (runtime/input_map.c
# input_prompts_folder). Both are written on every install, so the menu choices work without another run of
@@ -1123,25 +1109,6 @@ class Prepare(Step):
if code:
remove(out)
failed = failed or (code, log)
# Each prompts' folder once more for each shape of ASPECT_SIZES, romfs-patches-<style>-<w>x<h> with that
# shape's UI layout (--prompts <style> --aspect), which runtime/romfs.c overlay_init loads in place of
# romfs-patches-<w>x<h>: without it a player with Xbox or PC prompts on a screen that is not 16:9 chose between
# the prompts and the screen's shape. Only the Common archive differs from romfs-patches-<style>; --reuse links
# the fonts, messages and size table from there instead of compressing them again, so each folder takes
# seconds and a few MiB. Optional like romfs-patches-<style>, and skipped without it.
for style in ('xbox', 'xbox-label'):
plain = dest / f'romfs-patches-{style}'
for size in ASPECT_SIZES:
out = dest / f'romfs-patches-{style}-{size}'
remove(out)
if not (plain / 'manifest.tsv').is_file():
continue
code, log = run_tool(ctx, f'prepare-{style}-{size}', layout.tools / 'make_romfs_patches.py',
['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out',
out, '--prompts', style, '--aspect', size, '--reuse', plain])
if code:
remove(out)
failed = failed or (code, log)
if failed:
rep.warning('warn.xbox_prompts_failed', code=failed[0], log=str(failed[1]))
@@ -1192,11 +1159,17 @@ def bind_lines(dest):
if s.lower().startswith('bind_'))
def pc_binds(dest):
"""make_romfs_patches.py's --binds argument for the keyboard and mouse prompts: totk.ini when it has bind_ lines."""
return ['--binds', dest / 'totk.ini'] if bind_lines(dest) else []
class PcPrompts(Step):
"""romfs-patches-pc and romfs-patches-pc-<w>x<h>, for prompts = pc: the prompts drawn as the keys and mouse buttons
of totk.ini's bind_ lines (make_romfs_patches.py --prompts pc --binds), the keyboard defaults without them. Its own
step, keyed by those lines, so running the setup again after a change of the bindings draws the prompts again and
leaves the shaders alone. Optional like the Xbox prompts: a failure warns, and the game keeps the Switch prompts."""
"""romfs-patches-pc (16:9), for prompts = pc: the prompts drawn as the keys and mouse buttons of totk.ini's bind_
lines (make_romfs_patches.py --prompts pc --binds), the keyboard defaults without them. Its own step, keyed by those
lines, so running the setup again after a change of the bindings draws the prompts again and leaves the shaders
alone. The shaped romfs-patches-pc-<w>x<h> are the Shapes step's, which follows this key. Optional like the Xbox
prompts: a failure warns, and the game keeps the Switch prompts."""
id = 'pc_prompts'
def key(self, ctx):
@@ -1210,31 +1183,83 @@ class PcPrompts(Step):
def run(self, ctx):
layout, rep, dest = ctx.layout, ctx.reporter, ctx.dest
rep.progress('pc_prompts', 'draw', force=True)
binds = []
if bind_lines(dest):
binds = ['--binds', dest / 'totk.ini']
version = ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs']
plain = dest / 'romfs-patches-pc'
for out in [plain] + [dest / f'romfs-patches-pc-{size}' for size in ASPECT_SIZES]:
remove(out)
remove(plain)
code, log = run_tool(ctx, 'prepare-pc', layout.tools / 'make_romfs_patches.py',
version + ['--out', plain, '--prompts', 'pc', *binds])
failed = (code, log) if code else None
# Each shape of ASPECT_SIZES once more, as for the Xbox prompts (Prepare): --reuse links all but the Common
# archive from romfs-patches-pc.
for size in ASPECT_SIZES if not failed else ():
out = dest / f'romfs-patches-pc-{size}'
code, log = run_tool(ctx, f'prepare-pc-{size}', layout.tools / 'make_romfs_patches.py',
version + ['--out', out, '--prompts', 'pc', '--aspect', size, '--reuse', plain, *binds])
['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', plain,
'--prompts', 'pc', *pc_binds(dest)])
if code:
remove(plain)
rep.warning('warn.xbox_prompts_failed', code=code, log=str(log))
return {'failed': True}
return {}
# ---- 6b. screen shapes
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-xbox|-xbox-label|-pc)?-\d+x\d+$')
class Shapes(Step):
"""romfs-patches-<w>x<h> (the UI laid out for a shape, make_romfs_patches.py --aspect) and, with Xbox or PC prompts
in totk.ini, romfs-patches-<style>-<w>x<h> (that layout with those prompts), for the shapes this player needs:
those of the connected displays and of the totk.ini output_res, one folder per shape (installer/screens.py; the
game maps its resolution to the folder in runtime/romfs.c overlay_init). A setup before this step wrote all 15
sizes for every prompts style, 64 folders. The key holds the shapes and the style, so a run of the setup after a
monitor or settings change (or its rebuild mode) writes only these again; the game's settings menu can also start
the generator for the shape in use (runtime/ui/menu.cpp row_output_res)."""
id = 'shapes'
def wanted(self, ctx):
if not hasattr(ctx, 'shapes_wanted'):
ctx.shapes_wanted = screens.wanted(ctx.dest)
return ctx.shapes_wanted
def key(self, ctx):
sizes, style = self.wanted(ctx)
# The pc prompts' shaped folders are drawn from the same bindings as romfs-patches-pc, so they follow its key
prompts = ctx.keys.get('pc_prompts', '') if style == 'pc' else ''
return fingerprint('shapes-2', ctx.keys.get('prepare', ''), prompts, style or 'nintendo', *sizes)
def current(self, ctx, record):
return all((ctx.dest / name / 'manifest.tsv').is_file() for name in record.get('folders', []))
def run(self, ctx):
layout, rep, dest = ctx.layout, ctx.reporter, ctx.dest
sizes, style = self.wanted(ctx)
rep.log(f'shapes: displays {screens.displays()}, layouts for {sizes or "none"}, prompts {style or "nintendo"}')
for old in dest.iterdir() if dest.is_dir() else ():
if old.is_dir() and SHAPED_FOLDER.match(old.name):
remove(old)
version = version_tag(game_version(ctx))
plain = dest / f'romfs-patches-{style}' if style else None
folders, failed = [], None
for i, size in enumerate(sizes):
rep.progress('shapes', 'layouts', i, len(sizes), 'shapes', force=True)
out = dest / f'romfs-patches-{size}'
code, log = run_tool(ctx, 'shapes', layout.tools / 'make_romfs_patches.py',
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--aspect', size])
if code:
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
folders.append(out.name)
# Only the Common archive differs from romfs-patches-<style>: --reuse links the fonts, messages and size
# table from there. Optional like that folder: the game keeps the Switch prompts with this layout.
if not plain or not (plain / 'manifest.tsv').is_file():
continue
out = dest / f'romfs-patches-{style}-{size}'
code, log = run_tool(ctx, f'shapes-{style}', layout.tools / 'make_romfs_patches.py',
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--prompts', style,
'--aspect', size, '--reuse', plain, *(pc_binds(dest) if style == 'pc' else ())])
if code:
remove(out)
failed = failed or (code, log)
else:
folders.append(out.name)
rep.progress('shapes', 'layouts', len(sizes), len(sizes), 'shapes', force=True)
if failed:
if not (plain / 'manifest.tsv').is_file():
remove(plain)
rep.warning('warn.xbox_prompts_failed', code=failed[0], log=str(failed[1]))
return {'failed': True}
return {}
return {'folders': folders, 'sizes': sizes, 'style': style}
# ---- 7. NVIDIA DLSS
@@ -1380,4 +1405,4 @@ def romfs_problem(romfs, expected):
def all_steps():
return [Check(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Dlss(), Cleanup()]
return [Check(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Cleanup()]
+2
View File
@@ -6,6 +6,7 @@
"step.compile": "Compiling {game_exe}",
"step.prepare": "Preparing the shaders",
"step.pc_prompts": "Drawing the keyboard and mouse prompts",
"step.shapes": "Laying out the game screens for your displays",
"step.dlss": "Downloading NVIDIA DLSS",
"step.cleanup": "Cleaning up",
@@ -35,6 +36,7 @@
"phase.prepare.translate": "Translating the shaders",
"phase.prepare.libraries": "Building the shaders for the graphics driver",
"phase.prepare.pack": "Packing the shader cache into one file",
"phase.shapes.layouts": "Writing the screen layouts and button prompts for each display shape",
"phase.dlss.download": "Downloading nvngx_dlss.dll from NVIDIA's DLSS SDK",
"phase.cleanup.ini": "Writing totk.ini",
"phase.cleanup.temp": "Removing temporary files",
+2
View File
@@ -6,6 +6,7 @@
"step.compile": "Compilando o {game_exe}",
"step.prepare": "Preparando os shaders",
"step.pc_prompts": "Desenhando os ícones de teclado e mouse",
"step.shapes": "Ajustando as telas do jogo aos seus monitores",
"step.dlss": "Baixando o NVIDIA DLSS",
"step.cleanup": "Finalizando",
@@ -35,6 +36,7 @@
"phase.prepare.translate": "Traduzindo os shaders",
"phase.prepare.libraries": "Montando os shaders para o driver de vídeo",
"phase.prepare.pack": "Juntando o cache de shaders num único arquivo",
"phase.shapes.layouts": "Gravando os layouts de tela e os botões para cada formato de monitor",
"phase.dlss.download": "Baixando o nvngx_dlss.dll do DLSS SDK da NVIDIA",
"phase.cleanup.ini": "Gravando o totk.ini",
"phase.cleanup.temp": "Removendo os arquivos temporários",
+2
View File
@@ -6,6 +6,7 @@
"step.compile": "Сборка {game_exe}",
"step.prepare": "Подготовка шейдеров",
"step.pc_prompts": "Рисование подсказок клавиатуры и мыши",
"step.shapes": "Раскладка экранов игры под ваши мониторы",
"step.dlss": "Загрузка NVIDIA DLSS",
"step.cleanup": "Уборка",
@@ -35,6 +36,7 @@
"phase.prepare.translate": "Трансляция шейдеров",
"phase.prepare.libraries": "Сборка шейдеров для драйвера видеокарты",
"phase.prepare.pack": "Упаковка кэша шейдеров в один файл",
"phase.shapes.layouts": "Запись раскладок экрана и кнопок для каждой формы монитора",
"phase.dlss.download": "Загрузка nvngx_dlss.dll из DLSS SDK от NVIDIA",
"phase.cleanup.ini": "Запись totk.ini",
"phase.cleanup.temp": "Удаление временных файлов",
+2
View File
@@ -6,6 +6,7 @@
"step.compile": "编译 {game_exe}",
"step.prepare": "准备着色器",
"step.pc_prompts": "绘制键盘和鼠标按键提示",
"step.shapes": "为你的显示器调整游戏画面布局",
"step.dlss": "下载 NVIDIA DLSS",
"step.cleanup": "清理",
@@ -35,6 +36,7 @@
"phase.prepare.translate": "转译着色器",
"phase.prepare.libraries": "为显卡驱动构建着色器",
"phase.prepare.pack": "将着色器缓存打包成一个文件",
"phase.shapes.layouts": "为每种显示器比例写入画面布局和按键提示",
"phase.dlss.download": "从 NVIDIA 的 DLSS SDK 下载 nvngx_dlss.dll",
"phase.cleanup.ini": "写入 totk.ini",
"phase.cleanup.temp": "删除临时文件",
+24 -4
View File
@@ -370,16 +370,36 @@ static const char *raw_get(const char *name) {
// picture between black bars. The sizes are the ones the installer lays the HUD out for (installer/steps.py
// ASPECT_SIZES, ui/menu.cpp row_output_res): of the display's shape within 1%, the smallest at least 1080 high that fits
// the display, else the largest that fits. A 16:9 display, an unknown one or one of another shape keeps 1920x1080.
// Xbox and keyboard prompts have a folder for each of these sizes (romfs-patches-xbox-<w>x<h>, -xbox-label-<w>x<h>,
// -pc-<w>x<h>, installer/steps.py Prepare): they keep 1920x1080 only when the one for the display's size is missing,
// as in a source build without make_romfs_patches.py --prompts <style> --aspect or an install by an older setup,
// where a default of another shape would trade the prompts the player chose for the Switch ones.
// Xbox and keyboard prompts need their folder for that size's shape too (romfs-patches-xbox-<w>x<h>, -xbox-label-,
// -pc-, written by installer/steps.py Shapes for the style totk.ini selects and the connected displays' shapes): they
// keep 1920x1080 when it is missing, as in a source build without make_romfs_patches.py --prompts <style> --aspect or
// after a switch of prompts in the menu, where a default of another shape would trade the prompts the player chose for
// the Switch ones.
static const unsigned SHAPED[][2] = {
{2560, 1080}, {3440, 1440}, {3840, 1600}, {5120, 2160}, // 21:9
{3840, 1080}, {5120, 1440}, // 32:9
{1280, 800}, {1680, 1050}, {1920, 1200}, {2560, 1600}, // 16:10
{1920, 1280}, {2160, 1440}, {2256, 1504}, {2880, 1920}, {3000, 2000}, // 3:2
};
// The folder size of w x h's shape: of SHAPED within 1% of its aspect ratio, the closest, the first of equal ones
// (5120x2160 takes 2560x1080). The UI layout depends on the aspect ratio alone (tools/ultrawide_layout.py apply), so
// the setup writes one romfs-patches-<w>x<h> per shape, named after this size (installer/screens.py shape_size, the
// same rule), and romfs.c overlay_init looks for it. 0 for 16:9 and for a shape without a layout.
int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]) {
if (!w || !h) return 0;
double r = (double)w / h, err = 0;
if (fabs(r / (16.0 / 9.0) - 1) <= 0.01) return 0;
int best = -1;
for (int i = 0; i < (int)(sizeof SHAPED / sizeof *SHAPED); i++) {
double e = fabs((double)SHAPED[i][0] / SHAPED[i][1] / r - 1);
if (e <= 0.01 && (best < 0 || e < err)) best = i, err = e;
}
if (best < 0) return 0;
out[0] = SHAPED[best][0], out[1] = SHAPED[best][1];
return 1;
}
static char screen_res[16]; // set once by cfg_init, "" for none
// romfs-patches-xbox-, romfs-patches-xbox-label- and romfs-patches-pc-<screen_res> have a manifest (set once by
// cfg_init)
+3
View File
@@ -23,6 +23,9 @@ unsigned cfg_version(void);
int cfg_from_env(const char *name);
// 1 when the player set name (the environment or totk.ini), 0 when cfg_get gives a device profile's default or NULL.
int cfg_is_set(const char *name);
// The folder size of w x h's shape (cfg.c SHAPED: the closest aspect ratio within 1%, the first of equal ones), the
// one romfs-patches-<w>x<h> the setup writes for it. 0 for 16:9 and for a shape without a UI layout.
int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]);
// The device profile in use, "deck" or "desktop" (TOTK_DEVICE_PROFILE, else what the machine is).
const char *cfg_device_profile(void);
// Writes the keys cfg_set changed since the last save into totk.ini next to totk.exe (cfg_save_to: the file at path).
+32
View File
@@ -339,6 +339,38 @@ int probe_cfg(void) {
CHECK(a_east == EQ(input_prompts_folder(PROMPTS_XBOX, layouts[i]), "romfs-patches-xbox"),
"prompts: the folder names A as B exactly when the layout puts A on the button labelled B");
}
// One folder per screen shape (cfg.c cfg_shape_size, installer/screens.py shape_size): the closest aspect ratio of
// SHAPED within 1%, the first of equal ones; 16:9 and unlisted shapes have none.
unsigned sz[2] = {0, 0};
CHECK(cfg_shape_size(5120, 2160, sz) && sz[0] == 2560 && sz[1] == 1080, "shape: 5120x2160 takes 2560x1080's folder");
CHECK(cfg_shape_size(3440, 1440, sz) && sz[0] == 3440 && sz[1] == 1440, "shape: 3440x1440 keeps its own (0.8% off 2560x1080)");
CHECK(cfg_shape_size(1920, 800, sz) && sz[0] == 3840 && sz[1] == 1600, "shape: 1920x800 takes 3840x1600's folder");
CHECK(cfg_shape_size(2560, 1600, sz) && sz[0] == 1280 && sz[1] == 800 && cfg_shape_size(3000, 2000, sz) &&
sz[0] == 1920 && sz[1] == 1280 && cfg_shape_size(5120, 1440, sz) && sz[0] == 3840 && sz[1] == 1080,
"shape: 16:10, 3:2 and 32:9 take their first size");
CHECK(!cfg_shape_size(1920, 1080, sz) && !cfg_shape_size(2560, 1440, sz) && !cfg_shape_size(1024, 768, sz),
"shape: none for 16:9 and 4:3");
// romfs.c shaped_name: the exact size's folder (an older setup wrote every size) wins, else the shape's
{
char dir[1100], f[1200];
snprintf(dir, sizeof dir, "%.*scfg-probe-shapes", (int)(cut + 1 - path), path);
static const char *const made[] = {"romfs-patches-2560x1080", "romfs-patches-xbox-5120x2160"};
for (int i = 0; i < 2; i++) {
snprintf(f, sizeof f, "%s/%s", dir, made[i]);
plat_file_mkdir_p(f);
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, made[i]);
plat_file_write(f, "#\n", 2);
}
snprintf(f, sizeof f, "%s/romfs-index.bin", dir);
plat_setenv("TOTK_ROMFS_INDEX", f);
CHECK(romfs_shaped_ready(2560, 1080) && romfs_shaped_ready(5120, 2160) && !romfs_shaped_ready(3440, 1440),
"shape: 5120x2160 finds 2560x1080's layout folder, 3440x1440 does not");
CHECK(romfs_shaped_prompts_ready("romfs-patches-xbox", 5120, 2160) &&
!romfs_shaped_prompts_ready("romfs-patches-xbox", 2560, 1080) &&
!romfs_shaped_prompts_ready("romfs-patches-pc", 5120, 2160),
"shape: an older install's exact-size prompts folder serves that size only");
plat_setenv("TOTK_ROMFS_INDEX", NULL);
}
uint8_t pd[PAD_COUNT] = {0};
pd[PAD_SOUTH] = pd[PAD_NORTH] = 1;
CHECK(input_map_pad_buttons(pd, PAD_LAYOUT_NINTENDO) == (1ull << B_B | 1ull << B_X) &&
+8
View File
@@ -47,6 +47,14 @@ enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROM
ROMFS_PROMPTS_PATCHES };
const char *romfs_prompts(void);
int romfs_prompts_ready(const char *folder);
// 1 when the game resolution w x h is of another shape whose folders are missing: the UI layout, or that of
// prompts_folder (a prompts' folder that is there at 16:9; NULL for the game's own prompts). romfs.c shaped_name.
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder);
// 1 when build-cache/rebuild.txt names the setup's Python and tools/make_romfs_patches.py and both exist, with romfs/.
int romfs_shape_can_prepare(void);
// Starts the generator for w x h's shape (its layout, and prompts_folder's when that is there at 16:9 and lacks it) as
// child processes the game does not wait for; the next start loads the result. 1 when every one started.
int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder);
int romfs_prompts_off(const char *folder);
const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added); // RomFS path of overlay k
void fs_trace(const char *what, const char *path); // TOTK_TRACE=fs: one line per open
+125 -20
View File
@@ -967,11 +967,29 @@ static void overlay_drop(size_t a, size_t b) {
noverlay -= b - a;
}
// The folder <prefix>-<w>x<h> the game resolution w x h takes in base: that exact size when it has a manifest (an
// install by a setup that wrote every size, or make_romfs_patches.py --aspect <w>x<h> in a source build), else the
// size of its shape (cfg.c cfg_shape_size), the one folder per shape installer/steps.py Shapes writes. name gets the
// folder found, or the shape's one when neither has a manifest (for the log). 1 when found.
static int shaped_name(const char *base, const char *prefix, unsigned w, unsigned h, char *name, size_t cap) {
char path[2400];
unsigned s[2] = {w, h};
for (int pass = 0; pass < 2; pass++) {
if (pass && !cfg_shape_size(w, h, s)) break;
if (pass && s[0] == w && s[1] == h) break;
snprintf(name, cap, "%s-%ux%u", prefix, s[0], s[1]);
if (snprintf(path, sizeof path, "%s/%s/manifest.tsv", base, name) < (int)sizeof path && plat_file_exists(path))
return 1;
}
return 0;
}
static void overlay_init(void) {
// TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py).
// A game resolution that is not 16:9 takes romfs-patches-<w>x<h> instead when it is there: the same overlay with
// the UI laid out for that shape (make_romfs_patches.py --aspect), when the game version has the camera aspect patch
// the layout goes with (res_wants_wide_overlay).
// A game resolution that is not 16:9 takes romfs-patches-<w>x<h> instead when it is there (shaped_name: the exact
// size, else the folder of its shape): the same overlay with the UI laid out for that shape
// (make_romfs_patches.py --aspect), when the game version has the camera aspect patch the layout goes with
// (res_wants_wide_overlay).
// With prompts = xbox, the Xbox prompts' folder for the pad layout in its place (input_prompts_folder): the same
// patches with Xbox button icons (make_romfs_patches.py --prompts); prompts = pc takes romfs-patches-pc whatever
// the pad layout. The game reads the archives once at boot, so the prompts stay until restart even though the
@@ -987,23 +1005,29 @@ static void overlay_init(void) {
int wide = 0;
unsigned out[2];
res_wanted(out);
unsigned shape[2] = {out[0], out[1]}; // the --aspect of the folder made for this shape
cfg_shape_size(out[0], out[1], shape);
if (!patches && res_wants_wide_overlay(out)) {
if (snprintf(def, sizeof def, "%s/romfs-patches-%ux%u/manifest.tsv", index_dir, out[0], out[1]) < (int)sizeof def &&
plat_file_exists(def)) {
def[strlen(def) - strlen("/manifest.tsv")] = 0;
char name[128];
if (shaped_name(index_dir, "romfs-patches", out[0], out[1], name, sizeof name) &&
snprintf(def, sizeof def, "%s/%s", index_dir, name) < (int)sizeof def) {
patches = def, wide = 1;
rt_log("RomFS overlay: the UI layout for %ux%u from %s", out[0], out[1], name);
} else {
rt_log("RomFS overlay: no romfs-patches-%ux%u for this game resolution, the UI keeps its 16:9 layout "
"(tools/make_romfs_patches.py --aspect %ux%u)", out[0], out[1], out[0], out[1]);
rt_log("RomFS overlay: no %s for this game resolution, the UI keeps its 16:9 layout (run the setup again, "
"or tools/make_romfs_patches.py --aspect %ux%u)", name, shape[0], shape[1]);
}
}
static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each Xbox folder, then the PC one
for (int i = 0; i < 3; i++) {
const char *name = i < 2 ? input_prompts_folder(PROMPTS_XBOX, layouts[i]) : input_prompts_folder(PROMPTS_PC, 0);
char *dir = prompts_folders[i].dir;
if (wide) snprintf(dir, sizeof prompts_folders[i].dir, "%s-%ux%u", name, out[0], out[1]);
else snprintf(dir, sizeof prompts_folders[i].dir, "%s", name);
prompts_folders[i].name = name;
if (wide) {
prompts_folders[i].ready = shaped_name(index_dir, name, out[0], out[1], dir, sizeof prompts_folders[i].dir);
continue;
}
snprintf(dir, sizeof prompts_folders[i].dir, "%s", name);
prompts_folders[i].ready =
snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, dir) < (int)sizeof path && plat_file_exists(path);
}
@@ -1035,7 +1059,7 @@ static void overlay_init(void) {
char why[256];
if (prompts_off == ROMFS_PROMPTS_SHAPE)
snprintf(why, sizeof why, "the game resolution has no %s (tools/make_romfs_patches.py --prompts %s "
"--aspect %ux%u)", wanted_dir, prompts_wanted + strlen("romfs-patches-"), out[0], out[1]);
"--aspect %ux%u)", wanted_dir, prompts_wanted + strlen("romfs-patches-"), shape[0], shape[1]);
else
snprintf(why, sizeof why, "%s", prompts_off == ROMFS_PROMPTS_PATCHES
? "TOTK_ROMFS_PATCHES is set"
@@ -1091,26 +1115,107 @@ static void index_path(char *out, size_t cap) {
strcpy(out + k, "romfs-index.bin");
}
// 1 when <prefix>-<w>x<h> has a manifest next to romfs-index.bin. Works before fs_init: index_dir is not set that early
// (cfg_init, res_init and resolution.c decide run first), so the index path is worked out again here.
static int shaped_folder_ready(const char *prefix, unsigned w, unsigned h) {
char dir[2100], path[2200];
index_path(dir, sizeof dir);
// The folder of romfs-index.bin. Works before fs_init: index_dir is not set that early (cfg_init, res_init and
// resolution.c decide run first), so the index path is worked out again here.
static void index_folder(char *dir, size_t cap) {
index_path(dir, cap);
char *sep = plat_last_sep(dir);
if (sep) *sep = 0;
else strcpy(dir, ".");
return snprintf(path, sizeof path, "%s/%s-%ux%u/manifest.tsv", dir, prefix, w, h) < (int)sizeof path &&
plat_file_exists(path);
}
// 1 when the game resolution w x h has the UI layout of its shape: romfs-patches-<w>x<h>, the folder overlay_init
// looks for.
// 1 when the folder overlay_init takes for <prefix> at w x h (shaped_name) has a manifest next to romfs-index.bin.
static int shaped_folder_ready(const char *prefix, unsigned w, unsigned h) {
char dir[2100], name[128];
index_folder(dir, sizeof dir);
return shaped_name(dir, prefix, w, h, name, sizeof name);
}
// 1 when the game resolution w x h has the UI layout of its shape: romfs-patches-<w>x<h> of that size or of its shape,
// the folder overlay_init looks for.
int romfs_shaped_ready(unsigned w, unsigned h) { return shaped_folder_ready("romfs-patches", w, h); }
// 1 when it has a prompts' folder (input_prompts_folder) with that layout too: <folder>-<w>x<h>, which overlay_init
// loads in its place with those prompts.
int romfs_shaped_prompts_ready(const char *folder, unsigned w, unsigned h) { return shaped_folder_ready(folder, w, h); }
// ---- the layout for a new screen, from the settings menu (ui/menu.cpp row_output_res)
// The setup writes the shaped folders for the displays connected when it ran (installer/steps.py Shapes). After a
// monitor change the menu can start the same generator for the shape of the game resolution: the setup's Python and
// tools/make_romfs_patches.py, which build-cache/rebuild.txt names (installer/steps.py write_rebuild_command: line 1 the
// Python, pythonw on Windows, so no console opens; line 4 the setup's folder), on the install folder's romfs/. Child
// processes the game does not wait for: the generator writes manifest.tsv last, so a folder it has not finished is not
// taken, and the next start loads the finished one.
static int prepare_tools(char *python, size_t pcap, char *script, size_t scap, char *dir, size_t dcap) {
char path[2400];
index_folder(dir, dcap);
uint64_t n = 0;
snprintf(path, sizeof path, "%s/build-cache/rebuild.txt", dir);
char *text = (char *)plat_file_read(path, &n);
if (!text) return 0;
char *lines[5] = {0};
int k = 0;
for (char *p = text; k < 5 && p < text + n;) {
char *e = memchr(p, '\n', (size_t)(text + n - p));
if (!e) e = text + n;
if (e > p && e[-1] == '\r') e[-1] = 0;
*e = 0;
lines[k++] = p;
p = e + 1;
}
int ok = k >= 4 && !strcmp(lines[1], "-c") && snprintf(python, pcap, "%s", lines[0]) < (int)pcap &&
snprintf(script, scap, "%s/tools/make_romfs_patches.py", lines[3]) < (int)scap;
free(text);
snprintf(path, sizeof path, "%s/romfs/romfs.bin", dir);
return ok && plat_file_exists(python) && plat_file_exists(script) && plat_file_exists(path);
}
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder) {
unsigned out[2] = {w, h};
if (!res_wants_wide_overlay(out)) return 0;
return !shaped_folder_ready("romfs-patches", w, h) ||
(prompts_folder && romfs_prompts_ready(prompts_folder) && !shaped_folder_ready(prompts_folder, w, h));
}
int romfs_shape_can_prepare(void) {
static int known = -1;
if (known < 0) {
char python[1024], script[1100], dir[2100];
known = prepare_tools(python, sizeof python, script, sizeof script, dir, sizeof dir);
}
return known;
}
int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder) {
char python[1024], script[1100], dir[2100], romfs[2200], out[2300], reuse[2300], size[32], version[8], name[128];
unsigned s[2];
if (!cfg_shape_size(w, h, s) || !prepare_tools(python, sizeof python, script, sizeof script, dir, sizeof dir))
return 0;
snprintf(size, sizeof size, "%ux%u", s[0], s[1]);
snprintf(version, sizeof version, "v%d", rt_game_version);
snprintf(romfs, sizeof romfs, "%s/romfs", dir);
int started = 0, failed = 0;
if (!shaped_name(dir, "romfs-patches", w, h, name, sizeof name)) {
snprintf(out, sizeof out, "%s/romfs-patches-%s", dir, size);
const char *argv[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--aspect", size,
NULL};
if (plat_spawn(argv, dir)) started++;
else failed++;
}
snprintf(reuse, sizeof reuse, "%s/%s/manifest.tsv", dir, prompts_folder ? prompts_folder : "");
if (prompts_folder && plat_file_exists(reuse) && !shaped_name(dir, prompts_folder, w, h, name, sizeof name)) {
snprintf(reuse, sizeof reuse, "%s/%s", dir, prompts_folder);
snprintf(out, sizeof out, "%s/%s-%s", dir, prompts_folder, size);
const char *argv[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--prompts",
prompts_folder + strlen("romfs-patches-"), "--aspect", size, "--reuse", reuse, NULL};
if (plat_spawn(argv, dir)) started++;
else failed++;
}
rt_log("RomFS overlay: making the layout for %s in the background (%d generators started, %d failed; %s)", size,
started, failed, script);
return started && !failed;
}
static void load_index(void) {
char path[2100];
index_path(path, sizeof path);
+32 -3
View File
@@ -515,7 +515,35 @@ static void row_output_res(void) {
snprintf(shown[i], sizeof shown[i], "%d × %d", w, h); // U+00D7, the multiplication sign
names[i] = shown[i];
}
opt_choice_list("TOTK_OUTPUT_RES", UI_MENU_OUTPUT_RES, vals, names, N, UI_MENU_OUTPUT_RES_DESC);
// A size of another shape needs that shape's folders (romfs.c overlay_init): the layout, and with Xbox or PC
// prompts the prompts' one too. The setup writes them for the displays it saw (installer/steps.py Shapes); at a
// shape without them the game draws 16:9 with bars or keeps the Switch prompts, so the row says so and offers to
// start the generator for the next start (romfs_shape_prepare; a child process, the menu does not wait). The file
// checks run again only when a setting or the started generation changes.
static unsigned seen = ~0u;
static int missing, started; // started: 0 not asked, 1 running, -1 failed to start
static char asked[16];
const char *now = cfg_value("TOTK_OUTPUT_RES");
if (seen != cfg_version()) {
seen = cfg_version();
unsigned w = 0, h = 0;
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
missing = sscanf(now, "%ux%u", &w, &h) == 2 && romfs_shape_missing(w, h, want);
}
int here = started && !strcmp(asked, now); // the generation started for the value shown
const char *note = !missing ? nullptr
: here ? menu_text(started > 0 ? UI_MENU_OUTPUT_RES_PREPARING : UI_MENU_SHAPE_PREPARE_FAILED)
: menu_text(UI_MENU_OUTPUT_RES_NO_LAYOUT);
opt_choice_list("TOTK_OUTPUT_RES", UI_MENU_OUTPUT_RES, vals, names, N, UI_MENU_OUTPUT_RES_DESC, -1, note);
if (!missing || here || !romfs_shape_can_prepare()) return;
if (!opt_button("##shape_prepare", UI_MENU_SHAPE_PREPARE, UI_MENU_SHAPE_PREPARE_DESC)) return;
unsigned w = 0, h = 0;
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
sscanf(now, "%ux%u", &w, &h);
snprintf(asked, sizeof asked, "%s", now);
started = romfs_shape_prepare(w, h, input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout))
? 1 : -1;
}
static void row_render_scale(void) {
@@ -807,8 +835,9 @@ static const char *prompts_note(bool *restart) {
const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts();
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
if (want == used || (want && used && !strcmp(want, used))) return nullptr;
// A game resolution of another shape needs a folder of its own for the prompts (<folder>-<w>x<h>). The setup writes
// one for each size the Screen tab offers; at any other size the shape is the reason, not the setup.
// A game resolution of another shape needs a folder of its own for the prompts (<folder>-<w>x<h>, one per shape).
// The setup writes it for the shapes of the displays it saw and the prompts totk.ini had then; at another shape
// the shape is the reason (row_output_res offers to make it), not a damaged install.
int off = romfs_prompts_off(want);
if (want && !romfs_prompts_ready(want) && off != ROMFS_PROMPTS_SHAPE) return menu_text(UI_MENU_PROMPTS_MISSING);
switch (off) {
+20
View File
@@ -275,6 +275,11 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_FAILED] = "prompt files damaged: run the setup again",
[UI_MENU_PROMPTS_RESTART] = "prompts change after restart",
[UI_MENU_PROMPTS_OFF_SHAPE] = "off at this game resolution (no layout made for it)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "no layout made for this shape: run the setup again",
[UI_MENU_OUTPUT_RES_PREPARING] = "layout being made in the background; used at the next start",
[UI_MENU_SHAPE_PREPARE] = "Prepare the layout for this screen",
[UI_MENU_SHAPE_PREPARE_DESC] = "Makes the interface layout and the chosen button prompts for this game resolution's shape in the background, with the setup's tools, as the setup does for the displays it saw. The game keeps running; it uses them from its next start.",
[UI_MENU_SHAPE_PREPARE_FAILED] = "the setup's tools did not start: run the setup again",
[UI_MENU_PROMPTS_OFF_MODS] = "off: a RomFS mod replaces their files",
[UI_MENU_PROMPTS_OFF_PATCHES] = "off while TOTK_ROMFS_PATCHES is set",
[UI_MENU_RESTART] = "Restart now",
@@ -798,6 +803,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова",
[UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска",
[UI_MENU_PROMPTS_OFF_SHAPE] = "выкл. при этом разрешении игры (для него нет раскладки)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "для этой формы нет раскладки: запустите установщик снова",
[UI_MENU_OUTPUT_RES_PREPARING] = "раскладка создаётся в фоне; будет при следующем запуске",
[UI_MENU_SHAPE_PREPARE] = "Подготовить раскладку для этого экрана",
[UI_MENU_SHAPE_PREPARE_DESC] = "Создаёт в фоне раскладку интерфейса и выбранные подсказки кнопок для формы этого разрешения игры инструментами установщика, как установщик делает для мониторов, которые видел. Игра продолжает работать; раскладка будет со следующего запуска.",
[UI_MENU_SHAPE_PREPARE_FAILED] = "инструменты установщика не запустились: запустите установщик снова",
[UI_MENU_PROMPTS_OFF_MODS] = "выкл.: мод RomFS заменяет их файлы",
[UI_MENU_PROMPTS_OFF_PATCHES] = "выкл., пока задан TOTK_ROMFS_PATCHES",
[UI_MENU_RESTART] = "Перезапустить сейчас",
@@ -1513,6 +1523,11 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_FAILED] = "arquivos dos ícones danificados: execute a instalação de novo",
[UI_MENU_PROMPTS_RESTART] = "os ícones mudam após reiniciar",
[UI_MENU_PROMPTS_OFF_SHAPE] = "desligados nesta resolução de jogo (sem layout feito para ela)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "sem layout feito para este formato: rode o instalador de novo",
[UI_MENU_OUTPUT_RES_PREPARING] = "layout sendo feito em segundo plano; usado na próxima vez que o jogo abrir",
[UI_MENU_SHAPE_PREPARE] = "Preparar o layout para esta tela",
[UI_MENU_SHAPE_PREPARE_DESC] = "Faz em segundo plano o layout da interface e os botões escolhidos para o formato desta resolução de jogo, com as ferramentas do instalador, como o instalador faz para os monitores que viu. O jogo continua rodando; ele os usa a partir da próxima vez que abrir.",
[UI_MENU_SHAPE_PREPARE_FAILED] = "as ferramentas do instalador não abriram: rode o instalador de novo",
[UI_MENU_PROMPTS_OFF_MODS] = "desligados: um mod de RomFS substitui os arquivos deles",
[UI_MENU_PROMPTS_OFF_PATCHES] = "desligados enquanto TOTK_ROMFS_PATCHES está definido",
[UI_MENU_RESTART] = "Reiniciar agora",
@@ -2185,6 +2200,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_FAILED] = "按键提示文件已损坏:请重新运行安装程序",
[UI_MENU_PROMPTS_RESTART] = "按键提示重启后生效",
[UI_MENU_PROMPTS_OFF_SHAPE] = "此游戏分辨率下关闭(未为其制作布局)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "未为此比例制作布局:请重新运行安装程序",
[UI_MENU_OUTPUT_RES_PREPARING] = "布局正在后台制作;下次启动时使用",
[UI_MENU_SHAPE_PREPARE] = "为此屏幕准备布局",
[UI_MENU_SHAPE_PREPARE_DESC] = "使用安装程序的工具,在后台为此游戏分辨率的比例制作界面布局和所选按键提示,与安装程序为其检测到的显示器所做的相同。游戏继续运行;下次启动时生效。",
[UI_MENU_SHAPE_PREPARE_FAILED] = "安装程序的工具未能启动:请重新运行安装程序",
[UI_MENU_PROMPTS_OFF_MODS] = "已关闭:RomFS 模组替换了它们的文件",
[UI_MENU_PROMPTS_OFF_PATCHES] = "设置了 TOTK_ROMFS_PATCHES 时关闭",
[UI_MENU_RESTART] = "立即重启",
+2
View File
@@ -111,6 +111,8 @@ typedef enum {
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC,
// the notes under the prompts: their files are missing or damaged, they change after restart, or why they are off
UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE,
UI_MENU_OUTPUT_RES_NO_LAYOUT, UI_MENU_OUTPUT_RES_PREPARING, UI_MENU_SHAPE_PREPARE, UI_MENU_SHAPE_PREPARE_DESC,
UI_MENU_SHAPE_PREPARE_FAILED,
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
// "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO)
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
+88 -2
View File
@@ -16,7 +16,7 @@ from unittest import mock
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from installer import ini, runner, state, steps # noqa: E402
from installer import ini, runner, screens, state, steps # noqa: E402
from installer.events import Reporter # noqa: E402
from installer.layout import Layout # noqa: E402
@@ -588,6 +588,92 @@ class BaseGameCheckTest(unittest.TestCase):
self.assertEqual(steps.program_nca(records)[0]['title_id'], self.BASE)
class ShapesTest(unittest.TestCase):
"""installer/screens.py and the shapes step: one folder per screen shape, only for the displays and the prompts
style this player has (runtime/cfg.c cfg_shape_size maps the game resolution the same way)."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.dest = Path(self.tmp.name)
self.ctx = SimpleNamespace(dest=self.dest, keys={'prepare': 'p'}, layout=SimpleNamespace(tools=ROOT / 'tools'),
reporter=Reporter(out=io.StringIO()))
self.saved = steps.run_tool, steps.game_version, screens.displays
steps.game_version = lambda ctx: '1.4.3'
self.calls = []
def run(ctx, step, script, args, parse=None, cwd=None):
self.calls.append([str(a) for a in args])
out = Path(args[args.index('--out') + 1])
out.mkdir(parents=True)
(out / 'manifest.tsv').write_text('#\n')
return 0, None
steps.run_tool = run
def tearDown(self):
steps.run_tool, steps.game_version, screens.displays = self.saved
self.ctx.reporter.close()
self.tmp.cleanup()
def test_shape_rule(self):
self.assertEqual([screens.shape_size(*s) for s in ((5120, 2160), (3440, 1440), (1920, 800), (2560, 1600),
(1920, 1080), (1024, 768))],
['2560x1080', '3440x1440', '3840x1600', '1280x800', None, None])
self.assertEqual(screens.default_size(3440, 1440), '2560x1080') # runtime/cfg.c screen_default
self.assertEqual(screens.default_size(1280, 800), '1280x800')
def test_prompts_style_as_the_game_picks_it(self):
self.assertEqual([screens.prompts_style(t) for t in ('', 'prompts = pc', 'prompts = xbox',
'pad_layout = nintendo\nprompts = xbox',
'pad_layout = xbox_prompts', 'prompts = nintendo')],
[None, 'pc', 'xbox-label', 'xbox', 'xbox', None])
def test_wanted_from_displays_and_ini(self):
(self.dest / 'totk.ini').write_text('[display]\noutput_res = 3000x2000\n[input]\nprompts = pc\n')
self.assertEqual(screens.wanted(self.dest, [(3440, 1440), (1920, 1080), (800, 1280)]),
(['2560x1080', '3440x1440', '1280x800', '1920x1280'], 'pc'))
self.assertEqual(screens.wanted(self.dest / 'none', [(2560, 1440)]), ([], None))
def test_run_writes_only_the_wanted_folders(self):
screens.displays = lambda: [(2560, 1080)]
(self.dest / 'totk.ini').write_text('pad_layout = nintendo\nprompts = xbox\n')
for old in ('romfs-patches-3440x1440', 'romfs-patches-pc-1280x800', 'romfs-patches-xbox'):
(self.dest / old).mkdir()
(self.dest / 'romfs-patches-xbox' / 'manifest.tsv').write_text('#\n')
step = steps.Shapes()
step.key(self.ctx)
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-xbox-2560x1080'])
self.assertEqual(sorted(p.name for p in self.dest.iterdir() if p.is_dir()),
['romfs-patches-2560x1080', 'romfs-patches-xbox', 'romfs-patches-xbox-2560x1080'])
self.assertEqual(self.calls[0][-2:], ['--aspect', '2560x1080'])
self.assertTrue(step.current(self.ctx, record))
def test_pc_prompts_shapes_follow_the_bindings(self):
screens.displays = lambda: [(3440, 1440)]
(self.dest / 'totk.ini').write_text('[input]\nprompts = pc\nbind_attack = key:f\n')
(self.dest / 'romfs-patches-pc').mkdir()
(self.dest / 'romfs-patches-pc' / 'manifest.tsv').write_text('#\n')
step = steps.Shapes()
self.ctx.keys['pc_prompts'] = 'a'
key = step.key(self.ctx)
self.ctx.keys['pc_prompts'] = 'b'
self.assertNotEqual(step.key(self.ctx), key)
record = step.run(self.ctx)
# the display's own shape and that of the 2560x1080 the game defaults to on it (runtime/cfg.c screen_default)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-pc-2560x1080',
'romfs-patches-3440x1440', 'romfs-patches-pc-3440x1440'])
self.assertEqual(self.calls[1][-4:], ['--reuse', str(self.dest / 'romfs-patches-pc'), '--binds',
str(self.dest / 'totk.ini')])
self.assertNotIn('--binds', self.calls[0])
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), {})
self.assertEqual([p.name for p in self.dest.iterdir() if p.is_dir()], ['romfs-patches-pc'])
self.assertEqual(len(self.calls), 1)
self.assertEqual(self.calls[0][-2:], ['--binds', str(self.dest / 'totk.ini')])
class FontsTest(unittest.TestCase):
"""The fonts step: keyed by language and firmware, a no-op without firmware, writes dest/shared-fonts."""
@@ -626,7 +712,7 @@ class FontsTest(unittest.TestCase):
def test_all_steps_order(self):
self.assertEqual([s.id for s in steps.all_steps()],
['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'dlss', 'cleanup'])
['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup'])
def test_extracts_into_the_install_folder(self):
self.fake_tool()