diff --git a/docs/cheats.md b/docs/cheats.md index f1646fec..fbb012f1 100644 --- a/docs/cheats.md +++ b/docs/cheats.md @@ -14,7 +14,7 @@ The port reads Atmosphère cheat files, the format Switch homebrew and the emula The Cheats tab names the file the installed game reads when no mod holds one, and `logs\totk.log` says `cheats: no enabled mod holds cheats/.txt`. 2. Put it in the `cheats` folder of a mod: `mods\My cheats\cheats\277178B7DBA1B6D4.txt`. A download laid out for the Switch's SD card or an emulator works as it is: unpack it into a folder of its own under `mods`, and the port finds `atmosphere\contents\0100F2C0115B6000\cheats`, `contents\0100F2C0115B6000\cheats` or `0100F2C0115B6000\cheats` inside it. The file name's case does not matter. 3. Start the game. Cheats that write the game's memory work now. -4. Cheats that change the game's code are greyed out with "run the setup again" until you run `TotK-Setup.exe` again on the same folder. It builds the code cheats of every mod into the game; saves and settings are kept. +4. Cheats that change the game's code need the game rebuilt with them. When the game starts and finds such cheats it did not build, it opens the setup's rebuild window, which builds them in (a few minutes; the shaders stay prepared) and starts the game again. Until then they are greyed out with "after the rebuild". When the rebuild fails or you cancel it, the game starts without them and does not try again for the same cheats; "Rebuild the game now" on the Cheats tab tries again. `mods_rebuild = off` under `[mods]` in `totk.ini` turns the automatic rebuild off; running `TotK-Setup.exe` on the same folder does the same job by hand. Saves and settings are kept. 5. Switch the cheats on the Cheats tab of the menu. The Cheats tab lists the cheats grouped by mod, in the order of the Mods tab. A mod switched off on the Mods tab, or one the port cannot use, contributes no cheats; the change applies at the next start. The Mods tab says how many cheats each mod brought. @@ -53,7 +53,7 @@ The game's code is compiled ahead of time, so a cheat cannot write new instructi | master | `{name}` with code writes | A patch set that is always on. | | restore | Writes back only the game's original instructions | Not needed: switching a cheat off restores them. Greyed out. | -A cheat whose code writes call or jump into a code cave the cheat writes itself (into main's zero padding) gets the cave inlined at the call site. The setup builds the code cheats of every mod in the `mods` folder, switched on or off, so switching a mod on later needs only a restart. A code cheat added or edited after the setup ran is greyed out until the setup runs again; a data cheat runs at the next start. +A cheat whose code writes call or jump into a code cave the cheat writes itself (into main's zero padding) gets the cave inlined at the call site. The setup builds the code cheats of every mod in the `mods` folder, switched on or off, so switching a mod on later needs only a restart. A code cheat added or edited after the last build waits for the rebuild; a data cheat runs at the next start. Not supported, and shown greyed out with the reason: diff --git a/docs/installer.md b/docs/installer.md index 1c681cac..f25b27d7 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -53,12 +53,14 @@ loads the saves 1.4.3 wrote. and BFTTF header). Without a firmware folder the setup warns and goes on; the game then lacks those glyphs. 3. **Extract** ExeFS and RomFS into the install folder and verify the hashes. 4. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into a temp folder next - to the installer. + to the installer. The code cheats of the mods' cheat files become patch sets first (`tools/cheats.py`, status in + `build-cache/cheats.status`); a cheat file the tool refuses costs the cheats, not the install. 5. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS hashes and the game version's patch page) and link them with the prebuilt runtime library for the host's level (`libtotkrt.a` or `libtotkrt-v2.a`) into `totk.exe` (`build_game.py --runtime-lib`; about 3 min on 24 cores). -6. **Prepare** the RomFS patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`, +6. **Prepare** (only when the runtime, the translator or the game version changed, not for a new lift) the RomFS + patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`, `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. @@ -68,10 +70,25 @@ loads the saves 1.4.3 wrote. 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. **Clean up** the temp folder (generated C and objects, about 1.3 GB). +7. **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`). +## Rebuilding for the mods + +The generated C and the objects stay in the temp folder, so the next lift rewrites only the chunks whose C changed and +Ninja recompiles only those: a new or edited code cheat costs the lift (under a minute on 24 cores, a few minutes on 4) +and a few dozen chunks, not a full compile, and the shaders stay prepared. + +`build-cache/rebuild.txt` holds the command that opens the setup window in its rebuild mode on the install folder +(`python -m installer.gui --rebuild `), one argument per line. When an enabled mod has code cheats the +build lacks, `totk.exe` runs it at start and exits (`runtime/cheats.c` `rebuild_if_needed`); the window runs the setup +on the folder at once and starts the game again when it succeeds. A failed or cancelled rebuild offers to start the +game with the code it has; `build-cache/rebuild.skip` then keeps the same cheats from starting it again, until "Rebuild +the game now" on the Cheats tab. `[mods] mods_rebuild = off` turns it off. The rebuild needs the release folder the +setup ran from: a moved or deleted release folder means running a setup again. + ## Command line `installer/` (stdlib only; `installer/layout.py` maps the release folder and, in a repository, the dev toolchain): diff --git a/docs/tester-guide.md b/docs/tester-guide.md index a0289283..c36fe03a 100644 --- a/docs/tester-guide.md +++ b/docs/tester-guide.md @@ -74,8 +74,8 @@ it up or down. When two mods change the same file, the higher one wins. included. - Cheats: an Atmosphère cheat file goes into a mod's `cheats` folder (`mods//cheats/.txt`, the build id `277178B7DBA1B6D4` for 1.4.3, `9B4E43650501A4D4` for 1.2.1). The Cheats tab of the menu switches them. - Cheats that write memory work at the next start; cheats that change the game's code need the setup run again on - the install folder. The port ships no cheat files. Details: [cheats.md](cheats.md). + Cheats that write memory work at the next start; for cheats that change the game's code the game opens the setup's + rebuild window at start and comes back after it (a few minutes). The port ships no cheat files. Details: [cheats.md](cheats.md). The log names every mod at the start (`mods: : ...`) and how many of its files it serves. diff --git a/installer/gui.py b/installer/gui.py index 543064c5..f93e4635 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -7,6 +7,8 @@ installer/text/.json under "ui.*" and "launcher.*" ids. --selftest [--shots DIR] build every screen in every language and close by itself (PNG per screen with --shots) --lang en|ru|pt-BR|zh-Hans window language (default: the Windows display language) + --rebuild DIR rebuild the install folder DIR for its mods (totk.exe starts this, build-cache/rebuild.txt): + the run starts at once with that folder, and the game starts again when it succeeds """ import argparse import json @@ -43,8 +45,9 @@ def fix_tcl_paths(): class App: - def __init__(self, root, ui_lang, layout, run_args=None): + def __init__(self, root, ui_lang, layout, run_args=None, rebuild=None): self.root, self.layout = root, layout + self.rebuild = rebuild # the install folder of --rebuild, or None self.cat = Catalog(ui_lang) self.model = Model() self.process = None @@ -94,6 +97,10 @@ class App: self.vars['lang'].set(self.lang_label(self.lang_code)) self.vars['dest'].trace_add('write', lambda *_: self.refresh_form()) self.show('form') + if rebuild: + self.bind_text(self.title, 'text', 'ui.rebuild_title') + self.vars['dest'].set(str(rebuild)) + root.after(POLL_MS, self.start) # ---- text ----------------------------------------------------------------------------------------------------- @@ -258,6 +265,8 @@ class App: self.open_button.pack(side='right', padx=(0, 8)) self.back_button = self.button(bar, 'ui.back', lambda: self.show('form')) self.back_button.pack(side='left') + if self.rebuild: # a failed or cancelled rebuild: the game starts with the code it has + self.button(bar, 'ui.start_game', self.start_game).pack(side='right', padx=(0, 8)) self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=620, justify='left') self.finish_title.pack(anchor='w') self.finish_text = ttk.Label(f, wraplength=620, justify='left') @@ -363,6 +372,9 @@ class App: return self.model.finish(code) self.process = None + if self.rebuild and self.model.result == 'ok' and not self.closing: + self.start_game() + return self.refresh_run() self.refresh_finish() self.show('finish') @@ -493,6 +505,15 @@ class App: else: self.open_button.state(['disabled' if not Path(m.dest or '.').is_dir() else '!disabled']) + def start_game(self): + """Starts the game of the install folder and closes the window.""" + dest = Path(self.vars['dest'].get().strip()) + exe = dest / ('totk.exe' if os.name == 'nt' else 'totk') + flags = subprocess.DETACHED_PROCESS if os.name == 'nt' else 0 + if exe.is_file(): + subprocess.Popen([str(exe)], cwd=str(dest), creationflags=flags, close_fds=True) + self.root.destroy() + def open_folder(self): dest = self.model.dest if dest and Path(dest).is_dir(): @@ -625,13 +646,14 @@ def main(argv=None): ap.add_argument('--shots', type=Path) ap.add_argument('--lang', choices=UI_LANGUAGES) ap.add_argument('--root', type=Path) + ap.add_argument('--rebuild', type=Path) args = ap.parse_args(argv) layout = layouts.find(args.root) if args.selftest: return selftest(layout, args.shots) fix_tcl_paths() root = tk.Tk() - App(root, args.lang or windows_ui_language(), layout) + App(root, args.lang or windows_ui_language(), layout, rebuild=args.rebuild) root.mainloop() return 0 diff --git a/installer/steps.py b/installer/steps.py index fa6a67e0..6d96a600 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -10,7 +10,13 @@ Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ and its DLLs, romfs-index.bin, romfs-patches/, romfs-patches-xbox/, romfs-patches-xbox-label/, totk_xlate.exe, the shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json. Temp folder (/-): check/ (ExeFS of both inputs, the host check), gen/ (C), build/ (objects), -logs/ (kept by the cleanup). +logs/. The cleanup keeps gen/, build/ and logs/: the next run lifts into the same gen/, where recomp/gen.py rewrites +only the chunks whose C changed, and Ninja in build/ recompiles only those. A change of the mods' code cheats then +costs the lift (about a minute) and the chunks it touches, not a full compile. + +Install folder build-cache/: cheats.status (tools/cheats.py) and rebuild.txt, the command that starts this setup in +its rebuild mode on the install folder (installer/gui.py --rebuild), one argument per line; totk.exe runs it at start +when an enabled mod has code cheats the build lacks (runtime/cheats.c). """ import hashlib import json @@ -747,8 +753,10 @@ class Lift(Step): return (gen / 'layout.json').is_file() and stamp.is_file() and stamp.read_text().strip() == ctx.keys['lift'] def run(self, ctx): + # gen/ of the last run stays: gen.py rewrites only the chunks whose C changed (and removes the ones a smaller + # partition no longer has), so Ninja recompiles only those layout, rep, gen = ctx.layout, ctx.reporter, ctx.temp / 'gen' - remove(gen) + (gen / STAMP).unlink(missing_ok=True) rep.progress('lift', 'discover', force=True) def parse(line): @@ -775,7 +783,6 @@ class Lift(Step): if code and patches != plain: skipped = log status.unlink(missing_ok=True) - remove(gen) code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', plain], parse) if code: raise InstallError('lift.failed', code=code, log=str(log)) @@ -790,16 +797,21 @@ class Lift(Step): NINJA_LINE = re.compile(r'^\[(\d+)/(\d+)\] ') +def runtime_key(ctx): + """Fingerprint of what totk.exe is built from besides the lifted code: the runtime, the toolchain and the build + tools. Shader preparation depends on these, not on the code cheats a lift adds.""" + layout, cpu = ctx.layout, getattr(ctx, 'cpu', 'v3') + clang = subprocess.run([str(layout.clang), '--version'], capture_output=True, text=True).stdout + tools = [layout.tools / n for n in ('build_game.py', 'romfs_index.py', 'check_content.py')] + return fingerprint('runtime-1', cpu, layout.runtime_lib_for(cpu), layout.runtime, layout.deps or 'system', + layout.sysroot or 'host', *tools, clang, *[d.name for d in layout.dlls]) + + class Compile(Step): id = 'compile' def key(self, ctx): - layout, cpu = ctx.layout, getattr(ctx, 'cpu', 'v3') - clang = subprocess.run([str(layout.clang), '--version'], capture_output=True, text=True).stdout - tools = [layout.tools / n for n in ('build_game.py', 'romfs_index.py', 'check_content.py')] - return fingerprint('compile-2', cpu, layout.runtime_lib_for(cpu), ctx.keys['lift'], layout.runtime, - layout.deps or 'system', layout.sysroot or 'host', *tools, clang, - *[d.name for d in layout.dlls]) + return fingerprint('compile-3', ctx.keys['lift'], runtime_key(ctx)) def current(self, ctx, record): exe = ctx.dest / ('totk' + EXE) @@ -867,7 +879,9 @@ class Prepare(Step): xlate_id = layout.xlate.with_suffix('.id') tools = [layout.tools / n for n in ('prepare_shaders.py', 'shader_census.py', 'make_romfs_patches.py', 'pack_shader_cache.py', 'ultrawide_layout.py', 'button_icons.py')] - return fingerprint('prepare-1', ctx.keys['compile'], layout.xlate, xlate_id, shader_list_text(layout), *tools) + # not the compile key: a rebuild for the mods' code cheats keeps the prepared shaders + return fingerprint('prepare-2', ctx.keys['extract'], runtime_key(ctx), layout.xlate, xlate_id, + shader_list_text(layout), *tools) def current(self, ctx, record): dest = ctx.dest @@ -977,12 +991,32 @@ class Cleanup(Step): rep.progress('cleanup', 'temp', force=True) for stale in dest.glob('update-merge-*'): remove(stale) - for name in ('gen', 'build', 'check', 'shader_list.tsv', 'shared-fonts'): + for name in ('check', 'shader_list.tsv', 'shared-fonts'): # gen/ and build/ stay for the next rebuild remove(ctx.temp / name) romfs_problem(dest / 'romfs', expected_update(ctx)) + write_rebuild_command(ctx) return {} +def rebuild_command(ctx): + """The command that starts the setup window in its rebuild mode on this install folder (installer/gui.py + --rebuild): pythonw beside the setup's Python on Windows, so no console opens.""" + layout = ctx.layout + python = layout.python + if os.name == 'nt' and python.with_name('pythonw.exe').is_file(): + python = python.with_name('pythonw.exe') + return [str(python), '-m', 'installer.gui', '--root', str(layout.root), '--rebuild', str(ctx.dest)] + + +def write_rebuild_command(ctx): + """build-cache/rebuild.txt in the install folder: rebuild_command, one argument per line, for totk.exe.""" + cache = ctx.dest / 'build-cache' + cache.mkdir(exist_ok=True) + tmp = cache / 'rebuild.txt.tmp' + tmp.write_text('\n'.join(rebuild_command(ctx)) + '\n', encoding='utf-8', newline='\n') + os.replace(tmp, cache / 'rebuild.txt') + + def romfs_problem(romfs, expected): """Raise cleanup.romfs_unreadable unless romfs/ still holds the verified image. The game opens romfs.bin at start; an install whose romfs/ went empty and unreadable after the extraction verified it (a folder Windows was still diff --git a/installer/text/en.json b/installer/text/en.json index f83a62d4..5c4c7079 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -100,6 +100,8 @@ "warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.", "ui.title": "TotK Setup", + "ui.rebuild_title": "Rebuilding the game for your mods", + "ui.start_game": "Start the game", "ui.version": "version {version}", "ui.intro": "Builds a playable Tears of the Kingdom folder from your own game files. This takes a while and runs once.", "ui.notice": "The folder this setup builds contains the game. It is for your own use only; do not share or upload it.", diff --git a/installer/text/pt-BR.json b/installer/text/pt-BR.json index 08eb8d06..5699f35b 100644 --- a/installer/text/pt-BR.json +++ b/installer/text/pt-BR.json @@ -100,6 +100,8 @@ "warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.", "ui.title": "Instalação do TotK", + "ui.rebuild_title": "Recompilando o jogo para os seus mods", + "ui.start_game": "Iniciar o jogo", "ui.version": "versão {version}", "ui.intro": "Monta uma pasta jogável de Tears of the Kingdom a partir dos seus próprios arquivos do jogo. Isso demora um pouco e só precisa ser feito uma vez.", "ui.notice": "A pasta que esta instalação monta contém o jogo. Ela é só para seu uso pessoal; não compartilhe nem envie para a internet.", diff --git a/installer/text/ru.json b/installer/text/ru.json index cf8d4c33..4c871a75 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -100,6 +100,8 @@ "warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.", "ui.title": "Установка TotK", + "ui.rebuild_title": "Пересборка игры под ваши моды", + "ui.start_game": "Запустить игру", "ui.version": "версия {version}", "ui.intro": "Собирает готовую к запуску папку с Tears of the Kingdom из ваших игровых файлов. Занимает много времени и выполняется один раз.", "ui.notice": "Папка, которую создаёт установка, содержит игру. Она предназначена только для личного использования: не передавайте и не выкладывайте её.", diff --git a/installer/text/zh-Hans.json b/installer/text/zh-Hans.json index 7a80f25b..df75fd0e 100644 --- a/installer/text/zh-Hans.json +++ b/installer/text/zh-Hans.json @@ -100,6 +100,8 @@ "warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。", "ui.title": "TotK 安装程序", + "ui.rebuild_title": "正在为你的模组重新构建游戏", + "ui.start_game": "启动游戏", "ui.version": "版本 {version}", "ui.intro": "用你自己的游戏文件构建一个可以游玩的《王国之泪》文件夹。耗时较长,只需运行一次。", "ui.notice": "此安装程序构建的文件夹包含游戏本身,仅供你个人使用;请勿分享或上传。", diff --git a/runtime/cfg.c b/runtime/cfg.c index d40c2cfa..015cda1b 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -43,7 +43,7 @@ static const char *const known[] = { "FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", "HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MENU_LANG", "MENU_TEST", - "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", + "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC", @@ -74,7 +74,7 @@ static const struct { const char *key, *section; } sections[] = { {"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"}, - {"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, + {"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -129,6 +129,7 @@ static const CfgMeta metas[] = { // Game {"FPS_LIMIT", "60", "30|40|45|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, + {"MODS_REBUILD", "auto", "auto|off", RESTART}, {"HIGHFPS_FIX", "1", "0|1", RESTART}, {"LANG", "", "ja|en-US|fr|de|it|es|zh-CN|ko|nl|pt|ru|zh-TW|en-GB|fr-CA|es-419|zh-Hans|zh-Hant|pt-BR", RESTART}, {"OPERATION_MODE", "docked", "docked|handheld", RESTART}, diff --git a/runtime/cheats.c b/runtime/cheats.c index 4fa54d71..b777566c 100644 --- a/runtime/cheats.c +++ b/runtime/cheats.c @@ -42,6 +42,7 @@ typedef struct { uint32_t *words; int n; int dup; // 1 for the first cheat of its name in its file, 2 for the next ... + uint32_t content; // FNV-1a 32 of its words as tools/cheats.py writes them int set; // patch set, -1 none volatile int32_t on; char note[STATUS_MAX]; @@ -50,6 +51,7 @@ typedef struct { static Cheat *g_cheats; static int g_n, g_cap, g_vm; // g_vm: some cheat needs cheats_frame static char g_file[64]; // ".txt" +static char g_dir[PLAT_PATH_MAX]; // the folder of totk.exe, with a trailing separator static int g_files; // mods whose file was read static uint64_t g_main, g_main_size, g_code_end; // main's image; its code with the padding up to .rodata @@ -438,10 +440,74 @@ static void plain_name(char *s) { } } +// ---- rebuild: code cheats the build lacks +// The setup writes build-cache\rebuild.txt (installer/steps.py write_rebuild_command), the command that starts its +// window in rebuild mode on this install folder, one argument per line. When an enabled mod has code cheats this build +// lacks (CHEAT_REBUILD), the game runs it and exits; the setup lifts and compiles them in and starts the game again. +// build-cache\rebuild.skip holds the key of the cheats a rebuild was started for: a rebuild that failed or was +// cancelled leaves them unbuilt, and the same set does not start it again. TOTK_MODS_REBUILD=off never starts it. +// Scripted runs (--seconds, --boot) never start it. +static void rebuild_if_needed(const char *dir) { + uint32_t key = 0x811C9DC5u; + int need = 0; + for (int i = 0; i < g_n; i++) { + const Cheat *c = &g_cheats[i]; + if (c->info.kind != CHEAT_REBUILD) continue; + need++; + key = (key ^ fnv(c->info.key, strlen(c->info.key))) * 0x01000193u; + key = (key ^ c->content) * 0x01000193u; + } + if (!need) return; + char cmd_path[PLAT_PATH_MAX + 64], skip_path[PLAT_PATH_MAX + 64], skip[16] = "", want[16]; + snprintf(cmd_path, sizeof cmd_path, "%sbuild-cache" SEP "rebuild.txt", dir); + snprintf(skip_path, sizeof skip_path, "%sbuild-cache" SEP "rebuild.skip", dir); + snprintf(want, sizeof want, "%08X", key); + char *old = read_text(skip_path); + if (old) snprintf(skip, sizeof skip, "%.8s", old); + free(old); + const char *why = !strcmp(cfg_value("TOTK_MODS_REBUILD"), "off") ? "mods_rebuild = off" + : rt_config()->seconds || rt_config()->boot ? "a scripted run" + : !strcmp(skip, want) ? "the last rebuild for them failed or was cancelled" + : NULL; + char *cmd = why ? NULL : read_text(cmd_path); + if (!why && !cmd) why = "no build-cache/rebuild.txt (a build without the setup)"; + if (why) { + rt_log("cheats: %d code cheats are not built into the game; no rebuild: %s", need, why); + free(cmd); + return; + } + const char *argv[32]; + int argc = 0; + for (char *line = cmd; line && *line && argc < 31;) { + char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL; + if (end) *end = 0; + size_t n = strlen(line); + if (n && line[n - 1] == '\r') line[n - 1] = 0; + if (*line) argv[argc++] = line; + line = next; + } + argv[argc] = NULL; + if (argc < 2 || !plat_file_write(skip_path, want, strlen(want))) { + rt_log("cheats: %d code cheats are not built into the game; cannot start the rebuild (%s)", need, cmd_path); + free(cmd); + return; + } + rt_log("cheats: %d code cheats are not built into the game; starting the rebuild: %s", need, argv[0]); + int ok = plat_spawn(argv, dir); + free(cmd); + if (!ok) { + rt_log("cheats: the rebuild did not start; the game starts with the code it has"); + return; + } + prof_write(); // plat_exit runs no atexit handlers + plat_exit(0); +} + void cheats_init(void) { const RtLoaded *m = ldr_count() ? ldr_module(0) : NULL; char dir[PLAT_PATH_MAX], bid[17], path[2400]; // path: a mod's cheats folder (ModInfo.cheats) + the file if (!m || !exe_dir(dir, sizeof dir) || !build_id(bid)) return; + snprintf(g_dir, sizeof g_dir, "%s", dir); g_main = m->base; g_main_size = m->size; g_code_end = m->base + ((m->text_end + 0xFFF) & ~0xFFFull); @@ -479,7 +545,8 @@ void cheats_init(void) { if (!t) rt_fatal("cheats: out of memory"); t[0] = 0; for (int k = 0; k < c->n; k++) tl += (size_t)snprintf(t + tl, tn - tl, k ? " %08X" : "%08X", c->words[k]); - snprintf(content, sizeof content, "%08X", fnv(t, tl)); + c->content = fnv(t, tl); + snprintf(content, sizeof content, "%08X", c->content); free(t); snprintf(c->info.key, sizeof c->info.key, "TOTK_CHEAT_%s", key); int master = c->info.kind == CHEAT_MASTER; @@ -511,16 +578,31 @@ void cheats_init(void) { counts[kind]++; } free(status); + rebuild_if_needed(dir); for (int i = 0; i < g_n; i++) plain_name((char *)g_cheats[i].info.name); // the hashes above read the file's bytes int on = 0; for (int i = 0; i < g_n; i++) on += g_cheats[i].on && g_cheats[i].info.kind != CHEAT_HEADING; rt_log("cheats: %s in %d mods: %d cheats, %d on; %d code, %d while buttons are held, %d data, %d master, " - "%d restore, %d headings, %d need the setup again, %d not supported%s", + "%d restore, %d headings, %d wait for a rebuild, %d not supported%s", g_file, g_files, g_n, on, counts[CHEAT_CODE], counts[CHEAT_KEY], counts[CHEAT_DATA], counts[CHEAT_MASTER], counts[CHEAT_RESTORE], counts[CHEAT_HEADING], counts[CHEAT_REBUILD], counts[CHEAT_UNSUPPORTED], seen_dups ? " (repeated names numbered)" : ""); } +int cheats_rebuild_pending(void) { + char path[PLAT_PATH_MAX + 64]; + snprintf(path, sizeof path, "%sbuild-cache" SEP "rebuild.txt", g_dir); + for (int i = 0; i < g_n; i++) + if (g_cheats[i].info.kind == CHEAT_REBUILD) return g_dir[0] && plat_file_exists(path); + return 0; +} + +void cheats_rebuild_allow(void) { + char path[PLAT_PATH_MAX + 64]; + snprintf(path, sizeof path, "%sbuild-cache" SEP "rebuild.skip", g_dir); + plat_fs_unlink(path); +} + int cheats_count(void) { return g_n; } const CheatInfo *cheats_info(int i) { return i >= 0 && i < g_n ? &g_cheats[i].info : NULL; } diff --git a/runtime/cheats.h b/runtime/cheats.h index 09589b1f..bbefa12c 100644 --- a/runtime/cheats.h +++ b/runtime/cheats.h @@ -30,6 +30,10 @@ typedef struct { void cheats_init(void); // after rt_patches_init: reads the mods' files and their build status int cheats_count(void); +// 1 when a cheat of an enabled mod waits for a rebuild (CHEAT_REBUILD) and the setup left its rebuild command. +int cheats_rebuild_pending(void); +// The next start rebuilds again for cheats whose last rebuild failed or was cancelled (the menu restarts after it). +void cheats_rebuild_allow(void); const CheatInfo *cheats_info(int i); int cheats_on(int i); // the player's switch (1 for a master cheat) void cheats_set(int i, int on); // switches at once and sets the cheat's setting (the menu saves totk.ini) diff --git a/runtime/platform/linux.c b/runtime/platform/linux.c index 690ecb44..0db015c7 100644 --- a/runtime/platform/linux.c +++ b/runtime/platform/linux.c @@ -1711,6 +1711,26 @@ int plat_restart(void) { return e == 0; } +int plat_spawn(const char *const *argv, const char *cwd) { + posix_spawn_file_actions_t fa; + posix_spawn_file_actions_init(&fa); + posix_spawn_file_actions_addclosefrom_np(&fa, 3); + posix_spawn_file_actions_addchdir_np(&fa, cwd); + posix_spawnattr_t at; + posix_spawnattr_init(&at); + sigset_t none, all; + sigemptyset(&none); + sigfillset(&all); + posix_spawnattr_setsigmask(&at, &none); + posix_spawnattr_setsigdefault(&at, &all); + posix_spawnattr_setflags(&at, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSID); + pid_t pid; + int e = posix_spawn(&pid, argv[0], &fa, &at, (char *const *)argv, environ); + posix_spawnattr_destroy(&at); + posix_spawn_file_actions_destroy(&fa); + return e == 0; +} + int plat_restart_wait(uint32_t timeout_ms) { const char *v = getenv(RESTART_WAIT); if (!v) return 0; diff --git a/runtime/platform/platform.h b/runtime/platform/platform.h index 70249095..b8e0c74b 100644 --- a/runtime/platform/platform.h +++ b/runtime/platform/platform.h @@ -416,6 +416,9 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap); // bytes read // Starts this executable again with the same command line, environment and working folder, and no handle of this // process. 1 when it started; the caller then exits. int plat_restart(void); +// Starts argv[0] with the arguments argv[1..] (NULL-terminated, UTF-8) in folder cwd, detached from this process: no +// console, no handle of this one. 1 when it started (the setup window that rebuilds the game, runtime/cheats.c). +int plat_spawn(const char *const *argv, const char *cwd); // In a process plat_restart started: waits, at most timeout_ms, until the process that started it has exited. 1 after // the wait, -1 on timeout, 0 when there is nothing to wait for (not started by plat_restart, or that process is gone). int plat_restart_wait(uint32_t timeout_ms); diff --git a/runtime/platform/win32.c b/runtime/platform/win32.c index 096ef9ec..6d83b6a3 100644 --- a/runtime/platform/win32.c +++ b/runtime/platform/win32.c @@ -1554,6 +1554,51 @@ int plat_restart(void) { return 1; } +// One argument of a command line as CommandLineToArgvW reads it back: in quotes, a backslash run doubled before a quote +// and at the end, a quote escaped. +static size_t quote_arg(const wchar_t *a, wchar_t *out, size_t cap, size_t at) { +#define PUT(c) do { if (at + 1 < cap) out[at] = (c); at++; } while (0) + PUT(L'"'); + for (const wchar_t *p = a;; p++) { + size_t slashes = 0; + while (*p == L'\\') p++, slashes++; + size_t times = !*p || *p == L'"' ? 2 : 1; + for (size_t k = 0; k < slashes * times; k++) PUT(L'\\'); + if (!*p) break; + if (*p == L'"') PUT(L'\\'); + PUT(*p); + } + PUT(L'"'); + PUT(L' '); +#undef PUT + return at; +} + +int plat_spawn(const char *const *argv, const char *cwd) { + enum { CMD = 32768 }; + wchar_t *cmd = calloc(CMD, sizeof *cmd), *arg = malloc(WPATH * sizeof *arg), *dir = malloc(WPATH * sizeof *dir); + int ok = cmd && arg && dir && argv[0] && widen(cwd, dir, WPATH); + size_t at = 0; + for (int i = 0; ok && argv[i]; i++) { + ok = widen(argv[i], arg, WPATH); + if (ok) at = quote_arg(arg, cmd, CMD, at); + } + ok = ok && at < CMD && at > 0; + if (ok) cmd[at - 1] = 0; // the last separator + STARTUPINFOW si = {.cb = sizeof si}; + PROCESS_INFORMATION pi; + ok = ok && CreateProcessW(NULL, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, NULL, dir, &si, + &pi); + if (ok) { + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + } + free(cmd); + free(arg); + free(dir); + return ok; +} + int plat_restart_wait(uint32_t timeout_ms) { char v[48]; if (!plat_getenv(RESTART_WAIT, v, sizeof v)) return 0; diff --git a/runtime/ui/cheats_tab.cpp b/runtime/ui/cheats_tab.cpp index 5ab59500..236465df 100644 --- a/runtime/ui/cheats_tab.cpp +++ b/runtime/ui/cheats_tab.cpp @@ -1,6 +1,7 @@ // The Cheats tab of the in-game menu: the cheats of the mods' cheat files (cheats.c), a heading per mod in the Mods // tab's order, then a row per cheat in file order and a line per group label of the file; a cheat that cannot be -// switched here is greyed out with the reason. +// switched here is greyed out with the reason. While code cheats wait for a rebuild, a row on top restarts the game +// into it. #include #include @@ -12,7 +13,8 @@ extern "C" { #include "ui_text.h" } -extern "C" void tab_cheats(float scale) { +// Returns true when "Rebuild the game now" was chosen: the menu then asks to restart (ui/menu.cpp restart_confirm). +extern "C" bool tab_cheats(float scale) { opt_begin("##cheats", scale); static char line[512], desc[768], buttons[192]; int n = cheats_count(); @@ -20,8 +22,10 @@ extern "C" void tab_cheats(float scale) { snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_NONE), cheats_file()[0] ? cheats_file() : ".txt"); opt_text_str(line); opt_end(); - return; + return false; } + bool rebuild = + cheats_rebuild_pending() && opt_button("##restart", UI_MENU_CHEATS_REBUILD, UI_MENU_CHEATS_REBUILD_DESC); for (int i = 0; i < n; i++) { const CheatInfo *c = cheats_info(i); if (!i || strcmp(c->mod, cheats_info(i - 1)->mod)) { @@ -58,4 +62,5 @@ extern "C" void tab_cheats(float scale) { } } opt_end(); + return rebuild; } diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 53b7fef2..7319ac2e 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -56,7 +56,7 @@ double frame_step_limit_hz(void); extern const int rt_game_version; extern const char rt_port_version[]; void cheats_frame(uint64_t frame); // cheats.c -void tab_cheats(float scale); // ui/cheats_tab.cpp +bool tab_cheats(float scale); // ui/cheats_tab.cpp; true: restart into the rebuild } // Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs. @@ -771,7 +771,9 @@ static const char *prompts_note(bool *restart) { // The confirmation of "Restart now", over the menu; Cancel has the cursor first. Restart writes totk.ini, then closes // the game as Quit does and starts it again (gfx_window_request_restart). It waits while the game writes a save, and -// the game stays when totk.ini cannot be written, as the new prompts would not come back. +// the game stays when totk.ini cannot be written, as the new prompts would not come back. From the Cheats tab +// (restart_rebuild) Restart also lets the next start rebuild for cheats whose last rebuild failed (cheats_rebuild_allow). +static bool restart_rebuild; static void restart_confirm(void) { g_modal = false; ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); @@ -792,12 +794,16 @@ static void restart_confirm(void) { if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus(); ImGui::SameLine(); ImGui::BeginDisabled(saving); - if (ImGui::Button(yes, ImVec2(bw, 0)) && cfg_save()) gfx_window_request_restart(); + if (ImGui::Button(yes, ImVec2(bw, 0)) && cfg_save()) { + if (restart_rebuild) cheats_rebuild_allow(); + gfx_window_request_restart(); + } ImGui::EndDisabled(); if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) close = true; if (close) { ImGui::CloseCurrentPopup(); + restart_rebuild = false; opt_focus_key("##restart"); // back on the row it came from } ImGui::EndPopup(); @@ -1140,7 +1146,13 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { case TAB_CONTROLS: tab_controls(scale); break; case TAB_AMIIBO: tab_amiibo(scale); break; case TAB_MENU: tab_menu(scale); break; - case TAB_CHEATS: tab_cheats(scale); break; + case TAB_CHEATS: + if (tab_cheats(scale)) { + restart_rebuild = true; + ImGui::OpenPopup("##restart_confirm"); + } + restart_confirm(); + break; case TAB_ADVANCED: tab_advanced(scale); break; } ImGui::EndTabItem(); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 9e905de7..e3c21958 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -418,8 +418,8 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_TAB_CHEATS] = "Cheats", [UI_MENU_CHEATS_NONE] = "No cheats for this game version. A mod's cheats are an Atmosphere cheat file in its " "cheats folder, named after the game's build: mods\\\\cheats\\%s. Restart the game to " - "read them. Cheats that change the game's code also need the setup run again on this " - "folder.", + "read them. For cheats that change the game's code, the game rebuilds itself at start (a " + "few minutes).", [UI_MENU_CHEATS_MOD] = "%s: %d cheats", [UI_MENU_CHEAT_CODE_DESC] = "Changes the game's code. Switches at once.", [UI_MENU_CHEAT_KEY_DESC] = "Changes the game's code while you hold %s. Switches at once.", @@ -428,11 +428,17 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_CHEAT_MASTER_DESC] = "The file's master code: it is always on.", [UI_MENU_CHEAT_RESTORE] = "not needed", [UI_MENU_CHEAT_RESTORE_DESC] = "It only writes the game's own code back. Switching a cheat off already does that.", - [UI_MENU_CHEAT_REBUILD] = "run the setup again", + [UI_MENU_CHEAT_REBUILD] = "after the rebuild", [UI_MENU_CHEAT_REBUILD_DESC] = "This cheat changes the game's code and is new or edited since the game was built. " - "Run the setup again on this folder to build it (about three minutes).", + "The game builds it in when it starts next (a few minutes), or use Rebuild the game " + "now.", [UI_MENU_CHEAT_UNSUPPORTED] = "not supported", [UI_MENU_CHEAT_UNSUPPORTED_DESC] = "This cheat cannot be used with this version of the game:", + [UI_MENU_CHEATS_REBUILD] = "Rebuild the game now", + [UI_MENU_CHEATS_REBUILD_DESC] = "Some cheats change the game's code and are not built into it: they are new or " + "edited, or their last rebuild failed or was cancelled. Closes the game; the setup " + "builds them in (a few minutes) and starts the game again. Progress since your " + "last save is lost.", }; static const char *const text_ru[UI_TEXT_COUNT] = { @@ -834,7 +840,8 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_TAB_CHEATS] = "Читы", [UI_MENU_CHEATS_NONE] = "Для этой версии игры читов нет. Читы мода — это файл читов Atmosphere в его папке cheats " "с именем по сборке игры: mods\\<мод>\\cheats\\%s. Перезапустите игру, чтобы они " - "прочитались. Для читов, меняющих код игры, ещё раз запустите установщик для этой папки.", + "прочитались. Для читов, меняющих код игры, игра пересоберётся сама при запуске (несколько " + "минут).", [UI_MENU_CHEATS_MOD] = "%s — читов: %d", [UI_MENU_CHEAT_CODE_DESC] = "Меняет код игры. Включается и выключается сразу.", [UI_MENU_CHEAT_KEY_DESC] = "Меняет код игры, пока вы держите %s. Включается и выключается сразу.", @@ -843,11 +850,16 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_CHEAT_MASTER_DESC] = "Главный код файла: включён всегда.", [UI_MENU_CHEAT_RESTORE] = "не нужен", [UI_MENU_CHEAT_RESTORE_DESC] = "Он только возвращает исходный код игры. Выключение чита уже делает это.", - [UI_MENU_CHEAT_REBUILD] = "запустите установщик", - [UI_MENU_CHEAT_REBUILD_DESC] = "Этот чит меняет код игры и появился или изменился после сборки игры. Запустите " - "установщик для этой папки ещё раз, чтобы собрать его (около трёх минут).", + [UI_MENU_CHEAT_REBUILD] = "после пересборки", + [UI_MENU_CHEAT_REBUILD_DESC] = "Этот чит меняет код игры и появился или изменился после сборки игры. Игра соберёт " + "его при следующем запуске (несколько минут), или нажмите «Пересобрать игру сейчас».", [UI_MENU_CHEAT_UNSUPPORTED] = "не поддерживается", [UI_MENU_CHEAT_UNSUPPORTED_DESC] = "Этот чит нельзя использовать с этой версией игры:", + [UI_MENU_CHEATS_REBUILD] = "Пересобрать игру сейчас", + [UI_MENU_CHEATS_REBUILD_DESC] = "Некоторые читы меняют код игры и ещё не собраны в неё: они новые или изменены, " + "либо прошлая пересборка не удалась или была отменена. Закрывает игру; установщик " + "собирает их (несколько минут) и снова запускает игру. Прогресс после последнего " + "сохранения будет потерян.", }; static const char *const text_pt_br[UI_TEXT_COUNT] = { @@ -1276,8 +1288,8 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_TAB_CHEATS] = "Cheats", [UI_MENU_CHEATS_NONE] = "Nenhum cheat para esta versão do jogo. Os cheats de um mod são um arquivo de cheats do " "Atmosphere na pasta cheats dele, com o nome da build do jogo: mods\\\\cheats\\%s. " - "Reinicie o jogo para lê-los. Cheats que alteram o código do jogo também precisam que o " - "instalador seja executado de novo nesta pasta.", + "Reinicie o jogo para lê-los. Para cheats que alteram o código do jogo, o jogo se recompila " + "sozinho ao iniciar (alguns minutos).", [UI_MENU_CHEATS_MOD] = "%s: %d cheats", [UI_MENU_CHEAT_CODE_DESC] = "Altera o código do jogo. Liga e desliga na hora.", [UI_MENU_CHEAT_KEY_DESC] = "Altera o código do jogo enquanto você segura %s. Liga e desliga na hora.", @@ -1286,12 +1298,17 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_CHEAT_MASTER_DESC] = "O código mestre do arquivo: está sempre ligado.", [UI_MENU_CHEAT_RESTORE] = "desnecessário", [UI_MENU_CHEAT_RESTORE_DESC] = "Ele só escreve de volta o código original do jogo. Desligar um cheat já faz isso.", - [UI_MENU_CHEAT_REBUILD] = "execute o instalador", + [UI_MENU_CHEAT_REBUILD] = "após recompilar", [UI_MENU_CHEAT_REBUILD_DESC] = "Este cheat altera o código do jogo e é novo ou foi editado depois que o jogo foi " - "compilado. Execute o instalador de novo nesta pasta para compilá-lo (cerca de três " - "minutos).", + "compilado. O jogo o compila na próxima vez que iniciar (alguns minutos), ou use " + "Recompilar o jogo agora.", [UI_MENU_CHEAT_UNSUPPORTED] = "não suportado", [UI_MENU_CHEAT_UNSUPPORTED_DESC] = "Este cheat não pode ser usado com esta versão do jogo:", + [UI_MENU_CHEATS_REBUILD] = "Recompilar o jogo agora", + [UI_MENU_CHEATS_REBUILD_DESC] = "Alguns cheats alteram o código do jogo e ainda não foram compilados nele: são " + "novos ou editados, ou a última recompilação falhou ou foi cancelada. Fecha o " + "jogo; o instalador os compila (alguns minutos) e inicia o jogo de novo. O " + "progresso desde o último salvamento é perdido.", }; // Simplified Chinese: this row covers the software keyboard and the whole menu, so the menu and the overlay read Chinese @@ -1820,7 +1837,8 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_FXAA_DESC] = "游戏自身的 FXAA 边缘平滑。会让细节略微模糊;开启 DLAA 时不需要。", [UI_MENU_TAB_CHEATS] = "金手指", [UI_MENU_CHEATS_NONE] = "此游戏版本没有金手指。模组的金手指是它的 cheats 文件夹中以游戏构建命名的 Atmosphere " - "金手指文件:mods\\<模组>\\cheats\\%s。重启游戏后才会读取。修改游戏代码的金手指还需要对此文件夹重新运行安装程序。", + "金手指文件:mods\\<模组>\\cheats\\%s。重启游戏后才会读取。对于修改游戏代码的金手指," + "游戏会在启动时自行重新构建(几分钟)。", [UI_MENU_CHEATS_MOD] = "%s:%d 个金手指", [UI_MENU_CHEAT_CODE_DESC] = "修改游戏代码。立即开关。", [UI_MENU_CHEAT_KEY_DESC] = "按住 %s 时修改游戏代码。立即开关。", @@ -1829,10 +1847,12 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_CHEAT_MASTER_DESC] = "文件的主代码:始终开启。", [UI_MENU_CHEAT_RESTORE] = "无需使用", [UI_MENU_CHEAT_RESTORE_DESC] = "它只会写回游戏原本的代码。关闭金手指时已经会这样做。", - [UI_MENU_CHEAT_REBUILD] = "重新运行安装程序", - [UI_MENU_CHEAT_REBUILD_DESC] = "此金手指修改游戏代码,并且是在游戏构建后新增或修改的。对此文件夹重新运行安装程序来构建它(约三分钟)。", + [UI_MENU_CHEAT_REBUILD] = "重新构建后", + [UI_MENU_CHEAT_REBUILD_DESC] = "此金手指修改游戏代码,并且是在游戏构建后新增或修改的。游戏会在下次启动时把它构建进去(几分钟),也可以使用“立即重新构建游戏”。", [UI_MENU_CHEAT_UNSUPPORTED] = "不支持", [UI_MENU_CHEAT_UNSUPPORTED_DESC] = "此金手指不能用于此游戏版本:", + [UI_MENU_CHEATS_REBUILD] = "立即重新构建游戏", + [UI_MENU_CHEATS_REBUILD_DESC] = "有些金手指会修改游戏代码,但尚未构建进游戏:它们是新增或修改的,或上次重新构建失败或被取消。将关闭游戏;安装程序会把它们构建进去(几分钟)并重新启动游戏。上次存档之后的进度会丢失。", }; #define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)} diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 706e445c..abd1d49c 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -215,6 +215,7 @@ typedef enum { UI_MENU_TAB_CHEATS, UI_MENU_CHEATS_NONE, // "%s": .txt UI_MENU_CHEATS_MOD, // "%s": the mod, "%d": its cheats + UI_MENU_CHEATS_REBUILD, UI_MENU_CHEATS_REBUILD_DESC, // restart into the rebuild for unbuilt code cheats UI_MENU_CHEAT_CODE_DESC, UI_MENU_CHEAT_KEY_DESC /* "%s": the buttons */, UI_MENU_CHEAT_DATA_DESC, UI_MENU_CHEAT_MASTER, UI_MENU_CHEAT_MASTER_DESC, UI_MENU_CHEAT_RESTORE, UI_MENU_CHEAT_RESTORE_DESC, UI_MENU_CHEAT_REBUILD, UI_MENU_CHEAT_REBUILD_DESC, UI_MENU_CHEAT_UNSUPPORTED, UI_MENU_CHEAT_UNSUPPORTED_DESC, diff --git a/tests/installer_test.py b/tests/installer_test.py index 9ebedaf5..0cba2c9f 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -315,7 +315,8 @@ class CleanupTest(unittest.TestCase): self.expected = {'romfs': {'size': len(image), 'sha256': digest}} self.ctx = SimpleNamespace(reporter=Reporter(out=io.StringIO(), log_path=base / 'x.log'), dest=self.dest, temp=temp, lang='en-US', state={}, - layout=SimpleNamespace(ini_example=ROOT / 'totk.ini.example')) + layout=SimpleNamespace(ini_example=ROOT / 'totk.ini.example', + python=base / 'python' / 'python.exe', root=base / 'release')) self.saved = steps.expected_update steps.expected_update = lambda ctx: self.expected @@ -334,6 +335,16 @@ class CleanupTest(unittest.TestCase): def test_intact_romfs_passes(self): self.assertEqual(self.run_cleanup(), 'ok') + def test_keeps_build_and_writes_rebuild_command(self): + for name in ('gen', 'build', 'check'): + (self.ctx.temp / name).mkdir() + self.assertEqual(self.run_cleanup(), 'ok') + self.assertTrue((self.ctx.temp / 'gen').is_dir() and (self.ctx.temp / 'build').is_dir()) + self.assertFalse((self.ctx.temp / 'check').exists()) + lines = (self.dest / 'build-cache' / 'rebuild.txt').read_text(encoding='utf-8').splitlines() + self.assertEqual(lines[1:], ['-m', 'installer.gui', '--root', str(self.ctx.layout.root), '--rebuild', + str(self.dest)]) + def test_emptied_romfs_fails(self): for p in (self.dest / 'romfs').iterdir(): p.unlink() diff --git a/totk.ini.example b/totk.ini.example index d889ab24..227a923f 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -286,6 +286,10 @@ # mods_order = # Mods switched off, names separated by |. # mods_disabled = +# auto: when an enabled mod has cheats that change the game's code and the game was built without them, the game starts +# the setup's rebuild at start (a few minutes) and starts again after it. off: the game starts with the code it has. +# A rebuild that failed or was cancelled is not started again for the same cheats. Default: auto. +# mods_rebuild = auto [files] # Developer overlay: a folder with RomFS files and a manifest.tsv (tools/make_romfs_patches.py format). Players put