Merge remote-tracking branch 'origin/dev' into perf/heap-lazy-commit

# Conflicts:
#	runtime/cfg.c
This commit is contained in:
Ruan Shannon committed 2026-11-23 13:37:39 -08:00
commit 54b2975d98
91 files changed
+11601 -528

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ Open pull requests against `dev`. Branch from the current `dev` and rebase on it
- **The fix, not a disabled feature.** A crash that goes away with a feature off points at the bug in that feature. Turning the feature off for a vendor is not a fix.
- **The frame time on weak hardware.** Game threads and the render thread do no file I/O, no GPU allocations, no per-draw state copies and no global atomic counters. Memory kept per frame or per object is freed. The full list with measured costs: [docs/pr-review-kit/02-performance.md](docs/pr-review-kit/02-performance.md), "What the hot path must not do".
- **Other GPUs.** New Vulkan code queries each feature, extension, format and limit it uses and keeps a working path without it. Nothing is hardcoded from what one GPU reports.
- **Text in the catalogs.** Text a player sees gets an id in `runtime/ui_text.h` and an entry in `runtime/ui_text.c` for every menu language (English, Russian, Brazilian Portuguese, Simplified Chinese); installer text goes into `installer/text/*.json`.
- **Text in the catalogs.** Text a player sees gets an id in `runtime/ui_text.h` and an entry in `runtime/ui_text.c` for every menu language (English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean, Vietnamese); installer text goes into `installer/text/*.json`.
- **The generator owns generated C.** Change `recomp/`, never `generated/`.
### Checks by what you changed
+16 -11
View File
@@ -22,13 +22,16 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling
- NVIDIA DLSS / DLAA on RTX GPUs: the setup downloads `nvngx_dlss.dll` from NVIDIA's DLSS SDK repository
(github.com/NVIDIA/DLSS, NVIDIA RTX SDK license) when it finds an RTX GPU; untick it in the setup to skip it
- AMD FSR 3.1 on any GPU, and AMD FSR 4 on Windows on the Radeon GPUs AMD's FSR SDK libraries support, in the same
modes as DLSS: for FSR 4 the setup downloads AMD's signed FSR SDK libraries
(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, AMD FSR SDK license), ticked by default with an AMD GPU
- HDR10 output with peak, game and HUD brightness settings
- 16:10 (Steam Deck, handhelds), 3:2 (Surface, Framework), 21:9 and 32:9 (ultrawide) game resolutions, with the camera and the interface in that shape
- Anisotropic texture filtering up to 16x, for sharp ground into the distance
- In-game settings menu (F1) and performance overlay (F10)
- Play time across runs on the Game tab of the settings menu, kept in `playtime.txt` next to the saves
- Discord Rich Presence ("Playing TotK Recomp" with the play time), off by default, own application id supported
- Setup in 11 languages, in-game menu in 4 ([Languages](#languages))
- Setup in 12 languages, in-game menu in 12 ([Languages](#languages))
- Keyboard, mouse and gamepad with remapping, rumble and gyro
- Stereo or 5.1 surround sound output
- Xbox and PlayStation button prompts: Xbox's LB, RB, LT, RT, Menu, View and A, B, X, Y, or PlayStation's ○ × △ □, L1, R1, L2, R2, Options and Share, as labelled on the button to press, with either button layout
@@ -43,7 +46,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
The game keeps the text and voices of every language it shipped with. The port's own setup and in-game menu (F1) come
in these; both follow the Windows display language, and the menu has its own choice on its Menu tab. A Traditional
Chinese Windows gets the Simplified Chinese setup.
Chinese Windows gets the Simplified Chinese setup and menu.
| Language | Setup | In-game menu |
|---|:---:|:---:|
@@ -51,13 +54,14 @@ Chinese Windows gets the Simplified Chinese setup.
| Русский | ✅ | ✅ |
| Português (Brasil) | ✅ | ✅ |
| 简体中文 | ✅ | ✅ |
| Deutsch | ✅ | English |
| Français | ✅ | English |
| Español | ✅ | English |
| Italiano | ✅ | English |
| Nederlands | ✅ | English |
| 日本語 | ✅ | English |
| 한국어 | ✅ | English |
| Deutsch | ✅ | ✅ |
| Français | ✅ | ✅ |
| Español | ✅ | ✅ |
| Italiano | ✅ | ✅ |
| Nederlands | ✅ | ✅ |
| 日本語 | ✅ | ✅ |
| 한국어 | ✅ | ✅ |
| Tiếng Việt | ✅ | ✅ |
Spotted a clumsy phrase, or want your language added? The setup texts are in `installer/text/<language>.json`, the
menu texts in `runtime/ui_text.c`; open an issue or a pull request ([CONTRIBUTING.md](CONTRIBUTING.md)). Fixes from
@@ -71,13 +75,14 @@ native speakers are welcome.
### Windows
Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines get a faster build), a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, about 36 GiB free during setup (20 GiB after).
Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines get a faster build), a GPU with Vulkan 1.3 (`VK_EXT_external_memory_host` recommended: without it the game copies its memory pools and runs slower), about 36 GiB free during setup (20 GiB after).
1. Download `TotK-Setup-<version>-windows.zip` from [Releases](../../releases/latest) and unpack it.
2. Start `TotK-Setup.exe`. If SmartScreen warns about an unsigned app, choose *More info*, then *Run anyway*.
3. Pick your game files, the language and an install folder, and press *Start*. The setup builds the game once. With
an NVIDIA RTX GPU it also downloads NVIDIA DLSS, unless you untick *Download NVIDIA DLSS*; turn DLSS on in the
menu (F1).
menu (F1). With *Download AMD FSR 4* ticked (the default with an AMD GPU) it downloads AMD's FSR SDK libraries;
in the menu, pick *AMD FSR 4* as the *3D scene upscaler*.
4. Play `totk.exe` from the install folder.
### Linux
+3 -1
View File
@@ -30,7 +30,7 @@ Code copied or adapted from another project is listed here with its source, the
| SDL 3.4.20, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.20-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) |
| libopus (MSYS2 `mingw-w64-ucrt-x86_64-opus`), dynamic link, `libopus-0.dll` copied next to `totk.exe` | https://opus-codec.org, Copyright (c) 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon | BSD-3-Clause | `runtime/ov_media.c` (nn::codec hardware Opus decoder) |
| Dear ImGui 1.91.9 (core and Vulkan back end, unmodified), as vendored by LAS Recomp | https://github.com/ocornut/imgui, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/`), Copyright (c) 2014-2025 Omar Cornut | MIT | `runtime/third_party/imgui/` (compiled into `totk.exe` for the in-game menu, `runtime/ui/`) |
| AMD FidelityFX SDK 1.1.4 subset (public host and shader headers, frame interpolation, optical flow and FSR 3 upscaler components, the Vulkan backend `ffx_vk.cpp` and its GLSL shaders, shared helpers), with four marked Savage Wind patches (64-byte aligned backend scratch arrays, doubled context size where `wchar_t` is 4 bytes, all six descriptor pool sizes, the upscaler's Catmull-Rom history reprojection) and one of ours (the upscaler's luma history declared `rgba16f`) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4, Copyright (C) 2024 Advanced Micro Devices, Inc., via https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/`) | MIT | `runtime/third_party/FidelityFX/` (compiled into `totk.exe`; licence text in `runtime/third_party/FidelityFX/LICENSE.txt`, shipped as `licenses/FidelityFX-SDK-LICENSE.txt`) |
| AMD FidelityFX SDK 1.1.4 subset (public host and shader headers, frame interpolation, optical flow and FSR 3 upscaler components, the Vulkan backend `ffx_vk.cpp` and its GLSL shaders, shared helpers), with four marked Savage Wind patches (64-byte aligned backend scratch arrays, doubled context size where `wchar_t` is 4 bytes, all six descriptor pool sizes, the upscaler's Catmull-Rom history reprojection) and two of ours (the upscaler's luma history declared `rgba16f`, the backend's memory type choice skipping protected and AMD device-coherent types) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4, Copyright (C) 2024 Advanced Micro Devices, Inc., via https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/`) | MIT | `runtime/third_party/FidelityFX/` (compiled into `totk.exe`; licence text in `runtime/third_party/FidelityFX/LICENSE.txt`, shipped as `licenses/FidelityFX-SDK-LICENSE.txt`) |
| SavageWindRecomp FidelityFX build support, frame generation and FSR 3 upscaler set-up: the SDK-to-clang compat header, the glslang SPIR-V shader generator with its resource reflection and its FSR 3 upscaler permutations, the blob lookup and the backend and context creation of `runtime/nvn/vulkan/framegen.cpp`, the upscaler context with its shared images and the dispatch parameters of `runtime/nvn/vulkan/fsr3.cpp`, the pair's present spacing of `runtime/nvn/vulkan/device.c` `present_wait_turn` | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/ffx_compat.h`, `tools/ffx_shaders.py`, `runtime/nvn/vulkan/framegen.cpp`, `runtime/nvn/vulkan/fsr3.cpp`, `runtime/nvn/vulkan/device.c`) | MIT | `runtime/third_party/FidelityFX/ffx_compat.h`, `runtime/third_party/FidelityFX/spirv/ffx_shaders_vk.h` and `ffx_fsr3upscaler_vk.h` (output of `tools/ffx_shaders.py`), `tools/ffx_shaders.py`, `runtime/vk_fg.cpp`, `runtime/vk_fsr3.cpp`, `runtime/vk_backend.c` (`present_pair`) |
| SavageWindRecomp settings menu: two-pane option rows (row look, left / right stepping, hold speed-up, description pane), the menu style and tab bar | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/ui/option_rows.mm`, `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/ui/option_rows.cpp`, `runtime/ui/option_rows.h`, `runtime/ui/menu.cpp` |
| SavageWindRecomp GPU overlap one-off readback rule: a target not read back within the last 16 frames (64-entry table) makes the frame wait wait up to the value that rendered it | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`runtime/nvn/vulkan/exec.c` readback_schedule, renderer_wait_seq), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/vk_texture.c` (oneoff_streaming, vk_texture_oneshot) |
@@ -41,6 +41,8 @@ Code copied or adapted from another project is listed here with its source, the
| MacNativeGames host movie decoder (`movie::Decoder` for VP9 over libvpx: entry list, buffer and event semantics, NV12 output format, PTS pacing) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/movie_host.c`, `movie_host.h`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/ov_movie.c`, `runtime/movie.h` |
| libvpx 1.17.0 (MSYS2 `mingw-w64-ucrt-x86_64-libvpx`), static link (`libvpx.a`), no DLL shipped; the release notices must carry its BSD licence text and the WebM Project's `PATENTS` grant | https://chromium.googlesource.com/webm/libvpx, Copyright (c) 2010, The WebM Project authors | BSD-3-Clause | `runtime/ov_movie.c` (VP9 decoding of the `Event/Movie` WebM files) |
| MacNativeGames TotK resolution patches: output, swapchain and scene size sites and instruction words for 1.2.1 and 1.4.3, the data-page layout, the HeapDef heap names and sizes | https://github.com/ly05010419/MacNativeGames @ `aaf6ba1f494fabaa209d049e528d6f923dfe822a` (`games/totk/runtime/game_patches.c`, `game_patches_v143.c`, `game_version.h`, `games/totk/scripts/make_output_res_overlay.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v121.txt`, `recomp/patches-v143.txt`, `runtime/resolution.c` |
| AMD FSR SDK ffx-api declarations (`ffx_api.h`, `ffx_api_types.h`, `vk/ffx_api_vk.h`, `upscalers/include/ffx_upscale.h`, trimmed to the declarations used, layouts unchanged) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ tag `v2.4.0`, Copyright (C) 2026 Advanced Micro Devices, Inc. | MIT | `runtime/ffx_api_min.h` |
| AMD FSR SDK signed binaries `amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` (not in this repository or the release: the setup's `--fsr` step downloads AMD's copies into the install folder) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ tag `v2.4.0` (`Kits/FidelityFX/signedbin/`), Copyright (C) 2026 Advanced Micro Devices, Inc. | AMD FSR SDK license (`docs/license.md` of that tag): redistribution in binary form with its notice, no reverse engineering | loaded at run time by `runtime/vk_ffx.c` |
| AMD FidelityFX Super Resolution 1.0 (`ffx_a.h`, `ffx_fsr1.h`, unmodified; licence text in `runtime/shaders/ffx/LICENSE.txt`) | https://github.com/GPUOpen-Effects/FidelityFX-FSR @ `a21ffb8f6c13233ba336352bdff293894c706575`, Copyright (c) 2021 Advanced Micro Devices, Inc. | MIT | `runtime/shaders/ffx/`, `runtime/shaders/fsr_easu.comp`, `runtime/shaders/fsr_rcas.comp` (compiled into `runtime/fsr_easu_spv.h`, `runtime/fsr_rcas_spv.h`) |
| AMD Display Library (ADL) declarations: `AdapterInfo`, `ADLSingleSensorData`, `ADLPMLogDataOutput`, the `ADL_PMLOG_*` sensor numbers and the `ADL2_*` function signatures | https://github.com/GPUOpen-LibrariesAndSDKs/display-library @ `84c881cb2136f04287eb3af12de00a9e2867aa9e` (`include/adl_structures.h`, `include/adl_defines.h`, `include/adl_sdk.h`), Copyright (c) 2016 - 2022 Advanced Micro Devices, Inc. | MIT | `runtime/perfmon.c` |
| Zstandard 1.5.7 (MSYS2 `mingw-w64-ucrt-x86_64-zstd`), static link | https://github.com/facebook/zstd, Copyright (c) Meta Platforms, Inc. and affiliates | BSD-3-Clause | `runtime/resolution.c` (the HeapDef table), `runtime/ov_zstd.c` (the game's zstd frames decoded on the host) |
+1 -1
View File
@@ -1 +1 @@
0.5.0
0.5.1-rc1
+17 -4
View File
@@ -59,8 +59,9 @@ MacNativeGames cannot run on x86-64 as is: its CPU path executes ARM64 code nati
- Settings and menu: every key with its default is in one table (`cfg.c`), read from `totk.ini` and `TOTK_*`
variables and written back when the in-game menu changes it. The menu and the performance overlay are Dear ImGui,
drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian, Brazilian Portuguese,
Simplified Chinese). The Chinese glyphs come from a system font (Microsoft YaHei, `plat_font_path`) merged into the
font atlas.
Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean,
Vietnamese). The Chinese, Japanese and Korean glyphs
come from a system font (`plat_font_path`) merged into the font atlas.
- OS calls the host makes go through `runtime/platform/` (`platform.h`, `win32.c`), so a Linux or macOS host adds one file instead of touching the rest. The split is not finished: `tools/check_platform.py` lists the Win32 uses left in the other files.
#### Threads and cores
@@ -87,7 +88,7 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
- NVN front end from MacNativeGames (`nvn_api_*.c`, `nvn_obj.h`, texture layout and deswizzle). The game records command buffers through it; nothing reaches the GPU until the game submits.
- Vulkan 1.3 back end in place of MacNativeGames' Metal one. At `QueueSubmitCommands` the recorded NVN commands are replayed into Vulkan command buffers (`vk_exec*.c`).
- Memory pools. Apple's unified memory let MacNativeGames use the game's pools zero-copy. The back end imports the pools as host memory (`VK_EXT_external_memory_host`). On a discrete GPU, pools bound as buffers are mirrored in device-local memory and the pages the CPU wrote (write watch, above) are uploaded before a replay; idle pool regions are made read-only so the write-watch queries skip them (`vk_memory.c`). GPU-rendered textures are written back when the CPU reads them: on a pool invalidate, on a CPU copy, and for small targets once the CPU waits for a fence (`vk_texture.c`).
- Memory pools. Apple's unified memory let MacNativeGames use the game's pools zero-copy. The back end imports the pools as host memory (`VK_EXT_external_memory_host`); under Wine, or on a GPU without the extension, CPU-visible pools get shadow storage instead (host-visible copies, `vk_memory.c` `mirror_mode`). On a discrete GPU, pools bound as buffers are mirrored in device-local memory and the pages the CPU wrote (write watch, above) are uploaded before a replay; idle pool regions are made read-only so the write-watch queries skip them (`vk_memory.c`). GPU-rendered textures are written back when the CPU reads them: on a pool invalidate, on a CPU copy, and for small targets once the CPU waits for a fence (`vk_texture.c`).
- Replay thread. `TOTK_REPLAY_ASYNC=1` moves the replay off the submitting thread onto a queue at most one frame behind the game; reads of GPU results wait for the newest writer instead of draining the queue (`vk_backend.c`). It is off by default. Where the game waits for the GPU it overlaps the replay with the game threads (a GTX 1650 in the Depths, issue #88), a gain measured only there; while it was the default, a GTX 1660 Ti at the 60 fps cap with the GPU at 26 % reported uneven motion (#659). It adds up to a frame of latency; `replay_async = 1` turns it on.
- Chunked replay. A large submission is recorded in chunks by several threads (`TOTK_REPLAY_WORKERS`, 0 by default: the sequential replay; 4 is a good value from 8 logical processors) and the chunks go to the queue in order (`vk_exec.c`). A sequential scan keeps a copy of the queue state where each chunk starts and lists what a chunk would otherwise learn from the chunks before it: inline uniform updates, conditions, contact shadow marches, uniform drops. It also makes render targets live in replay order and notes the op, since a chunk can sample a storage before the chunk that renders it got there or after the scan went past a later target there: a chunk's texture slots resolve as of its own op, and the chunks after a texture with no entry yet wait for the chunk that makes it. DLSS's decisions (the G-buffer, the light target, the end of the scene, the scaling pass) are the scan's too, and its copy of the lit scene and its evaluation are records of the chunk that holds the op; a chunk's draws are jittered while they come before the scan's end of the scene. The evaluation waits until the chunks before it are recorded, as it reads what their draws noted (the camera block, the jitter, the per-object motion list, which chunks add to under one lock), and the chunks after it wait for it, as they sample its output. `TOTK_REPLAY_STATE_CHECK=1` compares the state after the last chunk with the scan's.
- Frame ahead. `TOTK_SYNC_AHEAD=1` (`sync_ahead`, off by default) makes the one `nvnSyncWait` per frame that waits for the frame presented last wait for the frame before it, so the game builds the next frame while the GPU still runs the previous one (`nvn_api_core.c`, `nvnSyncWait`). The game then writes memory that in-flight work still reads. Two forms guard that. With shadow storage (`vk_memory.c`, the CPU-visible pools are host-visible copies of guest memory, on by default on Linux and Wine, `shadow = 1` (`TOTK_SHADOW=1`) on native Windows) a CPU write reaches the GPU only through the shadow copy made before each submit (`vk_mem_shadow_sync`), and a copy that would overwrite bytes an unfinished submission reads is queued as a GPU copy in the prologue command buffer of the part submitted next (`vk_mem_shadow_prologue`, `TOTK_SHADOW_DEFER=1`, the default with the feature) or, with `=0`, waited for on the replay thread (`shadow_reader_wait`). Only that one wait lags (identified by its call site, known for 1.1.0, 1.2.1 and 1.4.3). GPU writes into pool storage come back with their fence, so a buffer the game reads back every frame after that wait holds the result of the frame before; a buffer it has not read lately holds none, and its `nvnMemoryPoolInvalidateMappedRange` waits for the write (`vk_mem_shadow_read`): TotK reads single pixels through a buffer per request, and in the Depths zeros in one of them put Link in gloom. The exit line `mem: the game waited for a GPU write it reads` counts these waits and their time. On 1.4.3 the patch set `qstamp` (`recomp/patches-v143.txt`) lets the game take its depth query results one frame older; it follows the switch and is off when the switch is refused. The fence write-back of small render targets (`vk_texture.c`, `write_back_n`) does not wait for the GPU with `TOTK_WB_EAGER=1` (`wb_eager`, the default, but only while frame-ahead is in effect: with `sync_ahead` off or refused the setting does nothing and the write-back reads the image when it runs): `vk_sync_submit` has `vk_texture_eager_record` copy the targets that value rendered into staging buffers inside the same command buffer, so once the value has passed the write-back only copies from staging into the target's storage. Only a target that was written back within the last 64 timeline values is copied (the first write-back of a target takes the blocking path), and the staging of a target past that window, no longer wanted or released goes through the deferred free (`vk_defer_buffer_until`). A snapshot is used only when its value is the one that last rendered the target, nothing recorded a write to the image since (`wr_fence`) and the GPU has finished it; otherwise the write-back reads the image as before, and the exit line `vk: wb_eager:` counts the reasons. With frame-ahead in effect the exit line `vk: fence write-backs waited for the GPU` counts the write-backs that waited for a copy and the time they waited, for every value of the setting. `check` also reads the old way and compares.
@@ -139,10 +140,22 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
that computes last frame's position from last frame's blocks (the game writes them into two copies that take turns;
the uniform snapshot keeps both) and writes the difference into the motion image. `TOTK_MV_CHECK` measures the
vectors against the picture, `TOTK_DLAA_TIMES` times the passes on the GPU. `fxaa` switches the game's own FXAA pass.
- AMD FSR (`scene_upscaler = fsr3` or `fsr4`). The same frame, jitter and motion vectors (with the per-object pass)
go to AMD's FSR instead of DLSS: `vk_dlaa.c` `evaluate` calls `fsr_evaluate` where it would call NGX, and everything
around it is shared, including the texture bias (AMD's log2(scene / output) - 1), `fsr_sharpness` (FSR's own RCAS in
place of the FXAA's sharpening), the skip of the game's FXAA and of its copy of the scene onto itself, and the dynamic
resolution held at 100 %. The camera's planes and field of view come from the scene camera block (`vk_fg.cpp`
`vk_fg_camera`). FSR 3.1 (`vk_fsr3.cpp`) is compiled from the FidelityFX SDK 1.1.4 sources and runs on any GPU. FSR 4
(`vk_ffx.c`, Windows) is AMD's FSR SDK 2.4 signed libraries: `amd_fidelityfx_loader_vk.dll` is loaded at run time from
the executable's folder and finds `amd_fidelityfx_upscaler_vk.dll` next to it; only the descriptor layouts of
`ffx_api_min.h` are compiled in. At start the upscaler versions the libraries offer for the device are listed and the
newest FSR 4 is pinned; without one the scene upscaler stays off (no FSR 3 from the libraries). `vk_device.c` enables
`VK_KHR_cooperative_matrix` and `VK_EXT_shader_float8` with their features when FSR 4 is picked and the device has
them. Both hold one context per output size, made again when it changes.
- 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`).
- Allocation: Vulkan Memory Allocator. Debugging: Vulkan validation layers, per-pass frame dumps (`TOTK_DUMP`, `vk_dump.c`) and a flight recorder (`TOTK_FLIGHT`). RenderDoc cannot capture, because it hides `VK_EXT_external_memory_host` from the application.
- Allocation: Vulkan Memory Allocator. Debugging: Vulkan validation layers, per-pass frame dumps (`TOTK_DUMP`, `vk_dump.c`) and a flight recorder (`TOTK_FLIGHT`). RenderDoc hides `VK_EXT_external_memory_host` from the application, so under it CPU-visible pools get shadow storage, as on any GPU without the extension; captures on that path are untested.
Maxwell behaviour the back end has to match, and the TotK bugs other ports fixed: [maxwell.md](maxwell.md).
+6 -2
View File
@@ -1,6 +1,7 @@
# Building from source
Windows 10 or later, an x86-64 CPU with SSE4.2, and a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`. The
Windows 10 or later, an x86-64 CPU with SSE4.2, and a GPU with Vulkan 1.3; `VK_EXT_external_memory_host` is recommended (without it CPU-visible pools get shadow storage,
slower and larger, see `vk_no_host_import` in [settings.md](settings.md)). The
default build targets x86-64-v3 (AVX2/FMA); a CPU without them builds with `--cpu v2` instead and runs slower (see
"Build"). Allow about 60 GB for the work folder. Extraction wants about 55 GB free while it runs and keeps about 35 GB
afterwards.
@@ -78,6 +79,9 @@ of them.
.venv-py314\Scripts\python tools\extract.py
```
`--skip-base-romfs` leaves out the base game's 17 GB RomFS image (`extracted 0␍omfs`): no build step reads it, and
the update merge verifies what it takes from the base game file. Only a build of 1.0.0 itself needs it.
4. Shader translator (no game files; again after a change to its sources, and `tools\make_release.py` stops on an older
one). This publishes `build\xlate\totk_xlate.exe`:
@@ -193,7 +197,7 @@ Vega 7 of a Ryzen 5 4600G at about 34 fps). Long play sessions and the Steam Dec
Requirements:
- Linux 6.7 or later: the write watch uses userfaultfd write protection with `PAGEMAP_SCAN`. SteamOS 3.8 qualifies.
- A Vulkan 1.3 driver with `VK_EXT_external_memory_host` (RADV, NVIDIA).
- A Vulkan 1.3 driver (RADV, NVIDIA). Linux uses shadow storage by default, so `VK_EXT_external_memory_host` is not needed.
- Packages on Arch:
```sh
+1 -1
View File
@@ -356,4 +356,4 @@ each line (`mouse_camera` in `runtime/input.c`); spread a turn over lines a fram
## RenderDoc capture (blocked)
`TOTK_RDOC=<frame>[,...]` (`runtime/rdoc_win.c`; `TOTK_RDOC_DIR`, `TOTK_RDOC_DLL`) loads RenderDoc before `vkCreateInstance`. RenderDoc hides `VK_EXT_external_memory_host`, which the back end requires for guest pool imports (`runtime/vk_memory.c`), so device creation fails under it. A capture needs a copy-based pool fallback first.
`TOTK_RDOC=<frame>[,...]` (`runtime/rdoc_win.c`; `TOTK_RDOC_DIR`, `TOTK_RDOC_DLL`) loads RenderDoc before `vkCreateInstance`. RenderDoc hides `VK_EXT_external_memory_host`, which guest pool imports need (`runtime/vk_memory.c`); without it the back end gives CPU-visible pools shadow storage, as on any GPU without the extension (`vk_no_host_import`). Captures on that path are untested.
+12 -3
View File
@@ -26,6 +26,7 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port
<install folder>/
totk.exe, SDL3.dll, libopus-0.dll, totk_xlate.exe
nvngx_dlss.dll NVIDIA DLSS, downloaded by the setup's DLSS step when the player keeps it ticked
amd_fidelityfx_*_vk.dll AMD FSR 4 (loader and upscaler), downloaded by the setup's FSR step likewise
totk.ini language; the other keys as commented defaults (totk.ini.example)
exefs/, romfs/ extracted from the player's files
shared-fonts/ the Switch system fonts, with Chinese, Korean or Traditional Chinese text
@@ -123,7 +124,15 @@ loads the saves 1.4.3 wrote.
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.
10. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write
10. **FSR** (the window's tick box, on by default when Windows lists an AMD display adapter, `screens.py`
`windows_adapter_names`; or `--fsr`; Windows): download
`amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` from AMD's FSR SDK repository
(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, tag `v2.4.0`, `Kits/FidelityFX/signedbin/`, AMD FSR SDK
license) into the install folder and check their sizes and SHA-256 (`steps.py`, `Fsr`). Both go in only when both
downloaded and matched. `scene_upscaler = fsr4` loads them from the folder of totk.exe and runs FSR 4 where they
offer it for the GPU. Libraries already in the folder are kept; a failed download warns, the game runs without FSR
4, and the next run tries again.
11. **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`).
@@ -181,8 +190,8 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR
install sections, the explanations under More details, the share notice next to Start) in the Sun Valley ttk theme
(`installer/vendor/sv_ttk/`, the platform theme when it does not load), step list with progress, space line,
collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit), finish screen with Open
folder. English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese
or Korean (`guilogic.UI_LANGUAGES`), chosen from the Windows display language (every Chinese, zh-TW and zh-HK
folder. English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese,
Korean or Vietnamese (`guilogic.UI_LANGUAGES`), chosen from the Windows display language (every Chinese, zh-TW and zh-HK
included, gives Simplified Chinese; pt-PT and languages without a catalog give English), switchable in the window;
every sentence is an id in `installer/text/<lang>.json`. The game language starts as the window's when the game has
it; a Chinese or Korean window still starts with English, because that game text needs the Switch shared fonts,
+14 -6
View File
@@ -123,14 +123,22 @@ The Mods tab order decides between a plugin and another mod's patch on the same
plugin site over one of the port's own patches turns that built-in patch off while the mod is on.
The rebuild refuses a plugin when its start-up or the code its redirects reach needs what the port does not give it:
system calls other than the few its start-up needs (memory queries and maps, the clock, debug output), library calls
outside a reviewed list (memory and string functions, the heap, text formatting), threads, services or input; a
redirect that is not one of exlaunch's hook shapes (inline hook, replace hook, call-site rewrite); or two runs of its
start-up that differ in code; or a start-up that crashes the service run or does not return within two minutes. The
row then says **Its plugin ... cannot run in the port** with the reason, and the mod stays off; **Use <mod> without its
code** uses the rest of it, including its other plugins that were built in. UltraCam stays refused: it hooks the graphics API,
system calls other than the few its start-up needs (memory queries and maps, the heap size, the clock, debug output),
or a library call the game itself never makes and a reviewed list does not hold (memory and string functions, the heap,
text formatting, mutexes, the clock, the system language, the SD card's files), such as network sockets or the module
loader. A library call the game makes (threads, input, time, its files) runs on the path the game runs on. A start-up
still gets only the system calls above, so it cannot start a thread or open a service; a redirect that is not one of exlaunch's hook shapes
(inline hook, replace hook, call-site rewrite, a branch into its code from inside a game function, a pointer in the
game's data swapped for one into its code); a write into the game's read-only data or into another module; two runs of
its start-up that differ in code; or a start-up that crashes the service run or does not return within two minutes.
The row then says **Its plugin ... cannot run in the port** with the reason, and the mod stays off; **Use <mod> without
its code** uses the rest of it, including its other plugins that were built in. UltraCam stays refused: it hooks the graphics API,
reads input and opens sockets.
When a start-up calls into the middle of a game function, the rebuild lifts the game again with that address as a
function start and reruns the start-up, up to four times. A plugin that reads or writes files on the SD card gets
the folder `sdcard` in the game's profile folder in its place.
`plugin_trace = 1` in `totk.ini` logs the first call into each of a plugin's hooks (`plugins: hook entry ... reached`).
## Cheats
+7 -1
View File
@@ -115,6 +115,7 @@ Many rows below are developer tools that only act together with another setting
| `mods_without_code` (default `0`) | `1` uses every mod without its code part, as if `mods_no_code` named them all. | See `mods_no_code`. | Caution |
| `pipeline_cache` | Path of the Vulkan pipeline cache file (default `pipeline-cache.bin` beside `totk.exe`). | Moves the cache; a new path starts empty and pipelines are built again. | Caution |
| `profile_dir` | Folder of the game profile, which holds the user account id that save data is named after; the default is a `profile` folder beside `totk.exe`, else the build-time path. | Another folder means a different set of saves. | Save risk |
| `restbl_cache` (default `0`) | `1`: with player mods, the resource size table merged at the last start is served again when nothing it was built from changed: every mod file and shipped table (path, size, write time, file id), the mod list and its order, the RomFS image and `totk.exe` itself. `<profile>/mods/` keeps the table and its `.key`. `0` builds it at every start. | Saves the merge at start: the pass over every mod file and the mods' packs (about 0.9 s with The Second Quest, 3,300 files; more with a texture pack). A changed, added or removed mod file, another order, a new build or game version builds the table again; a damaged kept table or key is built again too. A tool that rewrites a mod file with the same size and write time is not seen. | Caution |
| `romfs` | Folder of the game's RomFS (with `romfs.bin`); a relative path is relative to `totk.exe`'s folder. | Without it, a `romfs` folder next to `totk.exe` is used, else the build-time path; a missing image stops the start with a message. | Save risk |
| `romfs_index` | Path of `romfs-index.bin`, which `tools/romfs_index.py` wrote; the default is beside `totk.exe`. | The index is checked against the image by SHA-256 and size; a mismatch stops the start. | Caution |
| `romfs_mmap` | `1` maps the RomFS image into memory instead of reading it with positional reads. | Changes how the image is read; the log reports when the mapped path is on. | Caution |
@@ -138,6 +139,7 @@ Many rows below are developer tools that only act together with another setting
| Setting | What it does | Effect of changing it | Safety |
| --- | --- | --- | --- |
| `anv_vs_barrier` | A by-region barrier before each draw in a pass whose vertex shader reads a storage buffer. Off by default (`0`). Only Intel GPUs with Mesa's ANV driver on Linux need it: there such reads see stale data and campfire smoke and clouds are drawn as white or dark blobs, or the sky flashes white for single frames (#927). Set `1` to turn it on. | `1` costs about 5% of the frame rate on an Iris Xe and does nothing useful on other GPUs or on Windows; `0` leaves the one-frame glitches on ANV. | Safe |
| `bind_inc` (default `0`) | `1` (or `on`) prepares a draw from what changed since the draw before (the bind ops mark the slots whose bytes they changed) instead of from the whole bound state; `check` prepares every draw as before, takes every decision of `on` beside it, logs each kind of difference once and counts them in a `bind_inc:` line every 300 frames; `0` or `off`: as before. `check` also counts what changed between draws in that line. | Less work per draw on the render thread; a change the marks missed would leave a stale descriptor, a wrong picture or a lost device, which `check` would show first. Off by default: with it on, a GTX 1050 Ti lost the device at one place, after the validation layer reported a descriptor pool reset while a command buffer still used its sets; the cause is not found yet. | Caution |
| `block_views_3d` (default `0`) | `1` gives 3D block-compressed images block views too. | On some AMD cards a GPU write past the end of the image's memory loses the Vulkan device, and the game stops. | Risky |
| `deswizzle` (default `auto`) | Where block-linear textures are deswizzled: `auto` or `gpu` uses a compute pass where the texture's storage is an imported pool and the CPU elsewhere, `cpu` always uses the CPU, `check` uses the GPU and also deswizzles every upload on the CPU and compares the two. | `cpu` brings back the long frames on entering new areas (the replay thread deswizzles every texture); `check` waits for the GPU at every upload and is for testing only. The log names the mode in use. | Caution |
@@ -170,7 +172,9 @@ Many rows below are developer tools that only act together with another setting
| `ub_overlay` (default `1`) | `0` copies each uniform update inside a pass into its buffer at once, ending the pass with a full barrier; `ab` alternates with the `ab` blocks. | With `0` scenes with many updated blocks (the terrain, the sky islands) take longer on the GPU; `TOTK_TRACE=perf` prints how many updates stayed in their pass. | Caution |
| `ub_overlay_out` (default `1`) | `0` copies each uniform update between passes into its buffer at once, behind a full barrier of its own; `ab` alternates with the `ab` blocks. Needs `ub_overlay`. | With `0` a run of updates before a pass costs a full GPU barrier each; `TOTK_TRACE=perf` prints how many updates between passes were overlaid. | Caution |
| `ubo_snapshot` (default `1`) | `0` binds live memory for uniform blocks; `ab` alternates with the `ab` blocks. | Without snapshots late draws read another object's matrix, so objects can be drawn in the wrong place. | Risky |
| `null_attach` (default `0`) | `1` gives the colour slots of a render pass that hold no target, below its last target, a dummy attachment (an `R8_UNORM` image covering the pass, writes masked off, loads and stores `DONT_CARE`) instead of a null image view; the pipelines name that format for those slots. A workaround to try on Intel's legacy Windows driver for 6th-10th generation graphics (HD 520, UHD 620, driver 101.21xx), which crashes inside `vkCmdBeginRendering` after the logo (#1343); untested there, and the crash dumps do not show that the empty slots are the cause. Also in `totk.ini.example`. | One or two dummy images per scene resolution (1.4 MiB at 1600x896, at most 24, freed when the device goes); pipelines with empty slots are built again once. | Caution |
| `vk_no_float64` (default `0`) | `1` clears the 64-bit float feature, so the translator lowers FP64 to FP32. | Shaders change, so the shader cache entries for it are made again; precision of FP64 shaders drops. | Caution |
| `vk_no_host_import` (default `0`) | `1` leaves `VK_EXT_external_memory_host` off even when the GPU has it, so the game takes the path of a GPU without it: every CPU-visible pool gets shadow storage, as under Wine. For testing that path. | Shadow storage costs CPU copies before each submission and more memory than imports. | Caution |
| `vk_ssbo_align` (default unset) | Power of two that storage buffer offsets are treated as needing, to test the unaligned path. | The translator and the draw code round storage offsets down to it; shaders are translated again. | Caution |
| `vk_subgroup` (default `32`) | Subgroup size to pin where the driver allows it. | A value other than 32 changes what the translator is told about the GPU, and shaders are translated again. | Caution |
| `volume_mask_bias` (default `1`) | `0` leaves the game's water volume mask draws (a volume's front faces tested LEQUAL without depth writes, blended ONE/ONE with reverse subtract) without the depth bias toward the viewer that `vk_pipeline.c` gives them; `ab` alternates with `TOTK_AB`. | Puddles and still water then flicker again where the volume's top face lies on the water surface; a test setting. | Caution |
@@ -194,6 +198,7 @@ Many rows below are developer tools that only act together with another setting
| `dlss_reactive` (default `0`) | `1` builds a reactive mask for DLSS where it ran. | Changes how DLSS blends moving areas; a test setting. | Caution |
| `fsr3_debug` (default `0`) | With `scene_upscaler = fsr3`: `1` creates the FSR 3.1 context with the SDK's input checks, whose warnings go to the log (the first 32). | Adds checks to every FSR 3.1 dispatch and log lines. | Caution |
| `fsr3_view` (default `0`) | With `scene_upscaler = fsr3`: `1` shows FSR 3.1's own debug view of its inputs and state in place of the picture. | The frame shows a debug image while it is set. | Caution |
| `fsr4_debug` (default `0`) | With `scene_upscaler = fsr4`: `1` creates the FSR 4 context with the AMD libraries' input checks, whose findings go to the log. | Adds checks to every FSR 4 dispatch and log lines. | Caution |
| `mv_check` | Frame interval; every that many DLSS frames copies the light target and motion images to host memory and logs how well the vectors explain the picture. | Costs a GPU-to-host copy and a comparison on the completion thread at each interval. | Caution |
| `mv_survey` (default `0`) | `1` notes the uniform blocks of each scene draw and compares them with those of earlier frames. | Adds per-draw work and log output. | Caution |
| `mvobj_all` (default `0`) | `1` also lists draws for object motion that read no object blocks (terrain and grass). | More draws are checked and listed, which costs time. | Caution |
@@ -208,7 +213,7 @@ Many rows below are developer tools that only act together with another setting
| `mvprev_grow` (default `1`) | `0` keeps only three banks in the previous-frame tables. | Object motion that depends on the other banks is no longer tracked. | Caution |
| `mvprev_skip` | Hex bank mask of banks left out of the previous-frame copy, replacing the default. | Different banks are tracked, which changes object motion. | Caution |
| `mvprev_trust` | Hex bank mask of banks whose found previous-frame copy is taken without the check. | A copy that does not match is used anyway, which can give wrong motion. | Caution |
| `reflex` (default `off`) | `off`, `on`, or `boost`; enables NVIDIA Reflex Low Latency (`VK_NV_low_latency2`) to reduce system input latency. Read at start. | On NVIDIA GPUs supporting the extension, coordinates simulation and presentation cadence to lower latency, holding frames to the frame limit the pacer uses (`fps_limit`, the monitor's rate for `display`); `boost` keeps GPU clocks high in CPU-bound scenes. Has no effect on non-NVIDIA GPUs. | Safe |
| `reflex` (default `off`) | `off`, `auto`, `on`, or `boost`; reduces system input latency. `on` and `boost` enable NVIDIA Reflex Low Latency (`VK_NV_low_latency2`); `auto` enables Reflex, or AMD Anti-Lag 2 (`VK_AMD_anti_lag`, Mesa RADV and AMD's Windows driver) on a GPU without Reflex. Read at start. | Only one of the two runs; on a GPU with neither extension the setting does nothing. Both coordinate simulation and presentation so input reaches the screen sooner when the GPU is the limit, holding frames to the frame limit the pacer uses (`fps_limit`, the monitor's rate for `display`). `boost` also keeps NVIDIA GPU clocks high in CPU-bound scenes. | Safe |
## Scheduling and host
@@ -245,6 +250,7 @@ These names are code patch sets built into the generated game code (`recomp/patc
| `fixed_res_patch` (default `0`) | Patch set that holds the game's dynamic resolution at 100 percent (the scene tier). | The resolution code switches this set from `dynamic_res` (on at `0`); a manual value is replaced. | Unknown |
| `freecam_patch` (default `0`) | Patch set of the hook in the camera component update behind the free camera (`freecam_pad`, `freecam_key`) on game 1.4.3; the *Free camera* row of the Controls tab. Read at start. | `1` puts the hook in the camera update: while the free camera is off it runs the game's own load and one compare. `0` runs the game's code as shipped: the combo and the key do nothing and the game gets the combo's buttons. | Safe |
| `fov_patch` (default `0`) | Patch set that scales the camera's vertical view angle by the field-of-view setting. | The resolution code switches this set itself whenever the field of view is not 100 percent; a manual value is replaced. | Unknown |
| `lightning_fix` (default `1`) | Patch set on 1.2.1 and 1.4.3 (set `lightning`; 1.4.3 main+0x62b1fc, main+0x62b3d8, main+0x62b51c; 1.2.1 main+0xab8d50, main+0xab9014, main+0xab8f90): in a thunderstorm the world manager's lightning update runs once per frame and draws, each update, a random number for each of three fixed chances, 0.013333 for a distant bolt and 0.01 for a near strike and for the environment's lightning flag that near strikes also set (#1287). The set multiplies each chance by the frame ratio, at most 1, so above 30 fps a storm has as much lightning per second as at 30 fps; at 30 fps and below the chances are the game's own. Game 1.1.0 has no site and keeps the game's code. | `0` runs the game's code: the higher the frame rate, the more distant bolts and lightning flags. Counted on 1.4.3 in one storm (205 s, the reporter's save) with a local build that logs each draw that succeeds: distant bolts 22, 52 and 94 to 96 a minute at 30, 60 and 120 fps with `0`, and 26, 27 and 20 to 24 with `1`; the lightning flag 19, 34 and 64 to 80 a minute of the storm's lightning phase with `0`, 12 to 17 with `1`. Near strikes stayed at 14 to 18 per run at every rate with either value. On 1.2.1 counted from screenshots only (no logging build; a storm in Hyrule Field, one screenshot every 0.2 s, each counted bolt checked by eye): 19 screenshots with a distant bolt a minute at 30 fps, about 61 at 120 fps with `0`, 15 with `1`; the same count on 1.4.3 gives 25 to 26, 65 to 68 and 16 to 20. | Safe |
| `mouse_direct_patch` (default `1`) | Patch set of the hooks in the game's camera code behind `mouse_mode = direct` on game 1.4.3. | `0` stops `mouse_mode = direct` from taking effect; other mouse modes are unaffected. | Safe |
| `optref_guard` (default `1`) | Patch set that treats a negative value in the optional reference at object +0x6b0 (1.4.3 main+0x1bd01c0, 1.2.1 main+0x1622bec) as absent instead of loading through it (#1005). | `0` runs the game's code as shipped: the random crash reading `0xffffffffffffffff` after minutes to hours of play can return. | Risky |
| `patch_output` (default `0`) | Patch set that makes the game use the configured output size for its swapchain and display configuration. | The resolution code switches this set whenever the output differs from the base size; a manual value is replaced. | Unknown |
+2 -1
View File
@@ -8,7 +8,8 @@ from it may be shared.
- Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA recommended: they build the default, faster version), about
60 GB free.
- A GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, with a current driver.
- A GPU with Vulkan 1.3, with a current driver. `VK_EXT_external_memory_host` is recommended: without it the game
runs on shadow storage, which costs memory and frame rate.
- *Tears of the Kingdom* base game (1.0.0) and the 1.1.0, 1.2.1 or 1.4.3 update, dumped from your own Switch as NSP or XCI.
- `prod.keys` dumped from your own Switch. Never send it to anyone, and never paste it into a log or an issue.
+6 -2
View File
@@ -1,5 +1,5 @@
"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR]
[--root DIR] [--temp DIR] [--verify] [--dlss]
[--root DIR] [--temp DIR] [--verify] [--dlss] [--fsr]
A first install needs every option. --firmware names the Switch firmware folder (an unpacked firmware or an emulator's
Contents/registered); the setup extracts the system shared fonts from it when the language is Chinese, Korean or
@@ -9,7 +9,9 @@ extraction has to run again. Prints JSON events on stdout (events.py). Exit code
line, 3 cancelled (Ctrl+C or Ctrl+Break).
--dlss downloads NVIDIA's DLSS library (nvngx_dlss.dll) from NVIDIA's DLSS SDK repository into the install folder on
Windows with an NVIDIA RTX GPU (steps.py, Dlss).
Windows with an NVIDIA RTX GPU (steps.py, Dlss). --fsr downloads AMD's FSR loader and upscaler
(amd_fidelityfx_loader_vk.dll, amd_fidelityfx_upscaler_vk.dll) from AMD's FSR SDK repository into the install folder on
Windows, for scene_upscaler = fsr4; the libraries decide which GPUs get FSR 4 (steps.py, Fsr).
"""
import argparse
import signal
@@ -51,6 +53,8 @@ def main(argv=None):
ap.add_argument('--verify', action='store_true', help='hash every kept file, also those this release made')
ap.add_argument('--dlss', action='store_true', help="download NVIDIA's nvngx_dlss.dll (NVIDIA RTX SDK license) next "
'to the game, for dlaa and the DLSS modes')
ap.add_argument('--fsr', action='store_true', help="download AMD's FSR loader and upscaler DLLs (AMD FSR SDK "
'license) next to the game, for scene_upscaler = fsr4')
args = ap.parse_args(argv)
# The window cancels with Ctrl+Break to the installer's process group (CREATE_NEW_PROCESS_GROUP), which also reaches
+122 -21
View File
@@ -38,8 +38,10 @@ except ImportError:
from . import ini
from . import layout as layouts
from . import recent
from . import screens
from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, UI_LANGUAGES, Catalog, Form, Model,
Process, amount, default_game_language, describe_event, parse_line, windows_ui_language)
Process, amount, default_game_language, describe_event, fsr_default, parse_line,
windows_ui_language)
POLL_MS = 100
GLYPH = {PENDING: '\u25cb', RUNNING: '\u25b6', DONE: '\u2714', SKIPPED: '\u2013', FAILED: '\u2716'}
@@ -114,6 +116,73 @@ def use_sun_valley(root, ui_font):
return True
class ScrollArea(ttk.Frame):
"""A screen's content scrolls while its action bar stays outside the viewport."""
def __init__(self, parent):
super().__init__(parent)
background = ttk.Style(parent).lookup('TFrame', 'background') or parent.winfo_toplevel().cget('background')
self.canvas = tk.Canvas(self, width=1, height=1, borderwidth=0, highlightthickness=0, background=background)
self.scrollbar = ttk.Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.pack(side='left', fill='both', expand=True)
self.content = ttk.Frame(self.canvas)
self.window = self.canvas.create_window((0, 0), window=self.content, anchor='nw')
self.content.bind('<Configure>', lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox('all')))
self.canvas.bind('<Configure>', lambda e: self.canvas.itemconfigure(self.window, width=e.width))
root = self.winfo_toplevel()
root.bind('<FocusIn>', self.reveal_focus, add='+')
for sequence in ('<MouseWheel>',) + (('<Button-4>', '<Button-5>') if sys.platform.startswith('linux') else ()):
root.bind(sequence, self.wheel, add='+')
def contains(self, widget):
return widget is self.canvas or str(widget).startswith(str(self.content) + '.') or widget is self.content
def natural(self):
width = self.content.winfo_reqwidth()
if int(self.canvas.cget('width')) == width:
return False
self.canvas.configure(width=width)
return True
def limit_height(self, height):
height = max(1, height)
scroll = height < self.content.winfo_reqheight()
changed = bool(self.scrollbar.winfo_manager()) != scroll
if changed:
if scroll:
self.scrollbar.pack(side='right', fill='y', before=self.canvas)
else:
self.scrollbar.pack_forget()
if int(self.canvas.cget('height')) != height:
self.canvas.configure(height=height)
changed = True
return changed
def reveal_focus(self, event):
if not self.contains(event.widget) or event.widget is self.canvas:
return
top = event.widget.winfo_rooty() - self.content.winfo_rooty()
bottom = top + event.widget.winfo_height()
visible = self.canvas.canvasy(0)
height = self.canvas.winfo_height()
if top < visible:
self.canvas.yview_moveto(top / max(1, self.content.winfo_height()))
elif bottom > visible + height:
self.canvas.yview_moveto((bottom - height) / max(1, self.content.winfo_height()))
def wheel(self, event):
if not self.contains(event.widget) or event.widget.winfo_class() in ('Text', 'Listbox', 'TCombobox'):
return
if self.canvas.yview() == (0.0, 1.0):
return
units = -1 if event.num == 4 else 1 if event.num == 5 else -int(event.delta / 120)
if not units and event.delta:
units = -1 if event.delta > 0 else 1
self.canvas.yview_scroll(units, 'units')
return 'break'
class App:
def __init__(self, root, ui_lang, layout, run_args=None, rebuild=None):
self.root, self.layout = root, layout
@@ -180,6 +249,7 @@ class App:
self.ui_box.pack(side='left')
self.body = ttk.Frame(root, padding=PAD)
self.body.pack(fill='both', expand=True)
self.scroll_areas = {}
self.frames = {'form': self.build_form(), 'run': self.build_run(), 'finish': self.build_finish()}
self.vars['lang'].set(self.lang_label(self.lang_code))
self.vars['dest'].trace_add('write', lambda *_: self.refresh_form())
@@ -267,13 +337,28 @@ class App:
for), so a screen or language switch does not move the buttons sideways, and the height of the shown screen,
so no screen carries the empty band of a taller one. Every text change that can add lines calls it again, or
pack takes the missing height from the button bars. Without `shrink` the window only grows and a size the user
dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit."""
dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit. A screen
taller than the display scrolls its content while its action bar remains outside the viewport."""
self.root.update_idletasks()
widths_changed = [area.natural() for area in self.scroll_areas.values()]
if any(widths_changed):
self.root.update_idletasks()
widths = [f.winfo_reqwidth() for f in self.frames.values()]
shown = self.frames[self.screen] if self.screen else max(self.frames.values(), key=lambda f: f.winfo_reqheight())
chrome = self.root.winfo_reqheight() - self.body.winfo_reqheight() # the title row above the body
w = max(self.root.winfo_reqwidth(), max(widths) + 2 * PAD)
h = chrome + shown.winfo_reqheight() + 2 * PAD
area = self.scroll_areas.get(self.screen)
if area:
h += area.content.winfo_reqheight() - area.canvas.winfo_reqheight()
# Leave room for window decorations and the desktop's panels. Content scrolls; the footer stays visible.
limit = max(1, self.root.winfo_screenheight() - dpi.px(80))
if area:
changed = area.limit_height(area.content.winfo_reqheight() - max(0, h - limit))
h = min(h, limit)
if changed:
self.root.update_idletasks()
w = max(w, shown.winfo_reqwidth() + 2 * PAD)
# refresh_run calls it on every poll: leave the window alone while nothing grew
if (w, h) == self.fitted and (not shrink or self.root.winfo_height() == h):
return
@@ -281,6 +366,12 @@ class App:
self.root.minsize(w, h)
self.root.geometry(f'{max(w, self.root.winfo_width())}x{h if shrink else max(h, self.root.winfo_height())}')
def scroll_content(self, parent, name):
area = ScrollArea(parent)
area.pack(fill='both', expand=True)
self.scroll_areas[name] = area
return area.content
def notice(self, parent):
w = ttk.Label(parent, style='Notice.TLabel', wraplength=WRAP, justify='left')
self.bind_text(w, 'text', 'ui.notice')
@@ -310,9 +401,10 @@ class App:
self.form_error.pack(side='bottom', anchor='w', pady=(dpi.px(4), 0))
self.update_hint = ttk.Label(f, style='Status.TLabel', wraplength=WRAP, justify='left')
self.update_hint.pack(side='bottom', anchor='w', pady=(dpi.px(8), 0))
self.form_intro = self.label(f, 'ui.intro', wraplength=WRAP, justify='left')
content = self.scroll_content(f, 'form')
self.form_intro = self.label(content, 'ui.intro', wraplength=WRAP, justify='left')
self.form_intro.pack(anchor='w', pady=(0, dpi.px(4)))
grid = ttk.Frame(f)
grid = ttk.Frame(content)
grid.pack(fill='x')
grid.columnconfigure(1, weight=1)
self.section(grid, 0, 'ui.section_files', dpi.px(6))
@@ -344,18 +436,25 @@ class App:
# On by default and named with its source and licence: the player sees what is downloaded and can untick it.
# The source and licence line is the first one under More details.
self.dlss_var = tk.BooleanVar(value=True)
dlss = ttk.Checkbutton(f, variable=self.dlss_var)
dlss = ttk.Checkbutton(content, variable=self.dlss_var)
self.bind_text(dlss, 'text', 'ui.dlss')
dlss.pack(anchor='w', pady=(dpi.px(12), 0))
# Ticked by default with an AMD display adapter only (guilogic.fsr_default); the player can tick it on any GPU.
# Its source and licence line follows DLSS's under More details.
self.fsr_var = tk.BooleanVar(value=fsr_default(screens.windows_adapter_names()))
fsr = ttk.Checkbutton(content, variable=self.fsr_var)
self.bind_text(fsr, 'text', 'ui.fsr')
fsr.pack(anchor='w', pady=(dpi.px(4), 0))
# The explanations stay out of the way until asked for: a link opens them under it
self.details_toggle = ttk.Label(f, style='Link.TLabel', cursor='hand2', takefocus=True)
self.details_toggle = ttk.Label(content, style='Link.TLabel', cursor='hand2', takefocus=True)
self.bind_text(self.details_toggle, 'text', 'ui.more_details')
for seq in ('<Button-1>', '<Return>', '<space>'):
self.details_toggle.bind(seq, lambda _e: self.toggle_details())
self.details_toggle.pack(anchor='w', pady=(dpi.px(8), 0))
self.details = ttk.Frame(f) # packed after the link when open; no holder frame, as an emptied Tk frame keeps
self.details = ttk.Frame(content) # packed after the link when open; no holder frame, as an emptied Tk frame keeps
# the height its last child gave it
for id in ('ui.dlss_help', 'ui.formats_help', 'ui.compressed_help', 'ui.firmware_help', 'ui.keys_private'):
for id in ('ui.dlss_help', 'ui.fsr_help', 'ui.formats_help', 'ui.compressed_help', 'ui.firmware_help',
'ui.keys_private'):
self.label(self.details, id, style='Muted.TLabel', wraplength=WRAP - dpi.px(16),
justify='left').pack(anchor='w', pady=(dpi.px(6), 0))
self.details_open = False
@@ -379,14 +478,15 @@ class App:
self.cancel_button.pack(side='right')
self.log_toggle = self.button(bar, 'ui.show_log', self.toggle_log)
self.log_toggle.pack(side='left')
self.run_header = ttk.Label(f, font=(self.ui_font, 11, 'bold'))
content = self.scroll_content(f, 'run')
self.run_header = ttk.Label(content, font=(self.ui_font, 11, 'bold'))
self.run_header.pack(anchor='w')
self.step_rows = {}
self.steps_box = ttk.Frame(f)
self.steps_box = ttk.Frame(content)
self.steps_box.pack(fill='x', pady=dpi.px(8))
self.phase_label = ttk.Label(f, wraplength=WRAP, justify='left')
self.phase_label = ttk.Label(content, wraplength=WRAP, justify='left')
self.phase_label.pack(anchor='w')
bar_holder = ttk.Frame(f)
bar_holder = ttk.Frame(content)
bar_holder.pack(fill='x', pady=(dpi.px(4), dpi.px(6)))
self.bar = ttk.Progressbar(bar_holder, mode='determinate', maximum=1000)
self.bar.pack(fill='both', expand=True)
@@ -396,11 +496,11 @@ class App:
# holder follows it.
bar_holder.pack_propagate(False)
bar_holder.configure(height=dpi.px(22))
self.space_label = ttk.Label(f, wraplength=WRAP, justify='left')
self.space_label = ttk.Label(content, wraplength=WRAP, justify='left')
self.space_label.pack(anchor='w')
self.warn_label = ttk.Label(f, wraplength=WRAP, justify='left', foreground='#9a6700')
self.warn_label = ttk.Label(content, wraplength=WRAP, justify='left', foreground='#9a6700')
self.warn_label.pack(anchor='w')
self.log_frame = ttk.Frame(f)
self.log_frame = ttk.Frame(content)
self.log = tk.Text(self.log_frame, height=10, wrap='word', state='disabled', font=(self.mono_font, 9))
scroll = ttk.Scrollbar(self.log_frame, command=self.log.yview)
self.log.configure(yscrollcommand=scroll.set)
@@ -420,13 +520,14 @@ class App:
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, dpi.px(8)))
self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=WRAP, justify='left')
content = self.scroll_content(f, 'finish')
self.finish_title = ttk.Label(content, style='Title.TLabel', wraplength=WRAP, justify='left')
self.finish_title.pack(anchor='w')
self.finish_text = ttk.Label(f, wraplength=WRAP, justify='left')
self.finish_text = ttk.Label(content, wraplength=WRAP, justify='left')
self.finish_text.pack(anchor='w', pady=dpi.px(8))
self.finish_steps = ttk.Frame(f)
self.finish_steps = ttk.Frame(content)
self.finish_steps.pack(fill='x', pady=(0, dpi.px(8)))
self.finish_notice = self.notice(f)
self.finish_notice = self.notice(content)
self.finish_notice.pack(fill='x', pady=(dpi.px(8), 0))
return f
@@ -435,7 +536,7 @@ class App:
def form(self):
return Form(base=self.vars['base'].get(), update=self.vars['update'].get(), keys=self.vars['keys'].get(),
firmware=self.vars['firmware'].get(), lang=self.selected_lang(), dest=self.vars['dest'].get(),
dlss=self.dlss_var.get())
dlss=self.dlss_var.get(), fsr=self.fsr_var.get())
def set_prefill(self, name, value):
self.programmatic = True
@@ -711,7 +812,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', 'shapes', 'dlss', 'cleanup']}
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'fsr', 'cleanup']}
SAMPLE_RUN = [
SAMPLE_START,
{'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}},
+15 -4
View File
@@ -24,20 +24,20 @@ from . import state as statefile
from .events import render
TEXT = Path(__file__).resolve().parent / 'text'
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans', 'de', 'fr', 'es', 'it', 'nl', 'ja', 'ko')
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans', 'de', 'fr', 'es', 'it', 'nl', 'ja', 'ko', 'vi')
# 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': '简体中文',
'de': 'Deutsch', 'fr': 'Français', 'es': 'Español', 'it': 'Italiano', 'nl': 'Nederlands',
'ja': '日本語', 'ko': '한국어'}
'ja': '日本語', 'ko': '한국어', 'vi': 'Tiếng Việt'}
STEP_ORDER = ('check', 'kit', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss',
'cleanup')
'fsr', '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_PT_BR = 0x0416 # Portuguese (Brazil), the whole LANGID: Portugal's Portuguese stays English
# primary language id in a Windows LANGID -> window language, for the languages whose every region gets the same text.
# Every Chinese gets Simplified Chinese: the setup has no Traditional Chinese text, as the in-game menu has none.
PRIMARY_LANGS = {0x04: 'zh-Hans', 0x19: 'ru', 0x07: 'de', 0x0c: 'fr', 0x0a: 'es', 0x10: 'it', 0x13: 'nl', 0x11: 'ja',
0x12: 'ko'}
0x12: 'ko', 0x2a: 'vi'}
# window language -> the game language the form starts with (default_game_language)
GAME_LANGUAGE_FOR_UI = {'ru': 'ru', 'de': 'de', 'fr': 'fr', 'es': 'es', 'it': 'it', 'nl': 'nl', 'ja': 'ja'}
@@ -142,6 +142,14 @@ def amount(cat, done, total, unit):
# ---- the form ----------------------------------------------------------------------------------------------------
def fsr_default(adapters):
"""Whether the window ticks Download AMD FSR at start: only with an AMD display adapter among adapters (their
names, screens.windows_adapter_names). The step downloads on any GPU when ticked (steps.Fsr); on other GPUs, and
when no adapter could be listed, the box starts unticked, so a player without an AMD GPU never downloads AMD's
libraries (about 36 MB) without choosing to."""
return any('AMD' in a.upper() or 'RADEON' in a.upper() for a in adapters)
@dataclass
class Form:
base: str = ''
@@ -151,6 +159,7 @@ class Form:
lang: str = ''
dest: str = ''
dlss: bool = False
fsr: bool = False
def installed_state(self):
"""The recorded state of the install folder (totk-install.json), or None. Never raises."""
@@ -203,6 +212,8 @@ class Form:
cmd.append('--verify')
if self.dlss:
cmd.append('--dlss')
if self.fsr:
cmd.append('--fsr')
return cmd
+4
View File
@@ -57,9 +57,12 @@ static int x86_64_v3(void) {
return (c & (1u << 5)) != 0; // LZCNT (ABM)
}
// stdout is a pipe, so it is fully buffered: each part is flushed before the next call that can crash, and a probe
// that a Vulkan layer or driver kills still hands the installer what it found (installer/steps.py Check.probe_host).
int main(void) {
printf("{\"x86_64_v2\": %s, \"x86_64_v3\": %s, ", x86_64_v2() ? "true" : "false",
x86_64_v3() ? "true" : "false");
fflush(stdout);
void *lib = open_lib();
PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)lib_sym(lib, "vkGetInstanceProcAddr") : NULL;
if (!gipa) {
@@ -67,6 +70,7 @@ int main(void) {
return 0;
}
printf("\"loader\": true, ");
fflush(stdout);
PFN_vkCreateInstance create = (PFN_vkCreateInstance)gipa(NULL, "vkCreateInstance");
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "totk-install",
.apiVersion = VK_API_VERSION_1_3};
+10 -5
View File
@@ -1,7 +1,7 @@
"""totk.ini: set the game language and keep everything else (keys and syntax as runtime/cfg.c reads them).
A new file starts from totk.ini.example, whose lines are all commented defaults. The language goes into `lang`
(a Switch language code, runtime/ov_system.c): an active `lang = ...` line is rewritten in place, else the commented
(a Switch language code, runtime/ov_system.c): the last active `lang = ...` line is rewritten in place, else the commented
`# lang = ...` line of the example is activated, else the line is added to [language] (created at the end if
missing). Other lines, comments and line order stay as they are.
"""
@@ -32,8 +32,9 @@ def set_language(text, lang):
"""text with `lang = <lang>` (an alias written as its canonical code); see the module docstring."""
lang = canonical_language(lang)
lines = text.splitlines()
for i, line in enumerate(lines):
m = ACTIVE.match(line)
# runtime/cfg.c add gives the last non-empty value priority, regardless of section or the totk_ prefix.
for i in range(len(lines) - 1, -1, -1):
m = ACTIVE.match(lines[i])
if m:
lines[i] = f'{m.group(1)}lang{m.group(2)}{lang}'
return '\n'.join(lines) + '\n'
@@ -53,10 +54,14 @@ def set_language(text, lang):
def get_language(text):
for line in text.splitlines():
for line in reversed(text.splitlines()):
m = ACTIVE.match(line)
if m:
return m.group(3)
value = m.group(3)
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
if value: # cfg.c add ignores empty values, including an empty quoted string
return value
return None
+1
View File
@@ -28,6 +28,7 @@ static void fail(void)
{ LANG_DUTCH, LAUNCHER_TITLE_NL, LAUNCHER_PYTHON_MISSING_NL },
{ LANG_JAPANESE, LAUNCHER_TITLE_JA, LAUNCHER_PYTHON_MISSING_JA },
{ LANG_KOREAN, LAUNCHER_TITLE_KO, LAUNCHER_PYTHON_MISSING_KO },
{ LANG_VIETNAMESE, LAUNCHER_TITLE_VI, LAUNCHER_PYTHON_MISSING_VI },
{ LANG_CHINESE, LAUNCHER_TITLE_ZH_HANS, LAUNCHER_PYTHON_MISSING_ZH_HANS },
};
LANGID ui = GetUserDefaultUILanguage();
+1 -1
View File
@@ -1,4 +1,4 @@
"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game
r"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game
version starts with the form filled in.
{"format": 1, "dest": ..., "base": ..., "update": ..., "keys": ..., "firmware": ...}
+29 -2
View File
@@ -94,6 +94,28 @@ def windows_displays():
return out
def windows_adapter_names():
"""The names of the display adapters Windows lists (EnumDisplayDevicesW, "AMD Radeon RX 9060 XT"), without
starting Vulkan; [] elsewhere or when the call fails. The setup window decides its defaults by them before the host
check has run."""
if os.name != 'nt':
return []
try:
user32 = ctypes.WinDLL('user32')
out, i = [], 0
while i < 64:
dev = DISPLAY_DEVICEW()
dev.cb = ctypes.sizeof(dev)
if not user32.EnumDisplayDevicesW(None, i, ctypes.byref(dev), 0):
break
i += 1
if dev.DeviceString and dev.DeviceString not in out:
out.append(dev.DeviceString)
return out
except (OSError, AttributeError, ValueError):
return []
XRANDR = re.compile(r'\sconnected\s+(?:primary\s+)?(\d+)x(\d+)\+')
@@ -132,11 +154,16 @@ def displays():
# ---- totk.ini (runtime/cfg.c reads the same keys, in any section, with or without the totk_ prefix)
def ini_value(text, name):
"""The last nonempty value, with matching quotes removed, as runtime/cfg.c cfg_load and add read it."""
value = None
for line in text.splitlines():
m = re.match(rf'^\s*(?:totk_)?{name}\s*=\s*([^\s#;]*)', line, re.IGNORECASE)
m = re.match(rf'^\s*(?:totk_)?{re.escape(name)}\s*=(.*)$', line, re.IGNORECASE)
if m:
value = m.group(1)
candidate = m.group(1).strip()
if len(candidate) >= 2 and candidate[0] == candidate[-1] == '"':
candidate = candidate[1:-1]
if candidate:
value = candidate
return value
+15 -2
View File
@@ -36,10 +36,23 @@ def load(dest):
data = json.loads(path.read_text(encoding='utf-8'))
except (OSError, ValueError):
raise StateError('state.unreadable', path) from None
if not isinstance(data, dict) or not isinstance(data.get('steps'), dict):
if not isinstance(data, dict):
raise StateError('state.unreadable', path)
if data.get('format', 0) > FORMAT:
version = data.get('format', 0)
if type(version) is not int or version < 0:
raise StateError('state.unreadable', path)
if version > FORMAT:
raise StateError('state.newer_format', path)
# The GUI and resume planner read these fields before running a step. A JSON value of the wrong type must take
# the same error path as unreadable JSON, rather than raising from their comparisons or dict lookups.
for name in ('release', 'lang', 'version'):
if name in data and not isinstance(data[name], str):
raise StateError('state.unreadable', path)
for name in ('steps', 'inputs'):
records = data.get(name, {} if name == 'inputs' else None)
if not isinstance(records, dict) or any(not isinstance(record, dict) for record in records.values()):
raise StateError('state.unreadable', path)
data.setdefault('inputs', {}) # older records may omit it; the extraction step expects a dictionary
return data
+265 -25
View File
@@ -1,5 +1,5 @@
"""The eleven setup steps of docs/installer.md: check, kit, fonts, extract, lift, compile, prepare, pc_prompts, shapes,
dlss, cleanup.
"""The twelve setup steps of docs/installer.md: check, kit, fonts, extract, lift, compile, prepare, pc_prompts,
shapes, dlss, fsr, 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,7 +8,8 @@ recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and tools/prepar
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/,
and its DLLs, nvngx_dlss.dll (with --dlss), amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll (with
--fsr), romfs-index.bin, romfs-patches/, romfs-patches-xbox/,
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, and on Windows build-kit/ (Kit): the release
@@ -41,6 +42,11 @@ import time
import urllib.request
from pathlib import Path
if os.name == 'nt':
import winreg
else:
winreg = None
from . import ini, screens
from . import layout as layouts
from .layout import EXE, SUPPORTED, version_tag
@@ -59,6 +65,7 @@ TEMP_NEED = 3 * GiB # generated C (about 0.9 GB) and objects
KIT_NEED = 1 * GiB # the build kit (Kit), about 0.65 GB
HOSTCHECK = Path(__file__).resolve().parent / 'hostcheck.c'
STAMP = '.install-key'
PLUGIN_ENTRY_ROUNDS = 4 # plugin lifts at most: each finds where an init called into main past a function start
# ---- helpers
@@ -124,6 +131,79 @@ def kill_tree(proc):
proc.kill()
def parse_host(text):
"""The host check's JSON object, or None when it did not finish (a crash leaves the parts it flushed)."""
try:
host = json.loads(text)
except ValueError:
return None
return host if isinstance(host, dict) and 'devices' in host else None
def exit_code(code):
"""A process exit code as Windows reports crashes (0xC0000005 for an access violation), else as a number."""
if os.name == 'nt' and code is not None and (code < 0 or code >= 0xC0000000):
return f'0x{code & 0xFFFFFFFF:08X}'
return str(code)
def layer_manifests():
"""Implicit Vulkan layer manifests where the Khronos loader looks for them (its docs, LoaderLayerInterface.md,
"Layer Discovery"): the folders in VK_IMPLICIT_LAYER_PATH or VK_ADD_IMPLICIT_LAYER_PATH, then on Windows the
manifests HKLM and HKCU\\SOFTWARE\\Khronos\\Vulkan\\ImplicitLayers enable with a DWORD 0, read in the 64-bit view
the 64-bit probe and game use; elsewhere the implicit_layer.d folders. Layers a driver registers under its display
adapter's key are not listed."""
found = []
for var in ('VK_IMPLICIT_LAYER_PATH', 'VK_ADD_IMPLICIT_LAYER_PATH'):
for part in filter(None, os.environ.get(var, '').split(os.pathsep)):
p = Path(part)
found += sorted(p.glob('*.json')) if p.is_dir() else [p]
if winreg:
for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
try:
key = winreg.OpenKey(root, r'SOFTWARE\Khronos\Vulkan\ImplicitLayers', 0,
winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
except OSError:
continue
with key:
i = 0
while True:
try:
path, enabled, _ = winreg.EnumValue(key, i)
except OSError:
break
i += 1
if enabled == 0: # a DWORD 0 enables the manifest, anything else skips it
found.append(Path(path))
else:
home = Path.home()
config = [os.environ.get('XDG_CONFIG_HOME') or home / '.config',
*(os.environ.get('XDG_CONFIG_DIRS') or '/etc/xdg').split(':'), '/usr/local/etc', '/etc']
data = [os.environ.get('XDG_DATA_HOME') or home / '.local' / 'share',
*(os.environ.get('XDG_DATA_DIRS') or '/usr/local/share:/usr/share').split(':')]
for base in filter(None, config + data):
found += sorted((Path(base) / 'vulkan' / 'implicit_layer.d').glob('*.json'))
return found
def implicit_vulkan_layers():
"""(layer name, manifest path) of each readable implicit Vulkan layer manifest of layer_manifests(), for the
search for the layer that crashes the host check. A manifest the loader cannot read loads no layer and is left
out; a manifest listed twice counts once."""
layers = []
for path in dict.fromkeys(layer_manifests()):
try:
manifest = json.loads(path.read_text(encoding='utf-8-sig'))
except (OSError, ValueError):
continue
entries = (manifest.get('layers') or [manifest.get('layer')]) if isinstance(manifest, dict) else []
for entry in entries:
name = entry.get('name') if isinstance(entry, dict) else None
if isinstance(name, str) and (name, path) not in layers:
layers.append((name, path))
return layers
def linux_glibc():
"""(major, minor) of the C library this Linux process runs on, None elsewhere or when it is not glibc."""
try:
@@ -423,8 +503,19 @@ class Check(Step):
return {}
def host(self, ctx):
"""Builds and runs the host check once per run: key() asks first and run() reports, so a failure is kept on
ctx and raised again rather than a crashing probe and its retries running twice."""
if getattr(ctx, 'host', None) is not None:
return
if getattr(ctx, 'host_error', None) is not None:
raise ctx.host_error
try:
self.check_host(ctx)
except InstallError as e:
ctx.host_error = e
raise
def check_host(self, ctx):
layout, work = ctx.layout, ctx.temp / 'check'
glibc = linux_glibc()
if glibc and glibc < GLIBC_NEEDED and not layout.dev:
@@ -443,12 +534,7 @@ class Check(Step):
if r.returncode:
ctx.reporter.log(r.stdout + r.stderr)
raise InstallError('check.toolchain_broken', detail=(r.stderr or r.stdout).strip()[-400:])
r = subprocess.run([str(exe)], capture_output=True, text=True, errors='replace')
try:
host = json.loads(r.stdout)
except ValueError:
raise InstallError('check.host_probe_failed', code=r.returncode) from None
ctx.reporter.log(f'host: {r.stdout.strip()}')
host = self.probe_host(ctx, exe)
if not host['x86_64_v2']:
raise InstallError('check.cpu_too_old')
# v3 is the faster build; v2 runs on CPUs without AVX2/FMA (runtime/fma.c supplies the fused multiply-add).
@@ -468,6 +554,60 @@ class Check(Step):
ctx.reporter.warning('warn.kernel_old', version='.'.join(map(str, kernel)))
ctx.host = host
# Windows refuses to start a program a policy does not trust (issue #875): Smart App Control and other App Control
# policies (4551 "An Application Control policy has blocked this file"; 4556-4559 and 4580-4583 the same with the
# reputation verdict, among them 4559 "Unable to contact reputation service for unknown file"), group policy (1260
# "This program is blocked by group policy") and an antivirus that flags or removes the file (225, 226). hostcheck
# is the first program the setup builds on this PC; totk.exe is built the same way and unsigned too, so the install
# cannot go on.
BLOCKED_WINERRORS = {225, 226, 1260, 4551, 4556, 4557, 4558, 4559, 4580, 4581, 4582, 4583}
LAYER_TRIES = 16 # implicit layers tried one by one in the search for the one that crashes the probe
def probe_host(self, ctx, exe):
"""Runs the host check check_host() built and returns its JSON. A probe that crashes inside Vulkan is run again
with the implicit Vulkan layers off (VK_LOADER_LAYERS_DISABLE=~implicit~, Vulkan loader 1.3.234 or later):
overlays, recorders and tuning tools install such layers, and a broken one kills every Vulkan program at
vkCreateInstance (issue #1345, exit code 0xC0000005 after "Checking the processor and the graphics card").
When that run passes, each listed layer is turned off alone to name the one that crashes. The install stops
either way: totk.exe --prepare-shaders in the prepare step and the game itself load the same layers
(runtime/vk_device.c create_instance), so going on would fail after lift and compile."""
rep = ctx.reporter
r = self.run_probe(exe)
host = parse_host(r.stdout)
if host is not None:
rep.log(f'host: {r.stdout.strip()}')
return host
code = exit_code(r.returncode)
rep.log(f'host: the check stopped with exit code {code}; it printed {r.stdout.strip()!r}')
if '"loader": true' not in r.stdout:
raise InstallError('check.host_probe_failed', code=code)
retry = self.run_probe(exe, dict(os.environ, VK_LOADER_LAYERS_DISABLE='~implicit~'))
if parse_host(retry.stdout) is None:
rep.log(f'host: without implicit Vulkan layers too: exit code {exit_code(retry.returncode)}, '
f'{retry.stdout.strip()!r}')
raise InstallError('check.vulkan_crash', code=code)
layers = implicit_vulkan_layers()
rep.log(f'host: passes with the implicit Vulkan layers off; installed: '
f'{", ".join(f"{n} ({p})" for n, p in layers) or "none listed"}')
culprits = [(name, path) for name, path in layers[:self.LAYER_TRIES]
if parse_host(self.run_probe(exe, dict(os.environ, VK_LOADER_LAYERS_DISABLE=name)).stdout)]
if culprits:
rep.log(f'host: passes without {", ".join(n for n, _ in culprits)}')
raise InstallError('check.vulkan_layer_crash', code=code,
layers=', '.join(f'{n} ({p})' for n, p in culprits),
disable=','.join(n for n, _ in culprits))
raise InstallError('check.vulkan_layers_crash', code=code,
layers=', '.join(f'{n} ({p})' for n, p in layers) or '?')
def run_probe(self, exe, env=None):
try:
return subprocess.run([str(exe)], capture_output=True, text=True, errors='replace', env=env)
except OSError as e:
if getattr(e, 'winerror', None) in self.BLOCKED_WINERRORS:
raise InstallError('check.host_blocked', path=str(exe), detail=e.strerror or str(e)) from None
raise InstallError('check.host_probe_failed',
code=f'{getattr(e, "winerror", None) or e.errno}: {e.strerror or e}') from None
def inputs(self, ctx):
"""Open both files with the keys as the extraction will. Returns the bytes of both Program NCAs."""
o = ctx.options
@@ -1108,20 +1248,39 @@ class Lift(Step):
lift_plugins = []
if plugins:
listed = ['--plugins', ','.join(str(f) for f in plugins)]
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', patches] + listed, parse)
if not code:
code, log = run_tool(ctx, 'lift', layout.tools / 'build_game.py', build_args(ctx, gen))
if not code:
# the service run's totk.exe loads its DLLs from its own folder, as the installed one does
for dll in layout.dlls:
replace_file(dll, ctx.temp / 'build' / dll.name)
code, log = run_tool(ctx, 'lift', layout.tools / 'exefs_plugins.py', [
'--exe', ctx.temp / 'build' / ('totk' + EXE), '--out', ctx.temp / 'plugins', '--mods',
ctx.dest / 'mods', '--patches', patches, '--patches-out', ctx.temp / 'patches-plugins.txt',
'--status', plugins_status(ctx)])
# exit 1 with a status file: refused plugins, their reasons in it; the rest goes on
if plugins_status(ctx).is_file() and (ctx.temp / 'patches-plugins.txt').is_file():
code = 0
# An init that calls into main where the lift has no function start crashes its service run; the tool
# names those addresses (--entries-out), and one more lift with them as `entry` lines lets the init go on
# (Zonai Fieldworks calls the second word of a 1.4.3 function). Each round adds what the last one found.
lift_patches, found = patches, []
for _ in range(PLUGIN_ENTRY_ROUNDS):
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', lift_patches] + listed,
parse)
if not code:
code, log = run_tool(ctx, 'lift', layout.tools / 'build_game.py', build_args(ctx, gen))
if not code:
# the service run's totk.exe loads its DLLs from its own folder, as the installed one does
for dll in layout.dlls:
replace_file(dll, ctx.temp / 'build' / dll.name)
entries_file = ctx.temp / 'plugin-entries.txt'
entries_file.unlink(missing_ok=True)
code, log = run_tool(ctx, 'lift', layout.tools / 'exefs_plugins.py', [
'--exe', ctx.temp / 'build' / ('totk' + EXE), '--out', ctx.temp / 'plugins', '--mods',
ctx.dest / 'mods', '--exefs', ctx.dest / 'exefs', '--patches', lift_patches,
'--patches-out', ctx.temp / 'patches-plugins.txt', '--status', plugins_status(ctx),
'--entries-out', entries_file])
# exit 1 with a status file: refused plugins, their reasons in it; the rest goes on
if plugins_status(ctx).is_file() and (ctx.temp / 'patches-plugins.txt').is_file():
code = 0
if code:
break
new = [line for line in (entries_file.read_text(encoding='utf-8').splitlines()
if entries_file.is_file() else []) if line and line not in found]
if not new:
break
found += new
lift_patches = ctx.temp / 'patches-entries.txt'
lift_patches.write_text(Path(patches).read_text(encoding='utf-8') + '\n' + '\n'.join(found) + '\n',
encoding='utf-8')
if code:
drop([plugins_status(ctx)])
skipped['warn.plugins_skipped'] = log
@@ -1603,7 +1762,87 @@ class Dlss(Step):
return {'installed': DLSS_VERSION}
# ---- 8. clean up
# ---- 8. AMD FSR
# AMD's FSR 4 for scene_upscaler = fsr4 (runtime/vk_ffx.c): the ffx-api loader and the upscaler effect, which the
# loader finds next to itself. AMD's FSR SDK license lets them be redistributed in binary form with its notice
# (THIRD_PARTY_NOTICES.md); the setup still does not ship them: with --fsr it downloads AMD's signed copies from the SDK
# repository at a pinned tag and checks their hashes. The game runs without them; scene_upscaler = fsr4 then does
# nothing.
FSR_VERSION = '2.4.0' # the FSR SDK release; the upscaler DLL is FSR 4.1.2 (FSR 3.1.6 inside goes unused)
FSR_BASE = (f'https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/v{FSR_VERSION}/'
'Kits/FidelityFX/signedbin/')
FSR_FILES = ( # name, size, SHA-256
('amd_fidelityfx_loader_vk.dll', 39184, '38a56a01fb3565c0757d9f5c1e4e69de4b65e5f2e5769b323b200dc1f142bab9'),
('amd_fidelityfx_upscaler_vk.dll', 36135696, '4a7e895af6e0b615d40a84d59eb8c2b1054ad91cdd0c739567940270d51bdab7'),
)
FSR_LICENSE = f'https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/blob/v{FSR_VERSION}/docs/license.md'
class Fsr(Step):
"""With --fsr on Windows: AMD's FSR loader and upscaler next to totk.exe; the game pins FSR 4 where they offer it
for the GPU. Libraries the player put there (other versions) are kept. A failed download warns and is tried again
on the next run; the game runs without them."""
id = 'fsr'
def key(self, ctx):
if not getattr(ctx.options, 'fsr', False):
return fingerprint('fsr-2', 'off')
return fingerprint('fsr-2', FSR_VERSION, *(sha for _, _, sha in FSR_FILES))
def current(self, ctx, record):
if record.get('failed'):
return False
return not record.get('installed') or all((ctx.dest / name).is_file() for name, _, _ in FSR_FILES)
def run(self, ctx):
if not getattr(ctx.options, 'fsr', False):
return {}
if os.name != 'nt':
return {'skipped': 'not_windows'}
rep = ctx.reporter
present = [ctx.dest / name for name, _, _ in FSR_FILES if (ctx.dest / name).is_file()]
if present:
if all((ctx.dest / name).is_file() and file_sha256(ctx.dest / name) == sha for name, _, sha in FSR_FILES):
return {'installed': FSR_VERSION}
# A set the player put there (or half of one): kept as it is, the loader and its effect belong together
rep.warning('warn.fsr_kept', path=str(present[0]))
return {'kept': True}
total, done = sum(size for _, size, _ in FSR_FILES), 0
rep.progress('fsr', 'download', 0, total, 'bytes', force=True)
rep.log(f'fsr: {FSR_BASE} (license {FSR_LICENSE})')
parts = []
try:
for name, size, sha in FSR_FILES:
url, part = FSR_BASE + name, ctx.temp / (name + '.part')
parts.append(part)
part.parent.mkdir(parents=True, exist_ok=True)
h, got = hashlib.sha256(), 0
with urllib.request.urlopen(url, timeout=60) as r, open(part, 'wb') as f:
while block := r.read(1 << 20):
f.write(block)
h.update(block)
got += len(block)
rep.progress('fsr', 'download', min(done + got, total), total, 'bytes')
if got != size or h.hexdigest() != sha:
raise OSError(f'{name}: {got} bytes, SHA-256 {h.hexdigest()[:16]}, not the expected file')
done += size
# both downloaded and checked: only then into the install folder, so it never holds half a set
for (name, _, _), part in zip(FSR_FILES, parts):
replace_file(part, ctx.dest / name)
remove(part)
# urllib's errors, timeouts and a bad file; a connection cut mid-file raises http.client.IncompleteRead,
# which is not an OSError
except (OSError, http.client.HTTPException) as e:
for part in parts:
remove(part)
rep.warning('warn.fsr_download_failed', url=FSR_BASE, detail=str(e)[:300])
return {'failed': True}
return {'installed': FSR_VERSION}
# ---- 9. clean up
class Cleanup(Step):
id = 'cleanup'
@@ -1685,4 +1924,5 @@ def romfs_problem(romfs, expected):
def all_steps():
return [Check(), Kit(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Cleanup()]
return [Check(), Kit(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Fsr(),
Cleanup()]
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Tastatur- und Maussymbole zeichnen",
"step.shapes": "Spielbildschirme für deine Monitore anordnen",
"step.dlss": "NVIDIA DLSS herunterladen",
"step.fsr": "AMD FSR 4 herunterladen",
"step.cleanup": "Aufräumen",
"phase.check.host": "Prozessor und Grafikkarte prüfen",
"phase.check.verify": "Bereits installierte Dateien prüfen",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Shader-Cache in eine Datei packen",
"phase.shapes.layouts": "Bildschirmlayouts und Tastensymbole für jedes Bildschirmformat schreiben",
"phase.dlss.download": "nvngx_dlss.dll aus NVIDIAs DLSS SDK herunterladen",
"phase.fsr.download": "Die FSR-4-Bibliotheken aus AMDs FSR SDK herunterladen",
"phase.cleanup.ini": "totk.ini schreiben",
"phase.cleanup.temp": "Temporäre Dateien entfernen",
"cli.usage": "Ungültige Befehlszeile: {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "Der mitgelieferte Compiler funktioniert nicht: {detail}",
"check.glibc_old": "Die C-Bibliothek dieses Systems ist glibc {version}; der Compiler des Setups braucht {need} oder neuer (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 und neuer haben sie). Ein Systemupdate behebt das.",
"check.host_probe_failed": "Die Computerprüfung ist nicht gelaufen (Exit-Code {code}).",
"check.host_blocked": "Windows hat ein Programm blockiert, das das Setup auf diesem PC erstellt hat ({path}): {detail}. Smart App Control, eine App-Control-Richtlinie oder ein Virenscanner blockiert unsignierte Programme; das Spiel selbst wird genauso auf diesem PC erstellt und würde ebenfalls blockiert. Erlaube den Setup-Ordner in deinem Virenscanner oder schalte Smart App Control in der Windows-Sicherheit (App- und Browsersteuerung) aus und starte das Setup erneut.",
"check.vulkan_crash": "Der Grafiktreiber ist abgestürzt, als das Setup nach den Grafikkarten gefragt hat (Exit-Code {code}), auch mit ausgeschalteten Vulkan-Layern anderer Programme. Installiere den neuesten Treiber für deine Grafikkarte.",
"check.vulkan_layer_crash": "Ein Vulkan-Layer, den ein anderes Programm installiert hat, lässt Vulkan-Programme auf diesem PC abstürzen (Exit-Code {code}), und das Spiel würde beim Start genauso abstürzen. Der Layer: {layers}. Aktualisiere oder deinstalliere das Programm, zu dem er gehört (der Pfad zeigt seinen Ordner), oder schalte den Layer aus: Setze für dein Benutzerkonto die Umgebungsvariable VK_LOADER_LAYERS_DISABLE auf {disable}. Starte danach das Setup erneut.",
"check.vulkan_layers_crash": "Ein Vulkan-Layer, den ein anderes Programm installiert hat, lässt Vulkan-Programme auf diesem PC abstürzen (Exit-Code {code}): Mit allen solchen Layern ausgeschaltet läuft die Prüfung durch, und mit ihnen würde das Spiel beim Start genauso abstürzen. Die installierten Layer einzeln auszuschalten hat ihn nicht eingegrenzt. Installierte Layer: {layers}. Aktualisiere oder deinstalliere die Overlay-, Aufnahme- oder Tuning-Programme darunter, oder schalte alle solchen Layer aus: Setze für dein Benutzerkonto die Umgebungsvariable VK_LOADER_LAYERS_DISABLE auf ~implicit~ (das schaltet auch Overlays wie das von Steam in jedem Vulkan-Spiel aus). Starte danach das Setup erneut.",
"check.cpu_too_old": "Diesem Prozessor fehlt x86-64-v2 (SSE4.2, POPCNT und CMPXCHG16B), die älteste Stufe, für die das Spiel gebaut wird. Intel Nehalem (2008) oder AMD Bulldozer (2011) und neuer haben sie.",
"check.vulkan_missing": "Es ist kein Vulkan-Treiber installiert. Installiere den neuesten Treiber für deine Grafikkarte.",
"check.vulkan_no_device": "Vulkan findet keine Grafikkarte. Installiere den neuesten Treiber für deine Grafikkarte.",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version} fehlt das Schreib-Tracking, auf das das Spiel angewiesen ist (6.7 oder neuer); das Spiel kann sehr langsam laufen. Ein Systemupdate behebt das.",
"warn.dlss_kept": "Im Installationsordner liegt bereits eine DLSS-Bibliothek ({path}); das Setup behält sie.",
"warn.dlss_download_failed": "NVIDIA DLSS konnte nicht von {url} heruntergeladen werden: {detail}. Das Spiel läuft ohne; der nächste Setup-Lauf versucht es erneut.",
"warn.fsr_kept": "Im Installationsordner liegt bereits eine FSR-Bibliothek ({path}); das Setup behält die Bibliotheken dort.",
"warn.fsr_download_failed": "AMD FSR 4 konnte nicht von {url} heruntergeladen werden: {detail}. Das Spiel läuft ohne; der nächste Setup-Lauf versucht es erneut.",
"ui.title": "TotK-Setup",
"ui.rebuild_title": "Spiel für deine Mods neu bauen",
"ui.start_game": "Spiel starten",
@@ -135,6 +143,8 @@
"ui.firmware_help": "Für chinesischen, koreanischen und traditionell chinesischen Text: der Ordner Contents/registered der Firmware, zum Beispiel aus Ryujinx oder Yuzu. Das Setup kopiert daraus die Systemschriften der Switch in den Installationsordner.",
"ui.dlss": "NVIDIA DLSS (nvngx_dlss.dll) für NVIDIA-RTX-Grafikkarten herunterladen",
"ui.dlss_help": "Aus NVIDIAs DLSS SDK auf GitHub, unter NVIDIAs RTX-SDK-Lizenz (github.com/NVIDIA/DLSS). Damit funktionieren die Einstellungen dlaa und DLSS; ohne die Datei bewirken sie nichts.",
"ui.fsr": "AMD FSR 4 (AMDs FSR-SDK-Bibliotheken) für AMD-Radeon-Grafikkarten herunterladen",
"ui.fsr_help": "Aus AMDs FSR SDK auf GitHub, unter AMDs FSR-SDK-Lizenz (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Damit funktioniert die Wahl AMD FSR 4 beim 3D-Szenen-Upscaler auf den Radeon-Karten, für die AMDs Bibliotheken FSR 4 anbieten; ohne sie bewirkt diese Wahl nichts. Beim Start angehakt, wenn der Computer eine AMD-Grafikkarte hat.",
"ui.compressed_help": "Komprimierte NSZ- und XCZ-Dateien funktionieren direkt: Das Setup entpackt sie selbst (bis die Spieldaten extrahiert sind, braucht das so viel freien Speicher, wie die entpackten Dateien belegen).",
"ui.section_files": "Spieldateien",
"ui.section_install": "Installation",
+10
View File
@@ -9,6 +9,7 @@
"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.fsr": "Downloading AMD FSR 4",
"step.cleanup": "Cleaning up",
"phase.check.host": "Checking the processor and the graphics card",
@@ -40,6 +41,7 @@
"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.fsr.download": "Downloading the FSR 4 libraries from AMD's FSR SDK",
"phase.cleanup.ini": "Writing totk.ini",
"phase.cleanup.temp": "Removing temporary files",
@@ -57,6 +59,10 @@
"check.toolchain_broken": "The bundled compiler does not work: {detail}",
"check.glibc_old": "This system's C library is glibc {version}; the setup's compiler needs {need} or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 and newer have it). Updating the system fixes this.",
"check.host_probe_failed": "The computer check did not run (exit code {code}).",
"check.host_blocked": "Windows blocked a program the setup built on this PC ({path}): {detail}. Smart App Control, an App Control policy or an antivirus blocks unsigned programs; the game itself is built on this PC the same way, so it would be blocked too. Allow the setup folder in your antivirus, or turn off Smart App Control in Windows Security (App & browser control), then run the setup again.",
"check.vulkan_crash": "The graphics driver crashed while the setup asked it for the graphics cards (exit code {code}), also with the Vulkan layers of other programs turned off. Install the latest driver for your graphics card.",
"check.vulkan_layer_crash": "A Vulkan layer that another program installed crashes Vulkan programs on this PC (exit code {code}), and the game would crash at start the same way. The layer: {layers}. Update or uninstall the program it belongs to (the path shows its folder), or turn the layer off: set the environment variable VK_LOADER_LAYERS_DISABLE to {disable} for your user account. Then run the setup again.",
"check.vulkan_layers_crash": "A Vulkan layer that another program installed crashes Vulkan programs on this PC (exit code {code}): with all such layers off the check passes, and the game would crash at start the same way with them on. Turning the installed layers off one at a time did not single it out. Installed layers: {layers}. Update or uninstall the overlay, recorder or tuning programs among them, or turn all such layers off: set the environment variable VK_LOADER_LAYERS_DISABLE to ~implicit~ for your user account (this also turns off overlays such as Steam's in every Vulkan game). Then run the setup again.",
"check.cpu_too_old": "This processor lacks x86-64-v2 (SSE4.2, POPCNT and CMPXCHG16B), the oldest level the game is built for. Intel Nehalem (2008) or AMD Bulldozer (2011) and newer have it.",
"check.vulkan_missing": "No Vulkan driver is installed. Install the latest driver for your graphics card.",
"check.vulkan_no_device": "Vulkan finds no graphics card. Install the latest driver for your graphics card.",
@@ -118,6 +124,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.",
"warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.",
"warn.dlss_download_failed": "NVIDIA DLSS could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.",
"warn.fsr_kept": "An FSR library is already in the install folder ({path}); the setup keeps the libraries there.",
"warn.fsr_download_failed": "AMD FSR 4 could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.",
"ui.title": "TotK Setup",
"ui.rebuild_title": "Rebuilding the game for your mods",
@@ -141,6 +149,8 @@
"ui.firmware_help": "For Chinese, Korean and Traditional Chinese text: the firmware's Contents/registered folder, for example from Ryujinx or Yuzu. The setup copies the Switch system fonts from it into the install folder.",
"ui.dlss": "Download NVIDIA DLSS (nvngx_dlss.dll) for NVIDIA RTX graphics cards",
"ui.dlss_help": "From NVIDIA's DLSS SDK on GitHub, under NVIDIA's RTX SDK license (github.com/NVIDIA/DLSS). It makes the dlaa and DLSS settings work; without it they do nothing.",
"ui.fsr": "Download AMD FSR 4 (AMD's FSR SDK libraries) for AMD Radeon graphics cards",
"ui.fsr_help": "From AMD's FSR SDK on GitHub, under AMD's FSR SDK license (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). It makes the AMD FSR 4 choice of the 3D scene upscaler work on the Radeon cards AMD's libraries offer FSR 4 for; without it that choice does nothing. Ticked at start when the computer has an AMD graphics card.",
"ui.compressed_help": "Compressed NSZ and XCZ files work as they are: the setup unpacks them by itself (until the game data is extracted, that needs as much free space as the unpacked files take).",
"ui.section_files": "Game files",
"ui.section_install": "Install",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Dibujando los iconos de teclado y ratón",
"step.shapes": "Ajustando las pantallas del juego a tus monitores",
"step.dlss": "Descargando NVIDIA DLSS",
"step.fsr": "Descargando AMD FSR 4",
"step.cleanup": "Limpiando",
"phase.check.host": "Comprobando el procesador y la tarjeta gráfica",
"phase.check.verify": "Comprobando los archivos ya instalados",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Empaquetando la caché de shaders en un archivo",
"phase.shapes.layouts": "Escribiendo las disposiciones de pantalla y los iconos de botones para cada formato de pantalla",
"phase.dlss.download": "Descargando nvngx_dlss.dll del DLSS SDK de NVIDIA",
"phase.fsr.download": "Descargando las bibliotecas de FSR 4 del FSR SDK de AMD",
"phase.cleanup.ini": "Escribiendo totk.ini",
"phase.cleanup.temp": "Eliminando los archivos temporales",
"cli.usage": "Línea de comandos no válida: {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "El compilador incluido no funciona: {detail}",
"check.glibc_old": "La biblioteca C de este sistema es glibc {version}; el compilador del instalador necesita {need} o posterior (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 y posteriores la tienen). Actualizar el sistema lo soluciona.",
"check.host_probe_failed": "La comprobación del equipo no se ejecutó (código de salida {code}).",
"check.host_blocked": "Windows bloqueó un programa que el instalador creó en este PC ({path}): {detail}. Smart App Control, una directiva de App Control o un antivirus bloquean los programas sin firmar; el propio juego se crea igual en este PC, así que también se bloquearía. Permite la carpeta del instalador en tu antivirus o desactiva Smart App Control en Seguridad de Windows (Control de aplicaciones y navegador) y vuelve a ejecutar el instalador.",
"check.vulkan_crash": "El controlador gráfico falló cuando el instalador le pidió las tarjetas gráficas (código de salida {code}), también con las capas Vulkan de otros programas desactivadas. Instala el controlador más reciente de tu tarjeta gráfica.",
"check.vulkan_layer_crash": "Una capa Vulkan que instaló otro programa hace fallar los programas Vulkan en este PC (código de salida {code}), y el juego fallaría igual al iniciar. La capa: {layers}. Actualiza o desinstala el programa al que pertenece (la ruta muestra su carpeta), o desactiva la capa: define para tu cuenta de usuario la variable de entorno VK_LOADER_LAYERS_DISABLE con el valor {disable}. Después vuelve a ejecutar el instalador.",
"check.vulkan_layers_crash": "Una capa Vulkan que instaló otro programa hace fallar los programas Vulkan en este PC (código de salida {code}): con todas esas capas desactivadas la comprobación pasa, y con ellas el juego fallaría igual al iniciar. Desactivar las capas instaladas una por una no permitió identificarla. Capas instaladas: {layers}. Actualiza o desinstala los programas de superposición, grabación o ajuste que haya entre ellas, o desactiva todas esas capas: define para tu cuenta de usuario la variable de entorno VK_LOADER_LAYERS_DISABLE con el valor ~implicit~ (esto también desactiva superposiciones como la de Steam en todos los juegos Vulkan). Después vuelve a ejecutar el instalador.",
"check.cpu_too_old": "Este procesador no tiene x86-64-v2 (SSE4.2, POPCNT y CMPXCHG16B), el nivel más antiguo para el que se compila el juego. Intel Nehalem (2008) o AMD Bulldozer (2011) y posteriores lo tienen.",
"check.vulkan_missing": "No hay ningún controlador Vulkan instalado. Instala el controlador más reciente de tu tarjeta gráfica.",
"check.vulkan_no_device": "Vulkan no encuentra ninguna tarjeta gráfica. Instala el controlador más reciente de tu tarjeta gráfica.",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version} no tiene el seguimiento de escrituras del que depende el juego (6.7 o posterior); el juego puede ir muy lento. Actualizar el sistema lo soluciona.",
"warn.dlss_kept": "Ya hay una biblioteca DLSS en la carpeta de instalación ({path}); el instalador la conserva.",
"warn.dlss_download_failed": "No se pudo descargar NVIDIA DLSS desde {url}: {detail}. El juego funciona sin él; la próxima ejecución del instalador lo intentará de nuevo.",
"warn.fsr_kept": "Ya hay una biblioteca FSR en la carpeta de instalación ({path}); el instalador conserva las bibliotecas que hay.",
"warn.fsr_download_failed": "No se pudo descargar AMD FSR 4 desde {url}: {detail}. El juego funciona sin él; la próxima ejecución del instalador lo intentará de nuevo.",
"ui.title": "Instalador de TotK",
"ui.rebuild_title": "Reconstruyendo el juego para tus mods",
"ui.start_game": "Iniciar el juego",
@@ -135,6 +143,8 @@
"ui.firmware_help": "Para texto en chino, coreano y chino tradicional: la carpeta Contents/registered del firmware, por ejemplo de Ryujinx o Yuzu. El instalador copia de ella las fuentes del sistema de Switch a la carpeta de instalación.",
"ui.dlss": "Descargar NVIDIA DLSS (nvngx_dlss.dll) para tarjetas gráficas NVIDIA RTX",
"ui.dlss_help": "Del DLSS SDK de NVIDIA en GitHub, bajo la licencia RTX SDK de NVIDIA (github.com/NVIDIA/DLSS). Hace que funcionen los ajustes dlaa y DLSS; sin él no hacen nada.",
"ui.fsr": "Descargar AMD FSR 4 (bibliotecas del FSR SDK de AMD) para tarjetas gráficas AMD Radeon",
"ui.fsr_help": "Del FSR SDK de AMD en GitHub, bajo la licencia FSR SDK de AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Hace que funcione la opción AMD FSR 4 del escalador de la escena 3D en las tarjetas Radeon para las que las bibliotecas de AMD ofrecen FSR 4; sin ellas esa opción no hace nada. Viene marcada si el equipo tiene una tarjeta gráfica AMD.",
"ui.compressed_help": "Los archivos comprimidos NSZ y XCZ funcionan tal cual: el instalador los descomprime por sí mismo (hasta que se extraen los datos del juego, necesita tanto espacio libre como ocupan los archivos descomprimidos).",
"ui.section_files": "Archivos del juego",
"ui.section_install": "Instalación",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Dessin des icônes du clavier et de la souris",
"step.shapes": "Mise en page des écrans du jeu pour vos moniteurs",
"step.dlss": "Téléchargement de NVIDIA DLSS",
"step.fsr": "Téléchargement d'AMD FSR 4",
"step.cleanup": "Nettoyage",
"phase.check.host": "Vérification du processeur et de la carte graphique",
"phase.check.verify": "Vérification des fichiers déjà installés",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Regroupement du cache de shaders en un fichier",
"phase.shapes.layouts": "Écriture des mises en page et des icônes de boutons pour chaque format d’écran",
"phase.dlss.download": "Téléchargement de nvngx_dlss.dll depuis le DLSS SDK de NVIDIA",
"phase.fsr.download": "Téléchargement des bibliothèques FSR 4 depuis le FSR SDK d'AMD",
"phase.cleanup.ini": "Écriture de totk.ini",
"phase.cleanup.temp": "Suppression des fichiers temporaires",
"cli.usage": "Ligne de commande invalide : {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "Le compilateur fourni ne fonctionne pas : {detail}",
"check.glibc_old": "La bibliothèque C de ce système est glibc {version} ; le compilateur de l'installation demande {need} ou plus récent (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 et plus récents l'ont). Mettre à jour le système corrige cela.",
"check.host_probe_failed": "La vérification de l'ordinateur ne s'est pas exécutée (code de sortie {code}).",
"check.host_blocked": "Windows a bloqué un programme que l'installateur a compilé sur ce PC ({path}) : {detail}. Smart App Control, une stratégie App Control ou un antivirus bloque les programmes non signés ; le jeu lui-même est compilé de la même façon sur ce PC et serait bloqué aussi. Autorisez le dossier de l'installateur dans votre antivirus, ou désactivez Smart App Control dans Sécurité Windows (Contrôle des applications et du navigateur), puis relancez l'installateur.",
"check.vulkan_crash": "Le pilote graphique a planté quand l'installateur lui a demandé les cartes graphiques (code de sortie {code}), même avec les couches Vulkan des autres programmes désactivées. Installez le dernier pilote de votre carte graphique.",
"check.vulkan_layer_crash": "Une couche Vulkan installée par un autre programme fait planter les programmes Vulkan sur ce PC (code de sortie {code}), et le jeu planterait de la même façon au démarrage. La couche : {layers}. Mettez à jour ou désinstallez le programme auquel elle appartient (le chemin montre son dossier), ou désactivez la couche : définissez pour votre compte utilisateur la variable d'environnement VK_LOADER_LAYERS_DISABLE avec la valeur {disable}. Relancez ensuite l'installateur.",
"check.vulkan_layers_crash": "Une couche Vulkan installée par un autre programme fait planter les programmes Vulkan sur ce PC (code de sortie {code}) : avec toutes ces couches désactivées, la vérification réussit, et avec elles le jeu planterait de la même façon au démarrage. Désactiver les couches installées une par une n'a pas permis de l'identifier. Couches installées : {layers}. Mettez à jour ou désinstallez les programmes d'overlay, d'enregistrement ou de réglage parmi elles, ou désactivez toutes ces couches : définissez pour votre compte utilisateur la variable d'environnement VK_LOADER_LAYERS_DISABLE avec la valeur ~implicit~ (cela désactive aussi les overlays comme celui de Steam dans tous les jeux Vulkan). Relancez ensuite l'installateur.",
"check.cpu_too_old": "Ce processeur ne prend pas en charge x86-64-v2 (SSE4.2, POPCNT et CMPXCHG16B), le niveau le plus ancien pour lequel le jeu est compilé. Intel Nehalem (2008) ou AMD Bulldozer (2011) et plus récents l'ont.",
"check.vulkan_missing": "Aucun pilote Vulkan n'est installé. Installez le dernier pilote de votre carte graphique.",
"check.vulkan_no_device": "Vulkan ne trouve aucune carte graphique. Installez le dernier pilote de votre carte graphique.",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version} ne dispose pas du suivi des écritures dont le jeu dépend (6.7 ou plus récent) ; le jeu peut être très lent. Mettre à jour le système corrige cela.",
"warn.dlss_kept": "Une bibliothèque DLSS se trouve déjà dans le dossier d'installation ({path}) ; l'installation la conserve.",
"warn.dlss_download_failed": "NVIDIA DLSS n'a pas pu être téléchargé depuis {url} : {detail}. Le jeu fonctionne sans ; la prochaine installation réessaiera.",
"warn.fsr_kept": "Une bibliothèque FSR se trouve déjà dans le dossier d'installation ({path}) ; l'installation conserve les bibliothèques présentes.",
"warn.fsr_download_failed": "AMD FSR 4 n'a pas pu être téléchargé depuis {url} : {detail}. Le jeu fonctionne sans ; la prochaine installation réessaiera.",
"ui.title": "Installation de TotK",
"ui.rebuild_title": "Reconstruction du jeu pour vos mods",
"ui.start_game": "Lancer le jeu",
@@ -135,6 +143,8 @@
"ui.firmware_help": "Pour le texte en chinois, en coréen et en chinois traditionnel : le dossier Contents/registered du firmware, par exemple celui de Ryujinx ou de Yuzu. L'installation en copie les polices système de la Switch dans le dossier d'installation.",
"ui.dlss": "Télécharger NVIDIA DLSS (nvngx_dlss.dll) pour les cartes graphiques NVIDIA RTX",
"ui.dlss_help": "Depuis le DLSS SDK de NVIDIA sur GitHub, sous la licence RTX SDK de NVIDIA (github.com/NVIDIA/DLSS). Il fait fonctionner les réglages dlaa et DLSS ; sans lui, ils n'ont aucun effet.",
"ui.fsr": "Télécharger AMD FSR 4 (bibliothèques du FSR SDK d'AMD) pour les cartes graphiques AMD Radeon",
"ui.fsr_help": "Depuis le FSR SDK d'AMD sur GitHub, sous la licence FSR SDK d'AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Il fait fonctionner le choix AMD FSR 4 de l'upscaler de la scène 3D sur les cartes Radeon pour lesquelles les bibliothèques d'AMD proposent FSR 4 ; sans elles, ce choix n'a aucun effet. Coché au départ quand l'ordinateur a une carte graphique AMD.",
"ui.compressed_help": "Les fichiers compressés NSZ et XCZ fonctionnent tels quels : l'installation les décompresse elle-même (jusqu'à l'extraction des données du jeu, il faut autant d'espace libre que les fichiers décompressés).",
"ui.section_files": "Fichiers du jeu",
"ui.section_install": "Installation",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Disegno delle icone di tastiera e mouse",
"step.shapes": "Impaginazione delle schermate del gioco per i tuoi monitor",
"step.dlss": "Download di NVIDIA DLSS",
"step.fsr": "Download di AMD FSR 4",
"step.cleanup": "Pulizia",
"phase.check.host": "Controllo del processore e della scheda grafica",
"phase.check.verify": "Controllo dei file già installati",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Raccolta della cache degli shader in un file",
"phase.shapes.layouts": "Scrittura dei layout dello schermo e delle icone dei pulsanti per ogni formato di schermo",
"phase.dlss.download": "Download di nvngx_dlss.dll dal DLSS SDK di NVIDIA",
"phase.fsr.download": "Download delle librerie FSR 4 dal FSR SDK di AMD",
"phase.cleanup.ini": "Scrittura di totk.ini",
"phase.cleanup.temp": "Rimozione dei file temporanei",
"cli.usage": "Riga di comando non valida: {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "Il compilatore incluso non funziona: {detail}",
"check.glibc_old": "La libreria C di questo sistema è glibc {version}; il compilatore dell'installazione richiede {need} o successiva (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e successivi la hanno). Aggiornare il sistema risolve il problema.",
"check.host_probe_failed": "Il controllo del computer non è stato eseguito (codice di uscita {code}).",
"check.host_blocked": "Windows ha bloccato un programma che il programma di installazione ha compilato su questo PC ({path}): {detail}. Smart App Control, un criterio App Control o un antivirus bloccano i programmi non firmati; anche il gioco viene compilato così su questo PC e verrebbe bloccato. Consenti la cartella di installazione nell'antivirus oppure disattiva Smart App Control in Sicurezza di Windows (Controllo app e browser), poi esegui di nuovo l'installazione.",
"check.vulkan_crash": "Il driver grafico si è bloccato quando l'installazione gli ha chiesto le schede grafiche (codice di uscita {code}), anche con i livelli Vulkan degli altri programmi disattivati. Installa il driver più recente della tua scheda grafica.",
"check.vulkan_layer_crash": "Un livello Vulkan installato da un altro programma fa bloccare i programmi Vulkan su questo PC (codice di uscita {code}) e il gioco si bloccherebbe allo stesso modo all'avvio. Il livello: {layers}. Aggiorna o disinstalla il programma a cui appartiene (il percorso mostra la sua cartella), oppure disattiva il livello: imposta per il tuo account utente la variabile d'ambiente VK_LOADER_LAYERS_DISABLE con il valore {disable}. Poi esegui di nuovo l'installazione.",
"check.vulkan_layers_crash": "Un livello Vulkan installato da un altro programma fa bloccare i programmi Vulkan su questo PC (codice di uscita {code}): con tutti questi livelli disattivati il controllo riesce, e con essi il gioco si bloccherebbe allo stesso modo all'avvio. Disattivare i livelli installati uno alla volta non ha permesso di individuarlo. Livelli installati: {layers}. Aggiorna o disinstalla i programmi di overlay, registrazione o tuning tra questi, oppure disattiva tutti questi livelli: imposta per il tuo account utente la variabile d'ambiente VK_LOADER_LAYERS_DISABLE con il valore ~implicit~ (questo disattiva anche overlay come quello di Steam in tutti i giochi Vulkan). Poi esegui di nuovo l'installazione.",
"check.cpu_too_old": "Questo processore non supporta x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), il livello più vecchio per cui il gioco viene compilato. Intel Nehalem (2008) o AMD Bulldozer (2011) e successivi lo supportano.",
"check.vulkan_missing": "Non è installato alcun driver Vulkan. Installa il driver più recente della tua scheda grafica.",
"check.vulkan_no_device": "Vulkan non trova alcuna scheda grafica. Installa il driver più recente della tua scheda grafica.",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version} non ha il tracciamento delle scritture su cui si basa il gioco (6.7 o successivo); il gioco potrebbe essere molto lento. Aggiornare il sistema risolve il problema.",
"warn.dlss_kept": "Nella cartella di installazione c'è già una libreria DLSS ({path}); l'installazione la mantiene.",
"warn.dlss_download_failed": "Impossibile scaricare NVIDIA DLSS da {url}: {detail}. Il gioco funziona senza; la prossima esecuzione dell'installazione riproverà.",
"warn.fsr_kept": "Nella cartella di installazione c'è già una libreria FSR ({path}); l'installazione mantiene le librerie presenti.",
"warn.fsr_download_failed": "Impossibile scaricare AMD FSR 4 da {url}: {detail}. Il gioco funziona senza; la prossima esecuzione dell'installazione riproverà.",
"ui.title": "Installazione di TotK",
"ui.rebuild_title": "Ricostruzione del gioco per le tue mod",
"ui.start_game": "Avvia il gioco",
@@ -135,6 +143,8 @@
"ui.firmware_help": "Per il testo in cinese, coreano e cinese tradizionale: la cartella Contents/registered del firmware, ad esempio da Ryujinx o Yuzu. L'installazione ne copia i font di sistema di Switch nella cartella di installazione.",
"ui.dlss": "Scarica NVIDIA DLSS (nvngx_dlss.dll) per le schede grafiche NVIDIA RTX",
"ui.dlss_help": "Dal DLSS SDK di NVIDIA su GitHub, con la licenza RTX SDK di NVIDIA (github.com/NVIDIA/DLSS). Fa funzionare le impostazioni dlaa e DLSS; senza, non hanno effetto.",
"ui.fsr": "Scarica AMD FSR 4 (librerie del FSR SDK di AMD) per le schede grafiche AMD Radeon",
"ui.fsr_help": "Dal FSR SDK di AMD su GitHub, con la licenza FSR SDK di AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Fa funzionare la scelta AMD FSR 4 dell'upscaler della scena 3D sulle schede Radeon per cui le librerie di AMD offrono FSR 4; senza, quella scelta non ha effetto. Selezionata all'avvio se il computer ha una scheda grafica AMD.",
"ui.compressed_help": "I file compressi NSZ e XCZ funzionano così come sono: l'installazione li decomprime da sé (finché i dati del gioco non sono estratti, serve tanto spazio libero quanto occupano i file decompressi).",
"ui.section_files": "File del gioco",
"ui.section_install": "Installazione",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "キーボードとマウスのボタン表示の作成",
"step.shapes": "ディスプレイに合わせたゲーム画面のレイアウト",
"step.dlss": "NVIDIA DLSS のダウンロード",
"step.fsr": "AMD FSR 4 のダウンロード",
"step.cleanup": "後片付け",
"phase.check.host": "プロセッサーとグラフィックカードを確認しています",
"phase.check.verify": "インストール済みのファイルを確認しています",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "シェーダーキャッシュを 1 つのファイルにまとめています",
"phase.shapes.layouts": "画面の形ごとに画面レイアウトとボタン表示を書き込んでいます",
"phase.dlss.download": "NVIDIA の DLSS SDK から nvngx_dlss.dll をダウンロードしています",
"phase.fsr.download": "AMD の FSR SDK から FSR 4 のライブラリをダウンロードしています",
"phase.cleanup.ini": "totk.ini を書き込んでいます",
"phase.cleanup.temp": "一時ファイルを削除しています",
"cli.usage": "コマンドラインが無効です: {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "同梱のコンパイラーが動作しません: {detail}",
"check.glibc_old": "このシステムの C ライブラリは glibc {version} です。セットアップのコンパイラーには {need} 以降が必要です (Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 以降にあります)。システムを更新すると解決します。",
"check.host_probe_failed": "コンピューターの確認を実行できませんでした (終了コード {code})。",
"check.host_blocked": "セットアップがこの PC でビルドしたプログラム ({path}) を Windows がブロックしました: {detail}。スマート アプリ コントロール、App Control ポリシー、またはウイルス対策ソフトが署名のないプログラムをブロックしています。ゲーム本体も同じ方法でこの PC でビルドされるため、同じくブロックされます。ウイルス対策ソフトでセットアップのフォルダーを許可するか、Windows セキュリティ (アプリとブラウザー コントロール) でスマート アプリ コントロールをオフにしてから、セットアップをもう一度実行してください。",
"check.vulkan_crash": "セットアップがグラフィックカードを問い合わせたときにグラフィックドライバーがクラッシュしました (終了コード {code})。他のプログラムの Vulkan レイヤーをオフにしても同じでした。グラフィックカードの最新ドライバーをインストールしてください。",
"check.vulkan_layer_crash": "他のプログラムがインストールした Vulkan レイヤーが、この PC の Vulkan プログラムをクラッシュさせています (終了コード {code})。ゲームも起動時に同じようにクラッシュします。レイヤー: {layers}。そのレイヤーが属するプログラムを更新するかアンインストールするか (パスでフォルダーがわかります)、レイヤーをオフにしてください: ユーザー アカウントの環境変数 VK_LOADER_LAYERS_DISABLE に {disable} を設定します。その後、セットアップをもう一度実行してください。",
"check.vulkan_layers_crash": "他のプログラムがインストールした Vulkan レイヤーが、この PC の Vulkan プログラムをクラッシュさせています (終了コード {code})。そのようなレイヤーをすべてオフにすると確認は成功し、オンのままではゲームも起動時に同じようにクラッシュします。インストール済みのレイヤーを 1 つずつオフにしても特定できませんでした。インストール済みのレイヤー: {layers}。この中のオーバーレイ、録画、チューニングのプログラムを更新するかアンインストールするか、そのようなレイヤーをすべてオフにしてください: ユーザー アカウントの環境変数 VK_LOADER_LAYERS_DISABLE に ~implicit~ を設定します (Steam などのオーバーレイもすべての Vulkan ゲームでオフになります)。その後、セットアップをもう一度実行してください。",
"check.cpu_too_old": "このプロセッサーは、ゲームのビルド対象となる最も古いレベルである x86-64-v2 (SSE4.2、POPCNT、CMPXCHG16B) に対応していません。Intel Nehalem (2008 年) または AMD Bulldozer (2011 年) 以降が対応しています。",
"check.vulkan_missing": "Vulkan ドライバーがインストールされていません。グラフィックカードの最新ドライバーをインストールしてください。",
"check.vulkan_no_device": "Vulkan がグラフィックカードを見つけられません。グラフィックカードの最新ドライバーをインストールしてください。",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version} には、ゲームが必要とする書き込み追跡 (6.7 以降) がありません。ゲームが非常に遅くなることがあります。システムを更新すると解決します。",
"warn.dlss_kept": "インストール先フォルダーには既に DLSS ライブラリがあります ({path})。セットアップはそれを残します。",
"warn.dlss_download_failed": "NVIDIA DLSS を {url} からダウンロードできませんでした: {detail}。ゲームはなしで動作します。次回のセットアップ実行時に再試行します。",
"warn.fsr_kept": "インストール先フォルダーには既に FSR ライブラリがあります ({path})。セットアップはそれらを残します。",
"warn.fsr_download_failed": "AMD FSR 4 を {url} からダウンロードできませんでした: {detail}。ゲームはなしで動作します。次回のセットアップ実行時に再試行します。",
"ui.title": "TotK セットアップ",
"ui.rebuild_title": "Mod に合わせてゲームを再ビルドしています",
"ui.start_game": "ゲームを開始",
@@ -135,6 +143,8 @@
"ui.firmware_help": "中国語、韓国語、繁体字中国語のテキスト用: ファームウェアの Contents/registered フォルダー (例: Ryujinx や Yuzu のもの)。セットアップはそこから Switch のシステムフォントをインストール先フォルダーにコピーします。",
"ui.dlss": "NVIDIA RTX グラフィックカード用に NVIDIA DLSS (nvngx_dlss.dll) をダウンロードする",
"ui.dlss_help": "GitHub 上の NVIDIA の DLSS SDK から、NVIDIA の RTX SDK ライセンスのもとで取得します (github.com/NVIDIA/DLSS)。これで dlaa と DLSS の設定が機能します。ない場合、これらの設定は効果がありません。",
"ui.fsr": "AMD Radeon グラフィックカード用に AMD FSR 4 (AMD の FSR SDK ライブラリ) をダウンロードする",
"ui.fsr_help": "GitHub 上の AMD の FSR SDK から、AMD の FSR SDK ライセンスのもとで取得します (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)。これで、AMD のライブラリが FSR 4 を提供する Radeon カードで、3D シーンのアップスケーラーの AMD FSR 4 が機能します。ない場合、この選択は効果がありません。AMD のグラフィックカードがあるときは最初からチェックされています。",
"ui.compressed_help": "圧縮された NSZ / XCZ ファイルはそのまま使えます。セットアップが自分で展開します(ゲームデータの展開が終わるまで、展開後のファイルと同じだけの空き容量が必要です)。",
"ui.section_files": "ゲームファイル",
"ui.section_install": "インストール",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "키보드 및 마우스 버튼 표시 그리기",
"step.shapes": "모니터에 맞게 게임 화면 배치",
"step.dlss": "NVIDIA DLSS 다운로드",
"step.fsr": "AMD FSR 4 다운로드",
"step.cleanup": "정리",
"phase.check.host": "프로세서와 그래픽 카드를 확인하는 중",
"phase.check.verify": "이미 설치된 파일을 확인하는 중",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "셰이더 캐시를 파일 하나로 묶는 중",
"phase.shapes.layouts": "화면 형태마다 화면 레이아웃과 버튼 표시 쓰는 중",
"phase.dlss.download": "NVIDIA DLSS SDK에서 nvngx_dlss.dll을 다운로드하는 중",
"phase.fsr.download": "AMD FSR SDK에서 FSR 4 라이브러리를 다운로드하는 중",
"phase.cleanup.ini": "totk.ini를 쓰는 중",
"phase.cleanup.temp": "임시 파일을 삭제하는 중",
"cli.usage": "잘못된 명령줄: {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "포함된 컴파일러가 작동하지 않습니다: {detail}",
"check.glibc_old": "이 시스템의 C 라이브러리는 glibc {version}입니다. 설치 프로그램의 컴파일러에는 {need} 이상이 필요합니다(Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 이상에 있음). 시스템을 업데이트하면 해결됩니다.",
"check.host_probe_failed": "컴퓨터 확인이 실행되지 않았습니다(종료 코드 {code}).",
"check.host_blocked": "설치 프로그램이 이 PC에서 빌드한 프로그램({path})을 Windows가 차단했습니다: {detail}. 스마트 앱 컨트롤, App Control 정책 또는 백신이 서명되지 않은 프로그램을 차단합니다. 게임 자체도 이 PC에서 같은 방식으로 빌드되므로 마찬가지로 차단됩니다. 백신에서 설치 프로그램 폴더를 허용하거나 Windows 보안(앱 및 브라우저 컨트롤)에서 스마트 앱 컨트롤을 끈 다음 설치 프로그램을 다시 실행하세요.",
"check.vulkan_crash": "설치 프로그램이 그래픽 카드를 조회하는 중에 그래픽 드라이버가 충돌했습니다(종료 코드 {code}). 다른 프로그램의 Vulkan 레이어를 끈 상태에서도 마찬가지였습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
"check.vulkan_layer_crash": "다른 프로그램이 설치한 Vulkan 레이어 때문에 이 PC의 Vulkan 프로그램이 충돌합니다(종료 코드 {code}). 게임도 시작할 때 같은 방식으로 충돌합니다. 레이어: {layers}. 그 레이어가 속한 프로그램을 업데이트하거나 제거하거나(경로에 폴더가 나옵니다), 레이어를 끄세요: 사용자 계정의 환경 변수 VK_LOADER_LAYERS_DISABLE을 {disable}(으)로 설정합니다. 그런 다음 설치 프로그램을 다시 실행하세요.",
"check.vulkan_layers_crash": "다른 프로그램이 설치한 Vulkan 레이어 때문에 이 PC의 Vulkan 프로그램이 충돌합니다(종료 코드 {code}). 그런 레이어를 모두 끄면 확인을 통과하고, 켜 두면 게임도 시작할 때 같은 방식으로 충돌합니다. 설치된 레이어를 하나씩 꺼 봐도 어느 것인지 찾지 못했습니다. 설치된 레이어: {layers}. 이 중 오버레이, 녹화 또는 튜닝 프로그램을 업데이트하거나 제거하거나, 그런 레이어를 모두 끄세요: 사용자 계정의 환경 변수 VK_LOADER_LAYERS_DISABLE을 ~implicit~(으)로 설정합니다(Steam 같은 오버레이도 모든 Vulkan 게임에서 꺼집니다). 그런 다음 설치 프로그램을 다시 실행하세요.",
"check.cpu_too_old": "이 프로세서에는 게임이 빌드되는 가장 오래된 수준인 x86-64-v2(SSE4.2, POPCNT, CMPXCHG16B)가 없습니다. Intel Nehalem(2008) 또는 AMD Bulldozer(2011) 이후 프로세서에 있습니다.",
"check.vulkan_missing": "Vulkan 드라이버가 설치되어 있지 않습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
"check.vulkan_no_device": "Vulkan이 그래픽 카드를 찾지 못했습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version}에는 게임이 사용하는 쓰기 추적(6.7 이상)이 없습니다. 게임이 매우 느릴 수 있습니다. 시스템을 업데이트하면 해결됩니다.",
"warn.dlss_kept": "설치 폴더에 이미 DLSS 라이브러리가 있습니다({path}). 설치 프로그램은 그대로 둡니다.",
"warn.dlss_download_failed": "{url}에서 NVIDIA DLSS를 다운로드할 수 없습니다: {detail}. 게임은 없이도 실행되며, 다음 설치 실행 때 다시 시도합니다.",
"warn.fsr_kept": "설치 폴더에 이미 FSR 라이브러리가 있습니다({path}). 설치 프로그램은 그대로 둡니다.",
"warn.fsr_download_failed": "{url}에서 AMD FSR 4를 다운로드할 수 없습니다: {detail}. 게임은 없이도 실행되며, 다음 설치 실행 때 다시 시도합니다.",
"ui.title": "TotK 설치",
"ui.rebuild_title": "모드에 맞게 게임을 다시 빌드하는 중",
"ui.start_game": "게임 시작",
@@ -135,6 +143,8 @@
"ui.firmware_help": "중국어, 한국어, 번체 중국어 텍스트용: 펌웨어의 Contents/registered 폴더(예: Ryujinx 또는 Yuzu의 폴더). 설치 프로그램이 여기에서 Switch 시스템 글꼴을 설치 폴더로 복사합니다.",
"ui.dlss": "NVIDIA RTX 그래픽 카드용 NVIDIA DLSS (nvngx_dlss.dll) 다운로드",
"ui.dlss_help": "GitHub의 NVIDIA DLSS SDK에서, NVIDIA RTX SDK 라이선스에 따라 받습니다(github.com/NVIDIA/DLSS). 이 파일이 있어야 dlaa 및 DLSS 설정이 작동하며, 없으면 아무 효과가 없습니다.",
"ui.fsr": "AMD Radeon 그래픽 카드용 AMD FSR 4 (AMD FSR SDK 라이브러리) 다운로드",
"ui.fsr_help": "GitHub의 AMD FSR SDK에서, AMD FSR SDK 라이선스에 따라 받습니다(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). 이 라이브러리가 있어야 AMD 라이브러리가 FSR 4를 제공하는 Radeon 카드에서 3D 장면 업스케일러의 AMD FSR 4 선택이 작동하며, 없으면 아무 효과가 없습니다. AMD 그래픽 카드가 있는 컴퓨터에서는 처음부터 체크되어 있습니다.",
"ui.compressed_help": "압축된 NSZ 및 XCZ 파일은 그대로 사용할 수 있습니다. 설치 프로그램이 직접 압축을 풉니다(게임 데이터를 추출할 때까지 압축을 푼 파일만큼의 여유 공간이 필요합니다).",
"ui.section_files": "게임 파일",
"ui.section_install": "설치",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Toetsenbord- en muispictogrammen tekenen",
"step.shapes": "De spelschermen voor je beeldschermen indelen",
"step.dlss": "NVIDIA DLSS downloaden",
"step.fsr": "AMD FSR 4 downloaden",
"step.cleanup": "Opruimen",
"phase.check.host": "Processor en videokaart controleren",
"phase.check.verify": "Al geïnstalleerde bestanden controleren",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Shadercache in één bestand verpakken",
"phase.shapes.layouts": "Schermindelingen en knoppictogrammen voor elke schermvorm schrijven",
"phase.dlss.download": "nvngx_dlss.dll downloaden uit NVIDIA's DLSS SDK",
"phase.fsr.download": "De FSR 4-bibliotheken downloaden uit AMD's FSR SDK",
"phase.cleanup.ini": "totk.ini schrijven",
"phase.cleanup.temp": "Tijdelijke bestanden verwijderen",
"cli.usage": "Ongeldige opdrachtregel: {detail}",
@@ -54,6 +56,10 @@
"check.toolchain_broken": "De meegeleverde compiler werkt niet: {detail}",
"check.glibc_old": "De C-bibliotheek van dit systeem is glibc {version}; de compiler van de installatie heeft {need} of nieuwer nodig (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 en nieuwer hebben die). Het systeem bijwerken lost dit op.",
"check.host_probe_failed": "De computercontrole is niet uitgevoerd (afsluitcode {code}).",
"check.host_blocked": "Windows heeft een programma geblokkeerd dat de installatie op deze pc heeft gebouwd ({path}): {detail}. Slim app-beheer, een App Control-beleid of een virusscanner blokkeert niet-ondertekende programma's; het spel zelf wordt op dezelfde manier op deze pc gebouwd en zou ook worden geblokkeerd. Sta de installatiemap toe in je virusscanner, of zet Slim app-beheer uit in Windows-beveiliging (App- en browserbeheer), en start de installatie opnieuw.",
"check.vulkan_crash": "Het grafische stuurprogramma is gecrasht toen de installatie het om de videokaarten vroeg (afsluitcode {code}), ook met de Vulkan-lagen van andere programma's uitgeschakeld. Installeer het nieuwste stuurprogramma voor je videokaart.",
"check.vulkan_layer_crash": "Een Vulkan-laag die een ander programma heeft geïnstalleerd laat Vulkan-programma's op deze pc crashen (afsluitcode {code}), en het spel zou bij het starten op dezelfde manier crashen. De laag: {layers}. Werk het programma waar hij bij hoort bij of verwijder het (het pad toont de map), of zet de laag uit: stel voor je gebruikersaccount de omgevingsvariabele VK_LOADER_LAYERS_DISABLE in op {disable}. Start daarna de installatie opnieuw.",
"check.vulkan_layers_crash": "Een Vulkan-laag die een ander programma heeft geïnstalleerd laat Vulkan-programma's op deze pc crashen (afsluitcode {code}): met al zulke lagen uit slaagt de controle, en met die lagen aan zou het spel bij het starten op dezelfde manier crashen. De geïnstalleerde lagen één voor één uitzetten wees hem niet aan. Geïnstalleerde lagen: {layers}. Werk de overlay-, opname- of tuningprogramma's daartussen bij of verwijder ze, of zet al zulke lagen uit: stel voor je gebruikersaccount de omgevingsvariabele VK_LOADER_LAYERS_DISABLE in op ~implicit~ (dit zet ook overlays zoals die van Steam uit in elk Vulkan-spel). Start daarna de installatie opnieuw.",
"check.cpu_too_old": "Deze processor mist x86-64-v2 (SSE4.2, POPCNT en CMPXCHG16B), het oudste niveau waarvoor het spel wordt gebouwd. Intel Nehalem (2008) of AMD Bulldozer (2011) en nieuwer hebben het.",
"check.vulkan_missing": "Er is geen Vulkan-stuurprogramma geïnstalleerd. Installeer het nieuwste stuurprogramma voor je videokaart.",
"check.vulkan_no_device": "Vulkan vindt geen videokaart. Installeer het nieuwste stuurprogramma voor je videokaart.",
@@ -113,6 +119,8 @@
"warn.kernel_old": "Linux {version} mist de schrijftracering waar het spel op rekent (6.7 of nieuwer); het spel kan erg traag zijn. Het systeem bijwerken lost dit op.",
"warn.dlss_kept": "Er staat al een DLSS-bibliotheek in de installatiemap ({path}); de installatie laat die staan.",
"warn.dlss_download_failed": "NVIDIA DLSS kon niet worden gedownload van {url}: {detail}. Het spel werkt zonder; de volgende installatieronde probeert het opnieuw.",
"warn.fsr_kept": "Er staat al een FSR-bibliotheek in de installatiemap ({path}); de installatie laat de bibliotheken daar staan.",
"warn.fsr_download_failed": "AMD FSR 4 kon niet worden gedownload van {url}: {detail}. Het spel werkt zonder; de volgende installatieronde probeert het opnieuw.",
"ui.title": "TotK-installatie",
"ui.rebuild_title": "Spel opnieuw bouwen voor je mods",
"ui.start_game": "Spel starten",
@@ -135,6 +143,8 @@
"ui.firmware_help": "Voor Chinese, Koreaanse en traditioneel Chinese tekst: de map Contents/registered van de firmware, bijvoorbeeld uit Ryujinx of Yuzu. De installatie kopieert daaruit de systeemlettertypen van de Switch naar de installatiemap.",
"ui.dlss": "NVIDIA DLSS (nvngx_dlss.dll) downloaden voor NVIDIA RTX-videokaarten",
"ui.dlss_help": "Uit NVIDIA's DLSS SDK op GitHub, onder NVIDIA's RTX SDK-licentie (github.com/NVIDIA/DLSS). Hiermee werken de instellingen dlaa en DLSS; zonder doen ze niets.",
"ui.fsr": "AMD FSR 4 (AMD's FSR SDK-bibliotheken) downloaden voor AMD Radeon-videokaarten",
"ui.fsr_help": "Uit AMD's FSR SDK op GitHub, onder AMD's FSR SDK-licentie (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Hiermee werkt de keuze AMD FSR 4 van de 3D-scène-upscaler op de Radeon-kaarten waarvoor AMD's bibliotheken FSR 4 bieden; zonder doet die keuze niets. Aangevinkt bij de start als de computer een AMD-videokaart heeft.",
"ui.compressed_help": "Gecomprimeerde NSZ- en XCZ-bestanden werken zoals ze zijn: de installatie pakt ze zelf uit (tot de spelgegevens zijn uitgepakt, is daarvoor evenveel vrije ruimte nodig als de uitgepakte bestanden innemen).",
"ui.section_files": "Spelbestanden",
"ui.section_install": "Installatie",
+10
View File
@@ -9,6 +9,7 @@
"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.fsr": "Baixando o AMD FSR 4",
"step.cleanup": "Finalizando",
"phase.check.host": "Verificando o processador e a placa de vídeo",
@@ -40,6 +41,7 @@
"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.fsr.download": "Baixando as bibliotecas do FSR 4 do FSR SDK da AMD",
"phase.cleanup.ini": "Gravando o totk.ini",
"phase.cleanup.temp": "Removendo os arquivos temporários",
@@ -57,6 +59,10 @@
"check.toolchain_broken": "O compilador incluído não funciona: {detail}",
"check.glibc_old": "A biblioteca C deste sistema é a glibc {version}; o compilador da instalação precisa da {need} ou mais nova (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e mais novos têm). Atualizar o sistema resolve.",
"check.host_probe_failed": "A verificação do computador não rodou (código de saída {code}).",
"check.host_blocked": "O Windows bloqueou um programa que o instalador compilou neste PC ({path}): {detail}. O Controle Inteligente de Aplicativos, uma política de App Control ou um antivírus bloqueia programas sem assinatura; o próprio jogo é compilado do mesmo jeito neste PC e também seria bloqueado. Libere a pasta do instalador no seu antivírus ou desative o Controle Inteligente de Aplicativos na Segurança do Windows (Controle de aplicativos e do navegador) e rode o instalador de novo.",
"check.vulkan_crash": "O driver de vídeo travou quando o instalador pediu a lista de placas de vídeo (código de saída {code}), mesmo com as camadas Vulkan de outros programas desativadas. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_layer_crash": "Uma camada Vulkan instalada por outro programa faz os programas Vulkan travarem neste PC (código de saída {code}), e o jogo travaria do mesmo jeito ao iniciar. A camada: {layers}. Atualize ou desinstale o programa ao qual ela pertence (o caminho mostra a pasta dele), ou desative a camada: defina para a sua conta de usuário a variável de ambiente VK_LOADER_LAYERS_DISABLE com o valor {disable}. Depois rode o instalador de novo.",
"check.vulkan_layers_crash": "Uma camada Vulkan instalada por outro programa faz os programas Vulkan travarem neste PC (código de saída {code}): com todas essas camadas desativadas a verificação passa, e com elas o jogo travaria do mesmo jeito ao iniciar. Desativar as camadas instaladas uma de cada vez não apontou qual é. Camadas instaladas: {layers}. Atualize ou desinstale os programas de overlay, gravação ou ajuste entre elas, ou desative todas essas camadas: defina para a sua conta de usuário a variável de ambiente VK_LOADER_LAYERS_DISABLE com o valor ~implicit~ (isso também desativa overlays como o da Steam em todos os jogos Vulkan). Depois rode o instalador de novo.",
"check.cpu_too_old": "Este processador não tem x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), o nível mais antigo para o qual o jogo é compilado. Intel Nehalem (2008) ou AMD Bulldozer (2011) e mais novos têm.",
"check.vulkan_missing": "Nenhum driver Vulkan está instalado. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_no_device": "O Vulkan não encontra nenhuma placa de vídeo. Instale o driver mais recente da sua placa de vídeo.",
@@ -118,6 +124,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.",
"warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.",
"warn.dlss_download_failed": "Não foi possível baixar o NVIDIA DLSS de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.",
"warn.fsr_kept": "Já existe uma biblioteca FSR na pasta de instalação ({path}); a instalação mantém as bibliotecas que estão lá.",
"warn.fsr_download_failed": "Não foi possível baixar o AMD FSR 4 de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.",
"ui.title": "Instalação do TotK",
"ui.rebuild_title": "Recompilando o jogo para os seus mods",
@@ -141,6 +149,8 @@
"ui.firmware_help": "Para textos em chinês, coreano e chinês tradicional: a pasta Contents/registered do firmware, por exemplo do Ryujinx ou do Yuzu. A instalação copia dela as fontes do sistema do Switch para a pasta de instalação.",
"ui.dlss": "Baixar o NVIDIA DLSS (nvngx_dlss.dll) para placas de vídeo NVIDIA RTX",
"ui.dlss_help": "Do DLSS SDK da NVIDIA no GitHub, sob a licença NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Sem ele as opções dlaa e DLSS não fazem nada.",
"ui.fsr": "Baixar o AMD FSR 4 (bibliotecas do FSR SDK da AMD) para placas de vídeo AMD Radeon",
"ui.fsr_help": "Do FSR SDK da AMD no GitHub, sob a licença do AMD FSR SDK (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Elas fazem a opção AMD FSR 4 do upscaler da cena 3D funcionar nas placas Radeon para as quais as bibliotecas da AMD oferecem o FSR 4; sem elas essa opção não faz nada. Vem marcada quando o computador tem uma placa de vídeo AMD.",
"ui.compressed_help": "Arquivos compactados NSZ e XCZ funcionam do jeito que estão: a instalação os descompacta sozinha (para isso, até os dados do jogo serem extraídos, ela precisa de tanto espaço livre quanto ocupam os arquivos descompactados).",
"ui.section_files": "Arquivos do jogo",
"ui.section_install": "Instalação",
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Рисование подсказок клавиатуры и мыши",
"step.shapes": "Раскладка экранов игры под ваши мониторы",
"step.dlss": "Загрузка NVIDIA DLSS",
"step.fsr": "Загрузка AMD FSR 4",
"step.cleanup": "Уборка",
"phase.check.host": "Проверка процессора и видеокарты",
@@ -40,6 +41,7 @@
"phase.prepare.pack": "Упаковка кэша шейдеров в один файл",
"phase.shapes.layouts": "Запись раскладок экрана и кнопок для каждой формы монитора",
"phase.dlss.download": "Загрузка nvngx_dlss.dll из DLSS SDK от NVIDIA",
"phase.fsr.download": "Загрузка библиотек FSR 4 из FSR SDK от AMD",
"phase.cleanup.ini": "Запись totk.ini",
"phase.cleanup.temp": "Удаление временных файлов",
@@ -57,6 +59,10 @@
"check.toolchain_broken": "Встроенный компилятор не работает: {detail}",
"check.glibc_old": "Библиотека C этой системы — glibc {version}; компилятору установщика нужна {need} или новее (она есть в Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 и новее). Обновление системы это исправит.",
"check.host_probe_failed": "Проверка компьютера не выполнилась (код выхода {code}).",
"check.host_blocked": "Windows заблокировала программу, которую установщик собрал на этом компьютере ({path}): {detail}. Интеллектуальное управление приложениями (Smart App Control), политика App Control или антивирус блокируют неподписанные программы; сама игра собирается на этом компьютере так же и тоже будет заблокирована. Разрешите папку установщика в антивирусе или отключите интеллектуальное управление приложениями в «Безопасности Windows» («Управление приложениями/браузером») и запустите установщик снова.",
"check.vulkan_crash": "Видеодрайвер аварийно завершился, когда установщик запросил список видеокарт (код выхода {code}), в том числе с отключёнными слоями Vulkan других программ. Установите свежий драйвер видеокарты.",
"check.vulkan_layer_crash": "Слой Vulkan, установленный другой программой, обрушивает Vulkan-программы на этом компьютере (код выхода {code}), и игра так же упадёт при запуске. Слой: {layers}. Обновите или удалите программу, которой он принадлежит (путь показывает её папку), или отключите слой: задайте для своей учётной записи переменную среды VK_LOADER_LAYERS_DISABLE со значением {disable}. Затем запустите установщик снова.",
"check.vulkan_layers_crash": "Слой Vulkan, установленный другой программой, обрушивает Vulkan-программы на этом компьютере (код выхода {code}): со всеми такими слоями отключёнными проверка проходит, а с ними игра так же упадёт при запуске. Отключение установленных слоёв по одному не выявило виновника. Установленные слои: {layers}. Обновите или удалите программы оверлея, записи или настройки среди них, или отключите все такие слои: задайте для своей учётной записи переменную среды VK_LOADER_LAYERS_DISABLE со значением ~implicit~ (это также отключит оверлеи вроде оверлея Steam во всех играх на Vulkan). Затем запустите установщик снова.",
"check.cpu_too_old": "Этому процессору не хватает x86-64-v2 (SSE4.2, POPCNT и CMPXCHG16B) — минимального уровня, под который собрана игра. Он есть у Intel Nehalem (2008) и AMD Bulldozer (2011) и новее.",
"check.vulkan_missing": "Драйвер Vulkan не установлен. Установите свежий драйвер видеокарты.",
"check.vulkan_no_device": "Vulkan не находит видеокарту. Установите свежий драйвер видеокарты.",
@@ -118,6 +124,8 @@
"warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.",
"warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.",
"warn.dlss_download_failed": "Не удалось загрузить NVIDIA DLSS с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.",
"warn.fsr_kept": "В папке установки уже есть библиотека FSR ({path}); установка оставляет имеющиеся библиотеки.",
"warn.fsr_download_failed": "Не удалось загрузить AMD FSR 4 с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.",
"ui.title": "Установка TotK",
"ui.rebuild_title": "Пересборка игры под ваши моды",
@@ -141,6 +149,8 @@
"ui.firmware_help": "Для текста на китайском и корейском: папка Contents/registered прошивки, например из Ryujinx или Yuzu. Установка скопирует из неё системные шрифты Switch в папку установки.",
"ui.dlss": "Загрузить NVIDIA DLSS (nvngx_dlss.dll) для видеокарт NVIDIA RTX",
"ui.dlss_help": "Из DLSS SDK от NVIDIA на GitHub, по лицензии NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Без него настройки dlaa и DLSS ничего не делают.",
"ui.fsr": "Загрузить AMD FSR 4 (библиотеки FSR SDK от AMD) для видеокарт AMD Radeon",
"ui.fsr_help": "Из FSR SDK от AMD на GitHub, по лицензии AMD FSR SDK (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). С ними работает вариант AMD FSR 4 в апскейлере 3D-сцены на тех видеокартах Radeon, для которых библиотеки AMD предлагают FSR 4; без них этот выбор ничего не делает. Отмечено по умолчанию, если в компьютере есть видеокарта AMD.",
"ui.compressed_help": "Сжатые файлы NSZ и XCZ подходят как есть: установка сама их распакует (для этого, пока извлекаются данные игры, нужно столько свободного места, сколько занимают распакованные файлы).",
"ui.section_files": "Файлы игры",
"ui.section_install": "Установка",
+225
View File
@@ -0,0 +1,225 @@
{
"step.check": "Kiểm tra máy tính và các tệp trò chơi",
"step.kit": "Sao chép bộ công cụ biên dịch vào thư mục trò chơi",
"step.fonts": "Trích xuất phông chữ hệ thống",
"step.extract": "Trích xuất trò chơi",
"step.lift": "Chuyển mã trò chơi sang C",
"step.compile": "Biên dịch {game_exe}",
"step.prepare": "Chuẩn bị shader",
"step.pc_prompts": "Vẽ biểu tượng nút bàn phím và chuột",
"step.shapes": "Bố trí giao diện trò chơi theo màn hình của bạn",
"step.dlss": "Tải xuống NVIDIA DLSS",
"step.fsr": "Tải xuống AMD FSR 4",
"step.cleanup": "Dọn dẹp",
"phase.check.host": "Kiểm tra bộ xử lý và card đồ họa",
"phase.check.verify": "Kiểm tra các tệp đã cài đặt",
"phase.check.verify_romfs": "Kiểm tra dữ liệu trò chơi đã cài đặt",
"phase.check.inputs": "Mở các tệp trò chơi bằng khóa",
"phase.check.unpack_base": "Giải nén trò chơi gốc đã nén",
"phase.check.unpack_update": "Giải nén bản cập nhật đã nén",
"phase.check.versions": "Kiểm tra phiên bản trò chơi",
"phase.kit.copy": "Sao chép các công cụ mà trò chơi dùng để tự biên dịch lại cho mod mã",
"phase.fonts.extract": "Trích xuất phông chữ dùng chung từ firmware",
"phase.fonts.copy": "Sao chép phông chữ dùng chung vào thư mục cài đặt",
"phase.extract.hash_base": "Tính tổng kiểm tra của trò chơi gốc",
"phase.extract.hash_update": "Tính tổng kiểm tra của bản cập nhật",
"phase.extract.exefs": "Trích xuất mã trò chơi",
"phase.extract.copy": "Sao chép dữ liệu trò chơi",
"phase.extract.merge": "Áp dụng bản cập nhật vào dữ liệu trò chơi",
"phase.extract.diagnose": "Tìm tệp trò chơi bị hỏng",
"phase.extract.index": "Xác minh dữ liệu trò chơi",
"phase.lift.discover": "Tìm các hàm",
"phase.lift.emit": "Ghi mã C",
"phase.compile.compile": "Biên dịch",
"phase.compile.link": "Liên kết {game_exe}",
"phase.prepare.romfs_patches": "Ghi các bản vá dữ liệu trò chơi cho 60 fps",
"phase.pc_prompts.draw": "Vẽ biểu tượng phím và nút chuột theo các phím gán trong totk.ini",
"phase.prepare.seed": "Đọc shader từ dữ liệu trò chơi",
"phase.prepare.translate": "Chuyển đổi shader",
"phase.prepare.libraries": "Biên dịch shader cho trình điều khiển đồ họa",
"phase.prepare.pack": "Đóng gói bộ nhớ đệm shader thành một tệp",
"phase.shapes.layouts": "Ghi bố cục màn hình và biểu tượng nút cho từng tỷ lệ màn hình",
"phase.dlss.download": "Tải xuống nvngx_dlss.dll từ DLSS SDK của NVIDIA",
"phase.fsr.download": "Tải xuống các thư viện FSR 4 từ FSR SDK của AMD",
"phase.cleanup.ini": "Ghi totk.ini",
"phase.cleanup.temp": "Xóa các tệp tạm",
"cli.usage": "Dòng lệnh không hợp lệ: {detail}",
"internal": "Lỗi không mong muốn ({exception}): {detail}",
"state.unreadable": "Không thể đọc {path}. Hãy chọn thư mục khác hoặc xóa tệp đó.",
"state.newer_format": "{path} được ghi bởi một trình cài đặt mới hơn. Hãy dùng trình cài đặt đó hoặc chọn thư mục khác.",
"state.output_changed": "Các tệp đã cài đặt của bước '{step}' đã thay đổi kể từ khi được tạo; bước đó sẽ chạy lại.",
"check.release_incomplete": "Thư mục trình cài đặt không đầy đủ; còn thiếu: {paths}. Hãy giải nén lại bản phát hành.",
"check.dest_not_folder": "Vị trí cài đặt {path} là một tệp, không phải thư mục.",
"check.dest_not_empty": "Thư mục cài đặt {path} không trống và không chứa bản cài đặt nào trước đó. Hãy chọn một thư mục trống.",
"check.lang_missing": "Hãy chọn ngôn ngữ trò chơi.",
"check.lang_unknown": "Ngôn ngữ không xác định '{lang}'. Các ngôn ngữ đã biết: {known}.",
"check.toolchain_broken": "Trình biên dịch đi kèm không hoạt động: {detail}",
"check.glibc_old": "Thư viện C của hệ thống này là glibc {version}; trình biên dịch của trình cài đặt cần {need} trở lên (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 và mới hơn đều có). Cập nhật hệ thống sẽ khắc phục lỗi này.",
"check.host_probe_failed": "Không chạy được bước kiểm tra máy tính (mã thoát {code}).",
"check.host_blocked": "Windows đã chặn một chương trình mà trình cài đặt biên dịch trên máy tính này ({path}): {detail}. Smart App Control (Kiểm soát ứng dụng thông minh), một chính sách App Control hoặc phần mềm diệt virus chặn các chương trình không có chữ ký; bản thân trò chơi cũng được biên dịch trên máy tính này theo cách tương tự nên cũng sẽ bị chặn. Hãy cho phép thư mục trình cài đặt trong phần mềm diệt virus, hoặc tắt Smart App Control trong Bảo mật Windows (Kiểm soát ứng dụng và trình duyệt), rồi chạy lại trình cài đặt.",
"check.vulkan_crash": "Trình điều khiển đồ họa bị lỗi khi trình cài đặt yêu cầu danh sách card đồ họa (mã thoát {code}), kể cả khi đã tắt các lớp Vulkan của chương trình khác. Hãy cài đặt trình điều khiển mới nhất cho card đồ họa của bạn.",
"check.vulkan_layer_crash": "Một lớp Vulkan do chương trình khác cài đặt làm các chương trình Vulkan trên máy tính này bị lỗi (mã thoát {code}), và trò chơi cũng sẽ bị lỗi khi khởi động theo cách tương tự. Lớp đó: {layers}. Hãy cập nhật hoặc gỡ cài đặt chương trình sở hữu lớp này (đường dẫn cho biết thư mục của chương trình), hoặc tắt lớp đó: đặt biến môi trường VK_LOADER_LAYERS_DISABLE thành {disable} cho tài khoản người dùng của bạn. Sau đó chạy lại trình cài đặt.",
"check.vulkan_layers_crash": "Một lớp Vulkan do chương trình khác cài đặt làm các chương trình Vulkan trên máy tính này bị lỗi (mã thoát {code}): khi tắt tất cả các lớp như vậy thì bước kiểm tra thành công, còn khi bật chúng thì trò chơi cũng sẽ bị lỗi khi khởi động theo cách tương tự. Tắt lần lượt từng lớp đã cài đặt không xác định được lớp gây lỗi. Các lớp đã cài đặt: {layers}. Hãy cập nhật hoặc gỡ cài đặt các chương trình lớp phủ (overlay), quay màn hình hoặc tinh chỉnh trong số đó, hoặc tắt tất cả các lớp như vậy: đặt biến môi trường VK_LOADER_LAYERS_DISABLE thành ~implicit~ cho tài khoản người dùng của bạn (thao tác này cũng tắt các lớp phủ như của Steam trong mọi trò chơi Vulkan). Sau đó chạy lại trình cài đặt.",
"check.cpu_too_old": "Bộ xử lý này không hỗ trợ x86-64-v2 (SSE4.2, POPCNT và CMPXCHG16B), mức thấp nhất mà trò chơi được biên dịch cho. Intel Nehalem (2008) hoặc AMD Bulldozer (2011) trở lên đều hỗ trợ.",
"check.vulkan_missing": "Chưa cài đặt trình điều khiển Vulkan nào. Hãy cài đặt trình điều khiển mới nhất cho card đồ họa của bạn.",
"check.vulkan_no_device": "Vulkan không tìm thấy card đồ họa nào. Hãy cài đặt trình điều khiển mới nhất cho card đồ họa của bạn.",
"check.vulkan_too_old": "Trò chơi cần card đồ họa hỗ trợ Vulkan 1.3; tìm thấy: {devices}. Hãy cập nhật trình điều khiển đồ họa.",
"check.no_display": "Cần có màn hình hiển thị để chuẩn bị shader. Hãy chạy trình cài đặt từ phiên làm việc trên màn hình nền (desktop), hoặc export DISPLAY=:0 (trên Steam Deck ở Game Mode thì thêm XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Cần có các tệp trò chơi: hãy chọn trò chơi gốc, bản cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3 và prod.keys.",
"check.input_missing": "Không tìm thấy tệp ({input}): {path}",
"check.keys_unreadable": "Không thể đọc tệp khóa. Hãy chọn một tệp prod.keys.",
"check.keys_no_header_key": "Tệp khóa không có header_key. Hãy trích xuất lại prod.keys từ máy console của bạn.",
"check.keys_wrong": "Các khóa này không mở được tệp {input}. Hãy dùng prod.keys của chính máy console của bạn.",
"check.keys_too_old": "Tệp khóa quá cũ đối với tệp {input} (cần thế hệ khóa {generation}). Hãy trích xuất prod.keys từ máy console có firmware mới hơn.",
"check.not_game_file": "Tệp {input} không phải là tệp trò chơi XCI, NSP, XCZ hoặc NSZ.",
"check.file_unreadable": "Không thể đọc tệp {input}: {detail}",
"check.unpack_failed": "Không thể giải nén tệp nén {input}: {detail}",
"check.ticket_personalized": "Tệp {input} chứa ticket cá nhân hóa (personalized); cần có ticket chung (common).",
"check.ticket_missing": "Tệp {input} thiếu ticket mà nội dung của nó cần.",
"check.base_not_totk": "Tệp trò chơi gốc không phải là The Legend of Zelda: Tears of the Kingdom ({detail}).",
"check.base_is_update": "Tệp trò chơi gốc là một bản cập nhật. Hãy chọn NSP hoặc XCI của trò chơi gốc (phiên bản 1.0.0) ở đây và chọn tệp này làm bản cập nhật.",
"check.base_combined": "Tệp trò chơi gốc chứa nhiều gói (trò chơi gốc, bản cập nhật hoặc DLC trong cùng một tệp). Hãy chọn bản dump trò chơi gốc chỉ chứa trò chơi.",
"check.update_not_nsp": "Bản cập nhật phải là tệp NSP hoặc NSZ.",
"check.update_is_base": "Tệp cập nhật chứa trò chơi gốc. Hãy chọn tệp NSP của bản cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3.",
"check.update_not_totk": "Tệp cập nhật không phải là bản cập nhật của Tears of the Kingdom ({detail}).",
"check.exefs_failed": "Mã trò chơi trong tệp {input} không vượt qua bước kiểm tra; xem {log}.",
"check.input_damaged": "Tệp {input} bị hỏng hoặc không đầy đủ: {path} ({detail}). Hãy sao chép lại tệp đó từ nguồn của nó hoặc dump lại, rồi chạy lại trình cài đặt.",
"check.base_wrong_version": "Trò chơi gốc không phải phiên bản 1.0.0 ({modules} khác biệt).",
"check.update_wrong_version": "Bản cập nhật là phiên bản {found}; bản phát hành này yêu cầu {wanted}.",
"check.disk_space": "Không đủ dung lượng trống cho {path}: cần {need_gb} GB, còn trống {free_gb} GB.",
"check.firmware_missing": "Thư mục firmware {path} không tồn tại. Hãy chọn thư mục Contents/registered của firmware.",
"check.firmware_empty": "Thư mục firmware {path} không chứa tệp NCA nào. Hãy chọn thư mục Contents/registered của firmware.",
"check.fonts_keys_needed": "Phông chữ dùng chung cho ngôn ngữ này chưa được cài đặt; hãy chọn prod.keys để trình cài đặt trích xuất chúng từ firmware.",
"extract.exefs_mismatch": "Mã trò chơi đã trích xuất không khớp với phiên bản {version} ({modules}).",
"extract.romfs_merge_failed": "Áp dụng bản cập nhật vào dữ liệu trò chơi không thành công: {detail}. Chi tiết: {log}",
"extract.romfs_mismatch": "Dữ liệu trò chơi đã trích xuất không khớp với phiên bản {version} (kích thước {size}, tổng kiểm tra {sha256}...).",
"fonts.failed": "Trích xuất phông chữ dùng chung không thành công (mã thoát {code}): {detail}. Chi tiết: {log}",
"fonts.incomplete": "Quá trình trích xuất phông chữ dùng chung không ghi đủ mọi tệp ({files}).",
"fonts.copy_failed": "Không thể sao chép phông chữ dùng chung vào {path}: {detail}",
"lift.failed": "Chuyển mã trò chơi không thành công (mã thoát {code}). Chi tiết: {log}",
"compile.failed": "Biên dịch {game_exe} không thành công (mã thoát {code}). Chi tiết: {log}",
"compile.exe_in_use": "{path} đang được sử dụng. Hãy đóng trò chơi rồi chạy lại trình cài đặt.",
"kit.in_use": "{path} đang được sử dụng. Hãy đóng trò chơi và mọi cửa sổ cài đặt hoặc biên dịch lại đang mở, rồi chạy lại trình cài đặt.",
"kit.copy_failed": "Không thể sao chép bộ công cụ biên dịch vào {path}: {detail}",
"compile.exe_locked": "Không thể ghi {path}: một chương trình khác đang giữ tệp này, có thể là trò chơi được khởi động từ thư mục đó hoặc phần mềm diệt virus đã gắn cờ tệp. Hãy đóng trò chơi, thêm thư mục trình cài đặt và thư mục cài đặt vào danh sách loại trừ của phần mềm diệt virus, khởi động lại Windows, rồi chạy lại trình cài đặt. Chi tiết: {log}",
"prepare.xlate_in_use": "{path} đang được sử dụng. Hãy đóng trò chơi, kết thúc mọi tiến trình totk_xlate còn sót lại từ lần chạy trước, rồi chạy lại trình cài đặt.",
"prepare.shader_list_missing": "Thiếu danh sách shader.",
"prepare.romfs_patches_failed": "Ghi các bản vá dữ liệu trò chơi không thành công (mã thoát {code}). Chi tiết: {log}",
"prepare.shaders_failed": "Chuẩn bị shader không thành công (mã thoát {code}). Chi tiết: {log}",
"cleanup.romfs_unreadable": "Dữ liệu trò chơi trong {path} bị thiếu hoặc không đọc được sau khi cài đặt. Hãy khởi động lại Windows, rồi chạy lại trình cài đặt trên cùng thư mục đó: trình cài đặt sẽ trích xuất lại dữ liệu trò chơi và giữ nguyên phần còn lại.",
"prepare.pack_failed": "Đóng gói bộ nhớ đệm shader không thành công (mã thoát {code}). Chi tiết: {log}",
"cleanup.ini_failed": "Không thể ghi totk.ini: {detail}",
"warn.lang_needs_fonts": "Văn bản bằng {lang} cần phông chữ hệ thống của Switch, nhưng chưa có phông chữ nào được cung cấp. Trò chơi sẽ không khởi động bằng ngôn ngữ này cho đến khi chúng được thêm vào. Hãy chọn thư mục firmware (Contents/registered), hoặc xem mục \"Switch system fonts\" trong docs/installer.md.",
"warn.npdm_differs": "main.npdm khác với bản dump tham chiếu {version}; chỉ các mô-đun mã được sử dụng.",
"warn.cheats_skipped": "Không thể biên dịch các cheat trong thư mục mods có thay đổi mã của trò chơi; trò chơi sẽ được cài đặt mà không có chúng. Chi tiết: {log}",
"warn.exefs_skipped": "Không thể biên dịch các bản vá ExeFS của mod (.ips, .pchtxt); trò chơi sẽ được cài đặt mà không có chúng. Chi tiết: {log}",
"warn.plugins_skipped": "Không thể biên dịch các plugin mã của mod (exefs subsdk); trò chơi sẽ được cài đặt mà không có chúng. Chi tiết: {log}",
"warn.xbox_prompts_failed": "Không thể chuẩn bị biểu tượng nút Xbox, PlayStation hoặc PC (mã thoát {code}); trò chơi giữ biểu tượng nút của Switch. Chi tiết: {log}",
"warn.shaders_skipped": "Trình điều khiển đồ họa bị lỗi khi biên dịch một số shader, nên {count} shader đã bị bỏ qua khi chuẩn bị. Trò chơi sẽ biên dịch chúng khi cần đến lần đầu, và trình điều khiển cũng có thể bị lỗi ở đó; cập nhật trình điều khiển có thể khắc phục điều này. Chi tiết: {log}",
"warn.kernel_old": "Linux {version} thiếu tính năng theo dõi ghi (write tracking) mà trò chơi cần (6.7 trở lên); trò chơi có thể chạy rất chậm. Cập nhật hệ thống sẽ khắc phục điều này.",
"warn.dlss_kept": "Thư mục cài đặt đã có một thư viện DLSS ({path}); trình cài đặt giữ nguyên thư viện đó.",
"warn.dlss_download_failed": "Không thể tải xuống NVIDIA DLSS từ {url}: {detail}. Trò chơi vẫn chạy mà không có DLSS; lần chạy trình cài đặt tiếp theo sẽ thử lại.",
"warn.fsr_kept": "Thư mục cài đặt đã có một thư viện FSR ({path}); trình cài đặt giữ nguyên các thư viện đó.",
"warn.fsr_download_failed": "Không thể tải xuống AMD FSR 4 từ {url}: {detail}. Trò chơi vẫn chạy mà không có nó; lần chạy trình cài đặt sau sẽ thử lại.",
"ui.title": "Cài đặt TotK",
"ui.rebuild_title": "Biên dịch lại trò chơi cho các mod của bạn",
"ui.start_game": "Khởi động trò chơi",
"ui.version": "phiên bản {version}",
"ui.intro": "Tạo một thư mục Tears of the Kingdom có thể chơi được từ chính các tệp trò chơi của bạn. Quá trình này mất khá nhiều thời gian và chỉ chạy một lần.",
"ui.notice": "Thư mục do trình cài đặt này tạo ra có chứa trò chơi. Thư mục này chỉ dành cho mục đích sử dụng cá nhân; không chia sẻ hoặc tải lên.",
"ui.keys_private": "Tệp khóa được đọc tại chỗ. Nội dung của tệp không bao giờ được hiển thị, sao chép hoặc lưu trữ.",
"ui.base": "Trò chơi gốc",
"ui.update": "Bản cập nhật",
"ui.keys": "prod.keys",
"ui.firmware": "Firmware (tùy chọn)",
"ui.game_language": "Ngôn ngữ trò chơi",
"ui.dest": "Thư mục cài đặt",
"ui.browse": "Duyệt...",
"ui.pick_game": "Chọn tệp trò chơi gốc",
"ui.pick_update": "Chọn tệp cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3",
"ui.pick_keys": "Chọn prod.keys",
"ui.pick_firmware": "Chọn thư mục firmware của Switch (Contents/registered)",
"ui.pick_dest": "Chọn thư mục cài đặt",
"ui.firmware_help": "Dành cho văn bản tiếng Trung Giản thể, tiếng Hàn và tiếng Trung Phồn thể: thư mục Contents/registered của firmware, ví dụ từ Ryujinx hoặc Yuzu. Trình cài đặt sẽ sao chép phông chữ hệ thống của Switch từ đó vào thư mục cài đặt.",
"ui.dlss": "Tải xuống NVIDIA DLSS (nvngx_dlss.dll) cho card đồ họa NVIDIA RTX",
"ui.dlss_help": "Từ DLSS SDK của NVIDIA trên GitHub, theo giấy phép RTX SDK của NVIDIA (github.com/NVIDIA/DLSS). Thư viện này giúp các tùy chọn dlaa và DLSS hoạt động; nếu không có, các tùy chọn đó không có tác dụng.",
"ui.fsr": "Tải xuống AMD FSR 4 (thư viện FSR SDK của AMD) cho card đồ họa AMD Radeon",
"ui.fsr_help": "Từ FSR SDK của AMD trên GitHub, theo giấy phép FSR SDK của AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Thư viện này giúp lựa chọn AMD FSR 4 cho bộ nâng độ phân giải cảnh 3D hoạt động trên các card Radeon mà thư viện của AMD hỗ trợ FSR 4; nếu không có, lựa chọn đó không có tác dụng. Được chọn sẵn khi máy có card đồ họa AMD.",
"ui.compressed_help": "Các tệp nén NSZ và XCZ dùng được ngay: trình cài đặt tự giải nén chúng (cho đến khi dữ liệu trò chơi được trích xuất xong, cần dung lượng trống bằng dung lượng của các tệp sau khi giải nén).",
"ui.section_files": "Tệp trò chơi",
"ui.section_install": "Cài đặt",
"ui.more_details": "▸ Xem thêm chi tiết",
"ui.fewer_details": "▾ Ẩn chi tiết",
"ui.formats_help": "Trò chơi gốc: NSP, XCI, NSZ hoặc XCZ. Bản cập nhật: 1.1.0, 1.2.1 hoặc 1.4.3, dạng NSP hoặc NSZ.",
"ui.type_game": "Tệp trò chơi (NSP, XCI, NSZ, XCZ)",
"ui.type_keys": "Tệp khóa (*.keys)",
"ui.type_all": "Tất cả các tệp",
"ui.start": "Bắt đầu",
"ui.cancel": "Hủy",
"ui.cancelling": "Đang hủy...",
"ui.show_log": "Hiện nhật ký",
"ui.hide_log": "Ẩn nhật ký",
"ui.close": "Đóng",
"ui.back": "Quay lại",
"ui.open_folder": "Mở thư mục",
"ui.update_mode": "Thư mục này có một bản cài đặt trước đó. Trình cài đặt sẽ tiếp tục hoặc cập nhật bản cài đặt đó; các tệp trò chơi chỉ được yêu cầu nếu cần dùng lại.",
"ui.need_dest": "Hãy chọn thư mục cài đặt.",
"ui.need_base": "Hãy chọn tệp trò chơi gốc.",
"ui.need_update": "Hãy chọn tệp cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3.",
"ui.need_keys": "Hãy chọn tệp prod.keys.",
"ui.need_lang": "Hãy chọn ngôn ngữ trò chơi.",
"ui.missing_base": "Tệp trò chơi gốc không tồn tại.",
"ui.missing_update": "Tệp cập nhật không tồn tại.",
"ui.missing_keys": "Tệp khóa không tồn tại.",
"ui.missing_firmware": "Thư mục firmware không tồn tại.",
"ui.running_install": "Đang cài đặt",
"ui.running_resume": "Đang tiếp tục lần cài đặt trước",
"ui.running_update": "Đang cập nhật bản cài đặt",
"ui.state_started": "đã bắt đầu",
"ui.state_done": "xong",
"ui.state_skipped": "đã bỏ qua",
"ui.state_pending": "đang chờ",
"ui.state_running": "đang chạy",
"ui.state_failed": "thất bại",
"ui.log_warning": "Cảnh báo",
"ui.log_error": "Lỗi",
"ui.log_space": "Dung lượng cần: {need} GB, còn trống: {free} GB",
"ui.log_end": "Đã hoàn tất",
"ui.result_ok": "Trò chơi đã sẵn sàng",
"ui.result_failed": "Cài đặt không thành công",
"ui.result_cancelled": "Đã hủy cài đặt",
"ui.done_text": "Hãy khởi động {game_exe} từ {dest}. Chương trình cài đặt và các tệp trò chơi bạn đã chọn không còn cần thiết nữa.",
"ui.cancelled_text": "Các bước đã hoàn tất được giữ lại. Hãy chạy lại trình cài đặt với cùng thư mục để tiếp tục.",
"ui.log_file": "Tệp nhật ký: {path}",
"ui.process_died": "Trình cài đặt đã dừng đột ngột (mã thoát {code}).",
"ui.confirm_cancel": "Trình cài đặt đang chạy. Hủy cài đặt và đóng cửa sổ?",
"ui.space_one": "Dung lượng trống cần có trên {path}: {need} GB (còn trống: {free} GB).",
"ui.space_two": "Dung lượng trống cần có trên {path}: {need} GB (còn trống: {free} GB); trên {temp}: {temp_need} GB (còn trống: {temp_free} GB).",
"ui.amount_bytes": "{done} / {total} GB",
"ui.amount_chunks": "{done} / {total} phần",
"ui.amount_objects": "{done} / {total} tệp",
"ui.amount_shaders": "{done} / {total} shader",
"ui.amount_other": "{done} / {total} {unit}",
"ui.seconds": "{n} giây",
"param.input.base": "trò chơi gốc",
"param.input.update": "cập nhật",
"param.input.keys": "khóa",
"launcher.title": "Cài đặt TotK",
"launcher.python_missing": "Các tệp cài đặt không đầy đủ: thiếu thư mục python bên cạnh TotK-Setup.exe. Hãy giải nén lại toàn bộ tệp lưu trữ và khởi động TotK-Setup.exe từ thư mục đã giải nén.",
"lang.ja": "Tiếng Nhật",
"lang.en-US": "Tiếng Anh (Mỹ)",
"lang.en-GB": "Tiếng Anh (Anh)",
"lang.fr": "Tiếng Pháp",
"lang.fr-CA": "Tiếng Pháp (Canada)",
"lang.de": "Tiếng Đức",
"lang.it": "Tiếng Ý",
"lang.es": "Tiếng Tây Ban Nha",
"lang.es-419": "Tiếng Tây Ban Nha (Mỹ Latinh)",
"lang.nl": "Tiếng Hà Lan",
"lang.pt": "Tiếng Bồ Đào Nha",
"lang.pt-BR": "Tiếng Bồ Đào Nha (Brazil)",
"lang.ru": "Tiếng Nga",
"lang.ko": "Tiếng Hàn",
"lang.zh-Hans": "Tiếng Trung (Giản thể)",
"lang.zh-Hant": "Tiếng Trung (Phồn thể)"
}
+10
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "绘制键盘和鼠标按键提示",
"step.shapes": "为你的显示器调整游戏画面布局",
"step.dlss": "下载 NVIDIA DLSS",
"step.fsr": "下载 AMD FSR 4",
"step.cleanup": "清理",
"phase.check.host": "检查处理器和显卡",
@@ -40,6 +41,7 @@
"phase.prepare.pack": "将着色器缓存打包成一个文件",
"phase.shapes.layouts": "为每种显示器比例写入画面布局和按键提示",
"phase.dlss.download": "从 NVIDIA 的 DLSS SDK 下载 nvngx_dlss.dll",
"phase.fsr.download": "从 AMD 的 FSR SDK 下载 FSR 4 库",
"phase.cleanup.ini": "写入 totk.ini",
"phase.cleanup.temp": "删除临时文件",
@@ -57,6 +59,10 @@
"check.toolchain_broken": "自带的编译器无法工作:{detail}",
"check.glibc_old": "此系统的 C 库为 glibc {version};安装程序的编译器需要 {need} 或更新版本(Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 及更新版本都满足)。更新系统即可解决。",
"check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。",
"check.host_blocked": "Windows 阻止了安装程序在这台电脑上编译的程序({path}):{detail}。智能应用控制、App Control 策略或杀毒软件会阻止未签名的程序;游戏本身也以同样方式在这台电脑上编译,同样会被阻止。请在杀毒软件中允许安装程序所在的文件夹,或在 Windows 安全中心(应用和浏览器控制)中关闭智能应用控制,然后重新运行安装程序。",
"check.vulkan_crash": "安装程序向显卡驱动查询显卡时,驱动崩溃了(退出代码 {code}),关闭其他程序的 Vulkan 层后依然如此。请为你的显卡安装最新的驱动程序。",
"check.vulkan_layer_crash": "另一个程序安装的 Vulkan 层会让这台电脑上的 Vulkan 程序崩溃(退出代码 {code}),游戏启动时也会同样崩溃。该层:{layers}。请更新或卸载它所属的程序(路径显示了它的文件夹),或者关闭该层:为你的用户帐户设置环境变量 VK_LOADER_LAYERS_DISABLE,值为 {disable}。然后重新运行安装程序。",
"check.vulkan_layers_crash": "另一个程序安装的 Vulkan 层会让这台电脑上的 Vulkan 程序崩溃(退出代码 {code}):关闭所有此类层后检查通过,开着它们时游戏启动也会同样崩溃。逐个关闭已安装的层未能找出是哪一个。已安装的层:{layers}。请更新或卸载其中的叠加层、录制或调校程序,或者关闭所有此类层:为你的用户帐户设置环境变量 VK_LOADER_LAYERS_DISABLE,值为 ~implicit~(这也会在所有 Vulkan 游戏中关闭 Steam 等叠加层)。然后重新运行安装程序。",
"check.cpu_too_old": "此处理器不支持 x86-64-v2(SSE4.2、POPCNT 和 CMPXCHG16B),这是游戏所需的最低指令集。Intel Nehalem(2008 年)或 AMD Bulldozer(2011 年)及更新的处理器都支持。",
"check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。",
"check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。",
@@ -118,6 +124,8 @@
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
"warn.dlss_download_failed": "无法从 {url} 下载 NVIDIA DLSS:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。",
"warn.fsr_kept": "安装文件夹中已有 FSR 库({path});安装程序将保留其中的库。",
"warn.fsr_download_failed": "无法从 {url} 下载 AMD FSR 4:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。",
"ui.title": "TotK 安装程序",
"ui.rebuild_title": "正在为你的模组重新构建游戏",
@@ -141,6 +149,8 @@
"ui.firmware_help": "用于中文、韩文和繁体中文文本:固件的 Contents/registered 文件夹,例如来自 Ryujinx 或 Yuzu。安装程序会从中把 Switch 系统字体复制到安装文件夹。",
"ui.dlss": "为 NVIDIA RTX 显卡下载 NVIDIA DLSS(nvngx_dlss.dll)",
"ui.dlss_help": "来自 GitHub 上 NVIDIA 的 DLSS SDK,遵循 NVIDIA RTX SDK 许可(github.com/NVIDIA/DLSS)。没有它,dlaa 和 DLSS 设置不起作用。",
"ui.fsr": "为 AMD Radeon 显卡下载 AMD FSR 4(AMD 的 FSR SDK 库)",
"ui.fsr_help": "来自 GitHub 上 AMD 的 FSR SDK,遵循 AMD FSR SDK 许可(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)。有了这些库,3D 场景超分中的 AMD FSR 4 选项才能在 AMD 库提供 FSR 4 的 Radeon 显卡上工作;没有它们,该选项不起作用。电脑装有 AMD 显卡时默认勾选。",
"ui.compressed_help": "压缩的 NSZ 和 XCZ 文件可以直接使用:安装程序会自行解压(在游戏数据提取完成之前,需要与解压后文件大小相同的可用空间)。",
"ui.section_files": "游戏文件",
"ui.section_install": "安装",
+50 -8
View File
@@ -15,6 +15,11 @@ definitions then also write it.
A read that can see flags a callee left reads the caller's flags from before the call instead. AAPCS64 code never
reads a callee's flags, so such a read only sits on a path that does not run: in TotK it follows calls to noreturn
functions (asserts) that the compiler placed before another branch's target. Plan.after_call counts them.
A mod plugin's inline hook breaks that rule. exlaunch's exl_inline_hook_impl saves and restores x0..x29 around the
callback but not NZCV, so the hooked game code goes on with the flags the callback left (Challenge Mode's callbacks end
in a cmp, and the b.eq at their sites follows it). So in a plugin module flags pass through calls and returns (plan's
`through`), and a hook site takes the flags the stub's call left (plan's `hooks`).
"""
import re
@@ -26,7 +31,7 @@ NZ_DEF = 'c->nzcv = '
NZ_USE = '(c->nzcv)'
KIND_NAME = {'subs': 'sub', 'adds': 'add', 'logic': 'logic'}
ENTRY, CALL = 'entry', 'call'
ENTRY, CALL, HOOK = 'entry', 'call', 'hook' # HOOK: (HOOK, i), the callback's flags at hook site i
class FlagError(Exception):
@@ -55,6 +60,8 @@ class Plan:
self.reader = [None] * n
self.pack = [False] * n
self.exit = [None] * n # kind of the flags to publish in c->nzcv at a tail exit, or None
self.pre = [None] * n # kind of the flags to publish before a call whose callee sees them, or None
self.takes = [False] * n # the call leaves its callee's flags (F.nz from c->nzcv after it)
self.entry = False # F.nz starts as c->nzcv: flags from the entry reach a read or an exit
self.entry_read = False # they reach a read, not only an exit
self.after_call = 0 # reads that can see flags a callee left (see the module docstring)
@@ -69,6 +76,16 @@ class Plan:
k = self.exit[i]
return f'c->nzcv = fnz_{k}(&F); ' if k else ''
def give(self, i):
"""Statement writing the flags to c->nzcv before instruction i's call, whose callee sees them (plan's through
and hooks; '' when it need not)."""
k = self.pre[i]
return f'c->nzcv = fnz_{k}(&F); ' if k else ''
def take(self, i):
"""Statement taking the flags the callee of instruction i's call left (plan's through and hooks)."""
return ' F.nz = c->nzcv;' if self.used and self.takes[i] else ''
def rewrite(self, i, code):
"""code of instruction i with its flag reads and writes on F."""
rk = self.reader[i]
@@ -91,7 +108,7 @@ class Plan:
return code
def plan(effects, succ, calls, exits):
def plan(effects, succ, calls, exits, through=(), hooks=()):
"""effects[i]: (reads, kind or None); succ[i]: successor indices inside the function; calls: indices of calls,
whose callee may leave any flags; exits: indices that can leave for another function other than by a call or a
return (a tail branch, falling into the next function, a br through rt_dispatch).
@@ -99,25 +116,41 @@ def plan(effects, succ, calls, exits):
Discovery can start a function inside another one (a branch target, a materialised address), and the code
before it then falls or branches into it with live flags. So a tail exit publishes the flags in c->nzcv, and a
function whose reads can see its entry flags starts F.nz from c->nzcv. Calls and returns publish nothing: AAPCS64
code neither passes flags to a callee nor reads a callee's, so a call's flags count as no definition."""
code neither passes flags to a callee nor reads a callee's, so a call's flags count as no definition.
through: calls whose flags pass both ways (a plugin module, see the module docstring; its returns are in exits):
each publishes the flags before the call (Plan.give) and defines F.nz from c->nzcv after it (Plan.take).
hooks: patched sites with a plugin inline hook before the site's own word, when the hook's set is on: the hook
publishes the flags before its call and leaves the callback's after it, which the site's own word reads unless it
writes flags itself. With the set off the flags are the ones before the site, so what follows can see both."""
n = len(effects)
p = Plan(n)
if not any(r or k for r, k in effects):
return p
p.used = True
hooks = set(hooks) - set(calls) # a hook before a bl: the bl's callee leaves the flags
reach = [set() for _ in range(n)]
reach[0].add(ENTRY)
work = [0]
while work:
i = work.pop()
out = {i} if effects[i][1] else ({CALL} if i in calls else reach[i])
if effects[i][1] or i in through:
out = {i}
elif i in calls:
out = {CALL}
elif i in hooks:
out = reach[i] | {(HOOK, i)}
else:
out = reach[i]
for s in succ[i]:
if not out <= reach[s]:
reach[s] |= out
work.append(s)
def kind(d):
return 'nz' if d == ENTRY else effects[d][1]
if d == ENTRY or isinstance(d, tuple):
return 'nz'
return effects[d][1] or 'nz' # a through call leaves its callee's flags packed
def use(r):
"""Kind a use of the definitions r reads; several kinds read the packed form, which they then all write."""
@@ -127,18 +160,27 @@ def plan(effects, succ, calls, exits):
if len(kinds) == 1:
return kinds.pop()
for d in r:
if d != ENTRY:
if isinstance(d, int) and effects[d][1]:
p.pack[d] = True
return 'nz' # several kinds, or none (unreachable)
def seen(i):
"""What a read or an exit at instruction i sees: at a hook site also the callback's flags."""
return reach[i] | {(HOOK, i)} if i in hooks else reach[i]
for i, (reads, _) in enumerate(effects):
if reads:
p.after_call += CALL in reach[i]
p.reader[i] = use(reach[i] - {CALL})
p.reader[i] = use(seen(i) - {CALL})
p.entry_read |= ENTRY in reach[i]
for i in exits:
# Entry flags alone are still in c->nzcv.
r = reach[i] - {CALL}
r = seen(i) - {CALL}
if r and r != {ENTRY}:
p.exit[i] = use(r)
for i in set(through) | hooks:
p.takes[i] = True
r = reach[i] - {CALL}
if r and r != {ENTRY}:
p.pre[i] = use(r)
return p
+96 -35
View File
@@ -96,10 +96,13 @@ def orig_name(a):
def open_module(name, path, base, table, plugin=False):
"""Module name for lifting: a plugin with a `plugin` line of the patch table (recomp/patches.py) is lifted from its
image after the init, its inline-hook stubs returning where they would branch to their trampolines."""
image after the init, its inline-hook stubs returning where they would branch to their trampolines. A game module's
`entry` lines are function starts of its lift."""
p = table.plugins.get(name)
if not p:
return Module(name, path, base, 'c', plugin=plugin)
mod = Module(name, path, base, 'c', plugin=plugin)
mod.entries = sorted(base + o for o in table.entries.get(name, ()))
return mod
image = Path(p['image']).read_bytes()
mod = Module(name, path, base, 'c', plugin=True, image=image, rets=[o + 12 for o in p['stubs']],
seeds=sorted(p['stubs'] | p['seeds']))
@@ -195,24 +198,58 @@ def discover(mod):
stats = {'seeds': int(len(seeds)), 'bl_targets': int(len(np.unique(bl_tgt))),
'materialised_targets': int(len(np.unique(mat))), 'initial_starts': int(len(starts))}
rounds = 0
while True:
rounds += 1
f = np.searchsorted(starts, br_src, side='right') - 1
live = f >= 0
f = np.where(live, f, 0)
lo = starts[f]
hi = np.where(f + 1 < len(starts), starts[np.minimum(f + 1, len(starts) - 1)], n)
out = live & ((br_tgt < lo) | (br_tgt >= hi))
new = np.setdiff1d(br_tgt[out], starts, assume_unique=False)
if not len(new):
break
starts = np.union1d(starts, new)
stats['rounds'] = rounds
def close(starts):
rounds = 0
while True:
rounds += 1
f = np.searchsorted(starts, br_src, side='right') - 1
live = f >= 0
f = np.where(live, f, 0)
lo = starts[f]
hi = np.where(f + 1 < len(starts), starts[np.minimum(f + 1, len(starts) - 1)], n)
out = live & ((br_tgt < lo) | (br_tgt >= hi))
new = np.setdiff1d(br_tgt[out], starts, assume_unique=False)
if not len(new):
return starts, rounds
starts = np.union1d(starts, new)
starts, stats['rounds'] = close(starts)
entries = getattr(mod, 'entries', ())
if entries:
extra = entry_starts(mod, starts, entries, br)
stats['entries'] = len(entries)
starts, more = close(np.union1d(starts, (np.asarray(sorted(extra), dtype=np.int64) - pc0) >> 2))
stats['rounds'] += more
stats['functions'] = int(len(starts))
return starts, stats
def entry_starts(mod, starts, entries, br):
"""The function starts mod's `entry` addresses add (recomp/patches.py): each entry, and every target of the jump
tables of the function that held it. A table whose cases fell on both sides of the new boundary would reach the
cases outside its function through rt_dispatch, which only enters function starts; with every case a start, the
table's br dispatches to them (the all-label fallback). An unresolved computed br there gets a warning: its targets
are not known, so a case past the entry would stop the game with a named fatal."""
out, pc0 = set(), mod.lo
for e in entries:
if not mod.in_text(e):
raise SystemExit(f'{mod.name}: the entry {e:#x} is outside its .text')
k = int(np.searchsorted(starts, (e - pc0) >> 2, side='right')) - 1
lo = pc0 + int(starts[k]) * 4
hi = pc0 + int(starts[k + 1]) * 4 if k + 1 < len(starts) else mod.hi
out.add(e)
if e == lo:
continue
for i in br[(br >= (lo - pc0) >> 2) & (br < (hi - pc0) >> 2)].tolist():
jt = jumptables.resolve(mod, pc0 + 4 * i, lo, hi)
if jt:
out.update(jt)
elif jumptables.is_computed(mod, pc0 + 4 * i, lo):
print(f'{mod.name}: warning: the entry {e:#x} lies in the function {lo:#x} with an unresolved table '
f'jump at {pc0 + 4 * i:#x}', flush=True)
return out
def estimate_sizes(mod, starts):
"""Estimated bytes of C per function (for chunking only; the manifest records the real sizes)."""
w = mod.words
@@ -316,7 +353,8 @@ class Emitter:
def replacements(self, a):
"""The lifted words of each alternative of the patched site a, in set order. Only the last word of an
alternative may branch (bl, b, b.cond / cbz / tbz, ret)."""
alternative may branch (bl, blr, b, b.cond / cbz / tbz, ret); a blr is a site's own word kept after an inline
hook."""
out = []
for _, words in self.patched[a]:
# ('call', target): a plugin's inline hook (recomp/patches.py @call), before the site's own instruction
@@ -325,7 +363,7 @@ class Emitter:
last = j == len(lifted) - 1
if r.kind == 'hook' and not last:
continue
if r.kind != 'op' and not (last and r.kind in ('bl', 'b', 'bcond', 'ret')):
if r.kind != 'op' and not (last and r.kind in ('bl', 'blr', 'b', 'bcond', 'ret')):
raise patches.PatchError(f'{a:#x}: replacement word {words[j]:08x} is a {r.kind}')
out.append(lifted)
return out
@@ -363,7 +401,7 @@ class Emitter:
def flag_plan(self, insns, entry, end, tables, succ):
"""recomp/flags.py plan for the function: each instruction's flag use over the flow succ (flow())."""
n = len(insns)
calls, effects, exits = set(), [], {n}
calls, effects, exits, hooks = set(), [], {n}, set()
for i, ins in enumerate(insns):
k, a = ins.kind, entry + 4 * i
if k in ('bl', 'blr'):
@@ -372,34 +410,45 @@ class Emitter:
exits.add(i)
elif k == 'br':
exits.add(i) # through rt_dispatch, also a table's default
elif k == 'ret' and self.mod.plugin:
exits.add(i) # a plugin's caller sees the flags it leaves (recomp/flags.py)
if a in self.patched:
effects.append(self.patched_effect(ins, a))
for words in self.replacements(a):
r = words[-1]
if r.kind == 'bl':
if r.kind in ('bl', 'blr'):
calls.add(i)
elif r.kind in ('b', 'bcond') and not entry <= r.target < end:
exits.add(i)
if any(w.kind == 'hook' for w in words):
hooks.add(i)
else:
effects.append(flags.effect(ins.cond if k == 'bcond' else ins.code or ''))
effects.append((False, None))
return flags.plan(effects, succ, calls, exits)
return flags.plan(effects, succ, calls, exits, through=calls if self.mod.plugin else (), hooks=hooks)
def patched_effect(self, ins, a):
"""Flag effect of a patched site: every alternative (the original and each replacement) must write the same
flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them)."""
flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them).
An alternative that only branches out of the module (a plugin's branch hook, whose trampoline runs the
original word) counts for none: it leaves with the flags from before the site, which its tail exit publishes
(flags.plan), and nothing after the site in this function sees it."""
alts = []
for words in [[ins]] + self.replacements(a):
for k, words in enumerate([[ins]] + self.replacements(a)):
fx = [flags.effect(w.code or '') if w.kind == 'op' else flags.effect(w.cond) for w in words
if w.kind in ('op', 'bcond')]
fx = [e for e in fx if e[0] or e[1]]
if len(fx) > 1:
raise patches.PatchError(f'{a:#x}: several flag-using words in one alternative')
last = words[-1]
if k and not fx and last.kind == 'b' and not self.mod.lo <= last.target < self.mod.hi:
continue
alts.append(fx[0] if fx else (False, None))
if any(e[1] != alts[0][1] for e in alts):
raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({[e[1] for e in alts]})')
reads = any(e[0] for e in alts)
if (alts[0][1] or reads) and (ins.kind == 'bl' or any(w[-1].kind == 'bl' for w in self.replacements(a))):
if (alts[0][1] or reads) and (ins.kind in ('bl', 'blr') or
any(w[-1].kind in ('bl', 'blr') for w in self.replacements(a))):
raise patches.PatchError(f'{a:#x}: a patched call that uses flags')
return reads, alts[0][1]
@@ -450,6 +499,12 @@ class Emitter:
def publish(i):
return fp.publish(i) if fp and fp.used else ''
def give(i): # flags a plugin's callee or a hook's callback sees (recomp/flags.py plan's through, hooks)
return fp.give(i) if fp and fp.used else ''
def take(i): # flags that callee or callback left
return fp.take(i) if fp and fp.used else ''
def jump(t, i):
if entry <= t < end:
return f'goto L_{t:x};'
@@ -478,12 +533,12 @@ class Emitter:
if fp.used:
out.append(' ' + fp.decl())
def call(t, a):
def call(t, a, i):
if t in starts:
refs.add(t)
return f'c->x[30] = {hx(a + 4)}; {spill}{fname(t)}(c);{reload_call}'
return f'{give(i)}c->x[30] = {hx(a + 4)}; {spill}{fname(t)}(c);{reload_call}{take(i)}'
self.stats['external_calls'] += 1
return f'c->x[30] = {hx(a + 4)}; {spill}c->pc = {hx(t)}; rt_dispatch(c);{reload_call}'
return f'{give(i)}c->x[30] = {hx(a + 4)}; {spill}c->pc = {hx(t)}; rt_dispatch(c);{reload_call}{take(i)}'
def op(i, code):
code = fx(i, code)
@@ -494,25 +549,29 @@ class Emitter:
if r.kind == 'op':
return op(i, r.code)
if r.kind == 'bl':
return call(r.target, a)
return call(r.target, a, i)
if r.kind == 'b':
return jump(r.target, i)
if r.kind == 'bcond':
return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}'
if r.kind == 'ret':
return f'{spill}return;'
if r.kind == 'blr': # an original call through a register (a plugin hooks Zonai Fieldworks' blr x8 sites)
return (f'{give(i)}c->pc = {r.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}'
f'{take(i)}')
if r.kind == 'hook':
# a call that writes no x30, the whole Cpu current before it and read back after it: the stub saves and
# restores x30 itself, and the callback may change any register through exlaunch's hook context
# exlaunch's hook impl saves no NZCV: the callback sees the flags and the site goes on with its own
refs.add(r.target)
self.stats['plugin_hook_calls'] += 1
return f'{spill}{fname(r.target)}(c);{reload}'
return f'{give(i)}{spill}{fname(r.target)}(c);{reload}{take(i)}'
raise patches.PatchError(f'{a:#x}: patched instruction is a {r.kind}')
def patch(i, ins, a):
"""if (switch) { replacement } else if ... else { original } for a patched site (recomp/patches.py); an
ordered set of a contested site tests the site's pick byte instead of its switch."""
if ins.kind not in ('op', 'bl', 'b', 'bcond'):
if ins.kind not in ('op', 'bl', 'blr', 'b', 'bcond'):
raise patches.PatchError(f'{a:#x}: patched instruction is a {ins.kind}')
line = ' '
n, values = self.picks.get(a, (None, {}))
@@ -548,9 +607,10 @@ class Emitter:
self.stats['spin_gates'] += 1
emit(i, ' ' + j if k == 'b' else f' if ({fx(i, ins.cond)}) {{ {j} }}')
elif k == 'bl':
emit(i, ' ' + call(ins.target, a))
emit(i, ' ' + call(ins.target, a, i))
elif k == 'blr':
emit(i, f' c->pc = {ins.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}')
emit(i, f' {give(i)}c->pc = {ins.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}'
f'{take(i)}')
elif k == 'br':
jt = tables.get(a)
if jt == 'all':
@@ -562,7 +622,7 @@ class Emitter:
else:
emit(i, f' {publish(i)}{spill}c->pc = {ins.target}; {MUSTTAIL} rt_dispatch(c);')
elif k == 'ret':
emit(i, f' {spill}return;')
emit(i, f' {publish(i)}{spill}return;')
else:
raise ValueError(f'{a:#x}: unknown instruction kind {k!r}')
n = len(insns)
@@ -992,8 +1052,9 @@ def main():
n = len(starts) if not args.limit else min(args.limit, len(starts))
ends = np.append(abs_starts[1:], mod.hi)
chunks = partition(est[:n], args.chunk_fns, args.chunk_bytes, args.big_fn)
missing = sorted(base + o for o in (table.plugins.get(name) or {}).get('seeds', ())
if base + o not in set(abs_starts.tolist()))
# a seed that is an `orig` trampoline counts as found: dispatch takes its address to the function's copy
missing = sorted(base + o for o in set((table.plugins.get(name) or {}).get('seeds', ())) |
table.entries.get(name, set()) if base + o not in set(abs_starts.tolist()) | set(extra))
if missing:
raise SystemExit(f'{name}: the seeds {", ".join(hex(a) for a in missing)} are no function starts')
mkey = module_key(gen_key, name, path, base, abs_starts)
+12
View File
@@ -1209,3 +1209,15 @@ site ability main 1622bf4 b4000155 aa0903f5 b4000155 # cbz x21 -> mov x21, x9;
# the game with the set off in two runs of two, a pause of 1 s in none of one.
set audiodrain TOTK_AUDIO_DRAIN_FIX 1
site audiodrain main 883780 17fffee6 17fffeda # b 0x883318 -> b 0x8832e8
# Thunderstorm lightning (issue #1287): as in patches-v143.txt, the same update (main+0xab849c, called from
# main+0xab7cf4) with the same chances and timers. The sites are the loads of 0.013333 (distant bolt) and of 0.01 (state
# 1, both draws through s9, which the prologue saves; state 5). The time object is loaded as the game's own trampoline
# check does (main+0xbda4bc): its global through the GOT slot main+0x462e038, then +0xc8. After each site x10, s2 and s3
# are written, or a call comes, before any read.
set lightning TOTK_LIGHTNING_FIX 1
site lightning main ab8d50 bd43fd01 bd43fd01 d001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0x3fc] (0.013333)
site lightning main ab9014 bd46f109 bd46f109 b001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220929 # ldr s9, [x8, #0x6f0] (0.01)
site lightning main ab8f90 bd46f101 bd46f101 d001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0x6f0] (0.01)
# each: the game's load; adrp x10, main+0x462e000; ldr x10, [x10, #0x38]; ldr x10, [x10]; ldr x10, [x10, #0xc8];
# ldr s2, [x10, #0x38] (ratio); fmov s3, #1.0; fminnm s2, s2, s3; fmul (chance * ratio)
+28
View File
@@ -1251,3 +1251,31 @@ site shutter main 25e55d0 bc605900 bc605900 f9402ea9 927ef529 39400129 1e230123
# keep their numbers.
set freecam TOTK_FREECAM_PATCH 0
site freecam main 6286d4 f9400e68 94d2de1f # ldr x8, [x19, #0x18]
# Thunderstorm lightning (issue #1287). While the current weather type has IsThunder (main+0x62a40c), the world
# manager's lightning update (main+0x62aac4, called once per frame from main+0x62a310) runs a state machine whose times
# advance by the world's frame step: near strikes for 150 to 450 units (state 1), a phase main+0x21c34d0 ends (2), 30
# and 240 units without (3, 4), then 1 again; 5 takes over from 1 when main+0x21d2930 returns false and leads back to 0.
# On top of it the update draws, each update, a random number in [0, 1) for each of three fixed chances: 0.013333 in
# every state but 0 for a distant bolt (bit 0 of its +8 flags, which main+0x58b4d8 hands to the environment, where
# main+0x69fb98 starts the effect Far_Lightning 2000 m from the camera along its view, picked by main+0x21c3940), 0.01
# in state 1 to pick a near strike (a point 90 m ahead of the camera, main+0x21c4c74, struck by main+0x21c3a6c once 90
# units of frame step pass without another pick) and 0.01 in states 1 and 5 for bit 3, which sets the environment
# input's flag +0x2e4 as a near strike does (main+0x58b4fc). Counted in one storm with a local build that logs each
# draw that succeeds: with the set off 22 distant bolts a minute at 30 fps, 52 at 60 and 94 to 96 at 120, each one a
# Far_Lightning effect, and bit 3 19, 34 and 64 to 80 times a minute of state 1. Near strikes stayed at 14 to 18 in
# 205 s at every rate: state 1 lets its last pick strike in state 2, where nothing is drawn, and state 2 ends with a
# strike of its own, so the picks that start the countdown again at high frame rates change little. Each site
# multiplies the chance it loads by the frame ratio, time object +0x38 ([[main+0x3ad27c8] + 0xc8], as the sets bounce
# and shutter read it), at most 1: above 30 fps the rates per second of 30 fps (counted: 26, 27 and 20 to 24 distant
# bolts a minute at 30, 60 and 120 fps, bit 3 12 to 17 times a minute of state 1), and at 30 fps and below the game's
# own chances. After each site x10 and the two scratch registers (s3 and s4 at the first,
# where s2 is the chance; s2 and s3 at the others) are written, or a call comes, before any read; at the second the
# chance is s9, which the prologue saves and both draws of state 1 compare with. Its own switch, lightning_fix
# (TOTK_LIGHTNING_FIX); 0 runs the game's loads.
set lightning TOTK_LIGHTNING_FIX 1
site lightning main 62b1fc bd472d02 bd472d02 f001a52a f943e54a f940654a bd403943 1e2e1004 1e247863 1e230842 # ldr s2, [x8, #0x72c] (0.013333)
site lightning main 62b3d8 bd4ccd09 bd4ccd09 f001a52a f943e54a f940654a bd403942 1e2e1003 1e237842 1e220929 # ldr s9, [x8, #0xccc] (0.01)
site lightning main 62b51c bd4ccd01 bd4ccd01 f001a52a f943e54a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0xccc] (0.01)
# each: the game's load; adrp x10, main+0x3ad2000; ldr x10, [x10, #0x7c8]; ldr x10, [x10, #0xc8];
# ldr s3 (s2), [x10, #0x38] (ratio); fmov s4 (s3), #1.0; fminnm (ratio, 1.0); fmul (chance * ratio)
+37 -9
View File
@@ -1,7 +1,8 @@
"""Code patch table for the generator: guest instructions replaced in the lifted C, switchable at run time.
Lifted code cannot be byte-patched when the game runs, so a patch is applied when the C is generated. A patch file
(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace:
(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace. A plugin image
path may be a JSON double-quoted string to preserve spaces, `#` and escaped characters:
set <name> <env> <default> [ordered] a patch set: a run-time switch <env>=0/1, <default> when it is unset
site <set> <module> <address> <original> <replacement> [<replacement> ...]
@@ -15,6 +16,7 @@ Lifted code cannot be byte-patched when the game runs, so a patch is applied whe
stub <module> <offset>
seed <module> <offset> [<offset> ...]
orig <set> <module> <offset> <function module> <function offset>
entry <module> <offset> [<offset> ...]
<address> is a module offset (hex), <original> the instruction word the module has there (checked; a mismatch stops
the generator), each <replacement> an instruction word (hex) or `@page:x<n>`, which is `adrp x<n>, <patch page>`
@@ -40,7 +42,7 @@ wins, a tie goes to the set later in the file). The other alternatives of a cont
their rt_patch_on test, so a cheat before the mods' sets still wins while it is on. A site with at most one ordered
set, and a table without contested sites, is emitted exactly as without the keyword.
The original may be any instruction but br, blr and ret; a replacement's last word may be
The original may be any instruction but br and ret; a replacement's last word may be
a bl (lifted with the site's return address), a b or b.cond / cbz / tbz (its target joins the function's labels when
inside it) or a ret; earlier words must not branch. Every alternative of a site writes the same flags. The generator
writes patches.h (set names, switches, the page address, the contested sites) next to layout.h for the runtime.
@@ -67,16 +69,24 @@ run's record; the design follows #845 by itaskaev2):
lifts the function at <function module>+<function offset> a second time without its patched sites
(fo_<address>) and lists that copy at the trampoline's address in <module>'s function table, so the call reaches
the original code and not the hook again.
An `entry` line names addresses of a game module that a plugin calls by pointer although they are no function start
of the game's code (Zonai Fieldworks calls main+0x481918 of 1.4.3, the second word of a function, skipping its first
test). gen.py makes each one a function start of the module's lift: the function that held it ends there and runs on
into it by a tail jump, as at any function boundary, so the game's own path through the code does not change.
tools/exefs_plugins.py writes them when a service run calls such an address (installer/steps.py lifts again).
A replacement word `@call:<module>+<offset>` is a call of the function there that writes no x30: every register in
the Cpu at the call and all read back after it (the callback may change any of them, as exlaunch's hook context
allows); the flags stay as they were. It may stand before the site's last word, which is then the original
instruction.
allows); the flags are published before it and taken back after it, since exlaunch's hook impl saves no NZCV and the
game code goes on with the flags the callback left (recomp/flags.py plan's hooks). It may stand before the site's last
word, which is then the original instruction.
A `hook` line names guest functions (module offsets of function starts; gen.py stops on any other address) whose
entry the runtime watches: their lifted C starts with FN_ENTER (runtime/cpu.h), a load of g_fnprof and a predicted
branch to fnprof_hit while the runtime sets it. A table with hook lines puts FN_ENTER into these functions only; a table
without any keeps it in every function, as does gen.py --fn-enter-all (a whole-game function-entry profile).
"""
import json
from pathlib import Path
PAGE = 0x1000
@@ -101,8 +111,9 @@ class Table:
from here (for_module, picks_for, spins_for, hooks_for) is in the lift cache's key (recomp/gen.py chunk_key); a new
kind of line the Emitter reads must go there too."""
def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None):
def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None, entries=None):
self.sets = list(sets)
self.entries = entries or {} # {module: {offset}}: `entry` lines
self.sites = sites or {}
self.page = page
self.spins = spins or {} # {module: {back-edge offset: head offset}}
@@ -184,13 +195,26 @@ class Table:
def load(path, mods):
"""Table from a patch file; mods is layout() output [(name, base, size)]."""
sets, index, sites, spins, hooks, ordered, plugins = [], {}, {}, {}, {}, set(), {}
sets, index, sites, spins, hooks, ordered, plugins, entries = [], {}, {}, {}, {}, set(), {}, {}
bases = {n: (b, s) for n, b, s in mods}
for no, raw in enumerate(Path(path).read_text(encoding='utf-8').splitlines(), 1):
f = raw.split('#', 1)[0].split()
where = f'{path}:{no}'
prefix = raw.split(None, 4)
if len(prefix) == 5 and prefix[0] == 'plugin' and prefix[4].startswith('"'):
try:
image, end = json.JSONDecoder().raw_decode(prefix[4])
except json.JSONDecodeError as e:
raise PatchError(f'{where}: invalid quoted plugin image: {e.msg}') from None
if not image:
raise PatchError(f'{where}: empty quoted plugin image')
tail = prefix[4][end:].strip()
if tail and not tail.startswith('#'):
raise PatchError(f'{where}: unexpected text after quoted plugin image')
f = prefix[:4] + [image]
else:
f = raw.split('#', 1)[0].split()
if not f:
continue
where = f'{path}:{no}'
if f[0] == 'set' and (len(f) == 4 or len(f) == 5 and f[4] == 'ordered'):
if f[1] in index:
raise PatchError(f'{where}: set {f[1]} defined twice')
@@ -239,6 +263,10 @@ def load(path, mods):
'seeds': set(), 'origs': {}}
elif f[0] in ('expect', 'stub', 'seed', 'orig'):
plugin_line(f, where, index, bases, plugins)
elif f[0] == 'entry' and len(f) >= 3:
if f[1] not in bases:
raise PatchError(f'{where}: module {f[1]} not in the layout')
entries.setdefault(f[1], set()).update(int(o, 16) for o in f[2:])
elif f[0] == 'hook' and len(f) >= 3:
if f[1] not in bases:
raise PatchError(f'{where}: module {f[1]} not in the layout')
@@ -250,7 +278,7 @@ def load(path, mods):
nxt = min((b for _, b, _ in mods if b > base), default=None)
if nxt is not None and page + PAGE > nxt:
raise PatchError(f'no room for the patch page after main ({page:#x})')
table = Table(sets, sites, page, spins, hooks, ordered, plugins)
table = Table(sets, sites, page, spins, hooks, ordered, plugins, entries)
table.bases = {n: b for n, (b, _) in bases.items()}
return table
+13 -12
View File
@@ -33,7 +33,7 @@ static int save_ok = 1; // the last cfg_save_to wrote (o
// logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line, and gets a
// description in totk.ini.example or docs/settings.md (tests/settings_doc_check.py checks both).
static const char *const known[] = {
"AB", "ABILITY_GUARD", "ADDR_REPORT", "AMIIBO_DIR", "ANISO", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_DRAIN_FIX", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"AB", "ABILITY_GUARD", "ADDR_REPORT", "AMIIBO_DIR", "ANISO", "ANV_VS_BARRIER", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_DRAIN_FIX", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT",
"BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS",
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP",
@@ -44,7 +44,7 @@ static const char *const known[] = {
"DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
"DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FG_DEBUG", "FG_OBJECTS", "FG_SHOT", "FG_SHOT_DIR", "FG_TEST", "FG_TIMES", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES",
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH",
"FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR_SHARPNESS",
"FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR4_DEBUG", "FSR_SHARPNESS",
"FULLSCREEN", "FXAA",
"GAMEPLAY_DISTANCE_SENSITIVITY", "GAMEPLAY_ITEM_AD", "GAMEPLAY_ITEM_SENSITIVITY", "GAMEPLAY_ITEM_WHEEL",
"GAMEPLAY_MAP_ZOOM", "GAMEPLAY_MAP_ZOOM_SENSITIVITY", "GAMEPLAY_ROTATION_SENSITIVITY", "GAMEPLAY_TWEAKS_ENABLED",
@@ -53,20 +53,20 @@ static const char *const known[] = {
"GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE",
"GYRO_AUTO_BIAS", "GYRO_BIAS_PAD", "GYRO_BIAS_X", "GYRO_BIAS_Y", "GYRO_BIAS_Z", "GYRO_CALIBRATION", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HEAP_LAZY", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIGHTNING_FIX", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG",
"MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
"MV_SURVEY",
"MV_SURVEY", "NULL_ATTACH",
"ONE_PER_CORE", "OPERATION_MODE", "OPTREF_GUARD", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "PERF_CENSUS", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PLUGIN_TICK_OFFSET", "PLUGIN_TRACE", "POINTER_IMAGE",
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_BENCH", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "QUICKLOAD_KEY", "QUICKSAVE", "QUICKSAVE_KEY", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_ASYNC", "REC_END", "REC_SPIN_US", "REEXEC", "REFLEX",
"RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHUNKS", "REPLAY_CHUNK_DRAWS", "REPLAY_SKEW_US", "REPLAY_STATE_CHECK", "REPLAY_WORKERS",
"REPLAY_CHECK", "REPORT_GUARD", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"REPLAY_CHECK", "REPORT_GUARD", "RESOLVE_CHECK", "RESTART_WAIT", "RESTBL_CACHE", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SCENE_UPSCALER", "SHADER_CACHE",
"SHADER_MEMO", "SHADOW", "SHADOW_DEFER", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHUTTER_FIX",
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
"SWKBD_ANSWER", "SYNC_AHEAD",
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PAD_RUMBLE_MS", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PAD_RUMBLE_MS", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", "VK_NO_HOST_IMPORT",
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VMA_BLOCK_MIB", "VOLUME", "VOLUME_MASK_BIAS", "VOLUME_MUSIC", "VOLUME_SFX", "VOLUME_VOICE", "VRAM_HEADROOM", "VRAM_LIMIT_MIB", "VS_OUTS",
"WALK_KEY", "WALK_SCALE", "WB_EAGER", "WB_EXACT", "WB_FENCE_LIMIT", "WB_MERGE", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS",
"ZSTD_CHECK", "ZSTD_NATIVE",
@@ -77,6 +77,7 @@ static const struct { const char *key, *section; } sections[] = {
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"}, {"FRAME_GEN", "frame rate"},
{"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"},
{"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"}, {"SHUTTER_FIX", "frame rate"},
{"LIGHTNING_FIX", "frame rate"},
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
{"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"},
{"HUD_WIDTH", "display"},
@@ -141,11 +142,11 @@ static const CfgMeta metas[] = {
{"HUD_WIDTH", "full", "full|21:9|16:9", RESTART},
{"DYNAMIC_RES", "1", "0|1", LIVE}, // resolution.c res_dynres_live
{"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE},
{"SCENE_UPSCALER", "off", "off|dlss|fsr3", RESTART}, {"DLAA", "0", "0|1", RESTART},
{"SCENE_UPSCALER", "off", "off|dlss|fsr3|fsr4", RESTART}, {"DLAA", "0", "0|1", RESTART},
{"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
{"FSR_SHARPNESS", "80", "0..100", LIVE}, // vk_dlaa.c fsr_evaluate
{"DLSS_PRESET", "default", "default|k|j", LIVE}, {"DLSS_FIXED_EXPOSURE", "0", "0|1", LIVE}, {"DLAA_EFFECTS_AFTER", "0", "0|1", LIVE},
{"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"REFLEX", "off", "off|on|boost", RESTART}, {"FXAA", "1", "0|1", LIVE},
{"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"REFLEX", "off", "off|auto|on|boost", RESTART}, {"FXAA", "1", "0|1", LIVE},
{"LOD_STEADY", "0", "0|1", RESTART}, // sets steady
{"ASPECT", "fit", "fit|stretch", LIVE}, {"MOVIE_ASPECT", "keep", "keep|stretch", LIVE}, {"FOV", "100", "70..140", LIVE},
{"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features
@@ -168,7 +169,7 @@ static const CfgMeta metas[] = {
{"MODS_REBUILD", "auto", "auto|off", RESTART},
{"MODS_WITHOUT_CODE", "0", "0|1", RESTART}, // 1: a mod is used without the code module it cannot run (mods.c)
{"HIGHFPS_FIX", "1", "0|1", RESTART}, {"CLIMB_FIX", "1", "0|1", RESTART}, {"AUDIO_DRAIN_FIX", "1", "0|1", RESTART},
{"SHUTTER_FIX", "1", "0|1", RESTART},
{"SHUTTER_FIX", "1", "0|1", RESTART}, {"LIGHTNING_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},
{"ASSUME_FOCUS", "1", "0|1", LIVE}, // read on every focus change (ov_system.c)
@@ -203,7 +204,7 @@ static const CfgMeta metas[] = {
{"GAMEPLAY_MAP_ZOOM_SENSITIVITY", "1", "0.25..4", LIVE}, {"GAMEPLAY_ROTATION_SENSITIVITY", "1", "0.25..4", LIVE},
{"GAMEPLAY_DISTANCE_SENSITIVITY", "1", "0.25..4", LIVE}, {"GAMEPLAY_ITEM_SENSITIVITY", "1", "0.25..4", LIVE},
{"GAMEPLAY_WEAPON_WHEEL", "1", "0|1", LIVE}, {"GAMEPLAY_WEAPON_SENSITIVITY", "1", "0.25..4", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans|de|fr|es|it|nl|ja|ko|vi", LIVE},
// plat_font_path on Linux: 1 asks fontconfig which file draws the language, 0 keeps the fixed distribution
// paths. A rebuild of the atlas reads it, so a change shows on the next window size or language switch.
{"MENU_FONT_FONTCONFIG", "1", "0|1", LIVE},
@@ -862,9 +863,9 @@ void cfg_init(void) {
}
// scene_upscaler, or for a totk.ini that predates it the dlaa switch it replaced: dlaa = 1 is DLSS, anything else off.
// FSR 3.1 is never the answer for a player who did not pick it. An unknown value is off.
// FSR is never the answer for a player who did not pick it. An unknown value is off.
const char *cfg_scene_upscaler(void) {
if (!cfg_is_set("TOTK_SCENE_UPSCALER")) return cfg_bool("TOTK_DLAA") ? "dlss" : "off";
const char *v = cfg_value("TOTK_SCENE_UPSCALER");
return !strcmp(v, "dlss") ? "dlss" : !strcmp(v, "fsr3") ? "fsr3" : "off";
return !strcmp(v, "dlss") ? "dlss" : !strcmp(v, "fsr3") ? "fsr3" : !strcmp(v, "fsr4") ? "fsr4" : "off";
}
+5 -3
View File
@@ -69,14 +69,16 @@ const char *cfg_value(const char *name);
int cfg_int(const char *name);
double cfg_double(const char *name);
int cfg_bool(const char *name);
// The 3D scene upscaler the settings name now: "off", "dlss" or "fsr3" (scene_upscaler; without it dlaa = 1 is "dlss").
// The 3D scene upscaler the settings name now: "off", "dlss", "fsr3" or "fsr4" (scene_upscaler; without it dlaa = 1 is
// "dlss").
// The engine in use is the one named at start (vk_dlaa.c vk_upscaler_engine).
const char *cfg_scene_upscaler(void);
// vk_dlaa.c, the 3D scene upscaler (scene_upscaler): the engine picked at start (UPSCALER_*),
// 1 while the settings still name it (the menu switches it off at once), the engine that is running (it
// ran and has not failed; 0 none), and why an engine cannot run here (UPSCALER_MISSING_*, 0 it can).
enum { UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3 };
enum { UPSCALER_MISSING_GPU = 1, UPSCALER_MISSING_DLL };
// UPSCALER_FSR4 is AMD's FSR 4 from its FSR SDK libraries (vk_ffx.c), Windows only (UPSCALER_MISSING_OS elsewhere).
enum { UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3, UPSCALER_FSR4 };
enum { UPSCALER_MISSING_GPU = 1, UPSCALER_MISSING_DLL, UPSCALER_MISSING_OS };
int vk_upscaler_engine(void);
int vk_upscaler_on(void);
int vk_upscaler_running(void);
+245
View File
@@ -0,0 +1,245 @@
// The part of AMD's FSR API (ffx-api) that vk_ffx.c uses: the entry points of amd_fidelityfx_loader_vk.dll, the
// Vulkan backend descriptor and the upscaler's create and dispatch descriptors. Copied from the FidelityFX SDK v2.4.0
// (GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, Kits/FidelityFX/api/include/ffx_api.h, ffx_api_types.h, vk/ffx_api_vk.h
// and Kits/FidelityFX/upscalers/include/ffx_upscale.h), trimmed to those declarations; the layouts and values are
// unchanged. The SDK's headers use a C++ attribute for deprecations, so they are not included as they are.
//
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2026 Advanced Micro Devices, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <wchar.h>
#include <vulkan/vulkan.h>
// ---- ffx_api.h
enum FfxApiReturnCodes {
FFX_API_RETURN_OK = 0,
FFX_API_RETURN_ERROR = 1,
FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE = 2,
FFX_API_RETURN_ERROR_RUNTIME_ERROR = 3,
FFX_API_RETURN_NO_PROVIDER = 4,
FFX_API_RETURN_ERROR_MEMORY = 5,
FFX_API_RETURN_ERROR_PARAMETER = 6,
FFX_API_RETURN_PROVIDER_NO_SUPPORT_NEW_DESCTYPE = 7,
};
typedef void *ffxContext;
typedef uint32_t ffxReturnCode_t;
#define FFX_API_EFFECT_MASK 0x00ff0000u
#define FFX_API_BACKEND_MASK 0xff000000u
typedef uint64_t ffxStructType_t;
typedef struct ffxApiHeader {
ffxStructType_t type;
struct ffxApiHeader *pNext;
} ffxApiHeader;
typedef ffxApiHeader ffxCreateContextDescHeader;
typedef ffxApiHeader ffxConfigureDescHeader;
typedef ffxApiHeader ffxQueryDescHeader;
typedef ffxApiHeader ffxDispatchDescHeader;
enum FfxApiMsgType { FFX_API_MESSAGE_TYPE_ERROR = 0, FFX_API_MESSAGE_TYPE_WARNING = 1 };
typedef void (*ffxApiMessage)(uint32_t type, const wchar_t *message);
#define FFX_API_QUERY_DESC_TYPE_GET_VERSIONS 4u
struct ffxQueryDescGetVersions {
ffxQueryDescHeader header;
uint64_t createDescType;
void *device; // Vulkan: a VkDeviceContext *
uint64_t *outputCount;
uint64_t *versionIds;
const char **versionNames;
};
#define FFX_API_DESC_TYPE_OVERRIDE_VERSION 5u
struct ffxOverrideVersion {
ffxApiHeader header;
uint64_t versionId;
};
#define FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION 6u
struct ffxQueryGetProviderVersion {
ffxQueryDescHeader header;
uint64_t versionId;
const char *versionName;
};
typedef struct ffxAllocationCallbacks ffxAllocationCallbacks;
typedef ffxReturnCode_t (*PfnFfxCreateContext)(ffxContext *context, ffxCreateContextDescHeader *desc,
const ffxAllocationCallbacks *memCb);
typedef ffxReturnCode_t (*PfnFfxDestroyContext)(ffxContext *context, const ffxAllocationCallbacks *memCb);
typedef ffxReturnCode_t (*PfnFfxQuery)(ffxContext *context, ffxQueryDescHeader *desc);
typedef ffxReturnCode_t (*PfnFfxDispatch)(ffxContext *context, const ffxDispatchDescHeader *desc);
#define FFX_API_EFFECT_ID_UPSCALE 0x00010000u
#define FFX_API_MAKE_EFFECT_SUB_ID(effectId, subversion) ((effectId & FFX_API_EFFECT_MASK) | (subversion & ~FFX_API_EFFECT_MASK))
#define FFX_API_BACKEND_ID_VK 0x01000000u
#define FFX_API_MAKE_BACKEND_SUB_ID(backendId, subversion) ((backendId & FFX_API_BACKEND_MASK) | (subversion & ~FFX_API_BACKEND_MASK))
// ---- ffx_api_types.h
enum FfxApiSurfaceFormat {
FFX_API_SURFACE_FORMAT_UNKNOWN,
FFX_API_SURFACE_FORMAT_R32G32B32A32_TYPELESS,
FFX_API_SURFACE_FORMAT_R32G32B32A32_UINT,
FFX_API_SURFACE_FORMAT_R32G32B32A32_FLOAT,
FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT,
FFX_API_SURFACE_FORMAT_R32G32B32_FLOAT,
FFX_API_SURFACE_FORMAT_R32G32_FLOAT,
FFX_API_SURFACE_FORMAT_R8_UINT,
FFX_API_SURFACE_FORMAT_R32_UINT,
FFX_API_SURFACE_FORMAT_R8G8B8A8_TYPELESS,
FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM,
FFX_API_SURFACE_FORMAT_R8G8B8A8_SNORM,
FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB,
FFX_API_SURFACE_FORMAT_B8G8R8A8_TYPELESS,
FFX_API_SURFACE_FORMAT_B8G8R8A8_UNORM,
FFX_API_SURFACE_FORMAT_B8G8R8A8_SRGB,
FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT,
FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM,
FFX_API_SURFACE_FORMAT_R16G16_FLOAT,
FFX_API_SURFACE_FORMAT_R16G16_UINT,
FFX_API_SURFACE_FORMAT_R16G16_SINT,
FFX_API_SURFACE_FORMAT_R16_FLOAT,
FFX_API_SURFACE_FORMAT_R16_UINT,
FFX_API_SURFACE_FORMAT_R16_UNORM,
FFX_API_SURFACE_FORMAT_R16_SNORM,
FFX_API_SURFACE_FORMAT_R8_UNORM,
FFX_API_SURFACE_FORMAT_R8G8_UNORM,
FFX_API_SURFACE_FORMAT_R8G8_UINT,
FFX_API_SURFACE_FORMAT_R32_FLOAT,
};
enum FfxApiResourceUsage {
FFX_API_RESOURCE_USAGE_READ_ONLY = 0,
FFX_API_RESOURCE_USAGE_RENDERTARGET = (1 << 0),
FFX_API_RESOURCE_USAGE_UAV = (1 << 1),
FFX_API_RESOURCE_USAGE_DEPTHTARGET = (1 << 2),
};
enum FfxApiResourceState {
FFX_API_RESOURCE_STATE_COMMON = (1 << 0),
FFX_API_RESOURCE_STATE_UNORDERED_ACCESS = (1 << 1),
FFX_API_RESOURCE_STATE_COMPUTE_READ = (1 << 2),
FFX_API_RESOURCE_STATE_PIXEL_READ = (1 << 3),
FFX_API_RESOURCE_STATE_COPY_SRC = (1 << 4),
FFX_API_RESOURCE_STATE_GENERIC_READ = (FFX_API_RESOURCE_STATE_COPY_SRC | FFX_API_RESOURCE_STATE_COMPUTE_READ),
};
enum FfxApiResourceType { FFX_API_RESOURCE_TYPE_BUFFER, FFX_API_RESOURCE_TYPE_TEXTURE1D, FFX_API_RESOURCE_TYPE_TEXTURE2D };
struct FfxApiDimensions2D {
uint32_t width, height;
};
struct FfxApiFloatCoords2D {
float x, y;
};
struct FfxApiResourceDescription {
uint32_t type;
uint32_t format;
uint32_t width; // union with size (buffers)
uint32_t height; // union with stride
uint32_t depth; // union with alignment
uint32_t mipCount;
uint32_t flags;
uint32_t usage;
};
struct FfxApiResource {
void *resource; // Vulkan: the VkImage
struct FfxApiResourceDescription description;
uint32_t state;
};
// ---- vk/ffx_api_vk.h
typedef struct VkDeviceContext {
VkDevice vkDevice;
VkPhysicalDevice vkPhysicalDevice;
PFN_vkGetDeviceProcAddr vkDeviceProcAddr;
} VkDeviceContext;
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK FFX_API_MAKE_BACKEND_SUB_ID(FFX_API_BACKEND_ID_VK, 0x03)
struct ffxCreateBackendVKDesc {
ffxCreateContextDescHeader header;
VkDeviceContext deviceContext;
};
// ---- upscalers/include/ffx_upscale.h
#define FFX_UPSCALER_MAKE_VERSION(major, minor, patch) (((major) << 22) | ((minor) << 12) | (patch))
#define FFX_UPSCALER_VERSION FFX_UPSCALER_MAKE_VERSION(4, 1, 2)
enum FfxApiCreateContextUpscaleFlags {
FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE = (1 << 0),
FFX_UPSCALE_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1 << 1),
FFX_UPSCALE_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1 << 2),
FFX_UPSCALE_ENABLE_DEPTH_INVERTED = (1 << 3),
FFX_UPSCALE_ENABLE_DEPTH_INFINITE = (1 << 4),
FFX_UPSCALE_ENABLE_AUTO_EXPOSURE = (1 << 5),
FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION = (1 << 6),
FFX_UPSCALE_ENABLE_DEBUG_CHECKING = (1 << 7),
};
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x00)
struct ffxCreateContextDescUpscale {
ffxCreateContextDescHeader header;
uint32_t flags;
struct FfxApiDimensions2D maxRenderSize;
struct FfxApiDimensions2D maxUpscaleSize;
ffxApiMessage fpMessage;
};
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x01)
struct ffxDispatchDescUpscale {
ffxDispatchDescHeader header;
void *commandList; // Vulkan: the VkCommandBuffer
struct FfxApiResource color;
struct FfxApiResource depth;
struct FfxApiResource motionVectors;
struct FfxApiResource exposure;
struct FfxApiResource reactive;
struct FfxApiResource transparencyAndComposition;
struct FfxApiResource output;
struct FfxApiFloatCoords2D jitterOffset;
struct FfxApiFloatCoords2D motionVectorScale;
struct FfxApiDimensions2D renderSize;
struct FfxApiDimensions2D upscaleSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta; // milliseconds
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical; // radians
float viewSpaceToMetersFactor;
uint32_t flags;
};
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x0b)
struct ffxCreateContextDescUpscaleVersion {
ffxCreateContextDescHeader header;
uint32_t version; // FFX_UPSCALER_VERSION
};
+15 -1
View File
@@ -11,6 +11,8 @@
// <profile>/save-backup/<time>/ the three committed saves before the current one
// <profile>/temp/ emptied at start
// <profile>/cache/<index>/ cache storage
// <profile>/sdcard/ the SD card a mod plugin mounts (MountSdCard, under any mount name: Zonai
// Fieldworks keeps its settings and logs there); the game never mounts it
//
// The save mount is journaled as on Horizon: changes go to a working copy and become the committed save atomically at
// Commit; a crash or an Unmount before Commit leaves the previous committed save. Commit returns at once and the copy
@@ -33,7 +35,8 @@
#define NMOUNTS 16
#define PATH_CAP 1100
enum { M_FREE, M_SAVE, M_TEMP, M_CACHE, M_SAVE_RO }; // M_SAVE: the working copy; M_SAVE_RO: the committed save
// M_SAVE: the working copy; M_SAVE_RO: the committed save; M_SDCARD: <profile>/sdcard
enum { M_FREE, M_SAVE, M_TEMP, M_CACHE, M_SAVE_RO, M_SDCARD };
typedef struct { int kind; char name[32]; char root[1024]; } Mount;
typedef struct { PlatFile *h; int mode, save; } File; // h NULL = free; save: on a save-data mount
@@ -800,6 +803,14 @@ static uint32_t mount_temp(const char *name) {
return mount_add(name, M_TEMP, p);
}
static uint32_t mount_sdcard(const char *name) {
ready();
char p[PATH_CAP];
snprintf(p, sizeof p, "%s/sdcard", profile);
make_dirs(p);
return mount_add(name, M_SDCARD, p);
}
static void cache_dir(int index, char *out, size_t cap) { snprintf(out, cap, "%s/cache/%d", profile, index); }
static uint32_t create_cache(int index, int64_t size, int64_t journal) {
@@ -1211,6 +1222,7 @@ static void ov_mount_save(Cpu *c) { ret_x(c, mount_save(arg_p(c, 0), arg_p(c, 1)
static void ov_mount_save_ro(Cpu *c) { ret_x(c, mount_save_ro(arg_p(c, 0), arg_x(c, 1), arg_p(c, 2))); }
static void ov_save_exists(Cpu *c) { ret_x(c, save_exists(arg_x(c, 0), arg_p(c, 1))); }
static void ov_mount_temp(Cpu *c) { ret_x(c, mount_temp(arg_p(c, 0))); }
static void ov_mount_sdcard(Cpu *c) { ret_x(c, mount_sdcard(arg_p(c, 0))); }
static void ov_unmount(Cpu *c) { unmount(arg_p(c, 0)); }
static void ov_commit(Cpu *c) { ret_x(c, commit(arg_p(c, 0))); }
static void ov_create_cache(Cpu *c) { ret_x(c, create_cache(I32(0), I64(1), I64(2))); }
@@ -1246,6 +1258,7 @@ static void ov_set_priority(Cpu *c) { (void)c; }
#define S_MOUNT_SAVE_RO "_ZN2nn2fs21MountSaveDataReadOnlyEPKcNS_13ApplicationIdERKNS_7account3UidE"
#define S_SAVE_EXISTS "_ZN2nn2fs18IsSaveDataExistingENS_13ApplicationIdERKNS_7account3UidE"
#define S_MOUNT_TEMP "_ZN2nn2fs21MountTemporaryStorageEPKc"
#define S_MOUNT_SDCARD "_ZN2nn2fs11MountSdCardEPKc"
#define S_UNMOUNT "_ZN2nn2fs7UnmountEPKc"
#define S_COMMIT "_ZN2nn2fs6CommitEPKc"
#define S_CREATE_CACHE "_ZN2nn2fs18CreateCacheStorageEill"
@@ -1282,6 +1295,7 @@ HOST_OVERRIDE(S_MOUNT_SAVE, ov_mount_save);
HOST_OVERRIDE(S_MOUNT_SAVE_RO, ov_mount_save_ro);
HOST_OVERRIDE(S_SAVE_EXISTS, ov_save_exists);
HOST_OVERRIDE(S_MOUNT_TEMP, ov_mount_temp);
HOST_OVERRIDE(S_MOUNT_SDCARD, ov_mount_sdcard);
HOST_OVERRIDE(S_UNMOUNT, ov_unmount);
HOST_OVERRIDE(S_COMMIT, ov_commit);
HOST_OVERRIDE(S_CREATE_CACHE, ov_create_cache);
+4
View File
@@ -33,6 +33,10 @@ void vk_reflex_marker(int marker, uint64_t present_id); // present_id: the fra
uint64_t vk_reflex_frame_begin(void); // SIMULATION_START: the new frame's present ID
uint64_t vk_reflex_frame(void); // the ID of the frame the game simulates now
void vk_reflex_sleep(void); // before SIMULATION_START: the driver's latency sleep
// AMD Anti-Lag 2 (gfx_present.c, VK_AMD_anti_lag): the driver paces the CPU from the INPUT call to the PRESENT call of a
// frame. Both return at once unless reflex = auto turned Anti-Lag on at device creation (vk_device.c create_device).
void vk_antilag_input(uint64_t frame); // before the frame's input and simulation; may sleep
void vk_antilag_present(uint64_t frame); // right before the frame's vkQueuePresentKHR
// ---- shader service client (gfx_shader.c)
enum { GFX_STAGE_VS, GFX_STAGE_TCS, GFX_STAGE_TES, GFX_STAGE_GS, GFX_STAGE_FS, GFX_STAGE_CS };
+33 -3
View File
@@ -390,8 +390,9 @@ static void latency_note(VkCtx *c, uint64_t pid) {
"end %.2f ms", full, gi.timingCount, full ? sum / full / 1000.0 : 0.0);
}
}
rt_log("reflex: frame start to present %.2f ms over %llu frames (reflex %s)%s", g_lat.n ? g_lat.ns / 1e6 / g_lat.n : 0.0,
(unsigned long long)g_lat.n, g_reflex_mode == 2 ? "boost" : g_reflex_mode == 1 ? "on" : "off", drv);
rt_log("reflex: frame start to present %.2f ms over %llu frames (reflex %s%s)%s", g_lat.n ? g_lat.ns / 1e6 / g_lat.n : 0.0,
(unsigned long long)g_lat.n, g_reflex_mode == 2 ? "boost" : g_reflex_mode == 1 ? "on" : "off",
c->has_amd_antilag ? ", anti-lag on" : "", drv);
g_lat.n = g_lat.ns = 0;
}
@@ -405,7 +406,8 @@ uint64_t vk_reflex_submit_id(void) { return t_reflex_submit ? t_reflex_submit :
void vk_reflex_present_frame(uint64_t id) {
// g_blit_pid feeds flip_locked's VkPresentIdKHR (Reflex) and latency_note (TOTK_TRACE=perf); with neither, the
// present skips the lock
if (!vk_has_reflex() && !(rt_trace & RT_TRACE_PERF)) return;
VkCtx *c = vk_ctx();
if (!vk_has_reflex() && !(c && c->has_amd_antilag) && !(rt_trace & RT_TRACE_PERF)) return;
plat_rmutex_lock(&g_pl);
g_blit_pid = id;
plat_rmutex_unlock(&g_pl);
@@ -452,6 +454,33 @@ void vk_reflex_sleep(void) {
}
}
// ---- AMD Anti-Lag 2 (VK_AMD_anti_lag)
static PFN_vkAntiLagUpdateAMD g_antilag_update;
// The INPUT call runs on the game thread (nvnWindowAcquireTexture), the PRESENT call on the present thread (flip_one,
// g_pl held): both carry the frame's ID, as the spec asks of a frame's two calls. The first call of either thread loads
// the entry point; the atomics keep that load race-free.
static void antilag_update(VkAntiLagStageAMD stage, uint64_t frame) {
VkCtx *c = vk_ctx();
if (!c || !c->has_amd_antilag || !frame) return;
PFN_vkAntiLagUpdateAMD fn = __atomic_load_n(&g_antilag_update, __ATOMIC_ACQUIRE);
if (!fn) {
fn = (PFN_vkAntiLagUpdateAMD)vkGetDeviceProcAddr(c->device, "vkAntiLagUpdateAMD");
if (!fn) return;
__atomic_store_n(&g_antilag_update, fn, __ATOMIC_RELEASE);
}
// the driver holds frames to the pacer's frame limit, as Reflex's minimum interval does (0: no limit known)
double hz = frame_step_limit_hz();
VkAntiLagPresentationInfoAMD pi = {
.sType = VK_STRUCTURE_TYPE_ANTI_LAG_PRESENTATION_INFO_AMD, .stage = stage, .frameIndex = frame};
VkAntiLagDataAMD d = {.sType = VK_STRUCTURE_TYPE_ANTI_LAG_DATA_AMD, .mode = VK_ANTI_LAG_MODE_ON_AMD,
.maxFPS = hz > 0 ? (uint32_t)(hz + 0.5) : 0, .pPresentationInfo = &pi};
fn(c->device, &d);
}
void vk_antilag_input(uint64_t frame) { antilag_update(VK_ANTI_LAG_STAGE_INPUT_AMD, frame); }
void vk_antilag_present(uint64_t frame) { antilag_update(VK_ANTI_LAG_STAGE_PRESENT_AMD, frame); }
// ---- swapchain
static const char *g_present_got = ""; // the TOTK_VK_PRESENT value of the mode the swapchain got; "" before one
@@ -503,6 +532,7 @@ static void flip_one(void) {
pid_info.pPresentIds = &pid;
vk_reflex_marker(4, pid); // VK_LATENCY_MARKER_PRESENT_START_NV
}
if (!generated) vk_antilag_present(frame_pid);
VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = with_id ? &pid_info : NULL,
.waitSemaphoreCount = 1,
+1
View File
@@ -315,6 +315,7 @@ void res_init(void); // after rt_patches_i
float res_dlss_lod_bias(void); // TOTK_DLSS upscaling: texture LOD bias (<= 0)
int res_dlss_mode(const char *mode); // TOTK_DLSS changed while running: new scene size
int res_dlss_dll(void); // the DLSS library is next to the executable
int res_ffx_dlls(void); // AMD's two FSR 4 libraries are (Windows; 0 elsewhere)
void res_fn_hit(uint64_t addr, uint64_t x0); // main.c fnprof_hit: catches the renderer at start
void res_present(Cpu *c); // nvnQueuePresentTexture: applies a pending scene size
void res_sizes(unsigned out[2], unsigned scene[2]); // the output and scene sizes in effect (the game's own
+3 -1
View File
@@ -688,7 +688,9 @@ NVN_API(nvnWindowAcquireTexture) {
perf_end(PERF_PACE, p0);
}
vk_reflex_sleep();
vk_reflex_marker(0, vk_reflex_frame_begin()); // VK_LATENCY_MARKER_SIMULATION_START_NV: a new frame and its ID
uint64_t fid = vk_reflex_frame_begin();
vk_reflex_marker(0, fid); // VK_LATENCY_MARKER_SIMULATION_START_NV: a new frame and its ID
vk_antilag_input(fid);
// The sync means "the display no longer reads this image". Presents are copies queued in submit order, so it is
// already satisfied: fenced = 3 with fence 0.
if (s) {
+34 -11
View File
@@ -1012,31 +1012,45 @@ static void probe_fonts(void) {
(unsigned long long)addr, (unsigned long long)size, path);
}
// The host catalog (ui_text.c): every menu id has its own English, Russian, Brazilian Portuguese and Simplified
// Chinese text, the software keyboard keeps its game-language rows, and menu_text follows TOTK_MENU_LANG.
// The host catalog (ui_text.c): every menu id has its own English, Russian, Brazilian Portuguese, Simplified Chinese
// and Vietnamese text, every menu language's text fits the description pane and keeps the English conversions of the
// overlay formats, the software keyboard keeps its game-language rows, and menu_text follows TOTK_MENU_LANG.
static void probe_menu_text(void) {
static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko",
"pt-BR"};
"pt-BR", "vi"};
static const char *const menu_langs[] = {"de", "fr", "es", "it", "nl", "ja", "ko", "vi"};
for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) {
CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id) &&
ui_text_defined("pt-BR", (UiTextId)id), "menu text id %d lacks en, ru or pt-BR", id);
ui_text_defined("pt-BR", (UiTextId)id) && ui_text_defined("vi", (UiTextId)id),
"menu text id %d lacks en, ru, pt-BR or vi", id);
CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id) && *ui_text_in("pt-BR", (UiTextId)id),
"menu text id %d is empty", id);
// the description pane keeps the whole text and a note after it (option_rows.cpp desc_set)
CHECK(strlen(ui_text_in("en", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("ru", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("pt-BR", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("zh-Hans", (UiTextId)id)) + 256 < UI_DESC_BYTES,
strlen(ui_text_in("zh-Hans", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("vi", (UiTextId)id)) + 256 < UI_DESC_BYTES,
"menu text id %d is too long for the description pane", id);
for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++)
CHECK(strlen(ui_text_in(menu_langs[i], (UiTextId)id)) + 256 < UI_DESC_BYTES,
"menu text id %d is too long for the description pane in %s", id, menu_langs[i]);
CHECK(ui_text_defined("zh-Hans", (UiTextId)id), "menu text id %d lacks Simplified Chinese", id);
}
CHECK(!ui_text_defined("en", UI_TEXT_COUNT) && !*ui_text_in("ru", UI_TEXT_COUNT), "an id past the catalog gives text");
// other languages fall back to English for the menu, and keep their own keyboard texts
CHECK(!strcmp(ui_text_in("ja", UI_MENU_CONTINUE), ui_text_in("en", UI_MENU_CONTINUE)), "ja menu text is not English");
// the other game languages have their own menu text; Traditional Chinese falls back to English in the catalog
for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++) {
CHECK(ui_text_defined(menu_langs[i], UI_MENU_TITLE) && ui_text_defined(menu_langs[i], UI_MENU_CONTINUE),
"%s has no menu text", menu_langs[i]);
CHECK(strstr(ui_text_in(menu_langs[i], UI_MENU_OV_GAME_PCT), "%.0f%%"), "%s overlay format lost its conversion",
menu_langs[i]);
}
CHECK(!strcmp(ui_text_in("zh-Hant", UI_MENU_CONTINUE), ui_text_in("en", UI_MENU_CONTINUE)),
"zh-Hant menu text is not English");
CHECK(!strcmp(ui_text_in("ru", UI_SWKBD_OK), "ОК") && !strcmp(ui_text_in("de", UI_SWKBD_CANCEL), "Abbrechen") &&
!strcmp(ui_text_in("en", UI_SWKBD_OK), "OK"), "keyboard texts changed");
// language names: the same string in every row
for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_ES_419; id++)
for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_VI; id++)
for (size_t i = 1; i < sizeof langs / sizeof *langs; i++)
CHECK(!strcmp(ui_text_in(langs[i], (UiTextId)id), ui_text_in("en", (UiTextId)id)), "language name %d differs in %s", id, langs[i]);
CHECK(!strcmp(ui_text_in("en", UI_MENU_LANGNAME_RU), "Русский"), "Russian is not shown as Russian");
@@ -1075,15 +1089,24 @@ static void probe_menu_text(void) {
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en");
cfg_set("TOTK_MENU_LANG", "zh-Hans");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("zh-Hans", UI_MENU_TITLE), "menu_text ignores MENU_LANG=zh-Hans");
cfg_set("TOTK_MENU_LANG", "ja");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("ja", UI_MENU_TITLE), "menu_text ignores MENU_LANG=ja");
cfg_set("TOTK_MENU_LANG", "de-DE");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("de", UI_MENU_TITLE), "menu_text ignores MENU_LANG=de-DE");
// Traditional Chinese (zh-TW, zh-HK) reads the Simplified Chinese menu
cfg_set("TOTK_MENU_LANG", "zh-TW");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("zh-Hans", UI_MENU_TITLE), "zh-TW does not get the zh-Hans menu");
cfg_set("TOTK_MENU_LANG", "");
// the system language as ui_text.c resolve_menu_lang takes it: the tag, else its base language (ru-RU: ru), else en
// the system language as ui_text.c resolve_menu_lang takes it: the tag, else its base language (ru-RU: ru), else
// Simplified Chinese for any Chinese, else en
const char *sys_lang = ui_text_lang(plat_ui_language());
char sys_base[16] = "";
size_t base_n = strcspn(sys_lang, "-");
if (sys_lang[base_n] && base_n < sizeof sys_base) memcpy(sys_base, sys_lang, base_n);
const char *auto_lang = ui_text_defined(sys_lang, UI_MENU_TITLE) ? sys_lang
const char *auto_lang = ui_text_defined(sys_lang, UI_MENU_TITLE) ? sys_lang
: *sys_base && ui_text_defined(sys_base, UI_MENU_TITLE) ? sys_base
: "en";
: !strncmp(sys_lang, "zh", 2) ? "zh-Hans"
: "en";
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(auto_lang, UI_MENU_CONTINUE), "menu_text auto ignores the system language");
}
+13
View File
@@ -119,6 +119,18 @@ static void ov_desired_language(Cpu *c) {
ret_x(c, v);
}
// nn::settings::detail::GetLanguageCode(LanguageCode *out): the system language, the one GetDesiredLanguage gives.
// The game never calls it; Material Columns picks its text by it. x0 = 0 for the callers that read a Result.
static void ov_settings_language(Cpu *c) {
const char *code = ov_language();
uint8_t *out = arg_p(c, 0);
if (out) {
memset(out, 0, 8);
memcpy(out, code, strlen(code));
}
ret_x(c, 0);
}
static void ov_oe_initialize(Cpu *c) { (void)c; rt_log("oe: application environment: a local host process"); }
// void SetPerformanceConfiguration(PerformanceMode mode, int config)
@@ -872,6 +884,7 @@ static void ov_font_size(Cpu *c) {
// ==== registration
HOST_OVERRIDE("_ZN2nn2oe10InitializeEv", ov_oe_initialize);
HOST_OVERRIDE("_ZN2nn2oe18GetDesiredLanguageEv", ov_desired_language);
HOST_OVERRIDE("_ZN2nn8settings6detail15GetLanguageCodeEPNS0_12LanguageCodeE", ov_settings_language);
HOST_OVERRIDE("_ZN2nn2oe27SetPerformanceConfigurationENS0_15PerformanceModeEi", ov_performance_config);
HOST_OVERRIDE("_ZN2nn2oe15SetCpuBoostModeENS0_12CpuBoostModeE", ov_cpu_boost);
HOST_OVERRIDE("_ZN2nn2oe16GetOperationModeEv", ov_operation_mode);
+32 -13
View File
@@ -38,9 +38,15 @@
// hook branches reach main's .text.
// - nn::oe::GetDisplayVersion is answered with this build's game version, so the plugin picks its table for the
// installed game without the applet services.
// Only svcs the init needs are allowed (QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-5, 12-15 and 65001,
// Map/UnmapProcessMemory); any other one, such as CreateSession and ReplyAndReceive of exlaunch's process-handle
// fallback, ends the run with the reason in the record.
// - GetInfo 6, 16 and 17, the total memory and the system resource size and use, are constants (memory.c
// mem_info); 7, the memory in use, is the same at the same point of the same init. Zonai Fieldworks asks them
// after its hooks are in.
// - SetHeapSize grows the process heap past the size the game's nninitStartup set before the init runs (Zonai
// Fieldworks keeps a pool in the tail). The heap base is fixed and the game asked its size the same way at every
// start, so the init gets the same answer each time.
// Only svcs the init needs are allowed (SetHeapSize, QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-7,
// 12-17 and 65001, Map/UnmapProcessMemory); any other one, such as CreateSession and ReplyAndReceive of exlaunch's
// process-handle fallback, ends the run with the reason in the record.
//
// The record, in DIR: record.json (modules, which plugins' inits ran, the writes into every game module as words, the
// alias calls, svc and import counts, the tick offset, a refusal), plugin<N>.img (the plugin's image after its init,
@@ -69,7 +75,9 @@
#define POOL_SIZE (64 * GiB)
#define POOL_ALIGN (4 * GiB)
#define RTLD_ALIGN 0x200000ull
#define MAX_ALIASES 256
// exlaunch maps a page alias for every patch it writes and unmaps it after; Zonai Fieldworks makes over 211 in its
// init. Each slot is 48 bytes, and only the live aliases hold a copy of their pages.
#define MAX_ALIASES 2048
#define MAX_IMPORTS 64
#define CUR_PROCESS 0xFFFF8001u
// Horizon memory states and permissions of QueryMemory, and results.
@@ -94,7 +102,7 @@ static uint64_t pool_base;
static int running; // a plugin's init runs: svcs and imports are counted
static int play; // plugins_start: a refused SVC fails the plugin instead of ending the process
static char failed[256]; // play: why the running init was refused
static uint64_t svc_count[0x80], info_count[16], info_65001;
static uint64_t svc_count[0x80], info_count[18], info_65001;
static struct { const char *name; uint64_t calls; } imports[MAX_IMPORTS];
static int nimports;
static uint8_t **pre; // per loaded module: its image before the plugins' inits
@@ -198,11 +206,22 @@ static uint32_t process_memory(int unmap, uint64_t dst, uint32_t process, uint64
}
return R_INVALID_STATE;
}
if (!module_holding(src, size)) return R_INVALID_STATE; // only the modules' own memory
if (!module_holding(src, size)) { // only the modules' own memory
rt_log("plugin-init: MapProcessMemory refused: the source %#llx+%#llx is no module's memory",
(unsigned long long)src, (unsigned long long)size);
return R_INVALID_STATE;
}
RtMemoryInfo q;
mem_query(dst, &q);
if (q.state != ST_FREE || dst + size > q.base + q.size) return R_INVALID_STATE;
if (naliases == MAX_ALIASES) return R_LIMIT_REACHED;
if (q.state != ST_FREE || dst + size > q.base + q.size) {
rt_log("plugin-init: MapProcessMemory refused: the destination %#llx+%#llx is not free (state %#x)",
(unsigned long long)dst, (unsigned long long)size, q.state);
return R_INVALID_STATE;
}
if (naliases == MAX_ALIASES) {
rt_log("plugin-init: MapProcessMemory refused: all %d alias slots used", MAX_ALIASES);
return R_LIMIT_REACHED;
}
if (!plat_mem_commit(dst, size)) return R_INVALID_STATE; // not inside one of our reservations
Alias *al = &aliases[naliases];
al->snap = malloc(size);
@@ -235,10 +254,10 @@ static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
svc_count[imm & 0x7F]++;
char why[256], at[128];
switch (imm) {
case 0x06: case 0x1E: case 0x27: case 0x74: case 0x75: return 0;
case 0x01: case 0x06: case 0x1E: case 0x27: case 0x74: case 0x75: return 0;
case 0x29: {
uint32_t id = (uint32_t)c->x[1];
if ((id >= 2 && id <= 5) || (id >= 12 && id <= 15)) {
if ((id >= 2 && id <= 7) || (id >= 12 && id <= 17)) {
info_count[id]++;
return 0;
}
@@ -252,8 +271,8 @@ static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
return 1;
}
}
snprintf(why, sizeof why, "svc %#x at %s (only QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-5, 12-15 "
"and 65001, Map/UnmapProcessMemory are served)", imm, ldr_describe(pc, at, sizeof at));
snprintf(why, sizeof why, "svc %#x at %s (only SetHeapSize, QueryMemory, GetSystemTick, OutputDebugString, "
"GetInfo 2-7, 12-17 and 65001, Map/UnmapProcessMemory are served)", imm, ldr_describe(pc, at, sizeof at));
refuse(why);
c->x[0] = R_NOT_IMPLEMENTED;
return 1;
@@ -392,7 +411,7 @@ static void write_record(const char *refused) {
if (svc_count[i]) fprintf(f, "%s\"%#x\": %llu", first ? "" : ", ", i, (unsigned long long)svc_count[i]), first = 0;
fputs("},\n\"get_info\": {", f);
first = 1;
for (int i = 0; i < 16; i++)
for (int i = 0; i < 18; i++)
if (info_count[i]) fprintf(f, "%s\"%d\": %llu", first ? "" : ", ", i, (unsigned long long)info_count[i]), first = 0;
if (info_65001) fprintf(f, "%s\"65001\": %llu", first ? "" : ", ", (unsigned long long)info_65001);
fputs("},\n\"imports\": {", f);
+39 -10
View File
@@ -102,11 +102,35 @@ int res_dlss_dll(void) {
return dll;
}
// The engine picked at start can run, as far as is known before the device exists: DLSS needs its DLL (dlss_dll); FSR
// 3.1 is built in (vk_fsr3.cpp). Off: nothing to run.
// AMD's FSR 4 (vk_ffx.c) loads amd_fidelityfx_loader_vk.dll from the folder of totk.exe, which finds
// amd_fidelityfx_upscaler_vk.dll next to itself; both come from the setup's FSR step. Windows only: AMD ships no Linux
// libraries.
static int ffx_dlls(void) {
#ifdef _WIN32
char exe[1024], path[1024 + 48];
if (!plat_exe_path(exe, sizeof exe)) return 1;
char *last = plat_last_sep(exe);
if (!last) return 1;
snprintf(path, sizeof path, "%.*s/amd_fidelityfx_loader_vk.dll", (int)(last - exe), exe);
if (!plat_file_exists(path)) return 0;
snprintf(path, sizeof path, "%.*s/amd_fidelityfx_upscaler_vk.dll", (int)(last - exe), exe);
return plat_file_exists(path);
#else
return 0;
#endif
}
int res_ffx_dlls(void) {
static int dlls = -1;
if (dlls < 0) dlls = ffx_dlls();
return dlls;
}
// The engine picked at start can run, as far as is known before the device exists: DLSS needs its DLL (dlss_dll), FSR
// 4 AMD's two libraries (ffx_dlls); FSR 3.1 is built in (vk_fsr3.cpp). Off: nothing to run.
static int upscaler_ready(void) {
int e = vk_upscaler_engine();
return e == UPSCALER_DLSS ? res_dlss_dll() : e == UPSCALER_FSR3;
return e == UPSCALER_DLSS ? res_dlss_dll() : e == UPSCALER_FSR4 ? res_ffx_dlls() : e == UPSCALER_FSR3;
}
static uint64_t shadow_kib(void);
@@ -143,8 +167,12 @@ static double dlss_share(const char *m) {
int ready = upscaler_ready();
if (!ready && !told++) {
#ifdef _WIN32
rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene follows "
"render_scale", m);
if (vk_upscaler_engine() == UPSCALER_FSR4)
rt_log("resolution: FSR 4 %s needs amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll "
"next to totk.exe, which are missing: the scene follows render_scale", m);
else
rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene "
"follows render_scale", m);
#else
rt_log("resolution: DLSS %s needs libnvidia-ngx-dlss.so.<version> next to totk, which is missing: the "
"scene follows render_scale", m);
@@ -208,7 +236,7 @@ static void decide(void) {
else rt_log("resolution: TOTK_SHADOW_RES=%s is not game or a size 256..4096 (a multiple of 8); game", sr);
}
// A DLSS mode other than dlaa sets the scene size instead. On 1.4.3 with the scene upscaler able to run (DLSS with
// its DLL there, or FSR 3.1 in the build)
// its DLL there, FSR 4 with AMD's libraries there, or FSR 3.1 in the build)
// the mode can change while the game runs (res_dlss_mode): the scene patch is then always on and the heap is sized
// for the largest scene the modes ask for. Everyone else keeps the game's own scene size and its dynamic resolution
// unless render_scale or a DLSS mode asks for another, and a heap sized for that scene alone.
@@ -674,8 +702,8 @@ void res_fov_live(void) {
// 2867-wide scene stays at 100 %, one wider than about 2970 does not, and a 4267-wide one (5120x1440 at render_scale
// 83) fits no tier and falls back to 80 % every frame, whatever the GPU's load. 1 (the default) leaves the game's own
// stepping and the set off. Runs on a settings change (gfx_present.c window_settings_live), like res_fov_live.
// FSR 3.1 as the scene upscaler holds it at 100 % whatever dynamic_res says, as codexx-dev's pull request #1245 does
// for its FSR: each tier is a scene of another size, so every step starts FSR's history again, and below 100 % the
// FSR 3.1 or FSR 4 as the scene upscaler holds it at 100 % whatever dynamic_res says, as codexx-dev's pull request
// #1245 does for its FSR: each tier is a scene of another size, so every step starts FSR's history again, and below 100 % the
// game ends its frame another way (a frame log on 1.4.3: its copy shader scales the scene straight into the
// output-sized target instead of the scaling FXAA draw), which #1245 measured as a picture that went soft and sharp in
// turns at a 2560x1440 scene. A 1280x720 scene (1080p, quality) stayed at 100 % through a 70 s town run, so it gains
@@ -683,7 +711,8 @@ void res_fov_live(void) {
void res_dynres_live(void) {
static int set = -2, shown = -1;
if (set == -2) set = rt_patch_set("fixres");
int fsr = vk_upscaler_on() && vk_upscaler_engine() == UPSCALER_FSR3;
int e = vk_upscaler_engine();
int fsr = vk_upscaler_on() && (e == UPSCALER_FSR3 || e == UPSCALER_FSR4);
int dyn = cfg_bool("TOTK_DYNAMIC_RES") && !fsr;
int state = dyn | fsr << 1;
if (state == shown) return;
@@ -695,7 +724,7 @@ void res_dynres_live(void) {
rt_patch_switch(set, !dyn);
rt_log("resolution: dynamic resolution %s",
dyn ? "on: the game's own 100, 90 or 80 %"
: fsr ? "off while FSR 3.1 upscales the scene: the scene stays at 100 %"
: fsr ? "off while FSR upscales the scene: the scene stays at 100 %"
: "off: the scene stays at 100 %");
}
+135 -2
View File
@@ -25,7 +25,8 @@
//
// The resource size table: with a player mod enabled, the game's table is rebuilt at start with the tables the mods
// ship merged in and the entries of the mods' files raised to what they need (restbl_overlay), the members of their
// packs too (restbl_packs), and served from <profile>/mods/ in place of the game's or a mod's table.
// packs too (restbl_packs), and served from <profile>/mods/ in place of the game's or a mod's table. TOTK_RESTBL_CACHE=1
// serves the table of the last start instead when every input of the build is the same (restbl_cache_key).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -761,6 +762,127 @@ static int restbl_packs(Restbl *out, const Restbl *base, int *packs, int *lines)
return raised;
}
// ---- the merged table across starts (TOTK_RESTBL_CACHE=1, off by default). Building it opens every mod file and
// unpacks the mods' packs. A start whose inputs are the same as the last one's serves the table that start wrote.
// The key is a SHA-256 over every input restbl_overlay reads:
// - the running totk.exe's path and identity: a new build may merge differently, and it carries the port version, the
// game version and the RomFS index's SHA-256 (romfs_config.h);
// - the RomFS image's path and identity and the game table's index entry: the base table, the game's copies of the
// mods' packs and Pack/ZsDic.pack.zs come from the image;
// - every shipped table (restbl_collect, mod_walk_cb; also the ones overlay_contest drops) with its owner and identity;
// - every overlay overlay_contest kept (player mods, the TOTK_ROMFS_MODS manifest, the port's folders) with its RomFS
// path, file path, place in the order (index, prio, mod) and identity.
// Identity is the volume, file id, size, last write and creation time. A file's bytes are not hashed: identity is
// what the overlay layer already trusts (romfs_open stops the game on a file whose identity changed after the start
// check), and hashing a texture pack would cost more than the merge does. <profile>/mods/<table>.key holds the key,
// what the build gave (a table or none) and the SHA-256 of the table it wrote; it is replaced atomically after the
// table is written. A key file of another size, magic or version, another key, or a table of another SHA-256 is a
// miss: the table is built again and both files are replaced, so the cache stays two files.
#define RESTBL_CACHE_VERSION 3
typedef struct { char magic[8]; uint32_t version, outcome; uint8_t key[32], table[32]; } RestblCache;
enum { RESTBL_NONE = 1, RESTBL_TABLE = 2 };
static void restbl_cache_paths(char *key, size_t key_cap, char *table, size_t table_cap) {
const char *leaf = strrchr(restbl_rel, '/') ? strrchr(restbl_rel, '/') + 1 : restbl_rel;
need(snprintf(table, table_cap, "%s/mods/%s", rt_config()->profile, leaf) < (int)table_cap, "table path");
need(snprintf(key, key_cap, "%s.key", table) < (int)key_cap, "table key path");
}
static void hash_identity(Sha256 *h, const char *path, const Identity *id) {
sha256_update(h, path, strlen(path) + 1);
sha256_update(h, id, sizeof *id);
}
// 0 when path cannot be opened.
static int hash_file_id(Sha256 *h, const char *path) {
PlatFile *f = open_read(path);
Identity id = {0};
if (f) id = identity_of(f), plat_file_close(f);
hash_identity(h, path, &id);
return f != NULL;
}
// The key of this start's inputs into out; 0 when the running exe cannot be opened (no key: the table is built).
static int restbl_cache_key(uint64_t gi, uint8_t out[32]) {
char exe[2100];
Sha256 h;
sha256_init(&h);
static const char tag[] = "totk restbl cache";
uint32_t v = RESTBL_CACHE_VERSION;
sha256_update(&h, tag, sizeof tag);
sha256_update(&h, &v, sizeof v);
sha256_update(&h, rt_port_version, strlen(rt_port_version) + 1);
if (!plat_exe_path(exe, sizeof exe) || !hash_file_id(&h, exe)) return 0;
Identity img = identity_of(image);
hash_identity(&h, image_file, &img);
Entry ge = entry(gi);
sha256_update(&h, &ge, sizeof ge);
uint64_t n = nshipped;
sha256_update(&h, &n, sizeof n);
for (size_t s = 0; s < nshipped; s++) {
int32_t m[2] = {shipped[s].mod, shipped[s].other};
sha256_update(&h, m, sizeof m);
hash_file_id(&h, shipped[s].file);
}
n = noverlay;
sha256_update(&h, &n, sizeof n);
for (size_t k = 0; k < noverlay; k++) {
const Overlay *o = &overlays[k];
int64_t place[3] = {o->index == ADDED ? -1 : (int64_t)o->index, o->prio, o->mod};
sha256_update(&h, o->name, strlen(o->name) + 1);
sha256_update(&h, place, sizeof place);
hash_identity(&h, o->path, &o->id);
}
sha256_final(&h, out);
return 1;
}
// Records the build's result for key: RESTBL_NONE, or RESTBL_TABLE with the SHA-256 of the table it wrote.
static void restbl_cache_store(const uint8_t key[32], int outcome, const uint8_t table[32]) {
char kp[2300], tp[2300];
restbl_cache_paths(kp, sizeof kp, tp, sizeof tp);
RestblCache c = {.magic = {'T', 'O', 'T', 'K', 'R', 'S', 'Z', 'C'}, .version = RESTBL_CACHE_VERSION,
.outcome = (uint32_t)outcome};
memcpy(c.key, key, 32);
if (table) memcpy(c.table, table, 32);
if (!plat_file_write_atomic(kp, &c, sizeof c))
rt_log("RomFS: cannot write %s; the resource size table is built at every start", kp);
}
// 1 when the last start's result fits: its table is served again (or none, as then). A miss logs why.
static int restbl_cache_use(const uint8_t key[32], Overlay *served, const char *keeps, double t0) {
char kp[2300], tp[2300];
restbl_cache_paths(kp, sizeof kp, tp, sizeof tp);
uint64_t n = 0;
RestblCache *c = (RestblCache *)plat_file_read(kp, &n);
const char *miss = NULL;
if (!c || n != sizeof *c || memcmp(c->magic, "TOTKRSZC", 8) || c->version != RESTBL_CACHE_VERSION ||
(c->outcome != RESTBL_NONE && c->outcome != RESTBL_TABLE))
miss = "no usable key from an earlier start";
else if (memcmp(c->key, key, 32))
miss = "the mods, the game files or the build changed since the last start";
if (!miss && c->outcome == RESTBL_TABLE) {
uint64_t zn = 0;
uint8_t *z = plat_file_read(tp, &zn), sum[32];
if (z) sha256(z, (size_t)zn, sum);
if (!z || memcmp(sum, c->table, 32)) {
free(z);
miss = "the kept table is missing or damaged";
} else if (!serve_generated(restbl_rel, served, z, (size_t)zn, "mods", // frees z
"merged resource sizes, kept from the last start", keeps)) {
miss = "the kept table cannot be served";
}
}
if (miss)
rt_log("RomFS: resource size table: built again: %s", miss);
else
rt_log("RomFS: resource size table: the mods' files are the ones of the last start: %s (%.0f ms)",
c->outcome == RESTBL_TABLE ? "its merged table is used" : "they fit the game's entries",
(now_s() - t0) * 1000);
free(c);
return !miss;
}
// With a player mod (or the TOTK_ROMFS_MODS manifest) serving files: the game's table with every shipped table of this
// version merged in (an entry larger than the game's wins), the entries a mod's table for another version gives for
// that mod's files, and each served mod file's entry raised to what its size needs (restbl_grow for a file the game
@@ -773,6 +895,12 @@ static void restbl_overlay(void) {
static const char keeps[] = "mod files that grew may fail to load";
double t0 = now_s();
uint64_t gi = lower(restbl_rel);
uint8_t cache_key[32];
Overlay *served_now = NULL;
for (size_t k = 0; k < noverlay; k++)
if (overlays[k].index == gi) served_now = &overlays[k];
int cached = rt_knob("RESTBL_CACHE", "0") && restbl_cache_key(gi, cache_key);
if (cached && restbl_cache_use(cache_key, served_now, keeps, t0)) return;
Entry ge = entry(gi);
void *gz = ge.size < (64u << 20) ? malloc((size_t)ge.size) : NULL;
Restbl *base = NULL, *out = NULL;
@@ -838,6 +966,7 @@ static void restbl_overlay(void) {
if (!merged && !raised && !members && !served) {
restbl_free(out);
rt_log("RomFS: resource size table: the mods' files fit the game's entries (%.0f ms)", (now_s() - t0) * 1000);
if (cached) restbl_cache_store(cache_key, RESTBL_NONE, NULL);
return;
}
size_t rn = 0, zn = 0;
@@ -852,10 +981,14 @@ static void restbl_overlay(void) {
rt_log("RomFS: cannot pack the merged resource size table; %s", keeps);
return;
}
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps))
uint8_t sum[32];
if (cached) sha256(z, zn, sum); // before serve_generated frees z
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps)) {
rt_log("RomFS: resource size table: %d tables merged (%d entries), %d entries raised for mod files (%d "
"added files estimated), %d for members of %d mod packs, %.0f ms", tables, merged, raised, estimated,
members, packs, (now_s() - t0) * 1000);
if (cached) restbl_cache_store(cache_key, RESTBL_TABLE, sum);
}
}
// The HeapDef table a bigger game resolution or TOTK_TEX_HEAP_EXTRA_MB needs (resolution.c): its texture heaps and
+6
View File
@@ -43,3 +43,9 @@ Changes of our own (marked "TotK Recomp"):
- `sdk/include/FidelityFX/gpu/fsr3upscaler/ffx_fsr3upscaler_callbacks_glsl.h`: the luma history's storage image is
declared `rgba16f`, the format of its images (R16G16B16A16_FLOAT in `ffx_fsr3upscaler.cpp`). It was `rgba8`, which
the Vulkan validation layer reports as a format mismatch with undefined loads and stores.
- `sdk/src/backends/vk/ffx_vk.cpp` `findMemoryTypeIndex`: memory types with `PROTECTED`, `DEVICE_COHERENT_AMD` or
`DEVICE_UNCACHED_AMD` are skipped, since the runtime enables neither protected memory nor device-coherent memory. The
function keeps the last matching type, and RADV lists those types after the plain device-local ones, so on a Radeon
780M (Mesa 26.3) FSR 3.1's images were allocated in them and its whole output was noise. When no device-local type
without `HOST_VISIBLE` exists (unified-memory GPUs: Adreno under Turnip) it takes a host-visible device-local one
instead of failing every texture allocation.
@@ -402,14 +402,28 @@ uint32_t findMemoryTypeIndex(VkPhysicalDevice physicalDevice, VkMemoryRequiremen
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
uint32_t bestCandidate = UINT32_MAX;
// TotK Recomp: unified-memory GPUs (Adreno under Turnip) have no device-local type without HOST_VISIBLE: the first
// host-visible one is taken rather than failing when no invisible type exists.
uint32_t visibleCandidate = UINT32_MAX;
VkMemoryPropertyFlags visibleProperties = 0;
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
if ((memRequirements.memoryTypeBits & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & requestedProperties)) {
// if just device-local memory is requested, make sure this is the invisible heap to prevent over-subscribing the local heap
if (requestedProperties == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT && (memProperties.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT))
// TotK Recomp: types that need a device feature the application did not enable are skipped. The loop keeps
// the last match, and RADV lists protected (TMZ) and AMD device-coherent/uncached device-local types after
// the plain ones: FSR 3.1's images landed in them and every pass read noise.
if (memProperties.memoryTypes[i].propertyFlags & (VK_MEMORY_PROPERTY_PROTECTED_BIT | VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD |
VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD))
continue;
// if just device-local memory is requested, make sure this is the invisible heap to prevent over-subscribing the local heap
if (requestedProperties == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT && (memProperties.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) {
if (visibleCandidate == UINT32_MAX)
visibleCandidate = i, visibleProperties = memProperties.memoryTypes[i].propertyFlags;
continue;
}
bestCandidate = i;
outProperties = memProperties.memoryTypes[i].propertyFlags;
@@ -419,6 +433,10 @@ uint32_t findMemoryTypeIndex(VkPhysicalDevice physicalDevice, VkMemoryRequiremen
}
}
if (bestCandidate == UINT32_MAX && visibleCandidate != UINT32_MAX) {
bestCandidate = visibleCandidate;
outProperties = visibleProperties;
}
return bestCandidate;
}
+39 -24
View File
@@ -67,7 +67,7 @@ int playtime_get(uint64_t *total_s, uint64_t *session_s); // playtime.c
bool amiibo_check_font_rebuild(void); // ui/amiibo_page.cpp; check and clear font rebuild request
}
// Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs.
// Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin, Vietnamese and Cyrillic glyphs.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc23-extensions" // #embed in C++
static const unsigned char roboto_ttf[] = {
@@ -276,12 +276,14 @@ static int vk_up(const MenuTarget *t) {
return 1;
}
// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean
// and Chinese language names merged in from a system font when there is one (each language is named in its own script).
// A catalog row also holds menu text (Simplified Chinese), so every string of the row goes into the builder: the merged
// font must cover the whole menu of that language, not only its name. Made again when the window height changes; the old
// texture goes after the queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0};
// Roboto Medium (Latin with Latin Extended-A for the French oe and the Vietnamese letters Latin-1 lacks:
// 0x0100-0x01B0, the combining marks 0x0300-0x0323 and 0x1EA0-0x1EF9; Cyrillic, dashes and quotes) at 26 px per
// 1080 lines, with the glyphs of the Japanese, Korean and Chinese language names merged in from a system font when
// there is one (each language is named in its own script). A catalog row also holds menu text (Japanese, Korean,
// Simplified Chinese), so every string of the row goes into the builder: the merged font must cover the whole menu
// of that language, not only its name. Made again when the window height changes; the old texture goes after the
// queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x01B0, 0x0300, 0x0323, 0x0400, 0x052F, 0x1EA0, 0x1EF9, 0x2010, 0x2027, 0};
static const struct { const char *lang; UiTextId name; } kCjk[] = {
{"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS},
{"zh-Hant", UI_MENU_LANGNAME_ZH_HANT},
@@ -616,22 +618,30 @@ static void row_hud_width(void) {
opt_choice_list("TOTK_HUD_WIDTH", UI_MENU_HUD_WIDTH, vals, names, n, UI_MENU_HUD_WIDTH_DESC);
}
// The 3D scene upscaler (vk_dlaa.c): off, NVIDIA DLSS or AMD FSR 3.1. An engine that cannot run here is left out of
// the steps, and the note under the value says why; a totk.ini that names it anyway shows it, with the same note.
// Returns the value the settings name ("off", "dlss", "fsr3"; without scene_upscaler, dlaa = 1 is "dlss").
// The 3D scene upscaler (vk_dlaa.c): off, NVIDIA DLSS, AMD FSR 3.1 or AMD FSR 4. An engine that cannot run here is
// left out of the steps, and the note under the value says why; a totk.ini that names it anyway shows it, with the
// same note. FSR 4 is Windows only (AMD ships no Linux libraries): elsewhere it is left out without a note.
// Returns the value the settings name ("off", "dlss", "fsr3", "fsr4"; without scene_upscaler, dlaa = 1 is "dlss").
static const char *row_scene_upscaler(void) {
static const char *const all[] = {"off", "dlss", "fsr3"};
static const int engines[] = {UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3};
static const UiTextId ids[] = {UI_MENU_SCENE_UPSCALER_OFF, UI_MENU_SCENE_UPSCALER_DLSS, UI_MENU_SCENE_UPSCALER_FSR3};
enum { N = 4 };
static const char *const all[N] = {"off", "dlss", "fsr3", "fsr4"};
static const int engines[N] = {UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3, UPSCALER_FSR4};
static const UiTextId ids[N] = {UI_MENU_SCENE_UPSCALER_OFF, UI_MENU_SCENE_UPSCALER_DLSS, UI_MENU_SCENE_UPSCALER_FSR3,
UI_MENU_SCENE_UPSCALER_FSR4};
const char *now = cfg_scene_upscaler();
const char *vals[3], *names[3];
const char *vals[N], *names[N];
static char note[256];
note[0] = 0;
int n = 0, cur = -1;
for (int i = 0; i < 3; i++) {
for (int i = 0; i < N; i++) {
int why = vk_upscaler_missing(engines[i]);
if (why) {
UiTextId t = why == UPSCALER_MISSING_DLL ? UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL : UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU;
if (why && (why != UPSCALER_MISSING_OS || !strcmp(now, all[i]))) {
UiTextId t = engines[i] == UPSCALER_FSR4
? (why == UPSCALER_MISSING_DLL ? UI_MENU_SCENE_UPSCALER_NO_FSR4_DLL
: why == UPSCALER_MISSING_OS ? UI_MENU_SCENE_UPSCALER_NO_FSR4_OS
: UI_MENU_SCENE_UPSCALER_NO_FSR4_GPU)
: why == UPSCALER_MISSING_DLL ? UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL
: UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU;
size_t k = strlen(note);
snprintf(note + k, sizeof note - k, "%s%s", k ? "; " : "", menu_text(t));
}
@@ -827,9 +837,9 @@ static void tab_screen(float scale) {
UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA};
opt_choice("TOTK_DLSS", UI_MENU_DLSS, dlss, 5, UI_MENU_DLSS_DESC);
}
if (!strcmp(engine, "fsr3")) // FSR 3.1's own sharpening (vk_dlaa.c fsr_evaluate)
opt_slider("TOTK_FSR_SHARPNESS", UI_MENU_FSR3_SHARPNESS, 0, 100, UI_MENU_FSR3_SHARPNESS_DESC, 5, "%.0f %%");
if (!strcmp(engine, "dlss")) { // DLSS's model, its characters' mask and its other switches (FSR 3.1 has none)
if (!strcmp(engine, "fsr3") || !strcmp(engine, "fsr4")) // FSR's own sharpening (vk_dlaa.c fsr_evaluate)
opt_slider("TOTK_FSR_SHARPNESS", UI_MENU_FSR_SHARPNESS, 0, 100, UI_MENU_FSR_SHARPNESS_DESC, 5, "%.0f %%");
if (!strcmp(engine, "dlss")) { // DLSS's model, its characters' mask and its other switches (FSR has none)
static const UiTextId preset[] = {UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J};
opt_choice("TOTK_DLSS_PRESET", UI_MENU_DLSS_PRESET, preset, 3, UI_MENU_DLSS_PRESET_DESC);
static const UiTextId chars[] = {UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM,
@@ -838,8 +848,8 @@ static void tab_screen(float scale) {
opt_toggle("TOTK_DLSS_FIXED_EXPOSURE", UI_MENU_DLSS_FIXED_EXPOSURE, UI_MENU_DLSS_FIXED_EXPOSURE_DESC);
opt_toggle("TOTK_DLAA_EFFECTS_AFTER", UI_MENU_DLAA_EFFECTS_AFTER, UI_MENU_DLAA_EFFECTS_AFTER_DESC);
}
static const UiTextId reflex[] = {UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST};
opt_choice("TOTK_REFLEX", UI_MENU_REFLEX, reflex, 3, UI_MENU_REFLEX_DESC);
static const UiTextId reflex[] = {UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_AUTO, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST};
opt_choice("TOTK_REFLEX", UI_MENU_REFLEX, reflex, 4, UI_MENU_REFLEX_DESC);
opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC);
rows_color();
opt_group(UI_MENU_HDR_GROUP);
@@ -1179,7 +1189,10 @@ static void tab_controls(float scale) {
static void tab_menu(float scale) {
opt_begin("##menu", scale);
static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU,
UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_ZH_HANS};
UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_ZH_HANS, UI_MENU_LANGNAME_DE,
UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_IT,
UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_KO,
UI_MENU_LANGNAME_VI};
opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, sizeof langs / sizeof *langs, UI_MENU_MENU_LANG_DESC);
opt_toggle("TOTK_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC);
opt_end();
@@ -1779,7 +1792,9 @@ static void perf_picture(const MenuTarget *t, const ImVec4 &c) {
: !strcmp(m, "ultra_performance") ? UI_MENU_DLSS_ULTRA
: UI_MENU_DLSS_DLAA;
snprintf(v[6], sizeof v[6], "%s, %s",
menu_text(up == UPSCALER_FSR3 ? UI_MENU_SCENE_UPSCALER_FSR3 : UI_MENU_SCENE_UPSCALER_DLSS),
menu_text(up == UPSCALER_FSR4 ? UI_MENU_SCENE_UPSCALER_FSR4
: up == UPSCALER_FSR3 ? UI_MENU_SCENE_UPSCALER_FSR3
: UI_MENU_SCENE_UPSCALER_DLSS),
menu_text(mt));
}
// with frame generation: the pictures shown a second, of which the FPS row above counts the ones the game drew
+6717 -36
View File
File diff suppressed because it is too large. Load diff
+10 -9
View File
@@ -11,8 +11,8 @@ typedef enum {
UI_SWKBD_CANCEL,
UI_SWKBD_PAD_HINT, // how a controller answers
// Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian, Brazilian Portuguese and
// Simplified Chinese texts.
// Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian, Brazilian Portuguese,
// Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean and Vietnamese texts.
UI_MENU_FIRST,
UI_MENU_TITLE = UI_MENU_FIRST,
UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_MODS, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO,
@@ -63,10 +63,11 @@ typedef enum {
UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA, UI_MENU_DLSS_PRESET, UI_MENU_DLSS_PRESET_DESC,
UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J, UI_MENU_DLSS_CHARS, UI_MENU_DLSS_CHARS_DESC,
UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM, UI_MENU_DLSS_CHARS_FULL, UI_MENU_FXAA, UI_MENU_FXAA_DESC,
UI_MENU_REFLEX, UI_MENU_REFLEX_DESC, UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST,
UI_MENU_REFLEX, UI_MENU_REFLEX_DESC, UI_MENU_REFLEX_AUTO, UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST,
UI_MENU_SCENE_UPSCALER, UI_MENU_SCENE_UPSCALER_DESC, UI_MENU_SCENE_UPSCALER_OFF, UI_MENU_SCENE_UPSCALER_DLSS,
UI_MENU_SCENE_UPSCALER_FSR3, UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU, UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL, UI_MENU_FSR3_SHARPNESS,
UI_MENU_FSR3_SHARPNESS_DESC,
UI_MENU_SCENE_UPSCALER_FSR3, UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU, UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL, UI_MENU_FSR_SHARPNESS,
UI_MENU_FSR_SHARPNESS_DESC, UI_MENU_SCENE_UPSCALER_FSR4, UI_MENU_SCENE_UPSCALER_NO_FSR4_GPU,
UI_MENU_SCENE_UPSCALER_NO_FSR4_DLL, UI_MENU_SCENE_UPSCALER_NO_FSR4_OS,
// Game
UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_40, UI_MENU_FPS_45, UI_MENU_FPS_60, UI_MENU_FPS_90,
@@ -228,7 +229,7 @@ typedef enum {
UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_DE, UI_MENU_LANGNAME_IT,
UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS,
UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO, UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_EN_GB,
UI_MENU_LANGNAME_FR_CA, UI_MENU_LANGNAME_ES_419,
UI_MENU_LANGNAME_FR_CA, UI_MENU_LANGNAME_ES_419, UI_MENU_LANGNAME_VI,
// Advanced
UI_MENU_ADV_WARNING,
@@ -331,7 +332,7 @@ const char *ui_text_lang(const char *switch_code);
typedef struct { const char *code; UiTextId name; } UiGameLang;
int ui_text_game_langs(int game_version, UiGameLang *out, int max);
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en", "ru", "pt-BR", "zh-Hans");
// unset, the system UI language when the catalog has menu text for it (English, Russian, Brazilian Portuguese,
// Simplified Chinese), else English. Follows a live change of the setting.
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en", "ru", "pt-BR", "zh-Hans", "de",
// "fr", "es", "it", "nl", "ja", "ko"); unset, the system UI language when the catalog has menu text for it, Simplified
// Chinese for Traditional Chinese, else English. Follows a live change of the setting.
const char *menu_text(UiTextId id);
+14 -4
View File
@@ -11,7 +11,7 @@
#include "vk_ahead.h" // TOTK_SYNC_AHEAD=check hooks (vk_ahead_on)
// Required (device choice fails without them): Vulkan 1.3; VK_KHR_swapchain, VK_KHR_push_descriptor,
// VK_EXT_depth_clip_control, VK_EXT_external_memory_host; features timelineSemaphore, dynamicRendering,
// VK_EXT_depth_clip_control; features timelineSemaphore, dynamicRendering,
// synchronization2, shaderStorageImageWriteWithoutFormat, depthClipControl, shaderInt64, samplerAnisotropy,
// independentBlend, geometryShader, textureCompressionBC.
// Optional (flag set in VkCtx when enabled): the has_* members.
@@ -38,13 +38,16 @@ typedef struct VkCtx {
has_astc_ldr, // textureCompressionASTC_LDR (enabled when reported)
has_calibrated, // VK_KHR/EXT_calibrated_timestamps (GPU idle split in the perf line)
has_hdr_metadata, // VK_EXT_hdr_metadata (vk_hdr.c vk_hdr_metadata)
has_nv_reflex; // VK_NV_low_latency2 (NVIDIA Reflex Low Latency)
has_nv_reflex, // VK_NV_low_latency2 (NVIDIA Reflex Low Latency)
has_amd_antilag; // VK_AMD_anti_lag (AMD Anti-Lag 2)
// Feedback loops (maxwell.md 1.9, vk_exec_draw.c feedback_prepare): a draw samples a target of its open pass that
// an earlier draw of the pass wrote. TOTK_FEEDBACK=0: VK_FEEDBACK_OFF (sampled in GENERAL without a barrier, the
// old behaviour); VK_FEEDBACK_LAYOUT with VK_EXT_attachment_feedback_loop_layout and dynamicRenderingLocalRead
// (attachable images get feedback usage, a by-region barrier inside the pass); else (or TOTK_FEEDBACK=restart)
// VK_FEEDBACK_RESTART (the pass ends and restarts behind the full barrier).
int feedback; // VK_FEEDBACK_*
int has_external_memory_host; // VK_EXT_external_memory_host; without it CPU-visible pools get shadow
// storage (vk_memory.c mirror_mode), as under Wine
uint32_t min_imported_host_alignment; // VK_EXT_external_memory_host
VkDeviceSize vma_block; // VMA's block size for heaps over 1 GiB (TOTK_VMA_BLOCK_MIB, vk_device.c)
int device_index; // index in vkEnumeratePhysicalDevices
@@ -63,6 +66,7 @@ typedef struct {
int mesa; // a Mesa driver the game runs on: RADV, ANV or NVK
int intel_igpu_win; // Intel's Windows driver on an integrated GPU (UHD, Iris Xe, Core Ultra graphics)
int demote; // shaderDemoteToHelperInvocation enabled: modules may use OpDemoteToHelperInvocation
int null_attach; // TOTK_NULL_ATTACH=1: empty colour slots get a dummy attachment (vk_exec.c null_attach_view)
} VkCaps;
extern VkCaps vk_caps;
void vk_caps_driver(VkPhysicalDevice p); // first, before vkCreateDevice: vk_caps.amd, amd_sc, mesa, intel_igpu_win
@@ -209,7 +213,8 @@ long vk_validation_errors_total(void); // validation errors since th
// Guest or host threads; every call needs vk_init(). The first nine have the GfxBackend signatures of gfx.h; vk_backend.c builds
// gfx_vulkan_backend from them.
int vk_pool_init(pool_t *p); // CPU-visible: guest storage imported (VK_EXT_external_memory_host) as one
// VkBuffer; physical: device-local memory; virtual: a 64 KiB page table
// VkBuffer, or its shadow copy (vk_memory.c mirror_mode); physical:
// device-local memory; virtual: a 64 KiB page table
void vk_pool_fini(pool_t *p); // drops images cut from the pool; waits for the GPU if it used the pool
int vk_pool_map_virtual(pool_t *v, int n, const void *requests); // nvn_mapping_t[n], checked by the front end
void vk_texture_register(int id, const tex_t *t, const view_t *v); // texture descriptor slot (copied)
@@ -343,7 +348,8 @@ int vk_mem_flush_add_probe(void); // --probe-vkexec: the flush range list
uint64_t vk_mem_mirror_uploaded(void); // --probe-vkexec: bytes copied into mirrors since the last summary line
int vk_mem_mirror_probe(uint64_t addr); // --probe-vkexec: the pool at addr gets its mirror as on a first buffer use;
// 1 when it has one
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m); // once
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m,
int host_import); // once; host_import: VK_EXT_external_memory_host is enabled
int vk_mem_class_of(uint64_t addr); // VK_MCLS_* of the pool at addr (NONE when unbacked)
void vk_mem_census(uint64_t frame); // at each present: pool census and traffic, logged at frame 1800 and,
// with TOTK_TRACE=perf, every 1800 frames
@@ -502,6 +508,10 @@ typedef struct {
// into it, when the last draw into it was that copy and the swapchain is HDR10.
void vk_hdr_present_source(const VkTexImage *win, VkImage *image, VkFormat *format);
void vk_hdr_image_gone(VkImage image);
// vk_caps.null_attach: empty colour slots of a pass get a dummy VK_EXEC_NULL_ATTACH_FMT attachment, and the pipelines
// name that format for them with writes masked off (vk_exec.c null_attach_view, vk_pipeline.c gkey_fill).
#define VK_EXEC_NULL_ATTACH_FMT VK_FORMAT_R8_UNORM
void vk_exec_null_attach_release(void); // vk_device.c, before the device goes: frees the dummy attachments
const VkTexImage *vk_texture_get(const tex_t *t); // created and made current; NULL for BUFFER or unmapped formats
const VkTexImage *vk_texture_revive(const tex_t *t, uint32_t pos); // the entry vk_texture_get would return if it exists, made live at op pos
// A texture slot; a slot whose texture was finalized follows the live texture at the same storage (hle_nvn.c).
+3
View File
@@ -123,6 +123,9 @@ void vk_caps_init(VkCtx *c) {
uint32_t zero_locals = env_u32("TOTK_ZERO_LOCALS", (uint32_t)vk_caps.mesa);
gfx_shader_set_host(vk_caps.float64, vk_caps.sbuf_align, told, gather, zero_locals != 0);
if (gather) rt_log("vk caps: gather coordinates biased for %u sub-texel bits (TOTK_GATHER_BIAS)", gather);
// Read here, before any pipeline key is made: the pipelines' colour formats depend on it (vk_pipeline.c gkey_fill)
vk_caps.null_attach = rt_knob("NULL_ATTACH", "0") == 1;
if (vk_caps.null_attach) rt_log("vk caps: empty colour slots get a dummy attachment (TOTK_NULL_ATTACH=1)");
char dv[32];
driver_version(dv, sizeof dv, c->props.vendorID, c->props.driverVersion);
+45 -7
View File
@@ -13,6 +13,7 @@
#include "platform/platform.h"
#include "vk_dlaa.h"
#include "vk_fg.h"
#include "vk_ffx.h"
#include "vk_fsr3.h"
static VkCtx g_vk;
@@ -174,8 +175,7 @@ static int create_instance(void) {
}
static const char *const k_required_ext[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME,
VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME};
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME};
// Name of the first missing required extension, or NULL.
static const char *missing_required(VkPhysicalDevice pd) {
@@ -263,7 +263,6 @@ static int pick_device(void) {
}
free(qp);
rt_log("vk: using gpu %d: %s", best, g_vk.props.deviceName);
vk_mem_class_log(&g_vk.props, &g_vk.mem_props);
return 1;
}
@@ -289,6 +288,11 @@ typedef struct {
VkPhysicalDeviceDynamicRenderingLocalReadFeaturesKHR lr;
VkPhysicalDeviceAddressBindingReportFeaturesEXT abr;
VkPhysicalDevicePresentIdFeaturesKHR pid;
VkPhysicalDeviceCooperativeMatrixFeaturesKHR coop; // FSR 4 (vk_ffx.c)
#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME
VkPhysicalDeviceShaderFloat8FeaturesEXT f8; // FSR 4 (vk_ffx.c)
#endif
VkPhysicalDeviceAntiLagFeaturesAMD al;
} FeatureChain;
static int create_device(void) {
@@ -299,6 +303,13 @@ static int create_device(void) {
const char *ext[52];
uint32_t n_ext = 0;
for (size_t i = 0; i < sizeof k_required_ext / sizeof *k_required_ext; i++) ext[n_ext++] = k_required_ext[i];
// VK_EXT_external_memory_host is optional: without it (or with TOTK_VK_NO_HOST_IMPORT=1, which tests that path on
// any GPU) CPU-visible pools get shadow storage (vk_memory.c mirror_mode).
const char *no_import = cfg_get("TOTK_VK_NO_HOST_IMPORT");
g_vk.has_external_memory_host = has_ext(ep, ne, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) &&
!(no_import && *no_import && strcmp(no_import, "0"));
if (g_vk.has_external_memory_host) ext[n_ext++] = VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME;
vk_mem_class_log(&g_vk.props, &g_vk.mem_props, g_vk.has_external_memory_host);
FeatureChain *c = calloc(1, sizeof *c);
void **tail = &c->f2.pNext;
@@ -340,7 +351,16 @@ static int create_device(void) {
CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT);
CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR);
}
vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's; the twelve slots after it stay for the nine below
vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's or FSR 4's; the twelve slots after it stay for the nine below
// FSR 4's shader extensions (vk_ffx_device_exts) are enabled with their features, as far as the driver reports them
for (uint32_t i = 0; i < n_ext; i++) {
if (!strcmp(ext[i], VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME))
CHAIN(coop, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR);
#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME
else if (!strcmp(ext[i], VK_EXT_SHADER_FLOAT8_EXTENSION_NAME))
CHAIN(f8, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT8_FEATURES_EXT);
#endif
}
if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; }
// GPU timestamps on the CPU clock (vk_sync.c): the perf line splits GPU idle time into waiting for a submission or not.
if (has_ext(ep, ne, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 2; ext[n_ext++] = VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; }
@@ -357,14 +377,24 @@ static int create_device(void) {
g_vk.has_nv_checkpoints = 1;
ext[n_ext++] = VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME;
}
// NVIDIA Reflex Low Latency (VK_NV_low_latency2 requires VK_KHR_present_id)
// Low latency (the reflex setting). on and boost: NVIDIA Reflex (VK_NV_low_latency2, which requires
// VK_KHR_present_id), as before Anti-Lag came in, so a GPU without Reflex still gets nothing new from them. auto:
// Reflex, or AMD Anti-Lag 2 (VK_AMD_anti_lag: RADV and AMD's Windows driver) on a GPU without Reflex. Only one of
// the two runs. off (the default) enables neither extension.
const char *rv = cfg_value("TOTK_REFLEX");
if (rv && strcmp(rv, "off") != 0 && strcmp(rv, "0") != 0) {
if (strcmp(rv, "off") != 0 && strcmp(rv, "0") != 0) {
int want_antilag = !strcmp(rv, "auto");
if (has_ext(ep, ne, VK_KHR_PRESENT_ID_EXTENSION_NAME) && has_ext(ep, ne, "VK_NV_low_latency2")) {
g_vk.has_nv_reflex = 1;
ext[n_ext++] = VK_KHR_PRESENT_ID_EXTENSION_NAME;
ext[n_ext++] = "VK_NV_low_latency2";
CHAIN(pid, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR);
} else if (want_antilag && has_ext(ep, ne, VK_AMD_ANTI_LAG_EXTENSION_NAME)) {
g_vk.has_amd_antilag = 1;
ext[n_ext++] = VK_AMD_ANTI_LAG_EXTENSION_NAME;
CHAIN(al, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ANTI_LAG_FEATURES_AMD);
} else if (want_antilag) {
rt_log("Low latency: neither VK_NV_low_latency2 nor VK_AMD_anti_lag is available");
} else {
rt_log("Reflex: VK_NV_low_latency2 not available");
}
@@ -418,6 +448,11 @@ static int create_device(void) {
g_vk.has_nv_reflex = 0;
rt_log("Reflex: VK_NV_low_latency2 not available (no presentId feature)");
}
if (g_vk.has_amd_antilag && !c->al.antiLag) {
g_vk.has_amd_antilag = 0;
rt_log("Anti-Lag: VK_AMD_anti_lag not available (no antiLag feature)");
}
if (g_vk.has_amd_antilag) rt_log("Anti-Lag: AMD Anti-Lag 2 on (VK_AMD_anti_lag)");
g_vk.has_astc_ldr = h->textureCompressionASTC_LDR;
{
const char *e = cfg_get("TOTK_FEEDBACK");
@@ -450,7 +485,8 @@ static int create_device(void) {
else { g_vk.xfer_queue = g_vk.gfx_queue; g_vk.xfer_shared = 1; }
VkPhysicalDeviceExternalMemoryHostPropertiesEXT emh = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};
VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &emh};
VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
.pNext = g_vk.has_external_memory_host ? &emh : NULL};
vkGetPhysicalDeviceProperties2(g_vk.phys, &p2);
g_vk.min_imported_host_alignment = (uint32_t)emh.minImportedHostPointerAlignment;
vk_caps_init(&g_vk);
@@ -486,9 +522,11 @@ static void destroy_all(void) {
if (g_vk.device) vkDeviceWaitIdle(g_vk.device);
if (g_vk.device) vk_fg_release();
if (g_vk.device) fsr3_release();
if (g_vk.device) vk_ffx_release();
if (g_vk.device) vk_astc_release();
if (g_vk.device) vk_deswz_release();
if (g_vk.device) vk_crumbs_release();
if (g_vk.device) vk_exec_null_attach_release();
if (g_vk.timeline) vkDestroySemaphore(g_vk.device, g_vk.timeline, NULL);
vk_headroom_stop();
if (g_vk.vma) vmaDestroyAllocator(g_vk.vma);
+114 -49
View File
@@ -11,6 +11,10 @@
// layout with a set-then-get round trip before anything relies on it.
//
// Where DLAA runs in the frame, the jitter and the motion vectors: see the sections below.
//
// The scene upscaler (scene_upscaler) is DLSS, AMD FSR 3.1 (vk_fsr3.cpp, built from the FidelityFX SDK 1.1.4 sources)
// or AMD FSR 4 (vk_ffx.c, AMD's FSR SDK 2.4 libraries, Windows): the arming, the jitter, the motion vectors and the
// copy of the result below are shared, and only the call that upscales differs (evaluate, fsr_evaluate).
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
@@ -25,6 +29,7 @@
#include "input.h"
#include "nvn_api.h"
#include "vk_exec.h"
#include "vk_ffx.h"
#include "vk_fg.h"
#include "vk_fsr3.h"
#include "vk_rec.h"
@@ -105,25 +110,43 @@ static int p_getp(const NgxParam *p, const char *n, void **v) { return NGX_OK(((
#endif
// The scene upscaler picked at start (scene_upscaler; without it dlaa = 1 is DLSS): a restart applies another. AMD FSR
// 3.1 (vk_fsr3.cpp) takes the same inputs at the same point of the frame as DLSS and runs on any GPU.
// 3.1 (vk_fsr3.cpp) and FSR 4 (vk_ffx.c) take the same inputs at the same point of the frame as DLSS; FSR 3.1 runs on
// any GPU, FSR 4 on Windows where AMD's libraries offer it for the GPU (vk_ffx_init). AMD ships those libraries for
// Windows only, so elsewhere fsr4 is off.
int vk_upscaler_engine(void) {
static int e = -1;
if (e < 0) {
const char *v = cfg_scene_upscaler();
e = !strcmp(v, "dlss") ? UPSCALER_DLSS : !strcmp(v, "fsr3") ? UPSCALER_FSR3 : UPSCALER_OFF;
e = !strcmp(v, "dlss") ? UPSCALER_DLSS : !strcmp(v, "fsr3") ? UPSCALER_FSR3
: !strcmp(v, "fsr4") ? UPSCALER_FSR4 : UPSCALER_OFF;
#ifndef _WIN32
if (e == UPSCALER_FSR4) {
rt_log("dlaa: scene_upscaler = fsr4 runs on Windows only (AMD's FSR SDK has no Linux libraries): off");
e = UPSCALER_OFF;
}
#endif
}
return e;
}
// The setting's name of an engine, and the name the log gives it.
static const char *engine_value(int e) {
return e == UPSCALER_DLSS ? "dlss" : e == UPSCALER_FSR3 ? "fsr3" : e == UPSCALER_FSR4 ? "fsr4" : "off";
}
static const char *engine_name(int e) {
return e == UPSCALER_DLSS ? "DLSS" : e == UPSCALER_FSR3 ? "FSR 3.1" : e == UPSCALER_FSR4 ? "FSR 4" : "none";
}
// The engine picked at start while the settings still name it (the menu turns it off at once, as dlaa did).
int vk_upscaler_on(void) {
int e = vk_upscaler_engine();
return e && !strcmp(cfg_scene_upscaler(), e == UPSCALER_DLSS ? "dlss" : "fsr3");
return e && !strcmp(cfg_scene_upscaler(), engine_value(e));
}
// NGX is brought up only when DLSS is the scene upscaler at start: its device extensions can only be asked for at
// device creation, and loading the driver's NGX core on every NVIDIA machine would cost start time and change the device
// with DLSS off. So the choice applies after a restart; with DLSS not picked (off or FSR 3.1), nothing of NGX runs.
// with DLSS off. So the choice applies after a restart; with DLSS not picked (off or FSR), nothing of NGX runs. FSR
// 4's device extensions are chosen at device creation as well (vk_ffx_device_exts).
int vk_dlaa_wanted(void) {
static int wanted = -1;
if (wanted < 0) wanted = vk_upscaler_engine() == UPSCALER_DLSS;
@@ -182,6 +205,7 @@ void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, cons
uint32_t max) {
unsigned ni = 0, nd = 0;
const char **ie = NULL, **de = NULL;
vk_ffx_device_exts(have, nhave, ext, n, max); // FSR 4's, when it is the engine
if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return;
for (unsigned i = 0; i < nd; i++) {
int ok = 0;
@@ -210,12 +234,18 @@ static int vtable_ok(void) {
}
// The upscaler's half of the per-object motion's gate (vk_objmv_wanted, below the frame state): DLSS once NGX came up
// with it (vk_dlaa_available), FSR 3.1 whenever it is the scene upscaler picked at start. Latched in vk_dlaa_init,
// before the first frame: with no upscaler, or DLSS without NGX, it stays 0 as vk_dlaa_available does.
// with it (vk_dlaa_available), FSR 3.1 whenever it is the scene upscaler picked at start, FSR 4 once AMD's libraries
// offered it for the device (vk_ffx_available). Latched in vk_dlaa_init, before the first frame: with no upscaler, or
// one that did not come up, it stays 0.
static int objmv;
void vk_dlaa_init(void) {
objmv = vk_upscaler_engine() == UPSCALER_FSR3;
if (vk_upscaler_engine() == UPSCALER_FSR4) {
vk_ffx_init();
objmv = vk_ffx_available();
return;
}
if (!vk_dlaa_wanted() || !core_load()) return;
// The executable's folder, where NGX looks for the DLSS model library and writes its logs.
wchar_t wdir[PLAT_PATH_MAX];
@@ -338,26 +368,38 @@ static struct {
VkExecTarget hud_t, win; // the output-sized target the scene is scaled into; the window texture
float cam_dr[2]; // the viewport depth range of the draw cam_addr was noted at
int fg_mv_ok; // the frame's motion is in the motion image (fg_motion)
int fsr; // the engine is AMD FSR 3.1 (scene_upscaler = fsr3 at start), else DLSS
int fsr; // the AMD FSR engine (UPSCALER_FSR3 or UPSCALER_FSR4, picked at start), 0: DLSS
} D = {.mv_ok = -1, .cfg_seen = ~0u};
#define DLSS_SIZES (sizeof D.sizes / sizeof D.sizes[0])
const VkTexImage *vk_dlaa_swap_img;
VkImageView vk_dlaa_swap_view;
// DLSS needs NGX and its model, FSR 3.1 runs on any GPU the back end runs on: on already says the engine is there.
// DLSS needs NGX and its model, FSR 4 AMD's libraries with FSR 4 for the GPU, FSR 3.1 runs on any GPU the back end
// runs on: on already says the engine is there (vk_dlaa_frame).
static int dl_active(void) { return !D.failed && D.on; }
// The scene is followed (its G-buffer, light target, end and camera): for DLSS, or with DLSS off for frame generation.
static int track(void) { return dl_active() || D.fg; }
int vk_dlaa_fg_on; // D.fg for vk_exec_draw.c's per-draw test (vk_dlaa_hud)
int vk_upscaler_running(void) {
return dl_active() && D.evals ? (D.fsr ? UPSCALER_FSR3 : UPSCALER_DLSS) : UPSCALER_OFF;
return dl_active() && D.evals ? (D.fsr ? D.fsr : UPSCALER_DLSS) : UPSCALER_OFF;
}
// For the menu. DLSS: after a start with it picked, what NGX said; before, an NVIDIA GPU and the DLL (an NVIDIA GPU
// without RTX shows only once NGX came up). FSR 3.1 is built in.
// without RTX shows only once NGX came up). FSR 4 likewise: Windows, AMD's two libraries, then after a start with it
// picked what they offered for the device (vk_ffx_init), before one an AMD GPU (the libraries decide which Radeons get
// FSR 4, so another Radeon shows only after that start). FSR 3.1 is built in.
int vk_upscaler_missing(int engine) {
if (engine == UPSCALER_FSR4) {
#ifndef _WIN32
return UPSCALER_MISSING_OS;
#else
if (!res_ffx_dlls()) return UPSCALER_MISSING_DLL;
if (vk_ffx_tried()) return vk_ffx_available() ? 0 : UPSCALER_MISSING_GPU;
return vk_ctx()->props.vendorID == 0x1002 ? 0 : UPSCALER_MISSING_GPU;
#endif
}
if (engine != UPSCALER_DLSS) return 0;
if (!res_dlss_dll()) return UPSCALER_MISSING_DLL;
if (N.tried) return N.available ? 0 : UPSCALER_MISSING_GPU;
@@ -377,7 +419,8 @@ static int fg_objects(void) {
int vk_fg_objects_on(void) { return D.fg && fg_objects(); }
// The per-object motion's gates (vk_mvprev.c's tables, vk_usnap.c's host copy, vk_exec_draw.c's motion draws and
// lock): the upscaler that reads the motion image (objmv: DLSS once NGX came up, or FSR 3.1 picked at start), or frame
// lock): the upscaler that reads the motion image (objmv: DLSS once NGX came up, FSR 3.1 picked at start, or FSR 4
// once it came up), or frame
// generation following the scene with its objects. Frame generation is off with either upscaler, so the second term is
// 0 whenever one runs.
int vk_objmv_wanted(void) { return objmv || vk_fg_objects_on(); }
@@ -1303,18 +1346,18 @@ static int scene_shaped(const VkExecTarget *c) {
return a * 20 >= b * 19 && b * 20 >= a * 19;
}
// FSR 3.1's half of evaluate (vk_fsr3.cpp), after the motion vectors and the recorder's drain: the camera, the time step
// and the history reset, then the dispatch into e->out. 0 when it failed (DLAA is then off for the run). The camera
// comes from the scene camera block's rows 0-10 (vk_fg.cpp vk_fg_camera, which frame generation reads too: FSR 3.1
// wants the near and far planes and the vertical field of view for its depth tests); a cut there (a cutscene's camera
// jump) starts a new history. The block's bytes are the snapshot's host copy, which vk_usnap.c keeps while the
// per-object motion runs (vk_objmv_wanted, so with FSR 3.1).
// FSR's half of evaluate (FSR 3.1: vk_fsr3.cpp, FSR 4: vk_ffx.c), after the motion vectors and the recorder's drain:
// the camera, the time step and the history reset, then the dispatch into e->out. Both engines get the same inputs.
// 0 when it failed (DLAA is then off for the run). The camera comes from the scene camera block's rows 0-10 (vk_fg.cpp
// vk_fg_camera, which frame generation reads too: FSR wants the near and far planes and the vertical field of view
// for its depth tests); a cut there (a cutscene's camera jump) starts a new history. The block's bytes are the
// snapshot's host copy, which vk_usnap.c keeps while the per-object motion runs (vk_objmv_wanted, so with FSR).
static int fsr_evaluate(VkExec *ex, struct Size *e, const VkExecTarget *t, const VkExecTarget *z, uint32_t ow,
uint32_t oh, float jx, float jy, int timed) {
static VkFgScene cam = {.near_m = 0.1f, .far_m = 25000.0f, .fov_y = 0.8727f}; // until the first camera read
// the SDK takes whole images: the scene's targets are level 0, layer 0 of their own images
if (t->level || t->base_layer || z->level || z->base_layer || z->format != VK_FORMAT_D32_SFLOAT)
return dl_fail("FSR 3.1 input (not level 0, layer 0 of a colour and a D32F depth image)", 0), 0;
return dl_fail("FSR input (not level 0, layer 0 of a colour and a D32F depth image)", 0), 0;
const float *rows = D.cam_addr ? (const float *)vk_usnap_bytes(D.cam_addr, 11 * 16) : NULL;
int cut = rows && vk_fg_camera(rows, nvn_depth_minus_w(), D.cam_dr, &cam);
if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image;
@@ -1326,19 +1369,31 @@ static int fsr_evaluate(VkExec *ex, struct Size *e, const VkExecTarget *t, const
// without (vk_dlaa_skip_draw), so without it FSR's picture is softer than the game's own
int sharp = cfg_int("TOTK_FSR_SHARPNESS");
sharp = sharp < 0 ? 0 : sharp > 100 ? 100 : sharp;
Fsr3Frame fr = {.color = t->image, .color_format = t->format, .depth = z->image, .mv = e->mv, .out = e->out,
.w = t->width, .h = t->height, .ow = ow, .oh = oh, .jx = jx, .jy = jy, .near_m = cam.near_m,
.far_m = cam.infinite || cam.far_m <= cam.near_m ? 1e5f : cam.far_m, .fov_y = cam.fov_y,
.dt_ms = dt > 0 && dt < 100 ? (float)dt : 16.67f, .reset = D.reset, .sharpness = sharp / 100.0f,
.fence = ex->fence};
float far_m = cam.infinite || cam.far_m <= cam.near_m ? 1e5f : cam.far_m;
float dt_ms = dt > 0 && dt < 100 ? (float)dt : 16.67f;
uint64_t c0 = timed ? kern_now_ns() : 0;
int ok = fsr3_dispatch(ex->cb, &fr);
int ok;
if (D.fsr == UPSCALER_FSR4) {
VkFfxDispatch fd = {.color = {t->image, t->format, t->width, t->height},
.depth = {z->image, z->format, t->width, t->height},
.mv = {e->mv, VK_FORMAT_R16G16_SFLOAT, t->width, t->height},
.out = {e->out, VK_FORMAT_R16G16B16A16_SFLOAT, ow, oh}, .jx = jx, .jy = jy,
.dt_ms = dt_ms, .cam_near = cam.near_m, .cam_far = far_m, .fov_y = cam.fov_y,
.sharpness = sharp / 100.0f, .reset = D.reset, .fence = ex->fence};
ok = vk_ffx_dispatch(ex->cb, &fd);
} else {
Fsr3Frame fr = {.color = t->image, .color_format = t->format, .depth = z->image, .mv = e->mv, .out = e->out,
.w = t->width, .h = t->height, .ow = ow, .oh = oh, .jx = jx, .jy = jy, .near_m = cam.near_m,
.far_m = far_m, .fov_y = cam.fov_y, .dt_ms = dt_ms, .reset = D.reset,
.sharpness = sharp / 100.0f, .fence = ex->fence};
ok = fsr3_dispatch(ex->cb, &fr);
}
if (timed) T.cpu_ngx += kern_now_ns() - c0;
if (!ok) {
// the SDK may have bound a pipeline or descriptor sets of its own before it failed: the next draw binds
// everything again, and the game's own scaling and FXAA run from the next frame (DLAA off for the run)
vk_exec_draw_new_cb(ex);
return dl_fail("FSR 3.1 dispatch", 0), 0;
return dl_fail(D.fsr == UPSCALER_FSR4 ? "FSR 4 dispatch" : "FSR 3.1 dispatch", 0), 0;
}
return 1;
}
@@ -1487,7 +1542,7 @@ engine_done:
rt_log("dlaa: %llu frames anti-aliased%s (scene %ux%u, output %ux%u; %llu before the effects, %llu frames without the "
"DLAA point, %llu with camera motion, %llu with the characters' mask, %llu without a camera, %llu jitter "
"holds; resets: %llu size, %llu camera, %llu target; reactive mask %llu, without its copy %llu)",
(unsigned long long)D.evals, D.fsr ? " by FSR 3.1" : "", w, h, ow, oh, (unsigned long long)D.fx_frames, (unsigned long long)D.frames_missed,
(unsigned long long)D.evals, D.fsr == UPSCALER_FSR4 ? " by FSR 4" : D.fsr ? " by FSR 3.1" : "", w, h, ow, oh, (unsigned long long)D.fx_frames, (unsigned long long)D.frames_missed,
(unsigned long long)D.mv_frames, (unsigned long long)D.masked, (unsigned long long)D.mv_none,
(unsigned long long)D.holds, (unsigned long long)D.why[0], (unsigned long long)D.why[1],
(unsigned long long)D.why[2], (unsigned long long)R.made, (unsigned long long)R.missed);
@@ -1832,9 +1887,9 @@ void vk_dlaa_pass(VkExec *ex) {
}
// TOTK_DLSS, read at each present (the menu switches it live): the scene size of the mode (resolution.c) and the
// texture bias that goes with it while the upscaler runs. DLSS takes NVIDIA's log2(scene / output); FSR 3.1 takes AMD's
// log2(scene / output) - 1 (FidelityFX FSR 3 upscaler docs, "Mipmap biasing"), so -1 also in place. The bias follows
// the mode and the upscaler going on or off; the engine is fixed for the run.
// texture bias that goes with it while the upscaler runs. DLSS takes NVIDIA's log2(scene / output); FSR 3.1 and FSR 4
// take AMD's log2(scene / output) - 1 (FidelityFX FSR 3 upscaler docs, "Mipmap biasing"), so -1 also in place. The
// bias follows the mode and the upscaler going on or off; the engine is fixed for the run.
static void dlss_mode(void) {
static char mode[32];
static float bias; // what the material samplers have (vk_texture.c starts at 0)
@@ -1844,7 +1899,8 @@ static void dlss_mode(void) {
res_dlss_mode(m);
}
float b = 0.0f;
if (dl_active()) b = res_dlss_lod_bias() - (vk_upscaler_engine() == UPSCALER_FSR3 ? 1.0f : 0.0f);
int e = vk_upscaler_engine();
if (dl_active()) b = res_dlss_lod_bias() - (e == UPSCALER_FSR3 || e == UPSCALER_FSR4 ? 1.0f : 0.0f);
if (b != bias) bias = b, vk_sampler_dlss_bias(b);
}
@@ -1870,17 +1926,24 @@ void vk_dlaa_frame(void) {
vk_dlaa_swap_img = NULL, vk_dlaa_swap_view = VK_NULL_HANDLE;
dlss_mode();
preset_check();
int fsr = vk_upscaler_engine() == UPSCALER_FSR3; // fixed for the run: D.fsr never changes while on
int on = (fsr || N.available) && vk_upscaler_on();
// the engine is fixed for the run: D.fsr never changes while on. FSR 4 runs once AMD's libraries offered it for
// the device (vk_ffx_init said why not otherwise, and the upscaler stays off)
int e = vk_upscaler_engine();
int fsr = e == UPSCALER_FSR3 || e == UPSCALER_FSR4 ? e : 0;
int ready = e == UPSCALER_FSR3 || (e == UPSCALER_FSR4 ? vk_ffx_available() : N.available);
int on = ready && vk_upscaler_on();
vk_fg_frame();
// frame generation with an upscaler is not built yet: with FSR 3.1 picked it stays off (said once)
// frame generation with an upscaler is not built yet: with FSR picked it stays off (said once)
static int fg_said;
if (fsr && on && vk_fg_engine() != VK_FG_OFF && !fg_said++)
rt_log("fg: frame generation off while FSR 3.1 upscales the scene (scene_upscaler = fsr3)");
rt_log("fg: frame generation off while %s upscales the scene (scene_upscaler = %s)", engine_name(fsr),
engine_value(fsr));
int fg = fsr && on ? 0 : vk_fg_wanted(on && !D.failed);
D.bloom = D.hud = D.hud_wait = D.fin = D.gen = D.fg_mv_ok = 0;
if (on != D.on || fg != D.fg) {
if (on != D.on) rt_log("dlaa: %s", on ? (fsr ? "on with FSR 3.1" : "on") : "off");
if (on != D.on)
rt_log("dlaa: %s%s%s", on ? "on" : "off", on && fsr ? " with " : "",
on && fsr == UPSCALER_FSR4 ? vk_ffx_version() : on && fsr ? "FSR 3.1" : "");
if (fg != D.fg) rt_log("dlaa: the scene is %s for frame generation", fg ? "followed" : "no longer followed");
D.on = on, D.fg = vk_dlaa_fg_on = fg, D.fsr = fsr;
// either way the next DLAA frame starts a new history from an unjittered frame
@@ -1922,10 +1985,12 @@ void vk_dlaa_frame(void) {
// stretched over the whole screen.
static const uint64_t FXAA_FS[] = {0xf450003ebeb3dc52ull, 0x0a12f4bc2a9a4fbeull, 0x5c43ae18948d52cbull,
0xaad42238801d31d8ull, 0xde20aef90fea4ce6ull, 0x755964e8dce7f34dull};
// The fragment shader of the FXAA's first pass, the copy of the scene target into the scratch target (this build's
// translator, seen in 1.4.3 frame logs; another hash leaves the draw alone). See vk_dlaa_skip_draw for why FSR 3.1's
// frames skip it where it copies the scene target onto itself.
static const uint64_t FXAA_COPY_FS[] = {0xa0fd34391f2af811ull};
// The fragment shader of the FXAA's first pass, the copy of the scene target into the scratch target (another hash
// leaves the draw alone): this build's translator, seen in 1.4.3 frame logs, and the one with patch 0017, whose two
// support buffer fields change every fragment shader's hash (as with FXAA_FS above), read by codexx-dev from a 1.4.3
// run with FSR on (pull request #1245). See vk_dlaa_skip_draw for why FSR's frames skip it where it copies the scene
// target onto itself.
static const uint64_t FXAA_COPY_FS[] = {0xa0fd34391f2af811ull, 0x9d065204aac9766bull};
// Chunks of one submission look shaders up side by side: an entry's hash is stored before its shader, and entries are
// added under the lock.
@@ -1970,14 +2035,14 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) {
"FXAA_FS): the FXAA stays on", (unsigned long long)fx_off_frames);
}
}
// FSR 3.1 in place (the scene as large as the output, so no scaling draw follows) goes without the game's FXAA
// and its copy of the scene target onto itself on every frame, as codexx-dev found for FSR (pull request #1245,
// vk_dlaa.c vk_dlaa_skip_draw there). Measured there on 1.4.3 at a 2560x1440 scene and output: with the upscaler on
// the game ran its FXAA, which also sharpens, on 17 frames in every 96 and on the others drew its copy shader from
// the scene target onto itself, so the picture went soft and sharp in turns. Here the dynamic resolution stays at
// 100 % while FSR 3.1 runs (resolution.c res_dynres_live) and FSR sharpens its own output (fsr_sharpness,
// fsr_evaluate) in place of the FXAA's sharpening. Scaled frames (D.up) need nothing more: there FSR's picture
// already replaces the scaling FXAA draw below.
// FSR 3.1 or FSR 4 in place (the scene as large as the output, so no scaling draw follows) goes without the game's
// FXAA and its copy of the scene target onto itself on every frame, as codexx-dev found for FSR (pull request
// #1245, vk_dlaa.c vk_dlaa_skip_draw there). Measured there on 1.4.3 at a 2560x1440 scene and output: with the
// upscaler on the game ran its FXAA, which also sharpens, on 17 frames in every 96 and on the others drew its copy
// shader from the scene target onto itself, so the picture went soft and sharp in turns. Here the dynamic
// resolution stays at 100 % while FSR runs (resolution.c res_dynres_live) and FSR sharpens its own output
// (fsr_sharpness, fsr_evaluate) in place of the FXAA's sharpening. Scaled frames (D.up) need nothing more: there
// FSR's picture already replaces the scaling FXAA draw below.
int fsr_in_place = D.done && !D.up && D.fsr;
if (fxaa && !D.up && !fsr_in_place) return 0; // nothing to skip: no shader lookup per draw at the defaults
if (!fs) return 0;
@@ -2003,7 +2068,7 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) {
static int logged_fxaa, logged_copy;
if (known && ex->depth.image) {
if (!logged_fxaa)
logged_fxaa = 1, rt_log("dlaa: FSR 3.1 skips the game's FXAA (fragment shader %016llx) and sharpens its "
logged_fxaa = 1, rt_log("dlaa: FSR skips the game's FXAA (fragment shader %016llx) and sharpens its "
"own picture (fsr_sharpness)", (unsigned long long)h);
return 1;
}
@@ -2011,7 +2076,7 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) {
for (size_t i = 0; i < sizeof FXAA_COPY_FS / sizeof FXAA_COPY_FS[0]; i++) copy |= h == FXAA_COPY_FS[i];
if (copy && ex->color[0].image == D.color.image && vk_exec_draw_samples(ex, fs, D.color.img)) {
if (!logged_copy)
logged_copy = 1, rt_log("dlaa: FSR 3.1 skips the game's copy of the scene target onto itself (fragment "
logged_copy = 1, rt_log("dlaa: FSR skips the game's copy of the scene target onto itself (fragment "
"shader %016llx)", (unsigned long long)h);
return 1;
}
+6 -5
View File
@@ -1,5 +1,5 @@
// DLAA (vk_dlaa.c): the scene upscaler, NVIDIA DLSS or AMD FSR 3.1 (vk_fsr3.cpp), behind scene_upscaler (dlaa = 1 without
// it: DLSS).
// DLAA (vk_dlaa.c): the scene upscaler, NVIDIA DLSS, AMD FSR 3.1 (vk_fsr3.cpp) or AMD FSR 4 (vk_ffx.c, Windows), behind
// scene_upscaler (dlaa = 1 without it: DLSS).
#pragma once
#include "vk.h"
@@ -15,9 +15,10 @@ void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, cons
void vk_dlaa_init(void);
// 1 when dlaa is on and NGX came up with DLSS (after vk_dlaa_init): a DLSS mode's smaller scene is scaled up by DLSS.
int vk_dlaa_available(void);
// 1 when the per-object motion runs (DLSS's and FSR 3.1's half after vk_dlaa_init, frame generation's live): DLSS
// with NGX up (vk_dlaa_available), FSR 3.1 picked as the scene upscaler, or frame generation following the scene with
// its objects (vk_fg_objects_on: TOTK_FG_OBJECTS, default 1).
// 1 when the per-object motion runs (the upscaler's half after vk_dlaa_init, frame generation's live): DLSS with NGX
// up (vk_dlaa_available), FSR 3.1 picked as the scene upscaler, FSR 4 picked and offered for the device
// (vk_ffx_available), or frame generation following the scene with its objects (vk_fg_objects_on: TOTK_FG_OBJECTS,
// default 1).
int vk_objmv_wanted(void);
int vk_fg_objects_on(void);
// vk_exec.c vk_exec_pass_begin, once the pass's targets are resolved and before its barrier: arms the frame on the
+94 -1
View File
@@ -674,6 +674,85 @@ static void barrier_to(VkExec *ex, const VkImage *want, const VkImageAspectFlags
void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); }
// TOTK_NULL_ATTACH=1 (null_attach, default 0; vk_caps.null_attach): colour slots of a pass that hold no target get a
// view of a dummy image instead of VK_NULL_HANDLE. Leaving a slot's imageView null is valid Vulkan, but Intel's legacy
// Windows driver for 6th-10th generation graphics (HD 520, UHD 620; driver 101.21xx, Vulkan 1.3.215) faulted inside
// vkCmdBeginRendering reading an attachment entry of the pass, at the first scene passes after the logo (issue #1343);
// whether the empty slots are the cause is untested on that driver. The pipelines then name NULL_ATTACH_FMT for those
// slots, with their writes masked off (vk_pipeline.c gkey_fill, target_wmask), so the views match the pipelines'
// formats. Only slots below the last one with a target get a dummy: the pipelines' colorAttachmentCount ends there
// (vk_pipeline.c target_count), and a pass without colour targets keeps none. All empty slots of a pass share one
// view; an image serves every pass it covers (size, layers) with its sample count, so TotK makes one or two per scene
// resolution. Each is moved to GENERAL in the upload batch and kept until the device goes (vk_exec_null_attach_release);
// loads and stores are DONT_CARE, so the slots cost no bandwidth.
#define NULL_ATTACH_MAX 24
typedef struct { uint32_t w, h, layers, samples; VkImage img; VmaAllocation alloc; VkImageView view; } NullAttach;
static NullAttach null_att[NULL_ATTACH_MAX];
static int nnull_att;
static PlatMutex null_att_lock = PLAT_MUTEX_INIT;
void vk_exec_null_attach_release(void) {
VkCtx *c = vk_ctx();
plat_mutex_lock(&null_att_lock);
for (int i = 0; c && i < nnull_att; i++) {
vkDestroyImageView(c->device, null_att[i].view, NULL);
vmaDestroyImage(c->vma, null_att[i].img, null_att[i].alloc);
}
nnull_att = 0;
plat_mutex_unlock(&null_att_lock);
}
static VkImageView null_attach_view(uint32_t w, uint32_t h, uint32_t layers, uint32_t samples) {
plat_mutex_lock(&null_att_lock);
for (int i = 0; i < nnull_att; i++) { // a view may be larger than the render area (VkRenderingInfo needs it to cover it)
const NullAttach *a = &null_att[i];
if (a->w >= w && a->h >= h && a->layers >= layers && a->samples == samples) {
VkImageView v = a->view;
plat_mutex_unlock(&null_att_lock);
return v;
}
}
static int warned;
if (nnull_att == NULL_ATTACH_MAX) {
if (!warned++) rt_log("vk_exec: more than %d dummy attachment shapes: further empty slots stay empty", NULL_ATTACH_MAX);
plat_mutex_unlock(&null_att_lock);
return VK_NULL_HANDLE;
}
VkCtx *c = vk_ctx();
NullAttach a = {w, h, layers, samples, VK_NULL_HANDLE, NULL, VK_NULL_HANDLE};
VkImageCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
.format = VK_EXEC_NULL_ATTACH_FMT, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = layers,
.samples = (VkSampleCountFlagBits)samples, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE};
VmaAllocationInfo info = {0};
if (vmaCreateImage(c->vma, &ci, &ai, &a.img, &a.alloc, &info) != VK_SUCCESS) {
if (!warned++) rt_log("vk_exec: a %ux%u x %u dummy attachment could not be created: the slot stays empty", w, h, layers);
plat_mutex_unlock(&null_att_lock);
return VK_NULL_HANDLE;
}
VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = a.img,
.viewType = layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D,
.format = VK_EXEC_NULL_ATTACH_FMT,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, layers}};
if (vkCreateImageView(c->device, &vi, NULL, &a.view) != VK_SUCCESS) {
vmaDestroyImage(c->vma, a.img, a.alloc);
if (!warned++) rt_log("vk_exec: a dummy attachment view could not be created: the slot stays empty");
plat_mutex_unlock(&null_att_lock);
return VK_NULL_HANDLE;
}
// In the upload batch, which goes to the queue before the part that records this pass (as the BC stand-ins)
VkCommandBuffer cb = vk_upload_begin();
image_barrier(cb, a.img, VK_IMAGE_LAYOUT_UNDEFINED, layers);
vk_upload_end();
null_att[nnull_att++] = a;
int n = nnull_att;
plat_mutex_unlock(&null_att_lock);
rt_log("vk_exec: dummy attachment %ux%u x %u, %u samples, for empty colour slots: %.2f MiB (%d of %d)", w, h, layers,
samples, info.size / 1048576.0, n, NULL_ATTACH_MAX);
return a.view;
}
void vk_exec_pass_begin(VkExec *ex) {
if (ex->in_pass) return;
resolve_rt(ex);
@@ -696,10 +775,24 @@ void vk_exec_pass_begin(VkExec *ex) {
ex->fb_dirty = 0;
ex->pass_serial++;
VkRenderingAttachmentInfo ca[8], da = {0}, sa = {0};
uint32_t dummies = 0; // null_attach: empty slots below this get a dummy (the pipelines' colorAttachmentCount)
VkImageView dummy = VK_NULL_HANDLE;
if (vk_caps.null_attach)
for (uint32_t i = 0; i < ex->pass_ncolor; i++)
if (ex->color[i].image) dummies = i + 1;
for (uint32_t i = 0; i < ex->pass_ncolor; i++) {
const VkExecTarget *t = &ex->color[i];
ca[i] = (VkRenderingAttachmentInfo){.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
if (!t->image) continue;
if (!t->image) {
if (i < dummies) { // a dummy for the empty slot, which the pipelines name too (null_attach_view)
if (!dummy) dummy = null_attach_view(ex->pass_w, ex->pass_h, ex->pass_layers, ex->pass_samples);
ca[i].imageView = dummy;
ca[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
ca[i].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
ca[i].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
continue;
}
ca[i].imageView = view_of(ex, t);
ca[i].imageLayout = fbl >> i & 1 ? VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT : VK_IMAGE_LAYOUT_GENERAL;
ca[i].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
+18
View File
@@ -3328,6 +3328,22 @@ static void bi_done(VkExec *ex, const VkPipeInfo *info, const VkPipeState *s, co
D->B.bi_valid = 1;
}
// Mesa ANV (Intel iGPU, Linux): a draw whose vertex shader reads a storage buffer reads stale data inside a pass unless
// the sampler cache is invalidated first: the half-resolution particle pass drew campfire smoke and clouds as white or
// dark blobs and turned the sky white for single frames (#927). A by-region barrier before such a draw removes it
// (0 of 1460 frames broken against 57 of 779, about 2 fps of 40 on an Iris Xe); a stall alone or the attachment flush
// alone does not. The barrier costs about 5% of the frame rate on an Iris Xe and was only tested there, so it is off
// on every GPU by default; TOTK_ANV_VS_BARRIER=1 (ini: anv_vs_barrier = 1) turns it on, 0 keeps it off.
static int anv_vs_barrier(void) {
static int on = -1;
if (on < 0) {
const char *e = cfg_get("TOTK_ANV_VS_BARRIER");
on = e && *e && strcmp(e, "0") != 0;
rt_log("vk_exec: barrier before vertex-stage storage reads in a pass %s", on ? "on" : "off");
}
return on;
}
// Pass, shaders, pipeline, fixed state and resources for a draw. 0: the draw is skipped.
static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
VkExecDraw *D = ex->draw;
@@ -3540,6 +3556,8 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
if (bim == 2) bi_census(ex, info, sp, bgt, bgb, bsg, sm_hit); // on counts nothing: it is what gets timed
bind_resources(ex, info, bim ? bgt : NULL, bgb);
if (fbl & ex->fb_dirty) feedback_barrier(ex);
else if (ex->in_pass && anv_vs_barrier() && gfx_shader_resources(vs, GFX_RES_SSBO, &(const GfxShaderRes *){0}))
{ uint32_t keep = ex->fb_dirty; feedback_barrier(ex); ex->fb_dirty = keep; } // keep fb_dirty: feedback_prepare learns from it
feedback_written(ex, sp);
bind_vertex_buffers(ex);
if (vk_dump_armed) vk_dump_draw(ex, sp, p, info);
+296
View File
@@ -0,0 +1,296 @@
// AMD FSR 4 for the scene upscaler (vk_ffx.h). The FSR SDK 2.4 ships its Vulkan effects as signed DLLs behind a
// loader: amd_fidelityfx_loader_vk.dll exports the ffx-api entry points and finds the effect DLL
// (amd_fidelityfx_upscaler_vk.dll) next to itself. Both are loaded from the executable's folder at run time; no SDK
// code is compiled in, only the descriptor layouts of ffx_api_min.h.
//
// The upscaler DLL offers several versions (FSR 4.x, FSR 3.1.x) and decides by itself which ones a device can run:
// vk_ffx_init lists them and pins the newest 4.x. A device the DLL offers no FSR 4 for runs without the upscaler (the
// log and the menu say so): FSR 3.1 is scene_upscaler = fsr3, built from the SDK 1.1.4 sources (vk_fsr3.cpp), not a
// fallback of this DLL. Every context is created with the pinned version (ffxOverrideVersion).
//
// What FSR 4 gets is what FSR 3.1 gets (vk_dlaa.c fsr_evaluate): the R11G11B10F light target as linear HDR colour, the
// D32F scene depth (standard direction, the far plane finite), motion vectors at the render size in render pixels
// pointing from this frame's position to last frame's without the jitter (motionVectorScale 1), the jitter the scene
// was drawn with, the camera's planes and field of view. That is FSR's own convention: its guide derives the
// projection offset as (2 jx / w, -2 jy / h), which moves the picture by (jx, jy) window pixels with y down, the way
// vk_dlaa_viewport moves the viewport. The exposure is FSR's own (AUTO_EXPOSURE), as codexx-dev's pull request #1245
// ran it on an RX 9070 XT.
#include "vk_ffx.h"
#include "cfg.h"
#include "host.h"
#ifndef _WIN32
int vk_ffx_wanted(void) { return 0; }
void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) {
(void)have, (void)nhave, (void)ext, (void)n, (void)max;
}
void vk_ffx_init(void) {}
int vk_ffx_tried(void) { return 0; }
int vk_ffx_available(void) { return 0; }
int vk_ffx_dispatch(VkCommandBuffer cb, const VkFfxDispatch *d) { return (void)cb, (void)d, 0; }
void vk_ffx_release(void) {}
const char *vk_ffx_version(void) { return ""; }
#else
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ffx_api_min.h"
#define FFX_LOADER L"amd_fidelityfx_loader_vk.dll"
#define FFX_MAX_VERSIONS 16
// The SDK's Vulkan backend writes a dispatch's descriptor sets and constants into rings this deep and frees the views
// of the dispatch that many back without knowing the GPU (FFX_MAX_QUEUED_FRAMES in the SDK's ffx_types.h, as
// vk_fsr3.cpp wait_ring reads it for SDK 1.1.4).
#define FFX_QUEUED 4
static struct {
HMODULE dll;
PfnFfxCreateContext create;
PfnFfxDestroyContext destroy;
PfnFfxQuery query;
PfnFfxDispatch dispatch;
int tried, loaded, available, failed;
VkDeviceContext dev;
uint64_t version_id;
char version[48];
ffxContext ctx; // the live context, made for ow x oh
uint32_t ow, oh;
uint64_t ring[FFX_QUEUED], n, waits; // the fences of the last dispatches (wait_ring)
} F;
int vk_ffx_wanted(void) { return vk_upscaler_engine() == UPSCALER_FSR4; }
static int loader_load(void) {
if (F.tried) return F.loaded;
F.tried = 1;
wchar_t path[MAX_PATH + 64];
DWORD len = GetModuleFileNameW(NULL, path, MAX_PATH);
while (len && path[len - 1] != L'\\') len--;
path[len] = 0;
wcscat(path, FFX_LOADER);
// LOAD_WITH_ALTERED_SEARCH_PATH: the loader's own imports and the effect DLL resolve from the executable's folder
F.dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!F.dll) {
rt_log("fsr4: cannot load amd_fidelityfx_loader_vk.dll next to totk.exe (error %lu): the scene upscaler is off",
GetLastError());
return 0;
}
F.create = (PfnFfxCreateContext)(void *)GetProcAddress(F.dll, "ffxCreateContext");
F.destroy = (PfnFfxDestroyContext)(void *)GetProcAddress(F.dll, "ffxDestroyContext");
F.query = (PfnFfxQuery)(void *)GetProcAddress(F.dll, "ffxQuery");
F.dispatch = (PfnFfxDispatch)(void *)GetProcAddress(F.dll, "ffxDispatch");
if (!F.create || !F.destroy || !F.query || !F.dispatch) {
rt_log("fsr4: amd_fidelityfx_loader_vk.dll lacks the ffx-api entry points: the scene upscaler is off");
return 0;
}
return F.loaded = 1;
}
static int has(const VkExtensionProperties *have, uint32_t nhave, const char *name) {
for (uint32_t i = 0; i < nhave; i++)
if (!strcmp(have[i].extensionName, name)) return 1;
return 0;
}
static void add(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max,
const char *name) {
for (uint32_t i = 0; i < *n; i++)
if (!strcmp(ext[i], name)) return;
if (has(have, nhave, name) && *n < max) ext[(*n)++] = name;
}
// The extensions the FSR SDK's own sample enables for its effects (Cauldron2 device_vk.cpp): cooperative matrix and
// 8-bit floats for FSR 4's network where the device has them. The rest it uses (16-bit floats and storage, integer
// dot products, subgroup size control) is core Vulkan 1.3, which vk_device.c enables as far as the driver reports it.
void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) {
if (!vk_ffx_wanted()) return;
add(have, nhave, ext, n, max, VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME);
#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME
add(have, nhave, ext, n, max, VK_EXT_SHADER_FLOAT8_EXTENSION_NAME);
#endif
}
void vk_ffx_init(void) {
if (!vk_ffx_wanted() || !loader_load()) return;
const VkCtx *c = vk_ctx();
F.dev = (VkDeviceContext){c->device, c->phys, vkGetDeviceProcAddr};
uint64_t count = FFX_MAX_VERSIONS, ids[FFX_MAX_VERSIONS] = {0};
const char *names[FFX_MAX_VERSIONS] = {0};
struct ffxQueryDescGetVersions q = {.header = {FFX_API_QUERY_DESC_TYPE_GET_VERSIONS, NULL},
.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE, .device = &F.dev,
.outputCount = &count, .versionIds = ids, .versionNames = names};
ffxReturnCode_t r = F.query(NULL, &q.header);
if (r != FFX_API_RETURN_OK || !count) {
rt_log("fsr4: no upscaler for this device (query %u, %llu versions; is amd_fidelityfx_upscaler_vk.dll next to "
"totk.exe?): the scene upscaler is off", (unsigned)r, (unsigned long long)count);
return;
}
if (count > FFX_MAX_VERSIONS) count = FFX_MAX_VERSIONS;
char list[256] = "";
// The newest 4.x the DLL offers for this device; the DLL leaves FSR 4 out for GPUs it does not run on
int best = -1, best_minor = 0, best_patch = 0;
for (uint64_t i = 0; i < count; i++) {
const char *nm = names[i] ? names[i] : "?";
size_t used = strlen(list);
snprintf(list + used, sizeof list - used, "%s%s", i ? ", " : "", nm);
int ma = 0, mi = 0, pa = 0;
if (sscanf(nm, "%d.%d.%d", &ma, &mi, &pa) < 1 || ma != 4) continue;
if (best < 0 || mi > best_minor || (mi == best_minor && pa > best_patch))
best = (int)i, best_minor = mi, best_patch = pa;
}
if (best < 0) {
rt_log("fsr4: the FSR libraries offer %s for this device, no FSR 4: the scene upscaler is off", list);
return;
}
F.version_id = ids[best];
snprintf(F.version, sizeof F.version, "FSR %s", names[best]);
F.available = 1;
rt_log("fsr4: upscaler versions for this device: %s; using %s", list, F.version);
}
int vk_ffx_tried(void) { return F.tried; }
int vk_ffx_available(void) { return vk_ffx_wanted() && F.available; }
const char *vk_ffx_version(void) { return F.available ? F.version : ""; }
// Messages from the upscaler (errors and warnings), in UTF-16; into the log as UTF-8.
static void on_message(uint32_t type, const wchar_t *msg) {
char s[512];
if (!msg || !WideCharToMultiByte(CP_UTF8, 0, msg, -1, s, (int)sizeof s, NULL, NULL)) return;
rt_log("fsr4: %s: %s", type == FFX_API_MESSAGE_TYPE_ERROR ? "error" : "warning", s);
}
// The context for an ow x oh output, any scene up to that size (DYNAMIC_RESOLUTION: the modes and the game's tiers
// change the scene without a new context), as vk_fsr3.cpp create makes FSR 3.1's.
static int create(uint32_t ow, uint32_t oh) {
struct ffxOverrideVersion ov = {.header = {FFX_API_DESC_TYPE_OVERRIDE_VERSION, NULL}, .versionId = F.version_id};
struct ffxCreateContextDescUpscaleVersion ver = {
.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION, &ov.header}, .version = FFX_UPSCALER_VERSION};
struct ffxCreateBackendVKDesc be = {.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK, &ver.header},
.deviceContext = F.dev};
// Linear HDR scene light with the upscaler's own exposure; standard depth with a finite far plane, as FSR 3.1's
uint32_t flags = FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE | FFX_UPSCALE_ENABLE_AUTO_EXPOSURE |
FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION;
if (rt_knob("FSR4_DEBUG", "0")) flags |= FFX_UPSCALE_ENABLE_DEBUG_CHECKING; // TOTK_FSR4_DEBUG=1: API checks
struct ffxCreateContextDescUpscale cd = {.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE, &be.header},
.flags = flags, .maxRenderSize = {ow, oh}, .maxUpscaleSize = {ow, oh},
.fpMessage = on_message};
ffxContext ctx = NULL;
ffxReturnCode_t r = F.create(&ctx, &cd.header, NULL);
if (r != FFX_API_RETURN_OK || !ctx) {
rt_log("fsr4: context creation failed (%u) at %ux%u: FSR 4 off for this run", (unsigned)r, ow, oh);
return 0;
}
struct ffxQueryGetProviderVersion pv = {.header = {FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION, NULL}};
F.query(&ctx, &pv.header);
rt_log("fsr4: context up to %ux%u -> %ux%u with %s (flags %#x)", ow, oh, ow, oh,
pv.versionName ? pv.versionName : F.version, flags);
F.ctx = ctx, F.ow = ow, F.oh = oh, F.n = 0;
memset(F.ring, 0, sizeof F.ring);
return 1;
}
static void destroy(void) {
if (F.ctx) F.destroy(&F.ctx, NULL);
F.ctx = NULL;
}
static uint32_t surface_format(VkFormat f) {
switch (f) {
case VK_FORMAT_B10G11R11_UFLOAT_PACK32: return FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT;
case VK_FORMAT_R16G16B16A16_SFLOAT: return FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT;
case VK_FORMAT_R16G16_SFLOAT: return FFX_API_SURFACE_FORMAT_R16G16_FLOAT;
case VK_FORMAT_D32_SFLOAT: return FFX_API_SURFACE_FORMAT_R32_FLOAT;
default: return FFX_API_SURFACE_FORMAT_UNKNOWN;
}
}
// Every image of the scene upscaler stays in VK_IMAGE_LAYOUT_GENERAL: GENERIC_READ and UNORDERED_ACCESS are the
// states the Vulkan backend maps to that layout (ffx_vk.cpp getVKImageLayoutFromResourceState), and it puts each
// resource back into the state it was given at the end of the dispatch.
static struct FfxApiResource resource(const VkFfxImage *im, uint32_t usage, uint32_t state) {
struct FfxApiResource r;
memset(&r, 0, sizeof r);
if (!im->image) return r;
r.resource = (void *)im->image;
r.description = (struct FfxApiResourceDescription){.type = FFX_API_RESOURCE_TYPE_TEXTURE2D,
.format = surface_format(im->format), .width = im->width,
.height = im->height, .depth = 1, .mipCount = 1, .usage = usage};
r.state = state;
return r;
}
// With the game's two or three frames in flight the dispatch FFX_QUEUED - 1 back is long done; should it not be, its
// submission is waited for here (counted), as vk_fsr3.cpp wait_ring does for FSR 3.1.
static void wait_ring(uint64_t fence) {
if (F.n >= FFX_QUEUED - 1) {
uint64_t back = F.ring[(F.n + 1) % FFX_QUEUED];
if (back && vk_sync_fence_done() < back) {
if (!F.waits++) rt_log("fsr4: waiting for the submission of a dispatch %d back (more frames in flight than "
"the SDK's rings hold)", FFX_QUEUED - 1);
vk_sync_fence_wait(back, 2000000000ull);
}
}
F.ring[F.n % FFX_QUEUED] = fence;
}
int vk_ffx_dispatch(VkCommandBuffer cb, const VkFfxDispatch *d) {
if (!F.available || F.failed) return 0;
uint32_t ow = d->out.width, oh = d->out.height;
if (!F.ctx || ow != F.ow || oh != F.oh) {
if (F.ctx) {
vkDeviceWaitIdle(vk_ctx()->device); // what the old context recorded is queued or submitted
destroy();
}
if (!create(ow, oh)) return F.failed = 1, 0;
}
if (d->color.width > F.ow || d->color.height > F.oh) {
rt_log("fsr4: a %ux%u scene is larger than the %ux%u output: FSR 4 off for this run", d->color.width,
d->color.height, F.ow, F.oh);
return F.failed = 1, 0;
}
wait_ring(d->fence);
struct ffxDispatchDescUpscale u;
memset(&u, 0, sizeof u);
u.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE;
u.commandList = (void *)cb;
u.color = resource(&d->color, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ);
u.depth = resource(&d->depth, FFX_API_RESOURCE_USAGE_DEPTHTARGET, FFX_API_RESOURCE_STATE_GENERIC_READ);
u.motionVectors = resource(&d->mv, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ);
u.output = resource(&d->out, FFX_API_RESOURCE_USAGE_UAV, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS);
// (no reactive or transparency mask: FSR 3.1 gets none either)
u.jitterOffset = (struct FfxApiFloatCoords2D){d->jx, d->jy};
u.motionVectorScale = (struct FfxApiFloatCoords2D){1.0f, 1.0f}; // render pixels already
u.renderSize = (struct FfxApiDimensions2D){d->color.width, d->color.height};
u.upscaleSize = (struct FfxApiDimensions2D){ow, oh};
u.enableSharpening = d->sharpness > 0;
u.sharpness = d->sharpness > 1.0f ? 1.0f : d->sharpness;
u.frameTimeDelta = d->dt_ms;
u.preExposure = 1.0f;
u.reset = d->reset != 0;
u.cameraNear = d->cam_near;
u.cameraFar = d->cam_far;
u.cameraFovAngleVertical = d->fov_y;
u.viewSpaceToMetersFactor = 1.0f; // TotK's world units are metres
ffxReturnCode_t r = F.dispatch(&F.ctx, &u.header);
F.n++;
if (r != FFX_API_RETURN_OK) {
rt_log("fsr4: dispatch failed (%u) at %ux%u -> %ux%u: FSR 4 off for this run", (unsigned)r, d->color.width,
d->color.height, ow, oh);
return F.failed = 1, 0;
}
return 1;
}
void vk_ffx_release(void) {
const VkCtx *c = vk_ctx();
if (!F.ctx || !c || !c->device) return;
vkDeviceWaitIdle(c->device);
if (F.waits) rt_log("fsr4: %llu dispatches waited for an earlier one's submission", (unsigned long long)F.waits);
destroy();
}
#endif
+41
View File
@@ -0,0 +1,41 @@
// AMD FSR 4 (vk_ffx.c), the fourth engine of vk_dlaa.c's scene upscaler (scene_upscaler = fsr4): the frame DLSS and
// FSR 3.1 get goes to FSR 4 through AMD's FSR SDK 2.4 signed libraries, amd_fidelityfx_loader_vk.dll and
// amd_fidelityfx_upscaler_vk.dll next to the executable. Windows only; elsewhere every call does nothing.
#pragma once
#include "vk.h"
// FSR 4 is the scene upscaler picked at start (vk_dlaa.c vk_upscaler_engine); the device may still lack it.
int vk_ffx_wanted(void);
// vk_device.c, while it builds the device: the extensions FSR 4's shaders use (cooperative matrix, 8-bit floats) join
// the list when the device has them; their feature structures are chained there.
void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max);
void vk_ffx_init(void); // vk_dlaa.c vk_dlaa_init, after the device exists: loads the loader and pins FSR 4
int vk_ffx_tried(void); // vk_ffx_init ran (FSR 4 picked at start, on Windows)
int vk_ffx_available(void); // vk_ffx_init found FSR 4 for this device
typedef struct { // one image FSR reads or writes, in VK_IMAGE_LAYOUT_GENERAL, level 0 and layer 0
VkImage image;
VkFormat format;
uint32_t width, height;
} VkFfxImage;
typedef struct {
VkFfxImage color; // the scene's light (R11G11B10F or RGBA16F, linear), the render size
VkFfxImage depth; // its D32F depth, standard direction (0 near), finite far plane
VkFfxImage mv; // RG16F motion vectors as vk_fsr3.h Fsr3Frame.mv (render pixels, without the jitter)
VkFfxImage out; // RGBA16F with storage, the output size
float jx, jy; // this frame's jitter, render pixels (window x right, y down), as the scene was drawn
float dt_ms; // time since the previous dispatch
float cam_near, cam_far; // the camera's planes (m)
float fov_y; // vertical field of view, radians
float sharpness; // FSR's own sharpening pass (RCAS) on its output, 0..1; 0: none
int reset; // a new history
uint64_t fence; // the submission's timeline value (VkExec.fence)
} VkFfxDispatch;
// Records FSR 4 into cb (every image in GENERAL, left so; no render pass open; recorder drained by the caller). The
// context is made at the first call and again when the output size changes; the scene may be any size up to the
// output. 0 when it failed (logged; FSR 4 stays off for the run). FSR binds pipelines and descriptors of its own.
int vk_ffx_dispatch(VkCommandBuffer cb, const VkFfxDispatch *d);
void vk_ffx_release(void); // vk_device.c destroy_all, before the device goes away; harmless when nothing was made
const char *vk_ffx_version(void); // "FSR 4.1.2" once vk_ffx_init pinned it, "" before or without
+11 -3
View File
@@ -1871,7 +1871,7 @@ static PlatMutex mirror_stat_lock = PLAT_MUTEX_INIT;
static volatile int64_t m_live_n, m_live_bytes, m_refused_n[MR_N], m_refused_bytes[MR_N];
static volatile int64_t m_flush_calls, m_flush_bytes, v_pages, v_skipped, v_mismatch;
static void mirror_mode(int discrete) {
static void mirror_mode(int discrete, int host_import) {
const char *e = cfg_value("TOTK_MEMORY");
int mode = discrete ? 1 : 0; // 0 import, 1 mirror, 2 verify
const char *why = discrete ? "auto, discrete gpu" : "auto, uma";
@@ -1906,6 +1906,14 @@ static void mirror_mode(int discrete) {
#else
shadow_on = !sh || !*sh || strcmp(sh, "0");
#endif
// Without VK_EXT_external_memory_host (Qualcomm Adreno's Windows driver, some mobile and older drivers, or
// TOTK_VK_NO_HOST_IMPORT=1) guest memory cannot be imported: every CPU-visible pool gets shadow storage, the path
// Wine already takes (import_pool -> shadow_pool), whatever TOTK_SHADOW says.
if (!host_import) {
if (!shadow_on) rt_log("mem: no host import (VK_EXT_external_memory_host): shadow storage%s",
sh && *sh ? ", TOTK_SHADOW=0 overridden" : "");
shadow_on = 1;
}
defer_on = shadow_on && cfg_bool("TOTK_SYNC_AHEAD") && strcmp(cfg_value("TOTK_SYNC_AHEAD"), "check") &&
cfg_bool("TOTK_SHADOW_DEFER"); // check: the wait stays exact, nothing is deferred
if (defer_on) rt_log("mem: TOTK_SHADOW_DEFER: shadow updates that wait for a reader are queued for the GPU instead");
@@ -2935,7 +2943,7 @@ static void vram_log(uint64_t frame) {
// Device class: INTEGRATED -> uma; a discrete GPU with a DEVICE_LOCAL heap of 1 GiB or more beside a
// heap that is not device-local (host memory) -> discrete; otherwise uma (import everywhere). Sets the mirror mode.
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m) {
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m, int host_import) {
int big_local = -1, host_heap = -1;
for (uint32_t h = 0; h < m->memoryHeapCount; h++) {
if (m->memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
@@ -2977,7 +2985,7 @@ void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDevic
if (host_backed == HB_UMA)
rt_log("mem: device memory against system memory: commit and physical memory (uma), reserve %llu MiB "
"(TOTK_MEM_RESERVE_MIB)", (unsigned long long)(room_reserve >> 20));
mirror_mode(discrete);
mirror_mode(discrete, host_import);
}
// ---------------------------------------------------------------- upload batches and deferred destruction
+4
View File
@@ -1345,6 +1345,7 @@ static uint32_t target_wmask(const VkPipeState *s, int i) {
uint32_t m = s->chmask.mask >> (4 * i) & 0xf;
if (s->fs && !(gfx_shader_outputs(s->fs, NULL) >> i & 1)) m = 0;
if (i == 1 && s->fs && P.f_dual_src && uses_src1(s)) m = 0; // output 1 is the second blend source (spirv_dual_source)
if (!s->color_fmt[i] && vk_caps.null_attach) m = 0; // an empty slot's dummy attachment (vk_exec.c) takes no writes
return m;
}
@@ -1380,6 +1381,9 @@ static void gkey_fill(const VkPipeState *s, GKey *k) {
o[3] = (uint8_t)blend_factor(b->src_a), o[4] = (uint8_t)blend_factor(b->dst_a), o[5] = (uint8_t)blend_op(b->eq_a);
}
}
if (vk_caps.null_attach) // empty slots get the dummy attachment's format (vk_exec.c null_attach_view)
for (int i = 0; i < k->n_color; i++)
if (k->color[i] == VK_FORMAT_UNDEFINED) k->color[i] = VK_EXEC_NULL_ATTACH_FMT;
if (!P.dyn_vi) {
VtxInput v;
vertex_input(s, &v);
+61
View File
@@ -0,0 +1,61 @@
"""A/B log reports keep absolute timings when a percentage has a zero baseline."""
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def window(frame, interval, replay, b, n=60, world=20):
return (f'perf: frame {frame}: interval avg {interval:.2f} ms max 100.00 ms ({1000 / interval:.1f} fps); '
f'replay avg {replay:.2f} ms; ab {b}/{n}; world {world:.1f} s\n')
class AbSummaryTest(unittest.TestCase):
def summarize(self, text):
with tempfile.TemporaryDirectory() as tmp:
log = Path(tmp) / 'synthetic.log'
log.write_text(text, encoding='utf-8')
return subprocess.run([sys.executable, str(ROOT / 'tools' / 'ab_summary.py'), str(log)],
capture_output=True, text=True)
def test_no_replay_on_either_side_keeps_the_interval_comparison(self):
run = self.summarize(window(60, 20, 0, 0) + window(120, 10, 0, 60))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('B - A: interval -10.00 ms (-50.0%), replay +0.00 ms (n/a: A is zero)', run.stdout)
def test_replay_appearing_in_b_reports_its_absolute_cost(self):
run = self.summarize(window(60, 10, 0, 0) + window(120, 12, 2, 60))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('replay +2.00 ms (n/a: A is zero)', run.stdout)
def test_replay_disappearing_in_b_still_has_a_defined_percentage(self):
run = self.summarize(window(60, 12, 2, 0) + window(120, 10, 0, 60))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('replay -2.00 ms (-100.0%)', run.stdout)
def test_nonzero_means_remain_weighted_by_each_windows_frames(self):
text = window(60, 10, 2, 0, n=30) + window(120, 20, 4, 0)
text += window(180, 10, 2, 60)
run = self.summarize(text)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('interval -6.67 ms (-40.0%), replay -1.33 ms (-40.0%)', run.stdout)
def test_load_and_mixed_windows_stay_excluded(self):
text = window(60, 100, 100, 0, world=5) + window(120, 100, 100, 30)
text += window(180, 10, 2, 0) + window(240, 12, 3, 60)
run = self.summarize(text)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('interval +2.00 ms (+20.0%), replay +1.00 ms (+50.0%)', run.stdout)
def test_missing_side_keeps_the_diagnostic_and_failure_exit(self):
run = self.summarize(window(60, 10, 2, 0))
self.assertEqual(run.returncode, 1)
self.assertIn('no whole A and B windows', run.stdout)
self.assertEqual(run.stderr, '')
if __name__ == '__main__':
unittest.main()
+112
View File
@@ -0,0 +1,112 @@
"""Build command arguments through real Ninja and a POSIX shell, using only synthetic paths and source files."""
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import build_game as build # noqa: E402
NINJA, SHELL = shutil.which('ninja'), shutil.which('sh')
@unittest.skipUnless(NINJA, 'no Ninja on PATH')
class CommandTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory(prefix='build command ')
self.addCleanup(tmp.cleanup)
self.folder = Path(tmp.name)
self.probe = self.folder / 'arguments.py'
self.probe.write_text('import json, pathlib, sys\n'
'pathlib.Path(sys.argv[1]).write_text(json.dumps(sys.argv[2:]))\n')
def ninja(self, target, command, posix=False, bindings=''):
if posix:
# Ninja on Unix uses sh -c. An expanded response file lets Windows exercise those same shell bytes too.
shell = subprocess.list2cmdline([SHELL]) if os.name == 'nt' else shlex.quote(SHELL)
text = (f'rule probe\n command = {shell.replace("$", "$$")} $out.rsp\n'
f' rspfile = $out.rsp\n rspfile_content = {command}\n')
else:
text = f'rule probe\n command = {command}\n'
(self.folder / 'build.ninja').write_text(bindings + text + f'build {target}: probe\n', encoding='utf-8')
env = dict(os.environ, BUILD_QUOTE_TEST='expanded', MSYS2_ARG_CONV_EXCL='*')
run = subprocess.run([NINJA, '-f', 'build.ninja', target], cwd=self.folder, env=env,
capture_output=True, text=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
@unittest.skipUnless(SHELL, 'no POSIX shell on PATH')
def test_posix_arguments_survive_ninja_and_the_shell(self):
values = ('ordinary/path', 'path with spaces', 'path/$BUILD_QUOTE_TEST/include',
'path with spaces/$BUILD_QUOTE_TEST/include', "path/O'Reilly/include",
'path/(parentheses)/include', 'path/double"quote/include',
'path/$(printf expanded)/include')
for index, value in enumerate(values):
with self.subTest(value=value), patch.object(build, 'WIN', False):
target = f'posix-{index}.json'
command = ' '.join(build.cmd_arg(arg) for arg in
(Path(sys.executable).as_posix(), self.probe.as_posix(), target, value))
self.ninja(target, command, posix=True)
self.assertEqual(json.loads((self.folder / target).read_text()), [value])
@unittest.skipUnless(os.name == 'nt', 'native Windows command parsing')
def test_windows_paths_still_survive_native_ninja_commands(self):
values = ['ordinary/path', 'path with spaces', 'path/$BUILD_QUOTE_TEST/include', "path/O'Reilly/include"]
with patch.object(build, 'WIN', True):
command = ' '.join(build.cmd_arg(arg) for arg in
(Path(sys.executable).as_posix(), self.probe.as_posix(), 'windows.json', *values))
self.ninja('windows.json', command)
self.assertEqual(json.loads((self.folder / 'windows.json').read_text()), values)
@unittest.skipUnless(SHELL and (os.environ.get('CC') or shutil.which('clang')), 'needs a POSIX shell and clang')
def test_compiler_finds_headers_in_a_path_with_shell_metacharacters(self):
include = self.folder / "O'Reilly $BUILD_QUOTE_TEST (headers)"
include.mkdir()
(include / 'synthetic.h').write_text('#define SYNTHETIC_VALUE 42\n')
source = self.folder / 'probe.c'
source.write_text('#include <synthetic.h>\nint main(void) { return SYNTHETIC_VALUE != 42; }\n')
compiler = os.environ.get('CC') or shutil.which('clang')
target = 'probe.exe' if os.name == 'nt' else 'probe'
with patch.object(build, 'WIN', False):
command = f'{build.cmd_arg(Path(compiler).as_posix())} -I {build.cmd_path(include)} '
command += f'{build.cmd_path(source)} -o {build.cmd_arg(target)}'
self.ninja(target, command, posix=True)
run = subprocess.run([str(self.folder / target)], timeout=10)
self.assertEqual(run.returncode, 0)
@unittest.skipUnless(SHELL and (os.environ.get('CC') or shutil.which('clang')), 'needs a POSIX shell and clang')
def test_linker_writes_the_map_in_the_literal_build_directory(self):
self.link_map(posix=True)
@unittest.skipUnless(os.name == 'nt' and (os.environ.get('CC') or shutil.which('clang')), 'native Windows linker')
def test_windows_linker_keeps_the_map_path_as_one_argument(self):
self.link_map(posix=False)
def link_map(self, posix):
output = self.folder / "O'Reilly $BUILD_QUOTE_TEST (output), comma"
output.mkdir()
source = self.folder / 'link.c'
source.write_text('int main(void) { return 0; }\n')
compiler = os.environ.get('CC') or shutil.which('clang')
target = 'link.exe' if os.name == 'nt' else 'link'
with patch.object(build, 'WIN', not posix), patch.object(build, 'vma_include', return_value=self.folder), \
patch.object(build, 'runtime_sources', return_value=[]):
# Use production Ninja bindings, but link only our own tiny program, without runtime or game inputs.
ninja, _, _ = build.ninja_file(self.folder, output, {}, 1)
bindings = '\n'.join(line for line in ninja.splitlines()
if line.startswith(('builddir = ', 'ldflags = '))) + '\n'
command = (f'{build.cmd_arg(Path(compiler).as_posix())} {build.cmd_path(source)} '
f'$ldflags -o {build.cmd_arg(target)}')
self.ninja(target, command, posix=posix, bindings=bindings)
self.assertTrue((output / 'totk.map').is_file(), 'the linker must write the map at the requested path')
self.assertIn('main', (output / 'totk.map').read_text())
if __name__ == '__main__':
unittest.main(verbosity=2)
+72
View File
@@ -0,0 +1,72 @@
"""tools/check_isa.py finds instructions above x86-64-v2 in objects and in linked images.
python tests/check_isa_test.py
The disassembly below is llvm-objdump -d --no-show-raw-insn output for one AVX2 function, once from an object (short
indented addresses) and once from a linked .exe (9+ hex digits at the start of the line). Standard library only.
"""
import subprocess
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import check_isa # noqa: E402
OBJECT = '''
avx.o:\tfile format coff-x86-64
Disassembly of section .text:
0000000000000000 <sum8>:
0: \tvmovdqu\t(%rcx), %ymm0
4: \tvpaddd\t%ymm0, %ymm1, %ymm0
8: \tvzeroupper
b: \tretq
'''
LINKED = '''
avx.exe:\tfile format coff-x86-64
Disassembly of section .text:
00000001400014b0 <sum8>:
1400014b0: \tvmovdqu\t(%rcx), %ymm0
1400014b4: \tvpshufd\t$0x55, %ymm0, %ymm1 # ymm1 = ymm0[1,1,1,1,5,5,5,5]
1400014b9: \tvpaddd\t%ymm0, %ymm1, %ymm0
1400014bd: \tvzeroupper
1400014c0: \tretq
00000001400014d0 <main>:
1400014d0: \tsubq\t$0x28, %rsp
1400014d4: \tpopcntl\t%eax, %eax
1400014d8: \taddq\t$0x28, %rsp
1400014dc: \tretq
'''
def scan(text):
done = subprocess.CompletedProcess([], 0, text, '')
with mock.patch.object(check_isa.subprocess, 'run', return_value=done):
return check_isa.scan_one(Path('x'), 'llvm-objdump')
class ScanTest(unittest.TestCase):
def test_an_object_is_scanned(self):
hits = scan(OBJECT)
self.assertEqual(set(hits), {('avx.o', 'sum8')})
self.assertEqual(hits[('avx.o', 'sum8')]['vpaddd'], 1)
def test_a_linked_image_is_scanned(self):
hits = scan(LINKED)
self.assertEqual(set(hits), {('avx.exe', 'sum8')}) # main's popcnt is x86-64-v2
self.assertEqual(sum(hits[('avx.exe', 'sum8')].values()), 4)
def test_function_headers_and_blank_lines_are_not_instructions(self):
self.assertEqual(scan('\nDisassembly of section .text:\n\n00000001400014b0 <vfoo>:\n'), {})
if __name__ == '__main__':
unittest.main()
+37
View File
@@ -0,0 +1,37 @@
"""tools/build_game.py compile_budget: the compile jobs fit the memory that is free, not only the RAM.
python tests/compile_budget_test.py
"""
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
from build_game import GiB, JOB_MEM, MEM_BUDGET, compile_budget # noqa: E402
def jobs(budget, cpus=16):
return max(1, min(cpus, budget // JOB_MEM)) # as build_game.main
class CompileBudgetTest(unittest.TestCase):
def test_free_memory_limits_a_pc_whose_ram_other_programs_hold(self):
self.assertEqual(jobs(compile_budget(8 * GiB, None)), 8) # the RAM alone: 6.4 GiB, 8 jobs
self.assertEqual(jobs(compile_budget(8 * GiB, 3 * GiB)), 3) # 3 GiB free: 2.4 GiB, 3 jobs
self.assertEqual(compile_budget(8 * GiB, 3 * GiB), int(3 * GiB * 0.8))
def test_ram_still_limits_when_more_is_reported_free(self):
self.assertEqual(compile_budget(4 * GiB, 64 * GiB), int(4 * GiB * 0.8))
def test_unknown_free_memory_keeps_the_old_budget(self):
self.assertEqual(compile_budget(4 * GiB, None), int(4 * GiB * 0.8))
self.assertEqual(compile_budget(128 * GiB, None), MEM_BUDGET)
def test_no_free_memory_still_runs_one_job(self):
self.assertEqual(compile_budget(4 * GiB, 0), 0)
self.assertEqual(compile_budget(4 * GiB, -1), 0)
self.assertEqual(jobs(compile_budget(4 * GiB, 0)), 1)
if __name__ == '__main__':
unittest.main()
+333 -15
View File
@@ -10,10 +10,12 @@ Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py
import hashlib
import json
import struct
import subprocess
import sys
import tempfile
import unittest
from types import SimpleNamespace
from unittest import mock
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
@@ -129,6 +131,11 @@ def b(src, dst, link=False):
return (0x94000000 if link else 0x14000000) | ((dst - src) >> 2) & 0x3FFFFFF
def quad(v):
"""The two words of a .quad v."""
return [v & 0xFFFFFFFF, v >> 32]
def record(original=0x94000010, trampoline_first=None, stub=None, writes=None, **extra):
"""A record of one inline hook at main+SITE_OFF whose original is `original` (default bl main+SITE_OFF+0x40)."""
site, stub_at, tramp = MAIN + SITE_OFF, PLUGIN + STUB_OFF, PLUGIN + TRAMP_OFF
@@ -176,6 +183,12 @@ class Check(unittest.TestCase):
self.assertEqual(hooks[0]['callback'], f'plugin0+{CB_OFF:#x}')
self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}')
def test_good_with_fp_impl(self): # Magic of the Kingdom: the impl that saves d0..d15 as well
self.assertIn('exl_inline_hook_with_fp_impl', xp.HOOK_IMPLS)
hooks, reasons = xp.check_record(record(), {PLUGIN + IMPL_OFF: 'exl_inline_hook_with_fp_impl'})
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['impl'], 'exl_inline_hook_with_fp_impl')
def test_good_plain_original(self):
self.assertEqual(self.reasons(record(original=0xAA0003F3)), []) # mov x19, x0, copied as it is
@@ -196,18 +209,22 @@ class Check(unittest.TestCase):
self.assertEqual(hooks[0]['kind'], 'replace')
self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}')
def test_replace_inside_function(self):
def test_branch_inside_function(self): # a far hook: the plugin's code comes back through an entry
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + THUNK_OFF),
'fn_start': False}]
self.refused(record(writes=w), 'from inside a main function')
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['kind'], 'branch')
def test_call_into_function_middle(self):
def test_call_into_function_middle(self): # the target becomes a seed of the plugin's lift
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + 0xf08, True)}]
self.refused(record(writes=w), 'neither an inline-hook stub nor a function start')
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual((hooks[0]['kind'], hooks[0]['target']), ('call', 'plugin0+0xf08'))
def test_bl_to_stub(self): # an inline stub is entered by b; a bl there would skip the saved x30
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + STUB_OFF, True)}]
self.refused(record(writes=w), 'neither an inline-hook stub nor a function start')
self.refused(record(writes=w), 'into an inline-hook stub')
def test_refused_run(self):
self.refused(record(refused='svc 0x40 at plugin0+0x76a0'), 'the run was refused')
@@ -221,13 +238,43 @@ class Check(unittest.TestCase):
def test_import(self):
self.refused(record(imports={'_ZN2nn2fs8MountRomEPKcPvm': 1}), 'the import _ZN2nn2fs8MountRom')
def test_write_main_data(self):
def test_import_the_game_imports_is_allowed(self):
rec = record(imports={'_ZN2nn3hid13GetNpadStatesEPNS0_16NpadFullKeyStateEiRKj': 1})
self.assertTrue(xp.check_record(rec, IMPLS)[1])
self.assertEqual(xp.check_record(rec, IMPLS, frozenset(rec['imports']))[1], [])
def test_game_imports_leave_out_the_loader_and_the_boot_hooks(self):
names = ['_ZN2nn2ro10LoadModuleEPNS0_6ModuleEPKvPvmi', '__nnmusl_init_dso', 'glslcCompile',
'_ZN2nn2os32SetMemoryAllocatorForThreadLocalEPFPvmmEPFvS1_mE']
self.assertEqual([n for n in names if not xp.GAME_IMPORTS_LEFT_OUT.search(n)], [])
kept = ['abort', '_ZN2nn2os12CreateThreadEPNS0_10ThreadTypeEPFvPvES3_S3_mi', '_ZN2nn2fs6CommitEPKc']
self.assertEqual([n for n in kept if xp.GAME_IMPORTS_LEFT_OUT.search(n)], [])
def test_game_imports_of_a_missing_exefs_are_none(self):
with tempfile.TemporaryDirectory() as d:
self.assertEqual(xp.game_imports(Path(d)), frozenset())
self.assertEqual(xp.game_imports(None), frozenset())
def test_write_main_data(self): # kept as written, compared at every start
w = [{'module': 'main', 'offset': 0x180008, 'old': 0, 'new': 1}]
self.refused(record(writes=w), "outside main's .text: main+0x180008")
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['kind'], 'data')
self.assertNotIn('target', hooks[0])
def test_pointer_swap(self): # a table entry of main's .data now points at a plugin function
w = [{'module': 'main', 'offset': 0x180010, 'old': 0x00001000, 'new': (PLUGIN + THUNK_OFF) & 0xFFFFFFFF}]
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['target'], f'plugin0+{THUNK_OFF:#x}')
def test_write_main_rodata(self): # the lift read .rodata as constants
w = [{'module': 'main', 'offset': 0x120000, 'old': 0, 'new': 1}]
self.refused(record(writes=w), "a write into main's .rodata: main+0x120000")
def test_write_other_module(self):
w = [{'module': 'sdk', 'offset': 0x100, 'old': 0, 'new': 1}]
self.refused(record(writes=w), "outside main's .text: sdk+0x100")
self.refused(record(writes=w), 'a write outside main: sdk+0x100')
def test_not_a_branch(self):
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': 0xD503201F}]
@@ -237,10 +284,12 @@ class Check(unittest.TestCase):
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, MAIN + 0x8000)}]
self.refused(record(writes=w), "does not reach into a plugin's .text")
def test_stub_shape(self):
def test_stub_shape(self): # not exlaunch's stub: plugin code the site branches to, a far hook
stub_at = PLUGIN + STUB_OFF
words = [0xD503201F, b(stub_at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30, b(stub_at + 12, PLUGIN + TRAMP_OFF)]
self.refused(record(stub=words), 'neither an inline-hook stub nor a function start')
hooks, reasons = xp.check_record(record(stub=words), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['kind'], 'branch')
def test_stub_impl(self):
stub_at = PLUGIN + STUB_OFF
@@ -269,7 +318,96 @@ class Check(unittest.TestCase):
self.refused(rec, 'no b to the site + 4')
def test_indirect_original(self):
self.refused(record(original=0xD65F03C0), 'is a br, blr or ret')
self.refused(record(original=0xD65F03C0), 'is a br or ret')
self.refused(record(original=0xD61F0100), 'is a br or ret')
def test_blr_original(self): # Zonai Fieldworks hooks blr x8 sites: the call returns, the site goes on
self.assertEqual(self.reasons(record(original=0xD63F0100)), [])
def test_veneer_entries(self): # Zonai Fieldworks: site -> veneer -> slot -> trampoline -> b site + 4
site, ven, slot, tramp = MAIN + SITE_OFF, PLUGIN + 0x5000, PLUGIN + 0xd000, PLUGIN + 0x5100
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0xD5033BBF, 'new': b(site, ven), 'fn_start': False}]
rec = record(writes=w)
img = bytearray(rec['images']['plugin0'])
imm = ((slot & ~0xFFF) - (ven & ~0xFFF)) >> 12
adrp = 0x90000011 | (imm & 3) << 29 | (imm >> 2 & 0x7FFFF) << 5
struct.pack_into('<3I', img, 0x5000, adrp, 0xF9400231 | ((slot & 0xFFF) // 8) << 10, 0xD61F0220)
struct.pack_into('<Q', img, 0xd000, tramp)
struct.pack_into('<2I', img, 0x5100, 0xD5033BBF, b(tramp + 4, site + 4))
rec['images']['plugin0'] = bytes(img)
hooks, reasons = xp.check_record(rec, IMPLS)
self.assertEqual(reasons, [])
back, ahead = xp.entries(rec, hooks, 'plugin0')
self.assertEqual(back, [SITE_OFF + 4])
self.assertEqual(ahead, [0x5100])
# exlaunch's long forms (tools/exefs_plugins.py relocation_end, returns_to): the trampoline at plugin0+off
def long_form(self, original, off, words):
rec = record(original=original)
img = bytearray(rec['images']['plugin0'])
struct.pack_into('<I', img, STUB_OFF + 12, b(PLUGIN + STUB_OFF + 12, PLUGIN + off))
struct.pack_into(f'<{len(words)}I', img, off, *words)
rec['images']['plugin0'] = bytes(img)
return rec
def test_trampoline_tbnz_long(self): # Challenge: tbnz w0, #0 out of the plugin's reach
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
words = [0x37000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17, *quad(site + 0x14), b(t + 24, site + 4)]
hooks, reasons = xp.check_record(self.long_form(0x370000A0, TRAMP_OFF, words), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['relocated'], '0x37000040 +5 words')
def test_trampoline_backward_unsigned(self): # Challenge: b.eq back 0x2ec; exlaunch's .quad lacks the sign
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
form = [0x54000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17]
for target in (site + 0x1FFD14, site - 0x2EC):
words = [*form, *quad(target), b(t + 24, site + 4)]
self.assertEqual(self.reasons(self.long_form(0x54FFE8A0, TRAMP_OFF, words)), [], hex(target))
self.refused(self.long_form(0x54FFE8A0, TRAMP_OFF, [*form, *quad(site + 0x1FFD18), b(t + 24, site + 4)]),
'not the original')
def test_trampoline_long_nop(self): # the .quad 8-byte aligned by one nop before the form
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF + 4
form = [0x37000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17, *quad(site + 0x14)]
self.assertEqual(self.reasons(self.long_form(0x370000A0, TRAMP_OFF + 4,
[xp.NOP, *form, b(t + 28, site + 4)])), [])
self.refused(self.long_form(0x370000A0, TRAMP_OFF + 4, [*form, b(t + 24, site + 4)]), 'not the original')
def test_trampoline_long_wrong_target(self):
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
words = [0x37000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17, *quad(site + 0x18), b(t + 24, site + 4)]
self.refused(self.long_form(0x370000A0, TRAMP_OFF, words), 'not the original')
def test_trampoline_bl_long(self): # ldr x17, #12; adr x30, #16; br x17; .quad, behind a nop here
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
words = [xp.NOP, xp.LDR_X17_12, xp.ADR_X30_16, xp.BR_X17, *quad(site + 0x40), b(t + 24, site + 4)]
self.assertEqual(self.reasons(self.long_form(0x94000010, TRAMP_OFF, words)), [])
def test_trampoline_adrp_long(self): # adrp x8: ldr x8, #8; b #12; .quad <page>
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
words = [0x58000048, 0x14000003, *quad(site & ~0xFFF), b(t + 16, site + 4)]
self.assertEqual(self.reasons(self.long_form(0x90000008, TRAMP_OFF, words)), [])
def test_trampoline_ldr_literal_long(self): # ldr x1, <literal>: ldr x1, #8; b over the 8 bytes; the bytes
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
words = [0x58000041, 0x14000003, 0x11223344, 0x55667788, b(t + 16, site + 4)]
self.assertEqual(self.reasons(self.long_form(0x58000801, TRAMP_OFF, words)), [])
def test_trampoline_absolute_return(self): # back to the site + 4 by ldr x17, #8; br x17; .quad, nop-aligned
site = MAIN + SITE_OFF
words = [0xAA0003F3, xp.NOP, xp.LDR_X17_8, xp.BR_X17, *quad(site + 4)]
self.assertEqual(self.reasons(self.long_form(0xAA0003F3, TRAMP_OFF, words)), [])
words[-2:] = quad(site + 8)
self.refused(self.long_form(0xAA0003F3, TRAMP_OFF, words), 'no b to the site + 4')
def test_replace_hook_adrp_orig(self): # a function starting with adrp: its Orig trampoline is the long form
site, t, adrp = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF, 0x90000008
w = [{'module': 'main', 'offset': SITE_OFF, 'old': adrp, 'new': b(site, PLUGIN + THUNK_OFF), 'fn_start': True}]
rec = self.long_form(adrp, TRAMP_OFF, [0x58000048, 0x14000003, *quad(site & ~0xFFF), b(t + 16, site + 4)])
rec['writes'] = w
hooks, reasons = xp.check_record(rec, IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}')
class Diff(unittest.TestCase):
@@ -304,12 +442,12 @@ class Reach(unittest.TestCase):
# root: bl +0x40; ret. callee at 0x40: svc 0x40; ret
img = bytearray(code([b(self.BASE, self.BASE + 0x40, True), RET_W]))
struct.pack_into('<II', img, 0x40, SVC_40, RET_W)
svcs, imports, indirect, outside = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {})
svcs, imports, indirect, outside, _ = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {})
self.assertEqual(svcs, {0x40})
def test_imports_through_plt(self):
img = code([b(self.BASE, self.BASE + 0x80, True), RET_W])
svcs, imports, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'})
svcs, imports, _, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'})
self.assertEqual((svcs, imports), (set(), {'malloc': 1}))
def test_stub_returns_at_its_trampoline_branch(self):
@@ -335,6 +473,36 @@ class Reach(unittest.TestCase):
reasons, _ = xp.reach_check(rec, hooks, IMPLS)
self.assertTrue(any('svc 0x40' in r for r in reasons), reasons)
def test_check_allows_the_game_imports_in_callbacks(self):
# callback: bl <PLT stub of a hid import>; ret
rec = record()
img = bytearray(rec['images']['plugin0'])
plt_at = PLUGIN + 0x7000
struct.pack_into('<II', img, CB_OFF, b(PLUGIN + CB_OFF, plt_at, True), RET_W)
struct.pack_into('<I', img, IMPL_OFF, RET_W)
rec['images']['plugin0'] = bytes(img)
hid = '_ZN2nn3hid13GetNpadStatesEPNS0_16NpadFullKeyStateEiRKj'
hooks, _ = xp.check_record(rec, IMPLS)
with tempfile.NamedTemporaryFile(delete=False) as f:
rec['modules'][2]['file'] = f.name
try:
with mock.patch.object(xp, 'Nso'), mock.patch.object(xp, 'plt_imports', return_value={plt_at: hid}):
refused, _ = xp.reach_check(rec, hooks, IMPLS)
allowed, _ = xp.reach_check(rec, hooks, IMPLS, frozenset({hid}))
finally:
Path(f.name).unlink()
self.assertEqual(refused, [f'the code its hooks reach calls the import {hid}'])
self.assertEqual(allowed, [])
def test_check_allows_break(self): # an abort or a failed assert ends the game, as on the Switch
rec = record()
img = bytearray(rec['images']['plugin0'])
struct.pack_into('<II', img, CB_OFF, 0xD40004C1, RET_W) # svc 0x26
struct.pack_into('<I', img, IMPL_OFF, RET_W)
rec['images']['plugin0'] = bytes(img)
hooks, _ = xp.check_record(rec, IMPLS)
self.assertEqual(xp.reach_check(rec, hooks, IMPLS)[0], [])
def test_check_allows_output_debug_string(self):
rec = record()
img = bytearray(rec['images']['plugin0'])
@@ -355,6 +523,47 @@ class Lines(unittest.TestCase):
rec['modules'][2]['image'] = 'plugin0.img'
return xp.plugin_lines(rec, xp.hooks_of(hooks, 'plugin0'), 'mod_x', d, 'plugin0')
def test_image_path_roundtrips_through_the_patch_table(self):
rec = record()
mods = [(m['name'], m['base'], m['size']) for m in rec['modules']]
with tempfile.TemporaryDirectory() as d:
for folder in ('plain', 'with spaces', 'with#hash', 'caf\u00e9 #1'):
with self.subTest(folder=folder):
dest = Path(d) / folder
dest.mkdir()
image = dest / 'plugin0.img'
image.write_bytes(rec['images']['plugin0'])
rec['modules'][2]['image'] = image.name
lines = xp.plugin_lines(rec, [], 'mod_x', dest, 'plugin0')
patch = dest / 'patches.txt'
patch.write_text('set mod_x TOTK_MODPATCH_X 0 ordered\n' + '\n'.join(lines), encoding='utf-8')
actual = patches.load(patch, mods).plugins['plugin0']['image']
self.assertEqual(actual, image.resolve().as_posix())
self.assertEqual(Path(actual).read_bytes(), rec['images']['plugin0'])
def test_quoted_image_and_legacy_unquoted_paths(self):
mods = [('main', MAIN, 0x200000), ('plugin0', PLUGIN, 0x14000)]
with tempfile.TemporaryDirectory() as d:
patch = Path(d) / 'patches.txt'
for image, field in (('C:/folder #1/plugin.img', '"C:/folder #1/plugin.img" # comment'),
('C:/plain/plugin.img', 'C:/plain/plugin.img # comment'),
(r'C:\with space\plugin.img', json.dumps(r'C:\with space\plugin.img')),
(r'C:\plain\plugin.img', r'C:\plain\plugin.img')):
with self.subTest(field=field):
patch.write_text(f'set x ENV 0\nplugin x plugin0 {"0" * 64} {field}\n')
self.assertEqual(patches.load(patch, mods).plugins['plugin0']['image'], image)
def test_malformed_quoted_image_names_the_patch_line(self):
mods = [('main', MAIN, 0x200000), ('plugin0', PLUGIN, 0x14000)]
with tempfile.TemporaryDirectory() as d:
patch = Path(d) / 'patches.txt'
for field in ('"unfinished', '""', '"image.img" extra', '"image.img" "#not a comment"'):
with self.subTest(field=field):
patch.write_text(f'set x ENV 0\nplugin x plugin0 {"0" * 64} {field}\n')
with self.assertRaises(patches.PatchError) as error:
patches.load(patch, mods)
self.assertIn(f'{patch}:2:', str(error.exception))
def test_inline(self):
out = self.lines(record(original=0xAA0003F3))
self.assertIn(f'site mod_x main {SITE_OFF:x} aa0003f3 @call:plugin0+{STUB_OFF:x} aa0003f3', out)
@@ -511,13 +720,34 @@ class Generator(unittest.TestCase):
n = Nso(str(self.plugin_file))
self.sha = hashlib.sha256(bytes(img[n.text[0]:n.text[0] + n.text[1]])).hexdigest()
def table(self, site_line, extra=()):
def table(self, site_line, extra=(), image=None):
image = image or self.d / 'plugin0.img'
text = '\n'.join(['set mod_x TOTK_MODPATCH_X 0 ordered',
f'plugin mod_x plugin0 {self.sha} {(self.d / "plugin0.img").as_posix()}',
f'plugin mod_x plugin0 {self.sha} {json.dumps(image.as_posix())}',
f'expect mod_x main {FN:x} aa0003f3 14000000', site_line, *extra]) + '\n'
(self.d / 'p.txt').write_text(text)
return patches.load(self.d / 'p.txt', self.mods)
def test_generator_cli_reads_image_in_a_folder_with_spaces_and_hash(self):
# The direct-emitter fixture needs a discoverable caller for a full CLI lift.
main = self.d / 'exefs' / 'main'
raw = bytearray(main.read_bytes())
struct.pack_into('<II', raw, 0x108, b(8, FN, True), RET_W)
main.write_bytes(raw)
image = self.d / 'record files #1' / 'plugin0.img'
image.parent.mkdir()
image.write_bytes((self.d / 'plugin0.img').read_bytes())
self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
['stub plugin0 4000', 'seed plugin0 4100 4200'], image=image)
out = self.d / 'generated'
run = subprocess.run([sys.executable, str(ROOT / 'recomp/gen.py'), '--exefs', str(self.d / 'exefs'),
'--out', str(out), '--modules', 'main', '--plugins', str(self.plugin_file),
'--patches', str(self.d / 'p.txt'), '--jobs', '1'],
capture_output=True, text=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
self.assertEqual(layout.read(out), self.mods)
self.assertTrue(list((out / 'plugin0').glob('*.c')))
def emit(self, table, name, entry, end, origs=()):
mod = gen.open_module(name, self.d / ('exefs/main' if name == 'main' else 'subsdk9'), self.bases[name], table,
plugin=name != 'main')
@@ -540,6 +770,55 @@ class Generator(unittest.TestCase):
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u)', h)
self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h)
# exlaunch's hook impl saves no NZCV: flags pass from the site to the callback and back (recomp/flags.py)
def code(self, main_words, plugin_words=None):
"""Main's hooked function and the plugin image's words replaced; the plugin hash follows."""
(self.d / 'exefs' / 'main').write_bytes(code_nso(main_words))
img = bytearray((self.d / 'plugin0.img').read_bytes())
for off, w in (plugin_words or {}).items():
struct.pack_into('<I', img, off, w)
(self.d / 'plugin0.img').write_bytes(bytes(img))
n = Nso(str(self.plugin_file))
self.sha = hashlib.sha256(bytes(img[n.text[0]:n.text[0] + n.text[1]])).hexdigest()
def test_hook_site_hands_the_flags_to_the_callback_and_back(self):
# cmp x0, x1; b.eq +8 (hooked); mov x0, x19; ret
self.code({FN: 0xEB01001F, FN + 4: 0x54000040, FN + 8: 0xAA1303E0, FN + 12: RET_W})
t = self.table(f'site mod_x main {FN + 4:x} 54000040 @call:plugin0+4000 54000040', ['stub plugin0 4000'])
m = self.bases['main'] + FN
c = self.emit(t, 'main', m, m + 16)
stub = self.bases['plugin0'] + 0x4000
on = c[c.index('if (rt_patch_on[0])'):]
on, off = on[:on.index('} else {')], on[on.index('} else {'):]
call = on.index(f'f_{stub:x}(c);')
self.assertIn('c->nzcv = fnz_', on[:call]) # the callback sees the cmp's flags
self.assertIn('F.nz = c->nzcv;', on[call:]) # the b.eq reads what the callback left
self.assertIn('fc_nz(&F, CC_EQ)', on[call:])
self.assertIn('fc_nz(&F, CC_EQ)', off[:off.index('}', 8)]) # off: the cmp's flags, packed into F.nz
self.assertIn('F.nz = fnz_sub64(&F);', c)
def test_plugin_return_leaves_its_flags(self):
pb = self.bases['plugin0']
# the callback: cmp w1, #5; ret
self.code({FN: 0xAA0003F3, FN + 4: 0xAA1303E0, FN + 8: RET_W}, {0x4200: 0x7100143F, 0x4204: RET_W})
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
['stub plugin0 4000', 'seed plugin0 4100 4200'])
c = self.emit(t, 'plugin0', pb + 0x4200, pb + 0x4208)
self.assertIn('c->nzcv = fnz_sub32(&F); return;', c)
def test_plugin_call_takes_the_callee_flags(self):
pb = self.bases['plugin0']
# bl 0x4200; b.eq +8; ret; ret
self.code({FN: 0xAA0003F3, FN + 4: 0xAA1303E0, FN + 8: RET_W},
{0x4100: b(pb + 0x4100, pb + 0x4200, True), 0x4104: 0x54000040, 0x4108: RET_W, 0x410c: RET_W})
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
['stub plugin0 4000', 'seed plugin0 4100 4200'])
c = self.emit(t, 'plugin0', pb + 0x4100, pb + 0x4110)
body = c[c.index(f'void f_{pb + 0x4100:x}(Cpu *c) {{'):]
self.assertLess(body.index(f'c->pc = {pb + 0x4200:#x}ull; rt_dispatch(c);'), body.index('F.nz = c->nzcv;'))
self.assertIn('fc_nz(&F, CC_EQ)', body)
self.assertEqual(body.count('c->nzcv = fnz_nz(&F); return;'), 2) # both returns leave the flags
def test_stub_returns_instead_of_branching_to_its_trampoline(self):
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000'])
stub = self.bases['plugin0'] + 0x4000
@@ -564,6 +843,45 @@ class Generator(unittest.TestCase):
self.assertIn(f'void fo_{m:x}(Cpu *c);', tab)
self.assertIn(f'fo_{m:x}', tab[tab.index('_fn_ptrs'):])
def test_branch_hook_on_a_flag_write_leaves_with_the_flags_before_it(self):
# cmp x0, x1; cmp x2, x3 (b to the plugin's trampoline, which runs the cmp); b.eq +8; ret; ret
pb = self.bases['plugin0']
m = self.bases['main'] + FN
self.code({FN: 0xEB01001F, FN + 4: 0xEB03005F, FN + 8: 0x54000040, FN + 12: RET_W, FN + 16: RET_W})
t = self.table(f'site mod_x main {FN + 4:x} eb03005f {b(m + 4, pb + 0x4200):08x}', ['seed plugin0 4200'])
c = self.emit(t, 'main', m, m + 20)
on = c[c.index('if (rt_patch_on[0])'):]
on = on[:on.index('} else {')]
self.assertIn('c->nzcv = fnz_sub64(&F);', on) # the first cmp's flags go to the trampoline
self.assertIn(f'{pb + 0x4200:#x}', on)
def test_inline_hook_on_a_register_call(self):
# blr x8 (inline-hooked); ret
self.code({FN: 0xD63F0100, FN + 4: RET_W})
t = self.table(f'site mod_x main {FN:x} d63f0100 @call:plugin0+4000 d63f0100', ['stub plugin0 4000'])
m = self.bases['main'] + FN
c = self.emit(t, 'main', m, m + 8)
stub = self.bases['plugin0'] + 0x4000
on = c[c.index('if (rt_patch_on[0])'):]
on = on[:on.index('} else {')]
self.assertLess(on.index(f'f_{stub:x}(c);'), on.index('rt_dispatch(c);')) # the hook, then the blr
self.assertIn(f'x30 = {m + 4:#x}ull; c->x[30] = x30; rt_dispatch(c);', on)
def test_orig_trampoline_counts_as_a_seed(self):
# a veneer slot names a replace hook's trampoline: dispatch serves it with the function's unpatched copy
main = self.d / 'exefs' / 'main'
raw = bytearray(main.read_bytes())
struct.pack_into('<II', raw, 0x108, b(8, FN, True), RET_W)
main.write_bytes(raw)
m = self.bases['main'] + FN
self.table(f'site mod_x main {FN:x} aa0003f3 {b(m, self.bases["plugin0"] + 0x4200):08x}',
[f'orig mod_x plugin0 2000 main {FN:x}', 'seed plugin0 4200 2000'])
run = subprocess.run([sys.executable, str(ROOT / 'recomp/gen.py'), '--exefs', str(self.d / 'exefs'),
'--out', str(self.d / 'generated'), '--modules', 'main,plugin0', '--plugins',
str(self.plugin_file), '--patches', str(self.d / 'p.txt'), '--jobs', '1'],
capture_output=True, text=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
def test_image_must_match_its_hash(self):
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000'])
t.plugins['plugin0']['sha256'] = '0' * 64
+86
View File
@@ -0,0 +1,86 @@
"""tools/extract.py --skip-base-romfs: the 17 GB base RomFS is not extracted, and nothing else stops being checked.
python tests/extract_skip_base_romfs_test.py
The base game's ExeFS still decides that the file is TotK 1.0.0, and the update merge still verifies all six IVFC
levels of what it takes from that file, so the flag trades a check that runs before the merge for one that runs during
it, and saves the 17 GB image no tool in the repository reads.
"""
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import extract # noqa: E402
EXPECTED = {'version': 0, 'display_version': '1.0.0',
'exefs_sha256': {**{name: '0' * 64 for name in extract.EXEFS_CODE}, 'main.npdm': '0' * 64},
'romfs': {'sha256': '1' * 64, 'size': 17_069_139_640}}
class SkipBaseRomfsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.out = Path(self.tmp.name) / 'v0'
(self.out / 'exefs').mkdir(parents=True)
for name in extract.EXEFS_CODE: # an ExeFS that matches EXPECTED, so no extraction is needed
(self.out / 'exefs' / name).write_bytes(b'')
self.patch = mock.patch.object(extract, 'sha256', lambda path: '0' * 64)
self.patch.start()
self.addCleanup(self.patch.stop)
self.addCleanup(self.tmp.cleanup)
def run_base(self, *, skip_romfs, romfs_present=False):
"""extract_base with the two RomFS steps recorded, and the log it printed."""
if romfs_present:
(self.out / 'romfs').mkdir()
(self.out / 'romfs' / 'index.json').write_text(json.dumps(
{'romfs_sha256': '1' * 64, 'romfs_size': 17_069_139_640, 'files': []}))
(self.out / 'romfs' / 'romfs.bin').write_bytes(b'')
calls = []
with mock.patch.object(extract, 'extract_base_romfs', lambda *a, **k: calls.append('extract')), \
mock.patch.object(extract, 'check_romfs', lambda *a, **k: calls.append('check')), \
mock.patch.object(extract, 'say', lambda message: calls.append(message)):
extract.extract_base(Path('base.xci'), Path('prod.keys'), self.out, Path('logs'), EXPECTED,
skip_romfs=skip_romfs)
return calls
def test_skipped_romfs_is_neither_extracted_nor_checked(self):
calls = self.run_base(skip_romfs=True)
self.assertNotIn('extract', calls)
self.assertNotIn('check', calls)
self.assertIn(' RomFS skipped (--skip-base-romfs)', calls)
def test_the_exefs_check_still_runs_when_the_romfs_is_skipped(self):
"""The flag drops the RomFS only: the ExeFS is what identifies the base game."""
calls = self.run_base(skip_romfs=True)
self.assertIn(' ExeFS 1.0.0: main, sdk, subsdk0, rtld match', calls)
def test_without_the_flag_the_romfs_is_extracted_and_checked(self):
calls = self.run_base(skip_romfs=False)
self.assertIn('extract', calls)
self.assertIn('check', calls)
self.assertNotIn(' RomFS skipped (--skip-base-romfs)', calls)
def test_without_the_flag_a_verified_romfs_is_reused(self):
calls = self.run_base(skip_romfs=False, romfs_present=True)
self.assertNotIn('extract', calls) # already there and verified: nothing to extract
self.assertIn('check', calls) # and still checked
def test_a_base_game_that_is_not_totk_1_0_0_is_refused_even_when_skipping(self):
"""The negative control: skipping the RomFS must not turn the base game check into a no-op."""
(self.out / 'exefs' / 'main').write_bytes(b'')
with mock.patch.object(extract, 'sha256', lambda path: 'f' * 64), \
mock.patch.object(extract, 'extract_exefs', lambda *a, **k: None), \
mock.patch.object(extract, 'say', lambda message: None):
with self.assertRaises(ValueError) as raised:
extract.extract_base(Path('base.xci'), Path('prod.keys'), self.out, Path('logs'), EXPECTED,
skip_romfs=True)
self.assertIn('Base game is not TotK 1.0.0', str(raised.exception))
if __name__ == '__main__':
unittest.main()
+119 -2
View File
@@ -41,8 +41,8 @@ from installer.runner import Context # noqa: E402
from installer.steps import Fonts, all_steps # noqa: E402
from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, # noqa: E402
UI_LANGUAGES, Catalog, Form, Model, Process, amount, default_game_language,
describe_event, parse_line, ui_language_for_langid, ui_language_for_locale,
windows_ui_language)
describe_event, fsr_default, parse_line, ui_language_for_langid,
ui_language_for_locale, windows_ui_language)
INSTALLED = ROOT / 'build' / 'install-test'
FIXTURE = ROOT / 'build' / 'inst-gui' / 'e2e-install'
@@ -182,6 +182,22 @@ class RunStatesTest(unittest.TestCase):
self.assertEqual(m.result, 'ok')
class FsrDefaultTest(unittest.TestCase):
"""Download AMD FSR is ticked at start with an AMD adapter only: not with other GPUs, nor when no adapter could be
listed."""
def test_amd(self):
self.assertTrue(fsr_default(['AMD Radeon RX 9060 XT']))
self.assertTrue(fsr_default(['Intel(R) UHD Graphics', 'AMD Radeon(TM) Graphics']))
def test_other_gpus(self):
self.assertFalse(fsr_default(['NVIDIA GeForce RTX 4080 SUPER']))
self.assertFalse(fsr_default(['Intel(R) Arc(TM) A770 Graphics', 'Microsoft Basic Render Driver']))
def test_unknown(self):
self.assertFalse(fsr_default([]))
class FormTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -247,6 +263,17 @@ class FormTest(unittest.TestCase):
(out / statefile.NAME).write_text('{nope', encoding='utf-8')
self.assertFalse(Form(dest=str(out)).update_mode())
def test_malformed_state_does_not_crash_form_validation(self):
out = self._mkdir(self.dir / 'out')
for fields in ({'format': '1'}, {'format': None}, {'inputs': [1]}, {'steps': {'compile': 'done'}},
{'lang': {}}):
with self.subTest(fields=fields):
(out / statefile.NAME).write_text(json.dumps(statefile.empty('r0') | fields), encoding='utf-8')
form = Form(dest=str(out))
self.assertIsNone(form.installed_state())
self.assertFalse(form.update_mode())
self.assertEqual(form.problems(), ['ui.need_base', 'ui.need_update', 'ui.need_keys', 'ui.need_lang'])
@staticmethod
def _mkdir(path):
path.mkdir(parents=True, exist_ok=True)
@@ -539,6 +566,96 @@ class RecentTest(unittest.TestCase):
self.assertEqual(gui.load_recent(), {'dest': 'x'})
@unittest.skipIf(gui is None, 'no tkinter')
class SmallScreenTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
env = unittest.mock.patch.dict(os.environ, {recent.ENV: str(Path(self.tmp.name) / 'recent.json')})
env.start()
self.addCleanup(env.stop)
gui.fix_tcl_paths()
self.root = gui.tk.Tk()
self.addCleanup(self.root.destroy)
self.root.tk.call('tk', 'scaling', 2.0)
for name, value in (('winfo_screenheight', 700), ('winfo_screenwidth', 1200)):
mock = unittest.mock.patch.object(self.root, name, return_value=value)
mock.start()
self.addCleanup(mock.stop)
self.app = gui.App(self.root, 'en', layouts.dev_layout(ROOT))
self.root.update()
def assert_start_visible(self):
self.assertLessEqual(self.root.winfo_height(), 700)
bottom = self.app.start_button.winfo_rooty() + self.app.start_button.winfo_height()
self.assertLessEqual(bottom, self.root.winfo_rooty() + self.root.winfo_height())
def test_form_fits_a_small_screen_with_large_fonts(self):
self.assert_start_visible()
self.app.toggle_details()
self.root.update()
self.assert_start_visible()
def test_expanded_details_are_reachable_without_moving_start(self):
self.app.toggle_details()
self.root.update()
self.assert_start_visible()
start_y = self.app.start_button.winfo_rooty()
canvas = self.app.scroll_areas['form'].canvas
canvas.yview_moveto(1)
self.root.update()
bottom = self.app.details.winfo_rooty() + self.app.details.winfo_height()
self.assertLessEqual(bottom, canvas.winfo_rooty() + canvas.winfo_height() + 1)
self.assertEqual(self.app.start_button.winfo_rooty(), start_y)
view = canvas.yview()
self.app.fit() # progress polling must not reset the user's scroll position
self.root.update()
self.assertEqual(canvas.yview(), view)
self.app.lang_box.focus_force()
self.root.update()
self.assertGreaterEqual(self.app.lang_box.winfo_rooty(), canvas.winfo_rooty())
self.assertLessEqual(self.app.lang_box.winfo_rooty() + self.app.lang_box.winfo_height(),
canvas.winfo_rooty() + canvas.winfo_height())
def test_mouse_wheel_and_linux_buttons_scroll_the_content(self):
self.app.toggle_details()
self.root.update()
canvas = self.app.scroll_areas['form'].canvas
for event, params in (('<MouseWheel>', {'delta': -120}), ('<Button-5>', {})):
with self.subTest(event=event):
canvas.yview_moveto(0)
if event == '<Button-5>' and not sys.platform.startswith('linux'):
self.app.scroll_areas['form'].wheel(SimpleNamespace(widget=canvas, num=5, delta=0))
else:
canvas.event_generate(event, **params)
self.root.update()
self.assertGreater(canvas.yview()[0], 0)
self.assert_start_visible()
def test_content_that_fits_needs_no_scrollbar(self):
with unittest.mock.patch.object(self.root, 'winfo_screenheight', return_value=2000):
self.app.fit(shrink=True)
self.root.update()
area = self.app.scroll_areas['form']
self.assertFalse(area.scrollbar.winfo_manager())
self.assertEqual(area.canvas.yview(), (0.0, 1.0))
def test_progress_and_finish_actions_stay_visible_with_long_content(self):
self.app.phase_label.configure(text='Long progress detail\n' * 40)
self.app.show('run')
self.root.update()
self.assertLessEqual(self.root.winfo_height(), 700)
self.assertLessEqual(self.app.cancel_button.winfo_rooty() + self.app.cancel_button.winfo_height(),
self.root.winfo_rooty() + self.root.winfo_height())
self.app.finish_text.configure(text='Long finish detail\n' * 40)
self.app.show('finish')
self.root.update()
close = next(w for w, _, id, _ in self.app.bound if id == 'ui.close')
self.assertLessEqual(self.root.winfo_height(), 700)
self.assertLessEqual(close.winfo_rooty() + close.winfo_height(),
self.root.winfo_rooty() + self.root.winfo_height())
class FakeVar:
def __init__(self, value=''):
self.value = value
+442 -1
View File
@@ -6,7 +6,9 @@ Run: python tests/installer_test.py
import http.client
import io
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
@@ -199,6 +201,58 @@ class RunnerTest(unittest.TestCase):
state.load(self.bed.dest)
self.assertEqual(e.exception.id, 'state.newer_format')
def test_invalid_state_format_is_reported_as_unreadable(self):
self.bed.dest.mkdir()
path = self.bed.dest / state.NAME
for value in ('1', None, [], {}, True, 1.5, -1):
with self.subTest(value=value):
data = state.empty('r0') | {'format': value}
path.write_text(json.dumps(data))
before = path.read_bytes()
with self.assertRaises(state.StateError) as error:
state.load(self.bed.dest)
self.assertEqual(error.exception.id, 'state.unreadable')
self.assertEqual(path.read_bytes(), before)
def test_invalid_state_records_are_reported_as_unreadable(self):
self.bed.dest.mkdir()
for field in ('inputs', 'steps'):
for value in (None, [], 'bad', {'entry': None}, {'entry': 'bad'}):
with self.subTest(field=field, value=value):
path = self.bed.dest / state.NAME
path.write_text(json.dumps(state.empty('r0') | {field: value}))
with self.assertRaises(state.StateError) as error:
state.load(self.bed.dest)
self.assertEqual(error.exception.id, 'state.unreadable')
def test_invalid_state_text_fields_are_reported_as_unreadable(self):
self.bed.dest.mkdir()
for field in ('release', 'lang', 'version'):
for value in (None, [], {}, 1):
with self.subTest(field=field, value=value):
(self.bed.dest / state.NAME).write_text(json.dumps(state.empty('r0') | {field: value}))
with self.assertRaises(state.StateError) as error:
state.load(self.bed.dest)
self.assertEqual(error.exception.id, 'state.unreadable')
def test_legacy_state_without_inputs_can_be_resumed(self):
self.bed.run()
path = self.bed.dest / state.NAME
data = json.loads(path.read_text())
del data['format'], data['inputs']
path.write_text(json.dumps(data))
self.assertEqual(state.load(self.bed.dest)['inputs'], {})
result = self.bed.run()
self.assertEqual((result.result, result.ran), ('ok', ['check', 'cleanup']))
def test_newer_state_format_is_not_validated_as_the_current_schema(self):
self.bed.dest.mkdir()
data = {'format': state.FORMAT + 1, 'steps': {}, 'inputs': [], 'lang': {}}
(self.bed.dest / state.NAME).write_text(json.dumps(data))
with self.assertRaises(state.StateError) as error:
state.load(self.bed.dest)
self.assertEqual(error.exception.id, 'state.newer_format')
class ReleaseFilesTest(unittest.TestCase):
def test_release_ships_every_tool_the_steps_run(self):
@@ -544,6 +598,21 @@ class IniTest(unittest.TestCase):
self.assertEqual(out, '[display]\nvk_present = fifo\n[language]\n lang = de\nfps60 = 0\n')
self.assertEqual(ini.get_language(out), 'de')
def test_the_last_active_language_is_rewritten(self):
text = 'lang = ru\n[language]\n# lang = fr\n TOTK_LANG = ja\nfps_limit = 60\n'
out = ini.set_language(text, 'de')
self.assertEqual(out, 'lang = ru\n[language]\n# lang = fr\n lang = de\nfps_limit = 60\n')
self.assertEqual(screens.ini_value(out, 'lang'), 'de')
self.assertEqual(ini.get_language(out), 'de')
def test_language_reader_uses_runtime_order_quotes_and_empty_values(self):
for text, expected in [('lang = ru\nTOTK_LANG = "ja"\n', 'ja'),
('lang = ru\nlang = \nTOTK_LANG = ""\n', 'ru'),
('lang = \nTOTK_LANG = ""\n', None),
('lang = " "\n', ' ')]:
with self.subTest(text=text):
self.assertEqual(ini.get_language(text), expected)
def test_missing_section_is_added(self):
self.assertEqual(ini.set_language('fps60 = 0\n', 'fr'), 'fps60 = 0\n\n[language]\nlang = fr\n')
self.assertEqual(ini.set_language('[language]\nlocale = de-DE\n', 'fr'),
@@ -573,6 +642,107 @@ class IniTest(unittest.TestCase):
self.assertEqual(ini.get_language(text), 'ja')
class ExtractMergeTest(unittest.TestCase):
"""The real merge wrapper with synthetic inputs and hactool output; no game files or keys."""
LEVELS = '\n'.join(f' Level {i} (GOOD):' for i in range(6))
LOG = ('NCA:\nFixed-Key Signature (FAIL): omitted\nNPDM Signature (GOOD): omitted\n'
'NPDM:\n ACID:\n Signature Key (GOOD): 0\n Signature (FAIL): omitted\n'
+ LEVELS + '\nDone!\n')
IMAGE = b'synthetic merged image'
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.output, self.logs = self.root / 'romfs', self.root / 'logs'
self.logs.mkdir()
self.base, self.update, self.keys = (self.root / name for name in ('base.nsp', 'update.nsp', 'prod.keys'))
self.log, self.code, self.base_log = self.LOG, 0, self.LEVELS
self.phases = []
header = bytearray(0xc00)
header[0x404] = 4 # one BKTR section
inputs = [(source, {'size': 1, 'nca_offset': 0}, bytes(header)) for source in (self.base, self.update)]
self.enterContext(mock.patch.object(steps.extract, 'program_ncas', return_value=({}, inputs)))
self.enterContext(mock.patch.object(steps.extract, 'copy_range'))
self.enterContext(mock.patch.object(steps.extract, 'hactool_prod_keys'))
self.enterContext(mock.patch.object(steps.extract.shutil, 'disk_usage',
return_value=SimpleNamespace(free=100 * steps.GiB)))
self.enterContext(mock.patch.object(steps.extract, 'run_hactool', side_effect=self.hactool))
self.index = self.enterContext(mock.patch.object(steps.extract, 'index_romfs', return_value=[]))
def hactool(self, command, environment):
if '-x' not in command:
return 0, self.base_log # the extra verification that identifies a damaged input
image = Path(next(arg.split('=', 1)[1] for arg in command if arg.startswith('--section0=')))
image.write_bytes(self.IMAGE)
return self.code, self.log
def merge(self):
steps.extract.merge_update_romfs(self.base, self.update, self.keys, self.root / 'hactool', self.output,
self.logs, phase=self.phases.append)
def test_acid_signature_warning_keeps_a_verified_merge(self):
self.merge()
image = self.output / 'romfs.bin'
self.assertEqual(image.read_bytes(), self.IMAGE)
report = json.loads((self.output / 'index.json').read_text())
self.assertEqual((report['status'], report['romfs_size'], report['romfs_sha256']),
('pass', len(self.IMAGE), steps.extract.sha256(image)))
self.assertEqual(self.phases, ['copy', 'merge', 'index'])
self.assertEqual((self.logs / f'merge_romfs-{self.root.name}.log').read_text(), self.LOG)
def test_existing_npdm_signature_warning_is_still_allowed(self):
self.log = self.LOG.replace('NPDM Signature (GOOD)', 'NPDM Signature (FAIL)')
self.merge()
self.assertTrue((self.output / 'index.json').is_file())
def test_data_hash_failures_still_identify_the_damaged_update(self):
for label in [*(f'Level {i}' for i in range(6)), 'Superblock Hash', 'Hash Table']:
with self.subTest(label=label):
self.log = self.LOG + f' {label} (FAIL): omitted\n'
with self.assertRaises(steps.extract.DamagedFile) as error:
self.merge()
self.assertEqual(error.exception.path, self.update)
self.assertIn('diagnose', self.phases)
self.index.assert_not_called()
self.assertFalse(self.output.exists())
def test_base_hash_failure_is_still_identified(self):
self.log = self.LOG.replace('Level 5 (GOOD)', 'Level 5 (FAIL)')
self.base_log = self.LEVELS.replace('Level 5 (GOOD)', 'Level 5 (FAIL)')
with self.assertRaises(steps.extract.DamagedFile) as error:
self.merge()
self.assertEqual(error.exception.path, self.base)
self.index.assert_not_called()
def test_every_ivfc_level_is_still_required(self):
for level in range(6):
with self.subTest(level=level):
self.log = self.LOG.replace(f' Level {level} (GOOD):\n', '')
with self.assertRaisesRegex(ValueError, 'did not verify all six IVFC levels'):
self.merge()
self.index.assert_not_called()
self.assertFalse(self.output.exists())
def test_other_hactool_errors_are_still_rejected(self):
for message in ('Signature Key (FAIL): 0', 'Fixed-Key Index (FAIL): 0', 'Other Signature (FAIL): omitted',
'Section (INVALID)', 'Failed to read section', 'Error: cannot save section'):
with self.subTest(message=message):
self.log = self.LOG + message + '\n'
with self.assertRaisesRegex(ValueError, 'hactool merge failed'):
self.merge()
self.index.assert_not_called()
self.assertFalse(self.output.exists())
def test_nonzero_exit_is_still_rejected(self):
self.code = 1
with self.assertRaisesRegex(ValueError, 'hactool merge failed'):
self.merge()
self.index.assert_not_called()
self.assertFalse(self.output.exists())
class CleanupTest(unittest.TestCase):
"""The real Cleanup step on a finished install whose romfs/ is intact, emptied or gone (#107)."""
@@ -610,6 +780,16 @@ class CleanupTest(unittest.TestCase):
def test_intact_romfs_passes(self):
self.assertEqual(self.run_cleanup(), 'ok')
def test_selected_language_overrides_the_last_duplicate(self):
path = self.dest / 'totk.ini'
path.write_text('lang = ru\n[language]\nTOTK_LANG = ja\n[display]\nfps_limit = 60\n')
self.assertEqual(self.run_cleanup(), 'ok')
text = path.read_text()
self.assertEqual(screens.ini_value(text, 'lang'), self.ctx.lang)
self.assertEqual(ini.get_language(text), self.ctx.state['lang'])
self.assertIn('lang = ru\n', text)
self.assertIn('fps_limit = 60\n', text)
def test_keeps_build_and_writes_rebuild_command(self):
for name in ('gen', 'build', 'check'):
(self.ctx.temp / name).mkdir()
@@ -906,6 +1086,35 @@ class ShapesTest(unittest.TestCase):
(['2560x1080', '3440x1440', '1280x800', '1920x1280'], 'pc'))
self.assertEqual(screens.wanted(self.dest / 'none', [(2560, 1440)]), ([], None))
def test_layout_settings_keep_the_last_nonempty_value(self):
for empty in ('', ' ', '""'):
with self.subTest(empty=empty):
text = f'prompts = xbox\nTOTK_PROMPTS = "pc"\nprompts = {empty}\n'
self.assertEqual(screens.ini_value(text, 'prompts'), 'pc')
self.assertEqual(screens.prompts_style(text), 'pc')
self.assertEqual(screens.ini_value('prompts = pc\n# prompts = xbox\n; prompts = xbox', 'prompts'), 'pc')
# cfg.c trims the whole value and removes matching quotes; it does not strip inline comments.
self.assertEqual(screens.ini_value('prompts = pc # comment', 'prompts'), 'pc # comment')
def test_quoted_pad_layout_selects_the_matching_prompts(self):
self.assertEqual(screens.prompts_style('TOTK_PAD_LAYOUT = "nintendo"\nprompts = "PS"'), 'playstation')
self.assertEqual(screens.prompts_style('pad_layout = "xbox_prompts"'), 'xbox')
def test_shapes_generate_the_layouts_selected_by_quoted_or_repeated_settings(self):
screens.displays = lambda: []
(self.dest / 'romfs-patches-pc').mkdir()
(self.dest / 'romfs-patches-pc' / 'manifest.tsv').write_text('#\n')
for trailing in ('', '\noutput_res =\nTOTK_PROMPTS = ""\nhud_width = \n'):
with self.subTest(trailing=trailing):
(self.dest / 'totk.ini').write_text('[display]\nTOTK_OUTPUT_RES = "3840x1080"\n'
'hud_width = "16:9"\n[input]\nprompts = "pc"\n' + trailing)
ctx = SimpleNamespace(**vars(self.ctx))
record = steps.Shapes().run(ctx)
self.assertEqual(record['folders'], ['romfs-patches-3840x1080', 'romfs-patches-pc-3840x1080',
'romfs-patches-3840x1080-hud16x9',
'romfs-patches-pc-3840x1080-hud16x9'])
self.assertTrue(steps.Shapes().current(ctx, record))
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')
@@ -1088,7 +1297,7 @@ class FontsTest(unittest.TestCase):
def test_all_steps_order(self):
self.assertEqual([s.id for s in steps.all_steps()],
['check', 'kit', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss',
'cleanup'])
'fsr', 'cleanup'])
def test_extracts_into_the_install_folder(self):
self.fake_tool()
@@ -1256,5 +1465,237 @@ class DlssTest(unittest.TestCase):
self.assertEqual(self.warnings(), [])
class HostProbeTest(unittest.TestCase):
"""Check.probe_host: the host check's crashes and refusals (issues #875, #1345)."""
GOOD = '{"x86_64_v2": true, "x86_64_v3": true, "loader": true, "instance": 0, "devices": [' \
'{"name": "Intel(R) UHD Graphics", "api": [1, 3, 215], "type": 1}]}\n'
CRASHED_IN_VULKAN = '{"x86_64_v2": true, "x86_64_v3": true, "loader": true, '
ACCESS_VIOLATION = 0xC0000005
LAYERS = [('VK_LAYER_VALVE_steam_overlay_64', Path('C:/Steam/SteamOverlayVulkanLayer64.json')),
('VK_LAYER_BAD_overlay', Path('C:/Bad/BadOverlay64.json'))]
def setUp(self):
self.ctx = SimpleNamespace(reporter=Reporter(out=io.StringIO()))
self.calls = []
def tearDown(self):
self.ctx.reporter.close()
def probe(self, *results, layers=()):
"""Runs probe_host with subprocess.run answering each call with the next of results (an exception is raised,
a callable gets the run's VK_LOADER_LAYERS_DISABLE)."""
answers = iter(results)
def run(command, **kwargs):
env = kwargs.get('env')
self.calls.append(env)
r = next(answers)
if callable(r):
r = r((env or {}).get('VK_LOADER_LAYERS_DISABLE'))
if isinstance(r, BaseException):
raise r
return subprocess.CompletedProcess(command, r[0], r[1], '')
with mock.patch.object(steps.subprocess, 'run', run), \
mock.patch.object(steps, 'implicit_vulkan_layers', lambda: list(layers)):
return steps.Check().probe_host(self.ctx, Path('hostcheck.exe'))
def bad_layer(self, disabled):
"""The probe on a PC whose VK_LAYER_BAD_overlay is broken, with the layers in disabled turned off."""
if disabled in ('~implicit~', 'VK_LAYER_BAD_overlay'):
return 0, self.GOOD
return self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN
def only_all_off(self, disabled):
"""The probe on a PC whose broken layer is not in the list (a driver's, under its adapter key)."""
if disabled == '~implicit~':
return 0, self.GOOD
return self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN
def events(self, kind):
return [e for e in map(json.loads, self.ctx.reporter.out.getvalue().splitlines()) if e['type'] == kind]
def test_a_good_probe_runs_once(self):
host = self.probe((0, self.GOOD))
self.assertEqual(host['devices'][0]['api'], [1, 3, 215])
self.assertEqual(self.calls, [None])
self.assertEqual(self.events('warning'), [])
def test_a_crashing_layer_is_named_and_stops_the_install(self):
# totk.exe --prepare-shaders and the game load the same layer, so going on would fail after lift and compile
with self.assertRaises(steps.InstallError) as e:
self.probe(*[self.bad_layer] * 4, layers=self.LAYERS)
self.assertEqual(e.exception.id, 'check.vulkan_layer_crash')
self.assertEqual(e.exception.params['disable'], 'VK_LAYER_BAD_overlay')
self.assertIn('VK_LAYER_BAD_overlay (', e.exception.params['layers'])
self.assertNotIn('steam', e.exception.params['layers'])
self.assertEqual([c and c['VK_LOADER_LAYERS_DISABLE'] for c in self.calls],
[None, '~implicit~', 'VK_LAYER_VALVE_steam_overlay_64', 'VK_LAYER_BAD_overlay'])
if os.name == 'nt':
self.assertEqual(e.exception.params['code'], '0xC0000005')
def test_a_crashing_layer_that_cannot_be_singled_out_lists_the_installed_ones(self):
with self.assertRaises(steps.InstallError) as e:
self.probe(*[self.only_all_off] * 4, layers=self.LAYERS)
self.assertEqual(e.exception.id, 'check.vulkan_layers_crash')
self.assertIn('VK_LAYER_VALVE_steam_overlay_64', e.exception.params['layers'])
self.assertIn('VK_LAYER_BAD_overlay', e.exception.params['layers'])
with self.assertRaises(steps.InstallError) as e:
self.probe(self.only_all_off, self.only_all_off)
self.assertEqual((e.exception.id, e.exception.params['layers']), ('check.vulkan_layers_crash', '?'))
def test_a_driver_that_crashes_without_the_layers_too_stops_the_install(self):
with self.assertRaises(steps.InstallError) as e:
self.probe((self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN), (self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN),
layers=self.LAYERS)
self.assertEqual(e.exception.id, 'check.vulkan_crash')
self.assertEqual(len(self.calls), 2)
def test_a_crash_before_vulkan_is_not_run_again(self):
with self.assertRaises(steps.InstallError) as e:
self.probe((self.ACCESS_VIOLATION, ''))
self.assertEqual(e.exception.id, 'check.host_probe_failed')
self.assertEqual(len(self.calls), 1)
if os.name == 'nt':
self.assertEqual(e.exception.params['code'], '0xC0000005')
@unittest.skipUnless(os.name == 'nt', 'winerror is set on Windows only')
def test_a_probe_blocked_by_smart_app_control_names_the_policy(self):
for code in (4551, 4559, 1260, 225):
with self.subTest(code=code):
blocked = OSError(None, 'An Application Control policy has blocked this file', None, code)
with self.assertRaises(steps.InstallError) as e:
self.probe(blocked)
self.assertEqual(e.exception.id, 'check.host_blocked')
self.assertIn('Application Control', e.exception.params['detail'])
self.assertTrue(e.exception.params['path'].endswith('hostcheck.exe'))
def test_another_start_failure_is_reported_not_raised(self):
with self.assertRaises(steps.InstallError) as e:
self.probe(OSError(2, 'The system cannot find the file specified'))
self.assertEqual(e.exception.id, 'check.host_probe_failed')
self.assertIn('cannot find', e.exception.params['code'])
def test_a_failed_host_check_runs_once_per_install(self):
# key() probes first and run() reports: the crashing probe and its retries must not run twice
check, ctx = steps.Check(), SimpleNamespace()
failure = steps.InstallError('check.vulkan_crash', code='1')
with mock.patch.object(steps.Check, 'check_host', side_effect=failure) as probe:
check.key(ctx)
with self.assertRaises(steps.InstallError) as e:
check.host(ctx)
self.assertEqual(e.exception.id, 'check.vulkan_crash')
self.assertEqual(probe.call_count, 1)
def test_layer_names_come_from_the_manifests_the_loader_reads(self):
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
(folder / 'one.json').write_text(json.dumps({'file_format_version': '1.1.2', 'layer': {
'name': 'VK_LAYER_TEST_one', 'library_path': 'one.dll'}}), encoding='utf-8-sig')
(folder / 'two.json').write_text(json.dumps({'file_format_version': '1.0.1', 'layers': [
{'name': 'VK_LAYER_TEST_a'}, {'name': 'VK_LAYER_TEST_b'}]}), encoding='utf-8')
(folder / 'broken.json').write_text('{', encoding='utf-8')
with mock.patch.dict(os.environ, {'VK_ADD_IMPLICIT_LAYER_PATH': tmp}):
mine = [(n, p.name) for n, p in steps.implicit_vulkan_layers() if p.parent == folder]
self.assertEqual(mine, [('VK_LAYER_TEST_one', 'one.json'), ('VK_LAYER_TEST_a', 'two.json'),
('VK_LAYER_TEST_b', 'two.json')])
def test_messages_in_every_language(self):
need = {'check.host_blocked': ('{path}', '{detail}'), 'check.vulkan_crash': ('{code}',),
'check.vulkan_layer_crash': ('{code}', '{layers}', '{disable}', 'VK_LOADER_LAYERS_DISABLE'),
'check.vulkan_layers_crash': ('{code}', '{layers}', 'VK_LOADER_LAYERS_DISABLE', '~implicit~')}
for path in sorted((ROOT / 'installer' / 'text').glob('*.json')):
text = json.loads(path.read_text(encoding='utf-8'))
self.assertNotIn('warn.vulkan_layer_crash', text, path.name)
for key, parts in need.items():
for part in parts:
self.assertIn(part, text[key], f'{path.name} {key}')
@unittest.skipUnless(steps.os.name == 'nt', 'FSR is Windows-only')
class FsrTest(unittest.TestCase):
"""The FSR step: off without --fsr, Windows-only, keeps a player's libraries, installs both files or none."""
NAMES = ('amd_fidelityfx_loader_vk.dll', 'amd_fidelityfx_upscaler_vk.dll')
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
base = Path(self.tmp.name)
self.dest, temp, src = base / 'dest', base / 'temp', base / 'src'
for d in (self.dest, temp, src):
d.mkdir()
files = []
for i, name in enumerate(self.NAMES):
(src / name).write_bytes(bytes([65 + i]) * (1000 + i))
files.append((name, 1000 + i, steps.file_sha256(src / name)))
self.src = src
self.saved = steps.FSR_BASE, steps.FSR_FILES
steps.FSR_BASE = src.as_uri() + '/' # urllib reads file: URLs as it reads https: ones
steps.FSR_FILES = tuple(files)
amd = {'devices': [{'name': 'AMD Radeon RX 9070 XT', 'api': [1, 4, 0], 'type': 2}]}
self.ctx = SimpleNamespace(dest=self.dest, temp=temp, host=amd, reporter=Reporter(out=io.StringIO()),
options=SimpleNamespace(fsr=True))
def tearDown(self):
steps.FSR_BASE, steps.FSR_FILES = self.saved
self.ctx.reporter.close()
self.tmp.cleanup()
def warnings(self):
return [json.loads(line)['id'] for line in self.ctx.reporter.out.getvalue().splitlines()
if json.loads(line)['type'] == 'warning']
def test_off_without_the_option(self):
self.ctx.options.fsr = False
self.assertEqual(steps.Fsr().run(self.ctx), {})
self.assertFalse(any((self.dest / n).exists() for n in self.NAMES))
self.assertNotEqual(steps.Fsr().key(self.ctx), steps.Fsr().key(SimpleNamespace(options=SimpleNamespace(fsr=True))))
def test_downloads_and_checks_both_libraries(self):
rec = steps.Fsr().run(self.ctx)
self.assertEqual(rec, {'installed': steps.FSR_VERSION})
for n in self.NAMES:
self.assertEqual((self.dest / n).read_bytes(), (self.src / n).read_bytes())
self.assertFalse(list(self.ctx.temp.iterdir()))
self.assertTrue(steps.Fsr().current(self.ctx, rec))
(self.dest / self.NAMES[1]).unlink()
self.assertFalse(steps.Fsr().current(self.ctx, rec))
def test_a_wrong_file_installs_neither(self):
name, size, _ = steps.FSR_FILES[1]
steps.FSR_FILES = (steps.FSR_FILES[0], (name, size, '0' * 64))
rec = steps.Fsr().run(self.ctx)
self.assertEqual(rec, {'failed': True})
self.assertFalse(any((self.dest / n).exists() for n in self.NAMES))
self.assertFalse(list(self.ctx.temp.iterdir()))
self.assertEqual(self.warnings(), ['warn.fsr_download_failed'])
self.assertFalse(steps.Fsr().current(self.ctx, rec))
def test_keeps_the_players_libraries(self):
(self.dest / self.NAMES[1]).write_bytes(b'newer')
self.assertEqual(steps.Fsr().run(self.ctx), {'kept': True})
self.assertEqual((self.dest / self.NAMES[1]).read_bytes(), b'newer')
self.assertFalse((self.dest / self.NAMES[0]).exists())
self.assertEqual(self.warnings(), ['warn.fsr_kept'])
def test_downloads_on_an_nvidia_gpu(self):
self.ctx.host = {'devices': [{'name': 'NVIDIA GeForce GTX 1050', 'api': [1, 3, 0], 'type': 2}]}
rec = steps.Fsr().run(self.ctx)
self.assertEqual(rec, {'installed': steps.FSR_VERSION})
for name in self.NAMES:
self.assertEqual((self.dest / name).read_bytes(), (self.src / name).read_bytes())
def test_old_no_amd_skip_record_is_retried(self):
old_key = steps.fingerprint('fsr-1', steps.FSR_VERSION,
*(sha for _, _, sha in steps.FSR_FILES))
state = {'format': 1, 'release': 'old', 'inputs': {},
'steps': {'fsr': {'key': old_key, 'release': 'old', 'skipped': 'no_amd'}}}
ctx = runner.Context(SimpleNamespace(release='new'), self.dest, self.ctx.temp, self.ctx.reporter,
self.ctx.options, state=state)
ctx.steps = [steps.Fsr()]
ctx.plan()
self.assertTrue(ctx.runs['fsr'])
if __name__ == '__main__':
unittest.main()
+73 -3
View File
@@ -6,12 +6,15 @@ Builds a mods folder in a temp directory with files of its own bytes at real Rom
build/extracted/<version>/romfs/index.json unless --romfs says otherwise), runs `totk.exe --probe-fs` on it and reads the `mods:` lines of the log.
--probe-fs compares the bytes it reads through the RomFS with every overlay file, so a wrong winner fails it too.
A second folder checks the merged resource size table the start writes to the profile (runtime/romfs.c
restbl_overlay): a grown file's entry, an added file's, a shipped table's and another version's table's.
restbl_overlay): a grown file's entry, an added file's, a shipped table's and another version's table's. Then the
table kept across starts (restbl_cache = 1, runtime/romfs.c restbl_cache_key): served again when nothing changed, built
again after a changed mod file, an added or removed mod, another order, a new totk.exe, a damaged key or table.
Needs the extracted RomFS of the version.
"""
import argparse
import json
import os
import shutil
import struct
import subprocess
import sys
@@ -43,9 +46,10 @@ def put(root, mod, rel, data, part='romfs', times=64):
f.write_bytes(data * times)
def run(exe, mods, order, disabled=''):
def run(exe, mods, order, disabled='', cache='0'):
"""--probe-fs with a profile of its own beside mods (the merged resource size table is written there)."""
env = dict(os.environ, TOTK_MODS_DIR=str(mods), TOTK_MODS_ORDER=order, TOTK_MODS_DISABLED=disabled)
env = dict(os.environ, TOTK_MODS_DIR=str(mods), TOTK_MODS_ORDER=order, TOTK_MODS_DISABLED=disabled,
TOTK_RESTBL_CACHE=cache, TOTK_BACKGROUND_WINDOW='1', TOTK_ASSUME_FOCUS='1')
profile = Path(mods).parent / 'profile'
r = subprocess.run([str(exe), '--profile', str(profile), '--probe-fs'], env=env, capture_output=True, timeout=600)
log = (r.stdout + r.stderr).decode('utf-8', 'replace')
@@ -122,6 +126,72 @@ def restbl_case(exe, version, romfs, check, tmp):
check(merged[key(old_other)] == game[key(old_other)], 'another version\'s table leaves other files alone')
lower = [h for h, s in game.items() if merged.get(h, 0) < s]
check(not lower, f'no entry of the game\'s table is lowered ({len(lower)})')
restbl_cache_case(exe, mods, merged_file, grown, check)
HIT = 'the mods\' files are the ones of the last start'
BUILT = 'RomFS: resource size table: built again: '
def restbl_cache_case(exe, mods, table, grown, check):
"""restbl_cache = 1 across starts on the mods restbl_case made (order Grow|Ships|Old)."""
keyf = table.with_name(table.name + '.key')
order = 'Grow|Ships|Old'
def start(what, hit, why=None, order=order):
code, log = run(exe, mods, order, cache='1')
ok = code == 0 and (HIT in log) == hit and (why is None or BUILT + why in log)
check(ok, f'restbl_cache: {what}: ' + ('served from the last start' if hit else f'built again ({why})'), log)
start('first start', False, 'no usable key')
check(keyf.is_file() and keyf.stat().st_size == 80, 'restbl_cache: the key file is written beside the table')
good = table.read_bytes()
start('same mods', True)
check(table.read_bytes() == good, 'restbl_cache: the served table is the built one')
changed = 'the mods, the game files or the build changed'
f = mods / 'Grow' / 'romfs' / grown
data = f.read_bytes()
f.write_bytes(data[:-1] + bytes([data[-1] ^ 1])) # same size, new bytes and write time
start('a mod file rewritten', False, changed)
start('the rewritten file again', True)
f.write_bytes(data)
start('the file restored', False, changed)
put(mods, 'Extra', 'Pack/Actor/ModTest_Extra.pack.zs',
zstandard.ZstdCompressor(write_content_size=True).compress(bytes(40000)), times=1)
start('a mod added', False, changed, order=order + '|Extra')
shutil.rmtree(mods / 'Extra')
start('the mod removed', False, changed)
start('another order', False, changed, order='Ships|Grow|Old')
start('the first order again', False, changed)
check(table.read_bytes() == good, 'restbl_cache: the table built again equals the first one')
st = os.stat(exe)
try:
os.utime(exe, ns=(st.st_atime_ns, st.st_mtime_ns + 2_000_000_000)) # what a new build changes
start('a new totk.exe', False, changed)
finally:
os.utime(exe, ns=(st.st_atime_ns, st.st_mtime_ns))
start('the old totk.exe again', False, changed)
keyf.write_bytes(keyf.read_bytes()[:40])
start('a torn key file', False, 'no usable key')
keyf.write_bytes(os.urandom(80))
start('a key file of random bytes', False, 'no usable key')
start('after the damaged key', True)
t = bytearray(table.read_bytes())
t[len(t) // 2] ^= 0xff
table.write_bytes(bytes(t))
start('a damaged table', False, 'the kept table is missing or damaged')
check(table.read_bytes() == good, 'restbl_cache: the damaged table is replaced by the built one')
table.unlink()
start('a missing table', False, 'the kept table is missing or damaged')
key_before = keyf.read_bytes()
code, log = run(exe, mods, order)
check(code == 0 and HIT not in log and BUILT not in log and keyf.read_bytes() == key_before,
'restbl_cache = 0 (the default): the table is built, the key is neither read nor written', log)
def main():
+78
View File
@@ -66,6 +66,35 @@ def ncz_file(nca, body, blocks=False):
return out + b''.join(stored)
class BlocksTest(unittest.TestCase):
def read(self, data, plain=1 << 14):
header = b'NCZBLOCK' + bytes([2, 1, 0, 14]) + struct.pack('<IQI', 1, plain, len(data))
return ncz.blocks(io.BytesIO(header + data), 0, len(header) + len(data), plain)
def test_oversized_compressed_block_is_rejected_before_yielding(self):
data = zstd.compress(bytes(1 << 20)) # a small fixture, 64 times the declared output
with self.assertRaisesRegex(ValueError, 'NCZ block decompressed size'):
next(self.read(data))
def test_short_compressed_block_is_rejected_before_yielding(self):
with self.assertRaisesRegex(ValueError, 'NCZ block decompressed size'):
next(self.read(zstd.compress(bytes(100))))
def test_compressed_block_can_contain_multiple_frames(self):
plain = bytes(1 << 14)
data = zstd.compress(plain[:100]) + zstd.compress(plain[100:])
self.assertEqual(b''.join(self.read(data)), plain)
def test_compressed_final_block_uses_its_actual_plain_size(self):
plain = bytes(123)
self.assertEqual(b''.join(self.read(zstd.compress(plain), len(plain))), plain)
def test_compressed_block_must_reach_its_end_marker(self):
data = zstd.compress(bytes(1 << 14), options={zstd.CompressionParameter.checksum_flag: True})
with self.assertRaises((zstd.ZstdError, EOFError)):
next(self.read(data[:-1]))
class UnpackTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -88,6 +117,25 @@ class UnpackTest(unittest.TestCase):
def expected(self):
return pfs0([(self.name + '.nca', self.nca), ('a.tik', self.tik)])
def padded_nsz(self, indices, truncate=False):
"""Store selected blocks raw, followed by padding included in the stored length, not the NCA body."""
def pad(data):
head = ncz.HEADER + 16 + 0x40 * len(SECTIONS)
exponent = data[head + 11]
count = struct.unpack_from('<I', data, head + 12)[0]
for index in indices:
index %= count
lengths = struct.unpack_from(f'<{count}I', data, head + 24)
start = head + 24 + 4 * count + sum(lengths[:index])
plain = self.body[index << exponent:(index + 1) << exponent]
padding = bytes(max(16, (1 << exponent) - len(plain)))
stored = plain + padding
data[start:start + lengths[index]] = stored
struct.pack_into('<I', data, head + 24 + 4 * index, len(stored))
return data[:-1] if truncate else data
return self.nsz(blocks=True, damage=pad)
def test_stream_comes_back_byte_for_byte(self):
src = self.nsz()
self.assertEqual(ncz.compressed(src)[0], 'nsz')
@@ -102,6 +150,36 @@ class UnpackTest(unittest.TestCase):
ncz.unpack(self.nsz(blocks=True), self.dir / 'out.nsp')
self.assertEqual((self.dir / 'out.nsp').read_bytes(), self.expected())
def test_raw_block_padding_is_not_written_into_the_nca(self):
for indices in ((0,), (-1,), (0, -1)):
with self.subTest(indices=indices):
seen = []
ncz.unpack(self.padded_nsz(indices), self.dir / 'out.nsp', lambda d, t: seen.append((d, t)))
self.assertEqual((self.dir / 'out.nsp').read_bytes(), self.expected())
self.assertEqual(seen[-1], (len(self.expected()), len(self.expected())))
def test_a_raw_block_cannot_claim_padding_outside_its_entry(self):
with self.assertRaisesRegex(ValueError, 'Truncated NCZ block'):
ncz.unpack(self.padded_nsz((-1,), truncate=True), self.dir / 'out.nsp')
self.assertFalse((self.dir / 'out.nsp').exists())
def test_block_of_the_wrong_size_is_a_damaged_file(self):
"""The installer turns DamagedFile into check.input_damaged, which asks for a fresh copy of the file."""
def short(data):
head = ncz.HEADER + 16 + 0x40 * len(SECTIONS)
count = struct.unpack_from('<I', data, head + 12)[0]
lengths = struct.unpack_from(f'<{count}I', data, head + 24)
start = head + 24 + 4 * count + lengths[0]
frame = zstd.compress(self.body[1 << 14:(2 << 14) - 100]) # block 1 is zeros, stored compressed
data[start:start + lengths[1]] = frame
struct.pack_into('<I', data, head + 24 + 4, len(frame))
return data
with self.assertRaises(ncz.DamagedFile) as e:
ncz.unpack(self.nsz(blocks=True, damage=short), self.dir / 'out.nsp')
self.assertIn('decompressed size', e.exception.detail)
self.assertFalse((self.dir / 'out.nsp').exists())
def test_plain_nsp_is_not_compressed(self):
path = self.dir / 'plain.nsp'
path.write_bytes(self.expected())
+193 -1
View File
@@ -1,15 +1,23 @@
"""tools/pack_shader_cache.py on a fake shader cache: the pack layout gfx_shader.c reads (sorted index, bounds, data),
loose files folded in and deleted, a second run merging new loose files, a loose file winning over its packed copy,
malformed files skipped and --keep. No game files; stdlib only.
malformed files skipped, --keep, and the parallel reads: same bytes as serial, the worker choice, the read-ahead caps
and the fallback to serial reads when the parallel path fails. No game files; stdlib only.
Run: python tests/pack_shader_cache_test.py
"""
import contextlib
import hashlib
import io
import shutil
import struct
import sys
import tempfile
import threading
import unittest
from concurrent.futures import Future
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / 'tools'))
@@ -22,6 +30,25 @@ def name(seed):
return hashlib.sha256(seed.encode()).hexdigest()
class InlinePool:
"""Stands in for ThreadPoolExecutor: runs each read at submit, records the submits, and raises the error of a
thread that does not start after fail_after of them."""
def __init__(self, submitted, fail_after=None):
self.submitted, self.fail_after = submitted, fail_after
def submit(self, fn, *args):
if self.fail_after is not None and len(self.submitted) >= self.fail_after:
raise RuntimeError("can't start new thread")
self.submitted.append(args)
future = Future()
future.set_result(fn(*args))
return future
def shutdown(self, wait=True, cancel_futures=False):
pass
def read_pack(path):
"""{(kind, name hex): bytes}, checking what gfx_shader.c pack_open checks."""
b = path.read_bytes()
@@ -100,12 +127,177 @@ class PackTest(unittest.TestCase):
self.assertTrue((self.cache / f'{k}.spv').exists())
self.assertEqual(len(read_pack(self.cache / psc.PACK)), 4)
def test_parallel_pack_is_byte_identical_for_fresh_and_incremental_inputs(self):
for i in range(80):
self.shader(str(i))
serial = self.cache.parent / 'serial'
shutil.copytree(self.cache, serial)
self.assertEqual(psc.pack(self.cache, read_workers=8), psc.pack(serial, read_workers=1))
self.assertEqual((self.cache / psc.PACK).read_bytes(), (serial / psc.PACK).read_bytes())
self.shader('new')
(self.cache / f'{name("0")}.res.json').write_bytes(b'{"changed":true}')
(self.cache / f'{name("use1")}.use').write_bytes(b'invalid loose copy')
shutil.copytree(self.cache, serial, dirs_exist_ok=True)
self.assertEqual(psc.pack(self.cache, read_workers=8), psc.pack(serial, read_workers=1))
self.assertEqual((self.cache / psc.PACK).read_bytes(), (serial / psc.PACK).read_bytes())
def test_prefetch_preserves_order_and_bounds_inflight_reads(self):
keys = [(1, bytes([i])) for i in range(100)]
# The first yielded result must not require reading every file; only the bounded prefetch can start.
with mock.patch.object(psc, 'read_loose', return_value=b'data') as read:
iterator = psc.prefetched_files(keys, dict.fromkeys(keys, Path('fixture')), 3)
self.assertEqual(next(iterator), (keys[0], b'data'))
self.assertLessEqual(read.call_count, 6)
self.assertEqual([key for key, _ in iterator], keys[1:])
def test_read_workers_follow_the_cpus_and_free_memory(self):
plenty = 8 << 30
for cpus, want in ((None, 1), (1, 1), (2, 1), (3, 1), (4, 2), (6, 3), (8, 4), (12, 6), (16, 8), (64, 8)):
with self.subTest(cpus=cpus):
self.assertEqual(psc.read_workers(cpus, plenty), want)
self.assertEqual(psc.read_workers(cpus, None), want) # free memory unknown: by the CPUs alone
self.assertEqual(psc.read_workers(24, psc.LOW_FREE_RAM - 1), 1)
self.assertEqual(psc.read_workers(24, psc.LOW_FREE_RAM), 8)
self.assertEqual(psc.read_workers(24, 0), 1)
def test_pack_without_read_workers_uses_the_machine_choice(self):
self.shader('a')
with mock.patch.object(psc, 'machine_read_workers', return_value=(1, 'test')) as choice:
self.assertEqual(psc.pack(self.cache)[0], 4)
choice.assert_called_once()
with mock.patch.object(psc.hostmem, 'available_ram', side_effect=OSError('no answer')):
self.assertEqual(psc.machine_read_workers()[0], psc.read_workers(psc.os.cpu_count(), None))
def test_read_ahead_stays_under_the_byte_cap_and_a_large_file_goes_alone(self):
mib = 1 << 20
keys = [(1, bytes([i])) for i in range(40)]
sizes = {k: 10 * mib for k in keys}
sizes[keys[20]] = 100 * mib # larger than the cap on its own
loose = dict.fromkeys(keys, Path('fixture'))
submitted = []
with mock.patch.object(psc, 'ThreadPoolExecutor', lambda max_workers: InlinePool(submitted)), \
mock.patch.object(psc, 'read_loose', return_value=b'x'):
got = []
for key, _ in psc.prefetched_files(keys, loose, 8, sizes, max_bytes=32 * mib):
ahead = keys[len(got):len(submitted)] # read and not yet given out, this one included
self.assertTrue(sum(sizes[k] for k in ahead) <= 32 * mib or ahead == [key], (key, len(ahead)))
self.assertLessEqual(len(ahead), 16)
got.append(key)
self.assertEqual(got, keys)
def test_a_failing_parallel_path_falls_back_to_serial_reads(self):
for i in range(80):
self.shader(str(i))
reference = self.cache.parent / 'reference'
shutil.copytree(self.cache, reference)
psc.pack(reference, read_workers=1)
main_thread = threading.main_thread()
def no_thread_after_forty(max_workers):
return InlinePool([], fail_after=40)
def no_executor(max_workers):
raise RuntimeError("can't start new thread")
real_read = psc.read_loose
calls = [0]
def out_of_memory_in_a_reader(path):
if threading.current_thread() is not main_thread:
calls[0] += 1
if calls[0] > 30:
raise MemoryError()
return real_read(path)
failures = {
'thread start': mock.patch.object(psc, 'ThreadPoolExecutor', no_thread_after_forty),
'executor': mock.patch.object(psc, 'ThreadPoolExecutor', no_executor),
'reader MemoryError': mock.patch.object(psc, 'read_loose', out_of_memory_in_a_reader),
}
for what, failure in failures.items():
with self.subTest(failure=what):
cache = self.cache.parent / what.replace(' ', '-')
shutil.copytree(self.cache, cache)
out = io.StringIO()
with failure, contextlib.redirect_stdout(out):
n, new, skipped, _ = psc.pack(cache, read_workers=8)
self.assertIn('parallel reads failed', out.getvalue())
self.assertEqual((n, new, skipped), (320, 320, 0))
self.assertEqual((cache / psc.PACK).read_bytes(), (reference / psc.PACK).read_bytes())
self.assertEqual(sorted(p.name for p in cache.iterdir()), [psc.PACK])
def test_an_error_of_the_caller_is_not_taken_for_a_reader_failure(self):
keys = [(1, bytes([i])) for i in range(10)]
iterator = psc.prefetched_files(keys, {}, 4)
next(iterator)
with self.assertRaises(ValueError):
iterator.throw(ValueError('disk full'))
def test_a_broken_pack_is_rebuilt_from_the_loose_files(self):
self.shader('a')
(self.cache / psc.PACK).write_bytes(b'garbage')
n, _, _, _ = psc.pack(self.cache)
self.assertEqual(n, 4)
def bounded_read_pack(self, path):
"""Record real file reads; fail before a corrupt count can request a large allocation, even before the fix."""
requests = []
with path.open('rb') as f:
read = f.read
def bounded(n):
requests.append(n)
self.assertLessEqual(n, 1024, 'corrupt index count reached the allocating read')
return read(n)
with mock.patch.object(psc, 'open', return_value=f, create=True), \
mock.patch.object(f, 'read', side_effect=bounded):
result = psc.read_pack(path)
return result, requests
def test_truncated_index_is_rejected_before_reading_it(self):
path = self.cache / psc.PACK
for count in (1, 0xffffffff):
with self.subTest(count=count):
path.write_bytes(psc.MAGIC + struct.pack('<II', count, 0))
result, requests = self.bounded_read_pack(path)
self.assertEqual(result, {})
self.assertEqual(requests, [16])
def test_runtime_index_limit_is_checked_before_reading_it(self):
path = self.cache / psc.PACK
count = (1 << 24) + 1 # gfx_shader.c pack_open rejects more than 2**24 entries
path.write_bytes(psc.MAGIC + struct.pack('<II', count, 0))
with mock.patch.object(psc.os, 'fstat', return_value=SimpleNamespace(st_size=16 + 48 * count)):
result, requests = self.bounded_read_pack(path)
self.assertEqual(result, {})
self.assertEqual(requests, [16])
def test_short_read_after_the_size_check_is_still_rejected(self):
path = self.cache / psc.PACK
path.write_bytes(psc.MAGIC + struct.pack('<II', 1, 0) + bytes(24))
with mock.patch.object(psc.os, 'fstat', return_value=SimpleNamespace(st_size=64)):
result, requests = self.bounded_read_pack(path)
self.assertEqual(result, {})
self.assertEqual(requests, [16, 48])
def test_a_truncated_pack_is_rebuilt_from_the_loose_files(self):
key = self.shader('a')
(self.cache / psc.PACK).write_bytes(psc.MAGIC + struct.pack('<II', 4096, 0))
n, new, skipped, size = psc.pack(self.cache)
self.assertEqual((n, new, skipped), (4, 4, 0))
self.assertEqual(size, (self.cache / psc.PACK).stat().st_size)
self.assertEqual(read_pack(self.cache / psc.PACK)[(1, key)], b'\x03\x02\x23\x07spirva')
def test_a_valid_empty_pack_is_not_rewritten(self):
path = self.cache / psc.PACK
data = psc.MAGIC + struct.pack('<II', 0, 0)
path.write_bytes(data)
before = path.stat().st_mtime_ns
self.assertEqual(psc.pack(self.cache), (0, 0, 0, len(data)))
self.assertEqual(path.read_bytes(), data)
self.assertEqual(path.stat().st_mtime_ns, before)
if __name__ == '__main__':
unittest.main()
+61
View File
@@ -0,0 +1,61 @@
"""The performance log summary reports total frames divided by elapsed time.
python tests/perf_summary_test.py
"""
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def window(frame, fps, count=60):
# Synthetic text in runtime/perf.c perf_present's format; no game log is read.
line = (f'perf: frame {frame}: interval avg {1000 / fps:.2f} ms max 50.00 ms ({fps:.1f} fps); '
'render thread blocked: pacing 0% fence 0% drain 0% pipeline build 0% shader xlate 0% texture 0%')
return line + (f'; replay avg 1.00 ms; ab 0/{count}; world 20.0 s' if count is not None else '') + '\n'
class PerfSummaryTest(unittest.TestCase):
def summarize(self, text, lo=0, hi=1000):
with tempfile.TemporaryDirectory() as tmp:
log = Path(tmp) / 'perf.log'
log.write_text(text, encoding='utf-8')
result = subprocess.run([sys.executable, str(ROOT / 'tools' / 'perf_summary.py'),
str(log), str(lo), str(hi)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout
def test_equal_frame_windows_use_their_combined_duration(self):
# 120 frames in 0.6 + 2.4 seconds = 40 fps, not (100 + 25) / 2.
out = self.summarize(window(60, 100) + window(120, 25))
self.assertIn('mean fps 40.0, min window fps 25.0, max frame 50.0 ms', out)
def test_partial_window_uses_its_logged_frame_count(self):
# 30 frames in 0.3 seconds and 60 in 2.4 seconds = 33.3 fps.
out = self.summarize(window(60, 100, 30) + window(120, 25))
self.assertIn('mean fps 33.3,', out)
def test_older_logs_without_counts_keep_equal_window_weights(self):
out = self.summarize(window(60, 100, None) + window(120, 25, None))
self.assertIn('mean fps 40.0,', out)
def test_frame_bounds_only_include_the_selected_windows(self):
text = window(60, 100) + window(120, 50) + window(180, 25) + window(240, 200)
out = self.summarize(text, lo=60, hi=180)
self.assertIn('SUMMARY frames 60-180: mean fps 33.3, min window fps 25.0,', out)
self.assertNotIn('perf 60:', out)
self.assertNotIn('perf 240:', out)
def test_constant_rate_is_unchanged(self):
out = self.summarize(window(60, 60) + window(120, 60))
self.assertIn('mean fps 60.0, min window fps 60.0,', out)
def test_no_perf_windows_does_not_print_a_frame_summary(self):
self.assertNotIn('SUMMARY frames', self.summarize('unrelated diagnostic\n'))
if __name__ == '__main__':
unittest.main()
+43 -14
View File
@@ -35,36 +35,54 @@ GAME_NEEDS = {'exefs', 'exe', 'romfs', 'embed', 'gui'}
def interp(venv):
""".venv / .venv-py314, falling back to this interpreter when the venv is absent."""
"""The requested venv, this interpreter if absent, or its standalone base for user-site tests."""
if venv == 'system':
return Path(getattr(sys, '_base_executable', None) or sys.executable)
d = ROOT / venv
p = d / ('Scripts/python.exe' if WIN else 'bin/python')
return p if p.exists() else Path(sys.executable)
# name: (venv, needs, args, why the need is there)
# needs: None | needs joined by '+' (exefs | exe | romfs | embed | gui | cc)
# venv: .venv | .venv-py314 | system (the standalone base interpreter)
# needs: None | needs joined by '+' (exefs | exe | romfs | embed | gui | cc | ninja)
# name: the script below tests/, without .py (diff/simd is tests/diff/simd.py)
TESTS = {
# ---- no game files, no build ----
'flags_check': ('.venv', None, [], ''),
'excl_mt': ('.venv', None, [], ''),
'flags_check': ('.venv', 'cc', [], 'compiles the CPU flag helpers with clang'),
'excl_mt': ('.venv', 'cc', [], 'compiles the threaded exclusive-monitor harness with clang'),
'check_isa_test': ('.venv', None, [], ''),
'build_command_test': ('.venv', 'ninja', [], 'checks command arguments through Ninja'),
'compile_budget_test': ('.venv', None, [], ''),
'extract_skip_base_romfs_test': ('.venv-py314', None, [], ''),
'perf_summary_test': ('.venv', None, [], ''),
'pack_shader_cache_test': ('.venv', None, [], ''),
'spin_waits_test': ('.venv', None, [], ''),
'worktree_test': ('.venv', None, [], ''),
'run_game_test': ('.venv', None, [], ''),
'installer_test': ('.venv-py314', None, [], ''),
'ncz_test': ('.venv-py314', None, [], ''),
'romfs_prompts_test': ('.venv-py314', None, [], ''),
'hud_layout_test': ('.venv-py314', None, [], ''),
'release_linux_apprun_test': ('system', None, [], ''),
'exefs_patches_test': ('.venv', None, [], ''),
'exefs_plugins_test': ('.venv', None, [], ''),
'lift_cache_test': ('.venv', None, [], ''),
'ab_summary_test': ('.venv', None, [], ''),
'settings_doc_check': ('.venv', None, [], ''),
'mouse_direct_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles its checks with clang'),
'cheats_vm_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles runtime/cheats.c into a harness with clang'),
'diff/atomic': ('.venv', None, [], ''),
'diff/simd': ('.venv', None, [], ''),
'romfs_shapes_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production overlay selection helpers'),
'frame_world_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production world-clock player walk'),
'sync_ahead_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production sync-ahead wait selection'),
'patches_v110_check': ('.venv', 'cc', [], 'compiles synthetic patch contracts for comparison with Unicorn'),
'patches_v110_highfps_check': ('.venv', 'cc', [], 'compiles synthetic high-fps contracts for comparison with Unicorn'),
'diff/atomic': ('.venv', 'cc', [], 'compiles generated atomic checks for comparison with Unicorn'),
'diff/simd': ('.venv', 'cc', [], 'compiles generated SIMD checks for comparison with Unicorn'),
# ---- read the game or a build ----
'diff/lift': ('.venv', 'exefs', ['--exefs', '<exefs>'],
'diff/lift': ('.venv', 'exefs+cc', ['--exefs', '<exefs>'],
'samples instructions from the game modules; needs an unpacked exefs'),
'diff/func': ('.venv', 'exefs', ['--exefs', '<exefs>'],
'diff/func': ('.venv', 'exefs+cc', ['--exefs', '<exefs>'],
'lifts whole functions of the game modules; needs an unpacked exefs'),
'jumptables_check': ('.venv', 'exefs', ['--exefs', '<exefs>'],
'replays the modules through Unicorn; needs an unpacked exefs'),
@@ -100,10 +118,11 @@ def find_exefs():
def find_exe():
"""A built totk.exe: the plain v143 tree, else the newest variant (v143-heropath, ...)."""
if (ROOT / 'build' / 'v143' / 'totk.exe').exists():
return ROOT / 'build' / 'v143' / 'totk.exe'
builds = sorted(ROOT.glob('build/v143-*/totk.exe'),
"""A built totk[.exe]: the plain v143 tree, else the newest variant (v143-heropath, ...)."""
name = 'totk.exe' if WIN else 'totk'
if (ROOT / 'build' / 'v143' / name).exists():
return ROOT / 'build' / 'v143' / name
builds = sorted(ROOT.glob('build/v143-*/' + name),
key=lambda p: p.stat().st_mtime, reverse=True)
return builds[0] if builds else None
@@ -133,7 +152,11 @@ def find_embed():
def find_cc():
"""clang for the tests that compile C: MSYS2 UCRT64's on Windows, else the one on PATH."""
"""The compiler the differential harness uses: CC, MSYS2 UCRT64, or clang on PATH."""
cc = os.environ.get('CC')
if cc:
found = shutil.which(cc)
return Path(found) if found else None
c = MSYS_BIN / 'clang.exe'
if WIN and c.exists():
return c
@@ -153,7 +176,7 @@ def resolve(needs):
else: vals['<exefs>'] = str(p)
elif need == 'exe':
p = find_exe()
if p is None: missing.append('no built build/v143/totk.exe')
if p is None: missing.append('no built build/v143/totk' + ('.exe' if WIN else ''))
else: vals['<exe>'] = str(p)
elif need == 'romfs':
p = find_romfs()
@@ -167,6 +190,12 @@ def resolve(needs):
p = find_cc()
if p is None: missing.append('no clang (MSYS2 UCRT64 on Windows)')
else: vals['<cc>'] = str(p)
elif need == 'ninja':
p = MSYS_BIN / 'ninja.exe'
if not (WIN and p.is_file()):
found = shutil.which('ninja')
p = Path(found) if found else None
if p is None: missing.append('no Ninja on PATH or in MSYS2 UCRT64')
elif need == 'gui':
missing.append('drives a window; run it by hand on a desktop session')
else:
+130
View File
@@ -0,0 +1,130 @@
"""Run-profile copying and CLI rejection with disposable marker files; never launches a game."""
import contextlib
import io
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import run_game as run # noqa: E402
class ProfileTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.folder = Path(tmp.name)
self.profile = self.folder / 'profile'
self.profile.mkdir()
(self.profile / 'marker').write_text('original profile')
source = patch.object(run, 'PROFILE', self.profile)
source.start()
self.addCleanup(source.stop)
def test_overlapping_copies_fail_before_cleanup_or_copying(self):
for target in (self.profile, self.profile.parent, self.profile / 'nested'):
with self.subTest(target=target), \
patch.object(run.shutil, 'rmtree', side_effect=AssertionError('cleanup ran before overlap check')), \
patch.object(run.shutil, 'copytree', side_effect=AssertionError('copy ran before overlap check')):
with self.assertRaisesRegex(ValueError, 'profile'):
run.profile_copy(target, None)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
def test_separate_copy_refreshes_only_the_disposable_destination(self):
target = self.folder / 'build' / 'prof-run'
target.mkdir(parents=True)
(target / 'stale').write_text('old copy')
run.profile_copy(target, None)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
self.assertEqual((target / 'marker').read_text(), 'original profile')
self.assertFalse((target / 'stale').exists())
def test_path_like_tags_are_rejected_before_files_or_locks_are_touched(self):
for tag in ('../escape', '../../profile', '../../../profile', '..\\escape', 'nested/run', '/absolute'):
with self.subTest(tag=tag), \
patch.object(sys, 'argv', ['run_game.py', str(self.folder / 'build'), '--seconds', '1', '--tag', tag]), \
patch.object(Path, 'mkdir', side_effect=AssertionError('created a folder before checking tag')), \
patch.object(run, 'take_slot', side_effect=AssertionError('took a slot before checking tag')), \
contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as error:
run.main()
self.assertEqual(error.exception.code, 2)
def test_build_inside_the_original_profile_is_rejected_before_writes(self):
with patch.object(sys, 'argv', ['run_game.py', str(self.profile), '--seconds', '1']), \
patch.object(Path, 'mkdir', side_effect=AssertionError('created a folder before overlap check')), \
contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as error:
run.main()
self.assertEqual(error.exception.code, 2)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
def test_normal_run_cleans_its_copy_and_keeps_the_source(self):
build = self.folder / 'build'
proc = unittest.mock.Mock()
proc.wait.return_value = 0
proc.poll.return_value = 0
with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--tag', 'bench-1', '--show']), \
patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \
patch.object(run.subprocess, 'Popen', return_value=proc) as launch, \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(SystemExit) as error:
run.main()
self.assertEqual(error.exception.code, 0)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
self.assertFalse((build / 'prof-bench-1').exists())
self.assertIn('rc=0', (build / 'logs' / 'bench-1.log').read_text())
launch.assert_called_once()
proc.terminate.assert_not_called()
def test_interrupted_wait_stops_the_owned_child_before_cleanup(self):
child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
proxy = unittest.mock.Mock(wraps=child)
interrupted = False
def wait(*args, **kwargs):
nonlocal interrupted
if not interrupted:
interrupted = True
raise KeyboardInterrupt
return child.wait(*args, **kwargs)
proxy.wait.side_effect = wait
build = self.folder / 'build'
remove = run.shutil.rmtree
def remove_after_exit(path, *args, **kwargs):
if Path(path) == build / 'prof-run':
self.assertIsNotNone(child.poll(), 'profile cleanup ran while the child was alive')
return remove(path, *args, **kwargs)
try:
with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--show']), \
patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \
patch.object(run.shutil, 'rmtree', side_effect=remove_after_exit), \
patch.object(run.subprocess, 'Popen', return_value=proxy):
with self.assertRaises(KeyboardInterrupt):
run.main()
self.assertIsNotNone(child.poll(), 'interrupted run left its child alive')
self.assertFalse((build / 'prof-run').exists())
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
finally:
if child.poll() is None:
child.kill()
child.wait(timeout=5)
def test_unresponsive_child_is_killed_after_termination_timeout(self):
proc = unittest.mock.Mock()
proc.poll.return_value = None
proc.wait.side_effect = [subprocess.TimeoutExpired('owned child', 5), 0]
run.stop_process(proc)
proc.terminate.assert_called_once()
proc.kill.assert_called_once()
self.assertEqual(proc.wait.call_args_list, [unittest.mock.call(timeout=5), unittest.mock.call()])
if __name__ == '__main__':
unittest.main(verbosity=2)
+2 -1
View File
@@ -34,7 +34,8 @@ def main():
iv, rp, secs = means(side[k])
print(f'{name}: {len(side[k]):3d} windows ({secs:5.1f} s), interval {iv:6.2f} ms ({1000 / iv:5.1f} fps), replay {rp:5.2f} ms')
(ia, ra, _), (ib, rb, _) = means(side[0]), means(side[1])
print(f'B - A: interval {ib - ia:+.2f} ms ({100 * (ib - ia) / ia:+.1f}%), replay {rb - ra:+.2f} ms ({100 * (rb - ra) / ra:+.1f}%)')
replay_change = f'{100 * (rb - ra) / ra:+.1f}%' if ra else 'n/a: A is zero'
print(f'B - A: interval {ib - ia:+.2f} ms ({100 * (ib - ia) / ia:+.1f}%), replay {rb - ra:+.2f} ms ({replay_change})')
return 0
+33 -12
View File
@@ -42,8 +42,9 @@ objects Ninja just rebuilt (new mtime). A mismatch deletes the object, Ninja rec
summary line. A fork checks the hardlinked generated objects against build/<version>/obj/objects.sha256 (read-only; a
bad shared object stops the fork and asks for a main build run, which recompiles it and breaks the shared inode).
Compile jobs share a memory budget (MEM_BUDGET, default the smaller of 50 GiB and 80% of RAM) at JOB_MEM per job, so a
big machine does not run out of memory on the largest chunks. Each phase reports its wall time and the peak memory
Compile jobs share a memory budget (compile_budget: the smaller of MEM_BUDGET = 50 GiB, 80% of RAM and, on Windows,
80% of the memory free at the start) at JOB_MEM per job, so a big machine does not run out of memory on the largest
chunks, nor a small one already running a browser and the setup. Each phase reports its wall time and the peak memory
of its processes (Windows job object accounting: committed private bytes).
--ninja PATH names the Ninja to run; without MSYS2 the bin/ninja.exe of the release folder (tools/make_release.py) is used.
@@ -69,6 +70,7 @@ import hashlib
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
@@ -77,6 +79,7 @@ import urllib.request
from pathlib import Path
import check_isa
import hostmem
import romfs_index
from build_shaders import stale as stale_shaders
from check_content import GENERATED_MARKER
@@ -158,15 +161,13 @@ if WIN:
# _WIN32_WINNT: Windows 10, the port's minimum. MSYS2's headers default to it, llvm-mingw's (the release toolchain)
# to Windows 7, which hides the per-monitor DPI functions gfx_window_win.c and dpi_probe_win.c call.
RT_FLAGS.append('-D_WIN32_WINNT=0x0A00')
# -Xlinker passes the map path as one argument; -Wl, would split it at any comma in the build dir path
LINK_FLAGS = ['-fuse-ld=lld', '-Wl,--stack,16777216', '-Xlinker', '"--Map=$builddir/totk.map"'] # the map feeds tools/prof_report.py
LINK_FLAGS = ['-fuse-ld=lld', '-Wl,--stack,16777216']
LINK_LIBS = ['-lpsapi', '-lbcrypt', '-lvulkan-1', '-luser32', '-lgdi32', '-ldwmapi', '-limm32', '-lwinmm', '-lole32', '-lshell32', '-luuid', '-lSDL3', '-lopus', '-l:libvpx.a', '-l:libzstd.a', '-l:libstdc++.a', '-l:libwinpthread.a'] # Vulkan back end; libvpx static (movies); libzstd static (resolution.c)
VMA_INCLUDE = UCRT.parent / 'include' / 'vma' # vk_mem_alloc.h; MSYS2 package vulkan-memory-allocator
else:
# -no-pie: the lifted modules' function tables (hundreds of thousands of pointers) need no load-time relocation.
# $ORIGIN: a libSDL3.so.0 next to totk comes before the system's (the release's portable folder).
LINK_FLAGS = ['-fuse-ld=lld', '-no-pie', '-Wl,-z,noexecstack', "'-Wl,-rpath,$$ORIGIN'",
'"-Wl,-Map=$builddir/totk.map"']
LINK_FLAGS = ['-fuse-ld=lld', '-no-pie', '-Wl,-z,noexecstack', "'-Wl,-rpath,$$ORIGIN'"]
LINK_LIBS = ['-lvulkan', '-lSDL3', '-lopus', '-lvpx', '-lzstd', '-l:libstdc++.a', '-lm', '-lpthread', '-ldl']
VMA_INCLUDE = Path('/usr/include') # vk_mem_alloc.h; Arch (AUR) vulkan-memory-allocator, Debian libvulkan-memory-allocator-dev
# Without a system vk_mem_alloc.h, the header the Windows release pins (tools/make_release.py, VMA 3.4.0) is fetched once
@@ -220,6 +221,18 @@ GiB = 1 << 30
# (295k-entry tables). 768 MiB leaves headroom for the largest file.
JOB_MEM = 768 << 20
MEM_BUDGET = 50 * GiB # total for all compile jobs
MEM_SHARE = 0.8 # of the RAM, and of the free memory, the compile jobs may take
def compile_budget(total, free):
"""Bytes the compile jobs may take together: MEM_BUDGET, MEM_SHARE of the RAM (total) and MEM_SHARE of the memory
free now (free: hostmem.available_ram, None when unknown). The total alone counted the RAM other programs hold: on
an 8 GiB PC with 3 GiB free it allowed 8 jobs of JOB_MEM (6 GiB), so the compile paged or a job ran out of memory.
recomp/gen.py sizes the lift workers from the free memory the same way."""
budget = min(MEM_BUDGET, int(total * MEM_SHARE))
if free is not None:
budget = min(budget, int(max(0, free) * MEM_SHARE))
return budget
def below_root(p):
@@ -255,10 +268,12 @@ def flag_path(p):
def cmd_arg(s):
"""s for a Ninja command line: Ninja-escaped, and quoted when it holds a space (a user or folder name), as clang and
lld split their Windows command line at unquoted spaces."""
s = s.replace('$', '$$')
return f'"{s}"' if ' ' in s else s
"""One command argument: quote for the host's command parser, then escape Ninja's dollar signs."""
if not WIN: # Ninja runs Unix commands through sh: double quotes alone still expand $ and command substitutions
s = shlex.quote(s)
elif ' ' in s:
s = f'"{s}"'
return s.replace('$', '$$')
def cmd_path(p):
@@ -491,6 +506,8 @@ def ninja_file(gen, out, mods, pool_depth, skip=(), prebuilt=(), runtime_lib=Non
ffx / 'spirv')) # FidelityFX/host headers, ffx_shader_blobs.h, ffx_shaders_vk.h
rt_inc = f'{inc} -I {cmd_path(out)} -I {vma} -I {imgui} {ffx_inc}' # romfs_config.h, vk_mem_alloc.h (+ deps headers), imgui.h
libs = [f'-L {cmd_path(DEPS / "lib")}'] + (LLVM_LINK_LIBS if WIN else LINK_LIBS) if DEPS else LINK_LIBS
# The map feeds tools/prof_report.py. Quote its literal path before Ninja expansion; -Xlinker preserves commas.
map_arg = cmd_arg('--Map=' + flag_path(out / 'totk.map'))
lines = [
'# Written by tools/build_game.py; do not edit.',
'ninja_required_version = 1.10',
@@ -498,7 +515,7 @@ def ninja_file(gen, out, mods, pool_depth, skip=(), prebuilt=(), runtime_lib=Non
cc_line(),
genflags_line(RUNTIME, gen),
f'rtflags = {" ".join(RT_FLAGS)} {rt_inc}',
f'ldflags = {" ".join(LINK_FLAGS)}',
f'ldflags = {" ".join(LINK_FLAGS)} -Xlinker {map_arg}',
f'libs = {" ".join(libs)}',
'',
'pool gen',
@@ -1179,8 +1196,12 @@ def main():
mods = {} if args.make_runtime_lib else {m: chunk_files(gen, m) for m in linked}
cpus = os.cpu_count() or 1
budget = min(MEM_BUDGET, int(total_ram() * 0.8))
free = hostmem.available_ram()
budget = compile_budget(total_ram(), free)
jobs = args.jobs or max(1, min(cpus, budget // JOB_MEM))
if not args.jobs:
print(f'build_game: {cpus} CPUs, {mib(budget)} for compile jobs'
f'{"" if free is None else f" ({mib(free)} free memory)"}', flush=True)
plugins = read_plugin_files(gen)
missing = [n for n in names if n not in hashes and n not in plugins]
if missing:
+5 -1
View File
@@ -33,6 +33,7 @@ NON_V2 = {'andn', 'bextr', 'blsi', 'blsmsk', 'blsr', 'bzhi', 'shlx', 'shrx', 'sa
'pclmulqdq', 'rdrand', 'rdseed'}
PREFIXES = {'rep', 'repe', 'repz', 'repne', 'repnz', 'lock', 'notrack', 'data16', 'cs', 'ds', 'es', 'ss', 'fs', 'gs'}
WIDE = re.compile(r'%[yz]mm\d|%k[0-7]\b')
INSN = re.compile(r'^\s*[0-9a-f]+:')
# Function -> the runtime check that keeps it off CPUs without the instructions.
DISPATCHED = {
@@ -89,7 +90,10 @@ def scan_one(path, objdump):
if m:
func = m.group(1)
continue
if not line[:1].isspace():
# An instruction line starts with its address: short and indented in an object, 9+ hex digits at the start of
# the line in a linked .exe or .dll. Testing for leading whitespace alone skipped every instruction of a linked
# image and reported it clean.
if not INSN.match(line):
continue
mn = mnemonic(line)
if mn and func not in DISPATCHED and is_non_v2(line, mn):
+333 -79
View File
@@ -34,19 +34,22 @@ the plugin's .text or .rodata) refuses the plugin: its start could not be compar
The check (check_record) accepts a record only when every rule holds; each broken rule is one reason:
- the run was not refused (an svc outside the served set, such as CreateSession of exlaunch's process-handle
fallback, ends the run with the reason);
- the init called only the svcs ALLOWED_SVCS, GetInfo with ALLOWED_INFO, and the imports ALLOWED_IMPORTS;
- the init called only the svcs ALLOWED_SVCS, GetInfo with ALLOWED_INFO, and the imports ALLOWED_IMPORTS or the
game's (--exefs: what the game's main imports, game_imports);
- every write into a game module is a word of main's .text whose original is no br, blr or ret, and it is one of:
- an inline hook (MSFix, Full Inventory Expansion): `b <stub>` into a plugin's .text, the stub in exlaunch's
shape (stur x30, [sp, #-0x10]; bl exl_inline_hook_impl or the float one; ldur x30, [sp, #-0x10];
shape (stur x30, [sp, #-0x10]; bl one of exlaunch's hook impls, HOOK_IMPLS; ldur x30, [sp, #-0x10];
b <trampoline>; .quad <callback in the plugin's .text>), the trampoline the site's original relocated (the
same word, or the same PC-relative target) and `b <site + 4>`;
same word, the same PC-relative target, or exlaunch's long form of it, relocation_end) and its jump back to
the site + 4 (returns_to);
- a call-site rewrite (Quick Weapon Durability): `bl` straight to a function start of the plugin's lift (the
record lists them), which the generator can emit as a patch site whose replacement is that branch;
- a replace hook (Full Inventory Expansion's Sort Fixer): `b` from a function start of main to a function start of
the plugin's lift; the Orig trampoline (the original relocated, b site+4) is listed when the pool holds one.
the plugin's lift; the Orig trampoline (the original relocated, back to site+4) is listed when the pool holds
one.
- the code the hooks reach (the stubs, exlaunch's hook impls, the callbacks, the replace and call targets, and what
they reach by direct branches and calls, reach()) has no svc but OutputDebugString and calls only the imports
REACH_IMPORTS. An indirect call (blr) is not followed: what it reaches cannot be known before the run.
they reach by direct branches and calls, reach()) makes only the svcs REACH_SVCS and calls only the imports
REACH_IMPORTS or the game's. An indirect call (blr) is not followed: what it reaches cannot be known before the run.
A site shared with a built-in patch set turns that set off while the mod is on (the status line names it); a site
shared with another mod goes through the run time's pick (the Mods tab order, runtime/patches.c).
"""
@@ -54,6 +57,7 @@ import argparse
import hashlib
import json
import os
import re
import struct
import subprocess
import sys
@@ -65,30 +69,63 @@ from cheats import fnv # noqa: E402
from exefs_patches import EXEFS_PLACES, builtin_sites # noqa: E402
from nso import R_AARCH64_JUMP_SLOT, Nso # noqa: E402
ALLOWED_SVCS = {0x06: 'QueryMemory', 0x1E: 'GetSystemTick', 0x27: 'OutputDebugString', 0x29: 'GetInfo',
0x74: 'MapProcessMemory', 0x75: 'UnmapProcessMemory'}
ALLOWED_INFO = {2, 3, 4, 5, 12, 13, 14, 15, 65001}
# Reviewed one by one: SNPrintf formats into the caller's buffer; GetDisplayVersion is answered by the runtime with
# the build's game version; mersenne_twister_engine<uint64_t, ...>::_M_gen_rand (Full Inventory Expansion's alias
# picker) refills the state of the engine object it is given, which lives in the plugin's .bss; memcmp and strlen only
# read; memcpy, memmove and memset write the buffers they are given; malloc and free use the game's heap (sdk's musl
# allocator), and since the init runs again at every start, a block it keeps exists at play time (Quick Weapon
# Durability's init keeps one in its .bss).
SAFE_LIBC = {'malloc', 'free', 'memcpy', 'memmove', 'memset', 'memcmp', 'strlen'}
ALLOWED_SVCS = {0x01: 'SetHeapSize', 0x06: 'QueryMemory', 0x1E: 'GetSystemTick', 0x27: 'OutputDebugString',
0x29: 'GetInfo', 0x74: 'MapProcessMemory', 0x75: 'UnmapProcessMemory'}
ALLOWED_INFO = {2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 65001} # 6, 7, 16, 17: runtime/plugin_init.c header
# Reviewed one by one: SNPrintf and snprintf format into the caller's buffer; GetDisplayVersion is answered by the
# runtime with the build's game version; mersenne_twister_engine<uint64_t, ...>::_M_gen_rand (Full Inventory
# Expansion's alias picker) refills the state of the engine object it is given, which lives in the plugin's .bss;
# memcmp and strlen only read; memcpy, memmove and memset write the buffers they are given; malloc and free use the
# game's heap (sdk's musl allocator), and since the init runs again at every start, a block it keeps exists at play
# time (Quick Weapon Durability's init keeps one in its .bss); nn::os::InitializeMutex fills the mutex object it is
# given, GetSystemTickFrequency is a constant (Zonai Fieldworks).
SAFE_LIBC = {'malloc', 'free', 'memcpy', 'memmove', 'memset', 'memcmp', 'strlen', 'snprintf'}
MT_GEN_RAND = ('_ZNSt23mersenne_twister_engineImLm64ELm312ELm156ELm31ELm13043109905998158313ELm29ELm6148914691236517205'
'ELm17ELm8202884508482404352ELm37ELm18444473444759240704ELm43ELm6364136223846793005EE11_M_gen_randEv')
SNPRINTF = '_ZN2nn4util8SNPrintfEPcmPKcz'
ALLOWED_IMPORTS = SAFE_LIBC | {SNPRINTF, '_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE', MT_GEN_RAND}
OS_MUTEX = {'_ZN2nn2os15InitializeMutexEPNS0_9MutexTypeEbi', '_ZN2nn2os9LockMutexEPNS0_9MutexTypeE',
'_ZN2nn2os12TryLockMutexEPNS0_9MutexTypeE', '_ZN2nn2os11UnlockMutexEPNS0_9MutexTypeE'}
OS_TIME = {'_ZN2nn2os22GetSystemTickFrequencyEv', '_ZN2nn2os16GetCurrentThreadEv'}
ALLOWED_IMPORTS = SAFE_LIBC | {SNPRINTF, '_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE', MT_GEN_RAND,
'_ZN2nn2os15InitializeMutexEPNS0_9MutexTypeEbi', '_ZN2nn2os22GetSystemTickFrequencyEv'}
# nn::fs functions the runtime serves on the host (runtime/fs_host.c): a plugin's files live on the mounts it opens,
# the SD card (MountSdCard, <profile>/sdcard) or the game's RomFS with the mods' files over it.
HOST_FS = {'_ZN2nn2fs11MountSdCardEPKc', '_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci',
'_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE', '_ZN2nn2fs9CloseFileENS0_10FileHandleE',
'_ZN2nn2fs8ReadFileENS0_10FileHandleElPvm', '_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm',
'_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE', '_ZN2nn2fs9FlushFileENS0_10FileHandleE',
'_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl', '_ZN2nn2fs10CreateFileEPKcl', '_ZN2nn2fs10DeleteFileEPKc',
'_ZN2nn2fs15CreateDirectoryEPKc', '_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci',
'_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandleEl',
'_ZN2nn2fs14CloseDirectoryENS0_15DirectoryHandleE', '_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc',
'_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvmRKNS0_10ReadOptionE', '_ZN2nn2fs10RenameFileEPKcS2_',
'_ZN2nn2fs26DeleteDirectoryRecursivelyEPKc', '_ZN2nn2fs6CommitEPKc', '_ZN2nn2fs7UnmountEPKc'}
LANGUAGE = {'_ZN2nn2oe18GetDesiredLanguageEv', '_ZN2nn8settings6detail15GetLanguageCodeEPNS0_12LanguageCodeE'}
# The imports the code the hooks reach may call while the game runs (reach()). Each reviewed for what it touches: the
# libc ones above (the caller's buffers and the game's heap), SNPrintf (the caller's buffer). Nothing that waits,
# talks to a service or changes memory mappings.
REACH_IMPORTS = SAFE_LIBC | {SNPRINTF}
SVC_OUTPUT_DEBUG_STRING = 0x27
HOOK_IMPLS = ('exl_inline_hook_impl', 'exl_inline_float_hook_impl')
# libc ones above (the caller's buffers and the game's heap), SNPrintf (the caller's buffer), the sdk's mutexes and
# thread and tick queries (the game's threads use the same ones), the host file functions above and the language
# (runtime/ov_system.c). Nothing that talks to a service or changes memory mappings.
REACH_IMPORTS = SAFE_LIBC | {SNPRINTF} | OS_MUTEX | OS_TIME | HOST_FS | LANGUAGE
# Besides the lists above, a plugin may call what the game's main imports (game_imports): the game runs on those paths,
# so the runtime serves them, through its overrides or the lifted sdk, on every thread. Left out are the imports the
# game calls once at boot or not at all in play, where a second call from a plugin would meet a path nothing has run:
# the module loader (nn::ro), the C runtime's start, the thread-local allocator hook and the shader compiler.
GAME_IMPORTS_LEFT_OUT = re.compile(r'_ZN2nn2ro|__nnmusl_init|SetMemoryAllocatorForThreadLocal|^glslc')
# svcs the code the hooks reach may make: OutputDebugString (the log), GetSystemTick and SleepThread, which the
# runtime serves to every game thread the same way, and Break, an abort or a failed assert, which ends the game with
# the reason in the log as it ends it on the Switch (runtime/svc.c).
REACH_SVCS = {0x0B, 0x1E, 0x26, 0x27}
# exlaunch's inline-hook entry points. Each saves the registers its context holds, calls the callback with that context
# and restores them; none saves NZCV (recomp/flags.py). exl_inline_hook_with_fp_impl (Magic of the Kingdom) saves
# d0..d15 next to x0..x29.
HOOK_IMPLS = ('exl_inline_hook_impl', 'exl_inline_float_hook_impl', 'exl_inline_hook_with_fp_impl')
STUR_X30 = 0xF81F03FE # stur x30, [sp, #-0x10]
LDUR_X30 = 0xF85F03FE # ldur x30, [sp, #-0x10]
STUB_WORDS = 6 # 4 instructions and the callback's .quad
TICK_OFFSET = 0x0123456789AB
# An init that calls into main where the lift has no function start (Zonai Fieldworks calls main+0x481918 of 1.4.3,
# the second word of a function): the runtime's fatal names the address (runtime/dispatch.c dispatch_fail).
MID_CALL = re.compile(r'no function at guest pc 0x[0-9a-f]+ \(main\+0x([0-9a-f]+)\): not a function start')
def u(v):
@@ -105,6 +142,7 @@ def ran_view(rec):
view['modules'] = [dict(m, plugin=False) if m['plugin'] and not m.get('ran', True) else m for m in rec['modules']]
names = {m['name'] for m in view['modules'] if m['plugin']}
view['images'] = {k: v for k, v in rec['images'].items() if k in names}
view['pre_images'] = {k: v for k, v in rec.get('pre_images', {}).items() if k in names}
return view
@@ -153,6 +191,91 @@ def relocated(orig, site, word, at):
return b is not None and a == b
# exlaunch's trampolines: its relocation of a hooked instruction (exlaunch source/lib/hook/nx64/hook_impl.cpp,
# __fix_instructions and the __fix_* helpers it calls, after And64InlineHook, MIT). A PC-relative original whose target
# the trampoline cannot reach in one word becomes a long form that keeps the target in a .quad; exlaunch puts one nop
# before the form when the .quad would not be 8-byte aligned. The generated code never runs a trampoline (an inline
# hook's site calls the stub and runs main's own original after it, recomp/patches.py @call; a replace hook's Orig
# reaches an unpatched copy of the function, `orig`), so these forms only tell an exlaunch hook from other code.
NOP = 0xD503201F
LDR_X17_8 = 0x58000051 # ldr x17, #8
LDR_X17_12 = 0x58000071 # ldr x17, #12
ADR_X30_16 = 0x1000009E # adr x30, #16
BR_X17 = 0xD61F0220 # br x17
def quad(word, a):
"""The .quad at absolute a of word(a) (the plugin word there, None outside its .text), else None."""
lo, hi = word(a), word(a + 4)
return None if lo is None or hi is None else lo | hi << 32
def literal_end(word, orig, at):
"""End of exlaunch's relocation of the load-literal original at `at` (__fix_loadlit), else None. A prfm is dropped
(no words); an ldr or ldrsw becomes the same load from #8 and a b over the literal's bytes, which follow it aligned
to their size by leading nops. The bytes are not compared: the record holds no image of main."""
simd, opc = orig >> 26 & 1, orig >> 30
if not simd and opc == 3:
return at
size = (4, 8, 16)[opc] if simd else (4, 8, 4)[opc]
p = at
while word(p) == NOP and p < at + 12:
p += 4
if (p + 8) % size or word(p + 4 + size) is None:
return None
if word(p) != (orig & 0xFF00001F) | 2 << 5 or word(p + 4) != 0x14000001 + size // 4:
return None
return p + 8 + size
def relocation_end(word, orig, site, at):
"""End (absolute) of exlaunch's relocation of the original `orig` at `site` when it starts at `at`, else None:
the same word or a PC-relative one re-encoded to the same target (one word), or one of the long forms:
b.cond / cbz / tbz: <the same with offset 8>; b #20; ldr x17, #8; br x17; .quad <target>
b: ldr x17, #8; br x17; .quad <target>
bl: ldr x17, #12; adr x30, #16; br x17; .quad <target>
adr / adrp: ldr <rd>, #8; b #12; .quad <its value>
ldr / ldrsw literal: literal_end
word(a) is the plugin word at absolute a, None outside its .text."""
w0 = word(at)
if w0 is None:
return None
if relocated(orig, site, w0, at):
return at + 4
rel = pc_relative(orig, site)
if rel is None:
return None
(kind, _), target = rel
if kind == 'ldr':
return literal_end(word, orig, at)
p = at + 4 if w0 == NOP else at
w = [word(p + 4 * i) for i in range(4)]
targets = {target}
if kind in ('b.cond', 'cbz', 'tbz'):
# exlaunch's __fix_cond_comp_test_branch takes the offset field without its sign: a backward target lands
# 2^21 (b.cond, cbz) or 2^16 (tbz) bytes too far. Challenge Mode's trampolines hold such .quads; the generated
# code runs main's own branch instead, to its real target.
targets.add(site + ((orig >> 5 & (0x3FFF if kind == 'tbz' else 0x7FFFF)) << 2))
form, data = pc_relative(w[0], p) == (rel[0], p + 8) and w[1:] == [0x14000005, LDR_X17_8, BR_X17], p + 16
elif kind == 'b' and orig >> 31:
form, data = w[:3] == [LDR_X17_12, ADR_X30_16, BR_X17], p + 12
elif kind == 'b':
form, data = w[:2] == [LDR_X17_8, BR_X17], p + 8
else: # adr, adrp
form, data = w[:2] == [0x58000040 | orig & 0x1F, 0x14000003], p + 8
return data + 8 if form and data % 8 == 0 and quad(word, data) in targets else None
def returns_to(word, at, back):
"""The trampoline jumps back to `back` from `at`: b <back>, or out of its range the nop-aligned
ldr x17, #8; br x17; .quad <back> (exlaunch __fix_instructions)."""
w = word(at)
if w is not None and w >> 26 == 0x05 and branch_target(w, at) == back:
return True
p = at + 4 if w == NOP else at
return p % 8 == 0 and word(p) == LDR_X17_8 and word(p + 4) == BR_X17 and quad(word, p + 8) == back
def inline_stub(img, o, p):
"""The words at image offset o of plugin p have exlaunch's inline-hook entry shape: stur x30; bl; ldur x30; b;
and the .quad after them lies inside the plugin's .text."""
@@ -162,29 +285,37 @@ def inline_stub(img, o, p):
return s[0] == STUR_X30 and s[2] == LDUR_X30 and s[1] >> 26 == 0x25 and s[3] >> 26 == 0x05
def text_words(img, p):
"""word(a): the word of plugin p's .text image img at absolute a, None outside that .text."""
base, end = p['base'], p['text_end']
return lambda a: struct.unpack_from('<I', img, a - base)[0] if base <= a <= base + end - 4 else None
def orig_trampoline(img, p, original, site):
"""Image offset of a pair in the plugin's .text that runs the site's original instruction relocated, then b site+4
(exlaunch's Orig trampoline of a replace hook), else None."""
base = p['base']
"""Image offset of code in the plugin's .text that runs the site's original instruction relocated, then jumps back
to site+4 (exlaunch's Orig trampoline of a replace hook, relocation_end and returns_to), else None."""
base, word = p['base'], text_words(img, p)
for o in range(0, p['text_end'] - 4, 4):
t1 = struct.unpack_from('<I', img, o + 4)[0]
if t1 >> 26 == 0x05 and branch_target(t1, base + o + 4) == site + 4 and \
relocated(original, site, struct.unpack_from('<I', img, o)[0], base + o):
end = relocation_end(word, original, site, base + o)
if end is not None and returns_to(word, end, site + 4):
return o
return None
# ---- records
def load_record(d):
"""record.json of a service run directory, with the images of its plugins as bytes (key 'images')."""
"""record.json of a service run directory, with the images of its plugins as bytes (key 'images') and their
images from before the init (key 'pre_images', where the run wrote one)."""
d = Path(d)
rec = json.loads((d / 'record.json').read_text(encoding='utf-8'))
rec['images'] = {}
rec['images'], rec['pre_images'] = {}, {}
for m in rec['modules']:
for k in ('base', 'size', 'text_end', 'data_off', 'init'):
m[k] = u(m[k])
if m.get('image'):
rec['images'][m['name']] = (d / m['image']).read_bytes()
if m.get('pre_image') and (d / m['pre_image']).is_file():
rec['pre_images'][m['name']] = (d / m['pre_image']).read_bytes()
for w in rec['writes']:
for k in ('offset', 'old', 'new'):
w[k] = u(w[k])
@@ -202,8 +333,17 @@ def hook_impls(rec):
return out
def check_record(rec, impls):
"""(hooks, reasons): one dict per hook site, and one line per broken rule (no lines: the record is accepted)."""
def game_imports(exefs):
"""The imports of the game's main in the ExeFS folder exefs, without GAME_IMPORTS_LEFT_OUT; empty without one."""
main = Path(exefs) / 'main' if exefs else None
if not main or not main.is_file():
return frozenset()
return frozenset(s[0] for s in Nso(main).imports() if not GAME_IMPORTS_LEFT_OUT.search(s[0]))
def check_record(rec, impls, game=frozenset()):
"""(hooks, reasons): one dict per hook site, and one line per broken rule (no lines: the record is accepted).
game: the game's imports (game_imports), which the init may call besides ALLOWED_IMPORTS."""
reasons, hooks = [], []
if rec.get('refused'):
reasons.append(f'the run was refused: {rec["refused"]}')
@@ -214,7 +354,7 @@ def check_record(rec, impls):
if int(i) not in ALLOWED_INFO:
reasons.append(f'the init asked GetInfo id {i}')
for name, calls in rec.get('imports', {}).items():
if calls and name not in ALLOWED_IMPORTS:
if calls and name not in ALLOWED_IMPORTS and name not in game:
reasons.append(f'the init called the import {name}')
mods = {m['name']: m for m in rec['modules']}
plugins = [m for m in rec['modules'] if m['plugin']]
@@ -229,8 +369,25 @@ def check_record(rec, impls):
main = mods.get('main')
for w in rec['writes']:
where = f'{w["module"]}+{w["offset"]:#x}'
if w['module'] != 'main' or not main or w['offset'] >= main['text_end'] or w['offset'] & 3:
reasons.append(f'a write outside main\'s .text: {where} {w["old"]:#010x} -> {w["new"]:#010x}')
if w['module'] != 'main' or not main or w['offset'] & 3:
reasons.append(f'a write outside main: {where} {w["old"]:#010x} -> {w["new"]:#010x}')
continue
if w['offset'] >= main['text_end']:
# main's .data and .bss: the init runs at every start before the game's constructors and leaves these
# words as it left them here (runtime/plugin_init.c check_writes keeps data pages, compared word by word
# with the expect lines). .rodata holds what the lift read as constants (the jump tables), so no write
# goes there. A word that makes a pointer into a plugin's .text (a table entry swapped for a plugin
# function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift.
if w['offset'] < main['data_off']:
reasons.append(f"a write into main's .rodata: {where} {w['old']:#010x} -> {w['new']:#010x}")
continue
hook = {'site': f'main+{w["offset"]:#x}', 'original': f'{w["old"]:#010x}', 'kind': 'data',
'new': f'{w["new"]:#010x}'}
if w['offset'] % 8 == 0:
p, _ = plugin_word(main['base'] & ~0xFFFFFFFF | w['new'])
if p is not None:
hook['target'] = f'{p["name"]}+{(main["base"] & ~0xFFFFFFFF | w["new"]) - p["base"]:#x}'
hooks.append(hook)
continue
site = main['base'] + w['offset']
stub = branch_target(w['new'], site)
@@ -238,30 +395,32 @@ def check_record(rec, impls):
if stub is None:
reasons.append(f'{where}: the new word {w["new"]:#010x} is no b or bl')
continue
if is_indirect(w['old']):
reasons.append(f'{where}: the original {w["old"]:#010x} is a br, blr or ret')
if w['old'] & 0xFFFFFC1F in (0xD61F0000, 0xD65F0000): # br, ret: the site would end its function
reasons.append(f'{where}: the original {w["old"]:#010x} is a br or ret')
p, _ = plugin_word(stub)
if p is None:
reasons.append(f"{where}: {'bl' if link else 'b'} {stub:#x} does not reach into a plugin's .text")
continue
if not (not link and inline_stub(rec['images'][p['name']], stub - p['base'], p)):
# A b or bl straight into the plugin's code (CodePatcher-style call-site rewrite): a site whose replacement
# is that branch, when the target is a function start of the plugin's lift.
# A b replaces the whole main function, so it must sit at a function start of main; exlaunch's replace
# hook keeps the function's first instruction relocated + b site+4 in its pool for the callback's Orig.
exl = inline_stub(rec['images'][p['name']], stub - p['base'], p)
if link and exl: # an inline stub is entered by b: it saves x30 itself
reasons.append(f"{where}: bl {p['name']}+{stub - p['base']:#x} into an inline-hook stub")
continue
if not exl:
# A b or bl straight into the plugin's code: a site whose replacement is that branch, its target a
# function start of the plugin's lift (a seed). A bl returns to the site + 4 inside the lifted function
# (Quick Weapon Durability's call-site rewrite). A b leaves main's function: at a function start it
# replaces it (Full Inventory Expansion's Sort Fixer; exlaunch keeps the first instruction relocated +
# b site+4 for the callback's Orig), inside one it is a far hook (Zonai Fieldworks' veneers and gated
# edits). Where the plugin's code comes back into main, entries() makes a function start of the lift.
o = stub - p['base']
hook = {'site': f'main+{w["offset"]:#x}', 'original': f'{w["old"]:#010x}',
'kind': 'call' if link else 'replace', 'target': f'{p["name"]}+{o:#x}'}
orig = orig_trampoline(rec['images'][p['name']], p, w['old'], site)
kind = 'call' if link else 'replace' if w.get('fn_start') else 'branch'
hook = {'site': f'main+{w["offset"]:#x}', 'original': f'{w["old"]:#010x}', 'kind': kind,
'target': f'{p["name"]}+{o:#x}'}
# the Orig trampoline of a replace hook (an `orig` line); a far hook's way back is an entry instead
orig = orig_trampoline(rec['images'][p['name']], p, w['old'], site) if kind == 'replace' else None
if orig is not None:
hook['trampoline'] = f'{p["name"]}+{orig:#x}'
hooks.append(hook)
if o not in {u(x) for x in p.get('functions', [])}:
reasons.append(f"{where}: {'bl' if link else 'b'} {p['name']}+{o:#x} is neither an inline-hook stub "
f"nor a function start of {p['name']}'s lift")
if not link and not w.get('fn_start'):
reasons.append(f"{where}: b {p['name']}+{o:#x} from inside a main function (only a function start can "
f"be replaced)")
continue
img, o = rec['images'][p['name']], stub - p['base']
s = struct.unpack_from('<4IQ', img, o)
@@ -276,17 +435,21 @@ def check_record(rec, impls):
reasons.append(f'{where}: the stub calls {impl:#x}, not {" or ".join(HOOK_IMPLS)}')
if not p['base'] <= cb < p['base'] + p['text_end']:
reasons.append(f'{where}: the stub\'s callback {cb:#x} is outside {p["name"]}\'s .text')
tp, t0 = plugin_word(tramp)
_, t1 = plugin_word(tramp + 4)
if tp is None or t1 is None:
tp, t0 = plugin_word(tramp) if tramp is not None else (None, None)
if tp is None:
reasons.append(f'{where}: the trampoline {tramp:#x} is outside a plugin\'s .text')
continue
hook['relocated'] = f'{t0:#010x}'
if not relocated(w['old'], site, t0, tramp):
word = text_words(rec['images'][tp['name']], tp)
end = relocation_end(word, w['old'], site, tramp)
hook['relocated'] = f'{t0:#010x}' + (f' +{(end - tramp) // 4 - 1} words' if end and end != tramp + 4 else '')
if end is None:
reasons.append(f'{where}: the trampoline {hook["trampoline"]} starts with {t0:#010x}, not the original '
f'{w["old"]:#010x} relocated')
if branch_target(t1, tramp + 4) != site + 4 or t1 >> 31:
reasons.append(f'{where}: the trampoline\'s second word {t1:#010x} is no b to the site + 4')
elif not returns_to(word, end, site + 4):
back = word(end)
reasons.append(f'{where}: the trampoline\'s word after the relocated original, '
f'{back if back is not None else 0:#010x} at {tp["name"]}+{end - tp["base"]:#x}, is no b '
f'to the site + 4')
return hooks, reasons
@@ -307,11 +470,26 @@ def plt_imports(nso, img, base, text_end):
return out
def veneer_slot(img, base, text_end, a):
"""Image offset of the pointer a far-jump veneer at a goes through (adrp x17, page; ldr x17, [x17, #off];
br x17: Zonai Fieldworks' hook pads), else None."""
o = a - base
if not 0 <= o <= text_end - 12:
return None
w0, w1, w2 = struct.unpack_from('<3I', img, o)
if w0 & 0x9F00001F != 0x90000011 or w1 & 0xFFC003FF != 0xF9400231 or w2 != 0xD61F0220:
return None
imm = sext((w0 >> 29 & 3) | (w0 >> 5 & 0x7FFFF) << 2, 21)
slot = (a & ~0xFFF) + (imm << 12) + (w1 >> 10 & 0xFFF) * 8 - base
return slot if 0 <= slot <= len(img) - 8 else None
def reach(img, base, text_end, roots, plt, stubs=()):
"""What the code from roots (absolute addresses in the plugin's .text) reaches by falling through, direct branches
and direct calls: (svc immediates, {import: calls}, indirect calls, words outside the .text it branched to). A
stub's b to its trampoline counts as its return (recomp/patches.py `stub`)."""
svcs, imports, indirect, outside = set(), {}, 0, set()
and direct calls: (svc immediates, {import: calls}, indirect calls, words outside the .text it branched to,
veneer targets). A stub's b to its trampoline counts as its return (recomp/patches.py `stub`). A veneer goes on to
the pointer its slot holds after the init (the plugin may change it later, to code its own lift discovers)."""
svcs, imports, indirect, outside, veneers = set(), {}, 0, set(), set()
seen, work = set(), list(roots)
stub_rets = {s + 12 for s in stubs}
while work:
@@ -329,6 +507,11 @@ def reach(img, base, text_end, roots, plt, stubs=()):
w = struct.unpack_from('<I', img, a - base)[0]
if a in stub_rets:
break
slot = veneer_slot(img, base, text_end, a)
if slot is not None:
a = struct.unpack_from('<Q', img, slot)[0]
veneers.add(a)
continue
if w & 0xFFE0001F == 0xD4000001: # svc #imm
svcs.add(w >> 5 & 0xFFFF)
if w & 0x7C000000 == 0x14000000: # b, bl
@@ -347,11 +530,12 @@ def reach(img, base, text_end, roots, plt, stubs=()):
elif w == 0 or w & 0xFFE0001F == 0xD4200000: # udf, brk: ends too
break
a += 4
return svcs, imports, indirect, outside
return svcs, imports, indirect, outside, veneers
def reach_check(rec, hooks, impls):
"""Reasons the code the hooks reach breaks the rules (svcs, imports), and a summary line."""
def reach_check(rec, hooks, impls, game=frozenset()):
"""Reasons the code the hooks reach breaks the rules (svcs, imports), and a summary line. game: the game's imports
(game_imports), which that code may call besides REACH_IMPORTS."""
reasons, notes = [], []
for p in (m for m in rec['modules'] if m['plugin'] and m['name'] in rec['images']):
img, base = rec['images'][p['name']], p['base']
@@ -363,12 +547,13 @@ def reach_check(rec, hooks, impls):
if h['kind'] == 'inline' and h['stub'].startswith(p['name'] + '+'):
stubs.add(base + int(h['stub'].split('+')[1], 16))
roots |= {a for a in impls if base <= a < base + p['text_end']}
roots |= init_code(rec, hooks, p['name'])
nso = Nso(p['file']) if p.get('file') and Path(p['file']).is_file() else None
plt = plt_imports(nso, img, base, p['text_end']) if nso else {}
svcs, imports, indirect, outside = reach(img, base, p['text_end'], sorted(roots), plt, stubs)
for imm in sorted(svcs - {SVC_OUTPUT_DEBUG_STRING}):
svcs, imports, indirect, outside, _ = reach(img, base, p['text_end'], sorted(roots), plt, stubs)
for imm in sorted(svcs - REACH_SVCS):
reasons.append(f'the code its hooks reach has svc {imm:#x}')
for name in sorted(set(imports) - REACH_IMPORTS):
for name in sorted(set(imports) - REACH_IMPORTS - game):
reasons.append(f'the code its hooks reach calls the import {name}')
notes.append(f'{p["name"]}: hooks reach {len(roots)} roots, imports {", ".join(sorted(imports)) or "none"}, '
f'{indirect} indirect calls not followed' + (f', {len(outside)} branches out of its .text'
@@ -387,8 +572,55 @@ def mod_of(nso_path, mods):
def hooks_of(hooks, module):
"""The hooks whose stub or target lies in the plugin module: its own, when one record holds several plugins."""
return [h for h in hooks if (h.get('stub') or h.get('target') or '').split('+')[0] == module]
"""The hooks whose stub or target lies in the plugin module: its own, when one record holds several plugins. A
data write without a target belongs to the plugin whose init ran (each record is one plugin's, TOTK_PLUGIN_ONLY)."""
return [h for h in hooks if (h.get('stub') or h.get('target') or module).split('+')[0] == module]
def init_code(rec, hooks, module):
"""Absolute starts of the code module's init wrote into its own .text where the file had zeros: exlaunch's
trampolines of its far hooks (the moved original words and a branch back). The plugin may point a veneer at any of
them at play (Zonai Fieldworks turns its features' hooks on and off), so each is a root of the reach check and a
seed of the lift. The trampolines of inline hooks (never run) and the Orig trampolines of replace hooks (the lift
serves them with the function's unpatched copy) are left out: their way back would split main's functions."""
p = {m['name']: m for m in rec['modules']}[module]
img, pre = rec['images'].get(module), rec.get('pre_images', {}).get(module)
if img is None or pre is None:
return set()
n = p['text_end'] // 4
now, old = struct.unpack_from(f'<{n}I', img), struct.unpack_from(f'<{n}I', pre)
known = {p['base'] + int(h['trampoline'].split('+')[1], 16) for h in hooks
if (h.get('trampoline') or '').startswith(module + '+')}
out, inside = set(), False # inside: the word before is a written word that goes on to this one
for i in range(n):
new = old[i] == 0 and now[i] != 0
if new and not inside:
out.add(p['base'] + 4 * i)
# b, br, ret end a trampoline; one may follow right after
inside = new and now[i] & 0xFC000000 != 0x14000000 and now[i] & 0xFFFFFC1F not in (0xD61F0000, 0xD65F0000)
return out - known
def entries(rec, hooks, module):
"""(main offsets, plugin offsets): where module's hook code comes back into main's .text, which the lift makes
function starts (recomp/patches.py `entry`), and the code its veneers lead to, seeds of its lift. The site + 4 of a
far hook, and of a replace hook without an Orig trampoline, is one either way: the plugin may point the site's
veneer at its own code later (Zonai Fieldworks turns a feature's hooks on and off at play), and that code comes
back there too."""
mods = {m['name']: m for m in rec['modules']}
main, p = mods['main'], mods[module]
out = {int(h['site'].split('+')[1], 16) + 4 for h in hooks
if h['kind'] == 'branch' or h['kind'] == 'replace' and not h.get('trampoline')}
base, img = p['base'], rec['images'][module]
roots = {base + int(h['target'].split('+')[1], 16) for h in hooks
if h['kind'] in ('branch', 'call', 'data', 'replace') and h.get('target', '').startswith(module + '+')}
tramps = init_code(rec, hooks, module)
roots |= tramps
nso = Nso(p['file']) if p.get('file') and Path(p['file']).is_file() else None
plt = plt_imports(nso, img, base, p['text_end']) if nso else {}
_, _, _, outside, veneers = reach(img, base, p['text_end'], sorted(roots), plt)
out |= {a - main['base'] for a in outside if main['base'] <= a < main['base'] + main['text_end'] and a % 4 == 0}
return sorted(out), sorted(v - base for v in veneers | tramps if base <= v < base + p['text_end'])
def plugin_lines(rec, hooks, name, record_dir, module):
@@ -399,7 +631,8 @@ def plugin_lines(rec, hooks, name, record_dir, module):
p = mods[module]
img = rec['images'][p['name']]
text_sha = hashlib.sha256(img[:p['text_end']]).hexdigest()
lines.append(f'plugin {name} {p["name"]} {text_sha} {(Path(record_dir) / p["image"]).resolve().as_posix()}')
image = json.dumps((Path(record_dir) / p['image']).resolve().as_posix(), ensure_ascii=False)
lines.append(f'plugin {name} {p["name"]} {text_sha} {image}')
own = {int(h['site'].split('+')[1], 16) for h in hooks}
for w in rec['writes']:
if w['module'] == 'main' and w['offset'] in own:
@@ -422,6 +655,9 @@ def plugin_lines(rec, hooks, name, record_dir, module):
impl = branch_target(struct.unpack_from('<I', rec['images'][sm], so + 4)[0], stub_at + 4)
seeds.setdefault(sm, set()).add(impl - mods[sm]['base'])
lines.append(f'site {name} main {site:x} {u(h["original"]):08x} @call:{sm}+{so:x} {u(h["original"]):08x}')
elif h['kind'] == 'data':
if h.get('target', '').startswith(module + '+'):
seeds.setdefault(module, set()).add(at(h['target'])[1])
else:
tm, to = at(h['target'])
seeds.setdefault(tm, set()).add(to)
@@ -430,10 +666,15 @@ def plugin_lines(rec, hooks, name, record_dir, module):
if h['kind'] == 'replace' and h.get('trampoline'):
rm, ro = at(h['trampoline'])
lines.append(f'orig {name} {rm} {ro:x} main {site:x}')
back, ahead = entries(rec, hooks, module)
if ahead:
seeds.setdefault(module, set()).update(ahead)
for m in sorted(stubs):
lines += [f'stub {m} {o:x}' for o in sorted(stubs[m])]
for m in sorted(seeds):
lines.append(f'seed {m} ' + ' '.join(f'{o:x}' for o in sorted(seeds[m])))
if back:
lines.append('entry main ' + ' '.join(f'{o:x}' for o in back))
return lines
@@ -568,11 +809,11 @@ def run(exe, out, tick_offset, timeout, only):
return r.returncode, None
def report(rec, label):
def report(rec, label, game=frozenset()):
rec = ran_view(rec)
impls = hook_impls(rec)
hooks, reasons = check_record(rec, impls)
more, notes = reach_check(rec, hooks, impls)
hooks, reasons = check_record(rec, impls, game)
more, notes = reach_check(rec, hooks, impls, game)
reasons += more
for n in notes:
print(f' {n}')
@@ -583,7 +824,10 @@ def report(rec, label):
for h in hooks:
if h['kind'] == 'inline':
print(f' inline hook {h["site"]} (was {h["original"]}) -> stub {h["stub"]} -> {h["impl"]}, callback '
f'{h["callback"]}, trampoline {h["trampoline"]} ({h.get("relocated")}; b site+4)')
f'{h["callback"]}, trampoline {h["trampoline"]} ({h.get("relocated")}; back to site+4)')
elif h['kind'] == 'data':
print(f' data {h["site"]} {h["original"]} -> {h["new"]}' +
(f' (points at {h["target"]})' if h.get('target') else ''))
else:
print(f' {h["kind"]} {h["site"]} (was {h["original"]}) -> {"bl" if h["kind"] == "call" else "b"} '
f'{h["target"]}' + (f', Orig trampoline {h["trampoline"]}' if h.get('trampoline') else ''))
@@ -594,7 +838,7 @@ def report(rec, label):
return hooks, reasons
def plugin_runs(exe, out, module, timeout):
def plugin_runs(exe, out, module, timeout, game=frozenset()):
"""The two service runs of one plugin (run2 with the tick offset) into out/<module>: (its first record or None,
hooks, reasons)."""
recs = []
@@ -607,9 +851,9 @@ def plugin_runs(exe, out, module, timeout):
recs.append(load_record(d))
print(f'{module} run {i}: exit {code}, tick offset {offset:#x}')
if recs[0].get('refused'): # refused: a second run says nothing more
hooks, bad = report(recs[0], f'{module} run 1')
hooks, bad = report(recs[0], f'{module} run 1', game)
return recs[0], hooks, bad
hooks, bad = report(recs[0], f'{module} run 1')
hooks, bad = report(recs[0], f'{module} run 1', game)
diff = diff_records(ran_view(recs[0]), ran_view(recs[1]))
print(f'{module} run 1 against run 2: {len(diff)} differences' + (':' if diff else ''))
for line in diff:
@@ -629,9 +873,12 @@ def main():
ap.add_argument('--check', type=Path, help='check the record in this directory only')
ap.add_argument('--timeout', type=int, default=120, help='seconds a service run may take')
ap.add_argument('--mods', type=Path, help='the mods folder the plugins come from')
ap.add_argument('--exefs', type=Path, help="the game's ExeFS folder: a plugin may call what its main imports")
ap.add_argument('--patches', type=Path, help='the patch file so far')
ap.add_argument('--patches-out', type=Path, help='the patch file with the plugins\' sets added')
ap.add_argument('--status', type=Path, help='the plugin status file (build-cache/plugins.status)')
ap.add_argument('--entries-out', type=Path, help='file for `entry main` lines: addresses of main an init called '
'that the lift has no function start for; a lift with them lets the init go on')
args = ap.parse_args()
sys.stdout.reconfigure(errors='replace')
emitting = bool(args.patches_out or args.status)
@@ -639,7 +886,7 @@ def main():
ap.error('--mods, --patches-out and --status go together')
if args.check:
rec = load_record(args.check)
hooks, bad = report(rec, str(args.check))
hooks, bad = report(rec, str(args.check), game_imports(args.exefs))
if emitting:
emit([(m['name'], m.get('file'), rec, args.check, hooks, bad) for m in ran_view(rec)['modules']
if m['plugin']], args)
@@ -653,13 +900,20 @@ def main():
print(f'the service run without inits gave no record: {why}; see {args.out / "list" / "run.log"}')
return 2
listing = load_record(args.out / 'list')
game = game_imports(args.exefs)
results = []
for m in (m for m in listing['modules'] if m['plugin']):
rec, hooks, bad = plugin_runs(args.exe, args.out, m['name'], args.timeout)
rec, hooks, bad = plugin_runs(args.exe, args.out, m['name'], args.timeout, game)
print(f'{m["name"]}: ' + (f'refused: {bad[0]}' if bad else f'accepted, {len(hooks)} hooks'))
results.append((m['name'], m.get('file'), rec, args.out / m['name'] / 'run1', hooks, bad))
if emitting:
emit(results, args)
if args.entries_out:
found = sorted({int(m.group(1), 16) for r in results for why in r[5] for m in MID_CALL.finditer(why)})
args.entries_out.write_text(''.join(f'entry main {o:x}\n' for o in found), encoding='utf-8')
if found:
print('plugins: inits call main where the lift has no function start: ' +
', '.join(f'main+{o:#x}' for o in found))
return 1 if any(r[5] for r in results) else 0
+32 -16
View File
@@ -3,7 +3,9 @@
Steps, each skipped when its verified output already exists:
1. ExeFS (code modules) of the base game and of the update.
2. Base RomFS, verified through all six IVFC levels.
2. Base RomFS, verified through all six IVFC levels. --skip-base-romfs leaves this out: no other tool in the
repository reads it, and the merge of step 3 takes the base Program NCA from the base game file and verifies all
six IVFC levels of what it merges, so damage in the base game is still found, only later.
3. Update RomFS: hactool merges the base Program NCA with the update's BKTR section.
Steps 1 and 3 run for every file in `input.updates`. Each update's version is identified by the SHA-256 of its `main`,
@@ -37,9 +39,9 @@ from extract_update_romfs import copy_range, hactool_prod_keys # noqa: E402
DATA = ROOT / 'tools' / 'data'
EXEFS_CODE = ('main', 'sdk', 'subsdk0', 'rtld')
LONG_HEX = re.compile(r'[0-9A-Fa-f]{32,}')
# hactool checks two signatures with Nintendo public keys it does not ship, so these two lines always read (FAIL) and
# say nothing about the data. The IVFC levels and the image hash decide.
UNSIGNED = re.compile(r'\s*(?:Fixed-Key Signature|NPDM Signature) \(FAIL\)')
# Signature warnings can occur on dumps whose data is intact. hactool's npdm.c npdm_print labels the ACID check simply
# "Signature", alongside nca.c nca_print's Fixed-Key and NPDM signatures. The IVFC levels and image hash still decide.
UNSIGNED = re.compile(r'\s*(?:Fixed-Key Signature|NPDM Signature|Signature) \(FAIL\):')
HACTOOL_ERROR = re.compile(r'\(FAIL\)|\(INVALID\)|Failed to|Error:')
# hactool lines of a hash check that failed: a RomFS level, a section's superblock or its hash table.
HACTOOL_HASH_FAIL = re.compile(r'^\s*(?:Level \d|Superblock Hash|Hash Table) \(FAIL\)', re.M)
@@ -274,6 +276,28 @@ def merge_update_romfs(base, update, keys_path, hactool, output, logs, phase=lam
result.rename(output)
def extract_base(base, keys, out, logs, expected, *, skip_romfs=False):
"""The base game's ExeFS, and its RomFS unless skip_romfs.
The ExeFS identifies the base game as TotK 1.0.0: extract_update matches every update against the base game file
and reports a damaged one itself. skip_romfs leaves out the 17 GB image nothing reads, see the module docstring.
"""
if exefs_problems(out / 'exefs', expected):
say(' extracting ExeFS')
extract_exefs(base, keys, out, logs, update=False)
problems = exefs_problems(out / 'exefs', expected)
require(not problems, f'Base game is not TotK {expected["display_version"]}: {", ".join(problems)} differ')
say(f' ExeFS {expected["display_version"]}: main, sdk, subsdk0, rtld match')
report_npdm(out / 'exefs', expected)
if skip_romfs:
say(' RomFS skipped (--skip-base-romfs)')
return
if not romfs_verified(out / 'romfs', expected):
say(' extracting RomFS (17 GB)')
extract_base_romfs(out, keys, logs, base)
check_romfs(out / 'romfs', expected)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--config', type=Path, default=ROOT / 'config.local.toml')
@@ -285,6 +309,9 @@ def main():
parser.add_argument('--keys', type=Path, help='prod.keys (default: input.keys of the config)')
parser.add_argument('--work', type=Path, help='output directory with extracted/ and logs/ (default: work.dir of '
'the config, else build)')
parser.add_argument('--skip-base-romfs', action='store_true',
help="do not extract the base game's 17 GB RomFS: no other tool reads it, and the update merge "
'verifies all six IVFC levels of what it takes from the base game file')
args = parser.parse_args()
config = {}
@@ -300,18 +327,7 @@ def main():
v0 = versions['1.0.0']
say('Base game')
base_out = extracted / 'v0'
if exefs_problems(base_out / 'exefs', v0):
say(' extracting ExeFS')
extract_exefs(base, keys, base_out, logs, update=False)
problems = exefs_problems(base_out / 'exefs', v0)
require(not problems, f'Base game is not TotK 1.0.0: {", ".join(problems)} differ')
say(' ExeFS 1.0.0: main, sdk, subsdk0, rtld match')
report_npdm(base_out / 'exefs', v0)
if not romfs_verified(base_out / 'romfs', v0):
say(' extracting RomFS (17 GB)')
extract_base_romfs(base_out, keys, logs, base)
check_romfs(base_out / 'romfs', v0)
extract_base(base, keys, extracted / 'v0', logs, v0, skip_romfs=args.skip_base_romfs)
for update in updates:
extract_update(base, Path(update), keys, args.hactool, extracted, logs, versions)
+18 -3
View File
@@ -35,6 +35,10 @@ class DamagedFile(ValueError):
super().__init__(f'{self.path} is damaged or incomplete ({detail})')
class BlockSizeError(ValueError):
"""An NCZBLOCK block whose data decompresses to more or fewer bytes than its header declares."""
def compressed(path):
"""('nsz' or 'xcz', entries) for a game file holding NCZ files, else None. Raises ValueError for a file that is
neither an NSP nor an XCI."""
@@ -126,9 +130,18 @@ def blocks(f, pos, end, total):
for i, length in enumerate(stored):
plain = min(1 << exponent, size - (i << exponent))
require(pos + length <= end, 'Truncated NCZ block')
data = read_at(f, pos, length)
# nsz's BlockDecompressorReader.py __decompressBlock skips padding in a raw block: only plain bytes belong
# to the NCA, while the full stored length locates the next block.
data = read_at(f, pos, min(length, plain))
pos += length
yield zstd.decompress(data) if length < plain else data
if length < plain:
# Read at most one byte beyond the declared size: a damaged frame must not allocate its whole output.
# ZstdFile also preserves support for concatenated frames within a block.
with zstd.ZstdFile(io.BytesIO(data)) as z:
data = z.read(plain + 1)
if len(data) != plain:
raise BlockSizeError(f'NCZ block decompressed size does not match its header (block {i})')
yield data
def stream(f, pos, end, total):
@@ -176,7 +189,9 @@ def unpack_ncz(f, start, end, out, name, source, progress):
progress(n)
if at == total:
break
except (zstd.ZstdError, EOFError) as e: # EOFError: the stream ends before its end-of-frame marker
# EOFError: the stream ends before its end-of-frame marker. BlockSizeError: a block's data is damaged; like the
# other two it is a damaged file, so the installer asks for a fresh copy (installer/steps.py, Check.unpack).
except (zstd.ZstdError, EOFError, BlockSizeError) as e:
raise DamagedFile(source, f'{name}: {e}') from None
if at != total or pending:
raise DamagedFile(source, f'{name}: {at - HEADER:,} of {total - HEADER:,} bytes')
+145 -16
View File
@@ -15,22 +15,39 @@ bytes sorted by (kind, name): name (the 32 bytes the file name's 64 hex digits s
--keep leaves the loose files in place. Close the game first: a running totk.exe has read the old pack's index.
"""
import argparse
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from itertools import islice
import os
import re
import struct
import sys
import time
from pathlib import Path
import hostmem
MAGIC = b'TKSPACK1'
PACK = 'shader-cache.pack'
KINDS = {'.spv': 1, '.res.json': 2, '.use': 3, '.in': 4}
NAME = re.compile(r'([0-9a-f]{64})(\.spv|\.res\.json|\.use|\.in)')
USE_SIZE = 20 # gfx_shader.c use_store: magic, version, three masks
MAX_ENTRIES = 1 << 24 # gfx_shader.c pack_open's index limit
MAX_READERS = 8
# File data read ahead of the writer. The cache's files are 20 B to ~0.5 MiB (a 1.4.3 install: 117k files, 1.5 GiB),
# so the count limit (two files per reader) binds first; this cap keeps a cache of unusually large files from holding
# 16 of them in memory at once.
READ_AHEAD_BYTES = 32 << 20
# Below this much free RAM the files are read one at a time, as before the readers existed. It is 16 times the
# read-ahead cap, so the parallel path never asks for more than a sixteenth of what is free; under it the machine is
# already paging, and extra concurrent reads only compete with the page-ins of the other programs.
LOW_FREE_RAM = 512 << 20
def loose_files(cache):
"""{(kind, name): path} of the cache's loose files; *.in only in in/."""
found = {}
"""({(kind, name): path}, {(kind, name): size}) of the cache's loose files; *.in only in in/. The sizes come with
the directory listing on Windows and bound the read-ahead in prefetched_files."""
found, sizes = {}, {}
for folder, kinds in ((cache, (1, 2, 3)), (cache / 'in', (4,))):
if not folder.is_dir():
continue
@@ -41,8 +58,10 @@ def loose_files(cache):
continue
kind = KINDS[m.group(2)]
if kind in kinds:
found[(kind, bytes.fromhex(m.group(1)))] = Path(e.path)
return found
key = (kind, bytes.fromhex(m.group(1)))
found[key] = Path(e.path)
sizes[key] = e.stat().st_size
return found, sizes
def read_pack(path):
@@ -58,8 +77,13 @@ def read_pack(path):
print(f'{path}: not a cache pack, rebuilt from the loose files only', flush=True)
return {}
count = struct.unpack_from('<I', head, 8)[0]
raw = f.read(48 * count)
if len(raw) != 48 * count:
index_size = 48 * count
# Check the count before read() allocates its buffer: a damaged header can request hundreds of GiB.
if count > MAX_ENTRIES or index_size > size - 16:
print(f'{path}: invalid index size, rebuilt from the loose files only', flush=True)
return {}
raw = f.read(index_size)
if len(raw) != index_size:
print(f'{path}: truncated index, rebuilt from the loose files only', flush=True)
return {}
out = {}
@@ -74,11 +98,102 @@ def valid(kind, data):
return len(data) == USE_SIZE if kind == 3 else len(data) > 0
def pack(cache, keep=False):
def read_workers(cpus=None, free=None):
"""Readers for this machine: one per two logical CPUs (one per core on SMT CPUs), 1 to MAX_READERS, and 1 when
less than LOW_FREE_RAM is free. A reader spends its time in the kernel and in the antivirus scan of each opened
file, which runs on threads of its own, so half the logical CPUs keep the disk and the scanner busy and leave the
rest to them and to the setup window; a 1- or 2-CPU machine reads one file at a time. cpus: os.cpu_count();
free: hostmem.available_ram(), None when unknown."""
if free is not None and free < LOW_FREE_RAM:
return 1
return min(MAX_READERS, max(1, (cpus or 1) // 2))
def machine_read_workers():
"""read_workers() for this machine and a line saying why, for the log."""
cpus = os.cpu_count()
try:
free = hostmem.available_ram()
except (OSError, AttributeError, ValueError): # no answer from the OS: decide by the CPU count alone
free = None
n = read_workers(cpus, free)
known = 'free memory unknown' if free is None else f'{free / 2**20:.0f} MiB free memory'
return n, f'{n} reader{"s" if n > 1 else ""} ({cpus} CPUs, {known})'
def read_loose(path):
if path is not None:
try:
return path.read_bytes()
except OSError:
pass
return None
def parallel_reads(keys, loose, workers, sizes, max_bytes):
"""(key, data) in the order of keys, read on a pool of workers threads. At most 2 * workers files and max_bytes of
their data (by the listed size) are read ahead of the caller; a file larger than max_bytes is read alone."""
pool = ThreadPoolExecutor(max_workers=workers)
try:
pending, held = deque(), 0 # (key, future or None, bytes reserved), and the reserved bytes in total
following = iter(keys)
key = next(following, None)
while True:
while key is not None and len(pending) < 2 * workers:
size = sizes.get(key, 0) if key in loose else 0
if pending and held + size > max_bytes:
break
pending.append((key, pool.submit(read_loose, loose[key]) if key in loose else None, size))
held += size
key = next(following, None)
if not pending:
return
done, future, size = pending.popleft()
data = future.result() if future else None
held -= size
yield done, data
finally:
pool.shutdown(wait=True, cancel_futures=True)
def prefetched_files(keys, loose, workers, sizes=None, max_bytes=READ_AHEAD_BYTES):
"""(key, loose file's bytes or None) for every key in order, the same bytes as a serial read so the pack comes out
identical. workers > 1 reads ahead on threads (parallel_reads). Any failure of that path (a thread that does not
start, a MemoryError in a reader, an executor error) switches to serial reads from the first key not yet given
out, so the pack still completes; a file that cannot be read gives None in either path."""
given = 0
if workers > 1:
reads = parallel_reads(keys, loose, workers, sizes or {}, max_bytes)
while True:
try:
item = next(reads)
except StopIteration:
return
except Exception as e: # noqa: BLE001 the serial path below reads the rest
print(f'pack-cache: parallel reads failed ({type(e).__name__}: {e}); reading the remaining '
f'{len(keys) - given} files one at a time', flush=True)
try:
reads.close()
except Exception: # noqa: BLE001 the pool is dropped either way
pass
break
yield item # outside the try: errors of the caller never reach the fallback
given += 1
for key in islice(keys, given, None):
yield key, read_loose(loose.get(key))
def pack(cache, keep=False, read_workers=None, progress=None):
"""Fold the loose files into the pack. read_workers: concurrent file reads, 1..16; None picks them for the
machine (machine_read_workers)."""
if read_workers is None:
read_workers = machine_read_workers()[0]
if not 1 <= read_workers <= 16:
raise ValueError('read_workers must be 1..16')
cache = Path(cache)
out = cache / PACK
packed = read_pack(out)
loose = loose_files(cache)
loose, sizes = loose_files(cache)
if not loose:
# Nothing to fold in: every file of the cache is already in the pack, so writing it again copies the same
# bytes over the same entries (1.37 GiB here, 2.6 s, and a file system that then has the old pack's blocks to
@@ -91,13 +206,10 @@ def pack(cache, keep=False):
try:
with open(tmp, 'wb') as f:
f.write(bytes(offset)) # header and index, written once the offsets are known
for key in keys:
data = None
for done, (key, data) in enumerate(prefetched_files(keys, loose, read_workers, sizes), 1):
if progress and (done == len(keys) or done % 128 == 0):
progress('read', done, len(keys))
if key in loose: # a valid loose file, else the packed copy, else nothing
try:
data = loose[key].read_bytes()
except OSError:
pass
if data is not None and valid(key[0], data):
written.append(loose[key])
else:
@@ -120,8 +232,10 @@ def pack(cache, keep=False):
old.close()
os.replace(tmp, out)
if not keep:
for p in written:
for done, p in enumerate(written, 1):
p.unlink(missing_ok=True)
if progress and (done == len(written) or done % 128 == 0):
progress('cleanup', done, len(written))
try:
(cache / 'in').rmdir() # only when empty
except OSError:
@@ -133,10 +247,25 @@ def main():
ap = argparse.ArgumentParser(description='Fold a shader cache into shader-cache.pack.')
ap.add_argument('cache', type=Path, help='the shader-cache folder next to totk.exe')
ap.add_argument('--keep', action='store_true', help='keep the loose files')
ap.add_argument('--read-workers', type=int, choices=range(1, 17), metavar='1..16',
help='concurrent file reads (default: half the logical CPUs, 1 to 8, and 1 with less than '
f'{LOW_FREE_RAM >> 20} MiB free memory; 1 reads serially)')
a = ap.parse_args()
if not a.cache.is_dir():
sys.exit(f'{a.cache} is not a folder')
n, new, skipped, size = pack(a.cache, a.keep)
if a.read_workers:
workers = a.read_workers
print(f'pack-cache: {workers} reader{"s" if workers > 1 else ""} (--read-workers)', flush=True)
else:
workers, why = machine_read_workers()
print(f'pack-cache: {why}', flush=True)
last_progress = [0.0]
def progress(phase, done, total):
now = time.monotonic()
if done == total or now - last_progress[0] >= 5:
print(f'pack-cache: {phase}: {done} of {total} files', flush=True)
last_progress[0] = now
n, new, skipped, size = pack(a.cache, a.keep, workers, progress)
print(f'{a.cache / PACK}: {n} files, {size / 2**20:.0f} MiB ({new} loose files folded in'
f'{", " + str(skipped) + " unreadable or empty skipped" if skipped else ""})', flush=True)
+7 -1
View File
@@ -11,6 +11,7 @@ import sys
PERF = re.compile(r'perf: frame (\d+): interval avg ([\d.]+) ms max ([\d.]+) ms \(([\d.]+) fps\); render thread blocked: '
r'pacing (\d+)%.*?pipeline build (\d+)%.*?texture (\d+)%')
FRAME_COUNT = re.compile(r'; ab \d+/(\d+);')
GPU = re.compile(r'perf: frame (\d+): gpu avg (?:([\d.]+) ms|n/a).*?fence wait per frame: render thread ([\d.]+) ms, '
r'other threads ([\d.]+) ms; vram (?:([\d.]+) of ([\d.]+) MiB|n/a).*?ram working set ([\d.]+) MiB, '
r'private ([\d.]+) MiB; bound: (\w+)')
@@ -69,6 +70,7 @@ def main():
lo = int(sys.argv[2]) if len(sys.argv) > 2 else 1560
hi = int(sys.argv[3]) if len(sys.argv) > 3 else 10**9
fr, fps, mx, gpu, vram, ram, bound = None, [], [], [], [], [], {}
frame_counts = []
dirty, dframes, dlast = [], [], None
for line in open(sys.argv[1], encoding='utf-8', errors='replace'):
if line.startswith('run_game:'):
@@ -86,6 +88,8 @@ def main():
f = int(m[1])
if lo < f <= hi:
fps.append(float(m[4]))
count = FRAME_COUNT.search(line)
frame_counts.append(int(count[1]) if count else 60) # assume full windows when older logs omit the count
mx.append(float(m[3]))
print(f'perf {f}: {m[4]} fps max {m[3]} pacing {m[5]}% pipe {m[6]}% tex {m[7]}%')
elif m := GPU.search(line):
@@ -109,7 +113,9 @@ def main():
elif (m := RWAIT.search(line)) and fr and lo < fr <= hi:
print(f' rw{m[1]}: {m[2]}')
if fps:
print(f'SUMMARY frames {lo}-{hi}: mean fps {statistics.mean(fps):.1f}, min window fps {min(fps):.1f}, '
# Windows contain frames, not equal durations: total frames / total time is the weighted harmonic mean.
mean_fps = statistics.harmonic_mean(fps, weights=frame_counts)
print(f'SUMMARY frames {lo}-{hi}: mean fps {mean_fps:.1f}, min window fps {min(fps):.1f}, '
f'max frame {max(mx):.1f} ms')
if ram:
g = f'gpu mean {statistics.mean(gpu):.2f} ms' if gpu else 'gpu n/a'
+37 -5
View File
@@ -137,7 +137,20 @@ def release_gpu_lock(f):
f.close()
def tag_name(value):
if '/' in value or '\\' in value:
raise argparse.ArgumentTypeError('run tag must be a name without path separators')
return value
def check_profile_destination(dest):
source, target = PROFILE.resolve(), Path(dest).resolve()
if source.is_relative_to(target) or target.is_relative_to(source):
raise ValueError('profile copy must not overlap the original profile')
def profile_copy(dest, save):
check_profile_destination(dest)
if dest.exists():
shutil.rmtree(dest)
shutil.copytree(PROFILE, dest)
@@ -149,6 +162,18 @@ def profile_copy(dest, save):
shutil.copytree(SAVES / save, users[0])
def stop_process(proc):
"""Stop this run's child before its disposable profile is removed, including an interrupted wait."""
if proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('exe_dir', type=Path, help='build directory holding totk.exe')
@@ -157,7 +182,7 @@ def main():
ap.add_argument('--seconds', type=float, required=True,
help='game time to run: the run ends once the world clock (game time since the save loaded) passed '
'this many seconds (shot is taken of that frame)')
ap.add_argument('--tag', default='run', help='names the profile copy and the log')
ap.add_argument('--tag', type=tag_name, default='run', help='names the profile copy and the log (no path separators)')
ap.add_argument('--shot', type=Path, help='PNG of the last frame; turns async pipeline builds off (boot.c)')
ap.add_argument('--log', type=Path, help='default: <exe dir>/logs/<tag>.log')
ap.add_argument('--env', action='append', default=[], metavar='KEY=VALUE', help='extra environment, repeatable')
@@ -166,6 +191,11 @@ def main():
a = ap.parse_args()
exe_dir = a.exe_dir.resolve()
prof = exe_dir / f'prof-{a.tag}'
try:
check_profile_destination(prof)
except ValueError as e:
ap.error(str(e))
log = (a.log or exe_dir / 'logs' / f'{a.tag}.log').resolve()
log.parent.mkdir(parents=True, exist_ok=True)
gpu = take_gpu_lock(exe_dir) if a.quiet else None
@@ -174,7 +204,6 @@ def main():
if a.quiet:
while busy():
time.sleep(10)
prof = exe_dir / f'prof-{a.tag}'
profile_copy(prof, a.save)
env = dict(os.environ, TOTK_ASSUME_FOCUS='1', TOTK_INPUT='none', TOTK_INPUT_SCRIPT=str(a.script.resolve()))
@@ -192,9 +221,12 @@ def main():
f.flush()
start = time.time()
proc = subprocess.Popen(args, cwd=exe_dir, env=env, stdout=f, stderr=subprocess.STDOUT)
if not a.show:
threading.Thread(target=keep_in_background, args=(proc,), daemon=True).start()
rc = proc.wait()
try:
if not a.show:
threading.Thread(target=keep_in_background, args=(proc,), daemon=True).start()
rc = proc.wait()
finally:
stop_process(proc)
f.write(f'run_game: rc={rc} wall={time.time() - start:.0f}s; others running after: '
f'totk.exe {count("totk.exe")}, ninja.exe {count("ninja.exe")}\n')
finally:
+33 -16
View File
@@ -22,7 +22,7 @@
# frame_queue = 0
# Frame generation: off, or fsr3 (AMD FSR 3 frame interpolation). A generated picture goes on screen between each two
# the game draws: twice the pictures, the game at half of fps_limit (the limit counts the pictures shown), the controls
# about half a frame later. For displays of 120 Hz and more; off with DLSS, FSR 3.1 (scene_upscaler) or HDR, and in
# about half a frame later. For displays of 120 Hz and more; off with DLSS, FSR (scene_upscaler) or HDR, and in
# menus and fades. Applies at once.
# frame_gen = off
# Real-time frame step: game speed follows the clock instead of the frame count.
@@ -41,6 +41,9 @@
# Game 1.4.3: the two launchers in Tenbez Shrine throw the stone ball into the other launcher's seat above 30 fps.
# 0 = the game's own speed, tuned for 30 fps.
# shutter_fix = 1
# Games 1.2.1 and 1.4.3: above 30 fps a thunderstorm has the lightning of 30 fps, instead of more distant bolts and
# lightning flashes the higher the frame rate. 0 = the game's own chances per frame, tuned for 30 fps.
# lightning_fix = 1
[performance]
# The keys of this section and of [diagnostics] are for testing and troubleshooting, and take effect at the next start.
@@ -181,6 +184,10 @@
# vk_dyn_a2c = 1
# Pin the shader subgroup size to 32 when the GPU allows it.
# vk_subgroup_pin = 1
# 1 gives empty colour slots of a render pass a dummy image instead of none. Default: 0. A workaround to try if the
# game crashes right after the Nintendo logo on an Intel HD or UHD graphics chip (6th to 10th generation, such as
# HD 520 or UHD 620) with Intel's older driver (101.21xx); it costs a few MB of video memory.
# null_attach = 0
[display]
# Device profile: auto (the Steam Deck when this is one), desktop or deck. On a Steam Deck the keys this file does not
@@ -231,7 +238,7 @@
# Dynamic resolution: 1 lets the game lower the scene to 90 or 80 % of that size, 0 keeps it at 100 %. The game decides
# by a cost estimate made for the Switch, which grows with the scene's width and ignores how fast your GPU is: a
# scene wider than about 3000 pixels can drop to 80 % on any GPU. 1 is the default. 1.1.0, 1.2.1 and 1.4.3. Changes in
# the menu take effect at once. While FSR 3.1 upscales the scene (scene_upscaler = fsr3) it stays at 100 %.
# the menu take effect at once. While FSR upscales the scene (scene_upscaler = fsr3 or fsr4) it stays at 100 %.
# dynamic_res = 1
# Scaling to the window when it is larger than the game resolution: fsr (AMD FSR 1) or bilinear, and FSR's sharpening
# from 0 (off) to 100. Changes while the game runs take effect at once.
@@ -296,24 +303,27 @@
# The temporal upscaler for the 3D scene: off (the game's own scaling and FXAA), dlss (NVIDIA DLSS, on NVIDIA RTX GPUs
# with the DLSS model from NVIDIA's DLSS SDK next to the executable: Windows nvngx_dlss.dll next to totk.exe; Linux
# libnvidia-ngx-dlss.so.<version> next to totk, with the NVIDIA driver's libnvidia-ngx.so.1 installed) or fsr3 (AMD FSR
# 3.1 from AMD's FidelityFX SDK, on any GPU). FSR 3.1 below native (dlss = quality and down) pays where the GPU limits
# the frame rate: integrated GPUs, weak cards, 4K output; where the CPU limits it, its own GPU and CPU time make the game
# slower. An engine that cannot run here leaves the game's own scaling in place. The HUD is drawn after it, at the
# output size, and is not touched. The present's upscaler and sharpness below still scale the game image to the window.
# Frame generation stays off with fsr3. Read at start. Without this line, dlaa = 1 (the older switch) means dlss.
# libnvidia-ngx-dlss.so.<version> next to totk, with the NVIDIA driver's libnvidia-ngx.so.1 installed), fsr3 (AMD FSR
# 3.1 from AMD's FidelityFX SDK, on any GPU) or fsr4 (AMD FSR 4, Windows only, on the Radeon GPUs AMD's FSR SDK
# libraries offer it for, with amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll next to totk.exe, which
# the setup downloads; without FSR 4 for the GPU the log says so and the scene upscaler is off). FSR below native (dlss =
# quality and down) pays where the GPU limits the frame rate: integrated GPUs, weak cards, 4K output; where the CPU
# limits it, its own GPU and CPU time make the game slower. An engine that cannot run here leaves the game's own scaling
# in place. The HUD is drawn after it, at the output size, and is not touched. The present's upscaler and sharpness
# below still scale the game image to the window. Frame generation stays off with fsr3 and fsr4. Read at start. Without
# this line, dlaa = 1 (the older switch) means dlss.
# scene_upscaler = off
# The older DLSS switch, read only when scene_upscaler is not set: 1 is scene_upscaler = dlss.
# dlaa = 0
# The upscaling mode of the scene upscaler, DLSS or FSR 3.1: dlaa (native: the 3D scene at full size, anti-aliased
# The upscaling mode of the scene upscaler, DLSS or FSR: dlaa (native: the 3D scene at full size, anti-aliased
# only), quality, balanced, performance or ultra_performance (the scene at 67, 58, 50 or 33 % of the output, scaled up by
# the upscaler; these replace render_scale and sharpen texture filtering to match). They apply only while a scene
# upscaler runs; otherwise the scene follows render_scale. Changes while the game runs take effect at once (1.4.3; 1.2.1
# at the next start).
# dlss = dlaa
# FSR 3.1's own sharpening of the 3D scene, from 0 (off) to 100. The game's sharpening is part of its FXAA, which FSR
# 3.1 replaces, so at 0 FSR's picture is softer than the game's own. Only with scene_upscaler = fsr3. Changes while the
# game runs take effect at once.
# FSR's own sharpening of the 3D scene, from 0 (off) to 100. The game's sharpening is part of its FXAA, which FSR
# replaces, so at 0 FSR's picture is softer than the game's own. Only with scene_upscaler = fsr3 or fsr4. Changes while
# the game runs take effect at once.
# fsr_sharpness = 80
# The DLSS model: default (NVIDIA's advice per mode: K for dlaa, quality and balanced, M for performance, L for
# ultra_performance), k (K in every mode) or j (the other transformer model: slightly less ghosting behind moving
@@ -339,8 +349,10 @@
# processes these effects too, as before (the default until the inventory preview, the scope and water edges are
# checked on NVIDIA). The upscaling DLSS modes always process them. Changes while the game runs take effect at once.
# dlaa_effects_after = 0
# NVIDIA Reflex Low Latency (NVIDIA GPUs supporting VK_NV_low_latency2): off, on, or boost.
# Reduces system input latency; boost keeps GPU clocks high in CPU-bound scenes. Read at start.
# Low latency: off, auto, on or boost. Reduces system input latency. on and boost enable NVIDIA Reflex
# (VK_NV_low_latency2); boost also keeps NVIDIA GPU clocks high in CPU-bound scenes. auto enables Reflex, or AMD
# Anti-Lag 2 (VK_AMD_anti_lag: Mesa RADV, AMD's Windows driver) on a GPU without Reflex. On a GPU with neither the
# setting does nothing. Frames are held to the frame limit the pacer uses. Read at start.
# reflex = off
# The game's own FXAA after the post effects; with DLAA on it is not needed. Changes while the game runs take effect at
# once.
@@ -364,8 +376,8 @@
# lang = en-US
# System mode reported to the game: docked or handheld.
# operation_mode = docked
# Language of the settings menu and the overlay: en, ru, pt-BR or zh-Hans. Default: the Windows display language, English if
# it is none of them.
# Language of the settings menu and the overlay: en, ru, pt-BR, zh-Hans, de, fr, es, it, nl, ja, ko or vi. Default: the
# Windows display language (Simplified Chinese for any Chinese), English if it is none of them.
# menu_lang = en
[discord]
@@ -563,6 +575,11 @@
# cheats and the other patch files load. Its files may expect the missing code. 0: only the mods mods_no_code names.
# Read at start. Default: 0.
# mods_without_code = 0
# 1: the resource size table merged from the mods' files at start is kept in <profile>/mods/ and served again at the
# next start when no mod file, shipped table, the mod list or order, the game files or totk.exe changed (a file counts
# as changed when its size, write time or file id did). It saves the merge at start. A tool that rewrites a mod file
# with the same size and write time is not seen: set 0 while editing mod files that way. Read at start. Default: 0.
# restbl_cache = 0
# Extra room in MiB (0 to 4096) for the heap the world's textures stream into, for HD texture packs. Packs made for
# emulators with 8 GB of DRAM grow it in their own HeapDef table (System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs):
# the port reads that growth at start and applies it itself (about 3339 MiB for the HDPacks 4K pack), so such a pack