Give the interface its proportions at 16:10 and 21:9, and limit game resolutions to those shapes and 16:9.

The game lays its interface out in a 1920x1080 space and draws it over the whole output, so at 1280x800 every menu and
the HUD were 11 % taller than drawn, and at 21:9 34 % wider. tools/aspect_layouts.py rewrites the layout archive for
each shape: every layout's root pane scaled back, full-screen backgrounds kept full, the HUD moved to the screen's
edges, and the minimap, place name and dragon's tears map icon animations adjusted. It follows the behaviour of
Fruithapje21's TOTK-Ultrawide (GPL-3.0, read for behaviour only) and checks every original value before it writes.
make_romfs_patches.py writes the results to romfs-patches/16x10 and 21x9 at install and build time, and romfs.c serves
the one of the output's shape. resolution.c accepts 16:9, 16:10 and 21:9; another shape draws 16:9 with bars. The
menu lists the game resolutions by shape. Checked on 1.2.1 and 1.4.3 at 1280x800 and 3440x1440: HUD, minimap,
inventory, map, system tab and loading screen.
This commit is contained in:
Wellington Dias committed 2026-10-30 16:23:58 -03:00
1 parent b7baf43332
commit 7285688165
15 files changed
+402 -51

No files matched your search

+1 -1
View File
@@ -19,6 +19,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- Game updates 1.2.1 and 1.4.3, with saves that carry over between them
- 60 fps by default; up to 144 fps or the monitor's refresh rate (experimental)
- Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling
- 16:10 (Steam Deck, handhelds) and 21:9 (ultrawide) game resolutions, with the camera and the interface in that shape
- In-game settings menu (F1) and performance overlay (F10)
- Keyboard, mouse and gamepad with remapping, rumble and gyro
- Shaders prepared at install instead of during play
@@ -27,7 +28,6 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- Linux and the Steam Deck
- Mods made for emulators: unpack a mod into a `mods` folder
- Custom aspect ratios, including ultrawide
- VRR
## Installing
+6
View File
@@ -94,6 +94,12 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
(MacNativeGames' sites); `resolution.c` sets them from `output_res` and `render_scale` and grows the texture heap
and the application pool to match. When the window is larger than the output, `vk_fsr.c` runs AMD FSR 1 (EASU,
RCAS) on the present.
- Aspect ratio. Besides 16:9 the game draws in 16:10 and 21:9 (`resolution.c` `SHAPES`). The `aspect` patch set gives
the 3D camera and the 2D canvas the output's shape; the interface is laid out in a 1920x1080 space that the game
stretches over the output, so `tools/aspect_layouts.py` rewrites the layout archive for each shape (every layout's
root pane scaled back, full-screen panes kept full, edge-anchored HUD moved to the edges, after the behaviour of
Fruithapje21's TOTK-Ultrawide) and `romfs.c` serves the overlay of the output's shape (`romfs-patches/16x10`,
`21x9`). Another shape draws 16:9 with bars.
- Occlusion queries never block the CPU; a result that is not ready counts as visible.
- ASTC textures are uploaded as they are where the device reports `textureCompressionASTC_LDR`, and decoded by a compute shader everywhere else (`vk_astc.c`, `TOTK_ASTC`). The CPU decoder (`tex_astc*.c`) is the fallback and the test oracle.
- Draw state. A draw whose program, bound state and textures repeat reuses the previous draw's shaders and skips rebuilding its descriptor sets; descriptor sets are written through update templates (`vk_exec_draw.c`, `vk_pipeline.c`).
+2 -1
View File
@@ -80,7 +80,8 @@ From the repository root, in PowerShell. Every step that depends on the game ver
.venv\Scripts\python tools\build_xlate.py
```
5. Lift the modules to C, write the RomFS half of the frame-rate patches, then compile and link `build\<ver>\totk.exe`:
5. Lift the modules to C, write the RomFS overlays (the frame-rate fix, and the interface at 16:10 and 21:9), then
compile and link `build\<ver>\totk.exe`:
```powershell
.venv\Scripts\python recomp\gen.py --exefs build\extracted\<ver>\exefs --out generated\<ver> --patches recomp\patches-<ver>.txt
+3 -3
View File
@@ -77,9 +77,9 @@ vsync and a 40 fps limit. These are starting points, not measurements. What help
2. The same with `fps_limit` 30, 45 and 60 and `render_scale` 50, 67 and game, so the defaults can be picked from
measurements. Steam's own performance overlay (the ... button) adds power draw and temperatures.
3. LCD or OLED, SteamOS version (`uname -r` in Desktop Mode's terminal), and the game update.
4. Anything that looks stretched, squeezed or cut off, with a screenshot: at 16:10 the interface keeps its 16:9 layout
in the middle of the taller screen, and full-screen backgrounds of some menus may not reach the top and bottom
edges yet.
4. Anything that looks stretched, squeezed or cut off, with a screenshot. At 16:10 the menus keep their 16:9
proportions in the middle of the taller screen, the HUD sits at the top and bottom edges, and full-screen
backgrounds reach them; pre-rendered cutscenes play stretched.
`device_profile = desktop` in `totk.ini` turns the profile off; `deck` turns it on elsewhere, to try the Deck's
settings on a PC.
+5 -2
View File
@@ -630,13 +630,16 @@ class Prepare(Step):
def key(self, ctx):
layout = ctx.layout
xlate_id = layout.xlate.with_suffix('.id')
tools = [layout.tools / n for n in ('prepare_shaders.py', 'shader_census.py', 'make_romfs_patches.py')]
tools = [layout.tools / n for n in ('prepare_shaders.py', 'shader_census.py', 'make_romfs_patches.py',
'aspect_layouts.py')]
return fingerprint('prepare-1', ctx.keys['compile'], layout.xlate, xlate_id, shader_list_text(layout), *tools)
def current(self, ctx, record):
dest = ctx.dest
xlate = dest / ctx.layout.xlate.name
return ((dest / 'shader-prepared.bin').is_file() and (dest / 'romfs-patches' / 'manifest.tsv').is_file()
patches = dest / 'romfs-patches' # the 16:9 overlay and the 16:10 and 21:9 ones (tools/aspect_layouts.py)
return ((dest / 'shader-prepared.bin').is_file() and (patches / 'manifest.tsv').is_file()
and all((patches / shape / 'manifest.tsv').is_file() for shape in ('16x10', '21x9'))
and xlate.is_file() and file_sha256(xlate) == record.get('xlate_sha256'))
def run(self, ctx):
+1
View File
@@ -248,6 +248,7 @@ int res_heapdef_build(const void *in, size_t n, void **out, size_t *out_n); //
// the grown heaps, malloc'd; 0 = cannot (logged)
void res_heapdef_served(void); // romfs.c serves the grown table
void res_init(void); // after rt_patches_init: the patch page and the sets
const char *res_shape(void); // "16x10" or "21x9" (its layout overlay), NULL: 16:9
void res_sizes(unsigned out[2], unsigned scene[2]); // the output and scene sizes in effect (the game's own
// until res_init switched the sets on)
// ---- code patches (patches.c) and the frame step (frame_rate.c)
+31 -11
View File
@@ -5,8 +5,9 @@
// MacNativeGames contributors) make the game read both sizes from the patch page, and the texture heap that holds the
// output- and scene-sized render targets grows with them.
//
// Settings, read at start: TOTK_OUTPUT_RES = <w>x<h> (default 1920x1080, the game's own; another shape than 16:9 gets
// a camera and interface canvas of that shape, aspect_init), TOTK_RENDER_SCALE = the
// Settings, read at start: TOTK_OUTPUT_RES = <w>x<h> (default 1920x1080, the game's own; a 16:10 or 21:9 one gets a
// camera, canvas and interface of that shape, aspect_init and res_shape; another shape draws the largest 16:9 size
// inside it, letterboxed), TOTK_RENDER_SCALE = the
// scene's size relative to the output: "game" (default, 5/6, the game's 1600x900 at 1080p) or a percentage; above 100
// the game supersamples its scene, which smooths edges (anti-aliasing) at the cost of GPU time. The game's own final
// pass (FSR 1 EASU) scales the scene to the output; the present scales the output to the window (vk_fsr.c).
@@ -44,12 +45,17 @@
#define SCENE_MAX 4096 // per side, as MacNativeGames' TOTK_RENDER_RES
#define ASPECT_EPS 0.002 // an output this close to 16:9 is 16:9 (1366x768 is 1.7786)
// The shapes besides 16:9 the game gets, each with its layout overlay (tools/aspect_layouts.py SHAPES,
// romfs-patches/<name>): 16:10 (1280x800, 1920x1200, 2560x1600) and 21:9, 2560x1080 (2.370) to 3840x1600 (2.400).
static const struct { const char *name; double lo, hi; } SHAPES[] = {{"16x10", 1.59, 1.61}, {"21x9", 2.30, 2.45}};
static struct {
int decided;
unsigned ow, oh, sw, sh; // output and scene
int scene_set; // the scene differs from the game's 5/6 of the output
int heapdef_ok; // romfs.c serves the grown HeapDef
int on; // res_init switched the patch sets on
int shape; // SHAPES index of the output, -1: 16:9
} R;
static void decide(void) {
@@ -66,15 +72,24 @@ static void decide(void) {
} else {
rt_log("resolution: TOTK_OUTPUT_RES=%s is not <width>x<height> in 1280x720..7680x4320; 1920x1080", o);
}
// A game version without the aspect set draws 16:9 only: the largest 16:9 size inside the wanted one, which the
// present letterboxes in a window of the wanted shape (TOTK_PICTURE_FIT)
// Another shape than 16:9, 16:10 and 21:9, or any but 16:9 in a game version without the aspect set, draws the
// largest 16:9 size inside the wanted one, which the present letterboxes in a window of the wanted shape
// (TOTK_PICTURE_FIT)
double a = (double)R.ow / R.oh, base = (double)BASE_W / BASE_H;
if (fabs(a - base) >= ASPECT_EPS && rt_patch_set("aspect") < 0) {
unsigned w = R.ow, h = R.oh;
if (a > base) R.ow = (unsigned)(R.oh * base + 0.5) & ~1u;
else R.oh = (unsigned)(R.ow / base + 0.5) & ~1u;
rt_log("resolution: this game version has no aspect patch set: %ux%u draws %ux%u (16:9), letterboxed", w, h, R.ow,
R.oh);
R.shape = -1;
if (fabs(a - base) >= ASPECT_EPS) {
for (int i = 0; i < (int)(sizeof SHAPES / sizeof *SHAPES); i++)
if (a >= SHAPES[i].lo && a <= SHAPES[i].hi) R.shape = i;
const char *why = R.shape < 0 ? "is not 16:9, 16:10 or 21:9"
: rt_patch_set("aspect") < 0 ? "needs the aspect patch set, which this game version lacks"
: NULL;
if (why) {
unsigned w = R.ow, h = R.oh;
if (a > base) R.ow = (unsigned)(R.oh * base + 0.5) & ~1u;
else R.oh = (unsigned)(R.ow / base + 0.5) & ~1u;
R.shape = -1;
rt_log("resolution: %ux%u %s: the game draws %ux%u (16:9), letterboxed", w, h, why, R.ow, R.oh);
}
}
const char *s = cfg_value("TOTK_RENDER_SCALE");
double k = 5.0 / 6.0;
@@ -95,6 +110,11 @@ static void decide(void) {
R.sh = (unsigned)(sh * fit + 0.5);
}
const char *res_shape(void) {
decide();
return R.shape < 0 ? NULL : SHAPES[R.shape].name;
}
static int bigger(void) {
decide();
return R.ow != BASE_W || R.oh != BASE_H || R.scene_set;
@@ -206,7 +226,7 @@ void res_heapdef_served(void) { R.heapdef_ok = 1; }
static void aspect_init(uint8_t *page) {
int set = rt_patch_set("aspect"); // decide() kept a version without it at 16:9
double a = (double)R.ow / R.oh, base = (double)BASE_W / BASE_H;
if (fabs(a - base) < ASPECT_EPS || set < 0) return;
if (R.shape < 0 || set < 0) return;
float v[3] = {(float)a, (float)(a > base ? a / base : 1.0), (float)(a < base ? base / a : 1.0)};
memcpy(page + 80, v, sizeof v);
rt_patch_switch(set, 1);
+14 -2
View File
@@ -358,9 +358,21 @@ static void heapdef_overlay(void) {
}
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)
// TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py),
// for a 16:10 or 21:9 game resolution its subdirectory of that shape, the same overlay with the interface's layout
// edits (tools/aspect_layouts.py)
char def[2100];
const char *patches = cfg_get("TOTK_ROMFS_PATCHES");
const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *shape = res_shape();
if (!patches && shape && snprintf(def, sizeof def, "%s/romfs-patches/%s/manifest.tsv", index_dir, shape) <
(int)sizeof def) {
if (plat_file_exists(def)) {
def[strlen(def) - strlen("/manifest.tsv")] = 0;
patches = def;
} else {
rt_log("RomFS overlay: no %s: the interface draws stretched at this game resolution (run "
"tools/make_romfs_patches.py)", def);
}
}
if (!patches && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def &&
plat_file_exists(def)) {
def[strlen(def) - strlen("/manifest.tsv")] = 0;
+13 -8
View File
@@ -412,17 +412,22 @@ static void row_window_size(void) {
// The game resolution (resolution.c): 16:9 sizes from the game's own 1920x1080 up, and the current value when it is
// another size.
static void row_output_res(void) {
// 16:9, 16:10 (the Steam Deck's 1280x800) and 21:9 sizes: the aspect patch gives the game the output's shape
static const char *const vals[] = {"1280x720", "1280x800", "1600x900", "1920x1080", "1920x1200",
"2560x1080", "2560x1440", "3440x1440", "3200x1800", "3840x2160"};
enum { N = sizeof vals / sizeof *vals };
// The three shapes the game draws in (runtime/resolution.c SHAPES): 16:9, 16:10 (the Steam Deck's 1280x800,
// handhelds' 1920x1200) and 21:9 (ultrawide monitors), each with the aspect patch and its interface overlay
static const struct { const char *size, *shape; } sizes[] = {
{"1280x720", "16:9"}, {"1600x900", "16:9"}, {"1920x1080", "16:9"}, {"2560x1440", "16:9"},
{"3200x1800", "16:9"}, {"3840x2160", "16:9"}, {"1280x800", "16:10"}, {"1680x1050", "16:10"},
{"1920x1200", "16:10"}, {"2560x1600", "16:10"}, {"2560x1080", "21:9"}, {"3440x1440", "21:9"},
{"3840x1600", "21:9"},
};
enum { N = sizeof sizes / sizeof *sizes };
char shown[N][32];
const char *names[N];
const char *vals[N], *names[N];
for (int i = 0; i < N; i++) {
int w = 0, h = 0;
sscanf(vals[i], "%dx%d", &w, &h);
snprintf(shown[i], sizeof shown[i], "%d × %d", w, h); // U+00D7, the multiplication sign
names[i] = shown[i];
sscanf(sizes[i].size, "%dx%d", &w, &h);
snprintf(shown[i], sizeof shown[i], "%d × %d (%s)", w, h, sizes[i].shape); // U+00D7, the multiplication sign
vals[i] = sizes[i].size, names[i] = shown[i];
}
opt_choice_list("TOTK_OUTPUT_RES", UI_MENU_OUTPUT_RES, vals, names, N, UI_MENU_OUTPUT_RES_DESC);
}
+6 -5
View File
@@ -51,9 +51,9 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_PERF_LINE_FPS] = "%.0f fps",
[UI_MENU_GRAPHICS] = "Picture",
[UI_MENU_OUTPUT_RES] = "Game resolution",
[UI_MENU_OUTPUT_RES_DESC] = "The size the game draws its picture and interface in. A 16:10 or 21:9 size gives the "
"camera and the interface that shape. Above 1920 x 1080 the game needs more video memory "
"and GPU time.",
[UI_MENU_OUTPUT_RES_DESC] = "The size the game draws its picture and interface in, in one of three shapes: 16:9, "
"16:10 (Steam Deck, handhelds) or 21:9 (ultrawide monitors), which the camera and the "
"interface take. Above 1920 x 1080 the game needs more video memory and GPU time.",
[UI_MENU_RENDER_SCALE] = "3D render scale",
[UI_MENU_RENDER_SCALE_DESC] = "Size of the 3D scene relative to the game resolution; the game's FSR scales it to "
"that size. Above 100 % smooths jagged edges (supersampling) at a high GPU cost.",
@@ -276,8 +276,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_PERF_LINE_FPS] = "%.0f к/с",
[UI_MENU_GRAPHICS] = "Изображение",
[UI_MENU_OUTPUT_RES] = "Разрешение игры",
[UI_MENU_OUTPUT_RES_DESC] = "Размер, в котором игра рисует картинку и интерфейс. Размер 16:10 или 21:9 даёт камере и "
"интерфейсу эту форму. Выше 1920 × 1080 игре нужно больше видеопамяти и времени GPU.",
[UI_MENU_OUTPUT_RES_DESC] = "Размер, в котором игра рисует картинку и интерфейс, в одной из трёх форм: 16:9, 16:10 "
"(Steam Deck, портативные ПК) или 21:9 (сверхширокие мониторы); камера и интерфейс "
"принимают эту форму. Выше 1920 × 1080 игре нужно больше видеопамяти и времени GPU.",
[UI_MENU_RENDER_SCALE] = "Масштаб 3D-отрисовки",
[UI_MENU_RENDER_SCALE_DESC] = "Размер 3D-сцены относительно разрешения игры; FSR игры доводит её до этого размера. "
"Выше 100 % сглаживает лесенки на краях (суперсэмплинг) ценой большой нагрузки на GPU.",
+281
View File
@@ -0,0 +1,281 @@
"""Layout edits that give TotK's interface the proportions of a 16:10 or 21:9 game resolution.
runtime/resolution.c aspect_init gives the 3D camera and the 2D canvas the output's shape, but the game still lays
its interface out in a 1920x1080 space and draws that space over the whole output: at 16:10 every layout is 11 %
taller than drawn, at 21:9 34 % wider. tools/make_romfs_patches.py runs apply() on the layout archive for each shape
and writes the result as romfs-patches/16x10 and romfs-patches/21x9; runtime/romfs.c serves the one of the output's
shape.
The edits follow the behaviour of Fruithapje21's TOTK-Ultrawide (GPL-3.0, romfs_script.py) for its 1.0.0 to 1.2.1
mods, written down as a specification and implemented from it; no code of it is used. With k the interface's shrink
on the output's stretched axis, (16/9) / aspect on a wider output and aspect / (16/9) on a narrower one:
- every layout's RootPane is scaled by k on that axis, so its panes keep their proportions; the full-screen layouts
(FULL_SCREEN) are left out;
- panes that must still cover the screen (backgrounds, blur, fades, the camera scope) are scaled by 1 / k on it, a
few that a full-screen layout holds by k;
- layouts and panes anchored to an edge move to it again: the HUD to the top and bottom edges at 16:10 and to the
left and right ones at 21:9, the minimap through the end point of its slide-in animation;
- at 21:9 the hit boxes of three button layouts and two screen captures of ChallengeLog_00 move off the screen.
Every edit is a value of k that equals the file's own value at k = 1 (16:9); apply() checks that before it writes,
so an archive of another layout stops the build instead of drawing a broken interface. Run with .venv-py314.
"""
import struct
ASPECT_16_9 = 16 / 9
# The aspect each overlay is made for: 16:10 is one shape (1280x800, 1920x1200, 2560x1600); the 21:9 monitors are
# 2.370 (2560x1080, 5120x2160) to 2.400 (3840x1600), and 3440x1440 (43:18) lies between, so no size is more than 1 %
# from it. The camera always takes the output's exact shape (runtime/resolution.c aspect_init).
SHAPES = {'16x10': 16 / 10, '21x9': 43 / 18}
# Layouts that cover the whole screen and keep their size
FULL_SCREEN = {'AppMenuBG_00', 'PauseMenuBG_00', 'ShopMenuParasailBG_00', 'ShortCutBG_00', 'TitleMenuBG_00',
'EventFade_00', 'EventFadeWipe_00', 'CameraShutter_00', 'PaAppPictureBookDetail_00',
'AppMenuOverlay_00'}
SYSTEM_MENUS = ('SystemLoadList_00', 'SystemOption_00', 'SystemSaveLoad_00')
HIDE = 10000.0 # a translate that puts a pane outside the screen
def s2(k):
return 1 - k # the part of the screen the scaled layout no longer covers
def s3(k):
return 1 / k - 1 # the same in the layout's own (scaled) units
def shrink(k):
return k
def grow(k):
return 1 / k
def edits(table):
"""[(layout, pane, field, value(k))] from rows of (layouts, panes, fields, value): each layout, pane and field."""
one = lambda x: (x,) if isinstance(x, str) else x
return [(lay, pane, field, value) for lays, panes, fields, value in table
for lay in one(lays) for pane in one(panes) for field in one(fields)]
# Fields: tx, ty (translate), sx, sy (scale) of a pane. value(1) is the file's own value; value None hides the pane.
WIDE = edits([
('AppAlbum_00', 'N_FadeInOut_00', 'sx', shrink),
('AppMenuOverlay_00', ('N_FadeInOut_00', 'N_FadeInOut_01', 'N_Icon_00', 'N_TitleOne_01'), 'sx', shrink),
('CameraPointer_00', 'N_Type_01', 'sx', shrink),
('CameraSystemWindow_00', ('N_AlbumCon_00', 'Pa_BtnL_00', 'Pa_BtnR_00', 'T_Text_00'), 'sx', shrink),
('LoadingFade_00', ('P_SideBGDeco_00', 'Pa_IconPlayer_00', 'Pa_LargeDungeonMap_00', 'Pa_LargeDungeonMap_01',
'Pa_Map_00', 'Pa_Map_01'), 'sx', shrink),
('PauseMenuOverlay_00', ('P_DecoL_00', 'P_DecoR_00'), 'sx', shrink),
('SystemActionGuide_00', ('A_Title_00', 'P_DecoL_01', 'P_DecoL_02'), 'sx', shrink),
(SYSTEM_MENUS, ('A_Title_00', 'P_DecoL_00', 'P_DecoR_00'), 'sx', shrink),
('AppAlbum_00', 'N_Open_01', 'sx', grow),
('AppMap_00', ('N_BlurInOut_00', 'N_BlurInOut_01', 'N_BlurInOut_02', 'N_BlurInOut_03'), 'sx', grow),
(('AppOpenDemoWindow_00', 'GameOver_00', 'LoadingFade_00', 'PaLargeDungeonMap_00', 'PaRecipeCardList_00'),
'P_BG_00', 'sx', grow),
('LoadingFade_00', 'N_Base_00', 'sx', grow),
(('AutoBuilder_00', 'OwnedHorseList_00', 'ShopMenu_00', 'StaffRoll_00'), 'N_BG_00', 'sx', grow),
('CameraPointer_00', 'N_InOutScope_00', ('sx', 'sy'), grow),
('CameraPointer_00', ('Pa_CameraFocus_00', 'S_Scissor_00', 'W_Shadow_01'), 'sx', grow),
('CameraSystemWindow_00', 'N_InOut_00', 'sx', grow),
('MessageLog_01', 'P_Capture_00', 'sx', grow),
('PauseMenuOverlay_00', ('P_FooterBase_00', 'S_DecoScissor_00'), 'sx', grow),
(('SystemActionGuide_00',) + SYSTEM_MENUS, ('N_Header_00', 'N_SystemBG_00'), 'sx', grow),
('AppMap_00', 'N_MiniMap_00', 'tx', lambda k: -270 * s2(k)),
('ChallengeLog_00', ('C_CaptureUp_00', 'C_CaptureUp_01'), 'tx', None),
('PaCommonBtnTitle_00', ('B_Hit_00', 'N_Cursor_00'), 'tx', None),
('PaMessageBtn_00', 'B_Hit_00', 'tx', None),
('LoadingFade_00', ('N_Logo_00', 'N_Status_00'), 'tx', lambda k: 960 * s3(k)),
('LoadingFade_00', 'N_Tips_00', 'tx', lambda k: -960 * s3(k)),
(('PauseMenuOverlay_00',) + SYSTEM_MENUS, 'P_DecoL_00', 'tx', lambda k: -(675 + 960 * s3(k)) * k),
(('PauseMenuOverlay_00',) + SYSTEM_MENUS, 'P_DecoR_00', 'tx', lambda k: (737 + 960 * s3(k)) * k),
('SaveLoadIcon_00', 'RootPane', 'tx', lambda k: -960 * s2(k)),
('SystemActionGuide_00', 'P_DecoL_01', 'tx', lambda k: -(675 + 960 * s3(k)) * k),
('SystemActionGuide_00', 'P_DecoL_02', 'tx', lambda k: (675 + 960 * s3(k)) * k),
# The HUD at the screen's left and right edges instead of the middle 16:9 (TOTK-Ultrawide's "corner")
(('EnvironmentInfo_00', 'EventSkip_00', 'InstantTipsAppMenu_00', 'InstantTipsWithPict_00', 'InstantTips_00',
'NumDisplaySecond_00', 'NumDisplay_00', 'PickUpWin_00'), 'RootPane', 'tx', lambda k: 960 * s2(k)),
('Location_00', 'N_Small_00', 'tx', lambda k: -(388 + 960 * s3(k))),
('PlayerStatus3D_00', 'N_ExtraStaminaTarget_01', 'tx', lambda k: -(745 + 960 * s3(k))),
('PlayerStatus_00', 'N_DevilDemoTargetC_00', 'tx', lambda k: -(284 + 960 * s3(k))),
('PlayerStatus_00', ('N_DevilDemoTargetLT_00', 'N_HeartGaugeTargetLT_00'), 'tx', lambda k: -(576 + 960 * s3(k))),
('PlayerStatus_00', 'N_HeartPos_00', 'tx', lambda k: -960 * s3(k)),
('PlayerStatus_00', 'Pa_CompanionLife_00', 'tx', lambda k: -(840 + 960 * s3(k))),
])
TALL = edits([
('AppAlbum_00', 'N_FadeInOut_00', 'sy', shrink),
('AppMenuOverlay_00', ('N_FadeInOut_00', 'N_FadeInOut_01', 'N_Icon_00', 'N_TitleOne_01'), 'sy', shrink),
('CameraPointer_00', 'N_Type_01', 'sy', shrink),
('CameraSystemWindow_00', 'N_FirstOut_00', 'sy', shrink),
('LoadingFade_00', ('Pa_IconPlayer_00', 'Pa_LargeDungeonMap_00', 'Pa_LargeDungeonMap_01', 'Pa_Map_00',
'Pa_Map_01'), 'sy', shrink),
('AppAlbum_00', 'N_Open_01', 'sy', grow),
('AppMap_00', ('N_BlurInOut_00', 'N_BlurInOut_01', 'N_BlurInOut_02', 'N_BlurInOut_03'), 'sy', grow),
(('AppOpenDemoWindow_00', 'GameOver_00', 'LoadingFade_00', 'PaLargeDungeonMap_00', 'PaRecipeCardList_00'),
'P_BG_00', 'sy', grow),
('LoadingFade_00', 'N_Base_00', 'sy', grow),
(('AutoBuilder_00', 'OwnedHorseList_00', 'ShopMenu_00', 'StaffRoll_00'), 'N_BG_00', 'sy', grow),
('CameraPointer_00', ('N_InOutScope_00', 'Pa_CameraFocus_00', 'S_Scissor_00', 'W_Shadow_01'), 'sy', grow),
('CameraSystemWindow_00', 'N_InOut_00', 'sy', grow),
('MessageLog_01', 'P_Capture_00', 'sy', grow),
(('SystemActionGuide_00',) + SYSTEM_MENUS, 'N_SystemBG_00', 'sy', grow),
# The HUD at the screen's top and bottom edges instead of the middle 16:9
(('AppAlbum_00', 'AppPictureBook_00', 'ChallengeLog_00', 'Challenge_00', 'InstantTipsWithPict_00', 'InstantTips_00',
'MiniGameTimer_00', 'NumDisplaySecond_00', 'NumDisplay_00', 'PickUpWin_00', 'PlayerStatus_00', 'Pouch_00',
'ShopMenu_00', 'SystemActionGuide_00') + SYSTEM_MENUS, 'RootPane', 'ty', lambda k: 540 * s2(k)),
(('CtrlGuide_00', 'DoCommand_00', 'EnvironmentInfo_00', 'HorseGauge_00', 'MessageDialog_00', 'MessageLog_01',
'PauseMenuOverlay_00', 'SaveLoadIcon_00', 'TreasureFullShortCut_00'), 'RootPane', 'ty', lambda k: -540 * s2(k)),
('AppAlbum_00', 'N_PicLoad_01', 'ty', lambda k: -540 * s2(k)),
('AppMap_00', 'N_AllMapTime_00', 'ty', lambda k: -540 * s3(k)),
('AppMenuOverlay_00', ('A_Align_00', 'Pa_GuideLeft_00'), 'ty', lambda k: -(505 + 540 * s3(k))),
('AppMenuOverlay_00', 'N_TitleTab_00', 'ty', lambda k: 491 + 540 * s3(k)),
('LoadingFade_00', 'N_Logo_00', 'ty', lambda k: -540 * s3(k)),
('LoadingFade_00', 'N_Sage_00', 'ty', lambda k: -477 - 2 * 540 * s3(k)),
('LoadingFade_00', 'N_Status_00', 'ty', lambda k: 540 * s3(k)),
('LoadingFade_00', 'N_Tips_00', 'ty', lambda k: -(360 + 540 * s3(k))),
('Location_00', 'N_Large_00', 'ty', lambda k: 270 + 540 * s3(k)),
('Location_00', 'N_Small_00', 'ty', lambda k: -(395 + 540 * s3(k))),
('MessageLog_01', 'P_Capture_00', 'ty', lambda k: 540 * s3(k)),
('PaExtraStaminaGauge_00', ('N_BasePattern_00', 'N_GaugeMainPattern_00'), 'ty', lambda k: 540 * s3(k)),
('Pouch_00', ('N_Info_00', 'Pa_ExtraStamina_00'), 'ty', lambda k: -540 * s3(k)),
('ShopMenu_00', 'A_AlignGuide_00', 'ty', lambda k: -(477 + 540 * s3(k))),
(('SystemActionGuide_00',) + SYSTEM_MENUS, 'N_SystemBG_00', 'ty', lambda k: -540 * s3(k)),
('SystemLoadList_00', 'Pa_Guide_00', 'ty', lambda k: -(474 + 540 * s3(k))),
('SystemOption_00', 'A_Guide_00', 'ty', lambda k: -(474 + 540 * s3(k))),
])
FIELDS = {'tx': 44, 'ty': 48, 'sx': 68, 'sy': 72} # offsets in a pane section (after magic, size, flags and name)
PANES = {b'pan1', b'pic1', b'txt1', b'wnd1', b'bnd1', b'prt1', b'ali1', b'scr1', b'cpt1'}
FLPA_X, FLPA_Y = 0, 1 # FLPA (pane SRT) targets: translate x, y
FLTS_SX, FLTS_SY = 3, 4 # FLTS (texture SRT) targets: scale x, y
class LayoutError(Exception):
pass
def close(a, b):
return abs(a - b) <= 1e-3 * max(1.0, abs(b))
def panes_of(data, lo):
"""Pane name -> offset of its first pane section in the BFLYT at data[lo:]."""
if data[lo:lo + 4] != b'FLYT':
raise LayoutError(f'{lo:#x}: not a BFLYT')
pos, out = lo + struct.unpack_from('<H', data, lo + 6)[0], {}
for _ in range(struct.unpack_from('<H', data, lo + 16)[0]):
magic, size = bytes(data[pos:pos + 4]), struct.unpack_from('<I', data, pos + 4)[0]
if magic in PANES:
out.setdefault(data[pos + 12:pos + 36].split(b'\0')[0].decode(), pos)
pos += size
return out
def curves_of(data, lo, pane, tag):
"""[(target, [absolute key offsets])] of the hermite curves of one pane and animation tag in the BFLAN at data[lo:]."""
if data[lo:lo + 4] != b'FLAN':
raise LayoutError(f'{lo:#x}: not a BFLAN')
pos, out = lo + struct.unpack_from('<H', data, lo + 6)[0], []
for _ in range(struct.unpack_from('<H', data, lo + 0x10)[0]):
magic, size = data[pos:pos + 4], struct.unpack_from('<I', data, pos + 4)[0]
if magic == b'pai1':
table = pos + struct.unpack_from('<I', data, pos + 16)[0]
for e in range(struct.unpack_from('<H', data, pos + 14)[0]):
eo = pos + struct.unpack_from('<I', data, table + 4 * e)[0]
if data[eo:eo + 28].split(b'\0')[0].decode() != pane:
continue
for t in range(data[eo + 28]):
to = eo + struct.unpack_from('<I', data, eo + 32 + 4 * t)[0]
if data[to:to + 4] != tag:
continue
for g in range(data[to + 4]):
go = to + struct.unpack_from('<I', data, to + 8 + 4 * g)[0]
if data[go + 2] != 2:
raise LayoutError(f'{pane}: a {tag.decode()} curve that is not hermite')
keys = go + struct.unpack_from('<I', data, go + 8)[0]
out.append((data[go + 1], [keys + 12 * i for i in range(struct.unpack_from('<H', data, go + 4)[0])]))
pos += size
return out
def get(data, at):
return struct.unpack_from('<f', data, at)[0]
def put(data, at, value):
struct.pack_into('<f', data, at, value)
def apply(blarc, members, shape):
"""Edits the decompressed layout archive blarc (a bytearray; members: name -> (start, end), tools/
make_romfs_patches.py sarc_members) for SHAPES[shape]. Returns the number of edited values; LayoutError when a
layout, pane or value differs from what the edits expect."""
aspect = SHAPES[shape]
wide = aspect > ASPECT_16_9
k = ASPECT_16_9 / aspect if wide else aspect / ASPECT_16_9
axis = 'sx' if wide else 'sy'
layouts = {n[5:-6]: lo for n, (lo, hi) in members.items() if n.startswith('blyt/') and n.endswith('.bflyt')}
table = [(lay, 'RootPane', axis, shrink) for lay in sorted(layouts) if lay not in FULL_SCREEN]
table += WIDE if wide else TALL
count, cache = 0, {}
for lay, pane, field, value in table:
if lay not in layouts:
raise LayoutError(f'no layout {lay}')
panes = cache.setdefault(lay, panes_of(blarc, layouts[lay]))
if pane not in panes:
raise LayoutError(f'{lay}: no pane {pane}')
at = panes[pane] + FIELDS[field]
if value is None:
put(blarc, at, HIDE)
else:
if not close(get(blarc, at), value(1.0)):
raise LayoutError(f'{lay} {pane} {field} is {get(blarc, at):g}, the edit expects {value(1.0):g}')
put(blarc, at, value(k))
count += 1
def anim(name):
if f'anim/{name}.bflan' not in members:
raise LayoutError(f'no animation {name}')
return members[f'anim/{name}.bflan'][0]
# The minimap's four cut panes slide in on straight lines from 0 at frame 0 to (765, -360) at frame 1 (hermite
# keys: the first one's slope is the end point); the end point moves with the screen's edge.
target, end = (FLPA_X, lambda k: 765 + 960 * s3(k)) if wide else (FLPA_Y, lambda k: -(360 + 540 * s3(k)))
lo = anim('AppMap_00_MiniMap')
for pane in ('N_Cut_00', 'N_Cut_01', 'N_Cut_02', 'N_Cut_03'):
curves = [keys for t, keys in curves_of(blarc, lo, pane, b'FLPA') if t == target]
if len(curves) != 1 or len(curves[0]) != 2:
raise LayoutError(f'AppMap_00_MiniMap {pane}: {len(curves)} curves of the target')
k0, k1 = curves[0]
if not (get(blarc, k0) == 0 and get(blarc, k0 + 4) == 0 and close(get(blarc, k0 + 8), end(1.0)) and
get(blarc, k1) == 1 and close(get(blarc, k1 + 4), end(1.0)) and get(blarc, k1 + 8) == 0):
raise LayoutError(f'AppMap_00_MiniMap {pane}: not a line from 0 to {end(1.0):g}')
put(blarc, k0 + 8, end(k)), put(blarc, k1 + 4, end(k))
count += 2
if not wide:
# The large place name of a discovery holds its height (285, then 260) in flat keys; they move to the top edge.
curves = [keys for t, keys in curves_of(blarc, anim('Location_00_IsDiscovery'), 'N_Large_00', b'FLPA')
if t == FLPA_Y]
values = [get(blarc, key + 4) for keys in curves for key in keys]
if len(curves) != 1 or values != [285, 285, 260]:
raise LayoutError(f'Location_00_IsDiscovery N_Large_00: keys {values}')
for key in curves[0]:
put(blarc, key + 4, get(blarc, key + 4) + 540 * s3(k))
count += 1
# The dragon's tears map icon zooms its picture to 1.08 and 1.28 in flat keys; on the stretched axis by 1 / k more.
curves = [keys for t, keys in curves_of(blarc, anim('PaMapIconDragonTears_00_Zoom'), 'P_Geoglyph_00', b'FLTS')
if t == (FLTS_SX if wide else FLTS_SY)]
values = [round(get(blarc, key + 4), 4) for keys in curves for key in keys]
if len(curves) != 1 or values != [1.08, 1.28]:
raise LayoutError(f'PaMapIconDragonTears_00_Zoom P_Geoglyph_00: keys {values}')
for key in curves[0]:
put(blarc, key + 4, get(blarc, key + 4) / k)
count += 1
return count
+4 -2
View File
@@ -223,12 +223,14 @@ def write_if_changed(path, text):
def copy_romfs_patches(version, out):
"""totk.exe loads romfs-patches beside romfs-index.bin (runtime/romfs.c overlay_init). tools/make_romfs_patches.py
writes them into build/<version> only, so a build in another directory ran without the 60 fps overlay (the quick
menus' captured background turned black). Copies them when their manifest differs."""
menus' captured background turned black). Copies them when a manifest differs, the 16:10 and 21:9 ones in their
subdirectories included."""
src = ROOT / 'build' / version / 'romfs-patches'
dst = out / 'romfs-patches'
if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file():
return
if (dst / 'manifest.tsv').is_file() and (dst / 'manifest.tsv').read_bytes() == (src / 'manifest.tsv').read_bytes():
manifests = lambda d: {p.relative_to(d): p.read_bytes() for p in sorted(d.rglob('manifest.tsv'))}
if dst.is_dir() and manifests(dst) == manifests(src):
return
shutil.rmtree(dst, ignore_errors=True)
shutil.copytree(src, dst)
+2 -2
View File
@@ -100,8 +100,8 @@ LLVM_SKIP_DIRS = {'aarch64-w64-mingw32', 'armv7-w64-mingw32', 'i686-w64-mingw32'
LLVM_SKIP_SUFFIXES = {'.idl', '.tlb'}
# tools/ files the installer steps run (and what they import), copied from the repo.
TOOLS_FILES = ['build_game.py', 'build_shaders.py', 'check_content.py', 'extract.py', 'make_romfs_patches.py',
'prepare_shaders.py', 'romfs_index.py', 'shader_census.py', 'shader_list.py']
TOOLS_FILES = ['aspect_layouts.py', 'build_game.py', 'build_shaders.py', 'check_content.py', 'extract.py',
'make_romfs_patches.py', 'prepare_shaders.py', 'romfs_index.py', 'shader_census.py', 'shader_list.py']
TOOLS_DIRS = ['vendor/macnativegames', 'data'] # data/: expected hashes
RUNTIME_SUFFIXES = {'.h', '.inc', '.ico'} # .ico: the installer window icon
+29 -11
View File
@@ -1,6 +1,6 @@
# Adapted from MacNativeGames games/totk/scripts/make_romfs_patches.py @ ebe621d (MIT, Copyright (c) 2026
# MacNativeGames contributors).
"""Build the 60 fps RomFS overlay for TotK 1.2.1 or 1.4.3 (runtime/romfs.c, TOTK_ROMFS_PATCHES).
"""Build the RomFS overlays for TotK 1.2.1 or 1.4.3: 60 fps, and 16:10 and 21:9 (runtime/romfs.c, TOTK_ROMFS_PATCHES).
UI/LayoutArchive/Common.Product.<110 or 140>.Nin_NX_NVN.blarc.zs: the weapon / shield / material quick menus capture the game
picture for their background when the panes C_CaptureBG_00, C_CaptureClearBG_00 and P_CaptureClearBG_00 become
@@ -11,6 +11,9 @@ captured at once (upstream checked weapon, shield, material and ability wheel at
The game-over flow fix of the same upstream script is 1.0.0 only (1.2.1 and 1.4.3 run DmF_SY_GameOver.110) and is
left out.
The same archive with the layout edits of tools/aspect_layouts.py on top goes to <out>/16x10 and <out>/21x9, each an
overlay directory of its own: runtime/romfs.c serves the one of the game resolution's shape instead of <out>.
Input: build/extracted/<version>/romfs (romfs.bin and index.json, verified by tools/extract.py). Output:
build/<version>/romfs-patches/<path> by default, and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
"""
@@ -21,6 +24,8 @@ import json
import struct
from pathlib import Path
import aspect_layouts
root = Path(__file__).resolve().parents[1]
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--version', choices=('v121', 'v143'), default='v121')
@@ -117,13 +122,26 @@ for member, panes in MEMBERS.items():
patched[member] = changed
diff = [i for i in range(len(original)) if original[i] != blarc[i]]
assert diff and all(any(lo <= i < hi for lo, hi in (members[m] for m in MEMBERS)) for i in diff), diff
data = zstd.compress(bytes(blarc), level=19, zstd_dict=dictionary)
assert zstd.decompress(data, zstd_dict=dictionary) == bytes(blarc)
assert zstd.get_frame_info(data).dictionary_id == info.dictionary_id
target = args.out / ARCHIVE
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
line = '\t'.join([ARCHIVE, str(len(data)), hashlib.sha256(data).hexdigest(), hashlib.sha256(raw).hexdigest()])
(args.out / 'manifest.tsv').write_text('# path\tsize\tsha256\toriginal_sha256 (tools/make_romfs_patches.py)\n'
+ line + '\n')
print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, size=len(data), changed_bytes=len(diff))))
def write_overlay(out, archive):
"""The archive, compressed with the original's dictionary, as the one file of the overlay directory out."""
data = zstd.compress(bytes(archive), level=19, zstd_dict=dictionary)
assert zstd.decompress(data, zstd_dict=dictionary) == bytes(archive)
assert zstd.get_frame_info(data).dictionary_id == info.dictionary_id
target = out / ARCHIVE
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
line = '\t'.join([ARCHIVE, str(len(data)), hashlib.sha256(data).hexdigest(), hashlib.sha256(raw).hexdigest()])
(out / 'manifest.tsv').write_text('# path\tsize\tsha256\toriginal_sha256 (tools/make_romfs_patches.py)\n'
+ line + '\n')
return len(data)
size = write_overlay(args.out, blarc)
shapes = {}
for shape in aspect_layouts.SHAPES:
shaped = bytearray(blarc)
edited = aspect_layouts.apply(shaped, members, shape)
shapes[shape] = dict(values=edited, size=write_overlay(args.out / shape, shaped))
print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, size=size, changed_bytes=len(diff), shapes=shapes)))
+4 -3
View File
@@ -110,9 +110,10 @@
# Which GPU to use: its index in the log, or part of its name. Default: the first discrete GPU with Vulkan 1.3.
# gpu_index = 0
# gpu_name = NVIDIA
# Game resolution: the size the game draws its picture and interface in (1280x720 to 7680x4320). Another shape than
# 16:9 (1280x800, 2560x1080) gives the camera and the interface that shape. Above 1920x1080 the game's texture heap and
# memory pool grow with it. Read at start.
# Game resolution: the size the game draws its picture and interface in (1280x720 to 7680x4320). 16:10 (1280x800,
# 1920x1200, 2560x1600) and 21:9 (2560x1080, 3440x1440, 3840x1600) sizes give the camera and the interface that shape;
# another shape draws the largest 16:9 size inside it, with bars. Above 1920x1080 the game's texture heap and memory
# pool grow with it. Read at start.
# output_res = 1920x1080
# 3D render scale: the scene's size relative to the game resolution, game (5/6, the game's own 1600x900 at 1080p) or
# a percentage (25 to 400, at most 4096 pixels a side); above 100 supersamples the scene (anti-aliasing). Read at start.