mirror of
https://github.com/tangerineturtle1/NX2navi.git
synced 2026-11-20 06:09:58 -04:00
Redraw the in-game menu with the game's own interface textures, and bring in the launcher's save import and faster builds.
In-game menu: the settings window, its tabs, rows, buttons and cursor, the performance overlay and the Preparing shaders box are drawn with the game's interface textures where the RomFS holds them (runtime/ui/menu_skin.cpp, perf_panel.cpp; plain shapes until they are decoded). Restart joins Continue and Quit, each behind a confirmation; VSync is an on/off switch; DLSS is listed only on NVIDIA GPUs; the menu sounds are quieter; Picture shape is gone and the setting descriptions are shorter; edge cases of input, layout and fonts are fixed. tools/menu_preview.py draws the menu without the game. Launcher: Import Saves takes a save from the game folder's saves/ folder or one the player picks; downloads fall back to Windows' own certificate check when Python's refuses a server; updates are faster; the title bar is drawn in the window and Navi is every icon. tools/make_game.py builds with CLANG64's clang where the launcher installed it, packs the RomFS beside the lift and the compile, takes a prebuilt runtime, and compiles the game's resources without cmd.exe, so a user folder with a space in its name builds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -117,11 +117,15 @@ folder's `licenses/` and in each component's own folder.
|
|||||||
| CPython 3.14.9 embeddable package; includes `vcruntime140*.dll` (Microsoft, redistributable with Python), OpenSSL, libffi, SQLite, zlib, libmpdec | https://www.python.org/downloads/release/python-3149/ | PSF-2.0 | `python/` |
|
| CPython 3.14.9 embeddable package; includes `vcruntime140*.dll` (Microsoft, redistributable with Python), OpenSSL, libffi, SQLite, zlib, libmpdec | https://www.python.org/downloads/release/python-3149/ | PSF-2.0 | `python/` |
|
||||||
| `tkinter` and Tcl/Tk 9.0 (`_tkinter.pyd`, `tcl90.dll`, `tcl9tk90.dll`, `zlib1.dll`, `libtommath.dll`, `tcl/`), from python.org's 3.14.9 `amd64/tcltk.msi`, unpacked, never run | https://www.python.org/ftp/python/3.14.9/amd64/ | PSF-2.0; Tcl/Tk licence (BSD-style); libtommath public domain or BSD; zlib licence | `python/` |
|
| `tkinter` and Tcl/Tk 9.0 (`_tkinter.pyd`, `tcl90.dll`, `tcl9tk90.dll`, `zlib1.dll`, `libtommath.dll`, `tcl/`), from python.org's 3.14.9 `amd64/tcltk.msi`, unpacked, never run | https://www.python.org/ftp/python/3.14.9/amd64/ | PSF-2.0; Tcl/Tk licence (BSD-style); libtommath public domain or BSD; zlib licence | `python/` |
|
||||||
| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, zstandard 0.25.0 | PyPI binary wheels, pins in `tools/requirements-launcher.txt` | BSD-3-Clause; lz4 BSD-3-Clause; zstandard BSD-3-Clause | `python/Lib/site-packages/` |
|
| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, zstandard 0.25.0 | PyPI binary wheels, pins in `tools/requirements-launcher.txt` | BSD-3-Clause; lz4 BSD-3-Clause; zstandard BSD-3-Clause | `python/Lib/site-packages/` |
|
||||||
|
| The runtime of this repository compiled into `lib/libnx2navirt.a` (`tools/make_game.py --make-runtime-lib`), with the third-party code it contains as listed in the tables above (Dear ImGui, the copied runtime parts, FidelityFX FSR 1, Vulkan Memory Allocator and the others) and inline code from the toolchain's C++ headers | this repository; MSYS2 UCRT64 toolchain of `toolchain.lock.json` | as listed above for each part; libstdc++ headers GPL-3.0 with the GCC Runtime Library Exception | `app/<version>/lib/` |
|
||||||
|
| truststore 0.10.5, unmodified (Windows' own certificate check for `launcher/net.py`) | https://pypi.org/project/truststore/0.10.5/ (`truststore-0.10.5-py3-none-any.whl`, pinned with its sha256 in `tools/requirements-launcher.txt`), Copyright (c) 2022 Seth Michael Larson | MIT | `python/Lib/site-packages/truststore/`, its licence in `truststore-0.10.5.dist-info/licenses/` |
|
||||||
| zlib 1.4 (MSYS2 `mingw-w64-ucrt-x86_64-zlib`), static library | https://zlib.net, Copyright (C) Jean-loup Gailly and Mark Adler | zlib | linked into `NX2navi-Setup.exe` (its unzip) |
|
| zlib 1.4 (MSYS2 `mingw-w64-ucrt-x86_64-zlib`), static library | https://zlib.net, Copyright (C) Jean-loup Gailly and Mark Adler | zlib | linked into `NX2navi-Setup.exe` (its unzip) |
|
||||||
| mingw-w64 CRT startup code and winpthreads 14.0.0, GCC 16.2.0's `libgcc` (MSYS2 packages), static | https://www.mingw-w64.org, https://gcc.gnu.org | mingw-w64: ZPL-2.1 / MIT / public domain; libgcc: GPL-3.0 with the GCC Runtime Library Exception | linked into `NX2navi.exe` and `NX2navi-Setup.exe` |
|
| mingw-w64 CRT startup code and winpthreads 14.0.0, GCC 16.2.0's `libgcc` (MSYS2 packages), static | https://www.mingw-w64.org, https://gcc.gnu.org | mingw-w64: ZPL-2.1 / MIT / public domain; libgcc: GPL-3.0 with the GCC Runtime Library Exception | linked into `NX2navi.exe` and `NX2navi-Setup.exe` |
|
||||||
|
|
||||||
Downloaded on the player's PC by the launcher, not distributed: the MSYS2 UCRT64 packages that
|
Downloaded on the player's PC by the launcher, not distributed: the MSYS2 UCRT64 packages that
|
||||||
`toolchain.lock.json` pins (clang and LLVM, Apache-2.0 with LLVM exception; GCC and binutils, GPL-3.0; the
|
`toolchain.lock.json` pins (clang and LLVM, Apache-2.0 with LLVM exception; GCC and binutils, GPL-3.0; the
|
||||||
libraries of the "Compiler runtime in a source build" section and of `README-BuildKit.md`), from
|
libraries of the "Compiler runtime in a source build" section and of `README-BuildKit.md`), from
|
||||||
https://repo.msys2.org/mingw/ucrt64/; and zbic 1.0.1.post1 (GPL-2.0), from PyPI. The game build links them as a
|
https://repo.msys2.org/mingw/ucrt64/; the MSYS2 CLANG64 clang it pins beside them (clang, LLVM and libc++,
|
||||||
source build does.
|
Apache-2.0 with LLVM exception; libffi MIT; zlib; zstd BSD-3-Clause; libxml2 MIT; libiconv LGPL-2.1+), from
|
||||||
|
https://repo.msys2.org/mingw/clang64/, which only compiles the lifted code; and zbic 1.0.1.post1 (GPL-2.0), from
|
||||||
|
PyPI. The game build links them as a source build does.
|
||||||
|
|||||||
@@ -49,9 +49,9 @@ With extracted folders instead, use `--exefs "C:\path\exefs" --romfs "C:\path\ro
|
|||||||
check that your dump is the right version, add `--check` (it builds nothing).
|
check that your dump is the right version, add `--check` (it builds nothing).
|
||||||
|
|
||||||
The build checks the version, unpacks the program files, packs the 26 GB RomFS image (every file is checked against
|
The build checks the version, unpacks the program files, packs the 26 GB RomFS image (every file is checked against
|
||||||
the dump's own checksums), turns the game's code into C and compiles it (about 6 minutes on a 16-thread Ryzen 7; longer on fewer cores),
|
the dump's own checksums) while it turns the game's code into C and compiles it (about 6 minutes on a 16-thread
|
||||||
then prepares every one of the game's shaders for your graphics card (about 5 more minutes), so the game does not stop
|
Ryzen 7; longer on fewer cores), then prepares every one of the game's shaders for your graphics card (about 5 more
|
||||||
to compile shaders while you play.
|
minutes), so the game does not stop to compile shaders while you play. The game it builds is for this PC's processor.
|
||||||
You can use your PC meanwhile. If it stops,
|
You can use your PC meanwhile. If it stops,
|
||||||
run the same command again: finished steps are skipped.
|
run the same command again: finished steps are skipped.
|
||||||
|
|
||||||
@@ -62,7 +62,9 @@ When it says `finished`, start `C:\Games\Ocarina\ocarina.exe`. You can delete `C
|
|||||||
|
|
||||||
- **F1** opens the settings menu. Settings are saved in `nx2navi.ini` beside the game; saves go to `profile\`.
|
- **F1** opens the settings menu. Settings are saved in `nx2navi.ini` beside the game; saves go to `profile\`.
|
||||||
- Every shader was prepared during the build. After an update of your graphics driver, the next start shows
|
- Every shader was prepared during the build. After an update of your graphics driver, the next start shows
|
||||||
"Preparing shaders" once while the driver rebuilds them.
|
"Preparing shaders" once while the driver rebuilds them. With a driver that has Vulkan's graphics pipeline library
|
||||||
|
it lasts at most about 20 seconds once the shaders are translated, and the remaining pipelines are built in the
|
||||||
|
background while you play.
|
||||||
- **Screen** in the menu has Upscaling (DLSS on NVIDIA RTX cards, FSR 3.1 on any card), Frame generation (FSR 3.1; it
|
- **Screen** in the menu has Upscaling (DLSS on NVIDIA RTX cards, FSR 3.1 on any card), Frame generation (FSR 3.1; it
|
||||||
needs DLSS or FSR 3.1 upscaling on), HDR (Native is the game's own HDR; turn HDR on in Windows first) and the
|
needs DLSS or FSR 3.1 upscaling on), HDR (Native is the game's own HDR; turn HDR on in Windows first) and the
|
||||||
resolution. Those marked "after restart" take effect when the game starts again.
|
resolution. Those marked "after restart" take effect when the game starts again.
|
||||||
|
|||||||
@@ -85,9 +85,13 @@ keeps per-core data without locks and relies on that, so the host models it (`ru
|
|||||||
- Shaders: Ampere (SM86) code is lowered to Maxwell (`tools/xlate/AmpereLowering.cs`) and translated to SPIR-V by the
|
- Shaders: Ampere (SM86) code is lowered to Maxwell (`tools/xlate/AmpereLowering.cs`) and translated to SPIR-V by the
|
||||||
pinned shader translator (`tools/vendor/ryujinx`, 1.3.2) with our patches (`tools/xlate/patches/`), built with .NET 10 NativeAOT as
|
pinned shader translator (`tools/vendor/ryujinx`, 1.3.2) with our patches (`tools/xlate/patches/`), built with .NET 10 NativeAOT as
|
||||||
`nx2navi_xlate.exe` and run as separate processes. Translations are cached on disk; shaders and pipelines seen in
|
`nx2navi_xlate.exe` and run as separate processes. Translations are cached on disk; shaders and pipelines seen in
|
||||||
play are prepared at the next boot. The game waits for all of it (`runtime/boot.c` `boot_wait`): about half a second
|
play are prepared at the next boot. The game waits for it (`runtime/boot.c` `boot_wait`): about half a second
|
||||||
when warm; after a translator, GPU or driver change a "Preparing shaders" screen shows the progress (`ui/menu.cpp`
|
when warm; after a translator, GPU or driver change a "Preparing shaders" screen shows the progress (`ui/menu.cpp`
|
||||||
`menu_boot_frame`). `NX2NAVI_PREWARM_WAIT_MS` caps the wait, after which the rest finishes in the background.
|
`menu_boot_frame`). With the graphics pipeline library the boot builds recorded pipelines in record order for at
|
||||||
|
most 20 s after the shaders are ready and leaves the rest to the pipeline workers below normal priority; a draw
|
||||||
|
that meets one before it is built gets a fast-linked pipeline (`vk_pipeline.c` `PREWARM_PIPE_MS`).
|
||||||
|
`NX2NAVI_PREWARM_FULL=1`, and drivers without the library, wait for every pipeline. `NX2NAVI_PREWARM_WAIT_MS` caps
|
||||||
|
the whole wait, after which the rest finishes in the background.
|
||||||
- Mesh and task shaders run as `VK_EXT_mesh_shader`; indirect mesh draws read NVN's `{count, first}` record through a
|
- Mesh and task shaders run as `VK_EXT_mesh_shader`; indirect mesh draws read NVN's `{count, first}` record through a
|
||||||
ring of Vulkan `{x, y, z}` records filled on the GPU.
|
ring of Vulkan `{x, y, z}` records filled on the GPU.
|
||||||
- Pipelines: `VK_EXT_graphics_pipeline_library` where the driver has it: stage libraries compiled ahead, a fast link
|
- Pipelines: `VK_EXT_graphics_pipeline_library` where the driver has it: stage libraries compiled ahead, a fast link
|
||||||
|
|||||||
@@ -228,6 +228,13 @@ Before a commit:
|
|||||||
`git config core.hooksPath .githooks` runs it before each local commit.
|
`git config core.hooksPath .githooks` runs it before each local commit.
|
||||||
- `build\<ver>\nx2navi.exe --selftest`: layout, dispatch table and host-function registry, without game files.
|
- `build\<ver>\nx2navi.exe --selftest`: layout, dispatch table and host-function registry, without game files.
|
||||||
|
|
||||||
|
A change to the in-game menu's look (`runtime/ui/menu_skin.cpp`, `option_rows.cpp`, `perf_panel.cpp`) can be looked at
|
||||||
|
without game files: `python tools/menu_preview.py` builds the menu's own drawing code with the host's clang++ and
|
||||||
|
writes the Screen tab and the full performance overlay to `build/menu-preview/` (a stand-in font, and the window's
|
||||||
|
plain border in place of the game's ornamented frame). With `--romfs <extracted RomFS folder>` it draws the game's
|
||||||
|
interface textures as the game does; `python tools/ui_textures.py <folder>` lists the textures there and dumps those
|
||||||
|
matching `--match` to `build/ui-textures/`.
|
||||||
|
|
||||||
A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes
|
A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes
|
||||||
`.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game
|
`.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game
|
||||||
files); a change to the settings passes `nx2navi.exe --probe-cfg`.
|
files); a change to the settings passes `nx2navi.exe --probe-cfg`.
|
||||||
|
|||||||
@@ -23,20 +23,23 @@ game. Saves and settings are never touched.
|
|||||||
|
|
||||||
## Look
|
## Look
|
||||||
|
|
||||||
The window follows the game's options menu, with colours sampled from it: a wooden title band with the Triforce and
|
The window follows the game's options menu, with colours sampled from it: a wooden band across the whole top with
|
||||||
the name, bronze label cells, dark value cells, orange On/Off choices, a white glowing cursor around the selected
|
Navi and the name, which is also the window's title bar (no system title bar: drag the band to move the window,
|
||||||
|
minimise and close sit at its right end, Alt+F4 closes), bronze label cells, dark value cells, orange On/Off choices, a white glowing cursor around the selected
|
||||||
row, the menu's filigree dividers and a description box for the selected row. All text is in the game's own Cetra
|
row, the menu's filigree dividers and a description box for the selected row. All text is in the game's own Cetra
|
||||||
Display: the launcher decodes it from the player's dump or built game into `data/cache/fonts` (as
|
Display: the launcher decodes it from the player's dump or built game into `data/cache/fonts` (as
|
||||||
`runtime/menu_assets.c` does for the in-game menu) and uses the system's interface font until then. Every picture is
|
`runtime/menu_assets.c` does for the in-game menu) and uses the system's interface font until then. Every picture is
|
||||||
drawn in code (`launcher/ui/art.py`); no texture, font or sound of the game is in the repository or the release.
|
drawn in code (`launcher/ui/art.py`); no texture, font or sound of the game is in the repository or the release.
|
||||||
|
|
||||||
The Triforce is also the icon of `NX2navi.exe`, `NX2navi-Setup.exe`, the window and the taskbar
|
Navi (`art.NAVI`, 22 x 21 pixels, drawn in whole pixels at every size) is also the icon of `NX2navi.exe`,
|
||||||
(`art.triforce_ico`, written into the release by `tools/make_launcher.py`).
|
`NX2navi-Setup.exe`, the window and its taskbar button (`art.navi_ico`, written into the release by
|
||||||
|
`tools/make_launcher.py`). The window sets that icon on itself, and the setup's shortcuts carry the window's taskbar
|
||||||
|
identity (`NX2navi.Launcher`), so the taskbar groups and pins it under NX2navi rather than Python.
|
||||||
|
|
||||||
Screens (`launcher/ui/app.py`): first run (dump, install folder, Desktop Shortcut, Check for Updates at Start,
|
Screens (`launcher/ui/app.py`): first run (dump, install folder, Desktop Shortcut, Check for Updates at Start,
|
||||||
Update Channel, Begin Installation); the steps of an install, update or rebuild with their progress, the build log's
|
Update Channel, Begin Installation); the steps of an install, update or rebuild with their progress, the build log's
|
||||||
last lines and Cancel, and after a failure Try Again and Copy Report; home (Play, Updates, Game Folder, Rebuild the
|
last lines and Cancel, and after a failure Try Again and Copy Report; home (Play, Updates, Game Folder, Import Saves,
|
||||||
Game, Settings); settings (update check, Hide Launcher While Playing, Keep Build Cache, Update Channel, the folders,
|
Rebuild the Game, Settings); settings (update check, Hide Launcher While Playing, Keep Build Cache, Update Channel, the folders,
|
||||||
Open Logs Folder, Uninstall, Back); uninstall (keep or remove the built game).
|
Open Logs Folder, Uninstall, Back); uninstall (keep or remove the built game).
|
||||||
|
|
||||||
Controls: the mouse (hover moves the cursor, a click selects); the keyboard (arrows, Enter or Space, Esc, F5 checks
|
Controls: the mouse (hover moves the cursor, a click selects); the keyboard (arrows, Enter or Space, Esc, F5 checks
|
||||||
@@ -48,7 +51,7 @@ for updates); an XInput gamepad (d-pad or left stick, A, B, Y).
|
|||||||
|
|
||||||
```
|
```
|
||||||
NX2navi.exe launcher/native/nx2navi.c: swaps in a staged Python, starts app\<current>\launcher\start.pyw
|
NX2navi.exe launcher/native/nx2navi.c: swaps in a staged Python, starts app\<current>\launcher\start.pyw
|
||||||
python/ python.org's embeddable Python 3.14.9 with tkinter, numpy, lz4 and zstandard
|
python/ python.org's embeddable Python 3.14.9 with tkinter, numpy, lz4, zstandard and truststore
|
||||||
app/current.txt the version the stub starts; app/previous.txt the one before it
|
app/current.txt the version the stub starts; app/previous.txt the one before it
|
||||||
app/<version>/ launcher/, runtime/, recomp/, tools/, bin/nx2navi_xlate.exe, VERSION,
|
app/<version>/ launcher/, runtime/, recomp/, tools/, bin/nx2navi_xlate.exe, VERSION,
|
||||||
toolchain.lock.json (the pinned build tools), feed.json (where updates come from)
|
toolchain.lock.json (the pinned build tools), feed.json (where updates come from)
|
||||||
@@ -56,7 +59,8 @@ pydeps/ zbic, downloaded from PyPI on this PC
|
|||||||
toolchain/msys64/ucrt64 MSYS2's clang and libraries, downloaded from the MSYS2 repository on this PC
|
toolchain/msys64/ucrt64 MSYS2's clang and libraries, downloaded from the MSYS2 repository on this PC
|
||||||
toolchain/pkgs/ the downloaded package files
|
toolchain/pkgs/ the downloaded package files
|
||||||
data/launcher.json settings; data/logs/launcher.log (and crash.log); data/cache/fonts
|
data/launcher.json settings; data/logs/launcher.log (and crash.log); data/cache/fonts
|
||||||
game/ the built game, unless another folder was chosen (its layout: README-BuildKit.md)
|
game/ the built game, unless another folder was chosen (its layout: README-BuildKit.md), with
|
||||||
|
saves/ for saves to import (below)
|
||||||
```
|
```
|
||||||
|
|
||||||
A path the Windows ANSI code page cannot hold breaks the MSYS2 tools, so the toolchain then goes to
|
A path the Windows ANSI code page cannot hold breaks the MSYS2 tools, so the toolchain then goes to
|
||||||
@@ -67,12 +71,23 @@ A path the Windows ANSI code page cannot hold breaks the MSYS2 tools, so the too
|
|||||||
`jobs.InstallJob`, one row per step:
|
`jobs.InstallJob`, one row per step:
|
||||||
|
|
||||||
1. **Gather Build Tools** (`launcher/toolchain.py`): the packages `toolchain.lock.json` pins (MSYS2 UCRT64 clang,
|
1. **Gather Build Tools** (`launcher/toolchain.py`): the packages `toolchain.lock.json` pins (MSYS2 UCRT64 clang,
|
||||||
gcc, SDL3, Opus, libvpx, dav1d, zstd, Vulkan headers and loader, VMA and their dependencies: 31 packages, 170 MB),
|
gcc, lld, SDL3, Opus, libvpx, dav1d, zstd, Vulkan headers and loader, VMA and their dependencies: about 32
|
||||||
|
packages, 175 MB; and, when the release found the same clang version there, MSYS2 CLANG64's clang with the DLLs
|
||||||
|
it loads: 9 packages, about 100 MB),
|
||||||
each checked against its sha256 and unpacked into `toolchain/msys64.new`, which replaces `toolchain/msys64` once
|
each checked against its sha256 and unpacked into `toolchain/msys64.new`, which replaces `toolchain/msys64` once
|
||||||
complete. No MSYS2 shell or pacman runs. Then zbic: the wheel for the bundled Python from PyPI, checked against
|
complete. No MSYS2 shell or pacman runs. Then zbic: the wheel for the bundled Python from PyPI, checked against
|
||||||
PyPI's sha256, into `pydeps/`.
|
PyPI's sha256, into `pydeps/`.
|
||||||
2. **Inspect Your Game** to **Compile**: `tools/make_game.py --nup <dump> --out <game> --msys <toolchain> --events`,
|
2. **Inspect Your Game** to **Compile**: `tools/make_game.py --nup <dump> --out <game> --msys <toolchain> --events`,
|
||||||
whose `@@` progress lines drive the rows (check, exefs, romfs, lift, compile).
|
whose `@@` progress lines drive the rows (check, exefs, romfs, lift, compile). How it keeps the build short:
|
||||||
|
- The RomFS image (26 GB, mostly disk work) is packed beside the lift and the compile (processor work), so a first
|
||||||
|
build takes about as long as the longer of the two. Only `romfs.c`, which includes the RomFS index's
|
||||||
|
`romfs_config.h`, waits for the image.
|
||||||
|
- Every logical processor compiles, the largest files first, so no big file starts last and runs on alone.
|
||||||
|
- The lifted code compiles with MSYS2 CLANG64's clang when the toolchain has it: the same LLVM release as
|
||||||
|
UCRT64's, built with profile-guided optimisation, about a fifth faster on this code and writing the same objects
|
||||||
|
(it reads UCRT64's headers; `make_game.py` `fast_clang` checks that both report the same version and target).
|
||||||
|
- The lifted code is compiled for the processor's own level, x86-64-v3 (AVX2, FMA) or v2 (`cpu_level`): the game
|
||||||
|
runs on the PC that builds it, and a generic build would do every fused multiply-add of the game in software.
|
||||||
3. **Prepare the Shaders**: make_game.py's last step translates every shader of the game into the game's shader
|
3. **Prepare the Shaders**: make_game.py's last step translates every shader of the game into the game's shader
|
||||||
cache and the driver's own cache (`tools/prepare_shaders.py`), so play does not stop to compile them.
|
cache and the driver's own cache (`tools/prepare_shaders.py`), so play does not stop to compile them.
|
||||||
4. The game's Cetra Display is decoded for the window.
|
4. The game's Cetra Display is decoded for the window.
|
||||||
@@ -100,12 +115,19 @@ The stub swaps `python.next` in while no Python runs, then starts the new versio
|
|||||||
`jobs.ContinueUpdateJob`:
|
`jobs.ContinueUpdateJob`:
|
||||||
|
|
||||||
4. **Update Build Tools**: only when the new release pins other packages.
|
4. **Update Build Tools**: only when the new release pins other packages.
|
||||||
5. **Translate the Code** and **Compile Changed Files**: `make_game.py --rebuild`. The exefs and romfs steps depend
|
5. **Translate the Code** and **Compile Changed Files**: `make_game.py --rebuild`. Most updates compile almost
|
||||||
only on the game files, so they are kept and the dump is not needed again; the lift runs again and the compile
|
nothing:
|
||||||
step compiles only the files whose source, included headers, flags or compiler changed (`build-cache/obj/
|
- The exefs and romfs steps depend only on the game files: they are kept, and the dump is not needed again.
|
||||||
objects.json`, from clang's dependency files).
|
- The lift runs only when the lifter, its patch table or the bring-up fixes changed.
|
||||||
6. **Swap In the New Build**: the link writes `ocarina.exe.new`, which replaces `ocarina.exe` only once it is
|
- The runtime comes prebuilt with the release (`app/<version>/lib/libnx2navirt.a`, compiled by
|
||||||
complete. A failed rebuild leaves the old build playable; Rebuild the Game tries again.
|
`make_game.py --make-runtime-lib` with the release's own compiler). Only the few runtime files that include a
|
||||||
|
header written per install (`layout.h`, `patches.h`, `romfs_config.h`) are compiled on the player's PC.
|
||||||
|
- Every other file compiles only when its source, a header it includes, the flags or the compiler changed
|
||||||
|
(`build-cache/obj/objects.json`, from clang's dependency files). The kit's folder is not part of that key, so the
|
||||||
|
objects of the version before are reused although each version lives in its own folder. The lifted code
|
||||||
|
includes only `cpu.h` and `simd.h`: a change there compiles it all again, which is rare.
|
||||||
|
6. **Swap In the New Build**: lld links `ocarina.exe.new`, which replaces `ocarina.exe` only once it is complete. A
|
||||||
|
failed rebuild leaves the old build playable; Rebuild the Game tries again.
|
||||||
7. **Prepare the Shaders** again for the new build; shaders the translator already prepared come from the cache.
|
7. **Prepare the Shaders** again for the new build; shaders the translator already prepared come from the cache.
|
||||||
8. Every version but the current and the previous one is deleted.
|
8. Every version but the current and the previous one is deleted.
|
||||||
|
|
||||||
@@ -114,6 +136,32 @@ When the new version fails to start (exit code 86 from `start.pyw`, or any error
|
|||||||
runs. Keep Build Cache off deletes the lifted C and the objects (about 5 GB) after each build but keeps
|
runs. Keep Build Cache off deletes the lifted C and the objects (about 5 GB) after each build but keeps
|
||||||
`build-cache/state.json`, so updates still rebuild without the dump (compiling everything).
|
`build-cache/state.json`, so updates still rebuild without the dump (compiling everything).
|
||||||
|
|
||||||
|
## Importing a save
|
||||||
|
|
||||||
|
Import Saves (home, under Game Folder; `launcher/saves.py`) makes another save the game's own. The game folder has
|
||||||
|
a `saves` folder with a README for it: a save put there (its files, or the folder that holds them) is taken first,
|
||||||
|
and the row then reads "From the Saves Folder"; otherwise selecting the row asks for the folder. It recognises a
|
||||||
|
Switch save backup (the save's files), an emulator's save folder (nested folders named by user and title ids), and
|
||||||
|
another NX2navi game folder or its profile folder (the account folder inside). A folder with more than 4,000 files
|
||||||
|
or 1 GB is refused as picked by mistake.
|
||||||
|
|
||||||
|
The game keeps its save in `profile/save/<account>`, named after `profile/account.uid` (made as the game would when
|
||||||
|
it never ran). The import copies the save the game would load now (a finished commit still waiting in
|
||||||
|
`profile/save-tx`, else the account folder) to `saves/backup <date time>`, puts the new files in place and empties
|
||||||
|
`profile/save-tx`, so the game loads the imported save. A save taken from the saves folder moves to
|
||||||
|
`saves/imported <date time>`. It refuses while the game runs.
|
||||||
|
|
||||||
|
## Downloads
|
||||||
|
|
||||||
|
Every download (`launcher/net.py`) comes over HTTPS and is checked against a sha256. A server's certificate is checked
|
||||||
|
first by Python's OpenSSL against the certificates in Windows' stores and, when that refuses it, by Windows' own
|
||||||
|
certificate check (the truststore package of the bundled Python; not under Wine, whose crypt32 passes a chain that
|
||||||
|
stops at an issuer it does not know). OpenSSL sees only the roots the PC already holds, and it takes an expired
|
||||||
|
cross-signature still in a store before the server's valid one ("certificate has expired" on a valid chain); Windows
|
||||||
|
weighs every chain as its own programs do and downloads a missing root from Windows Update. A certificate both refuse
|
||||||
|
stops the step with what each check said, the PC's clock against the server's (the Date of a plain-HTTP request to
|
||||||
|
it), and what to check: the date, time and time zone, or security software that scans encrypted connections.
|
||||||
|
|
||||||
## Uninstalling
|
## Uninstalling
|
||||||
|
|
||||||
Settings > Uninstall NX2navi, or Settings > Apps > NX2navi (which runs `NX2navi.exe --uninstall`): the launcher
|
Settings > Uninstall NX2navi, or Settings > Apps > NX2navi (which runs `NX2navi.exe --uninstall`): the launcher
|
||||||
@@ -130,7 +178,9 @@ Built Game" is On. The dump is never touched.
|
|||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
1. Bump `VERSION`; build the shader translator (`tools/build_xlate.py`).
|
1. Bump `VERSION`; build the shader translator (`tools/build_xlate.py`).
|
||||||
2. With Python 3.14, numpy (the icon is drawn with it, `launcher/ui/art.py`) and uv:
|
2. With Python 3.14, numpy (the icon is drawn with it, `launcher/ui/art.py`) and uv, on Windows (the prebuilt runtime
|
||||||
|
needs MSYS2's own clang; on Linux add `--wine` to run it through Wine, else the release ships without it and
|
||||||
|
players compile `runtime/` themselves):
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
uv run --no-project --python 3.14 --with numpy tools\make_launcher.py --xlate build\xlate --ffx amd_fidelityfx_vk.dll --feed owner/name --notes notes.md
|
uv run --no-project --python 3.14 --with numpy tools\make_launcher.py --xlate build\xlate --ffx amd_fidelityfx_vk.dll --feed owner/name --notes notes.md
|
||||||
@@ -140,7 +190,8 @@ Built Game" is On. The dump is never touched.
|
|||||||
|
|
||||||
On Linux it cross-compiles the two programs with clang, lld and llvm-windres against the same MSYS2 packages and
|
On Linux it cross-compiles the two programs with clang, lld and llvm-windres against the same MSYS2 packages and
|
||||||
unpacks Tcl/Tk with msiextract (msitools). It writes into `build/launcher-release`: `NX2navi-Setup-<version>.exe`
|
unpacks Tcl/Tk with msiextract (msitools). It writes into `build/launcher-release`: `NX2navi-Setup-<version>.exe`
|
||||||
(the setup program with the launcher folder appended as a zip), `NX2navi-app-<version>.zip`,
|
(the setup program with the launcher folder appended as a zip), `NX2navi-app-<version>.zip` (with the prebuilt
|
||||||
|
runtime),
|
||||||
`NX2navi-runtime-<id>.zip` and `NX2navi-update.json`. `check_content` runs over the folder first.
|
`NX2navi-runtime-<id>.zip` and `NX2navi-update.json`. `check_content` runs over the folder first.
|
||||||
3. Upload those four files to GitHub release `v<version>` of the feed repository, by hand or with `--publish`
|
3. Upload those four files to GitHub release `v<version>` of the feed repository, by hand or with `--publish`
|
||||||
(`gh release create`; add `--draft` to look before it goes out). Launchers see it at their next start.
|
(`gh release create`; add `--draft` to look before it goes out). Launchers see it at their next start.
|
||||||
@@ -151,10 +202,15 @@ repository keeps old package files, so a release keeps building with the compile
|
|||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
`python tests/launcher_test.py` (Python 3.14): versions, settings, the toolchain resolver and installer against a
|
`python tests/launcher_test.py` (Python 3.14): versions, settings, the toolchain resolver and installer against a
|
||||||
local fake repository, resumed and checked downloads, the GitHub and URL feeds, staging, switching, rollback and
|
local fake repository, resumed and checked downloads, the certificate checks against a local HTTPS server (its
|
||||||
|
certificates made with the `openssl` command), the GitHub and URL feeds, staging, switching, rollback and
|
||||||
pruning, unsafe archives, the font decoding on a system font wrapped like the game's, `make_game.py` on a synthetic
|
pruning, unsafe archives, the font decoding on a system font wrapped like the game's, `make_game.py` on a synthetic
|
||||||
`.nup` (events, skipped steps, `--rebuild` without the dump, step keys), the compile step's object cache with the
|
`.nup` (events, skipped steps, `--rebuild` without the dump, step keys), the RomFS step beside the lift and compile
|
||||||
system's C compiler, the install job with a fake `make_game.py`, and the window's selftest when a display is there.
|
and its failure stopping the build, the compile step's object cache with the system's C compiler and its
|
||||||
|
largest-first order, its windres call under folders with spaces in their names, CLANG64's clang in the lock and the
|
||||||
|
install, the save import (the account folder, the save folders it recognises, backup, the commit journal, the saves
|
||||||
|
folder, refusals), the install job with a fake
|
||||||
|
`make_game.py`, and the window's selftest when a display is there.
|
||||||
|
|
||||||
## Requirements and limits
|
## Requirements and limits
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
"""The NX2navi launcher: installs the build tools, builds the game from the player's own dump, starts it and keeps
|
"""The NX2navi launcher: installs the build tools, builds the game from the player's own dump, starts it and keeps
|
||||||
the port up to date (docs/launcher.md).
|
the port up to date (docs/launcher.md).
|
||||||
|
|
||||||
Standard library only, plus numpy for drawing the window (launcher/ui/art.py) and zstandard where Python lacks
|
Standard library only, plus numpy for drawing the window (launcher/ui/art.py), zstandard where Python lacks
|
||||||
compression.zstd. tkinter draws the window; everything that does work runs without it (launcher/cli.py).
|
compression.zstd, and truststore for Windows' own certificate check (launcher/net.py). tkinter draws the window;
|
||||||
|
everything that does work runs without it (launcher/cli.py).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
NAME = 'NX2navi'
|
NAME = 'NX2navi'
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#include <shellapi.h>
|
#include <shellapi.h>
|
||||||
#include <shlobj.h>
|
#include <shlobj.h>
|
||||||
#include <shobjidl.h>
|
#include <shobjidl.h>
|
||||||
|
#include <propsys.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <wchar.h>
|
#include <wchar.h>
|
||||||
@@ -15,6 +16,12 @@
|
|||||||
#define PATHN 1024
|
#define PATHN 1024
|
||||||
#define APP_NAME L"NX2navi"
|
#define APP_NAME L"NX2navi"
|
||||||
#define UNINSTALL_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\NX2navi"
|
#define UNINSTALL_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\NX2navi"
|
||||||
|
/* The launcher window's taskbar identity (launcher/winsys.py app_id): a shortcut that carries it is the one the
|
||||||
|
taskbar groups and pins the window under, with the shortcut's icon. */
|
||||||
|
#define APP_USER_MODEL_ID L"NX2navi.Launcher"
|
||||||
|
static const PROPERTYKEY NX_PKEY_AppUserModel_ID = {
|
||||||
|
{0x9F4C2855, 0x9F79, 0x4B39, {0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3}}, 5};
|
||||||
|
static const IID NX_IID_IPropertyStore = {0x886d8eeb, 0x8cf2, 0x4446, {0x8d, 0x02, 0xcd, 0xba, 0x1d, 0xbd, 0xcf, 0x99}};
|
||||||
|
|
||||||
static inline void exe_dir(wchar_t *out, size_t n)
|
static inline void exe_dir(wchar_t *out, size_t n)
|
||||||
{
|
{
|
||||||
@@ -105,6 +112,16 @@ static inline int make_shortcut(const wchar_t *lnk, const wchar_t *target, const
|
|||||||
IShellLinkW_SetWorkingDirectory(sl, workdir);
|
IShellLinkW_SetWorkingDirectory(sl, workdir);
|
||||||
IShellLinkW_SetIconLocation(sl, target, 0);
|
IShellLinkW_SetIconLocation(sl, target, 0);
|
||||||
IShellLinkW_SetDescription(sl, desc);
|
IShellLinkW_SetDescription(sl, desc);
|
||||||
|
IPropertyStore *ps = NULL;
|
||||||
|
if (SUCCEEDED(IShellLinkW_QueryInterface(sl, &NX_IID_IPropertyStore, (void **)&ps))) {
|
||||||
|
PROPVARIANT pv;
|
||||||
|
memset(&pv, 0, sizeof pv);
|
||||||
|
pv.vt = VT_LPWSTR;
|
||||||
|
pv.pwszVal = (LPWSTR)APP_USER_MODEL_ID;
|
||||||
|
IPropertyStore_SetValue(ps, &NX_PKEY_AppUserModel_ID, &pv);
|
||||||
|
IPropertyStore_Commit(ps);
|
||||||
|
IPropertyStore_Release(ps);
|
||||||
|
}
|
||||||
if (SUCCEEDED(IShellLinkW_QueryInterface(sl, &IID_IPersistFile, (void **)&pf))) {
|
if (SUCCEEDED(IShellLinkW_QueryInterface(sl, &IID_IPersistFile, (void **)&pf))) {
|
||||||
ok = SUCCEEDED(IPersistFile_Save(pf, lnk, TRUE));
|
ok = SUCCEEDED(IPersistFile_Save(pf, lnk, TRUE));
|
||||||
IPersistFile_Release(pf);
|
IPersistFile_Release(pf);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
/* The icon (the Triforce, written by tools/make_launcher.py from launcher/ui/art.py triforce_ico into the build
|
/* The icon (Navi, written by tools/make_launcher.py from launcher/ui/art.py navi_ico into the build folder,
|
||||||
folder, found through -I) and the manifest of NX2navi.exe and NX2navi-Setup.exe. */
|
found through -I) and the manifest of NX2navi.exe and NX2navi-Setup.exe. */
|
||||||
1 ICON "nx2navi.ico"
|
1 ICON "nx2navi.ico"
|
||||||
1 24 "app.manifest"
|
1 24 "app.manifest"
|
||||||
|
|||||||
@@ -32,6 +32,16 @@ typedef struct {
|
|||||||
static Setup S;
|
static Setup S;
|
||||||
static HWND g_wnd;
|
static HWND g_wnd;
|
||||||
|
|
||||||
|
/* Navi as launcher/ui/art.py NAVI draws it: W white, g grey, K black, B and L blue, '.' transparent. */
|
||||||
|
static const char *const NAVI[21] = {
|
||||||
|
"WWWW..............WWWW", "WggWW............WWggW", "WgggWW..........WWgggW", "WgWggWW........WWggWgW",
|
||||||
|
"WggWggW........WggWggW", "WgWgWgWW......WWgWgWgW", "WggggWgWKKKKKKWgWggggW", "WWggWggKBBBBBBKggWggWW",
|
||||||
|
".WggggKKBBLLBBKKggggW.", ".WWggKKBBLLLLBBKKggWW.", "..WWgKBBLLWWLLBBKgWW..", "...WWKBBLWWWWLBBKWW...",
|
||||||
|
".....KBBLLWWLLBBK.....", ".....KBBBLLLLBBBK.....", ".....WKKBBBBBBKKW.....", "....WWgKKBBBBKKgWW....",
|
||||||
|
"...WWgggKKKKKKgggWW...", "...WggWgW....WgWggW...", "...WgWggW....WggWgW...", "...WWggWW....WWggWW...",
|
||||||
|
"....WWWW......WWWW....",
|
||||||
|
};
|
||||||
|
|
||||||
static void fail_msg(const wchar_t *fmt, const wchar_t *arg)
|
static void fail_msg(const wchar_t *fmt, const wchar_t *arg)
|
||||||
{
|
{
|
||||||
swprintf(S.error, 512, fmt, arg ? arg : L"");
|
swprintf(S.error, 512, fmt, arg ? arg : L"");
|
||||||
@@ -258,35 +268,37 @@ static LRESULT CALLBACK wndproc(HWND w, UINT m, WPARAM wp, LPARAM lp)
|
|||||||
FillRect(dc, &r, edge);
|
FillRect(dc, &r, edge);
|
||||||
RECT in = {r.left + 2, r.top + 2, r.right - 2, r.bottom - 2};
|
RECT in = {r.left + 2, r.top + 2, r.right - 2, r.bottom - 2};
|
||||||
FillRect(dc, &in, bg);
|
FillRect(dc, &in, bg);
|
||||||
/* the Triforce: three gold triangles */
|
/* Navi, the launcher's emblem: the artwork's 22 x 21 pixels, 4 x 4 screen pixels each */
|
||||||
HBRUSH gold = CreateSolidBrush(RGB(0xe8, 0xaf, 0x3d));
|
for (int y = 0; y < 21; y++)
|
||||||
HPEN none = CreatePen(PS_NULL, 0, 0);
|
for (int x = 0; x < 22; x++) {
|
||||||
HGDIOBJ ob = SelectObject(dc, gold), op = SelectObject(dc, none);
|
COLORREF col;
|
||||||
int cx = 52, top = 28, s = 44;
|
switch (NAVI[y][x]) {
|
||||||
POINT t1[3] = {{cx, top}, {cx + s / 4, top + s * 433 / 1000}, {cx - s / 4, top + s * 433 / 1000}};
|
case 'W': col = RGB(255, 255, 255); break;
|
||||||
POINT t2[3] = {{cx - s / 4, top + s * 433 / 1000 + 1}, {cx, top + s * 866 / 1000}, {cx - s / 2, top + s * 866 / 1000}};
|
case 'g': col = RGB(207, 216, 220); break;
|
||||||
POINT t3[3] = {{cx + s / 4, top + s * 433 / 1000 + 1}, {cx + s / 2, top + s * 866 / 1000}, {cx, top + s * 866 / 1000}};
|
case 'K': col = RGB(0, 0, 0); break;
|
||||||
Polygon(dc, t1, 3);
|
case 'B': col = RGB(2, 136, 209); break;
|
||||||
Polygon(dc, t2, 3);
|
case 'L': col = RGB(79, 195, 247); break;
|
||||||
Polygon(dc, t3, 3);
|
default: continue;
|
||||||
SelectObject(dc, ob);
|
}
|
||||||
SelectObject(dc, op);
|
HBRUSH b = CreateSolidBrush(col);
|
||||||
|
RECT px = {16 + 4 * x, 18 + 4 * y, 20 + 4 * x, 22 + 4 * y};
|
||||||
|
FillRect(dc, &px, b);
|
||||||
|
DeleteObject(b);
|
||||||
|
}
|
||||||
HFONT big = CreateFontW(-26, 0, 0, 0, FW_SEMIBOLD, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
|
HFONT big = CreateFontW(-26, 0, 0, 0, FW_SEMIBOLD, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
|
||||||
HFONT small = CreateFontW(-16, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
|
HFONT small = CreateFontW(-16, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
|
||||||
SetBkMode(dc, TRANSPARENT);
|
SetBkMode(dc, TRANSPARENT);
|
||||||
SetTextColor(dc, RGB(0xf3, 0xec, 0xdc));
|
SetTextColor(dc, RGB(0xf3, 0xec, 0xdc));
|
||||||
HGDIOBJ of = SelectObject(dc, big);
|
HGDIOBJ of = SelectObject(dc, big);
|
||||||
TextOutW(dc, 96, 30, APP_NAME, (int)wcslen(APP_NAME));
|
TextOutW(dc, 120, 30, APP_NAME, (int)wcslen(APP_NAME));
|
||||||
SelectObject(dc, small);
|
SelectObject(dc, small);
|
||||||
SetTextColor(dc, RGB(0xe9, 0xdc, 0xc0));
|
SetTextColor(dc, RGB(0xe9, 0xdc, 0xc0));
|
||||||
wchar_t line[96];
|
wchar_t line[96];
|
||||||
swprintf(line, 96, L"Installing version %ls\x2026 %llu MB", S.version, (unsigned long long)(S.written >> 20));
|
swprintf(line, 96, L"Installing version %ls\x2026 %llu MB", S.version, (unsigned long long)(S.written >> 20));
|
||||||
TextOutW(dc, 96, 66, line, (int)wcslen(line));
|
TextOutW(dc, 120, 66, line, (int)wcslen(line));
|
||||||
SelectObject(dc, of);
|
SelectObject(dc, of);
|
||||||
DeleteObject(big);
|
DeleteObject(big);
|
||||||
DeleteObject(small);
|
DeleteObject(small);
|
||||||
DeleteObject(gold);
|
|
||||||
DeleteObject(none);
|
|
||||||
DeleteObject(bg);
|
DeleteObject(bg);
|
||||||
DeleteObject(edge);
|
DeleteObject(edge);
|
||||||
EndPaint(w, &ps);
|
EndPaint(w, &ps);
|
||||||
|
|||||||
143
launcher/net.py
143
launcher/net.py
@@ -1,17 +1,37 @@
|
|||||||
"""HTTPS for the launcher: JSON requests and file downloads that resume, report progress, can be cancelled and are
|
"""HTTPS for the launcher: JSON requests and file downloads that resume, report progress, can be cancelled and are
|
||||||
checked against a sha256. Standard library only (urllib); Windows' own certificate store verifies the servers."""
|
checked against a sha256. The standard library (urllib), and on Windows the truststore package of the launcher's
|
||||||
|
Python for Windows' own certificate check.
|
||||||
|
|
||||||
|
Two checks can accept a server's certificate, tried in turn by request():
|
||||||
|
|
||||||
|
- Python's: OpenSSL with the certificates of Windows' ROOT and CA stores (ssl.create_default_context). It knows only
|
||||||
|
the certificates already in those stores, while Windows holds few roots and downloads the others the first time a
|
||||||
|
Windows program needs them. And it takes a stored certificate before the server's copy of the same name and key: a
|
||||||
|
store that still holds an old, expired cross-signature of the root a server's chain leads to makes it report
|
||||||
|
"certificate has expired" for a valid chain (repo.msys2.org's chain on a PC whose CA store still holds the
|
||||||
|
"ISRG Root X2" cross-signature that expired in September 2025).
|
||||||
|
- Windows': Windows' own chain engine, which Windows programs check servers with (CertGetCertificateChain and
|
||||||
|
CertVerifyCertificateChainPolicy, through truststore.SSLContext). It weighs every path the stores and the server
|
||||||
|
allow, prefers a valid one, and downloads a missing root from Windows Update.
|
||||||
|
|
||||||
|
A certificate both refuse ends the request with CertificateError: what each check said, whether the PC's clock agrees
|
||||||
|
with the server's, and what to do."""
|
||||||
|
import email.utils
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import ssl
|
import ssl
|
||||||
import time
|
import time
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
from datetime import timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from . import NAME
|
from . import NAME
|
||||||
|
|
||||||
CHUNK = 1 << 20
|
CHUNK = 1 << 20
|
||||||
|
CLOCK_TOLERANCE = 3600 # seconds between this PC's clock and a server's beyond which this PC's is wrong
|
||||||
|
|
||||||
|
|
||||||
class Cancelled(Exception):
|
class Cancelled(Exception):
|
||||||
@@ -22,26 +42,127 @@ class DownloadError(Exception):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class CertificateError(DownloadError):
|
||||||
|
"""No certificate check accepts a server's certificate. Asking again gets the same answer, so download() does
|
||||||
|
not retry it."""
|
||||||
|
|
||||||
|
|
||||||
def user_agent(version='dev'):
|
def user_agent(version='dev'):
|
||||||
return f'{NAME}-Launcher/{version}'
|
return f'{NAME}-Launcher/{version}'
|
||||||
|
|
||||||
|
|
||||||
_CTX = None
|
def _under_wine():
|
||||||
|
try:
|
||||||
|
import ctypes
|
||||||
|
return hasattr(ctypes.WinDLL('ntdll'), 'wine_get_version')
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _context():
|
def _windows_check():
|
||||||
global _CTX
|
"""An SSLContext that leaves the certificate to Windows' own verifier, or None off Windows, in a Python without
|
||||||
if _CTX is None:
|
truststore (a checkout's own Python) and under Wine. Wine's crypt32 accepts a chain that stops at an issuer it
|
||||||
_CTX = ssl.create_default_context()
|
does not know (CERT_TRUST_IS_PARTIAL_CHAIN passes its SSL policy), and its roots are the host's, which Python's
|
||||||
return _CTX
|
check reads already."""
|
||||||
|
if os.name != 'nt' or _under_wine():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
import truststore
|
||||||
|
return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
except Exception: # not installed, or crypt32 not reachable through ctypes
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
_CHECKS = None # [(name, SSLContext)] in the order request() tries them
|
||||||
|
_ACCEPTED = {} # host -> index into _CHECKS of the check that accepted its certificate last
|
||||||
|
|
||||||
|
|
||||||
|
def _checks():
|
||||||
|
global _CHECKS
|
||||||
|
if _CHECKS is None:
|
||||||
|
checks = [("Python's check", ssl.create_default_context())]
|
||||||
|
windows = _windows_check()
|
||||||
|
if windows is not None:
|
||||||
|
checks.append(("Windows' check", windows))
|
||||||
|
_CHECKS = checks
|
||||||
|
return _CHECKS
|
||||||
|
|
||||||
|
|
||||||
def request(url, headers=None, timeout=30, version='dev'):
|
def request(url, headers=None, timeout=30, version='dev'):
|
||||||
|
"""The open response to a GET of url. An https URL is tried with each certificate check in turn, first the one
|
||||||
|
that accepted the host last, until one accepts the server; CertificateError when none does."""
|
||||||
h = {'User-Agent': user_agent(version)}
|
h = {'User-Agent': user_agent(version)}
|
||||||
h.update(headers or {})
|
h.update(headers or {})
|
||||||
req = urllib.request.Request(url, headers=h)
|
if not url.startswith('https:'):
|
||||||
ctx = _context() if url.startswith('https:') else None
|
return urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout)
|
||||||
return urllib.request.urlopen(req, timeout=timeout, context=ctx)
|
host = urllib.parse.urlsplit(url).hostname or ''
|
||||||
|
checks = _checks()
|
||||||
|
first = min(_ACCEPTED.get(host, 0), len(checks) - 1)
|
||||||
|
refused = []
|
||||||
|
for i in [first] + [i for i in range(len(checks)) if i != first]:
|
||||||
|
name, ctx = checks[i]
|
||||||
|
try:
|
||||||
|
r = urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout, context=ctx)
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
if not isinstance(e.reason, ssl.SSLCertVerificationError):
|
||||||
|
raise
|
||||||
|
refused.append((name, e.reason))
|
||||||
|
continue
|
||||||
|
_ACCEPTED[host] = i
|
||||||
|
return r
|
||||||
|
raise CertificateError(certificate_problem(url, refused, version)) from refused[0][1]
|
||||||
|
|
||||||
|
|
||||||
|
def server_clock(url, timeout=10, version='dev'):
|
||||||
|
"""The time (epoch seconds) of the Date header a plain-HTTP HEAD request to url answers with, without following a
|
||||||
|
redirect, or None without an answer. A PC whose clock is wrong cannot check any certificate, so its clock is
|
||||||
|
compared over HTTP; the answer is not authenticated and only chooses the advice of an error message."""
|
||||||
|
class Stay(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, *args, **kwargs):
|
||||||
|
return None
|
||||||
|
|
||||||
|
req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': user_agent(version)})
|
||||||
|
try:
|
||||||
|
with urllib.request.build_opener(Stay).open(req, timeout=timeout) as r:
|
||||||
|
date = r.headers.get('Date')
|
||||||
|
except urllib.error.HTTPError as e: # the redirect to https, or any other status: its Date is as good
|
||||||
|
date = e.headers.get('Date')
|
||||||
|
e.close()
|
||||||
|
except Exception: # no answer, whatever the reason (refused, timed out, not HTTP)
|
||||||
|
return None
|
||||||
|
if not date:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
when = email.utils.parsedate_to_datetime(date)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return (when if when.tzinfo else when.replace(tzinfo=timezone.utc)).timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def _said(err):
|
||||||
|
said = getattr(err, 'verify_message', None) or (str(err.args[-1]) if err.args else type(err).__name__)
|
||||||
|
return said.strip().rstrip('.')
|
||||||
|
|
||||||
|
|
||||||
|
def _local(t):
|
||||||
|
return time.strftime('%Y-%m-%d %H:%M', time.localtime(t))
|
||||||
|
|
||||||
|
|
||||||
|
def certificate_problem(url, refused, version='dev'):
|
||||||
|
"""The message of a CertificateError for url: what each check in refused ([(name, error)]) said, then the advice
|
||||||
|
that fits this PC's clock."""
|
||||||
|
host = urllib.parse.urlsplit(url).hostname or url
|
||||||
|
said = '; '.join(f'{name}: {_said(e)}' for name, e in refused)
|
||||||
|
text = f'{url}: the certificate of {host} was not accepted ({said}).'
|
||||||
|
where = 'Windows Settings > Time & language > Date & time' if os.name == 'nt' else "the system's settings"
|
||||||
|
ours, theirs = time.time(), server_clock(f'http://{host}/', version=version)
|
||||||
|
if theirs is not None and abs(ours - theirs) > CLOCK_TOLERANCE:
|
||||||
|
return (f"{text} This PC's clock reads {_local(ours)}, but {host} says it is {_local(theirs)}: set the date, "
|
||||||
|
f'time and time zone in {where}, then try again.')
|
||||||
|
clock = (f"This PC's clock agrees with {host}'s." if theirs is not None else
|
||||||
|
f"Check that this PC's date, time and time zone are right ({where}).")
|
||||||
|
return (f'{text} {clock} Security software that scans encrypted connections (HTTPS or SSL scanning) or a proxy '
|
||||||
|
'may be replacing the certificate: let NX2navi through it or turn that scanning off, then try again.')
|
||||||
|
|
||||||
|
|
||||||
def get_bytes(url, headers=None, timeout=30, version='dev', limit=64 << 20):
|
def get_bytes(url, headers=None, timeout=30, version='dev', limit=64 << 20):
|
||||||
@@ -100,7 +221,7 @@ def download(url, dest, sha256=None, size=None, progress=None, cancel=None, head
|
|||||||
if progress:
|
if progress:
|
||||||
progress(done, total or done)
|
progress(done, total or done)
|
||||||
break
|
break
|
||||||
except Cancelled:
|
except (Cancelled, CertificateError):
|
||||||
raise
|
raise
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
if e.code == 416 and have: # the part file is complete or longer than the file: start over
|
if e.code == 416 and have: # the part file is complete or longer than the file: start over
|
||||||
|
|||||||
221
launcher/saves.py
Normal file
221
launcher/saves.py
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
"""Importing a save into the built game, and the saves folder of the game folder.
|
||||||
|
|
||||||
|
The game keeps its save in <game>/profile/save/<account>/ (runtime/fs_host.c storage_init). The folder is named after
|
||||||
|
the local account in <game>/profile/account.uid: 16 bytes, two little-endian 64-bit halves, the low one first; the
|
||||||
|
name is the high half then the low half, 16 hex digits each (runtime/ov_system.c load_uid). A game that never ran has
|
||||||
|
no account yet; the import makes one as the game would. Saves are committed through <game>/profile/save-tx/, where
|
||||||
|
a finished commit (ready-<n>) is newer than save/<account>: an import clears that folder, so the game loads the
|
||||||
|
imported save.
|
||||||
|
|
||||||
|
<game>/saves is the player's side. Import Saves takes a save put there first (its files, or the folder that holds
|
||||||
|
them); otherwise the player picks a folder. Before the save is replaced it is copied to saves/backup <time>, and a
|
||||||
|
save taken from saves/ moves to saves/imported <time>, so nothing is lost and nothing is imported twice.
|
||||||
|
|
||||||
|
A save folder can come from a Switch save backup (the save's files), an emulator (nested folders named by user and
|
||||||
|
title ids, gone down while each holds only one folder), another NX2navi game folder or its profile folder (the
|
||||||
|
account folder inside).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
README = '''NX2navi saves folder
|
||||||
|
|
||||||
|
To import a save, put it here and select Import Saves in the NX2navi launcher (next to Game Folder):
|
||||||
|
- the files of a Switch save backup, or the folder that holds them
|
||||||
|
- an emulator's save folder for the game
|
||||||
|
- the profile folder (or the whole game folder) of another NX2navi install
|
||||||
|
|
||||||
|
You can also select Import Saves and choose the folder instead.
|
||||||
|
|
||||||
|
Before a save is imported, the game's current save is copied here into a folder named "backup" and the date. An
|
||||||
|
imported save moves into a folder named "imported" and the date. The game itself keeps its save in profile\\save.
|
||||||
|
'''
|
||||||
|
HEX32 = re.compile(r'^[0-9a-fA-F]{32}$')
|
||||||
|
MAX_FILES, MAX_BYTES = 4000, 1 << 30 # a save is a few files of a few MB; more is a folder picked by mistake
|
||||||
|
OURS = re.compile(r'^(backup|imported) \d{4}-\d\d-\d\d') # what this module writes into saves/
|
||||||
|
|
||||||
|
|
||||||
|
class SaveError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def saves_dir(game):
|
||||||
|
return Path(game) / 'saves'
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_saves_dir(game):
|
||||||
|
"""<game>/saves with its README.txt."""
|
||||||
|
d = saves_dir(game)
|
||||||
|
d.mkdir(parents=True, exist_ok=True)
|
||||||
|
readme = d / 'README.txt'
|
||||||
|
if not readme.is_file():
|
||||||
|
readme.write_text(README, encoding='utf-8', newline='\r\n')
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def account_dir(game):
|
||||||
|
"""The game's save folder for its local account, making the account as the game does when it has none."""
|
||||||
|
prof = Path(game) / 'profile'
|
||||||
|
f = prof / 'account.uid'
|
||||||
|
data = f.read_bytes() if f.is_file() else b''
|
||||||
|
if not data:
|
||||||
|
data = bytes(16)
|
||||||
|
while data == bytes(16):
|
||||||
|
data = os.urandom(16)
|
||||||
|
prof.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp = f.with_name('account.uid.tmp')
|
||||||
|
tmp.write_bytes(data)
|
||||||
|
os.replace(tmp, f)
|
||||||
|
if len(data) != 16 or data == bytes(16):
|
||||||
|
raise SaveError(f'{f} is not an account file of the game')
|
||||||
|
lo, hi = int.from_bytes(data[:8], 'little'), int.from_bytes(data[8:], 'little')
|
||||||
|
return prof / 'save' / f'{hi:016x}{lo:016x}'
|
||||||
|
|
||||||
|
|
||||||
|
def _fresh(folder, name):
|
||||||
|
"""folder/name, or folder/"name (2)" and so on when that is taken (two imports in one second)."""
|
||||||
|
p, n = folder / name, 2
|
||||||
|
while p.exists():
|
||||||
|
p, n = folder / f'{name} ({n})', n + 1
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def _entries(folder, skip=()):
|
||||||
|
return [e for e in Path(folder).iterdir() if e.name not in skip and not e.name.startswith('.')]
|
||||||
|
|
||||||
|
|
||||||
|
def find_save(folder):
|
||||||
|
"""(source folder, top-level names to leave out) of the save in folder, or (None, ()) when it holds none."""
|
||||||
|
p = Path(folder)
|
||||||
|
if not p.is_dir():
|
||||||
|
return None, ()
|
||||||
|
for base in (p / 'profile' / 'save', p / 'save'): # another game folder, or its profile folder
|
||||||
|
if base.is_dir():
|
||||||
|
accounts = [d for d in base.iterdir() if d.is_dir() and HEX32.match(d.name)]
|
||||||
|
if accounts:
|
||||||
|
return max(accounts, key=lambda d: d.stat().st_mtime), ()
|
||||||
|
for _ in range(8): # nested id folders: go down while the folder holds a single folder and no file
|
||||||
|
entries = _entries(p)
|
||||||
|
dirs = [e for e in entries if e.is_dir()]
|
||||||
|
if len(entries) != 1 or len(dirs) != 1:
|
||||||
|
break
|
||||||
|
p = dirs[0]
|
||||||
|
return (p, ()) if _has_file(p) else (None, ())
|
||||||
|
|
||||||
|
|
||||||
|
def waiting(game):
|
||||||
|
"""(source, names to leave out) of a save put into <game>/saves, or (None, ())."""
|
||||||
|
d = saves_dir(game)
|
||||||
|
if not d.is_dir():
|
||||||
|
return None, ()
|
||||||
|
skip = {'README.txt'} | {e.name for e in d.iterdir() if e.is_dir() and OURS.match(e.name)}
|
||||||
|
entries = _entries(d, skip)
|
||||||
|
if not entries:
|
||||||
|
return None, ()
|
||||||
|
if len(entries) == 1 and entries[0].is_dir():
|
||||||
|
return find_save(entries[0])
|
||||||
|
return (d, tuple(sorted(skip))) if any(e.is_file() or _has_file(e) for e in entries) else (None, ())
|
||||||
|
|
||||||
|
|
||||||
|
def _has_file(folder):
|
||||||
|
return any(files for _, _, files in os.walk(folder))
|
||||||
|
|
||||||
|
|
||||||
|
def _files(src, skip):
|
||||||
|
"""Relative paths of the files to import; SaveError when there are too many or too large to be a save."""
|
||||||
|
out, size = [], 0
|
||||||
|
for root, dirs, files in os.walk(src):
|
||||||
|
if Path(root) == Path(src):
|
||||||
|
dirs[:] = [d for d in dirs if d not in skip and not d.startswith('.')]
|
||||||
|
files = [f for f in files if f not in skip and not f.startswith('.')]
|
||||||
|
for f in files:
|
||||||
|
p = Path(root) / f
|
||||||
|
out.append(p.relative_to(src))
|
||||||
|
size += p.stat().st_size
|
||||||
|
if len(out) > MAX_FILES or size > MAX_BYTES:
|
||||||
|
raise SaveError(f'{src} holds more than a save ({len(out)} files, {size / 1e6:.0f} MB so far); '
|
||||||
|
'choose the folder with the save\'s files')
|
||||||
|
if not out:
|
||||||
|
raise SaveError(f'{src} holds no files')
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _newest(game, account):
|
||||||
|
"""The folder the game would load now: a finished commit still waiting in save-tx, else the account folder."""
|
||||||
|
tx = Path(game) / 'profile' / 'save-tx'
|
||||||
|
ready = []
|
||||||
|
if tx.is_dir():
|
||||||
|
for d in tx.iterdir():
|
||||||
|
m = re.fullmatch(r'ready-(\d+)', d.name)
|
||||||
|
if m and d.is_dir():
|
||||||
|
ready.append((int(m.group(1)), d))
|
||||||
|
if ready:
|
||||||
|
return max(ready)[1]
|
||||||
|
return account if account.is_dir() else None
|
||||||
|
|
||||||
|
|
||||||
|
def game_running(game):
|
||||||
|
"""Windows: ocarina.exe cannot be opened for writing while it runs."""
|
||||||
|
exe = Path(game) / 'ocarina.exe'
|
||||||
|
if os.name != 'nt' or not exe.is_file():
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
with open(exe, 'r+b'):
|
||||||
|
return False
|
||||||
|
except PermissionError:
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def import_save(game, folder=None, log=print):
|
||||||
|
"""Make the save in folder (None: the one waiting in <game>/saves) the game's save. Returns {'files', 'source',
|
||||||
|
'backup'}; backup is the folder the replaced save went to, or None when there was none."""
|
||||||
|
game = Path(game)
|
||||||
|
from_saves = folder is None
|
||||||
|
src, skip = waiting(game) if from_saves else find_save(folder)
|
||||||
|
if src is None:
|
||||||
|
raise SaveError('the saves folder holds no save' if from_saves else f'{folder} holds no save files')
|
||||||
|
prof = (game / 'profile').resolve()
|
||||||
|
if Path(src).resolve() == prof or prof in Path(src).resolve().parents:
|
||||||
|
raise SaveError('that is the game\'s own save')
|
||||||
|
files = _files(src, set(skip))
|
||||||
|
account = account_dir(game)
|
||||||
|
saves = ensure_saves_dir(game)
|
||||||
|
stamp = time.strftime('%Y-%m-%d %H.%M.%S')
|
||||||
|
backup = None
|
||||||
|
current = _newest(game, account)
|
||||||
|
if current is not None and _has_file(current):
|
||||||
|
backup = _fresh(saves, f'backup {stamp}')
|
||||||
|
shutil.copytree(current, backup)
|
||||||
|
tx = game / 'profile' / 'save-tx'
|
||||||
|
tx.mkdir(parents=True, exist_ok=True)
|
||||||
|
stage = tx / 'import'
|
||||||
|
shutil.rmtree(stage, ignore_errors=True)
|
||||||
|
for rel in files:
|
||||||
|
(stage / rel).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(Path(src) / rel, stage / rel)
|
||||||
|
for d in list(tx.iterdir()): # the journal of the replaced save: the game would load a finished commit first
|
||||||
|
if d != stage:
|
||||||
|
shutil.rmtree(d, ignore_errors=True) if d.is_dir() else d.unlink(missing_ok=True)
|
||||||
|
account.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if account.exists():
|
||||||
|
gone = tx / 'replaced'
|
||||||
|
os.replace(account, gone)
|
||||||
|
shutil.rmtree(gone, ignore_errors=True)
|
||||||
|
os.replace(stage, account)
|
||||||
|
if from_saves: # what was put into saves/ moves out whole, so the next import does not take any of it again
|
||||||
|
done = _fresh(saves, f'imported {stamp}')
|
||||||
|
done.mkdir()
|
||||||
|
if Path(src) == saves:
|
||||||
|
top = sorted({rel.parts[0] for rel in files})
|
||||||
|
else: # the save sits in a folder that was put there (a game folder, an emulator's id folders)
|
||||||
|
top = [Path(src).relative_to(saves).parts[0]]
|
||||||
|
for name in top:
|
||||||
|
shutil.move(str(saves / name), str(done / name))
|
||||||
|
log(f'saves: imported {len(files)} files from {src} into {account}' + (f'; the old save is in {backup}' if backup
|
||||||
|
else ''))
|
||||||
|
return {'files': len(files), 'source': Path(src), 'backup': backup}
|
||||||
@@ -8,6 +8,10 @@ toolchain.lock.json (make_lock, written by tools/make_launcher.py), so every pla
|
|||||||
release was tested with; the repository keeps old package files. A checkout without a lock resolves the newest
|
release was tested with; the repository keeps old package files. A checkout without a lock resolves the newest
|
||||||
packages instead.
|
packages instead.
|
||||||
|
|
||||||
|
Beside it goes the clang of MSYS2's CLANG64 environment (toolchain/msys64/clang64), the same LLVM release built with
|
||||||
|
profile-guided optimisation: it compiles the lifted code about a fifth faster into the same objects, reading UCRT64's
|
||||||
|
headers (tools/make_game.py fast_clang). Only clang.exe, the DLLs it loads and its own headers are unpacked.
|
||||||
|
|
||||||
zbic (GPL-2.0) unpacks the game's compressed program files. The release does not carry it: the launcher downloads the
|
zbic (GPL-2.0) unpacks the game's compressed program files. The release does not carry it: the launcher downloads the
|
||||||
wheel for its own Python from PyPI and unpacks it into pydeps/, as `pip install zbic` would.
|
wheel for its own Python from PyPI and unpacks it into pydeps/, as `pip install zbic` would.
|
||||||
"""
|
"""
|
||||||
@@ -28,11 +32,17 @@ from . import net
|
|||||||
REPO = 'https://repo.msys2.org/mingw/ucrt64/'
|
REPO = 'https://repo.msys2.org/mingw/ucrt64/'
|
||||||
MIRRORS = (REPO, 'https://mirror.msys2.org/mingw/ucrt64/')
|
MIRRORS = (REPO, 'https://mirror.msys2.org/mingw/ucrt64/')
|
||||||
PREFIX = 'mingw-w64-ucrt-x86_64-'
|
PREFIX = 'mingw-w64-ucrt-x86_64-'
|
||||||
ROOTS = ('clang', 'gcc', 'sdl3', 'opus', 'libvpx', 'dav1d', 'zstd', 'vulkan-headers', 'vulkan-loader',
|
ROOTS = ('clang', 'gcc', 'lld', 'sdl3', 'opus', 'libvpx', 'dav1d', 'zstd', 'vulkan-headers', 'vulkan-loader',
|
||||||
'vulkan-memory-allocator')
|
'vulkan-memory-allocator') # lld: the game links several times faster than with GNU ld
|
||||||
REQUIRED = ('bin/clang.exe', 'bin/clang++.exe', 'bin/SDL3.dll', 'lib/libSDL3.dll.a', 'include/vma')
|
REQUIRED = ('bin/clang.exe', 'bin/clang++.exe', 'bin/SDL3.dll', 'lib/libSDL3.dll.a', 'include/vma')
|
||||||
SKIP_SHARE = ('ucrt64/share/doc/', 'ucrt64/share/man/', 'ucrt64/share/info/', 'ucrt64/share/locale/',
|
SKIP_SHARE = ('ucrt64/share/doc/', 'ucrt64/share/man/', 'ucrt64/share/info/', 'ucrt64/share/locale/',
|
||||||
'ucrt64/share/gtk-doc/', 'ucrt64/share/licenses/')
|
'ucrt64/share/gtk-doc/', 'ucrt64/share/licenses/')
|
||||||
|
# CLANG64's clang: exactly the packages clang.exe loads DLLs from (not the dependency closure, which adds the linker,
|
||||||
|
# the LLVM tools and the CLANG64 C runtime the lifted code does not use).
|
||||||
|
FAST_REPO = 'https://repo.msys2.org/mingw/clang64/'
|
||||||
|
FAST_MIRRORS = (FAST_REPO, 'https://mirror.msys2.org/mingw/clang64/')
|
||||||
|
FAST_PREFIX = 'mingw-w64-clang-x86_64-'
|
||||||
|
FAST_PACKAGES = ('clang', 'clang-libs', 'llvm-libs', 'libc++', 'libffi', 'zlib', 'zstd', 'libxml2', 'libiconv')
|
||||||
ZBIC = ('zbic', '1.0.1.post1')
|
ZBIC = ('zbic', '1.0.1.post1')
|
||||||
LOCK_FORMAT = 1
|
LOCK_FORMAT = 1
|
||||||
|
|
||||||
@@ -101,19 +111,37 @@ def resolve(db, roots=ROOTS):
|
|||||||
seen.add(n)
|
seen.add(n)
|
||||||
order.append(n)
|
order.append(n)
|
||||||
todo += db[n].get('DEPENDS', [])
|
todo += db[n].get('DEPENDS', [])
|
||||||
pkgs = []
|
return [_pkg(db, n) for n in order]
|
||||||
for n in order:
|
|
||||||
d = db[n]
|
|
||||||
pkgs.append({'name': n, 'version': d['VERSION'][0], 'filename': d['FILENAME'][0],
|
|
||||||
'sha256': d['SHA256SUM'][0], 'csize': int(d['CSIZE'][0]), 'isize': int(d.get('ISIZE', ['0'])[0])})
|
|
||||||
return pkgs
|
|
||||||
|
|
||||||
|
|
||||||
def make_lock(repo=REPO, roots=ROOTS, version='dev'):
|
def make_lock(repo=REPO, roots=ROOTS, version='dev', fast_repo=None):
|
||||||
"""The lock a release ships: the resolved package files of the repository's current database."""
|
"""The lock a release ships: the resolved package files of the repository's current database. With fast_repo
|
||||||
|
(FAST_REPO), also CLANG64's clang, when that repository has the same clang version as UCRT64's."""
|
||||||
db = parse_db(net.get_bytes(repo + 'ucrt64.db', version=version))
|
db = parse_db(net.get_bytes(repo + 'ucrt64.db', version=version))
|
||||||
return {'format': LOCK_FORMAT, 'repo': repo, 'roots': list(roots), 'packages': resolve(db, roots),
|
pkgs = resolve(db, roots)
|
||||||
|
lock = {'format': LOCK_FORMAT, 'repo': repo, 'roots': list(roots), 'packages': pkgs,
|
||||||
'zbic': {'name': ZBIC[0], 'version': ZBIC[1]}, 'made': time.strftime('%Y-%m-%d')}
|
'zbic': {'name': ZBIC[0], 'version': ZBIC[1]}, 'made': time.strftime('%Y-%m-%d')}
|
||||||
|
if fast_repo:
|
||||||
|
fdb = parse_db(net.get_bytes(fast_repo + 'clang64.db', version=version))
|
||||||
|
fast = [_pkg(fdb, FAST_PREFIX + n, env='clang64') for n in FAST_PACKAGES]
|
||||||
|
mine = next(p['version'] for p in pkgs if p['name'] == PREFIX + 'clang')
|
||||||
|
if fast[0]['version'] == mine:
|
||||||
|
lock['packages'] = pkgs + fast
|
||||||
|
lock['fast_repo'] = fast_repo
|
||||||
|
else:
|
||||||
|
lock['fast_skipped'] = f'CLANG64 has clang {fast[0]["version"]}, UCRT64 {mine}'
|
||||||
|
return lock
|
||||||
|
|
||||||
|
|
||||||
|
def _pkg(db, name, env=None):
|
||||||
|
if name not in db:
|
||||||
|
raise ToolchainError(f'the package database has no {name}')
|
||||||
|
d = db[name]
|
||||||
|
p = {'name': name, 'version': d['VERSION'][0], 'filename': d['FILENAME'][0], 'sha256': d['SHA256SUM'][0],
|
||||||
|
'csize': int(d['CSIZE'][0]), 'isize': int(d.get('ISIZE', ['0'])[0])}
|
||||||
|
if env:
|
||||||
|
p['env'] = env
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
def lock_digest(lock):
|
def lock_digest(lock):
|
||||||
@@ -150,9 +178,18 @@ def is_current(layout, lock):
|
|||||||
return bool(inst) and inst.get('digest') == lock_digest(lock) and not missing_files(layout.msys)
|
return bool(inst) and inst.get('digest') == lock_digest(lock) and not missing_files(layout.msys)
|
||||||
|
|
||||||
|
|
||||||
def _extract_package(path, dest):
|
def _wanted(name, env):
|
||||||
"""Unpack one .pkg.tar.zst into dest (the msys64 folder): only its ucrt64/ files, without the documentation.
|
"""Whether a package member is unpacked: UCRT64's files without the documentation; of CLANG64's, clang.exe, the
|
||||||
The archive is read as a stream, member by member, so a 350 MB package never sits in memory whole."""
|
DLLs and clang's own headers."""
|
||||||
|
if env == 'clang64':
|
||||||
|
return (name == 'clang64/bin/clang.exe' or (name.startswith('clang64/bin/') and name.endswith('.dll'))
|
||||||
|
or name.startswith('clang64/lib/clang/'))
|
||||||
|
return name.startswith('ucrt64/') and not name.startswith(SKIP_SHARE)
|
||||||
|
|
||||||
|
|
||||||
|
def _members(path):
|
||||||
|
"""The members of a .pkg.tar.zst (or plain tar), read as a stream, member by member, so a 350 MB package never
|
||||||
|
sits in memory whole. Yields (tarfile, member)."""
|
||||||
with open(path, 'rb') as raw:
|
with open(path, 'rb') as raw:
|
||||||
zst = raw.read(4) == b'\x28\xb5\x2f\xfd'
|
zst = raw.read(4) == b'\x28\xb5\x2f\xfd'
|
||||||
raw.seek(0)
|
raw.seek(0)
|
||||||
@@ -167,9 +204,22 @@ def _extract_package(path, dest):
|
|||||||
fileobj = raw
|
fileobj = raw
|
||||||
with tarfile.open(fileobj=fileobj, mode='r|*') as t:
|
with tarfile.open(fileobj=fileobj, mode='r|*') as t:
|
||||||
for m in t:
|
for m in t:
|
||||||
name = m.name.lstrip('./')
|
yield t, m
|
||||||
if name.startswith('ucrt64/') and not name.startswith(SKIP_SHARE):
|
|
||||||
t.extract(m, dest, filter='data')
|
|
||||||
|
def _extract_package(path, dest, env=None):
|
||||||
|
"""Unpack one package into dest (the msys64 folder): the members _wanted keeps. A wanted hard link needs its
|
||||||
|
target on disk, and a stream cannot go back for it: a selective unpack (env) first reads the headers for the
|
||||||
|
targets of the wanted links (CLANG64's clang.exe is one) and unpacks them too."""
|
||||||
|
want = set()
|
||||||
|
if env:
|
||||||
|
for _, m in _members(path):
|
||||||
|
if m.islnk() and _wanted(m.name.lstrip('./'), env):
|
||||||
|
want.add(m.linkname.lstrip('./'))
|
||||||
|
for t, m in _members(path):
|
||||||
|
name = m.name.lstrip('./')
|
||||||
|
if name in want or _wanted(name, env):
|
||||||
|
t.extract(m, dest, filter='data')
|
||||||
|
|
||||||
|
|
||||||
def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
|
def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
|
||||||
@@ -185,7 +235,9 @@ def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
|
|||||||
for p in need:
|
for p in need:
|
||||||
dest = layout.pkgs / p['filename']
|
dest = layout.pkgs / p['filename']
|
||||||
last_error = None
|
last_error = None
|
||||||
for mirror in [lock.get('repo', REPO)] + [m for m in MIRRORS if m != lock.get('repo', REPO)]:
|
first, others = ((lock.get('fast_repo', FAST_REPO), FAST_MIRRORS) if p.get('env') == 'clang64'
|
||||||
|
else (lock.get('repo', REPO), MIRRORS))
|
||||||
|
for mirror in [first] + [m for m in others if m != first]:
|
||||||
try:
|
try:
|
||||||
net.download(mirror + p['filename'], dest, sha256=p['sha256'], size=p['csize'], cancel=cancel,
|
net.download(mirror + p['filename'], dest, sha256=p['sha256'], size=p['csize'], cancel=cancel,
|
||||||
progress=(lambda d, t, base=done_before: progress and progress('download', base + d, total)),
|
progress=(lambda d, t, base=done_before: progress and progress('download', base + d, total)),
|
||||||
@@ -210,7 +262,7 @@ def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
|
|||||||
raise net.Cancelled()
|
raise net.Cancelled()
|
||||||
if progress:
|
if progress:
|
||||||
progress('unpack', i, len(pkgs))
|
progress('unpack', i, len(pkgs))
|
||||||
_extract_package(layout.pkgs / p['filename'], staging)
|
_extract_package(layout.pkgs / p['filename'], staging, p.get('env'))
|
||||||
if progress:
|
if progress:
|
||||||
progress('unpack', len(pkgs), len(pkgs))
|
progress('unpack', len(pkgs), len(pkgs))
|
||||||
missing = missing_files(staging / 'ucrt64')
|
missing = missing_files(staging / 'ucrt64')
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""The launcher's window, laid out like the game's options menu (docs/launcher.md, "Look"): a wooden title band with
|
"""The launcher's window, laid out like the game's options menu (docs/launcher.md, "Look"): a wooden title band with
|
||||||
the Triforce and the name in the game's Cetra Display, a list of rows on the left (a bronze label cell and a dark value cell each), a white
|
Navi and the name in the game's Cetra Display across the whole top (the window's own title bar: drag it to move the
|
||||||
|
window, minimise and close at its right end), a list of rows on the left (a bronze label cell and a dark value cell each), a white
|
||||||
glowing cursor on the selected row, filigree dividers between groups and a description box on the right that
|
glowing cursor on the selected row, filigree dividers between groups and a description box on the right that
|
||||||
explains the selected row.
|
explains the selected row.
|
||||||
|
|
||||||
@@ -25,12 +26,13 @@ import tkinter.font as tkfont
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tkinter import filedialog
|
from tkinter import filedialog
|
||||||
|
|
||||||
from .. import NAME, build, feed, gamefiles, jobs, versions, winsys
|
from .. import NAME, build, feed, gamefiles, jobs, saves, versions, winsys
|
||||||
from ..context import Context
|
from ..context import Context
|
||||||
from . import art
|
from . import art
|
||||||
|
|
||||||
W, H = 1000, 640
|
W, H = 1000, 640
|
||||||
BAND = (52, 948, 56) # x0, x1, height
|
BAND = (0, 1000, 56) # x0, x1, height: the whole top of the window, which is also its title bar
|
||||||
|
TITLE_BUTTONS = (('min', 908, 954), ('close', 954, 1000)) # x ranges on the band
|
||||||
PANEL = (112, 60, 580) # x0, top, x1
|
PANEL = (112, 60, 580) # x0, top, x1
|
||||||
ROWS = (140, 552, 96) # x0, x1, top
|
ROWS = (140, 552, 96) # x0, x1, top
|
||||||
LABEL_W = 222 # 54 % of the row
|
LABEL_W = 222 # 54 % of the row
|
||||||
@@ -105,6 +107,7 @@ class App:
|
|||||||
self.check_error = ''
|
self.check_error = ''
|
||||||
self.checked_at = 0.0
|
self.checked_at = 0.0
|
||||||
self.message = ''
|
self.message = ''
|
||||||
|
self.save_message = '' # the last Import Saves result, shown in its description
|
||||||
self.dumps = None
|
self.dumps = None
|
||||||
self.dump_search = None
|
self.dump_search = None
|
||||||
self.uninstall_game = False
|
self.uninstall_game = False
|
||||||
@@ -112,6 +115,9 @@ class App:
|
|||||||
self.cursor_frames, self.cursor_k = [], 0
|
self.cursor_frames, self.cursor_k = [], 0
|
||||||
self.last_second = 0
|
self.last_second = 0
|
||||||
self.gamepad = winsys.Gamepad()
|
self.gamepad = winsys.Gamepad()
|
||||||
|
self.tb_hover = None
|
||||||
|
self.drag = None
|
||||||
|
self.ico = None
|
||||||
|
|
||||||
root.title(NAME)
|
root.title(NAME)
|
||||||
root.resizable(False, False)
|
root.resizable(False, False)
|
||||||
@@ -128,6 +134,8 @@ class App:
|
|||||||
self.root.after(150, self.tick)
|
self.root.after(150, self.tick)
|
||||||
self.root.after(50, self.poll_gamepad)
|
self.root.after(50, self.poll_gamepad)
|
||||||
self.center()
|
self.center()
|
||||||
|
self.framed = not winsys.frameless(root) # Windows: the band is the title bar
|
||||||
|
self.root.after(60, self.native_window)
|
||||||
|
|
||||||
# ---------------------------------------------------------------- scale, icon, fonts
|
# ---------------------------------------------------------------- scale, icon, fonts
|
||||||
|
|
||||||
@@ -151,17 +159,27 @@ class App:
|
|||||||
self.root.geometry(f'{w}x{h}+{x}+{y}')
|
self.root.geometry(f'{w}x{h}+{x}+{y}')
|
||||||
|
|
||||||
def set_icon(self):
|
def set_icon(self):
|
||||||
|
"""Navi as the window's icon: Tk's photo icon everywhere, and on Windows the .ico set on the window itself, so
|
||||||
|
the taskbar button shows Navi rather than Python's icon."""
|
||||||
try:
|
try:
|
||||||
self.photos['icon'] = art.photo(self.root, art.triforce(64))
|
self.photos['icon'] = art.photo(self.root, art.navi_icon(64))
|
||||||
self.root.iconphoto(True, self.photos['icon'])
|
self.root.iconphoto(True, self.photos['icon'])
|
||||||
if os.name == 'nt':
|
if os.name == 'nt':
|
||||||
ico = self.layout.cache / 'nx2navi.ico'
|
data = art.navi_ico()
|
||||||
if not ico.is_file():
|
self.ico = self.layout.cache / 'nx2navi.ico'
|
||||||
ico.write_bytes(art.triforce_ico())
|
if not self.ico.is_file() or self.ico.read_bytes() != data:
|
||||||
self.root.iconbitmap(default=str(ico))
|
self.ico.write_bytes(data)
|
||||||
except (tk.TclError, OSError) as e:
|
except (tk.TclError, OSError) as e:
|
||||||
self.ctx.log(f'icon: {e}')
|
self.ctx.log(f'icon: {e}')
|
||||||
|
|
||||||
|
def native_window(self):
|
||||||
|
if self.ico:
|
||||||
|
winsys.set_window_icon(self.root, self.ico)
|
||||||
|
try:
|
||||||
|
self.root.focus_force()
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
|
||||||
def load_fonts(self):
|
def load_fonts(self):
|
||||||
"""The game's Cetra Display when this PC has decoded it from the player's game (data/cache/fonts), else the
|
"""The game's Cetra Display when this PC has decoded it from the player's game (data/cache/fonts), else the
|
||||||
system's interface font."""
|
system's interface font."""
|
||||||
@@ -239,23 +257,47 @@ class App:
|
|||||||
c.create_image(0, 0, anchor='nw', image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s)),
|
c.create_image(0, 0, anchor='nw', image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s)),
|
||||||
tags='static')
|
tags='static')
|
||||||
bx0, bx1, bh = BAND
|
bx0, bx1, bh = BAND
|
||||||
c.create_image(self.X(bx0), 0, anchor='nw', tags='static',
|
|
||||||
image=self.sprite('band', lambda: art.band(self.X(bx1) - self.X(bx0), self.X(bh), s)))
|
|
||||||
px0, ptop, px1 = PANEL
|
px0, ptop, px1 = PANEL
|
||||||
c.create_image(self.X(px0), self.X(ptop), anchor='nw', tags='static',
|
c.create_image(self.X(px0), self.X(ptop), anchor='nw', tags='static',
|
||||||
image=self.sprite('panel', lambda: art.panel(self.X(px1) - self.X(px0), self.X(H - ptop), s)))
|
image=self.sprite('panel', lambda: art.panel(self.X(px1) - self.X(px0), self.X(H - ptop), s)))
|
||||||
tri = self.sprite('triforce', lambda: art.triforce(self.X(44)))
|
c.create_image(self.X(bx0), 0, anchor='nw', tags='static',
|
||||||
|
image=self.sprite('band', lambda: art.band(self.X(bx1) - self.X(bx0), self.X(bh), s)))
|
||||||
|
k = max(1, int(round(2 * s))) # Navi in whole pixels: two screen pixels per artwork pixel at 100 %
|
||||||
|
emblem = self.sprite(('navi', k), lambda: art.navi(k))
|
||||||
|
ew = emblem.width()
|
||||||
title_w = self.f['band'].measure(NAME)
|
title_w = self.f['band'].measure(NAME)
|
||||||
gap = self.X(12)
|
gap = self.X(12)
|
||||||
total = self.X(44) + gap + title_w
|
x = self.X(W / 2) - (ew + gap + title_w) // 2
|
||||||
x = self.X(W / 2) - total // 2
|
c.create_image(x, self.X(bh / 2), anchor='w', image=emblem, tags='static')
|
||||||
c.create_image(x, self.X(bh / 2), anchor='w', image=tri, tags='static')
|
tx = x + ew + gap
|
||||||
tx = x + self.X(44) + gap
|
|
||||||
c.create_text(tx + 1, self.X(bh / 2) + self.X(2), text=NAME, anchor='w', font=self.f['band'], fill='#1a120a',
|
c.create_text(tx + 1, self.X(bh / 2) + self.X(2), text=NAME, anchor='w', font=self.f['band'], fill='#1a120a',
|
||||||
tags='static')
|
tags='static')
|
||||||
c.create_text(tx, self.X(bh / 2), text=NAME, anchor='w', font=self.f['band'], fill=P['band_text'],
|
c.create_text(tx, self.X(bh / 2), text=NAME, anchor='w', font=self.f['band'], fill=P['band_text'],
|
||||||
tags='static')
|
tags='static')
|
||||||
|
c.create_rectangle(0, 0, self.X(W) - 1, self.X(H) - 1, outline='#140e09', tags='static')
|
||||||
c.tag_lower('static')
|
c.tag_lower('static')
|
||||||
|
self.draw_title_buttons()
|
||||||
|
|
||||||
|
def draw_title_buttons(self):
|
||||||
|
"""Minimise and close at the band's right end, lit when the mouse is over them."""
|
||||||
|
c, X = self.canvas, self.X
|
||||||
|
c.delete('tb')
|
||||||
|
bh = X(BAND[2])
|
||||||
|
for kind, x0, x1 in TITLE_BUTTONS:
|
||||||
|
if self.tb_hover == kind:
|
||||||
|
c.create_rectangle(X(x0), 0, X(x1), bh - 1, outline='', tags='tb',
|
||||||
|
fill=P['close_hover'] if kind == 'close' else P['button_hover'])
|
||||||
|
size = X(12)
|
||||||
|
glyph = self.sprite(('glyph', kind, size), lambda kd=kind: art.title_glyph(kd, size, self.s))
|
||||||
|
c.create_image((X(x0) + X(x1)) // 2, bh // 2, image=glyph, tags='tb')
|
||||||
|
|
||||||
|
def title_button_at(self, x, y):
|
||||||
|
if y >= self.X(BAND[2]):
|
||||||
|
return None
|
||||||
|
for kind, x0, x1 in TITLE_BUTTONS:
|
||||||
|
if self.X(x0) <= x < self.X(x1):
|
||||||
|
return kind
|
||||||
|
return None
|
||||||
|
|
||||||
# ---------------------------------------------------------------- input
|
# ---------------------------------------------------------------- input
|
||||||
|
|
||||||
@@ -269,6 +311,10 @@ class App:
|
|||||||
r.bind(key, fn)
|
r.bind(key, fn)
|
||||||
self.canvas.bind('<Motion>', self.on_motion)
|
self.canvas.bind('<Motion>', self.on_motion)
|
||||||
self.canvas.bind('<Button-1>', self.on_click)
|
self.canvas.bind('<Button-1>', self.on_click)
|
||||||
|
self.canvas.bind('<B1-Motion>', self.on_drag)
|
||||||
|
self.canvas.bind('<ButtonRelease-1>', lambda e: setattr(self, 'drag', None))
|
||||||
|
self.canvas.bind('<Leave>', lambda e: self.set_tb_hover(None))
|
||||||
|
r.bind('<Alt-F4>', lambda e: self.on_close())
|
||||||
r.protocol('WM_DELETE_WINDOW', self.on_close)
|
r.protocol('WM_DELETE_WINDOW', self.on_close)
|
||||||
|
|
||||||
def poll_gamepad(self):
|
def poll_gamepad(self):
|
||||||
@@ -344,7 +390,18 @@ class App:
|
|||||||
return i
|
return i
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def set_tb_hover(self, kind):
|
||||||
|
if kind != self.tb_hover:
|
||||||
|
self.tb_hover = kind
|
||||||
|
self.draw_title_buttons()
|
||||||
|
|
||||||
|
def on_drag(self, e):
|
||||||
|
if self.drag: # moving the window without the system's help (Linux)
|
||||||
|
dx, dy = self.drag
|
||||||
|
self.root.geometry(f'+{e.x_root - dx}+{e.y_root - dy}')
|
||||||
|
|
||||||
def on_motion(self, e):
|
def on_motion(self, e):
|
||||||
|
self.set_tb_hover(self.title_button_at(e.x, e.y))
|
||||||
i = self.hit(e.x, e.y)
|
i = self.hit(e.x, e.y)
|
||||||
if i is not None and i != self.focus:
|
if i is not None and i != self.focus:
|
||||||
self.focus = i
|
self.focus = i
|
||||||
@@ -360,6 +417,22 @@ class App:
|
|||||||
self.render()
|
self.render()
|
||||||
|
|
||||||
def on_click(self, e):
|
def on_click(self, e):
|
||||||
|
try:
|
||||||
|
self.root.focus_force()
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
kind = self.title_button_at(e.x, e.y)
|
||||||
|
if kind == 'close':
|
||||||
|
self.on_close()
|
||||||
|
return
|
||||||
|
if kind == 'min':
|
||||||
|
self.set_tb_hover(None)
|
||||||
|
winsys.minimize(self.root)
|
||||||
|
return
|
||||||
|
if e.y < self.X(BAND[2]): # the band moves the window, like a title bar
|
||||||
|
if not winsys.start_drag(self.root):
|
||||||
|
self.drag = (e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y())
|
||||||
|
return
|
||||||
i = self.hit(e.x, e.y)
|
i = self.hit(e.x, e.y)
|
||||||
if i is None:
|
if i is None:
|
||||||
return
|
return
|
||||||
@@ -597,8 +670,9 @@ class App:
|
|||||||
upd,
|
upd,
|
||||||
Row('divider'),
|
Row('divider'),
|
||||||
Row('value', 'Game Folder', gd, on=lambda: self.open(gd),
|
Row('value', 'Game Folder', gd, on=lambda: self.open(gd),
|
||||||
desc=('Open the game folder. Your saves are in its profile folder, the game\'s settings in '
|
desc=('Open the game folder. The game keeps your save in its profile folder, its settings in '
|
||||||
'nx2navi.ini and its logs in logs.',)),
|
'nx2navi.ini and its logs in logs. Its saves folder is for saves to import.',)),
|
||||||
|
self.saves_row(gd),
|
||||||
Row('value', 'Rebuild the Game', rebuild_value, rebuild_style, on=self.start_rebuild,
|
Row('value', 'Rebuild the Game', rebuild_value, rebuild_style, on=self.start_rebuild,
|
||||||
desc=('Build the game again from the files of the last build. Only what changed is compiled. Use it '
|
desc=('Build the game again from the files of the last build. Only what changed is compiled. Use it '
|
||||||
'after changing build tools, or if the game stopped starting.',)),
|
'after changing build tools, or if the game stopped starting.',)),
|
||||||
@@ -606,6 +680,45 @@ class App:
|
|||||||
desc=('Updates, the game folder, the logs and uninstalling.',)),
|
desc=('Updates, the game folder, the logs and uninstalling.',)),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def saves_row(self, gd):
|
||||||
|
"""Import Saves: a save put into the game folder's saves folder, else a folder the player picks."""
|
||||||
|
ready = False
|
||||||
|
if gd and Path(gd).is_dir():
|
||||||
|
try:
|
||||||
|
saves.ensure_saves_dir(gd)
|
||||||
|
ready = saves.waiting(gd)[0] is not None
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
desc = ('Bring in a save from a Switch save backup, an emulator or another NX2navi install. Put it into the '
|
||||||
|
'saves folder of the game folder and select this row, or select this row and choose its folder.',
|
||||||
|
'Your current save is copied to the saves folder first.')
|
||||||
|
if self.save_message:
|
||||||
|
desc = (self.save_message,) + desc
|
||||||
|
return Row('value', 'Import Saves', 'From the Saves Folder' if ready else 'Choose a Folder',
|
||||||
|
'orange_arrow' if ready else 'arrow', on=self.import_saves, desc=desc)
|
||||||
|
|
||||||
|
def import_saves(self):
|
||||||
|
gd = self.settings.get('game_dir')
|
||||||
|
if not gd or not Path(gd).is_dir():
|
||||||
|
self.save_message = 'Install the game first.'
|
||||||
|
elif (self.game_proc and self.game_proc.poll() is None) or saves.game_running(gd):
|
||||||
|
self.save_message = 'Quit the game first: it keeps its save open while it runs.'
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
folder = None
|
||||||
|
if saves.waiting(gd)[0] is None:
|
||||||
|
folder = filedialog.askdirectory(parent=self.root, title='Choose the folder with the save',
|
||||||
|
initialdir=str(saves.ensure_saves_dir(gd)), mustexist=True)
|
||||||
|
if not folder:
|
||||||
|
return
|
||||||
|
r = saves.import_save(gd, folder, log=self.ctx.log)
|
||||||
|
except (saves.SaveError, OSError) as e:
|
||||||
|
self.save_message = f'The save was not imported: {e}'
|
||||||
|
else:
|
||||||
|
self.save_message = (f'Save imported: {r["files"]} files from {r["source"].name}.'
|
||||||
|
+ (f' Your old save is in saves\\{r["backup"].name}.' if r['backup'] else ''))
|
||||||
|
self.show('home', self.focus)
|
||||||
|
|
||||||
def update_desc(self):
|
def update_desc(self):
|
||||||
r = self.release
|
r = self.release
|
||||||
nv, mine = versions.display(r.version), versions.display(self.layout.version)
|
nv, mine = versions.display(r.version), versions.display(self.layout.version)
|
||||||
@@ -1083,6 +1196,12 @@ class App:
|
|||||||
cw, ch = X(9), X(12)
|
cw, ch = X(9), X(12)
|
||||||
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, '#d9ccae'))
|
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, '#d9ccae'))
|
||||||
c.create_image(x1 - X(16), cy, anchor='e', image=img, tags='dyn')
|
c.create_image(x1 - X(16), cy, anchor='e', image=img, tags='dyn')
|
||||||
|
if r.value: # a value, centred in the cell's room left of the arrow
|
||||||
|
right = x1 - X(16) - cw - X(10)
|
||||||
|
avail = right - vx0 - X(16)
|
||||||
|
vfont = self.fit_font(vfont, r.value, avail, 0.8)
|
||||||
|
c.create_text((vx0 + right) // 2, cy, text=fit(vfont, r.value, avail), font=vfont,
|
||||||
|
fill=P['value_text'], tags='dyn')
|
||||||
else:
|
else:
|
||||||
color = {'normal': P['value_text'], 'dim': P['dim'], 'salmon': P['salmon']}.get(r.style, P['value_text'])
|
color = {'normal': P['value_text'], 'dim': P['dim'], 'salmon': P['salmon']}.get(r.style, P['value_text'])
|
||||||
avail = (x1 - vx0) - X(20) - (X(21) if r.check else 0)
|
avail = (x1 - vx0) - X(20) - (X(21) if r.check else 0)
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"""The window's pictures, drawn with numpy into RGBA arrays and handed to Tk as PNG data.
|
"""The window's pictures, drawn with numpy into RGBA arrays and handed to Tk as PNG data.
|
||||||
|
|
||||||
Everything is drawn here from shapes and colours: the misty green backdrop, the wooden title band, the bronze label
|
Everything is drawn here from shapes and colours: the misty green backdrop, the wooden title band, the bronze label
|
||||||
cells with their mottled texture, the description box, the white glowing cursor, the filigree divider, the Triforce
|
cells with their mottled texture, the description box, the white glowing cursor, the filigree divider, Navi and
|
||||||
and the small icons. Tk's canvas draws lines and polygons without antialiasing on Windows, so every curved or soft
|
the small icons. Tk's canvas draws lines and polygons without antialiasing on Windows, so every curved or soft
|
||||||
shape is a picture; flat rectangles and text stay canvas items.
|
shape is a picture; flat rectangles and text stay canvas items.
|
||||||
|
|
||||||
Colours follow the game's options menu (docs/launcher.md, "Look"). Sizes are in logical pixels times the display
|
Colours follow the game's options menu (docs/launcher.md, "Look"). Sizes are in logical pixels times the display
|
||||||
@@ -29,7 +29,7 @@ PALETTE = {
|
|||||||
'muted': '#d4c6a6', 'dim': '#7d786a', 'off': '#5e5b51', 'on_text': '#fdf4de', 'salmon': '#e88f6c',
|
'muted': '#d4c6a6', 'dim': '#7d786a', 'off': '#5e5b51', 'on_text': '#fdf4de', 'salmon': '#e88f6c',
|
||||||
'ok': '#a7d68c', 'gold': '#e6b65a', 'band_text': '#f3ecdc', 'status': '#b9a988', 'log_text': '#cfc4ab',
|
'ok': '#a7d68c', 'gold': '#e6b65a', 'band_text': '#f3ecdc', 'status': '#b9a988', 'log_text': '#cfc4ab',
|
||||||
'line': '#54442f', 'dot': '#5d4b36', 'filigree': '#7a6443', 'glow': '#e9ebee',
|
'line': '#54442f', 'dot': '#5d4b36', 'filigree': '#7a6443', 'glow': '#e9ebee',
|
||||||
'tri_top': '#d49f36', 'tri_bottom': '#fcbf44',
|
'button_hover': '#8a6c3f', 'close_hover': '#b0402c',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -57,13 +57,30 @@ def photo(master, img):
|
|||||||
return tk.PhotoImage(master=master, data=base64.b64encode(png_bytes(img)).decode('ascii'), format='png')
|
return tk.PhotoImage(master=master, data=base64.b64encode(png_bytes(img)).decode('ascii'), format='png')
|
||||||
|
|
||||||
|
|
||||||
|
def dib_icon(img):
|
||||||
|
"""One .ico entry as a 32-bit bitmap with its AND mask (what every Windows API and Tk read)."""
|
||||||
|
a = img if img.dtype == np.uint8 else (np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)
|
||||||
|
n = a.shape[0]
|
||||||
|
bgra = a[::-1, :, [2, 1, 0, 3]].tobytes() # bottom-up rows
|
||||||
|
stride = ((n + 31) // 32) * 4
|
||||||
|
mask = bytearray()
|
||||||
|
for row in a[::-1]:
|
||||||
|
bits = bytearray(stride)
|
||||||
|
for x in range(n):
|
||||||
|
if row[x, 3] < 128:
|
||||||
|
bits[x // 8] |= 0x80 >> (x % 8)
|
||||||
|
mask += bits
|
||||||
|
head = struct.pack('<IiiHHIIiiII', 40, n, 2 * n, 1, 32, 0, len(bgra) + len(mask), 0, 0, 0, 0)
|
||||||
|
return head + bgra + bytes(mask)
|
||||||
|
|
||||||
|
|
||||||
def ico_bytes(images):
|
def ico_bytes(images):
|
||||||
"""A Windows .ico holding PNG-compressed images (one HxWx4 array per size, square)."""
|
"""A Windows .ico of square HxWx4 images: bitmaps up to 64 pixels, PNG above (as Windows' own icons do)."""
|
||||||
pngs = [png_bytes(im) for im in images]
|
datas = [png_bytes(im) if im.shape[0] > 64 else dib_icon(im) for im in images]
|
||||||
head = struct.pack('<HHH', 0, 1, len(pngs))
|
head = struct.pack('<HHH', 0, 1, len(datas))
|
||||||
offset = 6 + 16 * len(pngs)
|
offset = 6 + 16 * len(datas)
|
||||||
dirs, body = b'', b''
|
dirs, body = b'', b''
|
||||||
for im, data in zip(images, pngs):
|
for im, data in zip(images, datas):
|
||||||
n = im.shape[0]
|
n = im.shape[0]
|
||||||
dirs += struct.pack('<BBBBHHII', n % 256, n % 256, 0, 0, 1, 32, len(data), offset + len(body))
|
dirs += struct.pack('<BBBBHHII', n % 256, n % 256, 0, 0, 1, 32, len(data), offset + len(body))
|
||||||
body += data
|
body += data
|
||||||
@@ -450,37 +467,94 @@ def filigree(w, s):
|
|||||||
return img, h
|
return img, h
|
||||||
|
|
||||||
|
|
||||||
def triforce(w):
|
# Navi, the launcher's emblem and icon: 22 x 21 pixels as the artwork has them. W white (the outline and the
|
||||||
"""The Triforce, w pixels wide: three triangles, each shading from top to bottom, on a transparent ground."""
|
# wings' highlights), g the wings' grey, K the black outline of the body, B and L its two blues, . transparent.
|
||||||
h = int(round(w * 217 / 250))
|
NAVI = (
|
||||||
k = w / 250.0
|
'WWWW..............WWWW',
|
||||||
tris = [((125, 1), (186.2, 107), (63.8, 107)), ((62.2, 109), (123.4, 215), (1, 215)),
|
'WggWW............WWggW',
|
||||||
((187.8, 109), (249, 215), (126.6, 215))]
|
'WgggWW..........WWgggW',
|
||||||
img = new(h, w)
|
'WgWggWW........WWggWgW',
|
||||||
top, bottom = rgb(PALETTE['tri_top']), rgb(PALETTE['tri_bottom'])
|
'WggWggW........WggWggW',
|
||||||
for tri in tris:
|
'WgWgWgWW......WWgWgWgW',
|
||||||
pts = [(x * k, y * k) for x, y in tri]
|
'WggggWgWKKKKKKWgWggggW',
|
||||||
mask = polygon_mask(h, w, pts)
|
'WWggWggKBBBBBBKggWggWW',
|
||||||
y0, y1 = min(p[1] for p in pts), max(p[1] for p in pts)
|
'.WggggKKBBLLBBKKggggW.',
|
||||||
t = np.clip((np.arange(h, dtype=np.float32) + 0.5 - y0) / max(y1 - y0, 1e-6), 0, 1)[:, None, None]
|
'.WWggKKBBLLLLBBKKggWW.',
|
||||||
layer = new(h, w)
|
'..WWgKBBLLWWLLBBKgWW..',
|
||||||
layer[..., :3] = top + (bottom - top) * t
|
'...WWKBBLWWWWLBBKWW...',
|
||||||
layer[..., 3] = mask
|
'.....KBBLLWWLLBBK.....',
|
||||||
over(img, layer)
|
'.....KBBBLLLLBBBK.....',
|
||||||
|
'.....WKKBBBBBBKKW.....',
|
||||||
|
'....WWgKKBBBBKKgWW....',
|
||||||
|
'...WWgggKKKKKKgggWW...',
|
||||||
|
'...WggWgW....WgWggW...',
|
||||||
|
'...WgWggW....WggWgW...',
|
||||||
|
'...WWggWW....WWggWW...',
|
||||||
|
'....WWWW......WWWW....',
|
||||||
|
)
|
||||||
|
NAVI_COLORS = {'W': (255, 255, 255), 'g': (207, 216, 220), 'K': (0, 0, 0), 'B': (2, 136, 209), 'L': (79, 195, 247)}
|
||||||
|
|
||||||
|
|
||||||
|
def navi_pixels():
|
||||||
|
"""The artwork as a 21 x 22 RGBA uint8 array."""
|
||||||
|
a = np.zeros((len(NAVI), len(NAVI[0]), 4), dtype=np.uint8)
|
||||||
|
for y, row in enumerate(NAVI):
|
||||||
|
for x, ch in enumerate(row):
|
||||||
|
if ch in NAVI_COLORS:
|
||||||
|
a[y, x, :3] = NAVI_COLORS[ch]
|
||||||
|
a[y, x, 3] = 255
|
||||||
|
return a
|
||||||
|
|
||||||
|
|
||||||
|
def navi(k):
|
||||||
|
"""Navi with every artwork pixel k x k screen pixels (crisp edges), as a float RGBA array."""
|
||||||
|
a = np.repeat(np.repeat(navi_pixels(), k, axis=0), k, axis=1)
|
||||||
|
return a.astype(np.float32) / 255.0
|
||||||
|
|
||||||
|
|
||||||
|
def navi_icon(n):
|
||||||
|
"""Navi on a transparent n x n square: whole-pixel scaling where the size allows it, an average of a large
|
||||||
|
rendering below 22 pixels."""
|
||||||
|
sq = np.zeros((n, n, 4), dtype=np.float32)
|
||||||
|
rows, cols = len(NAVI), len(NAVI[0])
|
||||||
|
if n >= cols:
|
||||||
|
img = navi(n // cols)
|
||||||
|
else: # premultiplied box average of an 8x rendering, so the edges blend instead of dropping pixels
|
||||||
|
big = navi(8)
|
||||||
|
H, W = big.shape[:2]
|
||||||
|
h, w = max(1, round(rows * n / cols)), n
|
||||||
|
ys = (np.arange(h + 1) * H / h).astype(int)
|
||||||
|
xs = (np.arange(w + 1) * W / w).astype(int)
|
||||||
|
pm = big.copy()
|
||||||
|
pm[..., :3] *= pm[..., 3:4]
|
||||||
|
img = np.zeros((h, w, 4), dtype=np.float32)
|
||||||
|
for y in range(h):
|
||||||
|
for x in range(w):
|
||||||
|
img[y, x] = pm[ys[y]:ys[y + 1], xs[x]:xs[x + 1]].mean(axis=(0, 1))
|
||||||
|
img[..., :3] = np.where(img[..., 3:4] > 0, img[..., :3] / np.maximum(img[..., 3:4], 1e-6), 0)
|
||||||
|
h, w = img.shape[:2]
|
||||||
|
over(sq, img, (n - w) // 2, (n - h) // 2)
|
||||||
|
return sq
|
||||||
|
|
||||||
|
|
||||||
|
def navi_ico():
|
||||||
|
"""The launcher's icon (NX2navi.exe, the setup, the window, the taskbar) at the sizes Windows asks for."""
|
||||||
|
return ico_bytes([navi_icon(n) for n in (16, 20, 24, 32, 40, 48, 64, 96, 128, 256)])
|
||||||
|
|
||||||
|
|
||||||
|
def title_glyph(kind, size, s):
|
||||||
|
"""The minimise bar or the close cross of the band's buttons, in the band's light text colour."""
|
||||||
|
img = new(size, size)
|
||||||
|
t = max(1.2, 1.4 * s)
|
||||||
|
m = size * 0.12
|
||||||
|
if kind == 'min':
|
||||||
|
lines = [[(m, size / 2), (size - m, size / 2)]]
|
||||||
|
else:
|
||||||
|
lines = [[(m, m), (size - m, size - m)], [(size - m, m), (m, size - m)]]
|
||||||
|
paint(img, stroke_mask(size, size, lines, t), PALETTE['band_text'])
|
||||||
return img
|
return img
|
||||||
|
|
||||||
|
|
||||||
def triforce_ico():
|
|
||||||
"""The launcher's icon at the sizes Windows asks for."""
|
|
||||||
imgs = []
|
|
||||||
for n in (16, 24, 32, 48, 64, 128, 256):
|
|
||||||
t = triforce(n)
|
|
||||||
sq = new(n, n)
|
|
||||||
over(sq, t, 0, (n - t.shape[0]) // 2)
|
|
||||||
imgs.append(sq)
|
|
||||||
return ico_bytes(imgs)
|
|
||||||
|
|
||||||
|
|
||||||
def check_mark(size, s, color=None):
|
def check_mark(size, s, color=None):
|
||||||
img = new(size, size)
|
img = new(size, size)
|
||||||
k = size / 24.0
|
k = size / 24.0
|
||||||
|
|||||||
@@ -139,9 +139,15 @@ def states(app):
|
|||||||
def uninstall():
|
def uninstall():
|
||||||
app.show('uninstall', 0)
|
app.show('uninstall', 0)
|
||||||
|
|
||||||
|
def import_saves():
|
||||||
|
app.release, app.message = None, ''
|
||||||
|
app.save_message = ('Save imported: 3 files from 0100F2C0115B6000. Your old save is in '
|
||||||
|
'saves\\backup 2026-11-08 17.30.12.')
|
||||||
|
app.show('home', next(i for i, r in enumerate(app.rows_home()) if r.label == 'Import Saves'))
|
||||||
|
|
||||||
return [('1-first-run', first_run), ('2-installing', installing), ('3-home', home),
|
return [('1-first-run', first_run), ('2-installing', installing), ('3-home', home),
|
||||||
('4-update-ready', update_ready), ('5-updating', updating), ('6-settings', settings),
|
('4-update-ready', update_ready), ('5-updating', updating), ('6-settings', settings),
|
||||||
('7-build-failed', failed), ('8-uninstall', uninstall)]
|
('7-build-failed', failed), ('8-uninstall', uninstall), ('9-import-saves', import_saves)]
|
||||||
|
|
||||||
|
|
||||||
def run(app, shots):
|
def run(app, shots):
|
||||||
|
|||||||
@@ -35,6 +35,96 @@ def app_id():
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
GWL_STYLE, GWL_EXSTYLE = -16, -20
|
||||||
|
WS_MINIMIZEBOX, WS_SYSMENU = 0x00020000, 0x00080000
|
||||||
|
WS_EX_APPWINDOW, WS_EX_TOOLWINDOW = 0x00040000, 0x00000080
|
||||||
|
|
||||||
|
|
||||||
|
def _hwnd(root):
|
||||||
|
"""The Win32 window of a Tk toplevel (the wrapper around Tk's child window)."""
|
||||||
|
user32 = ctypes.windll.user32
|
||||||
|
user32.GetParent.restype = ctypes.c_void_p
|
||||||
|
user32.GetParent.argtypes = [ctypes.c_void_p]
|
||||||
|
return user32.GetParent(root.winfo_id()) or root.winfo_id()
|
||||||
|
|
||||||
|
|
||||||
|
def _post(hwnd, msg, wparam, lparam):
|
||||||
|
"""Queue a message for the window instead of sending it. A sent message runs the window's handler inside this
|
||||||
|
ctypes call, which has released Python's lock; when that handler dispatches Tk events (the move loop of a title
|
||||||
|
bar drag does), Tk calls back into Python without the lock and Python aborts. A posted message is handled by Tk's
|
||||||
|
own event loop, where calling back into Python is allowed."""
|
||||||
|
user32 = ctypes.windll.user32
|
||||||
|
user32.PostMessageW.restype = ctypes.c_int
|
||||||
|
user32.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t]
|
||||||
|
return user32.PostMessageW(hwnd, msg, wparam, lparam)
|
||||||
|
|
||||||
|
|
||||||
|
def frameless(root):
|
||||||
|
"""Windows: drop the system title bar (the window draws its own), but keep a taskbar button, Alt+Tab, minimise
|
||||||
|
from the taskbar and Alt+F4. False elsewhere, where the window keeps its frame."""
|
||||||
|
if os.name != 'nt':
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
root.overrideredirect(True)
|
||||||
|
root.update_idletasks()
|
||||||
|
user32 = ctypes.windll.user32
|
||||||
|
get, put = user32.GetWindowLongPtrW, user32.SetWindowLongPtrW
|
||||||
|
get.restype, get.argtypes = ctypes.c_ssize_t, [ctypes.c_void_p, ctypes.c_int]
|
||||||
|
put.restype, put.argtypes = ctypes.c_ssize_t, [ctypes.c_void_p, ctypes.c_int, ctypes.c_ssize_t]
|
||||||
|
hwnd = _hwnd(root)
|
||||||
|
put(hwnd, GWL_EXSTYLE, (get(hwnd, GWL_EXSTYLE) & ~WS_EX_TOOLWINDOW) | WS_EX_APPWINDOW)
|
||||||
|
put(hwnd, GWL_STYLE, get(hwnd, GWL_STYLE) | WS_MINIMIZEBOX | WS_SYSMENU)
|
||||||
|
root.withdraw() # the taskbar takes a changed window style only when the window is shown again
|
||||||
|
root.after(10, root.deiconify)
|
||||||
|
return True
|
||||||
|
except (AttributeError, OSError, Exception):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def minimize(root):
|
||||||
|
"""Tk refuses to iconify a window without a frame, so ask Windows; asynchronously, for the reason in _post."""
|
||||||
|
if os.name == 'nt':
|
||||||
|
ctypes.windll.user32.ShowWindowAsync(ctypes.c_void_p(_hwnd(root)), 6) # SW_MINIMIZE
|
||||||
|
else:
|
||||||
|
root.iconify()
|
||||||
|
|
||||||
|
|
||||||
|
def start_drag(root):
|
||||||
|
"""Windows: let the system move the window from the mouse's current press (as on a title bar, with snapping).
|
||||||
|
False elsewhere: the caller moves the window itself."""
|
||||||
|
if os.name != 'nt':
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
ctypes.windll.user32.ReleaseCapture()
|
||||||
|
return bool(_post(_hwnd(root), 0x00A1, 2, 0)) # WM_NCLBUTTONDOWN, HTCAPTION
|
||||||
|
except (AttributeError, OSError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
_ICONS = []
|
||||||
|
|
||||||
|
|
||||||
|
def set_window_icon(root, ico):
|
||||||
|
"""Windows: the window's and the taskbar button's icon, straight from an .ico (the large and the small size)."""
|
||||||
|
if os.name != 'nt':
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
user32 = ctypes.windll.user32
|
||||||
|
user32.LoadImageW.restype = ctypes.c_void_p
|
||||||
|
user32.LoadImageW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int,
|
||||||
|
ctypes.c_uint]
|
||||||
|
hwnd = _hwnd(root)
|
||||||
|
for which, (mx, my) in ((1, (11, 12)), (0, (49, 50))): # ICON_BIG: SM_CXICON; ICON_SMALL: SM_CXSMICON
|
||||||
|
h = user32.LoadImageW(None, str(ico), 1, user32.GetSystemMetrics(mx), user32.GetSystemMetrics(my),
|
||||||
|
0x10) # IMAGE_ICON, LR_LOADFROMFILE
|
||||||
|
if h:
|
||||||
|
_ICONS.append(h)
|
||||||
|
_post(hwnd, 0x0080, which, h) # WM_SETICON
|
||||||
|
return True
|
||||||
|
except (AttributeError, OSError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def register_font(path):
|
def register_font(path):
|
||||||
"""Make a font file usable by this process only (Tk then finds it by family name). True on success."""
|
"""Make a font file usable by this process only (Tk then finds it by family name). True on success."""
|
||||||
path = str(path)
|
path = str(path)
|
||||||
|
|||||||
@@ -60,6 +60,9 @@
|
|||||||
# lib_prebuild_threads = 4
|
# lib_prebuild_threads = 4
|
||||||
# Build known pipelines ahead of time.
|
# Build known pipelines ahead of time.
|
||||||
# pipe_prebuild = 1
|
# pipe_prebuild = 1
|
||||||
|
# 1: the start waits until every known pipeline is built. Default 0: with the graphics pipeline library the start
|
||||||
|
# builds them for at most 20 seconds and the rest in the background while you play.
|
||||||
|
# prewarm_full = 0
|
||||||
# Threads that translate known shaders at start (1 to 64; default: half the CPU threads, at most 16).
|
# Threads that translate known shaders at start (1 to 64; default: half the CPU threads, at most 16).
|
||||||
# prewarm_xlate = 8
|
# prewarm_xlate = 8
|
||||||
# Vulkan graphics pipeline library, 0 or 1. Default: on.
|
# Vulkan graphics pipeline library, 0 or 1. Default: on.
|
||||||
@@ -126,7 +129,8 @@
|
|||||||
# set default to fullscreen = 1, window_size = 1280x800, output_res = 1280x800, render_scale = game, vk_present = fifo
|
# set default to fullscreen = 1, window_size = 1280x800, output_res = 1280x800, render_scale = game, vk_present = fifo
|
||||||
# and fps_limit = 40 (starting points, not measured yet). Read at start.
|
# and fps_limit = 40 (starting points, not measured yet). Read at start.
|
||||||
# device_profile = auto
|
# device_profile = auto
|
||||||
# Presentation mode: mailbox (default when the driver offers it, vsync otherwise), fifo (vsync) or immediate.
|
# Presentation mode: mailbox (default when the driver offers it, vsync otherwise), fifo (vsync) or immediate. The menu's
|
||||||
|
# VSync switch sets mailbox when on and immediate when off.
|
||||||
# vk_present = mailbox
|
# vk_present = mailbox
|
||||||
# Window client area in screen pixels (640x360 to 7680x4320), and borderless fullscreen. Windows display scaling does
|
# Window client area in screen pixels (640x360 to 7680x4320), and borderless fullscreen. Windows display scaling does
|
||||||
# not apply: at 150% scale, 1920x1080 covers the area 1280x720 covers at 100%. F11 switches fullscreen and saves it
|
# not apply: at 150% scale, 1920x1080 covers the area 1280x720 covers at 100%. F11 switches fullscreen and saves it
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ static const char *const known[] = {
|
|||||||
"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",
|
"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",
|
||||||
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PACE_HZ", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_RES_FIXED", "PATCH_SCENE", "PATCH_WIDE_ASPECT", "PATCH_WIDE_HUD", "PATCH_WIDE_MOVIE", "PATCH_WIDE_OUT", "PATCH_WIDE_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
|
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PACE_HZ", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_RES_FIXED", "PATCH_SCENE", "PATCH_WIDE_ASPECT", "PATCH_WIDE_HUD", "PATCH_WIDE_MOVIE", "PATCH_WIDE_OUT", "PATCH_WIDE_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
|
||||||
"PREWARM_WAIT_MS", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
|
"PREWARM_FULL", "PREWARM_WAIT_MS", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
|
||||||
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC",
|
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC",
|
||||||
"RENDER_SCALE", "REPLAY_ASYNC", "RTSS",
|
"RENDER_SCALE", "REPLAY_ASYNC", "RTSS",
|
||||||
"REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
|
"REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
|
||||||
|
|||||||
@@ -137,11 +137,16 @@ static float volume(void) {
|
|||||||
|
|
||||||
static _Atomic uint64_t last_start_ns;
|
static _Atomic uint64_t last_start_ns;
|
||||||
|
|
||||||
|
// The least time between a cursor tick and the sound before it. Moving down a list or changing a value asks for a tick
|
||||||
|
// at every step, about 20 a second while a direction is held, and the focus moving with a press or a tab change is part
|
||||||
|
// of that sound: at most five ticks a second are heard.
|
||||||
|
#define CURSOR_GAP_NS 180000000ull
|
||||||
|
#define CURSOR_GAIN 0.6f // the tick under the sounds of a decision
|
||||||
|
|
||||||
void menu_sound_play(MenuSound id) {
|
void menu_sound_play(MenuSound id) {
|
||||||
if ((unsigned)id >= MENU_SOUND_COUNT || volume() <= 0) return;
|
if ((unsigned)id >= MENU_SOUND_COUNT || volume() <= 0) return;
|
||||||
// A cursor tick right after another sound (the focus moving with a tab change or a press) is the same action.
|
|
||||||
uint64_t now = plat_now_ns();
|
uint64_t now = plat_now_ns();
|
||||||
if (id == MENU_SOUND_CURSOR && now - atomic_load(&last_start_ns) < 40000000ull) return;
|
if (id == MENU_SOUND_CURSOR && now - atomic_load(&last_start_ns) < CURSOR_GAP_NS) return;
|
||||||
atomic_store(&last_start_ns, now);
|
atomic_store(&last_start_ns, now);
|
||||||
if (atomic_load_explicit(&loaded, memory_order_acquire) != 2) load_all();
|
if (atomic_load_explicit(&loaded, memory_order_acquire) != 2) load_all();
|
||||||
if (atomic_load_explicit(&loaded, memory_order_acquire) != 2 || !sounds[id].pcm) return;
|
if (atomic_load_explicit(&loaded, memory_order_acquire) != 2 || !sounds[id].pcm) return;
|
||||||
@@ -151,9 +156,11 @@ void menu_sound_play(MenuSound id) {
|
|||||||
if (atomic_load_explicit(&voices[i].pos, memory_order_acquire) < 0) { pick = i; break; }
|
if (atomic_load_explicit(&voices[i].pos, memory_order_acquire) < 0) { pick = i; break; }
|
||||||
if (voices[i].started < oldest) oldest = voices[i].started, pick = i;
|
if (voices[i].started < oldest) oldest = voices[i].started, pick = i;
|
||||||
}
|
}
|
||||||
// A sound that replaces itself (holding a direction) restarts instead of stacking up.
|
// A sound that replaces itself restarts instead of stacking up, and a decision replaces the tick of the same press
|
||||||
|
// (a row changes its value in the frame the press is seen).
|
||||||
for (int i = 0; i < VOICES; i++)
|
for (int i = 0; i < VOICES; i++)
|
||||||
if (atomic_load_explicit(&voices[i].pos, memory_order_acquire) >= 0 && atomic_load(&voices[i].sound) == (int)id &&
|
if (atomic_load_explicit(&voices[i].pos, memory_order_acquire) >= 0 &&
|
||||||
|
(atomic_load(&voices[i].sound) == (int)id || atomic_load(&voices[i].sound) == MENU_SOUND_CURSOR) &&
|
||||||
atomic_load(&voices[i].pos) < 2400) { // started under 50 ms ago
|
atomic_load(&voices[i].pos) < 2400) { // started under 50 ms ago
|
||||||
pick = i;
|
pick = i;
|
||||||
break;
|
break;
|
||||||
@@ -170,13 +177,15 @@ void menu_sound_mix(float *out, uint32_t frames, int channels, int rate) {
|
|||||||
for (int v = 0; v < VOICES; v++) {
|
for (int v = 0; v < VOICES; v++) {
|
||||||
int pos = atomic_load_explicit(&voices[v].pos, memory_order_acquire);
|
int pos = atomic_load_explicit(&voices[v].pos, memory_order_acquire);
|
||||||
if (pos < 0) continue;
|
if (pos < 0) continue;
|
||||||
const Sound *s = &sounds[atomic_load_explicit(&voices[v].sound, memory_order_relaxed)];
|
int which = atomic_load_explicit(&voices[v].sound, memory_order_relaxed);
|
||||||
|
const Sound *s = &sounds[which];
|
||||||
if (g < 0) g = volume();
|
if (g < 0) g = volume();
|
||||||
|
float vg = which == MENU_SOUND_CURSOR ? g * CURSOR_GAIN : g;
|
||||||
uint32_t n = s->frames - (uint32_t)pos < frames ? s->frames - (uint32_t)pos : frames;
|
uint32_t n = s->frames - (uint32_t)pos < frames ? s->frames - (uint32_t)pos : frames;
|
||||||
const float *src = s->pcm + (size_t)pos * 2;
|
const float *src = s->pcm + (size_t)pos * 2;
|
||||||
for (uint32_t i = 0; i < n; i++) {
|
for (uint32_t i = 0; i < n; i++) {
|
||||||
out[(size_t)i * channels] += src[2 * i] * g;
|
out[(size_t)i * channels] += src[2 * i] * vg;
|
||||||
out[(size_t)i * channels + 1] += src[2 * i + 1] * g;
|
out[(size_t)i * channels + 1] += src[2 * i + 1] * vg;
|
||||||
}
|
}
|
||||||
int next = pos + (int)n;
|
int next = pos + (int)n;
|
||||||
// Only advance if the menu thread did not restart the voice meanwhile.
|
// Only advance if the menu thread did not restart the voice meanwhile.
|
||||||
|
|||||||
@@ -192,13 +192,14 @@ static void capture_window(void) {
|
|||||||
if (!ImGui::IsPopupOpen("##bind_capture")) ImGui::OpenPopup("##bind_capture");
|
if (!ImGui::IsPopupOpen("##bind_capture")) ImGui::OpenPopup("##bind_capture");
|
||||||
uint64_t now = plat_now_ns();
|
uint64_t now = plat_now_ns();
|
||||||
bool pad_cell = g_cap.cell == 2;
|
bool pad_cell = g_cap.cell == 2;
|
||||||
|
// the timeout first: a press polled after it would compare with a held state long gone and bind what is held now
|
||||||
|
if (!g_cap.done && now - g_cap.start > CAPTURE_SECONDS * 1000000000ull) g_cap.done = now;
|
||||||
if (!g_cap.done) {
|
if (!g_cap.done) {
|
||||||
int id = 0, got = input_capture(g_cap.reset, &id);
|
int id = 0, got = input_capture(g_cap.reset, &id);
|
||||||
g_cap.reset = false;
|
g_cap.reset = false;
|
||||||
if (got == INPUT_CAPTURE_KEY && !pad_cell) change(g_cap.action, g_cap.cell, id);
|
if (got == INPUT_CAPTURE_KEY && !pad_cell) change(g_cap.action, g_cap.cell, id);
|
||||||
if (got == INPUT_CAPTURE_PAD && pad_cell) change(g_cap.action, g_cap.cell, id);
|
if (got == INPUT_CAPTURE_PAD && pad_cell) change(g_cap.action, g_cap.cell, id);
|
||||||
if (got != INPUT_CAPTURE_NONE && !(got == INPUT_CAPTURE_KEY && pad_cell)) g_cap.done = now;
|
if (got != INPUT_CAPTURE_NONE && !(got == INPUT_CAPTURE_KEY && pad_cell)) g_cap.done = now;
|
||||||
if (now - g_cap.start > CAPTURE_SECONDS * 1000000000ull) g_cap.done = now;
|
|
||||||
}
|
}
|
||||||
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
|
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
|
||||||
if (ImGui::BeginPopupModal("##bind_capture", nullptr,
|
if (ImGui::BeginPopupModal("##bind_capture", nullptr,
|
||||||
@@ -222,6 +223,8 @@ static void capture_window(void) {
|
|||||||
|
|
||||||
bool binds_modal(void) { return g_cap.action >= 0; }
|
bool binds_modal(void) { return g_cap.action >= 0; }
|
||||||
|
|
||||||
|
void binds_cancel(void) { g_cap.action = -1; }
|
||||||
|
|
||||||
static bool g_reset_asked; // the reset row was chosen this frame (acted on after the page)
|
static bool g_reset_asked; // the reset row was chosen this frame (acted on after the page)
|
||||||
|
|
||||||
void binds_rows(float scale) {
|
void binds_rows(float scale) {
|
||||||
|
|||||||
@@ -8,3 +8,6 @@ void binds_rows(float scale);
|
|||||||
void binds_after_page(void);
|
void binds_after_page(void);
|
||||||
// A cell waits for a press (or its press is still reaching the menu): B, Esc, L / R and the tab keys stay on the page.
|
// A cell waits for a press (or its press is still reaching the menu): B, Esc, L / R and the tab keys stay on the page.
|
||||||
bool binds_modal(void);
|
bool binds_modal(void);
|
||||||
|
// The menu opened or closed (menu.cpp): a cell still waiting for a press stops waiting, unchanged. Its window is closed
|
||||||
|
// with the menu's popups.
|
||||||
|
void binds_cancel(void);
|
||||||
|
|||||||
@@ -32,10 +32,12 @@ static int g_font_bad;
|
|||||||
#include "menu_sound.h"
|
#include "menu_sound.h"
|
||||||
#include "menu_assets.h"
|
#include "menu_assets.h"
|
||||||
#include "ui/menu_art.h"
|
#include "ui/menu_art.h"
|
||||||
|
#include "ui/menu_skin.h"
|
||||||
#pragma clang diagnostic pop
|
#pragma clang diagnostic pop
|
||||||
#include "ui/amiibo_page.h"
|
#include "ui/amiibo_page.h"
|
||||||
#include "ui/binds_page.h"
|
#include "ui/binds_page.h"
|
||||||
#include "ui/option_rows.h"
|
#include "ui/option_rows.h"
|
||||||
|
#include "ui/perf_panel.h"
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
#include "amiibo.h"
|
#include "amiibo.h"
|
||||||
@@ -86,13 +88,20 @@ static std::atomic<int> g_reset; // opened or closed since the last laid-out
|
|||||||
// (F1, Esc), the polling thread (combo) and the present path (Continue, B) race.
|
// (F1, Esc), the polling thread (combo) and the present path (Continue, B) race.
|
||||||
static PlatMutex open_lock = PLAT_MUTEX_INIT;
|
static PlatMutex open_lock = PLAT_MUTEX_INIT;
|
||||||
|
|
||||||
// want 0 or 1 sets the state; -1 flips it. Returns the new state.
|
static PlatMutex ev_lock = PLAT_MUTEX_INIT; // the event queue below
|
||||||
|
static int ev_n;
|
||||||
|
|
||||||
|
// want 0 or 1 sets the state; -1 flips it. Returns the new state. The window events queued before the change go with it:
|
||||||
|
// keys pressed just before a close would otherwise reach the menu when it next opens.
|
||||||
static int change_open(int want) {
|
static int change_open(int want) {
|
||||||
plat_mutex_lock(&open_lock);
|
plat_mutex_lock(&open_lock);
|
||||||
int open = want < 0 ? !g_open.load() : want;
|
int open = want < 0 ? !g_open.load() : want;
|
||||||
if (g_open.load() != open) {
|
if (g_open.load() != open) {
|
||||||
g_open.store(open);
|
g_open.store(open);
|
||||||
g_reset.store(1);
|
g_reset.store(1);
|
||||||
|
plat_mutex_lock(&ev_lock);
|
||||||
|
ev_n = 0;
|
||||||
|
plat_mutex_unlock(&ev_lock);
|
||||||
input_menu(open);
|
input_menu(open);
|
||||||
menu_sound_play(open ? MENU_SOUND_OPEN : MENU_SOUND_CLOSE);
|
menu_sound_play(open ? MENU_SOUND_OPEN : MENU_SOUND_CLOSE);
|
||||||
rt_log("menu: %s", open ? "open" : "closed");
|
rt_log("menu: %s", open ? "open" : "closed");
|
||||||
@@ -104,9 +113,9 @@ static int change_open(int want) {
|
|||||||
static void set_open(int open) { change_open(open); }
|
static void set_open(int open) { change_open(open); }
|
||||||
|
|
||||||
static int g_failed_flag();
|
static int g_failed_flag();
|
||||||
// The boot screen is up (menu_boot_set): the menu does not open, as it would not be drawn while its keys queued up and
|
// Until the game's first frame (menu_overlay_frame), boot screen included: the menu does not open, as it would not be
|
||||||
// changed settings once the game ran.
|
// drawn while its keys queued up and changed settings once the game ran.
|
||||||
static std::atomic<int> g_booting{0};
|
static std::atomic<int> g_booting{1};
|
||||||
extern "C" int menu_is_open(void) { return g_open.load(std::memory_order_relaxed); }
|
extern "C" int menu_is_open(void) { return g_open.load(std::memory_order_relaxed); }
|
||||||
extern "C" void menu_toggle(void) {
|
extern "C" void menu_toggle(void) {
|
||||||
if (!g_failed_flag() && !g_booting.load(std::memory_order_acquire)) change_open(-1);
|
if (!g_failed_flag() && !g_booting.load(std::memory_order_acquire)) change_open(-1);
|
||||||
@@ -115,13 +124,17 @@ extern "C" void menu_toggle(void) {
|
|||||||
// ---- events from the window adapter, queued while the menu is open; the present path hands them to ImGui
|
// ---- events from the window adapter, queued while the menu is open; the present path hands them to ImGui
|
||||||
enum { EV_KEY, EV_POS, EV_BUTTON, EV_WHEEL, EV_FOCUS, EV_MAX = 256 };
|
enum { EV_KEY, EV_POS, EV_BUTTON, EV_WHEEL, EV_FOCUS, EV_MAX = 256 };
|
||||||
struct Ev { int type, a, b; float x, y; };
|
struct Ev { int type, a, b; float x, y; };
|
||||||
static PlatMutex ev_lock = PLAT_MUTEX_INIT;
|
|
||||||
static Ev ev_q[EV_MAX];
|
static Ev ev_q[EV_MAX];
|
||||||
static int ev_n;
|
|
||||||
|
|
||||||
static void push(Ev e) {
|
static void push(Ev e) {
|
||||||
if (!menu_is_open()) return;
|
if (!menu_is_open()) return;
|
||||||
plat_mutex_lock(&ev_lock);
|
plat_mutex_lock(&ev_lock);
|
||||||
|
// checked again under the lock: change_open empties the queue after the state changes, so an event of the closed
|
||||||
|
// menu cannot slip in behind that
|
||||||
|
if (!menu_is_open()) {
|
||||||
|
plat_mutex_unlock(&ev_lock);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (e.type == EV_POS && ev_n && ev_q[ev_n - 1].type == EV_POS) ev_q[ev_n - 1] = e; // only the newest position
|
if (e.type == EV_POS && ev_n && ev_q[ev_n - 1].type == EV_POS) ev_q[ev_n - 1] = e; // only the newest position
|
||||||
else if (ev_n < EV_MAX) ev_q[ev_n++] = e;
|
else if (ev_n < EV_MAX) ev_q[ev_n++] = e;
|
||||||
plat_mutex_unlock(&ev_lock);
|
plat_mutex_unlock(&ev_lock);
|
||||||
@@ -143,7 +156,12 @@ static void drain_events(ImGuiIO &io) {
|
|||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
const Ev &e = q[i];
|
const Ev &e = q[i];
|
||||||
switch (e.type) {
|
switch (e.type) {
|
||||||
case EV_KEY: io.AddKeyEvent((ImGuiKey)e.a, e.b != 0); break;
|
case EV_KEY:
|
||||||
|
io.AddKeyEvent((ImGuiKey)e.a, e.b != 0);
|
||||||
|
// ImGui takes the modifier state (io.KeyShift, io.KeyCtrl: Shift+Tab, Ctrl+Up) from these keys only
|
||||||
|
if (e.a == ImGuiKey_LeftShift) io.AddKeyEvent(ImGuiMod_Shift, e.b != 0);
|
||||||
|
if (e.a == ImGuiKey_LeftCtrl) io.AddKeyEvent(ImGuiMod_Ctrl, e.b != 0);
|
||||||
|
break;
|
||||||
case EV_POS: io.AddMousePosEvent(e.x, e.y); break;
|
case EV_POS: io.AddMousePosEvent(e.x, e.y); break;
|
||||||
case EV_BUTTON: io.AddMouseButtonEvent(e.a, e.b != 0); break;
|
case EV_BUTTON: io.AddMouseButtonEvent(e.a, e.b != 0); break;
|
||||||
case EV_WHEEL: io.AddMouseWheelEvent(e.x, e.y); break;
|
case EV_WHEEL: io.AddMouseWheelEvent(e.x, e.y); break;
|
||||||
@@ -204,51 +222,17 @@ static ImGuiStyle g_base_style; // the menu's style at 1080 lines
|
|||||||
static uint64_t g_last_ns;
|
static uint64_t g_last_ns;
|
||||||
static uint64_t g_cost_ns, g_cost_frames; // CPU time of layout and recording while open, logged per 600 frames
|
static uint64_t g_cost_ns, g_cost_frames; // CPU time of layout and recording while open, logged per 600 frames
|
||||||
|
|
||||||
// Sizes are tuned for 1080 lines and follow the window's height. Under 720 lines at 100% display scale they stay at the
|
// Sizes are tuned for 1080 lines and follow the window's height, or its width in a window narrower than 1.47:1, where
|
||||||
// 720 size; that floor grows with the window's DPI, so a small window on a 150% or 200% display (sizes are physical
|
// the menu's 1400 pixels at 1080 lines would no longer fit 88 % of the width (layout_menu). Under 720 lines at 100%
|
||||||
// pixels) still gets text as large as the display scale asks for.
|
// display scale they stay at the 720 size; that floor grows with the window's DPI, so a small window on a 150% or 200%
|
||||||
static float menu_scale(uint32_t h) {
|
// display (sizes are physical pixels) still gets text as large as the display scale asks for.
|
||||||
float least = 720.0f * (float)gfx_window_dpi() / 96.0f;
|
static float menu_scale(uint32_t w, uint32_t h) {
|
||||||
return ((float)h >= least ? (float)h : least) / 1080.0f;
|
float least = 720.0f * (float)gfx_window_dpi() / 96.0f, lines = fminf((float)h, (float)w * 0.68f);
|
||||||
|
return (lines >= least ? lines : least) / 1080.0f;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The game's menu colours: a dark umber panel, warm browns for frames and what is selected, gold for the ornaments,
|
// The gold of the title and its Triforce (the rest of the menu's colours: ui/menu_skin.cpp skin_style).
|
||||||
// accents and the cursor, parchment text. kGreen and kOcarina keep their names for the selected and active controls.
|
static const ImVec4 kGold(0.93f, 0.76f, 0.38f, 1);
|
||||||
static const ImVec4 kGold(0.93f, 0.76f, 0.38f, 1), kGreen(0.36f, 0.26f, 0.13f, 1), kNavy(0.075f, 0.058f, 0.042f, 0.95f),
|
|
||||||
kOcarina(0.62f, 0.47f, 0.22f, 1);
|
|
||||||
static void style_init(ImGuiStyle &s) {
|
|
||||||
ImGui::StyleColorsDark(&s);
|
|
||||||
s.WindowRounding = 10; s.FrameRounding = 6; s.GrabRounding = 6; s.TabRounding = 6; s.ChildRounding = 8;
|
|
||||||
s.WindowPadding = ImVec2(40, 30); s.FramePadding = ImVec2(14, 8); s.ItemSpacing = ImVec2(14, 12);
|
|
||||||
s.WindowBorderSize = 2; s.ScrollbarSize = 16;
|
|
||||||
ImVec4 *c = s.Colors;
|
|
||||||
c[ImGuiCol_WindowBg] = kNavy;
|
|
||||||
c[ImGuiCol_Border] = ImVec4(kGold.x, kGold.y, kGold.z, 0.55f);
|
|
||||||
c[ImGuiCol_ChildBg] = ImVec4(0, 0, 0, 0);
|
|
||||||
c[ImGuiCol_PopupBg] = kNavy;
|
|
||||||
c[ImGuiCol_Text] = ImVec4(0.96f, 0.92f, 0.82f, 1);
|
|
||||||
c[ImGuiCol_TextDisabled] = ImVec4(0.62f, 0.56f, 0.46f, 1);
|
|
||||||
c[ImGuiCol_FrameBg] = ImVec4(0.15f, 0.115f, 0.08f, 1);
|
|
||||||
c[ImGuiCol_FrameBgHovered] = ImVec4(0.24f, 0.18f, 0.10f, 1);
|
|
||||||
c[ImGuiCol_FrameBgActive] = kGreen;
|
|
||||||
c[ImGuiCol_SliderGrab] = kOcarina;
|
|
||||||
c[ImGuiCol_SliderGrabActive] = kGold;
|
|
||||||
c[ImGuiCol_CheckMark] = kGold;
|
|
||||||
c[ImGuiCol_Button] = ImVec4(0.19f, 0.145f, 0.09f, 1);
|
|
||||||
c[ImGuiCol_ButtonHovered] = kGreen;
|
|
||||||
c[ImGuiCol_ButtonActive] = kOcarina;
|
|
||||||
c[ImGuiCol_Header] = ImVec4(0.24f, 0.18f, 0.10f, 1);
|
|
||||||
c[ImGuiCol_HeaderHovered] = kGreen;
|
|
||||||
c[ImGuiCol_HeaderActive] = kOcarina;
|
|
||||||
c[ImGuiCol_Tab] = ImVec4(0.13f, 0.10f, 0.07f, 1);
|
|
||||||
c[ImGuiCol_TabHovered] = kGreen;
|
|
||||||
c[ImGuiCol_TabSelected] = ImVec4(0.42f, 0.31f, 0.15f, 1);
|
|
||||||
c[ImGuiCol_TabSelectedOverline] = kGold;
|
|
||||||
c[ImGuiCol_NavCursor] = kGold;
|
|
||||||
c[ImGuiCol_Separator] = ImVec4(kGold.x, kGold.y, kGold.z, 0.30f);
|
|
||||||
c[ImGuiCol_ScrollbarGrab] = ImVec4(0.36f, 0.28f, 0.16f, 1);
|
|
||||||
c[ImGuiCol_ScrollbarBg] = ImVec4(0, 0, 0, 0.2f);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Triforce, its top at (x, y), h high, drawn with the title.
|
// The Triforce, its top at (x, y), h high, drawn with the title.
|
||||||
static void triforce(ImDrawList *dl, float x, float y, float h, ImU32 col) {
|
static void triforce(ImDrawList *dl, float x, float y, float h, ImU32 col) {
|
||||||
@@ -266,7 +250,9 @@ static void make_context(void) {
|
|||||||
io.LogFilename = nullptr;
|
io.LogFilename = nullptr;
|
||||||
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_NavEnableGamepad;
|
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_NavEnableGamepad;
|
||||||
io.BackendPlatformName = "nx2navi_menu";
|
io.BackendPlatformName = "nx2navi_menu";
|
||||||
style_init(g_base_style);
|
// no window switcher on Ctrl+Tab (the menu is one window; the switcher would list its inner windows by their ids)
|
||||||
|
GImGui->ConfigNavWindowingKeyNext = GImGui->ConfigNavWindowingKeyPrev = 0;
|
||||||
|
skin_style(g_base_style);
|
||||||
ImGui::GetStyle() = g_base_style;
|
ImGui::GetStyle() = g_base_style;
|
||||||
g_ctx_ok = 1;
|
g_ctx_ok = 1;
|
||||||
}
|
}
|
||||||
@@ -398,11 +384,12 @@ static int fonts_up(float scale) {
|
|||||||
fa->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 26.0f * scale, &fc, kRanges);
|
fa->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 26.0f * scale, &fc, kRanges);
|
||||||
}
|
}
|
||||||
uint8_t *data[N] = {};
|
uint8_t *data[N] = {};
|
||||||
ImVector<ImWchar> ranges[N];
|
uint64_t sizes[N] = {};
|
||||||
|
ImVector<ImWchar> ranges[N], title_ranges[N];
|
||||||
int merged = 0;
|
int merged = 0;
|
||||||
for (int i = 0; i < N; i++) {
|
for (int i = 0; i < N; i++) {
|
||||||
char path[512];
|
char path[512];
|
||||||
uint64_t size = 0;
|
uint64_t &size = sizes[i];
|
||||||
if (!plat_font_path(kCjk[i].lang, path, sizeof path) || !(data[i] = plat_file_read(path, &size))) continue;
|
if (!plat_font_path(kCjk[i].lang, path, sizeof path) || !(data[i] = plat_file_read(path, &size))) continue;
|
||||||
if (!font_usable(data[i], size)) {
|
if (!font_usable(data[i], size)) {
|
||||||
rt_log("menu: system font %s left out: the font parser cannot read it (%llu bytes)", path,
|
rt_log("menu: system font %s left out: the font parser cannot read it (%llu bytes)", path,
|
||||||
@@ -435,7 +422,23 @@ static int fonts_up(float scale) {
|
|||||||
rc.MergeMode = true;
|
rc.MergeMode = true;
|
||||||
rc.FontDataOwnedByAtlas = false;
|
rc.FontDataOwnedByAtlas = false;
|
||||||
fa->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 30.0f * scale, &rc, kRanges);
|
fa->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 30.0f * scale, &rc, kRanges);
|
||||||
|
// what the title face shows in the CJK languages: the menu's title and tabs (Simplified Chinese menu text) and
|
||||||
|
// the boot screen's title (the game's language)
|
||||||
|
static const UiTextId titles[] = {UI_MENU_TITLE, UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
|
||||||
|
UI_MENU_TAB_CONTROLS, UI_BOOT_TITLE};
|
||||||
|
for (int i = 0; i < N; i++) {
|
||||||
|
if (!data[i]) continue;
|
||||||
|
ImFontGlyphRangesBuilder b;
|
||||||
|
for (UiTextId id : titles) b.AddText(ui_text_in(kCjk[i].lang, id));
|
||||||
|
b.BuildRanges(&title_ranges[i]);
|
||||||
|
ImFontConfig mc;
|
||||||
|
mc.MergeMode = true;
|
||||||
|
mc.FontDataOwnedByAtlas = false;
|
||||||
|
fa->AddFontFromMemoryTTF(data[i], (int)sizes[i], 31.0f * scale, &mc, title_ranges[i].Data);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
skin_atlas_add(fa); // the boxes' grain tile (ui/menu_skin.cpp), drawn into the atlas once it is built
|
||||||
|
skin_atlas_fill(fa); // builds the atlas, which the upload below then takes as it is
|
||||||
vk_queue_lock(); // the upload submits on the queue and waits for it
|
vk_queue_lock(); // the upload submits on the queue and waits for it
|
||||||
int ok = ImGui_ImplVulkan_CreateFontsTexture();
|
int ok = ImGui_ImplVulkan_CreateFontsTexture();
|
||||||
// ClarimoUDPE's line (ascent to descent, which is all Dear ImGui spaces lines by) leaves wrapped lines touching: the
|
// ClarimoUDPE's line (ascent to descent, which is all Dear ImGui spaces lines by) leaves wrapped lines touching: the
|
||||||
@@ -450,19 +453,25 @@ static int fonts_up(float scale) {
|
|||||||
return ok;
|
return ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The font atlas follows the window's scale: rebuilt at once when it is more than 12% off (text would blur or shrink
|
// The atlas for scale. While the scale keeps changing (the window being resized), the atlas is made again only once it
|
||||||
// visibly), else once the scale has held for half a second, so dragging a window's edge does not rebuild it, and read the
|
// has held for a quarter of a second, and the old one is drawn scaled meanwhile (io.FontGlobalScale): each atlas reads
|
||||||
// system's fonts again, every frame. Until then io.FontGlobalScale stretches the atlas there is. False: fonts_up failed.
|
// the system fonts from disk and waits for the queue to upload. 0 when no atlas could be made.
|
||||||
static bool fonts_follow(float scale) {
|
static float g_scale_seen;
|
||||||
static float last;
|
static uint64_t g_scale_seen_ns;
|
||||||
static uint64_t since;
|
|
||||||
uint64_t now = plat_now_ns();
|
static int fonts_for(float scale, uint64_t now) {
|
||||||
if (scale != last) last = scale, since = now;
|
|
||||||
ImGuiIO &io = ImGui::GetIO();
|
ImGuiIO &io = ImGui::GetIO();
|
||||||
if (g_font_scale != scale && (!g_font_scale || fabsf(g_font_scale / scale - 1) > 0.12f || now - since > 500000000ull))
|
if (g_font_scale == scale) {
|
||||||
if (!fonts_up(scale)) return false;
|
io.FontGlobalScale = 1;
|
||||||
io.FontGlobalScale = scale / g_font_scale;
|
return 1;
|
||||||
return true;
|
}
|
||||||
|
if (scale != g_scale_seen) g_scale_seen = scale, g_scale_seen_ns = now;
|
||||||
|
if (g_font_scale > 0 && now - g_scale_seen_ns < 250000000ull) {
|
||||||
|
io.FontGlobalScale = scale / g_font_scale;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
io.FontGlobalScale = 1;
|
||||||
|
return fonts_up(scale);
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" void menu_vk_release(void) {
|
extern "C" void menu_vk_release(void) {
|
||||||
@@ -740,21 +749,33 @@ static const char *present_name(const char *mode) {
|
|||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// "in use: VSync" under the Presentation value when the swapchain got another mode than the setting (a driver without
|
// "in use: VSync" under the VSync row when it is off and the driver cannot present without waiting; NULL otherwise, and
|
||||||
// mailbox gets fifo); NULL when they agree or before the first swapchain.
|
// before the first swapchain.
|
||||||
static const char *present_note(void) {
|
static const char *vsync_note(void) {
|
||||||
const char *got = gfx_window_present_mode(), *name = present_name(got);
|
const char *got = gfx_window_present_mode();
|
||||||
if (!*got || !strcmp(got, cfg_value("NX2NAVI_VK_PRESENT")) || !name) return nullptr;
|
if (!*got || strcmp(cfg_value("NX2NAVI_VK_PRESENT"), "immediate") || !strcmp(got, "immediate")) return nullptr;
|
||||||
static char note[96];
|
static char note[96];
|
||||||
snprintf(note, sizeof note, menu_text(UI_MENU_PRESENT_IN_USE), name);
|
snprintf(note, sizeof note, menu_text(UI_MENU_PRESENT_IN_USE), menu_text(UI_MENU_PRESENT_VSYNC));
|
||||||
return note;
|
return note;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- the tabs
|
// ---- the tabs
|
||||||
|
|
||||||
|
// The PCI vendor of the GPU the game renders on (menu_overlay_frame reads it from the device it is given; 0 before the
|
||||||
|
// first frame). DLSS runs on NVIDIA GPUs only, so the rows below leave it out elsewhere (AMD, Intel).
|
||||||
|
static std::atomic<uint32_t> g_gpu_vendor;
|
||||||
|
static VkPhysicalDevice g_gpu_vendor_of;
|
||||||
|
static bool dlss_offered(void) {
|
||||||
|
uint32_t v = g_gpu_vendor.load(std::memory_order_relaxed);
|
||||||
|
return v == 0 || v == 0x10de; // unknown (no frame yet): as before, offered
|
||||||
|
}
|
||||||
|
|
||||||
// One upscaling choice over three settings: NX2NAVI_UPSCALER (how the picture is fitted to the window), NX2NAVI_DLAA
|
// One upscaling choice over three settings: NX2NAVI_UPSCALER (how the picture is fitted to the window), NX2NAVI_DLAA
|
||||||
// (DLSS on) and NX2NAVI_DLSS (its mode, the render scale: widescreen.c wide_present). A DLSS mode fits the picture with
|
// (DLSS or FSR 3.1 on) with NX2NAVI_TAA (which of them) and NX2NAVI_DLSS (the mode, the render scale: widescreen.c
|
||||||
// bilinear, DLSS having made it; the model is NVIDIA's own for the mode (vk_dlaa.c evaluate, dlss_preset at its default).
|
// wide_present). A temporal mode fits the picture with bilinear, the upscaler having made it; DLSS's model is NVIDIA's own
|
||||||
|
// for the mode (vk_dlaa.c evaluate, dlss_preset at its default). The list: bilinear, FSR 1, the DLSS modes where DLSS
|
||||||
|
// runs (dlss_offered), the FSR 3.1 modes; a DLSS mode still set where DLSS does not run stays listed last until another
|
||||||
|
// choice replaces it, so the row shows what is set.
|
||||||
static void row_upscaling(void) {
|
static void row_upscaling(void) {
|
||||||
static const char *const modes[] = {"dlaa", "quality", "balanced", "performance", "ultra_performance"};
|
static const char *const modes[] = {"dlaa", "quality", "balanced", "performance", "ultra_performance"};
|
||||||
static const UiTextId mode_names[] = {UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED,
|
static const UiTextId mode_names[] = {UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED,
|
||||||
@@ -762,28 +783,51 @@ static void row_upscaling(void) {
|
|||||||
// FSR 3.1's modes take the same render scales as DLSS's (Native AA is FSR's name for DLAA's full size)
|
// FSR 3.1's modes take the same render scales as DLSS's (Native AA is FSR's name for DLAA's full size)
|
||||||
static const UiTextId fsr_names[] = {UI_MENU_FSR3_NATIVE, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED,
|
static const UiTextId fsr_names[] = {UI_MENU_FSR3_NATIVE, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED,
|
||||||
UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA};
|
UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA};
|
||||||
static char dl[10][96];
|
enum { BILINEAR, FSR1, DLSS, FSR3 };
|
||||||
const char *names[12] = {menu_text(UI_MENU_UPSCALER_BILINEAR), menu_text(UI_MENU_UPSCALER_FSR)};
|
struct Entry { int kind, mode; };
|
||||||
for (int i = 0; i < 5; i++) {
|
static char text[10][96];
|
||||||
snprintf(dl[i], sizeof dl[i], i ? "DLSS %s" : "NVIDIA %s", menu_text(mode_names[i]));
|
Entry list[12];
|
||||||
snprintf(dl[5 + i], sizeof dl[5 + i], "AMD FSR 3.1 %s", menu_text(fsr_names[i]));
|
const char *names[12];
|
||||||
names[2 + i] = dl[i], names[7 + i] = dl[5 + i];
|
int n = 0;
|
||||||
}
|
auto add = [&](int kind, int mode) {
|
||||||
int cur = strcmp(cfg_value("NX2NAVI_UPSCALER"), "fsr") ? 0 : 1;
|
list[n] = {kind, mode};
|
||||||
|
if (kind == BILINEAR) names[n] = menu_text(UI_MENU_UPSCALER_BILINEAR);
|
||||||
|
else if (kind == FSR1) names[n] = menu_text(UI_MENU_UPSCALER_FSR);
|
||||||
|
else {
|
||||||
|
char *t = text[(kind == FSR3 ? 5 : 0) + mode];
|
||||||
|
if (kind == DLSS) snprintf(t, sizeof text[0], mode ? "DLSS %s" : "NVIDIA %s", menu_text(mode_names[mode]));
|
||||||
|
else snprintf(t, sizeof text[0], "AMD FSR 3.1 %s", menu_text(fsr_names[mode]));
|
||||||
|
names[n] = t;
|
||||||
|
}
|
||||||
|
n++;
|
||||||
|
};
|
||||||
|
// what is set now
|
||||||
|
Entry now = {strcmp(cfg_value("NX2NAVI_UPSCALER"), "fsr") ? BILINEAR : FSR1, 0};
|
||||||
if (cfg_bool("NX2NAVI_DLAA")) {
|
if (cfg_bool("NX2NAVI_DLAA")) {
|
||||||
int base = strcmp(cfg_value("NX2NAVI_TAA"), "fsr3") ? 2 : 7;
|
now = {strcmp(cfg_value("NX2NAVI_TAA"), "fsr3") ? DLSS : FSR3, 0};
|
||||||
cur = base;
|
|
||||||
for (int i = 0; i < 5; i++)
|
for (int i = 0; i < 5; i++)
|
||||||
if (!strcmp(cfg_value("NX2NAVI_DLSS"), modes[i])) cur = base + i;
|
if (!strcmp(cfg_value("NX2NAVI_DLSS"), modes[i])) now.mode = i;
|
||||||
}
|
}
|
||||||
int nv = opt_choice_index("NX2NAVI_UPSCALER", UI_MENU_UPSCALING, names, 12, cur, 1, UI_MENU_UPSCALING_DESC,
|
const bool dlss = dlss_offered();
|
||||||
cur >= 2 ? menu_text(UI_MENU_UPSCALING_DLSS_NOTE) : nullptr);
|
add(BILINEAR, 0);
|
||||||
if (nv < 0) return;
|
add(FSR1, 0);
|
||||||
opt_apply("NX2NAVI_UPSCALER", nv == 1 ? "fsr" : "bilinear");
|
for (int i = 0; dlss && i < 5; i++) add(DLSS, i);
|
||||||
opt_apply("NX2NAVI_DLAA", nv >= 2 ? "1" : "0");
|
for (int i = 0; i < 5; i++) add(FSR3, i);
|
||||||
if (nv < 2) opt_apply("NX2NAVI_FRAMEGEN", "off"); // it needs DLSS's or FSR 3.1's motion vectors (row_framegen)
|
if (!dlss && now.kind == DLSS) add(DLSS, now.mode);
|
||||||
if (nv >= 2) opt_apply("NX2NAVI_DLSS", modes[(nv - 2) % 5]);
|
int cur = 0;
|
||||||
if (nv >= 2) opt_apply("NX2NAVI_TAA", nv >= 7 ? "fsr3" : "dlss");
|
for (int i = 0; i < n; i++)
|
||||||
|
if (list[i].kind == now.kind && list[i].mode == now.mode) cur = i;
|
||||||
|
bool temporal = now.kind >= DLSS;
|
||||||
|
int nv = opt_choice_index("NX2NAVI_UPSCALER", UI_MENU_UPSCALING, names, n, cur, 1,
|
||||||
|
dlss ? UI_MENU_UPSCALING_DESC : UI_MENU_UPSCALING_DESC_FSR,
|
||||||
|
temporal ? menu_text(dlss ? UI_MENU_UPSCALING_DLSS_NOTE : UI_MENU_UPSCALING_FSR_NOTE) : nullptr);
|
||||||
|
if (nv < 0 || nv >= n) return;
|
||||||
|
const Entry e = list[nv];
|
||||||
|
opt_apply("NX2NAVI_UPSCALER", e.kind == FSR1 ? "fsr" : "bilinear");
|
||||||
|
opt_apply("NX2NAVI_DLAA", e.kind >= DLSS ? "1" : "0");
|
||||||
|
if (e.kind < DLSS) opt_apply("NX2NAVI_FRAMEGEN", "off"); // it needs DLSS's or FSR 3.1's motion vectors (row_framegen)
|
||||||
|
if (e.kind >= DLSS) opt_apply("NX2NAVI_DLSS", modes[e.mode]);
|
||||||
|
if (e.kind >= DLSS) opt_apply("NX2NAVI_TAA", e.kind == FSR3 ? "fsr3" : "dlss");
|
||||||
}
|
}
|
||||||
|
|
||||||
// "in use: off" under the HDR value when the game started with HDR on but the swapchain is not HDR10 (the display or
|
// "in use: off" under the HDR value when the game started with HDR on but the swapchain is not HDR10 (the display or
|
||||||
@@ -813,7 +857,8 @@ static void row_hdr(void) {
|
|||||||
// Frame generation (vk_fg.cpp), after a restart; it needs a temporal upscaler's motion vectors
|
// Frame generation (vk_fg.cpp), after a restart; it needs a temporal upscaler's motion vectors
|
||||||
static void row_framegen(void) {
|
static void row_framegen(void) {
|
||||||
// the generated frames are made from DLSS's or FSR 3.1's motion vectors: without one of them it would do nothing
|
// the generated frames are made from DLSS's or FSR 3.1's motion vectors: without one of them it would do nothing
|
||||||
if (!cfg_bool("NX2NAVI_DLAA")) opt_disable_next(UI_MENU_FRAMEGEN_NEEDS);
|
const bool dlss = dlss_offered();
|
||||||
|
if (!cfg_bool("NX2NAVI_DLAA")) opt_disable_next(dlss ? UI_MENU_FRAMEGEN_NEEDS : UI_MENU_FRAMEGEN_NEEDS_FSR);
|
||||||
static const char *const values[] = {"off", "fsr3", "dlss"};
|
static const char *const values[] = {"off", "fsr3", "dlss"};
|
||||||
const char *names[] = {menu_text(UI_MENU_FRAMEGEN_OFF), "AMD FSR 3.1", "NVIDIA DLSS"};
|
const char *names[] = {menu_text(UI_MENU_FRAMEGEN_OFF), "AMD FSR 3.1", "NVIDIA DLSS"};
|
||||||
const char *v = cfg_value("NX2NAVI_FRAMEGEN");
|
const char *v = cfg_value("NX2NAVI_FRAMEGEN");
|
||||||
@@ -821,9 +866,10 @@ static void row_framegen(void) {
|
|||||||
// NVIDIA DLSS (vk_dlssg.c) is listed only while it is set: Streamline now starts and takes the swapchain, but presents
|
// NVIDIA DLSS (vk_dlssg.c) is listed only while it is set: Streamline now starts and takes the swapchain, but presents
|
||||||
// no generated frames yet (one presented per frame, status OK)
|
// no generated frames yet (one presented per frame, status OK)
|
||||||
int n = cur == 2 ? 3 : 2;
|
int n = cur == 2 ? 3 : 2;
|
||||||
int nv = opt_choice_index("NX2NAVI_FRAMEGEN", UI_MENU_FRAMEGEN, names, n, cur, 0, UI_MENU_FRAMEGEN_DESC,
|
int nv = opt_choice_index("NX2NAVI_FRAMEGEN", UI_MENU_FRAMEGEN, names, n, cur, 0,
|
||||||
menu_text(UI_MENU_FRAMEGEN_NOTE));
|
dlss ? UI_MENU_FRAMEGEN_DESC : UI_MENU_FRAMEGEN_DESC_FSR,
|
||||||
if (nv >= 0) opt_apply("NX2NAVI_FRAMEGEN", values[nv]);
|
menu_text(dlss ? UI_MENU_FRAMEGEN_NOTE : UI_MENU_FRAMEGEN_NOTE_FSR));
|
||||||
|
if (nv >= 0 && nv < n) opt_apply("NX2NAVI_FRAMEGEN", values[nv]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The picture's height (widescreen.c picture_height): the game's 1440 or more.
|
// The picture's height (widescreen.c picture_height): the game's 1440 or more.
|
||||||
@@ -837,8 +883,9 @@ static void tab_screen(float scale) {
|
|||||||
opt_begin("##screen", scale);
|
opt_begin("##screen", scale);
|
||||||
opt_toggle("NX2NAVI_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC);
|
opt_toggle("NX2NAVI_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC);
|
||||||
row_window_size();
|
row_window_size();
|
||||||
static const UiTextId present[] = {UI_MENU_PRESENT_MAILBOX, UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_IMMEDIATE};
|
// On is the default mode, mailbox with its fallbacks (gfx_present.c pick_present_mode): plain fifo would drop the
|
||||||
opt_choice("NX2NAVI_VK_PRESENT", UI_MENU_PRESENT, present, 3, UI_MENU_PRESENT_DESC, present_note());
|
// game to 30 at every slow frame on a 60 Hz display. A fifo already saved also reads as on.
|
||||||
|
opt_toggle_value("NX2NAVI_VK_PRESENT", UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_DESC, "mailbox", "immediate", vsync_note());
|
||||||
row_gpu();
|
row_gpu();
|
||||||
static const UiTextId perf[] = {UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL};
|
static const UiTextId perf[] = {UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL};
|
||||||
opt_choice("NX2NAVI_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC);
|
opt_choice("NX2NAVI_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC);
|
||||||
@@ -859,8 +906,6 @@ static void tab_screen(float scale) {
|
|||||||
int dl = cfg_bool("NX2NAVI_DLAA"), fsr3 = dl && !strcmp(cfg_value("NX2NAVI_TAA"), "fsr3");
|
int dl = cfg_bool("NX2NAVI_DLAA"), fsr3 = dl && !strcmp(cfg_value("NX2NAVI_TAA"), "fsr3");
|
||||||
if (!fsr3 && (strcmp(cfg_value("NX2NAVI_UPSCALER"), "fsr") || dl)) opt_disable_next(UI_MENU_SHARPNESS_NEEDS_FSR);
|
if (!fsr3 && (strcmp(cfg_value("NX2NAVI_UPSCALER"), "fsr") || dl)) opt_disable_next(UI_MENU_SHARPNESS_NEEDS_FSR);
|
||||||
opt_slider("NX2NAVI_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%");
|
opt_slider("NX2NAVI_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%");
|
||||||
static const UiTextId aspect[] = {UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH};
|
|
||||||
opt_choice("NX2NAVI_ASPECT", UI_MENU_ASPECT, aspect, 2, UI_MENU_ASPECT_DESC);
|
|
||||||
opt_end();
|
opt_end();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -955,34 +1000,44 @@ static const char *prompts_note(bool *restart) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The confirmation of "Restart now", over the menu; Cancel has the cursor first. Restart writes nx2navi.ini, then closes
|
// The confirmation of the menu's Restart button, over the menu; Cancel has the cursor first. Restart writes nx2navi.ini,
|
||||||
// the game as Quit does and starts it again (gfx_window_request_restart). It waits while the game writes a save, and
|
// then closes the game as Quit does and starts it again (gfx_window_request_restart). It waits while the game writes a
|
||||||
// the game stays when nx2navi.ini cannot be written, as the new prompts would not come back. From the Cheats tab
|
// save, and the game stays when nx2navi.ini cannot be written, as the changed settings would not come back. From the
|
||||||
// (restart_rebuild) Restart also lets the next start rebuild for cheats whose last rebuild failed (cheats_rebuild_allow).
|
// Cheats tab (restart_rebuild) Restart also lets the next start rebuild for cheats whose last rebuild failed
|
||||||
static bool restart_rebuild;
|
// (cheats_rebuild_allow). The Quit button's confirmation is the same box (g_confirm_quit): closing the window already
|
||||||
static void restart_confirm(void) {
|
// finishes a save in progress (gfx_window_closed), so it does not wait.
|
||||||
|
static bool restart_rebuild, g_confirm_quit;
|
||||||
|
static void restart_confirm(float scale) {
|
||||||
g_modal = false;
|
g_modal = false;
|
||||||
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
|
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
|
||||||
if (!ImGui::BeginPopupModal("##restart_confirm", nullptr,
|
ImGui::PushStyleVar(ImGuiStyleVar_PopupBorderSize, 0);
|
||||||
ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize))
|
const bool open = ImGui::BeginPopupModal("##confirm", nullptr,
|
||||||
return;
|
ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize);
|
||||||
|
ImGui::PopStyleVar();
|
||||||
|
if (!open) return;
|
||||||
g_modal = true;
|
g_modal = true;
|
||||||
ImGui::TextUnformatted(menu_text(UI_MENU_RESTART_CONFIRM));
|
const ImVec2 box = ImGui::GetWindowPos(), box_size = ImGui::GetWindowSize();
|
||||||
bool saving = fs_save_busy() != 0;
|
skin_panel(ImGui::GetWindowDrawList(), box, ImVec2(box.x + box_size.x, box.y + box_size.y), scale);
|
||||||
if (saving || !cfg_last_save_ok())
|
ImGui::TextUnformatted(menu_text(g_confirm_quit ? UI_MENU_QUIT_CONFIRM : UI_MENU_RESTART_CONFIRM));
|
||||||
|
bool saving = !g_confirm_quit && fs_save_busy() != 0;
|
||||||
|
if (saving || (!g_confirm_quit && !cfg_last_save_ok()))
|
||||||
ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s",
|
ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s",
|
||||||
menu_text(saving ? UI_MENU_RESTART_SAVING : UI_MENU_SAVE_FAILED));
|
menu_text(saving ? UI_MENU_RESTART_SAVING : UI_MENU_SAVE_FAILED));
|
||||||
ImGui::Spacing();
|
ImGui::Spacing();
|
||||||
const char *yes = menu_text(UI_MENU_RESTART_YES), *no = menu_text(UI_MENU_RESET_NO);
|
const char *yes = menu_text(g_confirm_quit ? UI_MENU_QUIT : UI_MENU_RESTART_YES), *no = menu_text(UI_MENU_RESET_NO);
|
||||||
const ImGuiStyle &st = ImGui::GetStyle();
|
const ImGuiStyle &st = ImGui::GetStyle();
|
||||||
float bw = fmaxf(ImGui::CalcTextSize(yes).x, ImGui::CalcTextSize(no).x) + st.FramePadding.x * 4;
|
float bw = fmaxf(ImGui::CalcTextSize(yes).x, ImGui::CalcTextSize(no).x) + st.FramePadding.x * 4;
|
||||||
bool close = ImGui::Button(no, ImVec2(bw, 0));
|
bool close = skin_widget_button(no, ImVec2(bw, 0), scale);
|
||||||
if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus();
|
if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus();
|
||||||
ImGui::SameLine();
|
ImGui::SameLine(0, st.ItemSpacing.x + skin_cursor_reach(scale));
|
||||||
ImGui::BeginDisabled(saving);
|
ImGui::BeginDisabled(saving);
|
||||||
if (ImGui::Button(yes, ImVec2(bw, 0)) && cfg_save()) {
|
if (skin_widget_button(yes, ImVec2(bw, 0), scale)) {
|
||||||
if (restart_rebuild) cheats_rebuild_allow();
|
if (g_confirm_quit) {
|
||||||
gfx_window_request_restart();
|
gfx_window_request_close();
|
||||||
|
} else if (cfg_save()) {
|
||||||
|
if (restart_rebuild) cheats_rebuild_allow();
|
||||||
|
gfx_window_request_restart();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ImGui::EndDisabled();
|
ImGui::EndDisabled();
|
||||||
if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))
|
if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))
|
||||||
@@ -990,7 +1045,6 @@ static void restart_confirm(void) {
|
|||||||
if (close) {
|
if (close) {
|
||||||
ImGui::CloseCurrentPopup();
|
ImGui::CloseCurrentPopup();
|
||||||
restart_rebuild = false;
|
restart_rebuild = false;
|
||||||
opt_focus_key("##restart"); // back on the row it came from
|
|
||||||
}
|
}
|
||||||
ImGui::EndPopup();
|
ImGui::EndPopup();
|
||||||
}
|
}
|
||||||
@@ -1031,18 +1085,26 @@ static void go_to(int tab, const char *key) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The game's interface sounds (menu_sound.c) for what the frame did: a press or click on an item, the cursor on another
|
// The game's interface sounds (menu_sound.c) for what the frame did: a press or click on an item, the cursor on another
|
||||||
// item, another tab by a click (L and R play theirs where they are read). The first frame after opening only records.
|
// item, another tab by a click (L, R, Q and E play theirs where they are read: g_tab_sounded). The first frame after
|
||||||
|
// opening only records: the open sound has played, and the cursor going to the first row is part of it. g_sound_fresh
|
||||||
|
// marks that frame, as the frame count alone does not when nothing was laid out while the menu was closed.
|
||||||
|
static bool g_sound_fresh;
|
||||||
|
static int g_tab_sounded = -1; // the tab L / R / Q / E asked for, its sound played
|
||||||
|
|
||||||
static void menu_sounds_frame(void) {
|
static void menu_sounds_frame(void) {
|
||||||
ImGuiContext &g = *GImGui;
|
ImGuiContext &g = *GImGui;
|
||||||
static int last_frame = -2, last_tab = -1;
|
static int last_frame = -2, last_tab = -1;
|
||||||
static ImGuiID last_nav;
|
static ImGuiID last_nav;
|
||||||
bool fresh = g.FrameCount != last_frame + 1;
|
bool fresh = g_sound_fresh || g.FrameCount != last_frame + 1;
|
||||||
|
g_sound_fresh = false;
|
||||||
last_frame = g.FrameCount;
|
last_frame = g.FrameCount;
|
||||||
if (!fresh) {
|
if (!fresh) {
|
||||||
if (g.ActiveId && g.ActiveIdIsJustActivated) menu_sound_play(MENU_SOUND_DECIDE);
|
if (g.ActiveId && g.ActiveIdIsJustActivated) menu_sound_play(MENU_SOUND_DECIDE);
|
||||||
else if (g.NavId && g.NavId != last_nav) menu_sound_play(MENU_SOUND_CURSOR);
|
else if (g.NavId && g.NavId != last_nav) menu_sound_play(MENU_SOUND_CURSOR);
|
||||||
if (g_tab != last_tab && last_tab >= 0) menu_sound_play(g_tab > last_tab ? MENU_SOUND_TAB_RIGHT : MENU_SOUND_TAB_LEFT);
|
if (g_tab != last_tab && last_tab >= 0 && g_tab != g_tab_sounded)
|
||||||
|
menu_sound_play(g_tab > last_tab ? MENU_SOUND_TAB_RIGHT : MENU_SOUND_TAB_LEFT);
|
||||||
}
|
}
|
||||||
|
if (g_tab != last_tab) g_tab_sounded = -1;
|
||||||
last_nav = g.NavId, last_tab = g_tab;
|
last_nav = g.NavId, last_tab = g_tab;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1058,7 +1120,6 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
|||||||
ImGuiWindowFlags_NoSavedSettings);
|
ImGuiWindowFlags_NoSavedSettings);
|
||||||
if (framed) ImGui::PopStyleVar();
|
if (framed) ImGui::PopStyleVar();
|
||||||
const ImVec2 win_p = ImGui::GetWindowPos(), win_s = ImGui::GetWindowSize();
|
const ImVec2 win_p = ImGui::GetWindowPos(), win_s = ImGui::GetWindowSize();
|
||||||
const float inset = 7 * scale;
|
|
||||||
// The game's ornamented frame (ui/menu_art.cpp; nothing without the RomFS's), in gold. Its lines lie inside the
|
// The game's ornamented frame (ui/menu_art.cpp; nothing without the RomFS's), in gold. Its lines lie inside the
|
||||||
// texture (about 4 % of the width, 7 % of the height in), so the frame is drawn that far outside the window and its
|
// texture (about 4 % of the width, 7 % of the height in), so the frame is drawn that far outside the window and its
|
||||||
// lines run along the window's edge, clear of the title and the rows; unclipped, it may reach past the window.
|
// lines run along the window's edge, clear of the title and the rows; unclipped, it may reach past the window.
|
||||||
@@ -1085,19 +1146,24 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
|||||||
ImGui::SameLine();
|
ImGui::SameLine();
|
||||||
ImGui::TextUnformatted(menu_text(UI_MENU_TITLE));
|
ImGui::TextUnformatted(menu_text(UI_MENU_TITLE));
|
||||||
}
|
}
|
||||||
|
const float title_end = ImGui::GetItemRectMax().x;
|
||||||
if (g_title_font) ImGui::PopFont();
|
if (g_title_font) ImGui::PopFont();
|
||||||
// the port version and the game update, right-aligned on the title line: what a bug report needs first
|
// the port version and the game update, right-aligned on the title line: what a bug report needs first; left out
|
||||||
|
// where it would run into the title (a narrow window, a long title)
|
||||||
char game[16], version[96];
|
char game[16], version[96];
|
||||||
snprintf(game, sizeof game, "%d.%d.%d", rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10);
|
snprintf(game, sizeof game, "%d.%d.%d", rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10);
|
||||||
snprintf(version, sizeof version, "NX2navi %s - game %s", rt_port_version, game);
|
snprintf(version, sizeof version, "NX2navi %s - game %s", rt_port_version, game);
|
||||||
ImGui::SameLine(ImGui::GetWindowWidth() - ImGui::GetStyle().WindowPadding.x - ImGui::CalcTextSize(version).x);
|
float version_x = win_s.x - ImGui::GetStyle().WindowPadding.x - ImGui::CalcTextSize(version).x;
|
||||||
ImGui::TextDisabled("%s", version);
|
if (win_p.x + version_x >= title_end + ImGui::GetStyle().ItemSpacing.x * 2) {
|
||||||
|
ImGui::SameLine(version_x);
|
||||||
|
ImGui::TextDisabled("%s", version);
|
||||||
|
}
|
||||||
|
|
||||||
int step = g_modal || binds_modal() ? 0
|
int step = g_modal || binds_modal() ? 0
|
||||||
: ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false) || ImGui::IsKeyPressed(ImGuiKey_E, false) ? 1
|
: ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false) || ImGui::IsKeyPressed(ImGuiKey_E, false) ? 1
|
||||||
: ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false) || ImGui::IsKeyPressed(ImGuiKey_Q, false) ? -1
|
: ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false) || ImGui::IsKeyPressed(ImGuiKey_Q, false) ? -1
|
||||||
: 0;
|
: 0;
|
||||||
if (step) g_tab_request = (g_tab + step + TAB_COUNT) % TAB_COUNT;
|
if (step) g_tab_request = g_tab_sounded = (g_tab + step + TAB_COUNT) % TAB_COUNT;
|
||||||
if (step) menu_sound_play(step > 0 ? MENU_SOUND_TAB_RIGHT : MENU_SOUND_TAB_LEFT);
|
if (step) menu_sound_play(step > 0 ? MENU_SOUND_TAB_RIGHT : MENU_SOUND_TAB_LEFT);
|
||||||
if (g_tab_request >= 0) g_focus_page = g_tab_request; // the new page's first row takes the cursor
|
if (g_tab_request >= 0) g_focus_page = g_tab_request; // the new page's first row takes the cursor
|
||||||
|
|
||||||
@@ -1107,9 +1173,8 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
|||||||
for (int k = 0; k < TAB_COUNT; k++) {
|
for (int k = 0; k < TAB_COUNT; k++) {
|
||||||
char label[128];
|
char label[128];
|
||||||
snprintf(label, sizeof label, " %s ###tab%d", menu_text(kTabNames[k]), k); // the id stays per language
|
snprintf(label, sizeof label, " %s ###tab%d", menu_text(kTabNames[k]), k); // the id stays per language
|
||||||
if (g_title_font) ImGui::PushFont(g_title_font); // the tab labels in the title face
|
// the tab labels in the title face, on the rows' button (ui/menu_skin.cpp)
|
||||||
bool shown = ImGui::BeginTabItem(label, nullptr, g_tab_request == k ? ImGuiTabItemFlags_SetSelected : 0);
|
bool shown = skin_tab_item(label, menu_text(kTabNames[k]), g_tab_request == k ? ImGuiTabItemFlags_SetSelected : 0, scale, g_title_font);
|
||||||
if (g_title_font) ImGui::PopFont();
|
|
||||||
if (!shown) continue;
|
if (!shown) continue;
|
||||||
g_tab = k;
|
g_tab = k;
|
||||||
if (g_focus_page == k) {
|
if (g_focus_page == k) {
|
||||||
@@ -1146,15 +1211,20 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
|||||||
ImGui::SetCursorPosY(y + st.FramePadding.y);
|
ImGui::SetCursorPosY(y + st.FramePadding.y);
|
||||||
ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", menu_text(UI_MENU_SAVE_FAILED));
|
ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", menu_text(UI_MENU_SAVE_FAILED));
|
||||||
}
|
}
|
||||||
const char *cont = menu_text(UI_MENU_CONTINUE), *quit = menu_text(UI_MENU_QUIT);
|
const char *cont = menu_text(UI_MENU_CONTINUE), *restart = menu_text(UI_MENU_RESTART_YES), *quit = menu_text(UI_MENU_QUIT);
|
||||||
float bw = fmaxf(ImGui::CalcTextSize(cont).x, ImGui::CalcTextSize(quit).x) + st.FramePadding.x * 4;
|
float bw = fmaxf(fmaxf(ImGui::CalcTextSize(cont).x, ImGui::CalcTextSize(restart).x), ImGui::CalcTextSize(quit).x) + st.FramePadding.x * 4;
|
||||||
ImGui::SetCursorPos(ImVec2(ImGui::GetWindowWidth() - st.WindowPadding.x - bw * 2 - st.ItemSpacing.x, y));
|
// the save menu's brown buttons, with the game's cursor on the selected one (ui/menu_skin.cpp)
|
||||||
if (ImGui::Button(cont, ImVec2(bw, 0))) set_open(0);
|
float gap = st.ItemSpacing.x + skin_cursor_reach(scale);
|
||||||
ImGui::SameLine();
|
// right-aligned; in a window too narrow for all three, from the left edge
|
||||||
if (ImGui::Button(quit, ImVec2(bw, 0))) gfx_window_request_close();
|
ImGui::SetCursorPos(ImVec2(fmaxf(st.WindowPadding.x, ImGui::GetWindowWidth() - st.WindowPadding.x - bw * 3 - gap * 2), y));
|
||||||
|
if (skin_widget_button(cont, ImVec2(bw, 0), scale)) set_open(0);
|
||||||
|
ImGui::SameLine(0, gap);
|
||||||
|
if (skin_widget_button(restart, ImVec2(bw, 0), scale)) g_confirm_quit = false, ImGui::OpenPopup("##confirm");
|
||||||
|
ImGui::SameLine(0, gap);
|
||||||
|
if (skin_widget_button(quit, ImVec2(bw, 0), scale)) g_confirm_quit = true, ImGui::OpenPopup("##confirm");
|
||||||
|
restart_confirm(scale);
|
||||||
menu_sounds_frame();
|
menu_sounds_frame();
|
||||||
bool was_modal = g_modal || binds_modal();
|
bool was_modal = g_modal || binds_modal();
|
||||||
if (g_tab != TAB_CONTROLS) g_modal = false;
|
|
||||||
if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)))
|
if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)))
|
||||||
set_open(0);
|
set_open(0);
|
||||||
ImGui::End();
|
ImGui::End();
|
||||||
@@ -1240,54 +1310,13 @@ static void perf_tick(uint64_t now, const MenuTarget *t) {
|
|||||||
g_perf_last_ns = now;
|
g_perf_last_ns = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The panel keeps its width while the numbers change: every column is as wide as the widest text it can show, measured
|
|
||||||
// on samples of 8s (Roboto's digits share one width), and the numbers are right-aligned in it.
|
|
||||||
struct PerfCol { UiTextId fmt; float sample; };
|
|
||||||
|
|
||||||
static float perf_text_w(UiTextId fmt, float v) {
|
|
||||||
char b[64];
|
|
||||||
snprintf(b, sizeof b, menu_text(fmt), v);
|
|
||||||
return ImGui::CalcTextSize(b).x;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A fixed column as wide as the widest of the formats (with their samples) and labels given.
|
|
||||||
static void perf_column(const char *id, const PerfCol *cols, int n, const UiTextId *labels = nullptr, int nl = 0) {
|
|
||||||
float w = ImGui::CalcTextSize(menu_text(UI_MENU_OV_NONE)).x;
|
|
||||||
for (int i = 0; i < n; i++) w = fmaxf(w, perf_text_w(cols[i].fmt, cols[i].sample));
|
|
||||||
for (int i = 0; i < nl; i++) w = fmaxf(w, ImGui::CalcTextSize(menu_text(labels[i])).x);
|
|
||||||
ImGui::TableSetupColumn(id, ImGuiTableColumnFlags_WidthFixed, w);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void perf_right(const char *s, bool dim) {
|
|
||||||
float pad = ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(s).x;
|
|
||||||
if (pad > 0) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + pad);
|
|
||||||
if (dim) ImGui::TextDisabled("%s", s);
|
|
||||||
else ImGui::TextUnformatted(s);
|
|
||||||
}
|
|
||||||
|
|
||||||
// One cell of the full panel's table: fmt (a catalog format, one number) with v, or "-" when the machine gives none.
|
|
||||||
static void perf_cell(UiTextId fmt, float v) {
|
|
||||||
ImGui::TableNextColumn();
|
|
||||||
if (v < 0) return perf_right(menu_text(UI_MENU_OV_NONE), true);
|
|
||||||
char b[64];
|
|
||||||
snprintf(b, sizeof b, menu_text(fmt), v);
|
|
||||||
perf_right(b, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void perf_label(UiTextId label, const ImVec4 &c) {
|
|
||||||
ImGui::TableNextColumn();
|
|
||||||
ImGui::TextColored(c, "%s", menu_text(label));
|
|
||||||
}
|
|
||||||
|
|
||||||
static float perf_gb(float mb) { return mb < 0 ? -1 : mb / 1024; }
|
|
||||||
|
|
||||||
// The picture lines: the window, the game image the present shows and the 3D scene it holds (resolution.c), how the
|
// The picture lines: the window, the game image the present shows and the 3D scene it holds (resolution.c), how the
|
||||||
// present scales the image to the window (gfx_present.c, the last present), the frame limit and the presentation mode
|
// present scales the image to the window (gfx_present.c, the last present), the frame limit and the presentation mode
|
||||||
// in use.
|
// in use; formatted into the panel's picture lines.
|
||||||
static void perf_picture(const MenuTarget *t, const ImVec4 &c) {
|
static void perf_picture(const MenuTarget *t, PerfPanel *p) {
|
||||||
unsigned out[2], scene[2];
|
unsigned out[2], scene[2];
|
||||||
res_sizes(out, scene);
|
res_sizes(out, scene);
|
||||||
char v[6][64];
|
char (*v)[64] = p->picture;
|
||||||
snprintf(v[0], sizeof v[0], menu_text(UI_MENU_OV_FMT_SIZE), t->width, t->height);
|
snprintf(v[0], sizeof v[0], menu_text(UI_MENU_OV_FMT_SIZE), t->width, t->height);
|
||||||
snprintf(v[1], sizeof v[1], menu_text(UI_MENU_OV_FMT_SIZE), (unsigned)t->image_w, (unsigned)t->image_h);
|
snprintf(v[1], sizeof v[1], menu_text(UI_MENU_OV_FMT_SIZE), (unsigned)t->image_w, (unsigned)t->image_h);
|
||||||
snprintf(v[2], sizeof v[2], menu_text(UI_MENU_OV_FMT_SCENE), scene[0], scene[1], scene[0] * 100.0 / out[0]);
|
snprintf(v[2], sizeof v[2], menu_text(UI_MENU_OV_FMT_SCENE), scene[0], scene[1], scene[0] * 100.0 / out[0]);
|
||||||
@@ -1309,42 +1338,16 @@ static void perf_picture(const MenuTarget *t, const ImVec4 &c) {
|
|||||||
if (hz > 0) snprintf(v[4], sizeof v[4], menu_text(UI_MENU_OV_FPS), hz);
|
if (hz > 0) snprintf(v[4], sizeof v[4], menu_text(UI_MENU_OV_FPS), hz);
|
||||||
const char *pm = present_name(gfx_window_present_mode());
|
const char *pm = present_name(gfx_window_present_mode());
|
||||||
snprintf(v[5], sizeof v[5], "%s", pm ? pm : menu_text(UI_MENU_OV_NONE));
|
snprintf(v[5], sizeof v[5], "%s", pm ? pm : menu_text(UI_MENU_OV_NONE));
|
||||||
static const UiTextId labels[6] = {UI_MENU_OV_WINDOW, UI_MENU_OV_OUTPUT, UI_MENU_OV_SCENE,
|
// The 3D scene's size is known only where resolution.c sets it (the builds with its patch sets); Ocarina sizes its
|
||||||
UI_MENU_OV_SCALING, UI_MENU_OV_LIMIT, UI_MENU_OV_PRESENT};
|
// own scene dynamically and res_sizes would report a fixed 1600x900, so the line is left out
|
||||||
// The 3D scene's size is known only where resolution.c sets it (the builds with its patch sets); Ocarina sizes its own scene
|
p->scene_known = res_adjustable() != 0;
|
||||||
// dynamically and res_sizes would report a fixed 1600x900, so the line is left out
|
|
||||||
bool scene_known = res_adjustable() != 0;
|
|
||||||
if (!ImGui::BeginTable("##perfp", 2, ImGuiTableFlags_SizingFixedFit)) return;
|
|
||||||
float vw = 0;
|
|
||||||
for (auto &s : v) vw = fmaxf(vw, ImGui::CalcTextSize(s).x);
|
|
||||||
ImGui::TableSetupColumn("##p0", ImGuiTableColumnFlags_WidthStretch);
|
|
||||||
ImGui::TableSetupColumn("##p1", ImGuiTableColumnFlags_WidthFixed, vw);
|
|
||||||
for (int i = 0; i < 6; i++) {
|
|
||||||
if (i == 2 && !scene_known) continue;
|
|
||||||
perf_label(labels[i], c);
|
|
||||||
ImGui::TableNextColumn();
|
|
||||||
perf_right(v[i], false);
|
|
||||||
}
|
|
||||||
ImGui::EndTable();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The full panel (ui/perf_panel.cpp draws it in the menu's look): the numbers of this frame.
|
||||||
static void perf_full_draw(const MenuTarget *t, float scale) {
|
static void perf_full_draw(const MenuTarget *t, float scale) {
|
||||||
float w = (float)t->width;
|
static PerfPanel p;
|
||||||
PerfStats s;
|
perfmon_snapshot(&p.s);
|
||||||
perfmon_snapshot(&s);
|
// the port version and the game update, formatted once per menu language
|
||||||
ImGui::SetNextWindowPos(ImVec2(w - 12 * scale, 12 * scale), ImGuiCond_Always, ImVec2(1, 0));
|
|
||||||
ImGui::SetNextWindowBgAlpha(0.6f);
|
|
||||||
ImGui::Begin("##perf", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize |
|
|
||||||
ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoNav |
|
|
||||||
ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoSavedSettings);
|
|
||||||
// under the menu while it is open (the settings stay readable), else over everything
|
|
||||||
if (g_open.load(std::memory_order_relaxed)) ImGui::BringWindowToDisplayBack(ImGui::GetCurrentWindow());
|
|
||||||
else ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindow());
|
|
||||||
ImGui::SetWindowFontScale(0.72f);
|
|
||||||
const ImVec4 gpu_c(0.55f, 0.83f, 0.31f, 1), cpu_c(0.18f, 0.59f, 0.80f, 1), ram_c(0.80f, 0.45f, 0.70f, 1),
|
|
||||||
fps_c(0.95f, 0.95f, 0.95f, 1), wait_c(0.93f, 0.76f, 0.33f, 1), pic_c(0.62f, 0.70f, 0.95f, 1);
|
|
||||||
// the port version and the game update first, so a screenshot in a bug report carries both; formatted once per
|
|
||||||
// menu language
|
|
||||||
static char ver[96];
|
static char ver[96];
|
||||||
static const char *ver_fmt;
|
static const char *ver_fmt;
|
||||||
if (ver_fmt != menu_text(UI_MENU_VERSION)) {
|
if (ver_fmt != menu_text(UI_MENU_VERSION)) {
|
||||||
@@ -1353,82 +1356,11 @@ static void perf_full_draw(const MenuTarget *t, float scale) {
|
|||||||
snprintf(game, sizeof game, "%d.%d.%d", rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10);
|
snprintf(game, sizeof game, "%d.%d.%d", rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10);
|
||||||
snprintf(ver, sizeof ver, ver_fmt, rt_port_version, game);
|
snprintf(ver, sizeof ver, ver_fmt, rt_port_version, game);
|
||||||
}
|
}
|
||||||
ImGui::TextDisabled("%s", ver);
|
p.version = ver;
|
||||||
if (ImGui::BeginTable("##perft", 4, ImGuiTableFlags_SizingFixedFit)) {
|
perf_picture(t, &p);
|
||||||
static const UiTextId labels[] = {UI_MENU_OV_GPU, UI_MENU_OV_VRAM, UI_MENU_OV_CPU, UI_MENU_OV_RAM,
|
p.fg_fps = gfx_output_fps() > 0 ? (float)gfx_output_fps() : 0;
|
||||||
UI_MENU_OV_FPS_LABEL, UI_MENU_OV_FRAME_LABEL};
|
p.under_menu = g_open.load(std::memory_order_relaxed) != 0;
|
||||||
static const PerfCol c1[] = {{UI_MENU_OV_FMT_PCT, 100}, {UI_MENU_OV_FMT_GB, 888.8f}, {UI_MENU_OV_FMT_FPS, 888},
|
perf_panel_draw(&p, (float)t->width, scale);
|
||||||
{UI_MENU_OV_FRAME_MS, 888.8f}};
|
|
||||||
static const PerfCol c2[] = {{UI_MENU_OV_FMT_TEMP, 188}, {UI_MENU_OV_FMT_GB_OF, 888.8f}, {UI_MENU_OV_LOW1, 888},
|
|
||||||
{UI_MENU_OV_MAX_MS, 8888.8f}};
|
|
||||||
static const PerfCol c3[] = {{UI_MENU_OV_FMT_POWER, 888}, {UI_MENU_OV_FMT_MHZ, 8888}, {UI_MENU_OV_GAME_PCT, 100},
|
|
||||||
{UI_MENU_OV_GAME_GB, 888.8f}, {UI_MENU_OV_LOW01, 888}};
|
|
||||||
perf_column("##c0", nullptr, 0, labels, 6);
|
|
||||||
perf_column("##c1", c1, 4);
|
|
||||||
perf_column("##c2", c2, 4);
|
|
||||||
perf_column("##c3", c3, 5);
|
|
||||||
perf_label(UI_MENU_OV_GPU, gpu_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_PCT, s.gpu_pct);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_TEMP, s.gpu_temp_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_POWER, s.gpu_power_w);
|
|
||||||
perf_label(UI_MENU_OV_VRAM, gpu_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_GB, perf_gb(s.vram_used_mb));
|
|
||||||
perf_cell(UI_MENU_OV_FMT_GB_OF, perf_gb(s.vram_total_mb));
|
|
||||||
perf_cell(UI_MENU_OV_FMT_MHZ, s.gpu_clock_mhz);
|
|
||||||
perf_label(UI_MENU_OV_CPU, cpu_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_PCT, s.cpu_total_pct);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_TEMP, s.cpu_temp_c);
|
|
||||||
perf_cell(UI_MENU_OV_GAME_PCT, s.cpu_game_pct);
|
|
||||||
perf_label(UI_MENU_OV_RAM, ram_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_GB, perf_gb(s.ram_used_mb));
|
|
||||||
perf_cell(UI_MENU_OV_FMT_GB_OF, perf_gb(s.ram_total_mb));
|
|
||||||
perf_cell(UI_MENU_OV_GAME_GB, perf_gb(s.ram_game_mb));
|
|
||||||
ImGui::TableNextRow(ImGuiTableRowFlags_None, 6 * scale); // a gap between the machine and the frames
|
|
||||||
// the frames: the rate over the last second with the lows over the last ten seconds, then the frame times
|
|
||||||
perf_label(UI_MENU_OV_FPS_LABEL, fps_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_FPS, s.fps);
|
|
||||||
perf_cell(UI_MENU_OV_LOW1, s.low1_fps);
|
|
||||||
perf_cell(UI_MENU_OV_LOW01, s.low01_fps);
|
|
||||||
if (gfx_output_fps() > 0) { // frame generation: what the display gets, generated frames included
|
|
||||||
perf_label(UI_MENU_OV_FG_LABEL, fps_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_FPS, (float)gfx_output_fps());
|
|
||||||
ImGui::TableNextColumn();
|
|
||||||
ImGui::TableNextColumn();
|
|
||||||
}
|
|
||||||
perf_label(UI_MENU_OV_FRAME_LABEL, fps_c);
|
|
||||||
perf_cell(UI_MENU_OV_FRAME_MS, s.frame_ms_avg);
|
|
||||||
perf_cell(UI_MENU_OV_MAX_MS, s.frame_ms_max);
|
|
||||||
ImGui::TableNextColumn();
|
|
||||||
ImGui::EndTable();
|
|
||||||
}
|
|
||||||
float top = s.frame_ms_max > 50 ? s.frame_ms_max : 50;
|
|
||||||
// as wide as the panel the tables size; the plot does not count toward that width, so the panel can still shrink
|
|
||||||
ImGuiWindow *win = ImGui::GetCurrentWindow();
|
|
||||||
float max_x = win->DC.CursorMaxPos.x;
|
|
||||||
ImGui::PlotLines("##ft", s.frame_ms, PERF_HISTORY, 0, nullptr, 0, top, ImVec2(-FLT_MIN, 48 * scale));
|
|
||||||
win->DC.CursorMaxPos.x = max_x;
|
|
||||||
// per frame, averaged over the last half second; the labels' column stretches, so the numbers end at the panel's
|
|
||||||
// right edge, and the table still asks for no more than its widest label and number
|
|
||||||
if (ImGui::BeginTable("##perfw", 2, ImGuiTableFlags_SizingFixedFit)) {
|
|
||||||
static const PerfCol c1[] = {{UI_MENU_OV_FMT_MS, 888.88f}, {UI_MENU_OV_PER_FRAME, 888.8f}};
|
|
||||||
ImGui::TableSetupColumn("##w0", ImGuiTableColumnFlags_WidthStretch);
|
|
||||||
perf_column("##w1", c1, 2);
|
|
||||||
perf_label(UI_MENU_OV_REPLAY, wait_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_MS, s.replay_ms);
|
|
||||||
perf_label(UI_MENU_OV_GPU_TIME, wait_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_MS, s.gpu_ms);
|
|
||||||
perf_label(UI_MENU_OV_PIPE_WAIT, wait_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_MS, s.pipe_wait_ms);
|
|
||||||
perf_label(UI_MENU_OV_SHADER_WAIT, wait_c);
|
|
||||||
perf_cell(UI_MENU_OV_FMT_MS, s.xlate_ms);
|
|
||||||
perf_label(UI_MENU_OV_TEX_UPLOADS, wait_c);
|
|
||||||
perf_cell(UI_MENU_OV_PER_FRAME, s.tex_uploads);
|
|
||||||
ImGui::EndTable();
|
|
||||||
}
|
|
||||||
perf_picture(t, pic_c);
|
|
||||||
if (s.gpu_name[0]) ImGui::TextDisabled("%s", s.gpu_name);
|
|
||||||
if (s.cpu_name[0]) ImGui::TextDisabled("%s", s.cpu_name);
|
|
||||||
ImGui::End();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void perf_draw(const MenuTarget *t, float scale) {
|
static void perf_draw(const MenuTarget *t, float scale) {
|
||||||
@@ -1438,14 +1370,21 @@ static void perf_draw(const MenuTarget *t, float scale) {
|
|||||||
// with the menu open: under its window, over the dimming layout_menu drew before
|
// with the menu open: under its window, over the dimming layout_menu drew before
|
||||||
ImDrawList *dl = g_open.load(std::memory_order_relaxed) ? ImGui::GetBackgroundDrawList() : ImGui::GetForegroundDrawList();
|
ImDrawList *dl = g_open.load(std::memory_order_relaxed) ? ImGui::GetBackgroundDrawList() : ImGui::GetForegroundDrawList();
|
||||||
ImVec2 sz = ImGui::CalcTextSize(g_perf_text);
|
ImVec2 sz = ImGui::CalcTextSize(g_perf_text);
|
||||||
float pad = 6 * scale;
|
float padx = 14 * scale, pady = 9 * scale;
|
||||||
ImVec2 p(w - 12 * scale - sz.x - pad * 2, 12 * scale); // the top right corner: the game's HUD leaves it empty
|
ImVec2 p(w - 12 * scale - sz.x - padx * 2, 12 * scale); // the top right corner: the game's HUD leaves it empty
|
||||||
dl->AddRectFilled(p, ImVec2(p.x + sz.x + pad * 2, p.y + sz.y + pad * 2), IM_COL32(0, 0, 0, 150), 4 * scale);
|
// a small panel in the menu's look (ui/menu_skin.cpp), its frame scaled to the line
|
||||||
dl->AddText(ImVec2(p.x + pad, p.y + pad), IM_COL32(255, 255, 255, 235), g_perf_text);
|
skin_panel(dl, p, ImVec2(p.x + sz.x + padx * 2, p.y + sz.y + pady * 2), scale * 0.6f, 0.9f);
|
||||||
|
dl->AddText(ImVec2(p.x + padx, p.y + pady), SKIN_TEXT, g_perf_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
|
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
|
||||||
*shot = NULL;
|
*shot = NULL;
|
||||||
|
if (t->phys && t->phys != g_gpu_vendor_of) { // the GPU's vendor for the rows that depend on it (dlss_offered)
|
||||||
|
VkPhysicalDeviceProperties props;
|
||||||
|
vkGetPhysicalDeviceProperties(t->phys, &props);
|
||||||
|
g_gpu_vendor.store(props.vendorID, std::memory_order_relaxed);
|
||||||
|
g_gpu_vendor_of = t->phys;
|
||||||
|
}
|
||||||
menu_art_start(); // the game's interface textures decode on a worker from the first present on
|
menu_art_start(); // the game's interface textures decode on a worker from the first present on
|
||||||
cheats_frame(frame); // the data cheats and the buttons of the cheats that need them held
|
cheats_frame(frame); // the data cheats and the buttons of the cheats that need them held
|
||||||
if (!g_test.parsed) test_parse();
|
if (!g_test.parsed) test_parse();
|
||||||
@@ -1453,7 +1392,13 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
|||||||
if (g_perf_save.exchange(0)) cfg_save();
|
if (g_perf_save.exchange(0)) cfg_save();
|
||||||
perf_tick(plat_now_ns(), t);
|
perf_tick(plat_now_ns(), t);
|
||||||
amiibo_tick();
|
amiibo_tick();
|
||||||
|
if (g_booting.load(std::memory_order_relaxed)) g_booting.store(0, std::memory_order_release); // the game runs
|
||||||
bool open = g_open.load(std::memory_order_relaxed);
|
bool open = g_open.load(std::memory_order_relaxed);
|
||||||
|
// the frame the menu is first laid out after opening: also when its g_reset went to an earlier frame of the overlay
|
||||||
|
// alone (the menu opened between the two loads), the pad's buttons held now must not count as presses
|
||||||
|
static bool was_open;
|
||||||
|
bool opened = open && !was_open;
|
||||||
|
was_open = open;
|
||||||
if (!open) {
|
if (!open) {
|
||||||
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to nx2navi.ini now
|
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to nx2navi.ini now
|
||||||
if (g_test.at && !g_test.opened && frame >= g_test.at) {
|
if (g_test.at && !g_test.opened && frame >= g_test.at) {
|
||||||
@@ -1472,8 +1417,8 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
|||||||
}
|
}
|
||||||
uint64_t t0 = plat_now_ns();
|
uint64_t t0 = plat_now_ns();
|
||||||
if (!g_ctx_ok) make_context();
|
if (!g_ctx_ok) make_context();
|
||||||
float scale = menu_scale(t->height);
|
float scale = menu_scale(t->width, t->height);
|
||||||
if (!vk_up(t) || !fonts_follow(scale)) {
|
if (!vk_up(t) || !fonts_for(scale, t0)) {
|
||||||
rt_log("menu: Dear ImGui Vulkan back end set-up failed; the menu stays closed");
|
rt_log("menu: Dear ImGui Vulkan back end set-up failed; the menu stays closed");
|
||||||
g_failed.store(1);
|
g_failed.store(1);
|
||||||
set_open(0);
|
set_open(0);
|
||||||
@@ -1492,8 +1437,11 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
|||||||
// ran without its focus row and with the opening key still down.
|
// ran without its focus row and with the opening key still down.
|
||||||
open = g_open.load(std::memory_order_acquire);
|
open = g_open.load(std::memory_order_acquire);
|
||||||
if (reset) {
|
if (reset) {
|
||||||
|
io.ClearEventsQueue(); // events handed over before the close and not yet taken (ImGui spreads them over frames)
|
||||||
io.ClearInputKeys();
|
io.ClearInputKeys();
|
||||||
io.ClearInputMouse();
|
io.ClearInputMouse();
|
||||||
|
binds_cancel(); // a cell waiting for a press when the menu closed: no press binds on the next opening
|
||||||
|
g_sound_fresh = true;
|
||||||
g_last_ns = 0;
|
g_last_ns = 0;
|
||||||
g_focus_page = g_tab_request >= 0 ? g_tab_request : g_tab; // opening: the first row has the cursor
|
g_focus_page = g_tab_request >= 0 ? g_tab_request : g_tab; // opening: the first row has the cursor
|
||||||
if (GImGui->OpenPopupStack.Size) ImGui::ClosePopupToLevel(0, false); // a confirmation left open on closing
|
if (GImGui->OpenPopupStack.Size) ImGui::ClosePopupToLevel(0, false); // a confirmation left open on closing
|
||||||
@@ -1506,7 +1454,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
|||||||
if (!open) { // the overlay alone: no input reaches ImGui
|
if (!open) { // the overlay alone: no input reaches ImGui
|
||||||
} else if (g_test.page < 0) {
|
} else if (g_test.page < 0) {
|
||||||
drain_events(io);
|
drain_events(io);
|
||||||
pad_events(io, reset);
|
pad_events(io, reset || opened);
|
||||||
} else { // the test hook's pages: the user's input in a background test window must not change settings
|
} else { // the test hook's pages: the user's input in a background test window must not change settings
|
||||||
plat_mutex_lock(&ev_lock);
|
plat_mutex_lock(&ev_lock);
|
||||||
ev_n = 0;
|
ev_n = 0;
|
||||||
@@ -1544,20 +1492,20 @@ extern "C" void menu_boot_set(int phase, long long done, long long total) {
|
|||||||
g_boot_done.store(done, std::memory_order_relaxed);
|
g_boot_done.store(done, std::memory_order_relaxed);
|
||||||
g_boot_total.store(total, std::memory_order_relaxed);
|
g_boot_total.store(total, std::memory_order_relaxed);
|
||||||
g_boot_phase.store(phase, std::memory_order_release);
|
g_boot_phase.store(phase, std::memory_order_release);
|
||||||
g_booting.store(phase >= 0, std::memory_order_release);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A panel in the middle of the screen in the menu's colours: the title, the step with its count and a bar, and why it
|
// A box in the middle of the screen in the menu's look (ui/menu_skin.cpp skin_boot_panel): the title, the step with its
|
||||||
// happens. The input queue is left alone: keys pressed now reach the menu once the game runs.
|
// count and a bar, and why it happens. The input queue is left alone: keys pressed now reach the menu once the game runs.
|
||||||
extern "C" int menu_boot_frame(const MenuTarget *t) {
|
extern "C" int menu_boot_frame(const MenuTarget *t) {
|
||||||
if (g_failed_flag() || g_boot_phase.load(std::memory_order_acquire) < 0) return 0; // -1: done, a black frame
|
if (g_failed_flag() || g_boot_phase.load(std::memory_order_acquire) < 0) return 0; // -1: done, a black frame
|
||||||
if (!g_ctx_ok) make_context();
|
if (!g_ctx_ok) make_context();
|
||||||
float scale = menu_scale(t->height);
|
float scale = menu_scale(t->width, t->height);
|
||||||
if (!vk_up(t) || !fonts_follow(scale)) {
|
if (!vk_up(t) || !fonts_for(scale, plat_now_ns())) {
|
||||||
rt_log("menu: Dear ImGui Vulkan back end set-up failed; no boot screen, and the menu stays closed");
|
rt_log("menu: Dear ImGui Vulkan back end set-up failed; no boot screen, and the menu stays closed");
|
||||||
g_failed.store(1);
|
g_failed.store(1);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
menu_art_start(); // the box takes the game's textures as soon as they are decoded, plain shapes until then
|
||||||
if (g_style_scale != scale) {
|
if (g_style_scale != scale) {
|
||||||
ImGui::GetStyle() = g_base_style;
|
ImGui::GetStyle() = g_base_style;
|
||||||
ImGui::GetStyle().ScaleAllSizes(scale);
|
ImGui::GetStyle().ScaleAllSizes(scale);
|
||||||
@@ -1582,41 +1530,16 @@ extern "C" int menu_boot_frame(const MenuTarget *t) {
|
|||||||
snprintf(step, sizeof step, "%s", ui_text(UI_BOOT_STARTING));
|
snprintf(step, sizeof step, "%s", ui_text(UI_BOOT_STARTING));
|
||||||
const char *title = ui_text(UI_BOOT_TITLE), *hint = ui_text(UI_BOOT_HINT);
|
const char *title = ui_text(UI_BOOT_TITLE), *hint = ui_text(UI_BOOT_HINT);
|
||||||
|
|
||||||
ImDrawList *dl = ImGui::GetForegroundDrawList();
|
// the box in the menu's look (ui/menu_skin.cpp): a filled bar while there is a count, else a sweeping segment
|
||||||
float w = (float)t->width, h = (float)t->height, pad = 34 * scale, gap = 16 * scale;
|
|
||||||
ImFont *body = ImGui::GetFont();
|
ImFont *body = ImGui::GetFont();
|
||||||
float body_px = ImGui::GetFontSize();
|
float body_px = ImGui::GetFontSize();
|
||||||
ImFont *head = g_title_font ? g_title_font : body;
|
ImFont *head = g_title_font ? g_title_font : body;
|
||||||
float head_px = g_title_font ? g_title_font->FontSize * ImGui::GetIO().FontGlobalScale : body_px * 1.2f;
|
float head_px = g_title_font ? g_title_font->FontSize * io.FontGlobalScale : body_px * 1.2f; // as GetFontSize scales
|
||||||
ImVec2 ts = head->CalcTextSizeA(head_px, FLT_MAX, 0, title), ss = body->CalcTextSizeA(body_px, FLT_MAX, 0, step),
|
float frac = -1;
|
||||||
hs = body->CalcTextSizeA(body_px * 0.8f, FLT_MAX, 0, hint);
|
if ((phase == 1 || phase == 2) && total > 0) frac = done <= 0 ? 0 : done >= total ? 1 : (float)done / (float)total;
|
||||||
float bar_h = 10 * scale;
|
float s = (float)fmod((now - g_boot_t0) / 1e9 * 0.8, 2.0);
|
||||||
float pw = fmaxf(fmaxf(ts.x, hs.x), 560 * scale) + pad * 2;
|
skin_boot_panel(ImGui::GetForegroundDrawList(), head, head_px, body, body_px, title, step, hint, frac, s < 1 ? s : 2 - s,
|
||||||
float ph = pad + ts.y + gap * 1.5f + ss.y + gap * 0.6f + bar_h + gap * 1.4f + hs.y + pad;
|
(float)t->width, (float)t->height, scale);
|
||||||
ImVec2 a((w - pw) / 2, (h - ph) / 2), b(a.x + pw, a.y + ph);
|
|
||||||
ImU32 gold = ImGui::GetColorU32(kGold), panel = ImGui::GetColorU32(kNavy);
|
|
||||||
ImU32 text = IM_COL32(236, 224, 196, 255), dim = IM_COL32(236, 224, 196, 150);
|
|
||||||
dl->AddRectFilled(a, b, panel, 10 * scale);
|
|
||||||
dl->AddRect(a, b, IM_COL32(237, 194, 97, 140), 10 * scale, 0, 1.5f * scale);
|
|
||||||
float y = a.y + pad;
|
|
||||||
dl->AddText(head, head_px, ImVec2((w - ts.x) / 2, y), gold, title);
|
|
||||||
y += ts.y + gap * 1.5f;
|
|
||||||
dl->AddText(body, body_px, ImVec2(a.x + pad, y), text, step);
|
|
||||||
y += ss.y + gap * 0.6f;
|
|
||||||
ImVec2 ba(a.x + pad, y), bb(b.x - pad, y + bar_h);
|
|
||||||
dl->AddRectFilled(ba, bb, IM_COL32(255, 255, 255, 28), bar_h / 2);
|
|
||||||
if ((phase == 1 || phase == 2) && total > 0) {
|
|
||||||
float f = (float)done / (float)total;
|
|
||||||
f = f < 0 ? 0 : f > 1 ? 1 : f;
|
|
||||||
if (f > 0) dl->AddRectFilled(ba, ImVec2(ba.x + (bb.x - ba.x) * f, bb.y), gold, bar_h / 2);
|
|
||||||
} else { // no count yet: a short segment sweeps along the bar
|
|
||||||
float span = (bb.x - ba.x) * 0.2f, run = (bb.x - ba.x) - span;
|
|
||||||
float s = (float)fmod((now - g_boot_t0) / 1e9 * 0.8, 2.0);
|
|
||||||
float x = ba.x + run * (s < 1 ? s : 2 - s);
|
|
||||||
dl->AddRectFilled(ImVec2(x, ba.y), ImVec2(x + span, bb.y), gold, bar_h / 2);
|
|
||||||
}
|
|
||||||
y += bar_h + gap * 1.4f;
|
|
||||||
dl->AddText(body, body_px * 0.8f, ImVec2((w - hs.x) / 2, y), dim, hint);
|
|
||||||
ImGui::Render();
|
ImGui::Render();
|
||||||
return ImGui::GetDrawData()->TotalVtxCount > 0;
|
return ImGui::GetDrawData()->TotalVtxCount > 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ extern "C" {
|
|||||||
|
|
||||||
// ---- state, any thread
|
// ---- state, any thread
|
||||||
int menu_is_open(void);
|
int menu_is_open(void);
|
||||||
void menu_toggle(void); // F1 / Esc on the keyboard, Minus+Plus on the pad
|
void menu_toggle(void); // F1 / Esc on the keyboard, Minus+Plus on the pad; not before the game's first frame
|
||||||
void menu_perf_cycle(void); // F10: the performance overlay off, fps, full
|
void menu_perf_cycle(void); // F10: the performance overlay off, fps, full
|
||||||
|
|
||||||
// ---- events from the window adapter, used only while the menu is open. key: an ImGuiKey; coordinates in pixels of the
|
// ---- events from the window adapter, used only while the menu is open. key: an ImGuiKey; coordinates in pixels of the
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// The settings menu's art from the game's own interface textures (menu_assets.c reads them from the user's RomFS):
|
// The settings menu's art from the game's own interface textures (menu_assets.c reads them from the user's RomFS):
|
||||||
// the cursor's glow and line, the frame's corner ornaments and the control guide's bar. A worker decodes them into
|
// the frame's corner ornaments, the control guide's bar, and the layers of the buttons, cursor, panels and divider that
|
||||||
// RGBA once at start (the archive unpacks to about 240 MB and takes a moment); the window thread uploads each to the GPU
|
// ui/menu_skin.cpp puts together. A worker decodes them into RGBA once at start (the archive unpacks to about 240 MB and
|
||||||
// the first time the menu asks for it, and registers it with Dear ImGui's Vulkan back end. Without the files the menu
|
// takes a moment); the window thread uploads each to the GPU with its smaller levels the first time the menu asks for
|
||||||
// draws its plain shapes.
|
// it, and registers it with Dear ImGui's Vulkan back end. Without the files the menu draws its plain shapes.
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
@@ -18,12 +18,20 @@ extern "C" {
|
|||||||
}
|
}
|
||||||
#include "menu_assets.h"
|
#include "menu_assets.h"
|
||||||
#include "ui/menu_art.h"
|
#include "ui/menu_art.h"
|
||||||
|
#include "ui/menu_skin.h"
|
||||||
|
|
||||||
#define COMMON_BNTX "UI/Layout2Archive/Common.Product.100.Nin_Ounce_NVN2.bntx.zs"
|
#define COMMON_BNTX "UI/Layout2Archive/Common.Product.100.Nin_Ounce_NVN2.bntx.zs"
|
||||||
|
|
||||||
|
// in the order of MenuArt (tools/menu_preview.py reads this list too)
|
||||||
static const char *const kNames[MENU_ART_COUNT] = {
|
static const char *const kNames[MENU_ART_COUNT] = {
|
||||||
"CmnBtnCursorGlow_00", "CmnBtnCursorLine_00", "LocationDeco_00", "CtrlGuideBG_00", "MessageWindowCommonBase_00",
|
"LocationDeco_00", "CtrlGuideBG_00", "MessageWindowCommonBase_00",
|
||||||
|
"BtnThinBase_01", "BtnThinBase_00", "BtnThinBase_05", "BtnThinBase_04", "BtnThinBase_02",
|
||||||
|
"OptionBtnThinCursorGlow_00", "OptionBtnThinCursorLine_00", "SystemCaptionBg_00",
|
||||||
|
"OptionSeparateMark_00", "SystemLine_03", "MenuHeaderSelect_00",
|
||||||
};
|
};
|
||||||
|
// Levels uploaded for each art: the buttons draw it at about half size and smaller, where a line one or two texels wide
|
||||||
|
// would break up if sampled from the full image alone.
|
||||||
|
enum { MAX_LEVELS = 6 };
|
||||||
|
|
||||||
static struct Art {
|
static struct Art {
|
||||||
uint8_t *rgba;
|
uint8_t *rgba;
|
||||||
@@ -44,7 +52,7 @@ static void decode_all(void *) {
|
|||||||
if (!bntx) rt_log("menu: %s could not be read from the RomFS", COMMON_BNTX);
|
if (!bntx) rt_log("menu: %s could not be read from the RomFS", COMMON_BNTX);
|
||||||
for (int i = 0; bntx && i < MENU_ART_COUNT; i++) {
|
for (int i = 0; bntx && i < MENU_ART_COUNT; i++) {
|
||||||
Art &a = g_art[i];
|
Art &a = g_art[i];
|
||||||
if (menu_asset_texture(bntx, n, kNames[i], &a.rgba, &a.w, &a.h)) got++;
|
if (menu_asset_texture(bntx, n, kNames[i], &a.rgba, &a.w, &a.h)) got++, skin_art_prepare(i, a.rgba, a.w, a.h);
|
||||||
else rt_log("menu: interface texture %s not decoded (archive of %llu bytes)", kNames[i], (unsigned long long)n);
|
else rt_log("menu: interface texture %s not decoded (archive of %llu bytes)", kNames[i], (unsigned long long)n);
|
||||||
}
|
}
|
||||||
free(bntx);
|
free(bntx);
|
||||||
@@ -66,26 +74,52 @@ static int upload(Art &a) {
|
|||||||
si.magFilter = si.minFilter = VK_FILTER_LINEAR;
|
si.magFilter = si.minFilter = VK_FILTER_LINEAR;
|
||||||
si.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
|
si.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
|
||||||
si.addressModeU = si.addressModeV = si.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
|
si.addressModeU = si.addressModeV = si.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
|
||||||
si.maxLod = 1;
|
si.maxLod = MAX_LEVELS;
|
||||||
if (vkCreateSampler(c->device, &si, nullptr, &g_sampler) != VK_SUCCESS) return 0;
|
if (vkCreateSampler(c->device, &si, nullptr, &g_sampler) != VK_SUCCESS) return 0;
|
||||||
}
|
}
|
||||||
|
uint32_t lw[MAX_LEVELS] = {a.w}, lh[MAX_LEVELS] = {a.h}, levels = 1;
|
||||||
|
VkDeviceSize bytes = (VkDeviceSize)a.w * a.h * 4;
|
||||||
|
while (levels < MAX_LEVELS && (lw[levels - 1] > 1 || lh[levels - 1] > 1)) {
|
||||||
|
lw[levels] = lw[levels - 1] > 1 ? lw[levels - 1] / 2 : 1;
|
||||||
|
lh[levels] = lh[levels - 1] > 1 ? lh[levels - 1] / 2 : 1;
|
||||||
|
bytes += (VkDeviceSize)lw[levels] * lh[levels] * 4;
|
||||||
|
levels++;
|
||||||
|
}
|
||||||
VkImageCreateInfo ii = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
|
VkImageCreateInfo ii = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
|
||||||
ii.imageType = VK_IMAGE_TYPE_2D;
|
ii.imageType = VK_IMAGE_TYPE_2D;
|
||||||
ii.format = VK_FORMAT_R8G8B8A8_UNORM;
|
ii.format = VK_FORMAT_R8G8B8A8_UNORM;
|
||||||
ii.extent = {a.w, a.h, 1};
|
ii.extent = {a.w, a.h, 1};
|
||||||
ii.mipLevels = ii.arrayLayers = 1;
|
ii.mipLevels = levels;
|
||||||
|
ii.arrayLayers = 1;
|
||||||
ii.samples = VK_SAMPLE_COUNT_1_BIT;
|
ii.samples = VK_SAMPLE_COUNT_1_BIT;
|
||||||
ii.tiling = VK_IMAGE_TILING_OPTIMAL;
|
ii.tiling = VK_IMAGE_TILING_OPTIMAL;
|
||||||
ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||||
VmaAllocationCreateInfo ai = {};
|
VmaAllocationCreateInfo ai = {};
|
||||||
ai.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
|
ai.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
|
||||||
if (vmaCreateImage(c->vma, &ii, &ai, &a.img, &a.alloc, nullptr) != VK_SUCCESS) return 0;
|
if (vmaCreateImage(c->vma, &ii, &ai, &a.img, &a.alloc, nullptr) != VK_SUCCESS) return 0;
|
||||||
VkDeviceSize bytes = (VkDeviceSize)a.w * a.h * 4;
|
|
||||||
VkBuffer sb;
|
VkBuffer sb;
|
||||||
VmaAllocation sa;
|
VmaAllocation sa;
|
||||||
void *map = vk_staging(bytes, &sb, &sa);
|
uint8_t *map = (uint8_t *)vk_staging(bytes, &sb, &sa);
|
||||||
if (!map) return 0;
|
if (!map) return 0;
|
||||||
memcpy(map, a.rgba, (size_t)bytes);
|
// the levels one after the other in a plain allocation, each halved from the one before (the staging memory may be
|
||||||
|
// slow to read back)
|
||||||
|
uint8_t *chain = (uint8_t *)malloc((size_t)bytes);
|
||||||
|
if (!chain) {
|
||||||
|
vmaDestroyBuffer(c->vma, sb, sa);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
memcpy(chain, a.rgba, (size_t)a.w * a.h * 4);
|
||||||
|
VkBufferImageCopy regions[MAX_LEVELS] = {};
|
||||||
|
VkDeviceSize at = 0;
|
||||||
|
for (uint32_t l = 0; l < levels; l++) {
|
||||||
|
regions[l].bufferOffset = at;
|
||||||
|
regions[l].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, l, 0, 1};
|
||||||
|
regions[l].imageExtent = {lw[l], lh[l], 1};
|
||||||
|
if (l) skin_art_halve(chain + regions[l - 1].bufferOffset, lw[l - 1], lh[l - 1], chain + at, lw[l], lh[l]);
|
||||||
|
at += (VkDeviceSize)lw[l] * lh[l] * 4;
|
||||||
|
}
|
||||||
|
memcpy(map, chain, (size_t)bytes);
|
||||||
|
free(chain);
|
||||||
VkCommandBuffer cb = vk_upload_begin();
|
VkCommandBuffer cb = vk_upload_begin();
|
||||||
VkImageMemoryBarrier2 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2};
|
VkImageMemoryBarrier2 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2};
|
||||||
b.srcStageMask = VK_PIPELINE_STAGE_2_NONE;
|
b.srcStageMask = VK_PIPELINE_STAGE_2_NONE;
|
||||||
@@ -95,15 +129,12 @@ static int upload(Art &a) {
|
|||||||
b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||||
b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||||
b.image = a.img;
|
b.image = a.img;
|
||||||
b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, levels, 0, 1};
|
||||||
VkDependencyInfo di = {VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
|
VkDependencyInfo di = {VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
|
||||||
di.imageMemoryBarrierCount = 1;
|
di.imageMemoryBarrierCount = 1;
|
||||||
di.pImageMemoryBarriers = &b;
|
di.pImageMemoryBarriers = &b;
|
||||||
vkCmdPipelineBarrier2(cb, &di);
|
vkCmdPipelineBarrier2(cb, &di);
|
||||||
VkBufferImageCopy r = {};
|
vkCmdCopyBufferToImage(cb, sb, a.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, levels, regions);
|
||||||
r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
|
|
||||||
r.imageExtent = {a.w, a.h, 1};
|
|
||||||
vkCmdCopyBufferToImage(cb, sb, a.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &r);
|
|
||||||
b.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
|
b.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
|
||||||
b.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT;
|
b.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT;
|
||||||
b.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
|
b.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
|
||||||
@@ -118,7 +149,7 @@ static int upload(Art &a) {
|
|||||||
vi.image = a.img;
|
vi.image = a.img;
|
||||||
vi.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
vi.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||||
vi.format = VK_FORMAT_R8G8B8A8_UNORM;
|
vi.format = VK_FORMAT_R8G8B8A8_UNORM;
|
||||||
vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, levels, 0, 1};
|
||||||
if (vkCreateImageView(c->device, &vi, nullptr, &a.view) != VK_SUCCESS) return 0;
|
if (vkCreateImageView(c->device, &vi, nullptr, &a.view) != VK_SUCCESS) return 0;
|
||||||
a.ds = ImGui_ImplVulkan_AddTexture(g_sampler, a.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
a.ds = ImGui_ImplVulkan_AddTexture(g_sampler, a.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
||||||
return a.ds != VK_NULL_HANDLE; // the pixels stay (a few MB): the back end may start again on another format
|
return a.ds != VK_NULL_HANDLE; // the pixels stay (a few MB): the back end may start again on another format
|
||||||
@@ -147,37 +178,3 @@ extern "C" void menu_art_release(void) {
|
|||||||
}
|
}
|
||||||
if (g_sampler) vkDestroySampler(c->device, g_sampler, nullptr), g_sampler = VK_NULL_HANDLE;
|
if (g_sampler) vkDestroySampler(c->device, g_sampler, nullptr), g_sampler = VK_NULL_HANDLE;
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" int menu_art_draw(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, ImU32 tint) {
|
|
||||||
ImTextureID t;
|
|
||||||
if (!menu_art(id, &t, nullptr, nullptr)) return 0;
|
|
||||||
dl->AddImage(t, a, b, ImVec2(0, 0), ImVec2(1, 1), tint);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nine pieces: the corners at `corner` pixels on screen from the texture's outer `frac` of each side, the edges
|
|
||||||
// stretched between them, the middle left out (frames) or stretched (fill).
|
|
||||||
extern "C" int menu_art_draw9_turned(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float corner, float frac, ImU32 tint, int fill,
|
|
||||||
int turned);
|
|
||||||
extern "C" int menu_art_draw9(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float corner, float frac, ImU32 tint, int fill) {
|
|
||||||
return menu_art_draw9_turned(dl, id, a, b, corner, frac, tint, fill, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The same, the texture turned half a turn when turned: its top-left corner piece at the bottom right.
|
|
||||||
extern "C" int menu_art_draw9_turned(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float corner, float frac, ImU32 tint, int fill,
|
|
||||||
int turned) {
|
|
||||||
ImTextureID t;
|
|
||||||
if (!menu_art(id, &t, nullptr, nullptr)) return 0;
|
|
||||||
float c = corner, maxc = fminf((b.x - a.x) / 2, (b.y - a.y) / 2);
|
|
||||||
if (c > maxc) c = maxc;
|
|
||||||
const float xs[4] = {a.x, a.x + c, b.x - c, b.x}, ys[4] = {a.y, a.y + c, b.y - c, b.y};
|
|
||||||
float us[4] = {0, frac, 1 - frac, 1}, vs[4] = {0, frac, 1 - frac, 1};
|
|
||||||
if (turned)
|
|
||||||
for (int k = 0; k < 4; k++) us[k] = 1 - us[k], vs[k] = 1 - vs[k];
|
|
||||||
for (int j = 0; j < 3; j++)
|
|
||||||
for (int i = 0; i < 3; i++) {
|
|
||||||
if (i == 1 && j == 1 && !fill) continue;
|
|
||||||
dl->AddImage(t, ImVec2(xs[i], ys[j]), ImVec2(xs[i + 1], ys[j + 1]), ImVec2(us[i], vs[j]), ImVec2(us[i + 1], vs[j + 1]), tint);
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,11 +3,21 @@
|
|||||||
#include "imgui.h"
|
#include "imgui.h"
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
MENU_ART_CURSOR_GLOW, // the glow of the game's button cursor (white mask; tinted by the caller)
|
|
||||||
MENU_ART_CURSOR_LINE, // its outline
|
|
||||||
MENU_ART_FRAME_DECO, // a frame with ornamented corners
|
MENU_ART_FRAME_DECO, // a frame with ornamented corners
|
||||||
MENU_ART_GUIDE_BAR, // the control guide's bar
|
MENU_ART_GUIDE_BAR, // the control guide's bar
|
||||||
MENU_ART_WINDOW_BASE, // a rounded window base
|
MENU_ART_WINDOW_BASE, // a rounded window base
|
||||||
|
// the layers of the save menu's Load and Cancel button, in drawing order; white masks except for the grain
|
||||||
|
MENU_ART_BTN_RIM, // a soft line along the button's edge, reaching outside it
|
||||||
|
MENU_ART_BTN_FILL, // the button's shape
|
||||||
|
MENU_ART_BTN_GRAIN, // the mottling: light at the edge, dark and speckled in the middle
|
||||||
|
MENU_ART_BTN_EDGE, // the light edge
|
||||||
|
MENU_ART_BTN_LINE, // the inset line, a diamond and a curl at alternate corners
|
||||||
|
MENU_ART_CURSOR_GLOW, // the options cursor's soft glow
|
||||||
|
MENU_ART_CURSOR_LINE, // the options cursor's white frame (skin_art_prepare cuts it out of the texture)
|
||||||
|
MENU_ART_PANEL_FILL, // a dark brown panel
|
||||||
|
MENU_ART_DIVIDER, // the options menu's divider ornament
|
||||||
|
MENU_ART_DIVIDER_LINE, // the line beside the ornament, ending in a dot
|
||||||
|
MENU_ART_TAB_SELECT, // the plate of the selected category in the game's menu header
|
||||||
MENU_ART_COUNT
|
MENU_ART_COUNT
|
||||||
} MenuArt;
|
} MenuArt;
|
||||||
|
|
||||||
|
|||||||
545
runtime/ui/menu_skin.cpp
Normal file
545
runtime/ui/menu_skin.cpp
Normal file
@@ -0,0 +1,545 @@
|
|||||||
|
// The look of the game's own menus (ui/menu_skin.h). With the game's textures (ui/menu_art.cpp) each piece is those
|
||||||
|
// textures tinted and laid over each other in nine slices; until they are decoded, or without them, it is plain shapes
|
||||||
|
// whose colours and proportions are sampled from the game: the save menu's Load and Cancel buttons (brown fill, light
|
||||||
|
// edge, an inset line about a twentieth of the height in with a diamond and a curl at alternate corners), the options
|
||||||
|
// menu's cursor (a 3 px white frame with a soft white-blue glow) and its divider ornament (traced: two pointed lens
|
||||||
|
// ends, S-waves into spiral hooks and a diamond knot under the middle, in a 120 x 38 box with its centre at (60, 21)).
|
||||||
|
#include <float.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#include <initializer_list>
|
||||||
|
|
||||||
|
#include "imgui.h"
|
||||||
|
#include "imgui_internal.h" // NavCursorVisible
|
||||||
|
#include "ui/menu_art.h"
|
||||||
|
#include "ui/menu_skin.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// The mottled grain of the game's brown boxes: a tile in the font atlas (skin_atlas_add, skin_atlas_fill), white with
|
||||||
|
// the grain in alpha, drawn over a box darkened in some places and lightened in others.
|
||||||
|
const int kGrainW = 160, kGrainH = 48;
|
||||||
|
int g_grain_rect = -1;
|
||||||
|
ImVec2 g_grain_uv0, g_grain_uv1;
|
||||||
|
bool g_grain_ok;
|
||||||
|
|
||||||
|
ImU32 rgba(int r, int g, int b, float a) { return IM_COL32(r, g, b, (int)(a * 255.0f + 0.5f)); }
|
||||||
|
|
||||||
|
ImU32 mix(const int c0[3], const int c1[3], float t, float a) {
|
||||||
|
return rgba((int)(c0[0] + (c1[0] - c0[0]) * t), (int)(c0[1] + (c1[1] - c0[1]) * t), (int)(c0[2] + (c1[2] - c0[2]) * t),
|
||||||
|
a);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A spiral of `turns` turns around c, from radius r at angle a0 (radians, clockwise on screen) in to 35 % of it.
|
||||||
|
void curl(ImDrawList *dl, ImVec2 c, float r, float a0, float turns, ImU32 col, float thick) {
|
||||||
|
const int n = 28;
|
||||||
|
for (int i = 0; i <= n; i++) {
|
||||||
|
float t = (float)i / n, a = a0 + t * turns * 6.2831853f, rad = r * (1.0f - 0.65f * t);
|
||||||
|
dl->PathLineTo(ImVec2(c.x + cosf(a) * rad, c.y + sinf(a) * rad));
|
||||||
|
}
|
||||||
|
dl->PathStroke(col, 0, thick);
|
||||||
|
}
|
||||||
|
|
||||||
|
void diamond(ImDrawList *dl, ImVec2 c, float d, ImU32 col) {
|
||||||
|
dl->AddQuadFilled(ImVec2(c.x, c.y - d), ImVec2(c.x + d, c.y), ImVec2(c.x, c.y + d), ImVec2(c.x - d, c.y), col);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The inset line of the button and panel frames, `inset` inside [a, b]: a diamond at the top-left and bottom-right
|
||||||
|
// corners, a curl at the top-right and bottom-left ones, the four lines running between them with a small gap.
|
||||||
|
void ornament_line(ImDrawList *dl, ImVec2 a, ImVec2 b, float inset, float s, ImU32 col) {
|
||||||
|
const float l = a.x + inset, t = a.y + inset, r = b.x - inset, bt = b.y - inset;
|
||||||
|
// the ornaments grow with the box as on the game's buttons (a curl about a tenth of the height across), within limits
|
||||||
|
const float span = fminf(r - l, bt - t);
|
||||||
|
float rad = fminf(fmaxf(span * 0.13f, 3.5f * s), 7.0f * s), d = rad * 0.6f, gap = 2.4f * s, thick = 1.4f * s;
|
||||||
|
// top: from the diamond into the curl, whose outer turn starts at the top of its circle
|
||||||
|
dl->AddLine(ImVec2(l + d + gap, t), ImVec2(r - rad, t), col, thick);
|
||||||
|
curl(dl, ImVec2(r - rad, t + rad), rad, -1.5707963f, 1.3f, col, thick);
|
||||||
|
dl->AddLine(ImVec2(r, t + 2 * rad + gap), ImVec2(r, bt - d - gap), col, thick); // right: under the curl
|
||||||
|
dl->AddLine(ImVec2(r - d - gap, bt), ImVec2(l + rad, bt), col, thick); // bottom: into the other curl
|
||||||
|
curl(dl, ImVec2(l + rad, bt - rad), rad, 1.5707963f, 1.3f, col, thick);
|
||||||
|
dl->AddLine(ImVec2(l, bt - 2 * rad - gap), ImVec2(l, t + d + gap), col, thick); // left: over the curl
|
||||||
|
diamond(dl, ImVec2(l, t), d, col);
|
||||||
|
diamond(dl, ImVec2(r, bt), d, col);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The divider ornament's paths: F_M x y, F_L x y, F_C x1 y1 x2 y2 x y, ending with F_END.
|
||||||
|
enum { F_M = -1000, F_L = -1001, F_C = -1002, F_Z = -1003, F_END = -1004 };
|
||||||
|
static const float kFiligree0[] = {
|
||||||
|
F_M, 20, 17.4, F_C, 20.4, 17.3, 21.6, 16.8, 22.2, 16.9, F_C, 22.8, 17, 23.5, 17.7, 23.5, 18.2, F_C, 23.5, 18.7,
|
||||||
|
23.1, 19.4, 22.4, 19.8, F_C, 21.6, 20.2, 20.3, 20.4, 19, 20.4, F_C, 17.7, 20.4, 15.9, 20.2, 14.5, 19.9, F_C,
|
||||||
|
13.1, 19.6, 10.6, 19.4, 10.5, 18.6, F_C, 10.4, 17.9, 12.6, 16.3, 14, 15.4, F_C, 15.4, 14.5, 17.2, 13.6, 19, 13.2,
|
||||||
|
F_C, 20.8, 12.8, 23.2, 12.8, 25, 13.1, F_C, 26.8, 13.4, 28.1, 13.9, 29.5, 14.8, F_C, 30.9, 15.7, 32.2, 17.4,
|
||||||
|
33.5, 18.6, F_C, 34.8, 19.8, 36, 21.2, 37.5, 22, F_C, 39, 22.8, 40.8, 23.4, 42.5, 23.6, F_C, 44.2, 23.8, 46,
|
||||||
|
23.5, 47.5, 23.1, F_C, 49, 22.7, 50.4, 21.9, 51.2, 21.2, F_C, 52, 20.5, 52.5, 19.5, 52.4, 18.8, F_C, 52.3, 18.1,
|
||||||
|
51.5, 17.3, 50.6, 16.9, F_C, 49.7, 16.5, 48.2, 16.2, 47, 16.3, F_C, 45.8, 16.4, 44.2, 17.1, 43.6, 17.2, F_END};
|
||||||
|
static const float kFiligree1[] = {
|
||||||
|
F_M, 100, 17.4, F_C, 99.6, 17.3, 98.4, 16.8, 97.8, 16.9, F_C, 97.2, 17, 96.5, 17.7, 96.5, 18.2, F_C, 96.5, 18.7,
|
||||||
|
96.8, 19.4, 97.6, 19.8, F_C, 98.3, 20.2, 99.7, 20.4, 101, 20.4, F_C, 102.3, 20.4, 104.1, 20.2, 105.5, 19.9, F_C,
|
||||||
|
106.9, 19.6, 109.4, 19.4, 109.5, 18.6, F_C, 109.6, 17.9, 107.4, 16.3, 106, 15.4, F_C, 104.6, 14.5, 102.8, 13.6,
|
||||||
|
101, 13.2, F_C, 99.2, 12.8, 96.8, 12.8, 95, 13.1, F_C, 93.2, 13.4, 91.9, 13.9, 90.5, 14.8, F_C, 89.1, 15.7, 87.8,
|
||||||
|
17.4, 86.5, 18.6, F_C, 85.2, 19.8, 84, 21.2, 82.5, 22, F_C, 81, 22.8, 79.2, 23.4, 77.5, 23.6, F_C, 75.8, 23.8,
|
||||||
|
74, 23.5, 72.5, 23.1, F_C, 71, 22.7, 69.6, 21.9, 68.8, 21.2, F_C, 68, 20.5, 67.5, 19.5, 67.6, 18.8, F_C, 67.7,
|
||||||
|
18.1, 68.5, 17.3, 69.4, 16.9, F_C, 70.3, 16.5, 71.8, 16.2, 73, 16.3, F_C, 74.2, 16.4, 75.8, 17.1, 76.4, 17.2,
|
||||||
|
F_END};
|
||||||
|
static const float kFiligree2[] = {
|
||||||
|
F_M, 40.6, 17.6, F_C, 40.7, 17, 40.7, 14.9, 41.2, 14, F_C, 41.7, 13.1, 42.6, 12.4, 43.8, 12, F_C, 45, 11.6, 46.7,
|
||||||
|
11.4, 48.2, 11.5, F_C, 49.7, 11.6, 51.3, 11.8, 52.6, 12.3, F_C, 53.9, 12.8, 55, 13.6, 56, 14.6, F_C, 57, 15.6,
|
||||||
|
58.2, 17.6, 58.6, 18.2, F_L, 64.6, 26, F_L, 60, 31.6, F_END};
|
||||||
|
static const float kFiligree3[] = {
|
||||||
|
F_M, 79.4, 17.6, F_C, 79.3, 17, 79.3, 14.9, 78.8, 14, F_C, 78.3, 13.1, 77.4, 12.4, 76.2, 12, F_C, 75, 11.6, 73.3,
|
||||||
|
11.4, 71.8, 11.5, F_C, 70.3, 11.6, 68.7, 11.8, 67.4, 12.3, F_C, 66.1, 12.8, 65, 13.6, 64, 14.6, F_C, 63, 15.6,
|
||||||
|
61.8, 17.6, 61.4, 18.2, F_L, 55.4, 26, F_L, 60, 31.6, F_END};
|
||||||
|
const float *const kFiligree[] = {kFiligree0, kFiligree1, kFiligree2, kFiligree3};
|
||||||
|
|
||||||
|
// The settings menu's colours: a dark umber panel, warm browns for frames and what is selected, gold for the ornaments,
|
||||||
|
// accents and the cursor, parchment text. kGreen and kOcarina keep their names for the selected and active controls.
|
||||||
|
const ImVec4 kGold(0.93f, 0.76f, 0.38f, 1), kGreen(0.36f, 0.26f, 0.13f, 1), kNavy(0.075f, 0.058f, 0.042f, 0.95f),
|
||||||
|
kOcarina(0.62f, 0.47f, 0.22f, 1);
|
||||||
|
|
||||||
|
// Where the art's boxes lie in its textures, in texels (measured from the textures). The button's layers are 489 x 133
|
||||||
|
// with the button's box from (20, 19) to (469, 114); the cursor's are 640 x 173 and its box, the button it surrounds,
|
||||||
|
// runs from (49, 48) to (591, 125); the panel's box runs from (53, 53) to (1147, 374) in 1200 x 427.
|
||||||
|
const float kBtnW = 489, kBtnH = 133, kBtnL = 20, kBtnT = 19, kBtnBoxH = 95, kBtnCut = 60;
|
||||||
|
const float kCurW = 640, kCurH = 173, kCurX = 49, kCurY = 48, kCurCut = 70, kCurScale = 0.72f;
|
||||||
|
const float kPanelW = 1200, kPanelH = 427, kPanelM = 53;
|
||||||
|
const float kTabL = 25, kTabT = 0, kTabR = 336, kTabB = 151; // the selected tab's plate in its 360 x 173 texture
|
||||||
|
|
||||||
|
bool have_art(std::initializer_list<MenuArt> ids) {
|
||||||
|
ImTextureID t;
|
||||||
|
for (MenuArt id : ids)
|
||||||
|
if (!menu_art(id, &t, nullptr, nullptr)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum { MAX_COPIES = 15 };
|
||||||
|
struct Piece { float p0, p1, t0, t1; };
|
||||||
|
|
||||||
|
// One axis of a slice: screen [a, b] from texels [x0, x1] of a texture `size` long, the outer `cut` texels c pixels
|
||||||
|
// long. The middle is stretched, or with tile repeated at k pixels per texel: an odd number of copies, every other one
|
||||||
|
// mirrored, so each copy meets the next on the same texels and the last meets the far corner. Mottled art stretched
|
||||||
|
// across a wide box would turn into streaks.
|
||||||
|
int axis(Piece *out, float a, float b, float x0, float x1, float size, float cut, float c, float k, bool tile) {
|
||||||
|
const float m0 = a + c, m1 = b - c, t0 = (x0 + cut) / size, t1 = (x1 - cut) / size, unit = (x1 - x0 - 2 * cut) * k;
|
||||||
|
int copies = 1, n = 0;
|
||||||
|
if (tile && unit > 0) copies = 2 * (int)floorf(((m1 - m0) / unit - 1) * 0.5f + 0.5f) + 1;
|
||||||
|
copies = copies < 1 ? 1 : copies > MAX_COPIES ? MAX_COPIES : copies;
|
||||||
|
out[n++] = {a, m0, x0 / size, t0};
|
||||||
|
for (int i = 0; i < copies; i++) {
|
||||||
|
float w = (m1 - m0) / copies;
|
||||||
|
out[n++] = {m0 + i * w, m0 + (i + 1) * w, i & 1 ? t1 : t0, i & 1 ? t0 : t1};
|
||||||
|
}
|
||||||
|
out[n++] = {m1, b, t1, x1 / size};
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The texels (x0, y0)-(x1, y1) of an art over [a, b] in nine slices: the outer `cut` texels on each side at k screen
|
||||||
|
// pixels per texel, so corners keep their shape, the rest stretched or tiled. A box smaller than its two corners shrinks
|
||||||
|
// them.
|
||||||
|
void slice(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float x0, float y0, float x1, float y1, float cut, float k, ImU32 tint,
|
||||||
|
bool tile_x = false, bool tile_y = false) {
|
||||||
|
ImTextureID t;
|
||||||
|
float tw, th;
|
||||||
|
if (!menu_art(id, &t, &tw, &th)) return;
|
||||||
|
Piece xs[MAX_COPIES + 2], ys[MAX_COPIES + 2];
|
||||||
|
int nx = axis(xs, a.x, b.x, x0, x1, tw, cut, fminf(cut * k, (b.x - a.x) * 0.5f), k, tile_x);
|
||||||
|
int ny = axis(ys, a.y, b.y, y0, y1, th, cut, fminf(cut * k, (b.y - a.y) * 0.5f), k, tile_y);
|
||||||
|
for (int j = 0; j < ny; j++)
|
||||||
|
for (int i = 0; i < nx; i++)
|
||||||
|
dl->AddImage(t, ImVec2(xs[i].p0, ys[j].p0), ImVec2(xs[i].p1, ys[j].p1), ImVec2(xs[i].t0, ys[j].t0), ImVec2(xs[i].t1, ys[j].t1), tint);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A button layer over the box [a, b]: the whole texture, reaching past the box by its margins.
|
||||||
|
void btn_layer(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float k, ImU32 tint, bool tile_x = false) {
|
||||||
|
const float mx = kBtnL * k, my = kBtnT * k;
|
||||||
|
slice(dl, id, ImVec2(a.x - mx, a.y - my), ImVec2(b.x + mx, b.y + my), 0, 0, kBtnW, kBtnH, kBtnCut, k, tint, tile_x);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A cursor layer around the box [a, b], at a fixed size so its frame keeps its width on any box.
|
||||||
|
void cursor_layer(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float s, ImU32 tint) {
|
||||||
|
const float k = kCurScale * s, mx = kCurX * k, my = kCurY * k;
|
||||||
|
slice(dl, id, ImVec2(a.x - mx, a.y - my), ImVec2(b.x + mx, b.y + my), 0, 0, kCurW, kCurH, kCurCut, k, tint);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// The cursor line's texture is not the line: its alpha climbs from 0 at the outer edge to full about 28 texels in, and
|
||||||
|
// is full inside. The white frame is a band of that ramp, about 3.5 texels wide just outside the box it surrounds
|
||||||
|
// (alpha 102 lies about six texels out from the cursor's box), so the frame follows the texture's own corners.
|
||||||
|
void skin_art_prepare(int art, uint8_t *rgba, uint32_t w, uint32_t h) {
|
||||||
|
if (art != MENU_ART_CURSOR_LINE) return;
|
||||||
|
const int mid = 102, full = 16, soft = 8; // in alpha steps; the ramp climbs about 8.7 of them per texel
|
||||||
|
for (size_t i = 0, n = (size_t)w * h; i < n; i++) {
|
||||||
|
int d = abs((int)rgba[i * 4 + 3] - mid) - full;
|
||||||
|
rgba[i * 4 + 3] = d <= 0 ? 255 : d >= soft ? 0 : (uint8_t)(255 - d * 255 / soft);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A box filter over the 2 x 2 texels each destination texel covers (an odd last row or column repeats). Colour is
|
||||||
|
// weighted by alpha, so what is transparent does not bleed into the edges of the coloured art.
|
||||||
|
void skin_art_halve(const uint8_t *src, uint32_t w, uint32_t h, uint8_t *dst, uint32_t dw, uint32_t dh) {
|
||||||
|
for (uint32_t y = 0; y < dh; y++)
|
||||||
|
for (uint32_t x = 0; x < dw; x++) {
|
||||||
|
const uint32_t xs[2] = {x * 2 < w ? x * 2 : w - 1, x * 2 + 1 < w ? x * 2 + 1 : w - 1},
|
||||||
|
ys[2] = {y * 2 < h ? y * 2 : h - 1, y * 2 + 1 < h ? y * 2 + 1 : h - 1};
|
||||||
|
uint32_t rgb[3] = {0, 0, 0}, plain[3] = {0, 0, 0}, al = 0;
|
||||||
|
for (int j = 0; j < 2; j++)
|
||||||
|
for (int i = 0; i < 2; i++) {
|
||||||
|
const uint8_t *p = src + ((size_t)ys[j] * w + xs[i]) * 4;
|
||||||
|
for (int c = 0; c < 3; c++) rgb[c] += p[c] * (uint32_t)p[3], plain[c] += p[c];
|
||||||
|
al += p[3];
|
||||||
|
}
|
||||||
|
uint8_t *d = dst + ((size_t)y * dw + x) * 4;
|
||||||
|
for (int c = 0; c < 3; c++) d[c] = (uint8_t)(al ? (rgb[c] + al / 2) / al : (plain[c] + 2) / 4);
|
||||||
|
d[3] = (uint8_t)((al + 2) / 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" int menu_art_draw(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, ImU32 tint) {
|
||||||
|
ImTextureID t;
|
||||||
|
if (!menu_art(id, &t, nullptr, nullptr)) return 0;
|
||||||
|
dl->AddImage(t, a, b, ImVec2(0, 0), ImVec2(1, 1), tint);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" int menu_art_draw9(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float corner, float frac, ImU32 tint, int fill) {
|
||||||
|
return menu_art_draw9_turned(dl, id, a, b, corner, frac, tint, fill, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nine pieces: the corners at `corner` pixels on screen from the texture's outer `frac` of each side, the edges
|
||||||
|
// stretched between them, the middle left out (frames) or stretched (fill); the texture turned half a turn when turned,
|
||||||
|
// its top-left corner piece at the bottom right.
|
||||||
|
extern "C" int menu_art_draw9_turned(ImDrawList *dl, MenuArt id, ImVec2 a, ImVec2 b, float corner, float frac, ImU32 tint, int fill,
|
||||||
|
int turned) {
|
||||||
|
ImTextureID t;
|
||||||
|
if (!menu_art(id, &t, nullptr, nullptr)) return 0;
|
||||||
|
float c = corner, maxc = fminf((b.x - a.x) / 2, (b.y - a.y) / 2);
|
||||||
|
if (c > maxc) c = maxc;
|
||||||
|
const float xs[4] = {a.x, a.x + c, b.x - c, b.x}, ys[4] = {a.y, a.y + c, b.y - c, b.y};
|
||||||
|
float us[4] = {0, frac, 1 - frac, 1}, vs[4] = {0, frac, 1 - frac, 1};
|
||||||
|
if (turned)
|
||||||
|
for (int k = 0; k < 4; k++) us[k] = 1 - us[k], vs[k] = 1 - vs[k];
|
||||||
|
for (int j = 0; j < 3; j++)
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
if (i == 1 && j == 1 && !fill) continue;
|
||||||
|
dl->AddImage(t, ImVec2(xs[i], ys[j]), ImVec2(xs[i + 1], ys[j + 1]), ImVec2(us[i], vs[j]), ImVec2(us[i + 1], vs[j + 1]), tint);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_style(ImGuiStyle &s) {
|
||||||
|
ImGui::StyleColorsDark(&s);
|
||||||
|
s.WindowRounding = 10; s.FrameRounding = 6; s.GrabRounding = 6; s.TabRounding = 6; s.ChildRounding = 8;
|
||||||
|
s.WindowPadding = ImVec2(40, 30); s.FramePadding = ImVec2(14, 8); s.ItemSpacing = ImVec2(14, 12);
|
||||||
|
s.WindowBorderSize = 2; s.ScrollbarSize = 16;
|
||||||
|
ImVec4 *c = s.Colors;
|
||||||
|
c[ImGuiCol_WindowBg] = kNavy;
|
||||||
|
c[ImGuiCol_Border] = ImVec4(kGold.x, kGold.y, kGold.z, 0.55f);
|
||||||
|
c[ImGuiCol_ChildBg] = ImVec4(0, 0, 0, 0);
|
||||||
|
c[ImGuiCol_PopupBg] = kNavy;
|
||||||
|
c[ImGuiCol_Text] = ImVec4(0.96f, 0.92f, 0.82f, 1);
|
||||||
|
c[ImGuiCol_TextDisabled] = ImVec4(0.62f, 0.56f, 0.46f, 1);
|
||||||
|
c[ImGuiCol_FrameBg] = ImVec4(0.15f, 0.115f, 0.08f, 1);
|
||||||
|
c[ImGuiCol_FrameBgHovered] = ImVec4(0.24f, 0.18f, 0.10f, 1);
|
||||||
|
c[ImGuiCol_FrameBgActive] = kGreen;
|
||||||
|
c[ImGuiCol_SliderGrab] = kOcarina;
|
||||||
|
c[ImGuiCol_SliderGrabActive] = kGold;
|
||||||
|
c[ImGuiCol_CheckMark] = kGold;
|
||||||
|
c[ImGuiCol_Button] = ImVec4(0.19f, 0.145f, 0.09f, 1);
|
||||||
|
c[ImGuiCol_ButtonHovered] = kGreen;
|
||||||
|
c[ImGuiCol_ButtonActive] = kOcarina;
|
||||||
|
c[ImGuiCol_Header] = ImVec4(0.24f, 0.18f, 0.10f, 1);
|
||||||
|
c[ImGuiCol_HeaderHovered] = kGreen;
|
||||||
|
c[ImGuiCol_HeaderActive] = kOcarina;
|
||||||
|
c[ImGuiCol_Tab] = ImVec4(0.13f, 0.10f, 0.07f, 1);
|
||||||
|
c[ImGuiCol_TabHovered] = kGreen;
|
||||||
|
c[ImGuiCol_TabSelected] = ImVec4(0.42f, 0.31f, 0.15f, 1);
|
||||||
|
c[ImGuiCol_TabSelectedOverline] = kGold;
|
||||||
|
c[ImGuiCol_NavCursor] = kGold;
|
||||||
|
c[ImGuiCol_Separator] = ImVec4(kGold.x, kGold.y, kGold.z, 0.30f);
|
||||||
|
c[ImGuiCol_ScrollbarGrab] = ImVec4(0.36f, 0.28f, 0.16f, 1);
|
||||||
|
c[ImGuiCol_ScrollbarBg] = ImVec4(0, 0, 0, 0.2f);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The grain over [a, b]: the tile repeated at four pixels per texel (its noise wraps, so the copies join unseen), so the
|
||||||
|
// blotches keep their size on any box; darkening where the tile is dense, lightening where its mirror image is.
|
||||||
|
static void grain(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float strength) {
|
||||||
|
if (!g_grain_ok) return;
|
||||||
|
ImTextureID tex = ImGui::GetIO().Fonts->TexID;
|
||||||
|
const float pw = kGrainW * 4.0f * s, ph = kGrainH * 4.0f * s;
|
||||||
|
const ImVec2 du(g_grain_uv1.x - g_grain_uv0.x, g_grain_uv1.y - g_grain_uv0.y);
|
||||||
|
const ImU32 dark = rgba(20, 12, 4, 0.30f * strength), light = rgba(255, 236, 196, 0.12f * strength);
|
||||||
|
for (float y = a.y; y < b.y; y += ph)
|
||||||
|
for (float x = a.x; x < b.x; x += pw) {
|
||||||
|
float x1 = fminf(x + pw, b.x), y1 = fminf(y + ph, b.y);
|
||||||
|
ImVec2 u0 = g_grain_uv0, u1(g_grain_uv0.x + du.x * (x1 - x) / pw, g_grain_uv0.y + du.y * (y1 - y) / ph);
|
||||||
|
dl->AddImage(tex, ImVec2(x, y), ImVec2(x1, y1), u0, u1, dark);
|
||||||
|
// the mirror image: the tile read from its far corner, over the same piece
|
||||||
|
ImVec2 m0(g_grain_uv1.x, g_grain_uv1.y), m1(g_grain_uv1.x - du.x * (x1 - x) / pw, g_grain_uv1.y - du.y * (y1 - y) / ph);
|
||||||
|
dl->AddImage(tex, ImVec2(x, y), ImVec2(x1, y1), m0, m1, light);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_atlas_add(ImFontAtlas *fa) { g_grain_rect = fa->AddCustomRectRegular(kGrainW, kGrainH), g_grain_ok = false; }
|
||||||
|
|
||||||
|
void skin_atlas_fill(ImFontAtlas *fa) {
|
||||||
|
unsigned char *px;
|
||||||
|
int w, h;
|
||||||
|
fa->GetTexDataAsRGBA32(&px, &w, &h);
|
||||||
|
const ImFontAtlasCustomRect *r = g_grain_rect >= 0 ? fa->GetCustomRectByIndex(g_grain_rect) : nullptr;
|
||||||
|
if (!px || !r || !r->IsPacked()) return;
|
||||||
|
// value noise of three octaves on a lattice that wraps, with a little fine speckle: blotches and grain
|
||||||
|
auto lattice = [](int x, int y, int seed) {
|
||||||
|
unsigned v = (unsigned)(x * 374761393 + y * 668265263 + seed * 2246822519u);
|
||||||
|
v = (v ^ (v >> 13)) * 1274126177u;
|
||||||
|
return ((v ^ (v >> 16)) & 0xffff) / 65535.0f;
|
||||||
|
};
|
||||||
|
auto smooth = [&](float x, float y, int cell, int seed) {
|
||||||
|
float gx = x / cell, gy = y / cell;
|
||||||
|
int x0 = (int)floorf(gx), y0 = (int)floorf(gy);
|
||||||
|
float fx = gx - x0, fy = gy - y0;
|
||||||
|
fx = fx * fx * (3 - 2 * fx), fy = fy * fy * (3 - 2 * fy);
|
||||||
|
int wx = kGrainW / cell, wy = kGrainH / cell;
|
||||||
|
auto at = [&](int i, int j) { return lattice(((i % wx) + wx) % wx, ((j % wy) + wy) % wy, seed); };
|
||||||
|
float top = at(x0, y0) + (at(x0 + 1, y0) - at(x0, y0)) * fx;
|
||||||
|
float bot = at(x0, y0 + 1) + (at(x0 + 1, y0 + 1) - at(x0, y0 + 1)) * fx;
|
||||||
|
return top + (bot - top) * fy;
|
||||||
|
};
|
||||||
|
for (int y = 0; y < kGrainH; y++)
|
||||||
|
for (int x = 0; x < kGrainW; x++) {
|
||||||
|
float n = 0.55f * smooth((float)x, (float)y, 16, 1) + 0.30f * smooth((float)x, (float)y, 8, 2) +
|
||||||
|
0.15f * smooth((float)x, (float)y, 4, 3);
|
||||||
|
n = n * 0.85f + 0.15f * lattice(x, y, 9);
|
||||||
|
float v = fminf(1.0f, fmaxf(0.0f, (n - 0.35f) * 1.8f));
|
||||||
|
unsigned char *d = px + 4 * ((size_t)(r->Y + y) * w + r->X + x);
|
||||||
|
d[0] = d[1] = d[2] = 255, d[3] = (unsigned char)(v * 255.0f + 0.5f);
|
||||||
|
}
|
||||||
|
fa->CalcCustomRectUV(r, &g_grain_uv0, &g_grain_uv1);
|
||||||
|
g_grain_ok = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The button from the game's layers; false while they are not there. plate: the selected tab's plate under the lines.
|
||||||
|
static bool button_art(ImDrawList *dl, ImVec2 a, ImVec2 b, float lift, bool dim, bool plate) {
|
||||||
|
if (!have_art({MENU_ART_BTN_RIM, MENU_ART_BTN_FILL, MENU_ART_BTN_GRAIN, MENU_ART_BTN_EDGE, MENU_ART_BTN_LINE})) return false;
|
||||||
|
static const int fill0[3] = {100, 76, 42}, fill1[3] = {128, 99, 58}, grain0[3] = {150, 118, 76}, grain1[3] = {178, 144, 96};
|
||||||
|
static const int grey_fill[3] = {76, 67, 56}, grey_grain[3] = {128, 116, 100};
|
||||||
|
const float t = (b.y - a.y) / kBtnBoxH;
|
||||||
|
btn_layer(dl, MENU_ART_BTN_RIM, a, b, t, rgba(20, 14, 8, 0.85f));
|
||||||
|
btn_layer(dl, MENU_ART_BTN_FILL, a, b, t, dim ? mix(grey_fill, grey_fill, 0, 1) : mix(fill0, fill1, lift, 1));
|
||||||
|
btn_layer(dl, MENU_ART_BTN_GRAIN, a, b, t, dim ? mix(grey_grain, grey_grain, 0, 0.26f) : mix(grain0, grain1, lift, 0.32f), true);
|
||||||
|
if (plate) slice(dl, MENU_ART_TAB_SELECT, a, b, kTabL, kTabT, kTabR, kTabB, 30, t, rgba(232, 186, 104, 0.55f));
|
||||||
|
btn_layer(dl, MENU_ART_BTN_EDGE, a, b, t, dim ? rgba(98, 88, 74, 1) : rgba(140, 116, 74, 1));
|
||||||
|
btn_layer(dl, MENU_ART_BTN_LINE, a, b, t, dim ? rgba(112, 102, 88, 1) : rgba(150 + (int)(24 * lift), 124 + (int)(20 * lift), 80 + (int)(12 * lift), 1));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_button(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float lift, bool dim) {
|
||||||
|
static const int top0[3] = {98, 75, 41}, top1[3] = {122, 95, 55}, bot0[3] = {84, 63, 32}, bot1[3] = {106, 81, 44};
|
||||||
|
static const int grey_top[3] = {66, 58, 48}, grey_bot[3] = {56, 49, 40};
|
||||||
|
lift = lift < 0 ? 0 : lift > 1 ? 1 : lift;
|
||||||
|
if (button_art(dl, a, b, lift, dim, false)) return;
|
||||||
|
const float k = 1.0f * s;
|
||||||
|
dl->AddRectFilled(a, b, rgba(28, 22, 14, 0.92f)); // the dark rim between the button and what is behind it
|
||||||
|
ImVec2 ia(a.x + k, a.y + k), ib(b.x - k, b.y - k);
|
||||||
|
ImU32 top = dim ? mix(grey_top, grey_top, 0, 1) : mix(top0, top1, lift, 1);
|
||||||
|
ImU32 bot = dim ? mix(grey_bot, grey_bot, 0, 1) : mix(bot0, bot1, lift, 1);
|
||||||
|
dl->AddRectFilledMultiColor(ia, ib, top, top, bot, bot);
|
||||||
|
grain(dl, ia, ib, s, dim ? 0.5f : 1.0f);
|
||||||
|
dl->AddRect(ia, ib, dim ? rgba(98, 88, 74, 1) : rgba(126, 104, 68, 1), 0, 0, 1.4f * s); // the light edge
|
||||||
|
float h = b.y - a.y, inset = fmaxf(4.0f * s, h * 0.1f);
|
||||||
|
ornament_line(dl, a, b, inset, s, dim ? rgba(104, 94, 80, 1) : rgba(134 + (int)(18 * lift), 111 + (int)(14 * lift),
|
||||||
|
70 + (int)(8 * lift), 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
float skin_cursor_reach(float s) { return 3.0f * s + 2.5f * s + 12.0f * s; }
|
||||||
|
|
||||||
|
// one slow breath every 1.6 s, as the game's cursor pulses
|
||||||
|
static float breath(void) { return 0.5f - 0.5f * cosf((float)ImGui::GetTime() * 6.2831853f / 1.6f); }
|
||||||
|
|
||||||
|
void skin_cursor_glow(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float alpha) {
|
||||||
|
if (have_art({MENU_ART_CURSOR_GLOW})) {
|
||||||
|
cursor_layer(dl, MENU_ART_CURSOR_GLOW, a, b, s, rgba(164, 194, 240, alpha * (0.78f + 0.22f * breath())));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// filled rounded boxes stacked from the outside in, each faint, so the glow brightens towards the frame; the box
|
||||||
|
// drawn over them hides their middle
|
||||||
|
const float ring = 3.0f * s + 1.25f * s, br = breath();
|
||||||
|
const int n = 12;
|
||||||
|
for (int i = n; i >= 1; i--) {
|
||||||
|
float o = ring + i * 0.95f * s;
|
||||||
|
dl->AddRectFilled(ImVec2(a.x - o, a.y - o), ImVec2(b.x + o, b.y + o), rgba(160, 190, 236, alpha * (0.055f + 0.03f * br)),
|
||||||
|
2.0f * s + i * 0.9f * s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_cursor_frame(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float alpha) {
|
||||||
|
if (have_art({MENU_ART_CURSOR_LINE})) {
|
||||||
|
cursor_layer(dl, MENU_ART_CURSOR_LINE, a, b, s, rgba(240, 242, 245, alpha));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const float gap = 3.0f * s, thick = 2.5f * s, ring = gap + thick * 0.5f;
|
||||||
|
// a little glow in the gap between the box and the frame, then the white frame
|
||||||
|
dl->AddRect(ImVec2(a.x - gap * 0.5f, a.y - gap * 0.5f), ImVec2(b.x + gap * 0.5f, b.y + gap * 0.5f),
|
||||||
|
rgba(190, 210, 240, alpha * (0.30f + 0.15f * breath())), gap * 0.4f, 0, gap);
|
||||||
|
dl->AddRect(ImVec2(a.x - ring, a.y - ring), ImVec2(b.x + ring, b.y + ring), rgba(236, 238, 241, alpha), 2.0f * s, 0, thick);
|
||||||
|
}
|
||||||
|
|
||||||
|
float skin_filigree_height(float s) { return 26.0f * s; }
|
||||||
|
|
||||||
|
// The divider from the game's art: the ornament (its ink runs from (28, 24) to (200, 65) in 228 x 80) and on each side
|
||||||
|
// the line texture, turned round for the left one: its stroke from x = 38 to 217 stretched, then the dot up to x = 232
|
||||||
|
// at its own proportions, the whole on the row y = 23 of 240 x 43.
|
||||||
|
static bool filigree_art(ImDrawList *dl, float x0, float x1, float y, float s, float alpha) {
|
||||||
|
ImTextureID mark, stroke;
|
||||||
|
float mw, mh, lw, lh;
|
||||||
|
if (!menu_art(MENU_ART_DIVIDER, &mark, &mw, &mh) || !menu_art(MENU_ART_DIVIDER_LINE, &stroke, &lw, &lh)) return false;
|
||||||
|
const ImU32 orn = rgba(196, 164, 112, alpha), line = rgba(150, 126, 90, alpha);
|
||||||
|
const float orn_w = fminf(84.0f * s, (x1 - x0) * 0.5f), k = orn_w / 172.0f, cx = (x0 + x1) * 0.5f;
|
||||||
|
dl->AddImage(mark, ImVec2(cx - 114 * k, y - 44.5f * k), ImVec2(cx - 114 * k + mw * k, y - 44.5f * k + mh * k), ImVec2(0, 0), ImVec2(1, 1), orn);
|
||||||
|
const float lk = 0.42f * s, top = y - 9 * lk, bot = y + 9 * lk, v0 = 14 / lh, v1 = 32 / lh, dot = (232 - 217) * lk;
|
||||||
|
const float from = cx + orn_w * 0.5f + 5 * s, to = x1 - 4 * s;
|
||||||
|
if (to - dot <= from) return true;
|
||||||
|
const float u0 = 38 / lw, u1 = 217 / lw, u2 = 232 / lw, mirror = 2 * cx;
|
||||||
|
dl->AddImage(stroke, ImVec2(from, top), ImVec2(to - dot, bot), ImVec2(u0, v0), ImVec2(u1, v1), line);
|
||||||
|
dl->AddImage(stroke, ImVec2(to - dot, top), ImVec2(to, bot), ImVec2(u1, v0), ImVec2(u2, v1), line);
|
||||||
|
dl->AddImage(stroke, ImVec2(mirror - (to - dot), top), ImVec2(mirror - from, bot), ImVec2(u1, v0), ImVec2(u0, v1), line);
|
||||||
|
dl->AddImage(stroke, ImVec2(mirror - to, top), ImVec2(mirror - (to - dot), bot), ImVec2(u2, v0), ImVec2(u1, v1), line);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_filigree(ImDrawList *dl, float x0, float x1, float y, float s, float alpha) {
|
||||||
|
if (filigree_art(dl, x0, x1, y, s, alpha)) return;
|
||||||
|
const ImU32 line = rgba(96, 80, 56, alpha), dot = rgba(110, 92, 64, alpha), orn = rgba(138, 114, 76, alpha);
|
||||||
|
float orn_w = fminf(78.0f * s, (x1 - x0) * 0.5f), k = orn_w / 108.0f, cx = (x0 + x1) * 0.5f;
|
||||||
|
float dot_r = 1.5f * s, gap = 5.0f * s;
|
||||||
|
dl->AddCircleFilled(ImVec2(x0 + 4 * s + dot_r, y), dot_r, dot);
|
||||||
|
dl->AddCircleFilled(ImVec2(x1 - 4 * s - dot_r, y), dot_r, dot);
|
||||||
|
dl->AddLine(ImVec2(x0 + 4 * s + 2 * dot_r + gap, y), ImVec2(cx - orn_w * 0.5f - gap, y), line, 1.0f * s);
|
||||||
|
dl->AddLine(ImVec2(cx + orn_w * 0.5f + gap, y), ImVec2(x1 - 4 * s - 2 * dot_r - gap, y), line, 1.0f * s);
|
||||||
|
auto at = [&](float px, float py) { return ImVec2(cx + (px - 60.0f) * k, y + (py - 21.0f) * k); };
|
||||||
|
for (const float *p : kFiligree) {
|
||||||
|
ImVec2 cur(0, 0);
|
||||||
|
bool open = false;
|
||||||
|
for (int i = 0; p[i] != F_END;) {
|
||||||
|
if (p[i] == F_M) {
|
||||||
|
if (open) dl->PathStroke(orn, 0, 2.2f * k);
|
||||||
|
cur = at(p[i + 1], p[i + 2]);
|
||||||
|
dl->PathLineTo(cur);
|
||||||
|
open = true;
|
||||||
|
i += 3;
|
||||||
|
} else if (p[i] == F_L) {
|
||||||
|
cur = at(p[i + 1], p[i + 2]);
|
||||||
|
dl->PathLineTo(cur);
|
||||||
|
i += 3;
|
||||||
|
} else if (p[i] == F_C) {
|
||||||
|
cur = at(p[i + 5], p[i + 6]);
|
||||||
|
dl->PathBezierCubicCurveTo(at(p[i + 1], p[i + 2]), at(p[i + 3], p[i + 4]), cur, 8);
|
||||||
|
i += 7;
|
||||||
|
} else { // F_Z: back to the path's start (no path here uses it)
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (open) dl->PathStroke(orn, 0, 2.2f * k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_panel(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float alpha) {
|
||||||
|
if (have_art({MENU_ART_PANEL_FILL, MENU_ART_BTN_EDGE, MENU_ART_BTN_LINE})) {
|
||||||
|
// the panel's own texture inside its box, with the button's edge and inset line at a size that suits a large box
|
||||||
|
const float k = 0.62f * s;
|
||||||
|
slice(dl, MENU_ART_PANEL_FILL, a, b, kPanelM, kPanelM, kPanelW - kPanelM, kPanelH - kPanelM, 40, k, rgba(255, 255, 255, alpha), true, true);
|
||||||
|
btn_layer(dl, MENU_ART_BTN_EDGE, a, b, k, rgba(126, 104, 68, 1));
|
||||||
|
btn_layer(dl, MENU_ART_BTN_LINE, a, b, k, rgba(150, 124, 80, 1));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dl->AddRectFilled(a, b, rgba(20, 15, 10, 0.85f * alpha));
|
||||||
|
ImVec2 ia(a.x + 1.0f * s, a.y + 1.0f * s), ib(b.x - 1.0f * s, b.y - 1.0f * s);
|
||||||
|
dl->AddRectFilledMultiColor(ia, ib, rgba(44, 35, 25, alpha), rgba(44, 35, 25, alpha), rgba(33, 26, 19, alpha),
|
||||||
|
rgba(33, 26, 19, alpha));
|
||||||
|
grain(dl, ia, ib, s, 0.6f * alpha);
|
||||||
|
dl->AddRect(ia, ib, rgba(110, 90, 58, 1), 0, 0, 1.4f * s);
|
||||||
|
ornament_line(dl, a, b, 7.0f * s, s, rgba(122, 101, 66, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool skin_widget_button(const char *label, ImVec2 size, float s) {
|
||||||
|
ImVec2 ts = ImGui::CalcTextSize(label, nullptr, true);
|
||||||
|
const ImGuiStyle &st = ImGui::GetStyle();
|
||||||
|
ImVec2 sz(size.x > 0 ? size.x : ts.x + st.FramePadding.x * 2, size.y > 0 ? size.y : ts.y + st.FramePadding.y * 2);
|
||||||
|
ImVec2 a = ImGui::GetCursorScreenPos(), b(a.x + sz.x, a.y + sz.y);
|
||||||
|
ImGui::PushStyleColor(ImGuiCol_NavCursor, ImVec4(0, 0, 0, 0)); // the cursor below shows the selection
|
||||||
|
bool pressed = ImGui::InvisibleButton(label, sz, ImGuiButtonFlags_EnableNav);
|
||||||
|
ImGui::PopStyleColor();
|
||||||
|
bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible;
|
||||||
|
bool held = ImGui::IsItemActive();
|
||||||
|
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||||
|
if (foc || hov) skin_cursor_glow(dl, a, b, s, foc ? 1.0f : 0.55f); // under the button
|
||||||
|
skin_button(dl, a, b, s, held ? 0.4f : foc ? 1.0f : hov ? 0.7f : 0.15f, false);
|
||||||
|
const char *end = ImGui::FindRenderedTextEnd(label);
|
||||||
|
dl->AddText(ImVec2(floorf((a.x + b.x - ts.x) * 0.5f), floorf((a.y + b.y - ts.y) * 0.5f)), SKIN_TEXT, label, end);
|
||||||
|
if (foc || hov) skin_cursor_frame(dl, a, b, s, foc ? 1.0f : 0.55f);
|
||||||
|
return pressed;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool skin_tab_item(const char *id, const char *text, int flags, float s, ImFont *font) {
|
||||||
|
// Dear ImGui keeps the bar's behaviour (selecting, sizing, the D-pad) and lays out the tab with everything it would
|
||||||
|
// draw made invisible; the button and the text go over its rectangle here.
|
||||||
|
static const ImGuiCol hide[] = {ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed,
|
||||||
|
ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline, ImGuiCol_Text, ImGuiCol_NavCursor};
|
||||||
|
for (ImGuiCol c : hide) ImGui::PushStyleColor(c, ImVec4(0, 0, 0, 0));
|
||||||
|
ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(12.0f * s, ImGui::GetStyle().ItemInnerSpacing.y));
|
||||||
|
if (font) ImGui::PushFont(font);
|
||||||
|
const bool shown = ImGui::BeginTabItem(id, nullptr, flags);
|
||||||
|
ImGui::PopStyleVar();
|
||||||
|
ImGui::PopStyleColor((int)(sizeof hide / sizeof *hide));
|
||||||
|
ImVec2 a = ImGui::GetItemRectMin(), b = ImGui::GetItemRectMax();
|
||||||
|
if (b.x > a.x && b.y > a.y) {
|
||||||
|
b.y -= 4.0f * s; // clear of the line under the tabs
|
||||||
|
const bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible;
|
||||||
|
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||||
|
if (foc) skin_cursor_glow(dl, a, b, s, 1.0f);
|
||||||
|
const float lift = shown ? 1.0f : hov ? 0.6f : 0.0f;
|
||||||
|
if (!button_art(dl, a, b, lift, false, shown)) skin_button(dl, a, b, s, lift, false);
|
||||||
|
const ImVec2 ts = ImGui::CalcTextSize(text, nullptr, true);
|
||||||
|
dl->AddText(ImVec2(floorf((a.x + b.x - ts.x) * 0.5f), floorf((a.y + b.y - ts.y) * 0.5f)), shown ? SKIN_GOLD : SKIN_TEXT, text);
|
||||||
|
if (foc) skin_cursor_frame(dl, a, b, s, 1.0f);
|
||||||
|
}
|
||||||
|
if (font) ImGui::PopFont();
|
||||||
|
return shown;
|
||||||
|
}
|
||||||
|
|
||||||
|
void skin_boot_panel(ImDrawList *dl, ImFont *head, float head_px, ImFont *body, float body_px, const char *title,
|
||||||
|
const char *step, const char *hint, float frac, float sweep, float w, float h, float s) {
|
||||||
|
const float pad = 38 * s, gap = 16 * s, bar_h = 12 * s, fh = skin_filigree_height(s);
|
||||||
|
ImVec2 ts = head->CalcTextSizeA(head_px, FLT_MAX, 0, title), ss = body->CalcTextSizeA(body_px, FLT_MAX, 0, step),
|
||||||
|
hs = body->CalcTextSizeA(body_px * 0.8f, FLT_MAX, 0, hint);
|
||||||
|
float pw = fminf(fmaxf(fmaxf(fmaxf(ts.x, hs.x), ss.x), 560 * s) + pad * 2, w - 24 * s);
|
||||||
|
float ph = pad + ts.y + fh + gap * 0.4f + ss.y + gap * 0.7f + bar_h + gap * 1.4f + hs.y + pad;
|
||||||
|
ImVec2 a(floorf((w - pw) / 2), floorf((h - ph) / 2)), b(a.x + pw, a.y + ph);
|
||||||
|
skin_panel(dl, a, b, s);
|
||||||
|
float y = a.y + pad;
|
||||||
|
dl->AddText(head, head_px, ImVec2(floorf((w - ts.x) / 2), y), SKIN_GOLD, title);
|
||||||
|
y += ts.y;
|
||||||
|
skin_filigree(dl, a.x + pad, b.x - pad, y + fh * 0.5f, s);
|
||||||
|
y += fh + gap * 0.4f;
|
||||||
|
dl->AddText(body, body_px, ImVec2(a.x + pad, y), SKIN_TEXT, step);
|
||||||
|
y += ss.y + gap * 0.7f;
|
||||||
|
// the bar: a sunken track with the frames' brown edge, filled in gold from the left
|
||||||
|
ImVec2 ba(a.x + pad, y), bb(b.x - pad, y + bar_h);
|
||||||
|
dl->AddRectFilled(ba, bb, rgba(12, 9, 6, 0.85f), 2 * s);
|
||||||
|
float x0 = ba.x + 2 * s, x1 = bb.x - 2 * s, top = ba.y + 2 * s, bot = bb.y - 2 * s;
|
||||||
|
auto fill = [&](float from, float to) {
|
||||||
|
if (to - from < 1) return;
|
||||||
|
dl->AddRectFilledMultiColor(ImVec2(from, top), ImVec2(to, bot), rgba(246, 214, 128, 1), rgba(246, 214, 128, 1),
|
||||||
|
rgba(196, 148, 66, 1), rgba(196, 148, 66, 1));
|
||||||
|
dl->AddLine(ImVec2(from, top + 0.5f * s), ImVec2(to, top + 0.5f * s), rgba(255, 240, 196, 0.6f), 1.0f * s);
|
||||||
|
};
|
||||||
|
if (frac >= 0) {
|
||||||
|
fill(x0, x0 + (x1 - x0) * fminf(frac, 1.0f));
|
||||||
|
} else {
|
||||||
|
float span = (x1 - x0) * 0.2f, run = (x1 - x0) - span, at = sweep < 0 ? 0 : sweep > 1 ? 1 : sweep;
|
||||||
|
fill(x0 + run * at, x0 + run * at + span);
|
||||||
|
}
|
||||||
|
dl->AddRect(ba, bb, rgba(110, 90, 58, 1), 2 * s, 0, 1.3f * s);
|
||||||
|
y += bar_h + gap * 1.4f;
|
||||||
|
dl->AddText(body, body_px * 0.8f, ImVec2(floorf((w - hs.x) / 2), y), rgba(214, 198, 166, 0.85f), hint);
|
||||||
|
}
|
||||||
60
runtime/ui/menu_skin.h
Normal file
60
runtime/ui/menu_skin.h
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
// The look of the game's own menus (ui/menu_skin.cpp): the save menu's brown button with its inset line and corner
|
||||||
|
// ornaments, the options menu's white selection cursor and its filigree divider, and a dark panel framed like the
|
||||||
|
// buttons. Each is drawn from the game's textures when they are there (ui/menu_art.cpp), else from plain shapes in the
|
||||||
|
// same colours. Sizes are in pixels at 1080 lines; s scales them (menu.cpp menu_scale).
|
||||||
|
#pragma once
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "imgui.h"
|
||||||
|
|
||||||
|
// What the art needs after it is decoded: the cursor's frame is cut out of its texture here (art: a MenuArt).
|
||||||
|
void skin_art_prepare(int art, uint8_t *rgba, uint32_t w, uint32_t h);
|
||||||
|
// One level of an art at half the size of the last: dst is dw x dh (each half of the source's, at least 1).
|
||||||
|
void skin_art_halve(const uint8_t *src, uint32_t w, uint32_t h, uint8_t *dst, uint32_t dw, uint32_t dh);
|
||||||
|
|
||||||
|
// The settings menu's Dear ImGui style at 1080 lines: the colours of the game's menus (a dark umber panel, warm browns
|
||||||
|
// for frames and what is selected, gold ornaments and accents, parchment text) and the sizes of its frames.
|
||||||
|
void skin_style(ImGuiStyle &s);
|
||||||
|
|
||||||
|
// The boxes' mottled grain lives in the font atlas: skin_atlas_add before the atlas is built (it reserves the tile),
|
||||||
|
// skin_atlas_fill after it is built and before it is uploaded (it draws the tile). Without them the boxes are plain.
|
||||||
|
void skin_atlas_add(ImFontAtlas *fa);
|
||||||
|
void skin_atlas_fill(ImFontAtlas *fa);
|
||||||
|
|
||||||
|
// The brown button over [a, b]: a dark rim, a light edge, the fill, and an inset line that stops short of a diamond at
|
||||||
|
// the top-left and bottom-right corners and of a curl at the other two. lift 0..1 brightens the fill (hovered or
|
||||||
|
// selected); dim mutes it (a row the environment fixes).
|
||||||
|
void skin_button(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float lift, bool dim);
|
||||||
|
// How far skin_cursor reaches outside the box it surrounds: a box needs that much room on every side.
|
||||||
|
float skin_cursor_reach(float s);
|
||||||
|
// The selection cursor around the box [a, b], in two parts: a soft white-blue glow, drawn before the box (the box hides
|
||||||
|
// its middle, so it shows only around it), and a white frame a little outside the box, drawn after it. Both breathe
|
||||||
|
// slowly; alpha 0..1 (a hovered row's cursor is fainter than the selected one's).
|
||||||
|
void skin_cursor_glow(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float alpha);
|
||||||
|
void skin_cursor_frame(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float alpha);
|
||||||
|
// The divider: a thin line with a dot at each end and the ornament in its middle, centred on y between x0 and x1.
|
||||||
|
void skin_filigree(ImDrawList *dl, float x0, float x1, float y, float s, float alpha = 1);
|
||||||
|
float skin_filigree_height(float s);
|
||||||
|
// A dark panel over [a, b] with the button's edge, inset line and corner ornaments (the description pane, the
|
||||||
|
// performance overlay). alpha scales its fill.
|
||||||
|
void skin_panel(ImDrawList *dl, ImVec2 a, ImVec2 b, float s, float alpha = 1);
|
||||||
|
|
||||||
|
// The boot screen's box (menu.cpp menu_boot_frame) centred in a w x h frame: the panel, the title in gold over the
|
||||||
|
// divider, the step's line, a bar filled to frac (0..1; a negative frac: a short segment sweeping at position sweep
|
||||||
|
// 0..1, no count yet) and the hint under it.
|
||||||
|
void skin_boot_panel(ImDrawList *dl, ImFont *head, float head_px, ImFont *body, float body_px, const char *title,
|
||||||
|
const char *step, const char *hint, float frac, float sweep, float w, float h, float s);
|
||||||
|
|
||||||
|
// A button widget drawn as skin_button with its label centred and skin_cursor round it while selected or hovered (the
|
||||||
|
// save menu's Load and Cancel). True when pressed (click, A, Enter). size: as for ImGui::Button.
|
||||||
|
bool skin_widget_button(const char *label, ImVec2 size, float s);
|
||||||
|
|
||||||
|
// One tab of the bar: ImGui::BeginTabItem drawn as the rows' button, with the game's plate behind the selected tab's
|
||||||
|
// lines and its text in gold. id: BeginTabItem's label (it sizes the tab); text: what is shown. font: the label's font,
|
||||||
|
// NULL for the current one. True when selected: call ImGui::EndTabItem then.
|
||||||
|
bool skin_tab_item(const char *id, const char *text, int flags, float s, ImFont *font);
|
||||||
|
|
||||||
|
// The colours the boxes are drawn in, for text on them.
|
||||||
|
#define SKIN_TEXT IM_COL32(244, 236, 214, 255) // labels on a button
|
||||||
|
#define SKIN_TEXT_DIM IM_COL32(206, 188, 150, 255) // notes on a button
|
||||||
|
#define SKIN_GOLD IM_COL32(236, 196, 104, 255) // headings and accents
|
||||||
@@ -40,8 +40,12 @@ static ImGuiKey key_of(WPARAM vk) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The mouse buttons pressed on the open menu and not yet released, one bit each. While any is held the window has the
|
||||||
|
// mouse capture, so the release reaches the menu where the pointer went outside the window (else ImGui would hold the
|
||||||
|
// button down and miss the next click). The game itself only clips the cursor (input_win.c), it takes no capture.
|
||||||
|
static unsigned g_held;
|
||||||
|
|
||||||
extern "C" int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) {
|
extern "C" int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) {
|
||||||
(void)h;
|
|
||||||
switch (m) {
|
switch (m) {
|
||||||
case WM_KEYDOWN:
|
case WM_KEYDOWN:
|
||||||
case WM_SYSKEYDOWN:
|
case WM_SYSKEYDOWN:
|
||||||
@@ -71,9 +75,17 @@ extern "C" int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res)
|
|||||||
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
|
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
|
||||||
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
|
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
|
||||||
case WM_MBUTTONDOWN: case WM_MBUTTONUP: {
|
case WM_MBUTTONDOWN: case WM_MBUTTONUP: {
|
||||||
if (!menu_is_open()) return 0;
|
|
||||||
int b = m == WM_LBUTTONDOWN || m == WM_LBUTTONUP ? 0 : m == WM_RBUTTONDOWN || m == WM_RBUTTONUP ? 1 : 2;
|
int b = m == WM_LBUTTONDOWN || m == WM_LBUTTONUP ? 0 : m == WM_RBUTTONDOWN || m == WM_RBUTTONUP ? 1 : 2;
|
||||||
int down = m == WM_LBUTTONDOWN || m == WM_RBUTTONDOWN || m == WM_MBUTTONDOWN;
|
int down = m == WM_LBUTTONDOWN || m == WM_RBUTTONDOWN || m == WM_MBUTTONDOWN;
|
||||||
|
if (!down && (g_held & 1u << b)) { // also when the menu closed meanwhile: the capture goes either way
|
||||||
|
g_held &= ~(1u << b);
|
||||||
|
if (!g_held && GetCapture() == h) ReleaseCapture();
|
||||||
|
}
|
||||||
|
if (!menu_is_open()) return 0;
|
||||||
|
if (down) {
|
||||||
|
if (!g_held) SetCapture(h);
|
||||||
|
g_held |= 1u << b;
|
||||||
|
}
|
||||||
menu_event_mouse_pos((float)GET_X_LPARAM(l), (float)GET_Y_LPARAM(l));
|
menu_event_mouse_pos((float)GET_X_LPARAM(l), (float)GET_Y_LPARAM(l));
|
||||||
menu_event_mouse_button(b, down);
|
menu_event_mouse_button(b, down);
|
||||||
return 0;
|
return 0;
|
||||||
@@ -81,6 +93,13 @@ extern "C" int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res)
|
|||||||
case WM_MOUSEWHEEL:
|
case WM_MOUSEWHEEL:
|
||||||
if (menu_is_open()) menu_event_wheel(0, (float)GET_WHEEL_DELTA_WPARAM(w) / WHEEL_DELTA);
|
if (menu_is_open()) menu_event_wheel(0, (float)GET_WHEEL_DELTA_WPARAM(w) / WHEEL_DELTA);
|
||||||
return 0;
|
return 0;
|
||||||
|
case WM_CAPTURECHANGED: // another window took the capture (ReleaseCapture above finds g_held empty)
|
||||||
|
if ((HWND)l != h && g_held) {
|
||||||
|
for (int b = 0; b < 3; b++)
|
||||||
|
if (g_held & 1u << b) menu_event_mouse_button(b, 0);
|
||||||
|
g_held = 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
case WM_SETFOCUS:
|
case WM_SETFOCUS:
|
||||||
case WM_KILLFOCUS:
|
case WM_KILLFOCUS:
|
||||||
menu_event_focus(m == WM_SETFOCUS);
|
menu_event_focus(m == WM_SETFOCUS);
|
||||||
|
|||||||
@@ -12,20 +12,18 @@
|
|||||||
#include "imgui.h"
|
#include "imgui.h"
|
||||||
#include "imgui_internal.h" // SetKeyOwner, SetFocusID, NavCursorVisible
|
#include "imgui_internal.h" // SetKeyOwner, SetFocusID, NavCursorVisible
|
||||||
|
|
||||||
|
#include "ui/menu_skin.h"
|
||||||
#include "ui/option_rows.h"
|
#include "ui/option_rows.h"
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
#include "cfg.h"
|
#include "cfg.h"
|
||||||
#include "platform/platform.h"
|
#include "platform/platform.h"
|
||||||
#include "ui_text.h"
|
#include "ui_text.h"
|
||||||
#include "ui/menu_art.h"
|
|
||||||
#include "menu_sound.h"
|
#include "menu_sound.h"
|
||||||
// host.h pulls in cpu.h, which is C only: the one function needed from it, as declared there.
|
// host.h pulls in cpu.h, which is C only: the one function needed from it, as declared there.
|
||||||
void rt_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
|
void rt_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||||
}
|
}
|
||||||
|
|
||||||
static const ImU32 kGold = IM_COL32(236, 194, 84, 255);
|
|
||||||
static const ImU32 kDim = IM_COL32(150, 150, 140, 255);
|
|
||||||
static const ImU32 kGrey = IM_COL32(110, 110, 102, 255);
|
static const ImU32 kGrey = IM_COL32(110, 110, 102, 255);
|
||||||
|
|
||||||
static float g_scale = 1;
|
static float g_scale = 1;
|
||||||
@@ -36,9 +34,18 @@ static float g_bottom; // opt_reserve_bottom: kept free under
|
|||||||
static bool g_disable_next; // opt_disable_next: the next row is greyed out with g_disable_note
|
static bool g_disable_next; // opt_disable_next: the next row is greyed out with g_disable_note
|
||||||
static const char *g_disable_note;
|
static const char *g_disable_note;
|
||||||
|
|
||||||
// The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown.
|
// The rows' cursor, drawn once all rows are (opt_end), its glow in the layer under the rows and its frame in the one
|
||||||
|
// over them: the selected row's box, else the hovered one's (alpha: fainter for a hovered row, and for one the
|
||||||
|
// environment fixes).
|
||||||
|
static struct { bool on; ImVec2 a, b; float alpha; } g_cursor;
|
||||||
|
// Room left on each side of a row for its cursor, which is drawn outside the row's box.
|
||||||
|
static float row_margin(void) { return ceilf(skin_cursor_reach(g_scale) * 0.85f); }
|
||||||
|
|
||||||
|
// The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown (of the
|
||||||
|
// page g_page: another page starts from its first row's, however it was opened).
|
||||||
struct Desc { char text[UI_DESC_BYTES]; };
|
struct Desc { char text[UI_DESC_BYTES]; };
|
||||||
static Desc g_hover, g_focus, g_first, g_shown;
|
static Desc g_hover, g_focus, g_first, g_shown;
|
||||||
|
static ImGuiID g_page;
|
||||||
|
|
||||||
// disabled: the note of a row opt_disable_next greyed out, else NULL.
|
// disabled: the note of a row opt_disable_next greyed out, else NULL.
|
||||||
static void desc_set(Desc &d, const char *desc, const char *key, const CfgMeta *m, const char *disabled) {
|
static void desc_set(Desc &d, const char *desc, const char *key, const CfgMeta *m, const char *disabled) {
|
||||||
@@ -72,14 +79,30 @@ void opt_begin(const char *id, float scale) {
|
|||||||
g_focus_req = false;
|
g_focus_req = false;
|
||||||
if (g_take_first) ImGui::NavMoveRequestCancel(); // this frame's move goes to the first row instead
|
if (g_take_first) ImGui::NavMoveRequestCancel(); // this frame's move goes to the first row instead
|
||||||
g_hover.text[0] = g_focus.text[0] = g_first.text[0] = 0;
|
g_hover.text[0] = g_focus.text[0] = g_first.text[0] = 0;
|
||||||
|
if (ImGuiID page = ImGui::GetID(id); page != g_page) g_page = page, g_shown.text[0] = 0;
|
||||||
ImVec2 avail = ImGui::GetContentRegionAvail();
|
ImVec2 avail = ImGui::GetContentRegionAvail();
|
||||||
avail.y -= g_bottom;
|
avail.y -= g_bottom;
|
||||||
ImGui::PushID(id);
|
ImGui::PushID(id);
|
||||||
ImGui::BeginChild("##rows", ImVec2(avail.x * 0.58f, avail.y), ImGuiChildFlags_NavFlattened);
|
ImGui::BeginChild("##rows", ImVec2(avail.x * 0.58f, avail.y), ImGuiChildFlags_NavFlattened);
|
||||||
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 5 * scale));
|
// the rows sit far enough apart that the selected row's cursor frame clears its neighbours' boxes
|
||||||
|
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 9 * scale));
|
||||||
|
ImGui::Dummy(ImVec2(0, row_margin())); // and the first row's cursor stays inside the pane
|
||||||
|
g_cursor.on = false;
|
||||||
|
// three layers: the cursor's glow under the rows, the rows, the cursor's frame over them (opt_end draws the cursor)
|
||||||
|
ImGui::GetWindowDrawList()->ChannelsSplit(3);
|
||||||
|
ImGui::GetWindowDrawList()->ChannelsSetCurrent(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
void opt_end(void) {
|
void opt_end(void) {
|
||||||
|
ImGui::Dummy(ImVec2(0, row_margin())); // the last row's cursor stays inside the pane
|
||||||
|
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||||
|
if (g_cursor.on) {
|
||||||
|
dl->ChannelsSetCurrent(0);
|
||||||
|
skin_cursor_glow(dl, g_cursor.a, g_cursor.b, g_scale, g_cursor.alpha);
|
||||||
|
dl->ChannelsSetCurrent(2);
|
||||||
|
skin_cursor_frame(dl, g_cursor.a, g_cursor.b, g_scale, g_cursor.alpha);
|
||||||
|
}
|
||||||
|
dl->ChannelsMerge();
|
||||||
ImGui::PopStyleVar();
|
ImGui::PopStyleVar();
|
||||||
ImGui::EndChild();
|
ImGui::EndChild();
|
||||||
// the hovered row (mouse) wins, else the selected one (controller), else the last shown, else the first row
|
// the hovered row (mouse) wins, else the selected one (controller), else the last shown, else the first row
|
||||||
@@ -90,10 +113,10 @@ void opt_end(void) {
|
|||||||
ImVec2 p = ImGui::GetCursorScreenPos(), avail = ImGui::GetContentRegionAvail();
|
ImVec2 p = ImGui::GetCursorScreenPos(), avail = ImGui::GetContentRegionAvail();
|
||||||
avail.y -= g_bottom;
|
avail.y -= g_bottom;
|
||||||
float gap = 24 * g_scale;
|
float gap = 24 * g_scale;
|
||||||
ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + gap * 0.5f, p.y), ImVec2(p.x + gap * 0.5f, p.y + avail.y),
|
// the description on a dark panel framed like the rows' buttons
|
||||||
IM_COL32(236, 194, 84, 110), 1.0f);
|
skin_panel(ImGui::GetWindowDrawList(), ImVec2(p.x + gap * 0.5f, p.y), ImVec2(p.x + avail.x, p.y + avail.y), g_scale);
|
||||||
ImGui::SetCursorScreenPos(ImVec2(p.x + gap, p.y));
|
ImGui::SetCursorScreenPos(ImVec2(p.x + gap, p.y));
|
||||||
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(14 * g_scale, 6 * g_scale));
|
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(22 * g_scale, 20 * g_scale));
|
||||||
ImGui::BeginChild("##desc", ImVec2(0, avail.y), ImGuiChildFlags_AlwaysUseWindowPadding, ImGuiWindowFlags_NoNav);
|
ImGui::BeginChild("##desc", ImVec2(0, avail.y), ImGuiChildFlags_AlwaysUseWindowPadding, ImGuiWindowFlags_NoNav);
|
||||||
ImGui::PopStyleVar();
|
ImGui::PopStyleVar();
|
||||||
ImGui::PushTextWrapPos(0);
|
ImGui::PushTextWrapPos(0);
|
||||||
@@ -120,10 +143,15 @@ static int row_text(const char *key, const char *label, const char *desc, const
|
|||||||
g_disable_next = false;
|
g_disable_next = false;
|
||||||
bool off = disabled || cfg_from_env(key) != 0;
|
bool off = disabled || cfg_from_env(key) != 0;
|
||||||
ImGui::PushID(key);
|
ImGui::PushID(key);
|
||||||
|
// the row's box, inset from the pane's sides by the room its cursor needs
|
||||||
|
const float margin = row_margin();
|
||||||
|
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + margin);
|
||||||
ImVec2 p = ImGui::GetCursorScreenPos();
|
ImVec2 p = ImGui::GetCursorScreenPos();
|
||||||
// h whole pixels: ImGui truncates cursor positions, which rounds a fractional height the other way above the window's
|
// h whole pixels: ImGui truncates cursor positions, which rounds a fractional height the other way above the window's
|
||||||
// top (negative y), so the page grew a pixel per row scrolled out and a row scrolled to the bottom was cut off
|
// top (negative y), so the page grew a pixel per row scrolled out and a row scrolled to the bottom was cut off
|
||||||
float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x, h = floorf(fs * 2.2f);
|
// at least a pixel wide: InvisibleButton asserts on a zero size (a narrow window), and ImGui reads a negative one as
|
||||||
|
// "up to that far before the right edge", away from the box drawn
|
||||||
|
float fs = ImGui::GetFontSize(), w = fmaxf(ImGui::GetContentRegionAvail().x - margin, 1.0f), h = floorf(fs * 2.2f);
|
||||||
ImGui::PushStyleColor(ImGuiCol_NavCursor, ImVec4(0, 0, 0, 0)); // the row's own border shows the selection
|
ImGui::PushStyleColor(ImGuiCol_NavCursor, ImVec4(0, 0, 0, 0)); // the row's own border shows the selection
|
||||||
bool clicked = ImGui::InvisibleButton("##row", ImVec2(w, h), ImGuiButtonFlags_EnableNav);
|
bool clicked = ImGui::InvisibleButton("##row", ImVec2(w, h), ImGuiButtonFlags_EnableNav);
|
||||||
ImGui::PopStyleColor();
|
ImGui::PopStyleColor();
|
||||||
@@ -138,6 +166,8 @@ static int row_text(const char *key, const char *label, const char *desc, const
|
|||||||
}
|
}
|
||||||
bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible;
|
bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible;
|
||||||
int step = clicked && !off ? 2 : 0;
|
int step = clicked && !off ? 2 : 0;
|
||||||
|
// a click of the mouse, not A / Enter / Space: only a click picks an arrow by where the pointer is
|
||||||
|
const bool by_mouse = clicked && hov && ImGui::IsMouseReleased(ImGuiMouseButton_Left);
|
||||||
g_held = false;
|
g_held = false;
|
||||||
if (foc && !off) {
|
if (foc && !off) {
|
||||||
// the left stick arrives as the D-pad (menu.cpp pad_events)
|
// the left stick arrives as the D-pad (menu.cpp pad_events)
|
||||||
@@ -164,32 +194,31 @@ static int row_text(const char *key, const char *label, const char *desc, const
|
|||||||
|
|
||||||
ImDrawList *dl = ImGui::GetWindowDrawList();
|
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||||
ImFont *font = ImGui::GetFont();
|
ImFont *font = ImGui::GetFont();
|
||||||
float r = 9 * g_scale, pad = 16 * g_scale, small = fs * 0.72f;
|
float pad = 20 * g_scale, small = fs * 0.72f;
|
||||||
dl->AddRectFilled(p, ImVec2(p.x + w, p.y + h), hov || foc ? IM_COL32(255, 230, 170, 18) : IM_COL32(0, 0, 0, 46), r);
|
// the save menu's brown button, brighter while selected or hovered; the white cursor goes round it in opt_end
|
||||||
// the selected row in the game's own cursor (glow, then its line; ui/menu_art.cpp), else a gold border
|
skin_button(dl, p, ImVec2(p.x + w, p.y + h), g_scale, foc ? 1.0f : hov ? 0.6f : 0.0f, off);
|
||||||
bool art = false;
|
if (foc || (hov && !g_cursor.on)) {
|
||||||
if (hov || foc) { // a halo around the row (the glow's middle left out, so the label stays readable), then the line
|
g_cursor.on = true, g_cursor.a = p, g_cursor.b = ImVec2(p.x + w, p.y + h);
|
||||||
float gx = h * 0.22f, gy = h * 0.16f;
|
g_cursor.alpha = (foc ? 1.0f : 0.55f) * (off ? 0.5f : 1.0f);
|
||||||
art = menu_art_draw9(dl, MENU_ART_CURSOR_GLOW, ImVec2(p.x - gx, p.y - gy), ImVec2(p.x + w + gx, p.y + h + gy), h * 0.5f, 0.3f,
|
|
||||||
off ? IM_COL32(236, 194, 84, 50) : IM_COL32(244, 200, 96, 120), 0) &&
|
|
||||||
menu_art_draw9(dl, MENU_ART_CURSOR_LINE, ImVec2(p.x - gx * 0.3f, p.y - gy * 0.3f),
|
|
||||||
ImVec2(p.x + w + gx * 0.3f, p.y + h + gy * 0.3f), h * 0.12f, 0.1f,
|
|
||||||
off ? IM_COL32(255, 236, 190, 80) : IM_COL32(255, 236, 180, 150), 0); // edges only: the art is a filled bar
|
|
||||||
}
|
}
|
||||||
if (!art)
|
|
||||||
dl->AddRect(p, ImVec2(p.x + w, p.y + h),
|
|
||||||
hov || foc ? (off ? IM_COL32(236, 194, 84, 120) : kGold) : IM_COL32(255, 236, 200, off ? 16 : 34), r, 0,
|
|
||||||
hov || foc ? 2.0f : 1.0f);
|
|
||||||
float ty = p.y + fs * 0.25f, ny = p.y + fs * 1.3f; // the label line and the note line under it
|
float ty = p.y + fs * 0.25f, ny = p.y + fs * 1.3f; // the label line and the note line under it
|
||||||
float right = p.x + w - pad; // the value's right edge
|
float right = p.x + w - pad; // the value's right edge
|
||||||
float value_left = right;
|
float value_left = right;
|
||||||
|
// The value and its note take at most 60 % of the row: a longer value (a graphics card's full name) is drawn smaller,
|
||||||
|
// down to 75 % of the font size, then clipped, so the label keeps room and nothing reaches past the box.
|
||||||
|
const float cap = fmaxf((w - pad * 2) * 0.6f, 0.0f);
|
||||||
|
float vfs = fs, tv = v.value[0] ? font->CalcTextSizeA(fs, FLT_MAX, 0, v.value).x : 0;
|
||||||
|
if (tv > cap) {
|
||||||
|
vfs = fmaxf(fs * cap / tv, fs * 0.75f);
|
||||||
|
tv = fminf(font->CalcTextSizeA(vfs, FLT_MAX, 0, v.value).x, cap);
|
||||||
|
}
|
||||||
if (v.arrows && v.value[0]) { // < value >, drawn (the font has no arrow glyphs); a click on one steps
|
if (v.arrows && v.value[0]) { // < value >, drawn (the font has no arrow glyphs); a click on one steps
|
||||||
float aw = fs * 0.42f, gap = fs * 0.55f, cy = ty + fs * 0.52f;
|
float aw = fs * 0.42f, gap = fs * 0.55f, cy = ty + fs * 0.52f;
|
||||||
float rx = right - aw, lx = rx - gap - ImGui::CalcTextSize(v.value).x - gap - aw;
|
float rx = right - aw, lx = rx - gap - tv - gap - aw;
|
||||||
ImU32 ac = off ? kGrey : hov || foc ? kGold : IM_COL32(170, 170, 160, 255);
|
ImU32 ac = off ? kGrey : hov || foc ? SKIN_TEXT : SKIN_TEXT_DIM;
|
||||||
dl->AddTriangleFilled(ImVec2(lx, cy), ImVec2(lx + aw, cy - aw * 0.75f), ImVec2(lx + aw, cy + aw * 0.75f), ac);
|
dl->AddTriangleFilled(ImVec2(lx, cy), ImVec2(lx + aw, cy - aw * 0.75f), ImVec2(lx + aw, cy + aw * 0.75f), ac);
|
||||||
dl->AddTriangleFilled(ImVec2(rx + aw, cy), ImVec2(rx, cy - aw * 0.75f), ImVec2(rx, cy + aw * 0.75f), ac);
|
dl->AddTriangleFilled(ImVec2(rx + aw, cy), ImVec2(rx, cy - aw * 0.75f), ImVec2(rx, cy + aw * 0.75f), ac);
|
||||||
if (clicked && !off) {
|
if (by_mouse && !off) {
|
||||||
float mx = ImGui::GetIO().MousePos.x;
|
float mx = ImGui::GetIO().MousePos.x;
|
||||||
if (mx >= lx - gap && mx <= lx + aw + gap) step = -1;
|
if (mx >= lx - gap && mx <= lx + aw + gap) step = -1;
|
||||||
else if (mx >= rx - gap && mx <= rx + aw + gap) step = 1;
|
else if (mx >= rx - gap && mx <= rx + aw + gap) step = 1;
|
||||||
@@ -200,36 +229,45 @@ static int row_text(const char *key, const char *label, const char *desc, const
|
|||||||
if (movable) { // up and down arrows left of the value; a click on one moves the row
|
if (movable) { // up and down arrows left of the value; a click on one moves the row
|
||||||
// a fixed value column (On / Off differ in width) keeps the arrows of the rows in one line
|
// a fixed value column (On / Off differ in width) keeps the arrows of the rows in one line
|
||||||
float aw = fs * 0.42f, gap = fs * 0.55f;
|
float aw = fs * 0.42f, gap = fs * 0.55f;
|
||||||
float cx = right - fmaxf(ImGui::CalcTextSize(v.value).x, fs * 2.8f) - gap * 2 - aw;
|
float cx = right - fmaxf(tv, fs * 2.8f) - gap * 2 - aw;
|
||||||
float uy = ty + fs * 0.12f, dy = ty + fs * 0.92f;
|
float uy = ty + fs * 0.12f, dy = ty + fs * 0.92f;
|
||||||
ImU32 ac = off ? kGrey : hov || foc ? kGold : IM_COL32(170, 170, 160, 255);
|
ImU32 ac = off ? kGrey : hov || foc ? SKIN_TEXT : SKIN_TEXT_DIM;
|
||||||
dl->AddTriangleFilled(ImVec2(cx, uy + aw * 0.7f), ImVec2(cx + aw, uy + aw * 0.7f), ImVec2(cx + aw * 0.5f, uy), ac);
|
dl->AddTriangleFilled(ImVec2(cx, uy + aw * 0.7f), ImVec2(cx + aw, uy + aw * 0.7f), ImVec2(cx + aw * 0.5f, uy), ac);
|
||||||
dl->AddTriangleFilled(ImVec2(cx, dy - aw * 0.7f), ImVec2(cx + aw, dy - aw * 0.7f), ImVec2(cx + aw * 0.5f, dy), ac);
|
dl->AddTriangleFilled(ImVec2(cx, dy - aw * 0.7f), ImVec2(cx + aw, dy - aw * 0.7f), ImVec2(cx + aw * 0.5f, dy), ac);
|
||||||
if (clicked && !off) {
|
if (by_mouse && !off) {
|
||||||
ImVec2 mp = ImGui::GetIO().MousePos;
|
ImVec2 mp = ImGui::GetIO().MousePos;
|
||||||
if (mp.x >= cx - gap * 0.5f && mp.x <= cx + aw + gap * 0.5f) step = mp.y < ty + fs * 0.52f ? 3 : 4;
|
if (mp.x >= cx - gap * 0.5f && mp.x <= cx + aw + gap * 0.5f) step = mp.y < ty + fs * 0.52f ? 3 : 4;
|
||||||
}
|
}
|
||||||
value_left = cx - gap;
|
value_left = cx - gap;
|
||||||
}
|
}
|
||||||
if (v.value[0]) {
|
if (v.value[0]) {
|
||||||
float vx = right - ImGui::CalcTextSize(v.value).x;
|
float vx = right - tv;
|
||||||
dl->AddText(ImVec2(vx, ty), off ? kGrey : v.is_default ? IM_COL32(205, 205, 195, 255) : IM_COL32(255, 255, 255, 255),
|
ImVec4 vclip(vx, p.y, right, p.y + h);
|
||||||
v.value);
|
dl->AddText(font, vfs, ImVec2(vx, ty + (fs - vfs) * 0.5f),
|
||||||
|
off ? kGrey : v.is_default ? IM_COL32(232, 222, 198, 255) : IM_COL32(255, 255, 255, 255), v.value, NULL,
|
||||||
|
0, &vclip);
|
||||||
if (!v.arrows && !movable) value_left = vx;
|
if (!v.arrows && !movable) value_left = vx;
|
||||||
}
|
}
|
||||||
if (v.note || v.is_default) { // under the value, right-aligned with it
|
float note_right = p.x + w - pad; // where the label's own note stops: short of the value's note, when there is one
|
||||||
|
if (v.note || v.is_default) { // under the value, right-aligned with it; its start shows when it is too long
|
||||||
const char *t = v.note ? v.note : menu_text(UI_MENU_DEFAULT_MARK);
|
const char *t = v.note ? v.note : menu_text(UI_MENU_DEFAULT_MARK);
|
||||||
float tw = font->CalcTextSizeA(small, FLT_MAX, 0, t).x;
|
float tw = fminf(font->CalcTextSizeA(small, FLT_MAX, 0, t).x, cap);
|
||||||
dl->AddText(font, small, ImVec2(right - tw, ny), v.note ? IM_COL32(220, 170, 100, 255) : kDim, t);
|
ImVec4 nclip(right - tw, p.y, right, p.y + h);
|
||||||
|
dl->AddText(font, small, ImVec2(right - tw, ny), v.note ? IM_COL32(250, 206, 130, 255) : SKIN_TEXT_DIM, t, NULL, 0,
|
||||||
|
&nclip);
|
||||||
|
if (tw > 0) note_right = right - tw - fs * 0.6f;
|
||||||
}
|
}
|
||||||
// the label and its note, clipped before the value
|
// the label and its note, clipped before the value
|
||||||
ImVec4 clip(p.x, p.y, value_left - fs * 0.6f, p.y + h);
|
ImVec4 clip(p.x, p.y, value_left - fs * 0.6f, p.y + h);
|
||||||
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), label, NULL, 0, &clip);
|
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : SKIN_TEXT, label, NULL, 0, &clip);
|
||||||
const char *note = disabled ? disabled
|
const char *note = disabled ? disabled
|
||||||
: off ? menu_text(UI_MENU_SET_BY_ENV)
|
: off ? menu_text(UI_MENU_SET_BY_ENV)
|
||||||
: m && !m->live ? menu_text(UI_MENU_AFTER_RESTART)
|
: m && !m->live ? menu_text(UI_MENU_AFTER_RESTART)
|
||||||
: NULL;
|
: NULL;
|
||||||
if (note) dl->AddText(font, small, ImVec2(p.x + pad, ny), off ? IM_COL32(200, 150, 90, 255) : kDim, note);
|
ImVec4 note_clip(p.x, p.y, note_right, p.y + h);
|
||||||
|
if (note)
|
||||||
|
dl->AddText(font, small, ImVec2(p.x + pad, ny), off ? IM_COL32(200, 150, 90, 255) : SKIN_TEXT_DIM, note, NULL, 0,
|
||||||
|
¬e_clip);
|
||||||
ImGui::PopID();
|
ImGui::PopID();
|
||||||
return off ? 0 : step;
|
return off ? 0 : step;
|
||||||
}
|
}
|
||||||
@@ -283,6 +321,15 @@ bool opt_toggle(const char *key, UiTextId label, UiTextId desc, bool inverted) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool opt_toggle_value(const char *key, UiTextId label, UiTextId desc, const char *on_value, const char *off_value, const char *note) {
|
||||||
|
const CfgMeta *m = cfg_meta(key);
|
||||||
|
bool on = strcmp(cfg_value(key), off_value) != 0, def = m && strcmp(m->def, off_value) != 0;
|
||||||
|
RowView v = {menu_text(on ? UI_MENU_ON : UI_MENU_OFF), on == def, false, note};
|
||||||
|
if (!row(key, label, desc, v)) return false; // any step flips it
|
||||||
|
apply(key, on ? off_value : on_value);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value) {
|
bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value) {
|
||||||
RowView v = {value ? value : "", false, false, NULL};
|
RowView v = {value ? value : "", false, false, NULL};
|
||||||
return row(id, label, desc, v) == 2; // A or a click; left and right do nothing
|
return row(id, label, desc, v) == 2; // A or a click; left and right do nothing
|
||||||
@@ -294,32 +341,44 @@ bool opt_toggle_text(const char *id, const char *label, const char *desc, bool o
|
|||||||
return row_text(id, label, desc, v, false) != 0; // any step flips it
|
return row_text(id, label, desc, v, false) != 0; // any step flips it
|
||||||
}
|
}
|
||||||
|
|
||||||
void opt_group_text(const char *title) {
|
// A group heading: the game's divider ornament across the pane, then the title in the accent colour.
|
||||||
ImGui::Dummy(ImVec2(0, 6 * g_scale));
|
static void group_divider(void) {
|
||||||
ImGui::PushTextWrapPos(0);
|
float fh = skin_filigree_height(g_scale);
|
||||||
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", title);
|
ImVec2 p = ImGui::GetCursorScreenPos();
|
||||||
ImGui::PopTextWrapPos();
|
float m = row_margin();
|
||||||
|
skin_filigree(ImGui::GetWindowDrawList(), p.x + m, p.x + ImGui::GetContentRegionAvail().x - m, p.y + fh * 0.5f, g_scale);
|
||||||
|
ImGui::Dummy(ImVec2(0, fh));
|
||||||
|
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + m);
|
||||||
}
|
}
|
||||||
|
|
||||||
void opt_text_str(const char *text, bool warn) {
|
// Text across the rows' column, inset from its sides as the rows' boxes are and wrapped before their right edge. The
|
||||||
ImGui::PushTextWrapPos(0);
|
// cursor already stands at the inset when indented is true (after group_divider).
|
||||||
if (warn) ImGui::TextColored(ImVec4(0.95f, 0.66f, 0.40f, 1), "%s", text);
|
static void column_text(const char *text, const ImVec4 *col, bool indented) {
|
||||||
|
const float m = row_margin();
|
||||||
|
if (!indented) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + m);
|
||||||
|
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + fmaxf(ImGui::GetContentRegionAvail().x - m, 1.0f));
|
||||||
|
if (col) ImGui::TextColored(*col, "%s", text);
|
||||||
else ImGui::TextUnformatted(text);
|
else ImGui::TextUnformatted(text);
|
||||||
ImGui::PopTextWrapPos();
|
ImGui::PopTextWrapPos();
|
||||||
}
|
}
|
||||||
|
|
||||||
void opt_group(UiTextId title) {
|
static const ImVec4 kWarn(0.95f, 0.66f, 0.40f, 1);
|
||||||
ImGui::Dummy(ImVec2(0, 6 * g_scale));
|
|
||||||
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(title));
|
void opt_group_text(const char *title) {
|
||||||
|
group_divider();
|
||||||
|
const ImVec4 gold = ImGui::ColorConvertU32ToFloat4(SKIN_GOLD);
|
||||||
|
column_text(title, &gold, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
void opt_text(UiTextId text, bool warn) {
|
void opt_text_str(const char *text, bool warn) { column_text(text, warn ? &kWarn : nullptr, false); }
|
||||||
ImGui::PushTextWrapPos(0);
|
|
||||||
if (warn) ImGui::TextColored(ImVec4(0.95f, 0.66f, 0.40f, 1), "%s", menu_text(text));
|
void opt_group(UiTextId title) {
|
||||||
else ImGui::TextUnformatted(menu_text(text));
|
group_divider();
|
||||||
ImGui::PopTextWrapPos();
|
ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(SKIN_GOLD), "%s", menu_text(title));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void opt_text(UiTextId text, bool warn) { column_text(menu_text(text), warn ? &kWarn : nullptr, false); }
|
||||||
|
|
||||||
bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n,
|
bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n,
|
||||||
UiTextId desc, int cur, const char *note) {
|
UiTextId desc, int cur, const char *note) {
|
||||||
const char *d = cfg_default(key);
|
const char *d = cfg_default(key);
|
||||||
@@ -428,20 +487,22 @@ static void fit_text(ImDrawList *dl, float x0, float x1, float y, float h, ImU32
|
|||||||
// The label column and the three cells of a binding row of width w.
|
// The label column and the three cells of a binding row of width w.
|
||||||
static void bind_columns(float x, float w, float cx[3], float *cw) {
|
static void bind_columns(float x, float w, float cx[3], float *cw) {
|
||||||
float lw = floorf(w * 0.34f), gap = floorf(8 * g_scale);
|
float lw = floorf(w * 0.34f), gap = floorf(8 * g_scale);
|
||||||
*cw = floorf((w - lw - gap * 3) / 3);
|
*cw = fmaxf(floorf((w - lw - gap * 3) / 3), 1.0f); // a pixel at least: InvisibleButton asserts on a zero width
|
||||||
for (int c = 0; c < 3; c++) cx[c] = x + lw + gap + c * (*cw + gap);
|
for (int c = 0; c < 3; c++) cx[c] = x + lw + gap + c * (*cw + gap);
|
||||||
}
|
}
|
||||||
|
|
||||||
void opt_bind_header(UiTextId c0, UiTextId c1, UiTextId c2) {
|
void opt_bind_header(UiTextId c0, UiTextId c1, UiTextId c2) {
|
||||||
|
// over the cells of the binding rows: the same inset (opt_bind_row) and the same columns
|
||||||
|
const float margin = row_margin();
|
||||||
ImVec2 p = ImGui::GetCursorScreenPos();
|
ImVec2 p = ImGui::GetCursorScreenPos();
|
||||||
float w = ImGui::GetContentRegionAvail().x, cx[3], cw, fs = ImGui::GetFontSize() * 0.8f;
|
float w = fmaxf(ImGui::GetContentRegionAvail().x - margin * 2, 1.0f), cx[3], cw, fs = ImGui::GetFontSize() * 0.8f;
|
||||||
bind_columns(p.x, w, cx, &cw);
|
bind_columns(p.x + margin, w, cx, &cw);
|
||||||
const UiTextId cols[3] = {c0, c1, c2};
|
const UiTextId cols[3] = {c0, c1, c2};
|
||||||
ImFont *font = ImGui::GetFont();
|
ImFont *font = ImGui::GetFont();
|
||||||
for (int c = 0; c < 3; c++) {
|
for (int c = 0; c < 3; c++) {
|
||||||
const char *t = menu_text(cols[c]);
|
const char *t = menu_text(cols[c]);
|
||||||
float tw = font->CalcTextSizeA(fs, FLT_MAX, 0, t).x;
|
float tw = font->CalcTextSizeA(fs, FLT_MAX, 0, t).x;
|
||||||
ImGui::GetWindowDrawList()->AddText(font, fs, ImVec2(cx[c] + (cw - tw) * 0.5f, p.y), kDim, t);
|
ImGui::GetWindowDrawList()->AddText(font, fs, ImVec2(cx[c] + (cw - tw) * 0.5f, p.y), SKIN_TEXT_DIM, t);
|
||||||
}
|
}
|
||||||
ImGui::Dummy(ImVec2(w, fs * 1.2f));
|
ImGui::Dummy(ImVec2(w, fs * 1.2f));
|
||||||
}
|
}
|
||||||
@@ -449,11 +510,13 @@ void opt_bind_header(UiTextId c0, UiTextId c1, UiTextId c2) {
|
|||||||
int opt_bind_row(const char *key, const char *label, UiTextId desc, const char *const cells[3], const bool enabled[3],
|
int opt_bind_row(const char *key, const char *label, UiTextId desc, const char *const cells[3], const bool enabled[3],
|
||||||
const char *note) {
|
const char *note) {
|
||||||
ImGui::PushID(key);
|
ImGui::PushID(key);
|
||||||
|
const float margin = row_margin(); // room for the cursor, as the option rows leave
|
||||||
|
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + margin);
|
||||||
ImVec2 p = ImGui::GetCursorScreenPos();
|
ImVec2 p = ImGui::GetCursorScreenPos();
|
||||||
float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x, h = floorf(fs * 1.9f), cx[3], cw;
|
float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x - margin, h = floorf(fs * 1.9f), cx[3], cw;
|
||||||
bind_columns(p.x, w, cx, &cw);
|
bind_columns(p.x, w, cx, &cw);
|
||||||
ImDrawList *dl = ImGui::GetWindowDrawList();
|
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||||
float r = 8 * g_scale, pad = 6 * g_scale;
|
float pad = 6 * g_scale;
|
||||||
fit_text(dl, p.x + 16 * g_scale, cx[0] - fs * 0.3f, p.y, h, IM_COL32(240, 236, 224, 255), label, false);
|
fit_text(dl, p.x + 16 * g_scale, cx[0] - fs * 0.3f, p.y, h, IM_COL32(240, 236, 224, 255), label, false);
|
||||||
int result = -1;
|
int result = -1;
|
||||||
bool row_foc = false, row_hov = false;
|
bool row_foc = false, row_hov = false;
|
||||||
@@ -461,7 +524,7 @@ int opt_bind_row(const char *key, const char *label, UiTextId desc, const char *
|
|||||||
ImVec2 a(cx[c], p.y), b(cx[c] + cw, p.y + h);
|
ImVec2 a(cx[c], p.y), b(cx[c] + cw, p.y + h);
|
||||||
const char *t = cells[c] && cells[c][0] ? cells[c] : "-";
|
const char *t = cells[c] && cells[c][0] ? cells[c] : "-";
|
||||||
if (!enabled[c]) { // not a nav item: the cursor skips it
|
if (!enabled[c]) { // not a nav item: the cursor skips it
|
||||||
dl->AddRect(a, b, IM_COL32(255, 255, 255, 14), r);
|
skin_button(dl, a, b, g_scale, 0, true);
|
||||||
fit_text(dl, a.x + pad, b.x - pad, a.y, h, kGrey, t, true);
|
fit_text(dl, a.x + pad, b.x - pad, a.y, h, kGrey, t, true);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -488,9 +551,9 @@ int opt_bind_row(const char *key, const char *label, UiTextId desc, const char *
|
|||||||
if (foc && (ImGui::IsKeyPressed(ImGuiKey_Delete, false) || ImGui::IsKeyPressed(ImGuiKey_Backspace, false) ||
|
if (foc && (ImGui::IsKeyPressed(ImGuiKey_Delete, false) || ImGui::IsKeyPressed(ImGuiKey_Backspace, false) ||
|
||||||
ImGui::IsKeyPressed(ImGuiKey_GamepadFaceUp, false)))
|
ImGui::IsKeyPressed(ImGuiKey_GamepadFaceUp, false)))
|
||||||
result = 10 + c;
|
result = 10 + c;
|
||||||
dl->AddRectFilled(a, b, hov || foc ? IM_COL32(255, 255, 255, 22) : IM_COL32(0, 0, 0, 40), r);
|
skin_button(dl, a, b, g_scale, foc ? 1.0f : hov ? 0.6f : 0.0f, false); // a small brown button per cell
|
||||||
dl->AddRect(a, b, hov || foc ? kGold : IM_COL32(255, 255, 255, 38), r, 0, hov || foc ? 2.0f : 1.0f);
|
if (foc || (hov && !g_cursor.on)) g_cursor.on = true, g_cursor.a = a, g_cursor.b = b, g_cursor.alpha = foc ? 1.0f : 0.55f;
|
||||||
fit_text(dl, a.x + pad, b.x - pad, a.y, h, IM_COL32(255, 255, 255, 255), t, true);
|
fit_text(dl, a.x + pad, b.x - pad, a.y, h, SKIN_TEXT, t, true);
|
||||||
ImGui::PopID();
|
ImGui::PopID();
|
||||||
}
|
}
|
||||||
char k[64];
|
char k[64];
|
||||||
|
|||||||
@@ -36,6 +36,10 @@ void opt_text(UiTextId text, bool warn = false);
|
|||||||
// The return value of every row: true when it changed the setting this frame.
|
// The return value of every row: true when it changed the setting this frame.
|
||||||
// inverted: the row shows "on" while the key is 0 (a setting whose key names the opposite).
|
// inverted: the row shows "on" while the key is 0 (a setting whose key names the opposite).
|
||||||
bool opt_toggle(const char *key, UiTextId label, UiTextId desc, bool inverted = false);
|
bool opt_toggle(const char *key, UiTextId label, UiTextId desc, bool inverted = false);
|
||||||
|
// An on/off row over a key with named values: off while the key holds off_value and on for any other, so a value the
|
||||||
|
// row does not write itself still reads as on. Flipping it writes on_value or off_value. note: as for opt_choice.
|
||||||
|
bool opt_toggle_value(const char *key, UiTextId label, UiTextId desc, const char *on_value, const char *off_value,
|
||||||
|
const char *note = nullptr);
|
||||||
// One name per value of the key's cfg_meta values list, in its order. When the key has no fixed default (an empty
|
// One name per value of the key's cfg_meta values list, in its order. When the key has no fixed default (an empty
|
||||||
// def), names[0] is the automatic choice (the key unset) and names[1..] follow the values. note: a short line under
|
// def), names[0] is the automatic choice (the key unset) and names[1..] follow the values. note: a short line under
|
||||||
// the value in place of the "default" mark (NULL: none).
|
// the value in place of the "default" mark (NULL: none).
|
||||||
|
|||||||
221
runtime/ui/perf_panel.cpp
Normal file
221
runtime/ui/perf_panel.cpp
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
// The full performance overlay's panel (ui/perf_panel.h) in the settings menu's look: the menu's framed dark panel
|
||||||
|
// (ui/menu_skin.cpp), the numbers in tables with gold labels and parchment values, the game's divider between the
|
||||||
|
// machine, the frames, the per-frame waits and the picture, and the frame times as a gold line.
|
||||||
|
#include <float.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include "imgui.h"
|
||||||
|
#include "imgui_internal.h" // the window's draw cursor (the plot does not widen the panel)
|
||||||
|
|
||||||
|
#include "ui/menu_skin.h"
|
||||||
|
#include "ui/perf_panel.h"
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include "ui_text.h"
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
const ImVec4 kLabel(236 / 255.0f, 196 / 255.0f, 104 / 255.0f, 1); // SKIN_GOLD
|
||||||
|
const ImVec4 kValue(244 / 255.0f, 236 / 255.0f, 214 / 255.0f, 1); // SKIN_TEXT
|
||||||
|
const ImVec4 kDimText(170 / 255.0f, 152 / 255.0f, 120 / 255.0f, 1);
|
||||||
|
|
||||||
|
struct PerfCol { UiTextId fmt; float sample; };
|
||||||
|
|
||||||
|
float text_w(UiTextId fmt, float v) {
|
||||||
|
char b[64];
|
||||||
|
snprintf(b, sizeof b, menu_text(fmt), v);
|
||||||
|
return ImGui::CalcTextSize(b).x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The panel keeps its width while the numbers change: every column is as wide as the widest text it can show, measured
|
||||||
|
// on samples of 8s (the menu fonts' digits share one width), and the numbers are right-aligned in it.
|
||||||
|
// A fixed column as wide as the widest of the formats (with their samples) and labels given.
|
||||||
|
void column(const char *id, const PerfCol *cols, int n, const UiTextId *labels = nullptr, int nl = 0) {
|
||||||
|
float w = ImGui::CalcTextSize(menu_text(UI_MENU_OV_NONE)).x;
|
||||||
|
for (int i = 0; i < n; i++) w = fmaxf(w, text_w(cols[i].fmt, cols[i].sample));
|
||||||
|
for (int i = 0; i < nl; i++) w = fmaxf(w, ImGui::CalcTextSize(menu_text(labels[i])).x);
|
||||||
|
ImGui::TableSetupColumn(id, ImGuiTableColumnFlags_WidthFixed, w);
|
||||||
|
}
|
||||||
|
|
||||||
|
void right(const char *s, bool dim) {
|
||||||
|
float pad = ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(s).x;
|
||||||
|
if (pad > 0) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + pad);
|
||||||
|
ImGui::TextColored(dim ? kDimText : kValue, "%s", s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// One cell: fmt (a catalog format, one number) with v, or "-" when the machine gives none.
|
||||||
|
void cell(UiTextId fmt, float v) {
|
||||||
|
ImGui::TableNextColumn();
|
||||||
|
if (v < 0) return right(menu_text(UI_MENU_OV_NONE), true);
|
||||||
|
char b[64];
|
||||||
|
snprintf(b, sizeof b, menu_text(fmt), v);
|
||||||
|
right(b, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
void label(UiTextId id) {
|
||||||
|
ImGui::TableNextColumn();
|
||||||
|
ImGui::TextColored(kLabel, "%s", menu_text(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
float gb(float mb) { return mb < 0 ? -1 : mb / 1024; }
|
||||||
|
|
||||||
|
// The game's divider across the panel between two sections, smaller than the menu's.
|
||||||
|
void divider(float scale) {
|
||||||
|
float s = scale * 0.72f, h = skin_filigree_height(s);
|
||||||
|
ImVec2 p = ImGui::GetCursorScreenPos();
|
||||||
|
ImGuiWindow *win = ImGui::GetCurrentWindow();
|
||||||
|
float x1 = win->WorkRect.Max.x > p.x + 40 * s ? win->WorkRect.Max.x : p.x + 200 * s;
|
||||||
|
skin_filigree(ImGui::GetWindowDrawList(), p.x - 4 * s, x1 + 4 * s, p.y + h * 0.5f, s);
|
||||||
|
ImGui::Dummy(ImVec2(0, h));
|
||||||
|
}
|
||||||
|
|
||||||
|
void machine_and_frames(const PerfPanel *p, float scale) {
|
||||||
|
const PerfStats &s = p->s;
|
||||||
|
if (!ImGui::BeginTable("##perft", 4, ImGuiTableFlags_SizingFixedFit)) return;
|
||||||
|
static const UiTextId labels[] = {UI_MENU_OV_GPU, UI_MENU_OV_VRAM, UI_MENU_OV_CPU, UI_MENU_OV_RAM,
|
||||||
|
UI_MENU_OV_FPS_LABEL, UI_MENU_OV_FRAME_LABEL};
|
||||||
|
static const PerfCol c1[] = {{UI_MENU_OV_FMT_PCT, 100}, {UI_MENU_OV_FMT_GB, 888.8f}, {UI_MENU_OV_FMT_FPS, 888},
|
||||||
|
{UI_MENU_OV_FRAME_MS, 888.8f}};
|
||||||
|
static const PerfCol c2[] = {{UI_MENU_OV_FMT_TEMP, 188}, {UI_MENU_OV_FMT_GB_OF, 888.8f}, {UI_MENU_OV_LOW1, 888},
|
||||||
|
{UI_MENU_OV_MAX_MS, 8888.8f}};
|
||||||
|
static const PerfCol c3[] = {{UI_MENU_OV_FMT_POWER, 888}, {UI_MENU_OV_FMT_MHZ, 8888}, {UI_MENU_OV_GAME_PCT, 100},
|
||||||
|
{UI_MENU_OV_GAME_GB, 888.8f}, {UI_MENU_OV_LOW01, 888}};
|
||||||
|
column("##c0", nullptr, 0, labels, 6);
|
||||||
|
column("##c1", c1, 4);
|
||||||
|
column("##c2", c2, 4);
|
||||||
|
column("##c3", c3, 5);
|
||||||
|
label(UI_MENU_OV_GPU);
|
||||||
|
cell(UI_MENU_OV_FMT_PCT, s.gpu_pct);
|
||||||
|
cell(UI_MENU_OV_FMT_TEMP, s.gpu_temp_c);
|
||||||
|
cell(UI_MENU_OV_FMT_POWER, s.gpu_power_w);
|
||||||
|
label(UI_MENU_OV_VRAM);
|
||||||
|
cell(UI_MENU_OV_FMT_GB, gb(s.vram_used_mb));
|
||||||
|
cell(UI_MENU_OV_FMT_GB_OF, gb(s.vram_total_mb));
|
||||||
|
cell(UI_MENU_OV_FMT_MHZ, s.gpu_clock_mhz);
|
||||||
|
label(UI_MENU_OV_CPU);
|
||||||
|
cell(UI_MENU_OV_FMT_PCT, s.cpu_total_pct);
|
||||||
|
cell(UI_MENU_OV_FMT_TEMP, s.cpu_temp_c);
|
||||||
|
cell(UI_MENU_OV_GAME_PCT, s.cpu_game_pct);
|
||||||
|
label(UI_MENU_OV_RAM);
|
||||||
|
cell(UI_MENU_OV_FMT_GB, gb(s.ram_used_mb));
|
||||||
|
cell(UI_MENU_OV_FMT_GB_OF, gb(s.ram_total_mb));
|
||||||
|
cell(UI_MENU_OV_GAME_GB, gb(s.ram_game_mb));
|
||||||
|
ImGui::EndTable();
|
||||||
|
divider(scale);
|
||||||
|
if (!ImGui::BeginTable("##perff", 4, ImGuiTableFlags_SizingFixedFit)) return;
|
||||||
|
column("##f0", nullptr, 0, labels, 6);
|
||||||
|
column("##f1", c1, 4);
|
||||||
|
column("##f2", c2, 4);
|
||||||
|
column("##f3", c3, 5);
|
||||||
|
// the frames: the rate over the last second with the lows over the last ten seconds, then the frame times
|
||||||
|
label(UI_MENU_OV_FPS_LABEL);
|
||||||
|
cell(UI_MENU_OV_FMT_FPS, s.fps);
|
||||||
|
cell(UI_MENU_OV_LOW1, s.low1_fps);
|
||||||
|
cell(UI_MENU_OV_LOW01, s.low01_fps);
|
||||||
|
if (p->fg_fps > 0) { // frame generation: what the display gets, generated frames included
|
||||||
|
label(UI_MENU_OV_FG_LABEL);
|
||||||
|
cell(UI_MENU_OV_FMT_FPS, p->fg_fps);
|
||||||
|
ImGui::TableNextColumn();
|
||||||
|
ImGui::TableNextColumn();
|
||||||
|
}
|
||||||
|
label(UI_MENU_OV_FRAME_LABEL);
|
||||||
|
cell(UI_MENU_OV_FRAME_MS, s.frame_ms_avg);
|
||||||
|
cell(UI_MENU_OV_MAX_MS, s.frame_ms_max);
|
||||||
|
ImGui::TableNextColumn();
|
||||||
|
ImGui::EndTable();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The frame times of the last PERF_HISTORY frames as a gold line over a dark band, as wide as the tables made the panel
|
||||||
|
// (the plot does not count toward that width, so the panel can still shrink).
|
||||||
|
void frame_plot(const PerfStats &s, float scale) {
|
||||||
|
float top = s.frame_ms_max > 50 ? s.frame_ms_max : 50;
|
||||||
|
ImGuiWindow *win = ImGui::GetCurrentWindow();
|
||||||
|
float max_x = win->DC.CursorMaxPos.x;
|
||||||
|
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0.32f));
|
||||||
|
ImGui::PushStyleColor(ImGuiCol_PlotLines, kLabel);
|
||||||
|
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);
|
||||||
|
ImGui::PlotLines("##ft", s.frame_ms, PERF_HISTORY, 0, nullptr, 0, top, ImVec2(-FLT_MIN, 48 * scale));
|
||||||
|
ImGui::PopStyleVar();
|
||||||
|
ImGui::PopStyleColor(2);
|
||||||
|
win->DC.CursorMaxPos.x = max_x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per frame, averaged over the last half second; the labels' column stretches, so the numbers end at the panel's right
|
||||||
|
// edge, and the table still asks for no more than its widest label and number.
|
||||||
|
void waits(const PerfStats &s) {
|
||||||
|
if (!ImGui::BeginTable("##perfw", 2, ImGuiTableFlags_SizingFixedFit)) return;
|
||||||
|
static const PerfCol c1[] = {{UI_MENU_OV_FMT_MS, 888.88f}, {UI_MENU_OV_PER_FRAME, 888.8f}};
|
||||||
|
ImGui::TableSetupColumn("##w0", ImGuiTableColumnFlags_WidthStretch);
|
||||||
|
column("##w1", c1, 2);
|
||||||
|
label(UI_MENU_OV_REPLAY);
|
||||||
|
cell(UI_MENU_OV_FMT_MS, s.replay_ms);
|
||||||
|
label(UI_MENU_OV_GPU_TIME);
|
||||||
|
cell(UI_MENU_OV_FMT_MS, s.gpu_ms);
|
||||||
|
label(UI_MENU_OV_PIPE_WAIT);
|
||||||
|
cell(UI_MENU_OV_FMT_MS, s.pipe_wait_ms);
|
||||||
|
label(UI_MENU_OV_SHADER_WAIT);
|
||||||
|
cell(UI_MENU_OV_FMT_MS, s.xlate_ms);
|
||||||
|
label(UI_MENU_OV_TEX_UPLOADS);
|
||||||
|
cell(UI_MENU_OV_PER_FRAME, s.tex_uploads);
|
||||||
|
ImGui::EndTable();
|
||||||
|
}
|
||||||
|
|
||||||
|
void picture(const PerfPanel *p) {
|
||||||
|
static const UiTextId labels[6] = {UI_MENU_OV_WINDOW, UI_MENU_OV_OUTPUT, UI_MENU_OV_SCENE,
|
||||||
|
UI_MENU_OV_SCALING, UI_MENU_OV_LIMIT, UI_MENU_OV_PRESENT};
|
||||||
|
if (!ImGui::BeginTable("##perfp", 2, ImGuiTableFlags_SizingFixedFit)) return;
|
||||||
|
float vw = 0;
|
||||||
|
for (const auto &v : p->picture) vw = fmaxf(vw, ImGui::CalcTextSize(v).x);
|
||||||
|
ImGui::TableSetupColumn("##p0", ImGuiTableColumnFlags_WidthStretch);
|
||||||
|
ImGui::TableSetupColumn("##p1", ImGuiTableColumnFlags_WidthFixed, vw);
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
if (i == 2 && !p->scene_known) continue;
|
||||||
|
label(labels[i]);
|
||||||
|
ImGui::TableNextColumn();
|
||||||
|
right(p->picture[i], false);
|
||||||
|
}
|
||||||
|
ImGui::EndTable();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void perf_panel_draw(const PerfPanel *p, float width, float scale) {
|
||||||
|
const float m = 12 * scale;
|
||||||
|
ImGui::SetNextWindowPos(ImVec2(width - m, m), ImGuiCond_Always, ImVec2(1, 0));
|
||||||
|
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, 0)); // the panel below is the background
|
||||||
|
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);
|
||||||
|
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(24 * scale, 20 * scale));
|
||||||
|
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(7 * scale, 1.5f * scale));
|
||||||
|
ImGui::Begin("##perf", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize |
|
||||||
|
ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoNav |
|
||||||
|
ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoSavedSettings);
|
||||||
|
ImGui::PopStyleVar(3);
|
||||||
|
ImGui::PopStyleColor();
|
||||||
|
// under the menu while it is open (the settings stay readable), else over everything
|
||||||
|
if (p->under_menu) ImGui::BringWindowToDisplayBack(ImGui::GetCurrentWindow());
|
||||||
|
else ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindow());
|
||||||
|
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||||
|
dl->ChannelsSplit(2); // the panel goes under the text, drawn once the window's size is known
|
||||||
|
dl->ChannelsSetCurrent(1);
|
||||||
|
ImGui::SetWindowFontScale(0.72f);
|
||||||
|
// the port version and the game update first, so a screenshot in a bug report carries both
|
||||||
|
ImGui::TextColored(kDimText, "%s", p->version);
|
||||||
|
divider(scale);
|
||||||
|
machine_and_frames(p, scale);
|
||||||
|
ImGui::Dummy(ImVec2(0, 4 * scale));
|
||||||
|
frame_plot(p->s, scale);
|
||||||
|
ImGui::Dummy(ImVec2(0, 2 * scale));
|
||||||
|
waits(p->s);
|
||||||
|
divider(scale);
|
||||||
|
picture(p);
|
||||||
|
if (p->s.gpu_name[0] || p->s.cpu_name[0]) divider(scale);
|
||||||
|
if (p->s.gpu_name[0]) ImGui::TextColored(kDimText, "%s", p->s.gpu_name);
|
||||||
|
if (p->s.cpu_name[0]) ImGui::TextColored(kDimText, "%s", p->s.cpu_name);
|
||||||
|
dl->ChannelsSetCurrent(0);
|
||||||
|
ImVec2 a = ImGui::GetWindowPos(), sz = ImGui::GetWindowSize();
|
||||||
|
skin_panel(dl, a, ImVec2(a.x + sz.x, a.y + sz.y), scale * 0.8f, 0.94f);
|
||||||
|
dl->ChannelsMerge();
|
||||||
|
ImGui::End();
|
||||||
|
}
|
||||||
20
runtime/ui/perf_panel.h
Normal file
20
runtime/ui/perf_panel.h
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
// The full performance overlay's panel (ui/perf_panel.cpp), drawn in the settings menu's look: what menu.cpp
|
||||||
|
// perf_full_draw gathered, laid out in tables on the menu's framed panel with the game's divider between the sections.
|
||||||
|
#pragma once
|
||||||
|
#include "imgui.h"
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include "perfmon.h"
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
PerfStats s; // perfmon_snapshot
|
||||||
|
const char *version; // "NX2navi <version>, game <update>"
|
||||||
|
char picture[6][64]; // window, game image, scene, scaling, frame limit, presentation (formatted)
|
||||||
|
bool scene_known; // the scene line is shown (resolution.c sets the scene's size)
|
||||||
|
float fg_fps; // frames the display gets with frame generation, 0 without it
|
||||||
|
bool under_menu; // the menu is open: the panel goes under its window
|
||||||
|
} PerfPanel;
|
||||||
|
|
||||||
|
// The panel at the top right corner of a width-pixel-wide frame.
|
||||||
|
void perf_panel_draw(const PerfPanel *p, float width, float scale);
|
||||||
@@ -48,58 +48,44 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_SAVE_FAILED] = "could not save settings",
|
[UI_MENU_SAVE_FAILED] = "could not save settings",
|
||||||
[UI_MENU_VERSION] = "NX2navi %s, game %s",
|
[UI_MENU_VERSION] = "NX2navi %s, game %s",
|
||||||
|
|
||||||
[UI_MENU_FULLSCREEN] = "Fullscreen", [UI_MENU_FULLSCREEN_DESC] = "Fills the screen with the game; F11 toggles it.",
|
[UI_MENU_FULLSCREEN] = "Fullscreen", [UI_MENU_FULLSCREEN_DESC] = "Play in fullscreen. F11 switches it.",
|
||||||
[UI_MENU_WINDOW_SIZE] = "Window size", [UI_MENU_WINDOW_SIZE_DESC] = "Size of the game window when not fullscreen.",
|
[UI_MENU_WINDOW_SIZE] = "Window size", [UI_MENU_WINDOW_SIZE_DESC] = "Window size outside fullscreen.",
|
||||||
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Custom",
|
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Custom",
|
||||||
[UI_MENU_PRESENT] = "Presentation", [UI_MENU_PRESENT_DESC] = "How finished frames reach the screen.",
|
[UI_MENU_PRESENT_DESC] = "Stops screen tearing. Off lowers input delay slightly.",
|
||||||
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "VSync", [UI_MENU_PRESENT_IMMEDIATE] = "Immediate",
|
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "VSync", [UI_MENU_PRESENT_IMMEDIATE] = "Immediate",
|
||||||
[UI_MENU_PRESENT_IN_USE] = "in use: %s",
|
[UI_MENU_PRESENT_IN_USE] = "in use: %s",
|
||||||
[UI_MENU_GPU] = "Graphics card", [UI_MENU_GPU_DESC] = "The Vulkan device that draws the game.",
|
[UI_MENU_GPU] = "Graphics card", [UI_MENU_GPU_DESC] = "The graphics card that runs the game.",
|
||||||
[UI_MENU_GPU_AUTO] = "Automatic",
|
[UI_MENU_GPU_AUTO] = "Automatic",
|
||||||
[UI_MENU_PERF_OVERLAY] = "Performance overlay",
|
[UI_MENU_PERF_OVERLAY] = "Performance overlay",
|
||||||
[UI_MENU_PERF_OVERLAY_DESC] = "Frame rate in the top right corner. Full adds frame times with a graph, CPU, GPU and "
|
[UI_MENU_PERF_OVERLAY_DESC] = "Shows frame rate and system stats. F10 switches modes.",
|
||||||
"memory load, temperatures and the render thread's waits. F10 cycles the modes.",
|
|
||||||
[UI_MENU_PERF_OFF] = "Off", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Full",
|
[UI_MENU_PERF_OFF] = "Off", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Full",
|
||||||
// printf format of the overlay line in FPS mode: the frame rate
|
// printf format of the overlay line in FPS mode: the frame rate
|
||||||
[UI_PERF_LINE_FPS] = "%.0f fps",
|
[UI_PERF_LINE_FPS] = "%.0f fps",
|
||||||
[UI_MENU_GRAPHICS] = "Picture",
|
[UI_MENU_GRAPHICS] = "Picture",
|
||||||
[UI_MENU_OUTPUT_RES] = "Game resolution",
|
[UI_MENU_OUTPUT_RES] = "Game resolution",
|
||||||
[UI_MENU_OUTPUT_RES_DESC] = "The size the game draws its picture and interface in. Above 1920 x 1080 the game needs "
|
[UI_MENU_OUTPUT_RES_DESC] = "The resolution the game draws at. Higher needs a stronger GPU.",
|
||||||
"more video memory and GPU time. A wider size (21:9) widens the camera's view and moves "
|
|
||||||
"the HUD to the screen's corners; a taller one (16:10, 3:2) moves it to the top "
|
|
||||||
"and bottom edges.",
|
|
||||||
[UI_MENU_RENDER_SCALE] = "3D render scale",
|
[UI_MENU_RENDER_SCALE] = "3D render scale",
|
||||||
[UI_MENU_RENDER_SCALE_DESC] = "Size of the 3D scene relative to the game resolution; the game's FSR scales it to "
|
[UI_MENU_RENDER_SCALE_DESC] = "Size of the 3D scene. Higher is sharper but slower.",
|
||||||
"that size. Above 100 % smooths jagged edges (supersampling) at a high GPU cost.",
|
|
||||||
[UI_MENU_RENDER_SCALE_GAME] = "Game (83 %)",
|
[UI_MENU_RENDER_SCALE_GAME] = "Game (83 %)",
|
||||||
[UI_MENU_UPSCALER] = "Scaling to the window",
|
[UI_MENU_UPSCALER] = "Scaling to the window",
|
||||||
[UI_MENU_UPSCALER_DESC] = "How the game's picture is fitted to the window. Larger window: FSR keeps edges and detail "
|
[UI_MENU_UPSCALER_DESC] = "How the game's picture is fitted to the window. Larger window: FSR keeps edges and detail "
|
||||||
"sharper than bilinear. Smaller window (Ocarina draws 2560 x 1440): the picture is shrunk "
|
"sharper than bilinear. Smaller window (Ocarina draws 2560 x 1440): the picture is shrunk "
|
||||||
"and FSR sharpens it by the strength below.",
|
"and FSR sharpens it by the strength below.",
|
||||||
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear",
|
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear",
|
||||||
[UI_MENU_ASPECT] = "Picture shape",
|
|
||||||
[UI_MENU_ASPECT_DESC] = "When the window's shape differs from the game resolution's (a 16:9 picture on a 21:9 "
|
|
||||||
"screen): keep the picture's shape with black bars, or stretch it over the window.",
|
|
||||||
[UI_MENU_GAME_ASPECT] = "Widescreen",
|
[UI_MENU_GAME_ASPECT] = "Widescreen",
|
||||||
[UI_MENU_GAME_ASPECT_DESC] = "The game draws a wider picture: more of the world at the sides, the HUD and menus in "
|
[UI_MENU_GAME_ASPECT_DESC] = "Widens the view. HUD and menus stay 16:9.",
|
||||||
"the middle 16:9. Window shape follows the window (the monitor in fullscreen).",
|
|
||||||
[UI_MENU_GAME_ASPECT_16_9] = "16:9 (the game's)", [UI_MENU_GAME_ASPECT_WINDOW] = "Window shape",
|
[UI_MENU_GAME_ASPECT_16_9] = "16:9 (the game's)", [UI_MENU_GAME_ASPECT_WINDOW] = "Window shape",
|
||||||
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
||||||
[UI_MENU_ASPECT_FIT] = "Black bars", [UI_MENU_ASPECT_STRETCH] = "Stretch",
|
|
||||||
[UI_MENU_FOV] = "Field of view",
|
[UI_MENU_FOV] = "Field of view",
|
||||||
[UI_MENU_FOV_DESC] = "How much of the world the camera shows, in percent of the game's own. Game version 1.4.3 only.",
|
[UI_MENU_FOV_DESC] = "How much of the world the camera shows, in percent of the game's own. Game version 1.4.3 only.",
|
||||||
[UI_MENU_SHADOW_RES] = "Shadow map size",
|
[UI_MENU_SHADOW_RES] = "Shadow map size",
|
||||||
[UI_MENU_SHADOW_RES_DESC] = "Size of the sun's shadow map. The game's own size changes with the view, down to about 400 "
|
[UI_MENU_SHADOW_RES_DESC] = "Shadow detail. Higher costs more GPU power.",
|
||||||
"near the ground, so leaf shadows look blocky and jump; a fixed size keeps them still and "
|
|
||||||
"sharper. Above 1024 the shadows cost more GPU time and video memory; 256 is coarser than the "
|
|
||||||
"game's own and is for integrated GPUs short of memory bandwidth.",
|
|
||||||
[UI_MENU_SHADOW_RES_GAME] = "Game (changes)",
|
[UI_MENU_SHADOW_RES_GAME] = "Game (changes)",
|
||||||
[UI_MENU_ANISO] = "Texture filtering",
|
[UI_MENU_ANISO] = "Texture filtering",
|
||||||
[UI_MENU_ANISO_DESC] = "Anisotropic filtering of surface textures: ground, roads and walls seen at a shallow angle stay sharp into the distance instead of blurring. Game: the level the game asks for, as on the Switch.",
|
[UI_MENU_ANISO_DESC] = "Anisotropic filtering of surface textures: ground, roads and walls seen at a shallow angle stay sharp into the distance instead of blurring. Game: the level the game asks for, as on the Switch.",
|
||||||
[UI_MENU_ANISO_GAME] = "Game",
|
[UI_MENU_ANISO_GAME] = "Game",
|
||||||
[UI_MENU_SHARPNESS] = "FSR sharpness",
|
[UI_MENU_SHARPNESS] = "FSR sharpness",
|
||||||
[UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling, also when the picture is shrunk to the window; 0 turns it "
|
[UI_MENU_SHARPNESS_DESC] = "How sharp FSR makes the picture. 0 turns it off.",
|
||||||
"off.",
|
|
||||||
[UI_MENU_SHARPNESS_NEEDS_FSR] = "only with AMD FSR 1 or FSR 3.1",
|
[UI_MENU_SHARPNESS_NEEDS_FSR] = "only with AMD FSR 1 or FSR 3.1",
|
||||||
[UI_MENU_COLOR] = "Colour",
|
[UI_MENU_COLOR] = "Colour",
|
||||||
[UI_MENU_COLOR_PRESET] = "Colour profile",
|
[UI_MENU_COLOR_PRESET] = "Colour profile",
|
||||||
@@ -118,24 +104,18 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_COLOR_GAMMA_DESC] = "Below 1 brightens dark and middle tones, above 1 darkens them; 1 leaves them.",
|
[UI_MENU_COLOR_GAMMA_DESC] = "Below 1 brightens dark and middle tones, above 1 darkens them; 1 leaves them.",
|
||||||
[UI_MENU_HDR_GROUP] = "HDR",
|
[UI_MENU_HDR_GROUP] = "HDR",
|
||||||
[UI_MENU_HDR] = "HDR output",
|
[UI_MENU_HDR] = "HDR output",
|
||||||
[UI_MENU_HDR_DESC] = "Bright highlights on an HDR display. Needs HDR turned on in Windows (\"Use HDR\") or in a "
|
[UI_MENU_HDR_DESC] = "Brighter highlights on an HDR display. Turn on HDR in Windows first.",
|
||||||
"Wayland compositor with colour management; without it the picture stays SDR. Native: the "
|
|
||||||
"game's own HDR, as on a Switch 2 on an HDR TV. Enhanced: the game's picture with its highlights "
|
|
||||||
"kept above the SDR white. Applies after a restart. The colour profile above is for SDR and is "
|
|
||||||
"not used in HDR.",
|
|
||||||
[UI_MENU_HDR_PEAK] = "Peak brightness",
|
[UI_MENU_HDR_PEAK] = "Peak brightness",
|
||||||
[UI_MENU_HDR_PEAK_DESC] = "Your display's peak in nits; the brightest highlights stop there.",
|
[UI_MENU_HDR_PEAK_DESC] = "Your display's peak brightness in nits.",
|
||||||
[UI_MENU_HDR_GAME] = "Game brightness",
|
[UI_MENU_HDR_GAME] = "Game brightness",
|
||||||
[UI_MENU_HDR_GAME_DESC] = "Nits of the picture's white (paper white). 203 is the HDR reference; raise it in a "
|
[UI_MENU_HDR_GAME_DESC] = "Brightness of white in the game, in nits.",
|
||||||
"bright room.",
|
|
||||||
[UI_MENU_HDR_UI] = "HUD and menu brightness",
|
[UI_MENU_HDR_UI] = "HUD and menu brightness",
|
||||||
[UI_MENU_HDR_UI_DESC] = "Nits of the HUD's and this menu's white.",
|
[UI_MENU_HDR_UI_DESC] = "Brightness of the HUD and this menu, in nits.",
|
||||||
[UI_MENU_HDR_HUE] = "Highlight hue correction",
|
[UI_MENU_HDR_HUE] = "Highlight hue correction",
|
||||||
[UI_MENU_HDR_HUE_DESC] = "Bright colours such as fire and sparks turn towards white as in the game's own SDR picture, "
|
[UI_MENU_HDR_HUE_DESC] = "Bright colours such as fire and sparks turn towards white as in the game's own SDR picture, "
|
||||||
"matching the light they cast; 0 keeps them fully saturated.",
|
"matching the light they cast; 0 keeps them fully saturated.",
|
||||||
[UI_MENU_SHADOW_SCALE] = "Shadow resolution",
|
[UI_MENU_SHADOW_SCALE] = "Shadow resolution",
|
||||||
[UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: "
|
[UI_MENU_SHADOW_SCALE_DESC] = "Sharper shadows. Higher costs more GPU power.",
|
||||||
"sharper shadow edges and leaf shadows. Takes effect at the next start.",
|
|
||||||
[UI_MENU_PCSS] = "Soft shadows",
|
[UI_MENU_PCSS] = "Soft shadows",
|
||||||
[UI_MENU_PCSS_DESC] = "Sun shadows sharp where an object meets the ground and softer the further the shadow falls "
|
[UI_MENU_PCSS_DESC] = "Sun shadows sharp where an object meets the ground and softer the further the shadow falls "
|
||||||
"(PCSS). 0 keeps the game's filter. Takes effect at the next start.",
|
"(PCSS). 0 keeps the game's filter. Takes effect at the next start.",
|
||||||
@@ -143,9 +123,7 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. "
|
[UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. "
|
||||||
"Traced on the screen after lighting. Takes effect at the next start.",
|
"Traced on the screen after lighting. Takes effect at the next start.",
|
||||||
[UI_MENU_SHADOW_RANGE] = "Shadow cascade range",
|
[UI_MENU_SHADOW_RANGE] = "Shadow cascade range",
|
||||||
[UI_MENU_SHADOW_RANGE_DESC] = "Moves the steps where shadows turn softer (the game's 20, 40, 80 and 160 m) further "
|
[UI_MENU_SHADOW_RANGE_DESC] = "Keeps shadows sharp further away.",
|
||||||
"away. Spreads the shadow map over more ground: raise Shadow resolution with it. "
|
|
||||||
"Takes effect at the next start.",
|
|
||||||
[UI_MENU_DLAA] = "NVIDIA DLSS / DLAA",
|
[UI_MENU_DLAA] = "NVIDIA DLSS / DLAA",
|
||||||
[UI_MENU_DLAA_DESC] = "NVIDIA DLSS for the 3D scene (NVIDIA RTX GPUs; " DLSS_FILE " next to " EXE_FILE "): smoother "
|
[UI_MENU_DLAA_DESC] = "NVIDIA DLSS for the 3D scene (NVIDIA RTX GPUs; " DLSS_FILE " next to " EXE_FILE "): smoother "
|
||||||
"edges and less shimmer. The HUD is not touched. The mode below sets the resolution it works "
|
"edges and less shimmer. The HUD is not touched. The mode below sets the resolution it works "
|
||||||
@@ -173,8 +151,7 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.",
|
[UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.",
|
||||||
|
|
||||||
[UI_MENU_FPS_LIMIT] = "Frame rate limit",
|
[UI_MENU_FPS_LIMIT] = "Frame rate limit",
|
||||||
[UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. The game keeps time by the clock, so it "
|
[UI_MENU_FPS_LIMIT_DESC] = "The highest frame rate the game runs at.",
|
||||||
"plays at the same speed at any rate. Unlimited draws as fast as the PC can.",
|
|
||||||
[UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_40] = "40 FPS", [UI_MENU_FPS_45] = "45 FPS",
|
[UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_40] = "40 FPS", [UI_MENU_FPS_45] = "45 FPS",
|
||||||
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS",
|
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS",
|
||||||
// the monitor's refresh rate; printf format with the rate in Hz when it is known
|
// the monitor's refresh rate; printf format with the rate in Hz when it is known
|
||||||
@@ -193,13 +170,10 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_GAME_LANG] = "Game language", [UI_MENU_GAME_LANG_DESC] = "Language of the game's text and voices.",
|
[UI_MENU_GAME_LANG] = "Game language", [UI_MENU_GAME_LANG_DESC] = "Language of the game's text and voices.",
|
||||||
[UI_MENU_GAME_LANG_AUTO] = "Automatic",
|
[UI_MENU_GAME_LANG_AUTO] = "Automatic",
|
||||||
[UI_MENU_OPERATION_MODE] = "Console mode",
|
[UI_MENU_OPERATION_MODE] = "Console mode",
|
||||||
[UI_MENU_OPERATION_MODE_DESC] = "Whether the game thinks it runs docked or handheld.",
|
[UI_MENU_OPERATION_MODE_DESC] = "Runs the game as docked or handheld.",
|
||||||
[UI_MENU_MODE_DOCKED] = "Docked", [UI_MENU_MODE_HANDHELD] = "Handheld",
|
[UI_MENU_MODE_DOCKED] = "Docked", [UI_MENU_MODE_HANDHELD] = "Handheld",
|
||||||
[UI_MENU_ASSUME_FOCUS] = "Keep running out of focus",
|
[UI_MENU_ASSUME_FOCUS] = "Keep running out of focus",
|
||||||
[UI_MENU_ASSUME_FOCUS_DESC] = "On (the default), the game keeps running while you are in another window, and the "
|
[UI_MENU_ASSUME_FOCUS_DESC] = "Keeps the game running when you switch to another window.",
|
||||||
"keyboard stays quiet until the window is in front again. Off, it pauses when its "
|
|
||||||
"window loses focus, as on the Switch when Home is pressed; a load interrupted that "
|
|
||||||
"way can stop for good.",
|
|
||||||
|
|
||||||
[UI_MENU_MODS_BUILTIN] = "Built into the port", [UI_MENU_MODS_INSTALLED] = "Installed mods",
|
[UI_MENU_MODS_BUILTIN] = "Built into the port", [UI_MENU_MODS_INSTALLED] = "Installed mods",
|
||||||
[UI_MENU_MODS_NONE] = "No mods yet. Unpack a mod into the mods folder, one folder per mod with its romfs folder "
|
[UI_MENU_MODS_NONE] = "No mods yet. Unpack a mod into the mods folder, one folder per mod with its romfs folder "
|
||||||
@@ -232,24 +206,20 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_MODS_QUICKMENU_DESC] = "The port's fix for the black background of the weapon, shield and material menus "
|
[UI_MENU_MODS_QUICKMENU_DESC] = "The port's fix for the black background of the weapon, shield and material menus "
|
||||||
"at 60 FPS.",
|
"at 60 FPS.",
|
||||||
|
|
||||||
[UI_MENU_VOLUME] = "Volume", [UI_MENU_VOLUME_DESC] = "Master volume of the game.", [UI_MENU_MENU_SOUNDS] = "Menu sounds", [UI_MENU_MENU_SOUNDS_DESC] = "Volume of this menu's sounds, the game's own cursor, confirm and cancel sounds. 0 turns them off.",
|
[UI_MENU_VOLUME] = "Volume", [UI_MENU_VOLUME_DESC] = "Overall game volume.", [UI_MENU_MENU_SOUNDS] = "Menu sounds", [UI_MENU_MENU_SOUNDS_DESC] = "Volume of this menu's sounds.",
|
||||||
[UI_MENU_AUDIO_CHANNELS] = "Speakers",
|
[UI_MENU_AUDIO_CHANNELS] = "Speakers",
|
||||||
[UI_MENU_AUDIO_CHANNELS_DESC] = "Stereo or 5.1 surround output. Automatic picks 5.1 when the Windows speaker setup "
|
[UI_MENU_AUDIO_CHANNELS_DESC] = "Stereo or 5.1 surround sound.",
|
||||||
"has six or more channels. Applies after a restart.",
|
|
||||||
[UI_MENU_CHANNELS_AUTO] = "Automatic", [UI_MENU_CHANNELS_STEREO] = "Stereo", [UI_MENU_CHANNELS_51] = "5.1 surround",
|
[UI_MENU_CHANNELS_AUTO] = "Automatic", [UI_MENU_CHANNELS_STEREO] = "Stereo", [UI_MENU_CHANNELS_51] = "5.1 surround",
|
||||||
|
|
||||||
[UI_MENU_MOTION] = "Motion controls", [UI_MENU_MOTION_DESC] = "Aiming with the controller's gyroscope.",
|
[UI_MENU_MOTION] = "Motion controls", [UI_MENU_MOTION_DESC] = "Aim with the controller's gyro.",
|
||||||
[UI_MENU_RUMBLE_STRENGTH] = "Vibration strength",
|
[UI_MENU_RUMBLE_STRENGTH] = "Vibration strength",
|
||||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "How strong the controller vibrates.",
|
[UI_MENU_RUMBLE_STRENGTH_DESC] = "How strong the vibration is.",
|
||||||
[UI_MENU_RUMBLE_CURVE] = "Vibration curve",
|
[UI_MENU_RUMBLE_CURVE] = "Vibration curve",
|
||||||
[UI_MENU_RUMBLE_CURVE_DESC] = "Lower values make weak vibration stronger.",
|
[UI_MENU_RUMBLE_CURVE_DESC] = "Lower values make light vibration stronger.",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS] = "Trigger vibration (Xbox)",
|
[UI_MENU_RUMBLE_TRIGGERS] = "Trigger vibration (Xbox)",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Vibrates the triggers of an Xbox controller too.",
|
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Also vibrates the triggers on Xbox controllers.",
|
||||||
[UI_MENU_PAD_LAYOUT] = "Button layout",
|
[UI_MENU_PAD_LAYOUT] = "Button layout",
|
||||||
[UI_MENU_PAD_LAYOUT_DESC] = "Which button is A. Nintendo: the right one, as on a Switch. Xbox: the bottom one, as "
|
[UI_MENU_PAD_LAYOUT_DESC] = "Sets which button acts as A.",
|
||||||
"labelled on an Xbox controller (cross on a PlayStation controller). Automatic picks "
|
|
||||||
"Nintendo for controllers with Nintendo labels and Xbox for the others. The game's "
|
|
||||||
"prompts always show the Switch letters.",
|
|
||||||
[UI_MENU_PAD_LAYOUT_AUTO] = "Automatic", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A right)",
|
[UI_MENU_PAD_LAYOUT_AUTO] = "Automatic", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A right)",
|
||||||
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)",
|
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)",
|
||||||
[UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s",
|
[UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s",
|
||||||
@@ -272,11 +242,12 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_RESTART_DESC] = "Closes the game and starts it again with the new prompts. Progress since your last save "
|
[UI_MENU_RESTART_DESC] = "Closes the game and starts it again with the new prompts. Progress since your last save "
|
||||||
"is lost.",
|
"is lost.",
|
||||||
[UI_MENU_RESTART_CONFIRM] = "Restart the game now? Progress since your last save is lost.",
|
[UI_MENU_RESTART_CONFIRM] = "Restart the game now? Progress since your last save is lost.",
|
||||||
|
[UI_MENU_QUIT_CONFIRM] = "Quit the game? Progress since your last save is lost.",
|
||||||
[UI_MENU_RESTART_YES] = "Restart",
|
[UI_MENU_RESTART_YES] = "Restart",
|
||||||
[UI_MENU_RESTART_SAVING] = "The game is saving: Restart is possible in a moment.",
|
[UI_MENU_RESTART_SAVING] = "The game is saving: Restart is possible in a moment.",
|
||||||
[UI_MENU_GROUP_STICKS] = "Analog sticks",
|
[UI_MENU_GROUP_STICKS] = "Analog sticks",
|
||||||
[UI_MENU_LSTICK_DEADZONE] = "Left stick dead zone", [UI_MENU_RSTICK_DEADZONE] = "Right stick dead zone",
|
[UI_MENU_LSTICK_DEADZONE] = "Left stick dead zone", [UI_MENU_RSTICK_DEADZONE] = "Right stick dead zone",
|
||||||
[UI_MENU_STICK_DEADZONE_DESC] = "How far a gamepad stick moves before the game sees it. Raise it if the character or the camera moves on its own: let go of the stick, read \"stick now\" and set the dead zone a few percent above it.",
|
[UI_MENU_STICK_DEADZONE_DESC] = "How far a stick must move to register. Raise it if a stick drifts.",
|
||||||
[UI_MENU_STICK_DEADZONE_NOW] = "stick now: %.0f %%",
|
[UI_MENU_STICK_DEADZONE_NOW] = "stick now: %.0f %%",
|
||||||
[UI_MENU_MOUSE_MODE] = "Mouse camera",
|
[UI_MENU_MOUSE_MODE] = "Mouse camera",
|
||||||
[UI_MENU_MOUSE_MODE_DESC] = "Direct: the camera turns by how far the mouse moves, as in a PC game, with no stick dead zone or curve (game 1.4.3; other versions use stick emulation). Stick emulation: the mouse acts as the right stick.",
|
[UI_MENU_MOUSE_MODE_DESC] = "Direct: the camera turns by how far the mouse moves, as in a PC game, with no stick dead zone or curve (game 1.4.3; other versions use stick emulation). Stick emulation: the mouse acts as the right stick.",
|
||||||
@@ -287,15 +258,13 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity",
|
[UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity",
|
||||||
[UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.",
|
[UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.",
|
||||||
[UI_MENU_WALK_KEY] = "Walk key",
|
[UI_MENU_WALK_KEY] = "Walk key",
|
||||||
[UI_MENU_WALK_KEY_DESC] = "Hold it to tilt the keyboard's sticks part of the way, so the keyboard walks instead of "
|
[UI_MENU_WALK_KEY_DESC] = "Hold to walk on the keyboard.",
|
||||||
"runs. The walk scale sets how far. A controller and the mouse are not affected.",
|
|
||||||
[UI_MENU_WALK_KEY_TAKEN] = "also %s",
|
[UI_MENU_WALK_KEY_TAKEN] = "also %s",
|
||||||
[UI_MENU_WALK_SCALE] = "Walk scale",
|
[UI_MENU_WALK_SCALE] = "Walk scale",
|
||||||
[UI_MENU_WALK_SCALE_DESC] = "The tilt the keyboard's sticks get while the walk key is held. Half is a walk, the "
|
[UI_MENU_WALK_SCALE_DESC] = "The tilt the keyboard's sticks get while the walk key is held. Half is a walk, the "
|
||||||
"full tilt a run.",
|
"full tilt a run.",
|
||||||
[UI_MENU_STICK_SENS] = "Stick camera speed",
|
[UI_MENU_STICK_SENS] = "Stick camera speed",
|
||||||
[UI_MENU_STICK_SENS_DESC] = "Multiplies the game's own right-stick camera speed, top speed included, at each of the "
|
[UI_MENU_STICK_SENS_DESC] = "Right stick camera speed.",
|
||||||
"game's five camera sensitivities. The mouse keeps its own setting.",
|
|
||||||
|
|
||||||
[UI_BINDS_HELP] = "Select a cell and press A or Enter, then the key, mouse button or controller button. Delete or "
|
[UI_BINDS_HELP] = "Select a cell and press A or Enter, then the key, mouse button or controller button. Delete or "
|
||||||
"X clears a cell. A key in use moves here; a controller button swaps with the one it replaces.",
|
"X clears a cell. A key in use moves here; a controller button swaps with the one it replaces.",
|
||||||
@@ -306,7 +275,7 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_BINDS_CANCEL_HINT] = "Esc cancels, or wait %d s",
|
[UI_BINDS_CANCEL_HINT] = "Esc cancels, or wait %d s",
|
||||||
[UI_BINDS_TAKEN] = "%s was taken from %s", [UI_BINDS_SWAPPED] = "%s swapped with %s",
|
[UI_BINDS_TAKEN] = "%s was taken from %s", [UI_BINDS_SWAPPED] = "%s swapped with %s",
|
||||||
[UI_BINDS_RESET] = "Reset all buttons",
|
[UI_BINDS_RESET] = "Reset all buttons",
|
||||||
[UI_BINDS_RESET_DESC] = "Back to the default keys and controller buttons. The button layout above applies again: remapped controller buttons stay where you put them until this reset.",
|
[UI_BINDS_RESET_DESC] = "Restores the default keys and buttons.",
|
||||||
[UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y",
|
[UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y",
|
||||||
[UI_BIND_LCLICK] = "Left stick click", [UI_BIND_RCLICK] = "Right stick click", [UI_BIND_L] = "L",
|
[UI_BIND_LCLICK] = "Left stick click", [UI_BIND_RCLICK] = "Right stick click", [UI_BIND_L] = "L",
|
||||||
[UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Plus", [UI_BIND_MINUS] = "Minus",
|
[UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Plus", [UI_BIND_MINUS] = "Minus",
|
||||||
@@ -329,11 +298,10 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_BIND_DESC_PLUS] = "Menu: items, equipment, collection, system.", [UI_BIND_DESC_MINUS] = "Map.",
|
[UI_BIND_DESC_PLUS] = "Menu: items, equipment, collection, system.", [UI_BIND_DESC_MINUS] = "Map.",
|
||||||
[UI_BIND_DESC_LEFT] = "Play the ocarina.", [UI_BIND_DESC_UP] = "Put the accessory on or take it off.",
|
[UI_BIND_DESC_LEFT] = "Play the ocarina.", [UI_BIND_DESC_UP] = "Put the accessory on or take it off.",
|
||||||
[UI_BIND_DESC_RIGHT] = "Talk to Navi.", [UI_BIND_DESC_DOWN] = "Change boots.",
|
[UI_BIND_DESC_RIGHT] = "Talk to Navi.", [UI_BIND_DESC_DOWN] = "Change boots.",
|
||||||
[UI_BIND_DESC_MOVE] = "Moves Link like the left stick. The controller's left stick always works too.",
|
[UI_BIND_DESC_MOVE] = "Moves Link.",
|
||||||
[UI_BIND_DESC_CAMERA] = "Turns the camera like the right stick. The mouse and the controller's right stick always "
|
[UI_BIND_DESC_CAMERA] = "Turns the camera.",
|
||||||
"work too.",
|
|
||||||
[UI_BIND_SHAKE] = "Shake the camera stick",
|
[UI_BIND_SHAKE] = "Shake the camera stick",
|
||||||
[UI_BIND_DESC_SHAKE] = "Swings the right stick left and right for the game. Holding the key keeps shaking.",
|
[UI_BIND_DESC_SHAKE] = "Shakes the right stick. Hold to keep shaking.",
|
||||||
[UI_KEY_SPACE] = "Space", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Left Shift", [UI_KEY_LCTRL] = "Left Ctrl",
|
[UI_KEY_SPACE] = "Space", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Left Shift", [UI_KEY_LCTRL] = "Left Ctrl",
|
||||||
[UI_KEY_UP] = "Up arrow", [UI_KEY_DOWN] = "Down arrow", [UI_KEY_LEFT] = "Left arrow",
|
[UI_KEY_UP] = "Up arrow", [UI_KEY_DOWN] = "Down arrow", [UI_KEY_LEFT] = "Left arrow",
|
||||||
[UI_KEY_RIGHT] = "Right arrow",
|
[UI_KEY_RIGHT] = "Right arrow",
|
||||||
@@ -510,33 +478,22 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
|||||||
[UI_BOOT_TITLE] = "Preparing shaders", [UI_BOOT_HINT] = "This happens once after an update or a graphics driver change.",
|
[UI_BOOT_TITLE] = "Preparing shaders", [UI_BOOT_HINT] = "This happens once after an update or a graphics driver change.",
|
||||||
[UI_BOOT_STARTING] = "Starting", [UI_BOOT_SHADERS] = "Shaders: %lld of %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld of %lld",
|
[UI_BOOT_STARTING] = "Starting", [UI_BOOT_SHADERS] = "Shaders: %lld of %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld of %lld",
|
||||||
[UI_MENU_UPSCALING] = "Upscaling",
|
[UI_MENU_UPSCALING] = "Upscaling",
|
||||||
[UI_MENU_UPSCALING_DESC] = "How the picture is made smooth and fitted to the window. Bilinear: plain scaling. AMD FSR 1: "
|
[UI_MENU_UPSCALING_DESC] = "How the picture is smoothed and scaled to your window.",
|
||||||
"sharper edges and detail when the window is larger than the picture (strength below). "
|
|
||||||
"NVIDIA DLSS (RTX GPUs; " DLSS_FILE " next to the game's .exe) renders the 3D scene at "
|
|
||||||
"its mode's share of the picture and scales it up with NVIDIA's newest model for the mode: "
|
|
||||||
"DLAA 100 %, Quality 67 %, Balanced 58 %, Performance 50 %, Ultra Performance 33 %. The "
|
|
||||||
"HUD is not touched. AMD FSR 3.1 (any GPU; amd_fidelityfx_vk.dll next to the game's .exe) "
|
|
||||||
"works the same way, with Native AA at 100 % and the same shares for its other modes. "
|
|
||||||
"Turning DLSS or FSR 3.1 on or off, or changing between them, takes effect after a "
|
|
||||||
"restart; the mode changes at once.",
|
|
||||||
[UI_MENU_UPSCALING_DLSS_NOTE] = "DLSS or FSR 3.1 on or off: after restart",
|
[UI_MENU_UPSCALING_DLSS_NOTE] = "DLSS or FSR 3.1 on or off: after restart",
|
||||||
|
[UI_MENU_UPSCALING_DESC_FSR] = "How the picture is smoothed and scaled to your window.",
|
||||||
|
[UI_MENU_UPSCALING_FSR_NOTE] = "FSR 3.1 on or off: after restart",
|
||||||
[UI_MENU_FRAMEGEN] = "Frame generation",
|
[UI_MENU_FRAMEGEN] = "Frame generation",
|
||||||
[UI_MENU_FRAMEGEN_DESC] = "Shows a generated frame between every two the game draws, for about twice the frame rate "
|
[UI_MENU_FRAMEGEN_DESC] = "Adds generated frames for smoother motion. Needs DLSS or FSR 3.1.",
|
||||||
"on a fast display. It needs DLSS or FSR 3.1 under Upscaling (any mode), whose motion "
|
|
||||||
"vectors it uses. AMD FSR 3.1 frame generation runs on any GPU (amd_fidelityfx_vk.dll next "
|
|
||||||
"to the game's .exe); NVIDIA DLSS frame generation needs an RTX 40 or 50 GPU and "
|
|
||||||
"NVIDIA's Streamline files next to the .exe. It pauses while this menu is open. Takes "
|
|
||||||
"effect after a restart.",
|
|
||||||
[UI_MENU_FRAMEGEN_OFF] = "Off",
|
[UI_MENU_FRAMEGEN_OFF] = "Off",
|
||||||
[UI_MENU_HDR_NOTE] = "after restart",
|
[UI_MENU_HDR_NOTE] = "after restart",
|
||||||
[UI_MENU_HDR_ENHANCED] = "Enhanced", [UI_MENU_HDR_NATIVE] = "Native (the game's)",
|
[UI_MENU_HDR_ENHANCED] = "Enhanced", [UI_MENU_HDR_NATIVE] = "Native (the game's)",
|
||||||
[UI_MENU_FRAMEGEN_NOTE] = "after restart; needs DLSS or FSR 3.1",
|
[UI_MENU_FRAMEGEN_NOTE] = "after restart; needs DLSS or FSR 3.1",
|
||||||
[UI_MENU_FRAMEGEN_NEEDS] = "choose a DLSS or FSR 3.1 mode under Upscaling first",
|
[UI_MENU_FRAMEGEN_NEEDS] = "choose a DLSS or FSR 3.1 mode under Upscaling first",
|
||||||
|
[UI_MENU_FRAMEGEN_NEEDS_FSR] = "choose an FSR 3.1 mode under Upscaling first",
|
||||||
|
[UI_MENU_FRAMEGEN_NOTE_FSR] = "after restart; needs FSR 3.1",
|
||||||
|
[UI_MENU_FRAMEGEN_DESC_FSR] = "Adds generated frames for smoother motion. Needs FSR 3.1.",
|
||||||
[UI_MENU_GAME_RES] = "Resolution",
|
[UI_MENU_GAME_RES] = "Resolution",
|
||||||
[UI_MENU_GAME_RES_DESC] = "The height of the game's picture: 1440p is the game's own; higher draws a sharper picture "
|
[UI_MENU_GAME_RES_DESC] = "Height of the game's picture. Higher is sharper but costs more GPU power.",
|
||||||
"and its scene in proportion, at a matching cost on the graphics card. Native: the "
|
|
||||||
"window's height (the monitor's in fullscreen), from 1440 up to 4320. The width follows "
|
|
||||||
"the widescreen shape. Takes effect after a restart.",
|
|
||||||
[UI_MENU_GAME_RES_NATIVE] = "Native",
|
[UI_MENU_GAME_RES_NATIVE] = "Native",
|
||||||
[UI_MENU_CHEATS_REBUILD] = "Rebuild the game now",
|
[UI_MENU_CHEATS_REBUILD] = "Rebuild the game now",
|
||||||
[UI_MENU_CHEATS_REBUILD_DESC] = "Some cheats change the game's code and are not built into it: they are new or "
|
[UI_MENU_CHEATS_REBUILD_DESC] = "Some cheats change the game's code and are not built into it: they are new or "
|
||||||
@@ -564,59 +521,44 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_SAVE_FAILED] = "не удалось сохранить настройки",
|
[UI_MENU_SAVE_FAILED] = "не удалось сохранить настройки",
|
||||||
[UI_MENU_VERSION] = "NX2navi %s, игра %s",
|
[UI_MENU_VERSION] = "NX2navi %s, игра %s",
|
||||||
|
|
||||||
[UI_MENU_FULLSCREEN] = "Полный экран", [UI_MENU_FULLSCREEN_DESC] = "Игра на весь экран; F11 переключает режим.",
|
[UI_MENU_FULLSCREEN] = "Полный экран", [UI_MENU_FULLSCREEN_DESC] = "Игра на весь экран. F11 переключает.",
|
||||||
[UI_MENU_WINDOW_SIZE] = "Размер окна", [UI_MENU_WINDOW_SIZE_DESC] = "Размер окна игры вне полноэкранного режима.",
|
[UI_MENU_WINDOW_SIZE] = "Размер окна", [UI_MENU_WINDOW_SIZE_DESC] = "Размер окна вне полноэкранного режима.",
|
||||||
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Другой",
|
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Другой",
|
||||||
[UI_MENU_PRESENT] = "Вывод кадров", [UI_MENU_PRESENT_DESC] = "Как готовые кадры попадают на экран.",
|
[UI_MENU_PRESENT_DESC] = "Убирает разрывы изображения. Выкл. немного снижает задержку.",
|
||||||
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "Вертикальная синхронизация",
|
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "Вертикальная синхронизация",
|
||||||
[UI_MENU_PRESENT_IMMEDIATE] = "Без ожидания",
|
[UI_MENU_PRESENT_IMMEDIATE] = "Без ожидания",
|
||||||
[UI_MENU_PRESENT_IN_USE] = "сейчас: %s",
|
[UI_MENU_PRESENT_IN_USE] = "сейчас: %s",
|
||||||
[UI_MENU_GPU] = "Видеокарта", [UI_MENU_GPU_DESC] = "Устройство Vulkan, которое рисует игру.",
|
[UI_MENU_GPU] = "Видеокарта", [UI_MENU_GPU_DESC] = "Видеокарта, на которой работает игра.",
|
||||||
[UI_MENU_GPU_AUTO] = "Автоматически",
|
[UI_MENU_GPU_AUTO] = "Автоматически",
|
||||||
[UI_MENU_PERF_OVERLAY] = "Индикатор производительности",
|
[UI_MENU_PERF_OVERLAY] = "Индикатор производительности",
|
||||||
[UI_MENU_PERF_OVERLAY_DESC] = "Частота кадров в правом верхнем углу. «Полный» добавляет время кадров с графиком, "
|
[UI_MENU_PERF_OVERLAY_DESC] = "Показывает частоту кадров и данные системы. F10 меняет режим.",
|
||||||
"загрузку ЦП, GPU и памяти, температуры и ожидания потока отрисовки. F10 переключает "
|
|
||||||
"режимы.",
|
|
||||||
[UI_MENU_PERF_OFF] = "Выкл.", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Полный",
|
[UI_MENU_PERF_OFF] = "Выкл.", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Полный",
|
||||||
[UI_PERF_LINE_FPS] = "%.0f к/с",
|
[UI_PERF_LINE_FPS] = "%.0f к/с",
|
||||||
[UI_MENU_GRAPHICS] = "Изображение",
|
[UI_MENU_GRAPHICS] = "Изображение",
|
||||||
[UI_MENU_OUTPUT_RES] = "Разрешение игры",
|
[UI_MENU_OUTPUT_RES] = "Разрешение игры",
|
||||||
[UI_MENU_OUTPUT_RES_DESC] = "Размер, в котором игра рисует картинку и интерфейс. Выше 1920 × 1080 игре нужно больше "
|
[UI_MENU_OUTPUT_RES_DESC] = "Разрешение, в котором рисуется игра. Чем выше, тем больше нагрузка на видеокарту.",
|
||||||
"видеопамяти и времени GPU. Более широкий размер (21:9) расширяет обзор камеры и "
|
|
||||||
"переносит интерфейс в углы экрана, более высокий (16:10, 3:2) переносит его к "
|
|
||||||
"верхнему и нижнему краям.",
|
|
||||||
[UI_MENU_RENDER_SCALE] = "Масштаб 3D-отрисовки",
|
[UI_MENU_RENDER_SCALE] = "Масштаб 3D-отрисовки",
|
||||||
[UI_MENU_RENDER_SCALE_DESC] = "Размер 3D-сцены относительно разрешения игры; FSR игры доводит её до этого размера. "
|
[UI_MENU_RENDER_SCALE_DESC] = "Размер 3D-сцены. Выше — чётче, но медленнее.",
|
||||||
"Выше 100 % сглаживает лесенки на краях (суперсэмплинг) ценой большой нагрузки на GPU.",
|
|
||||||
[UI_MENU_RENDER_SCALE_GAME] = "Как в игре (83 %)",
|
[UI_MENU_RENDER_SCALE_GAME] = "Как в игре (83 %)",
|
||||||
[UI_MENU_UPSCALER] = "Масштабирование под окно",
|
[UI_MENU_UPSCALER] = "Масштабирование под окно",
|
||||||
[UI_MENU_UPSCALER_DESC] = "Как картинка игры вписывается в окно. Окно больше: FSR сохраняет края и детали чётче "
|
[UI_MENU_UPSCALER_DESC] = "Как картинка игры вписывается в окно. Окно больше: FSR сохраняет края и детали чётче "
|
||||||
"билинейного. Окно меньше (Ocarina рисует 2560 × 1440): картинка уменьшается, и FSR "
|
"билинейного. Окно меньше (Ocarina рисует 2560 × 1440): картинка уменьшается, и FSR "
|
||||||
"повышает её резкость на величину ниже.",
|
"повышает её резкость на величину ниже.",
|
||||||
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Билинейное",
|
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Билинейное",
|
||||||
[UI_MENU_ASPECT] = "Форма картинки",
|
|
||||||
[UI_MENU_ASPECT_DESC] = "Когда форма окна отличается от разрешения игры (картинка 16:9 на экране 21:9): сохранить "
|
|
||||||
"форму картинки с чёрными полосами или растянуть её на всё окно.",
|
|
||||||
[UI_MENU_GAME_ASPECT] = "Широкий экран",
|
[UI_MENU_GAME_ASPECT] = "Широкий экран",
|
||||||
[UI_MENU_GAME_ASPECT_DESC] = "Игра рисует более широкую картинку: больше мира по бокам, интерфейс и меню в "
|
[UI_MENU_GAME_ASPECT_DESC] = "Расширяет обзор. Интерфейс и меню остаются 16:9.",
|
||||||
"центральной части 16:9. «По окну» берёт форму окна (монитора в полноэкранном режиме).",
|
|
||||||
[UI_MENU_GAME_ASPECT_16_9] = "16:9 (как в игре)", [UI_MENU_GAME_ASPECT_WINDOW] = "По окну",
|
[UI_MENU_GAME_ASPECT_16_9] = "16:9 (как в игре)", [UI_MENU_GAME_ASPECT_WINDOW] = "По окну",
|
||||||
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
||||||
[UI_MENU_ASPECT_FIT] = "Чёрные полосы", [UI_MENU_ASPECT_STRETCH] = "Растянуть",
|
|
||||||
[UI_MENU_FOV] = "Поле зрения",
|
[UI_MENU_FOV] = "Поле зрения",
|
||||||
[UI_MENU_FOV_DESC] = "Сколько мира показывает камера, в процентах от игрового. Только для версии игры 1.4.3.",
|
[UI_MENU_FOV_DESC] = "Сколько мира показывает камера, в процентах от игрового. Только для версии игры 1.4.3.",
|
||||||
[UI_MENU_SHADOW_RES] = "Размер карты теней",
|
[UI_MENU_SHADOW_RES] = "Размер карты теней",
|
||||||
[UI_MENU_SHADOW_RES_DESC] = "Размер карты теней от солнца. Собственный размер игры меняется вместе с видом, у земли до "
|
[UI_MENU_SHADOW_RES_DESC] = "Детализация теней. Выше — больше нагрузка на видеокарту.",
|
||||||
"примерно 400, поэтому тени листвы выглядят квадратными и дёргаются; постоянный размер делает "
|
|
||||||
"их ровными и чётче. Выше 1024 тени требуют больше времени GPU и видеопамяти; 256 грубее "
|
|
||||||
"собственного размера игры и предназначен для встроенных GPU с нехваткой пропускной способности памяти.",
|
|
||||||
[UI_MENU_SHADOW_RES_GAME] = "Как в игре (меняется)",
|
[UI_MENU_SHADOW_RES_GAME] = "Как в игре (меняется)",
|
||||||
[UI_MENU_ANISO] = "Фильтрация текстур",
|
[UI_MENU_ANISO] = "Фильтрация текстур",
|
||||||
[UI_MENU_ANISO_DESC] = "Анизотропная фильтрация текстур поверхностей: земля, дороги и стены под острым углом остаются чёткими вдали, а не размываются. Игра: уровень, который запрашивает игра, как на Switch.",
|
[UI_MENU_ANISO_DESC] = "Анизотропная фильтрация текстур поверхностей: земля, дороги и стены под острым углом остаются чёткими вдали, а не размываются. Игра: уровень, который запрашивает игра, как на Switch.",
|
||||||
[UI_MENU_ANISO_GAME] = "Игра",
|
[UI_MENU_ANISO_GAME] = "Игра",
|
||||||
[UI_MENU_SHARPNESS] = "Резкость FSR",
|
[UI_MENU_SHARPNESS] = "Резкость FSR",
|
||||||
[UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR, в том числе когда картинка уменьшается "
|
[UI_MENU_SHARPNESS_DESC] = "Насколько FSR повышает резкость. 0 отключает.",
|
||||||
"под окно; 0 выключает его.",
|
|
||||||
[UI_MENU_SHARPNESS_NEEDS_FSR] = "только с AMD FSR 1",
|
[UI_MENU_SHARPNESS_NEEDS_FSR] = "только с AMD FSR 1",
|
||||||
[UI_MENU_COLOR] = "Цвет",
|
[UI_MENU_COLOR] = "Цвет",
|
||||||
[UI_MENU_COLOR_PRESET] = "Цветовой профиль",
|
[UI_MENU_COLOR_PRESET] = "Цветовой профиль",
|
||||||
@@ -636,22 +578,18 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_COLOR_GAMMA_DESC] = "Ниже 1 осветляет тёмные и средние тона, выше 1 затемняет их; 1 — без изменений.",
|
[UI_MENU_COLOR_GAMMA_DESC] = "Ниже 1 осветляет тёмные и средние тона, выше 1 затемняет их; 1 — без изменений.",
|
||||||
[UI_MENU_HDR_GROUP] = "HDR",
|
[UI_MENU_HDR_GROUP] = "HDR",
|
||||||
[UI_MENU_HDR] = "Вывод HDR",
|
[UI_MENU_HDR] = "Вывод HDR",
|
||||||
[UI_MENU_HDR_DESC] = "Яркие блики на HDR-дисплее. Нужен включённый HDR в Windows («Использовать HDR») или "
|
[UI_MENU_HDR_DESC] = "Более яркие блики на HDR-экране. Сначала включите HDR в Windows.",
|
||||||
"Wayland-композитор с управлением цветом; без него картинка остаётся SDR. Применяется после "
|
|
||||||
"перезапуска. Цветовой профиль выше — для SDR и в HDR не используется.",
|
|
||||||
[UI_MENU_HDR_PEAK] = "Пиковая яркость",
|
[UI_MENU_HDR_PEAK] = "Пиковая яркость",
|
||||||
[UI_MENU_HDR_PEAK_DESC] = "Пик вашего дисплея в нитах; самые яркие блики останавливаются на нём.",
|
[UI_MENU_HDR_PEAK_DESC] = "Пиковая яркость вашего экрана в нитах.",
|
||||||
[UI_MENU_HDR_GAME] = "Яркость игры",
|
[UI_MENU_HDR_GAME] = "Яркость игры",
|
||||||
[UI_MENU_HDR_GAME_DESC] = "Ниты белого цвета картинки (paper white). 203 — эталон HDR; в светлой комнате "
|
[UI_MENU_HDR_GAME_DESC] = "Яркость белого в игре, в нитах.",
|
||||||
"поднимите.",
|
|
||||||
[UI_MENU_HDR_UI] = "Яркость интерфейса и меню",
|
[UI_MENU_HDR_UI] = "Яркость интерфейса и меню",
|
||||||
[UI_MENU_HDR_UI_DESC] = "Ниты белого цвета интерфейса игры и этого меню.",
|
[UI_MENU_HDR_UI_DESC] = "Яркость интерфейса и этого меню, в нитах.",
|
||||||
[UI_MENU_HDR_HUE] = "Коррекция оттенка бликов",
|
[UI_MENU_HDR_HUE] = "Коррекция оттенка бликов",
|
||||||
[UI_MENU_HDR_HUE_DESC] = "Яркие цвета (огонь, искры) уходят к белому, как в SDR-картинке игры, и совпадают со светом, "
|
[UI_MENU_HDR_HUE_DESC] = "Яркие цвета (огонь, искры) уходят к белому, как в SDR-картинке игры, и совпадают со светом, "
|
||||||
"который они дают; 0 оставляет их полностью насыщенными.",
|
"который они дают; 0 оставляет их полностью насыщенными.",
|
||||||
[UI_MENU_SHADOW_SCALE] = "Разрешение теней",
|
[UI_MENU_SHADOW_SCALE] = "Разрешение теней",
|
||||||
[UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 "
|
[UI_MENU_SHADOW_SCALE_DESC] = "Более чёткие тени. Выше — больше нагрузка на видеокарту.",
|
||||||
"самой игры: края теней и тени листвы чётче. Действует после перезапуска.",
|
|
||||||
[UI_MENU_PCSS] = "Мягкие тени",
|
[UI_MENU_PCSS] = "Мягкие тени",
|
||||||
[UI_MENU_PCSS_DESC] = "Тени от солнца резкие там, где предмет касается земли, и мягче, чем дальше падает тень "
|
[UI_MENU_PCSS_DESC] = "Тени от солнца резкие там, где предмет касается земли, и мягче, чем дальше падает тень "
|
||||||
"(PCSS). 0 оставляет фильтр игры. Действует после перезапуска.",
|
"(PCSS). 0 оставляет фильтр игры. Действует после перезапуска.",
|
||||||
@@ -659,9 +597,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и "
|
[UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и "
|
||||||
"складках. Считаются по экрану после освещения. Действует после перезапуска.",
|
"складках. Считаются по экрану после освещения. Действует после перезапуска.",
|
||||||
[UI_MENU_SHADOW_RANGE] = "Дальность каскадов теней",
|
[UI_MENU_SHADOW_RANGE] = "Дальность каскадов теней",
|
||||||
[UI_MENU_SHADOW_RANGE_DESC] = "Отодвигает границы, за которыми тени становятся мягче (в игре 20, 40, 80 и 160 м). "
|
[UI_MENU_SHADOW_RANGE_DESC] = "Сохраняет чёткие тени на большем расстоянии.",
|
||||||
"Карта теней растягивается на большую площадь, поэтому вместе с этим поднимайте "
|
|
||||||
"разрешение теней. Действует после перезапуска.",
|
|
||||||
[UI_MENU_DLAA] = "NVIDIA DLSS / DLAA",
|
[UI_MENU_DLAA] = "NVIDIA DLSS / DLAA",
|
||||||
[UI_MENU_DLAA_DESC] = "NVIDIA DLSS для 3D-сцены (видеокарты NVIDIA RTX; " DLSS_FILE " рядом с " EXE_FILE "): ровнее "
|
[UI_MENU_DLAA_DESC] = "NVIDIA DLSS для 3D-сцены (видеокарты NVIDIA RTX; " DLSS_FILE " рядом с " EXE_FILE "): ровнее "
|
||||||
"края и меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он "
|
"края и меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он "
|
||||||
@@ -689,8 +625,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.",
|
[UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.",
|
||||||
|
|
||||||
[UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров",
|
[UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров",
|
||||||
[UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Игра идёт по часам, поэтому её скорость не "
|
[UI_MENU_FPS_LIMIT_DESC] = "Максимальная частота кадров игры.",
|
||||||
"зависит от частоты кадров. «Без ограничения» рисует так быстро, как может ПК.",
|
|
||||||
[UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_40] = "40 FPS", [UI_MENU_FPS_45] = "45 FPS",
|
[UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_40] = "40 FPS", [UI_MENU_FPS_45] = "45 FPS",
|
||||||
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS",
|
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS",
|
||||||
[UI_MENU_FPS_DISPLAY] = "Как у монитора", [UI_MENU_FPS_DISPLAY_HZ] = "Как у монитора (%.0f Гц)",
|
[UI_MENU_FPS_DISPLAY] = "Как у монитора", [UI_MENU_FPS_DISPLAY_HZ] = "Как у монитора (%.0f Гц)",
|
||||||
@@ -707,13 +642,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_GAME_LANG] = "Язык игры", [UI_MENU_GAME_LANG_DESC] = "Язык текста и озвучки игры.",
|
[UI_MENU_GAME_LANG] = "Язык игры", [UI_MENU_GAME_LANG_DESC] = "Язык текста и озвучки игры.",
|
||||||
[UI_MENU_GAME_LANG_AUTO] = "Автоматически",
|
[UI_MENU_GAME_LANG_AUTO] = "Автоматически",
|
||||||
[UI_MENU_OPERATION_MODE] = "Режим консоли",
|
[UI_MENU_OPERATION_MODE] = "Режим консоли",
|
||||||
[UI_MENU_OPERATION_MODE_DESC] = "Игра считает, что консоль в док-станции или в портативном режиме.",
|
[UI_MENU_OPERATION_MODE_DESC] = "Запускает игру как в док-станции или в портативном режиме.",
|
||||||
[UI_MENU_MODE_DOCKED] = "В док-станции", [UI_MENU_MODE_HANDHELD] = "Портативный",
|
[UI_MENU_MODE_DOCKED] = "В док-станции", [UI_MENU_MODE_HANDHELD] = "Портативный",
|
||||||
[UI_MENU_ASSUME_FOCUS] = "Работать без фокуса",
|
[UI_MENU_ASSUME_FOCUS] = "Работать без фокуса",
|
||||||
[UI_MENU_ASSUME_FOCUS_DESC] = "Включено (по умолчанию): игра идёт, пока вы в другом окне, а клавиатура не "
|
[UI_MENU_ASSUME_FOCUS_DESC] = "Игра продолжает работать, когда вы переключаетесь на другое окно.",
|
||||||
"действует, пока окно не вернётся на передний план. Выключено: игра встаёт на паузу, "
|
|
||||||
"когда окно теряет фокус, как на Switch при нажатии Home; прерванная так загрузка "
|
|
||||||
"может остановиться насовсем.",
|
|
||||||
|
|
||||||
[UI_MENU_MODS_BUILTIN] = "Встроенные в порт", [UI_MENU_MODS_INSTALLED] = "Установленные моды",
|
[UI_MENU_MODS_BUILTIN] = "Встроенные в порт", [UI_MENU_MODS_INSTALLED] = "Установленные моды",
|
||||||
[UI_MENU_MODS_NONE] = "Модов пока нет. Распакуйте мод в папку mods, каждый мод в свою папку с папкой romfs внутри, и "
|
[UI_MENU_MODS_NONE] = "Модов пока нет. Распакуйте мод в папку mods, каждый мод в свою папку с папкой romfs внутри, и "
|
||||||
@@ -744,24 +676,20 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_MODS_QUICKMENU] = "Исправление быстрого меню",
|
[UI_MENU_MODS_QUICKMENU] = "Исправление быстрого меню",
|
||||||
[UI_MENU_MODS_QUICKMENU_DESC] = "Исправление порта: чёрный фон меню оружия, щитов и материалов при 60 FPS.",
|
[UI_MENU_MODS_QUICKMENU_DESC] = "Исправление порта: чёрный фон меню оружия, щитов и материалов при 60 FPS.",
|
||||||
|
|
||||||
[UI_MENU_VOLUME] = "Громкость", [UI_MENU_VOLUME_DESC] = "Общая громкость игры.", [UI_MENU_MENU_SOUNDS] = "Звуки меню", [UI_MENU_MENU_SOUNDS_DESC] = "Громкость звуков этого меню (курсор, выбор и отмена из самой игры). 0 выключает их.",
|
[UI_MENU_VOLUME] = "Громкость", [UI_MENU_VOLUME_DESC] = "Общая громкость игры.", [UI_MENU_MENU_SOUNDS] = "Звуки меню", [UI_MENU_MENU_SOUNDS_DESC] = "Громкость звуков этого меню.",
|
||||||
[UI_MENU_AUDIO_CHANNELS] = "Динамики",
|
[UI_MENU_AUDIO_CHANNELS] = "Динамики",
|
||||||
[UI_MENU_AUDIO_CHANNELS_DESC] = "Стерео или объёмный звук 5.1. Автоматически выбирается 5.1, если в Windows "
|
[UI_MENU_AUDIO_CHANNELS_DESC] = "Стерео или объёмный звук 5.1.",
|
||||||
"настроено шесть каналов или больше. Применяется после перезапуска.",
|
|
||||||
[UI_MENU_CHANNELS_AUTO] = "Автоматически", [UI_MENU_CHANNELS_STEREO] = "Стерео", [UI_MENU_CHANNELS_51] = "Объёмный 5.1",
|
[UI_MENU_CHANNELS_AUTO] = "Автоматически", [UI_MENU_CHANNELS_STEREO] = "Стерео", [UI_MENU_CHANNELS_51] = "Объёмный 5.1",
|
||||||
|
|
||||||
[UI_MENU_MOTION] = "Управление движением", [UI_MENU_MOTION_DESC] = "Прицеливание гироскопом контроллера.",
|
[UI_MENU_MOTION] = "Управление движением", [UI_MENU_MOTION_DESC] = "Прицеливание гироскопом контроллера.",
|
||||||
[UI_MENU_RUMBLE_STRENGTH] = "Сила вибрации",
|
[UI_MENU_RUMBLE_STRENGTH] = "Сила вибрации",
|
||||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "Насколько сильно вибрирует контроллер.",
|
[UI_MENU_RUMBLE_STRENGTH_DESC] = "Сила вибрации.",
|
||||||
[UI_MENU_RUMBLE_CURVE] = "Кривая вибрации",
|
[UI_MENU_RUMBLE_CURVE] = "Кривая вибрации",
|
||||||
[UI_MENU_RUMBLE_CURVE_DESC] = "Чем ниже значение, тем сильнее слабая вибрация.",
|
[UI_MENU_RUMBLE_CURVE_DESC] = "Чем ниже, тем сильнее слабая вибрация.",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS] = "Вибрация триггеров (Xbox)",
|
[UI_MENU_RUMBLE_TRIGGERS] = "Вибрация триггеров (Xbox)",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Вибрация и в триггерах контроллера Xbox.",
|
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Вибрация также на курках контроллера Xbox.",
|
||||||
[UI_MENU_PAD_LAYOUT] = "Раскладка кнопок",
|
[UI_MENU_PAD_LAYOUT] = "Раскладка кнопок",
|
||||||
[UI_MENU_PAD_LAYOUT_DESC] = "Какая кнопка работает как A. Nintendo: правая, как на Switch. Xbox: нижняя, как "
|
[UI_MENU_PAD_LAYOUT_DESC] = "Какая кнопка работает как A.",
|
||||||
"подписано на контроллере Xbox (крест на контроллере PlayStation). Автоматически: "
|
|
||||||
"Nintendo для контроллеров с подписями Nintendo, Xbox для остальных. Подсказки игры "
|
|
||||||
"всегда показывают буквы Switch.",
|
|
||||||
[UI_MENU_PAD_LAYOUT_AUTO] = "Автоматически", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A справа)",
|
[UI_MENU_PAD_LAYOUT_AUTO] = "Автоматически", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A справа)",
|
||||||
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)",
|
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)",
|
||||||
[UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s",
|
[UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s",
|
||||||
@@ -784,11 +712,12 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_RESTART_DESC] = "Закрывает игру и запускает её снова с новыми подсказками. Прогресс после последнего "
|
[UI_MENU_RESTART_DESC] = "Закрывает игру и запускает её снова с новыми подсказками. Прогресс после последнего "
|
||||||
"сохранения будет потерян.",
|
"сохранения будет потерян.",
|
||||||
[UI_MENU_RESTART_CONFIRM] = "Перезапустить игру сейчас? Прогресс после последнего сохранения будет потерян.",
|
[UI_MENU_RESTART_CONFIRM] = "Перезапустить игру сейчас? Прогресс после последнего сохранения будет потерян.",
|
||||||
|
[UI_MENU_QUIT_CONFIRM] = "Выйти из игры? Прогресс после последнего сохранения будет потерян.",
|
||||||
[UI_MENU_RESTART_YES] = "Перезапустить",
|
[UI_MENU_RESTART_YES] = "Перезапустить",
|
||||||
[UI_MENU_RESTART_SAVING] = "Игра сохраняется: перезапуск будет доступен через мгновение.",
|
[UI_MENU_RESTART_SAVING] = "Игра сохраняется: перезапуск будет доступен через мгновение.",
|
||||||
[UI_MENU_GROUP_STICKS] = "Стики",
|
[UI_MENU_GROUP_STICKS] = "Стики",
|
||||||
[UI_MENU_LSTICK_DEADZONE] = "Мёртвая зона левого стика", [UI_MENU_RSTICK_DEADZONE] = "Мёртвая зона правого стика",
|
[UI_MENU_LSTICK_DEADZONE] = "Мёртвая зона левого стика", [UI_MENU_RSTICK_DEADZONE] = "Мёртвая зона правого стика",
|
||||||
[UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами: отпустите стик, посмотрите «стик сейчас» и поставьте мёртвую зону на несколько процентов выше.",
|
[UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно сдвинуть стик, чтобы он сработал. Увеличьте при дрейфе.",
|
||||||
[UI_MENU_STICK_DEADZONE_NOW] = "стик сейчас: %.0f %%",
|
[UI_MENU_STICK_DEADZONE_NOW] = "стик сейчас: %.0f %%",
|
||||||
[UI_MENU_MOUSE_MODE] = "Управление мышью",
|
[UI_MENU_MOUSE_MODE] = "Управление мышью",
|
||||||
[UI_MENU_MOUSE_MODE_DESC] = "Прямое: камера поворачивается на столько, на сколько сдвинута мышь, как в играх для ПК, без мёртвой зоны и кривой стика (версия игры 1.4.3; на других версиях эмуляция стика). Эмуляция стика: мышь работает как правый стик.",
|
[UI_MENU_MOUSE_MODE_DESC] = "Прямое: камера поворачивается на столько, на сколько сдвинута мышь, как в играх для ПК, без мёртвой зоны и кривой стика (версия игры 1.4.3; на других версиях эмуляция стика). Эмуляция стика: мышь работает как правый стик.",
|
||||||
@@ -799,15 +728,13 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_MOUSE_SENS] = "Чувствительность мыши",
|
[UI_MENU_MOUSE_SENS] = "Чувствительность мыши",
|
||||||
[UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.",
|
[UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.",
|
||||||
[UI_MENU_WALK_KEY] = "Клавиша шага",
|
[UI_MENU_WALK_KEY] = "Клавиша шага",
|
||||||
[UI_MENU_WALK_KEY_DESC] = "Удерживайте: стики клавиатуры отклоняются частично, и персонаж идёт, а не бежит. "
|
[UI_MENU_WALK_KEY_DESC] = "Удерживайте, чтобы идти шагом на клавиатуре.",
|
||||||
"Насколько — задаёт сила шага. Контроллер и мышь не затрагиваются.",
|
|
||||||
[UI_MENU_WALK_KEY_TAKEN] = "также %s",
|
[UI_MENU_WALK_KEY_TAKEN] = "также %s",
|
||||||
[UI_MENU_WALK_SCALE] = "Сила шага",
|
[UI_MENU_WALK_SCALE] = "Сила шага",
|
||||||
[UI_MENU_WALK_SCALE_DESC] = "Отклонение стиков клавиатуры при удержании клавиши шага. Половина — шаг, полное "
|
[UI_MENU_WALK_SCALE_DESC] = "Отклонение стиков клавиатуры при удержании клавиши шага. Половина — шаг, полное "
|
||||||
"отклонение — бег.",
|
"отклонение — бег.",
|
||||||
[UI_MENU_STICK_SENS] = "Скорость камеры (стик)",
|
[UI_MENU_STICK_SENS] = "Скорость камеры (стик)",
|
||||||
[UI_MENU_STICK_SENS_DESC] = "Умножает скорость поворота камеры правым стиком, включая наибольшую, при каждой из пяти "
|
[UI_MENU_STICK_SENS_DESC] = "Скорость камеры на правом стике.",
|
||||||
"чувствительностей камеры в игре. На мышь не влияет.",
|
|
||||||
|
|
||||||
[UI_BINDS_HELP] = "Выберите ячейку и нажмите A или Enter, затем клавишу, кнопку мыши или кнопку контроллера. "
|
[UI_BINDS_HELP] = "Выберите ячейку и нажмите A или Enter, затем клавишу, кнопку мыши или кнопку контроллера. "
|
||||||
"Delete или X очищает ячейку. Занятая клавиша переходит сюда; кнопка контроллера меняется "
|
"Delete или X очищает ячейку. Занятая клавиша переходит сюда; кнопка контроллера меняется "
|
||||||
@@ -819,9 +746,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_BINDS_CANCEL_HINT] = "Esc отменяет, или подождите %d с",
|
[UI_BINDS_CANCEL_HINT] = "Esc отменяет, или подождите %d с",
|
||||||
[UI_BINDS_TAKEN] = "%s: убрано с «%s»", [UI_BINDS_SWAPPED] = "«%s» и «%s» поменялись местами",
|
[UI_BINDS_TAKEN] = "%s: убрано с «%s»", [UI_BINDS_SWAPPED] = "«%s» и «%s» поменялись местами",
|
||||||
[UI_BINDS_RESET] = "Сбросить все кнопки",
|
[UI_BINDS_RESET] = "Сбросить все кнопки",
|
||||||
[UI_BINDS_RESET_DESC] = "Вернуть клавиши и кнопки контроллера по умолчанию. Снова действует раскладка кнопок выше: "
|
[UI_BINDS_RESET_DESC] = "Возвращает стандартные клавиши и кнопки.",
|
||||||
"переназначенные кнопки контроллера остаются на своих местах до "
|
|
||||||
"этого сброса.",
|
|
||||||
[UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y",
|
[UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y",
|
||||||
[UI_BIND_LCLICK] = "Нажатие левого стика", [UI_BIND_RCLICK] = "Нажатие правого стика", [UI_BIND_L] = "L",
|
[UI_BIND_LCLICK] = "Нажатие левого стика", [UI_BIND_RCLICK] = "Нажатие правого стика", [UI_BIND_L] = "L",
|
||||||
[UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Плюс", [UI_BIND_MINUS] = "Минус",
|
[UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Плюс", [UI_BIND_MINUS] = "Минус",
|
||||||
@@ -844,11 +769,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
|||||||
[UI_BIND_DESC_PLUS] = "Меню: предметы, снаряжение, коллекция, система.", [UI_BIND_DESC_MINUS] = "Карта.",
|
[UI_BIND_DESC_PLUS] = "Меню: предметы, снаряжение, коллекция, система.", [UI_BIND_DESC_MINUS] = "Карта.",
|
||||||
[UI_BIND_DESC_LEFT] = "Играть на окарине.", [UI_BIND_DESC_UP] = "Надеть или снять аксессуар.",
|
[UI_BIND_DESC_LEFT] = "Играть на окарине.", [UI_BIND_DESC_UP] = "Надеть или снять аксессуар.",
|
||||||
[UI_BIND_DESC_RIGHT] = "Поговорить с Нави.", [UI_BIND_DESC_DOWN] = "Сменить сапоги.",
|
[UI_BIND_DESC_RIGHT] = "Поговорить с Нави.", [UI_BIND_DESC_DOWN] = "Сменить сапоги.",
|
||||||
[UI_BIND_DESC_MOVE] = "Двигает Линка, как левый стик. Левый стик контроллера тоже всегда работает.",
|
[UI_BIND_DESC_MOVE] = "Двигает Линка.",
|
||||||
[UI_BIND_DESC_CAMERA] = "Поворачивает камеру, как правый стик. Мышь и правый стик контроллера тоже всегда "
|
[UI_BIND_DESC_CAMERA] = "Поворачивает камеру.",
|
||||||
"работают.",
|
|
||||||
[UI_BIND_SHAKE] = "Встряхнуть стик камеры",
|
[UI_BIND_SHAKE] = "Встряхнуть стик камеры",
|
||||||
[UI_BIND_DESC_SHAKE] = "Качает правый стик влево-вправо. Пока клавиша зажата, тряска продолжается.",
|
[UI_BIND_DESC_SHAKE] = "Трясёт правый стик. Удерживайте, чтобы продолжать.",
|
||||||
[UI_KEY_SPACE] = "Пробел", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Левый Shift", [UI_KEY_LCTRL] = "Левый Ctrl",
|
[UI_KEY_SPACE] = "Пробел", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Левый Shift", [UI_KEY_LCTRL] = "Левый Ctrl",
|
||||||
[UI_KEY_UP] = "Стрелка вверх", [UI_KEY_DOWN] = "Стрелка вниз", [UI_KEY_LEFT] = "Стрелка влево",
|
[UI_KEY_UP] = "Стрелка вверх", [UI_KEY_DOWN] = "Стрелка вниз", [UI_KEY_LEFT] = "Стрелка влево",
|
||||||
[UI_KEY_RIGHT] = "Стрелка вправо",
|
[UI_KEY_RIGHT] = "Стрелка вправо",
|
||||||
@@ -1082,61 +1006,44 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_SAVE_FAILED] = "não foi possível salvar as configurações",
|
[UI_MENU_SAVE_FAILED] = "não foi possível salvar as configurações",
|
||||||
[UI_MENU_VERSION] = "NX2navi %s, jogo %s",
|
[UI_MENU_VERSION] = "NX2navi %s, jogo %s",
|
||||||
|
|
||||||
[UI_MENU_FULLSCREEN] = "Tela cheia", [UI_MENU_FULLSCREEN_DESC] = "O jogo ocupa a tela inteira; F11 alterna.",
|
[UI_MENU_FULLSCREEN] = "Tela cheia", [UI_MENU_FULLSCREEN_DESC] = "Jogar em tela cheia. F11 alterna.",
|
||||||
[UI_MENU_WINDOW_SIZE] = "Tamanho da janela",
|
[UI_MENU_WINDOW_SIZE] = "Tamanho da janela",
|
||||||
[UI_MENU_WINDOW_SIZE_DESC] = "Tamanho da janela do jogo fora da tela cheia.",
|
[UI_MENU_WINDOW_SIZE_DESC] = "Tamanho da janela fora da tela cheia.",
|
||||||
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Personalizado",
|
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Personalizado",
|
||||||
[UI_MENU_PRESENT] = "Apresentação", [UI_MENU_PRESENT_DESC] = "Como os quadros prontos chegam à tela.",
|
[UI_MENU_PRESENT_DESC] = "Evita cortes na imagem. Desligado reduz um pouco o atraso.",
|
||||||
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "VSync", [UI_MENU_PRESENT_IMMEDIATE] = "Imediato",
|
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "VSync", [UI_MENU_PRESENT_IMMEDIATE] = "Imediato",
|
||||||
[UI_MENU_PRESENT_IN_USE] = "em uso: %s",
|
[UI_MENU_PRESENT_IN_USE] = "em uso: %s",
|
||||||
[UI_MENU_GPU] = "Placa de vídeo", [UI_MENU_GPU_DESC] = "O dispositivo Vulkan que desenha o jogo.",
|
[UI_MENU_GPU] = "Placa de vídeo", [UI_MENU_GPU_DESC] = "A placa de vídeo usada pelo jogo.",
|
||||||
[UI_MENU_GPU_AUTO] = "Automática",
|
[UI_MENU_GPU_AUTO] = "Automática",
|
||||||
[UI_MENU_PERF_OVERLAY] = "Indicador de desempenho",
|
[UI_MENU_PERF_OVERLAY] = "Indicador de desempenho",
|
||||||
[UI_MENU_PERF_OVERLAY_DESC] = "Taxa de quadros no canto superior direito. Completo adiciona os tempos de quadro com "
|
[UI_MENU_PERF_OVERLAY_DESC] = "Mostra a taxa de quadros e dados do sistema. F10 alterna.",
|
||||||
"gráfico, o uso de CPU, GPU e memória, as temperaturas e as esperas da thread de "
|
|
||||||
"renderização. F10 alterna os modos.",
|
|
||||||
[UI_MENU_PERF_OFF] = "Desligado", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Completo",
|
[UI_MENU_PERF_OFF] = "Desligado", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Completo",
|
||||||
[UI_PERF_LINE_FPS] = "%.0f fps",
|
[UI_PERF_LINE_FPS] = "%.0f fps",
|
||||||
[UI_MENU_GRAPHICS] = "Imagem",
|
[UI_MENU_GRAPHICS] = "Imagem",
|
||||||
[UI_MENU_OUTPUT_RES] = "Resolução do jogo",
|
[UI_MENU_OUTPUT_RES] = "Resolução do jogo",
|
||||||
[UI_MENU_OUTPUT_RES_DESC] = "O tamanho em que o jogo desenha a imagem e a interface. Acima de 1920 x 1080 o jogo "
|
[UI_MENU_OUTPUT_RES_DESC] = "A resolução do jogo. Mais alta exige mais da placa de vídeo.",
|
||||||
"precisa de mais memória de vídeo e tempo de GPU. Um tamanho mais largo (21:9) amplia a "
|
|
||||||
"visão da câmera e leva o HUD para os cantos da tela; um mais alto (16:10, 3:2) "
|
|
||||||
"leva-o para as bordas de cima e de baixo.",
|
|
||||||
[UI_MENU_RENDER_SCALE] = "Escala da renderização 3D",
|
[UI_MENU_RENDER_SCALE] = "Escala da renderização 3D",
|
||||||
[UI_MENU_RENDER_SCALE_DESC] = "Tamanho da cena 3D em relação à resolução do jogo; o FSR do jogo a amplia até esse "
|
[UI_MENU_RENDER_SCALE_DESC] = "Tamanho da cena 3D. Maior fica mais nítido, porém mais pesado.",
|
||||||
"tamanho. Acima de 100 % suaviza bordas serrilhadas (supersampling) com alto custo de "
|
|
||||||
"GPU.",
|
|
||||||
[UI_MENU_RENDER_SCALE_GAME] = "Jogo (83 %)",
|
[UI_MENU_RENDER_SCALE_GAME] = "Jogo (83 %)",
|
||||||
[UI_MENU_UPSCALER] = "Escala para a janela",
|
[UI_MENU_UPSCALER] = "Escala para a janela",
|
||||||
[UI_MENU_UPSCALER_DESC] = "Como a imagem do jogo se ajusta à janela. Janela maior: o FSR mantém bordas e detalhes "
|
[UI_MENU_UPSCALER_DESC] = "Como a imagem do jogo se ajusta à janela. Janela maior: o FSR mantém bordas e detalhes "
|
||||||
"mais nítidos que o bilinear. Janela menor (Ocarina desenha 2560 x 1440): a imagem é "
|
"mais nítidos que o bilinear. Janela menor (Ocarina desenha 2560 x 1440): a imagem é "
|
||||||
"reduzida e o FSR aumenta a nitidez com a intensidade abaixo.",
|
"reduzida e o FSR aumenta a nitidez com a intensidade abaixo.",
|
||||||
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear",
|
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear",
|
||||||
[UI_MENU_ASPECT] = "Formato da imagem",
|
|
||||||
[UI_MENU_ASPECT_DESC] = "Quando o formato da janela difere do da resolução do jogo (uma imagem 16:9 numa tela "
|
|
||||||
"21:9): manter o formato da imagem com barras pretas ou esticá-la sobre a janela.",
|
|
||||||
[UI_MENU_GAME_ASPECT] = "Tela larga",
|
[UI_MENU_GAME_ASPECT] = "Tela larga",
|
||||||
[UI_MENU_GAME_ASPECT_DESC] = "O jogo desenha uma imagem mais larga: mais do mundo nas laterais, a interface e os "
|
[UI_MENU_GAME_ASPECT_DESC] = "Amplia a visão. A interface e os menus continuam em 16:9.",
|
||||||
"menus no centro 16:9. Formato da janela segue a janela (o monitor em tela cheia).",
|
|
||||||
[UI_MENU_GAME_ASPECT_16_9] = "16:9 (o do jogo)", [UI_MENU_GAME_ASPECT_WINDOW] = "Formato da janela",
|
[UI_MENU_GAME_ASPECT_16_9] = "16:9 (o do jogo)", [UI_MENU_GAME_ASPECT_WINDOW] = "Formato da janela",
|
||||||
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
||||||
[UI_MENU_ASPECT_FIT] = "Barras pretas", [UI_MENU_ASPECT_STRETCH] = "Esticar",
|
|
||||||
[UI_MENU_SHARPNESS] = "Nitidez do FSR",
|
[UI_MENU_SHARPNESS] = "Nitidez do FSR",
|
||||||
[UI_MENU_SHARPNESS_DESC] = "Aumento de nitidez após a escala do FSR, também quando a imagem é reduzida à janela; 0 "
|
[UI_MENU_SHARPNESS_DESC] = "Nitidez aplicada pelo FSR. 0 desliga.",
|
||||||
"desliga.",
|
|
||||||
[UI_MENU_SHARPNESS_NEEDS_FSR] = "só com AMD FSR 1",
|
[UI_MENU_SHARPNESS_NEEDS_FSR] = "só com AMD FSR 1",
|
||||||
|
|
||||||
[UI_MENU_FPS_LIMIT] = "Limite de quadros",
|
[UI_MENU_FPS_LIMIT] = "Limite de quadros",
|
||||||
[UI_MENU_FPS_LIMIT_DESC] = "O máximo de quadros por segundo que o jogo desenha. O jogo segue o relógio, então a "
|
[UI_MENU_FPS_LIMIT_DESC] = "A taxa de quadros máxima do jogo.",
|
||||||
"velocidade é a mesma em qualquer taxa. Sem limite desenha o mais rápido que o PC puder.",
|
|
||||||
[UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_40] = "40 FPS", [UI_MENU_FPS_45] = "45 FPS",
|
[UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_40] = "40 FPS", [UI_MENU_FPS_45] = "45 FPS",
|
||||||
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS",
|
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS",
|
||||||
[UI_MENU_ASSUME_FOCUS] = "Continuar rodando fora de foco",
|
[UI_MENU_ASSUME_FOCUS] = "Continuar rodando fora de foco",
|
||||||
[UI_MENU_ASSUME_FOCUS_DESC] = "Ligado (o padrão), o jogo continua rodando enquanto você está em outra janela, e o "
|
[UI_MENU_ASSUME_FOCUS_DESC] = "Mantém o jogo rodando quando você troca de janela.",
|
||||||
"teclado fica sem efeito até a janela voltar para a frente. Desligado, ele pausa quando "
|
|
||||||
"a janela perde o foco, como no Switch ao apertar Home; um carregamento interrompido "
|
|
||||||
"assim pode parar de vez.",
|
|
||||||
[UI_MENU_FPS_DISPLAY] = "Taxa do monitor", [UI_MENU_FPS_DISPLAY_HZ] = "Taxa do monitor (%.0f Hz)",
|
[UI_MENU_FPS_DISPLAY] = "Taxa do monitor", [UI_MENU_FPS_DISPLAY_HZ] = "Taxa do monitor (%.0f Hz)",
|
||||||
[UI_MENU_FPS_UNLIMITED] = "Sem limite",
|
[UI_MENU_FPS_UNLIMITED] = "Sem limite",
|
||||||
[UI_MENU_FPS_RTSS] = "limitado pelo RivaTuner Statistics Server",
|
[UI_MENU_FPS_RTSS] = "limitado pelo RivaTuner Statistics Server",
|
||||||
@@ -1151,32 +1058,27 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_GAME_LANG] = "Idioma do jogo", [UI_MENU_GAME_LANG_DESC] = "Idioma dos textos e das vozes do jogo.",
|
[UI_MENU_GAME_LANG] = "Idioma do jogo", [UI_MENU_GAME_LANG_DESC] = "Idioma dos textos e das vozes do jogo.",
|
||||||
[UI_MENU_GAME_LANG_AUTO] = "Automático",
|
[UI_MENU_GAME_LANG_AUTO] = "Automático",
|
||||||
[UI_MENU_OPERATION_MODE] = "Modo do console",
|
[UI_MENU_OPERATION_MODE] = "Modo do console",
|
||||||
[UI_MENU_OPERATION_MODE_DESC] = "Se o jogo acha que está no modo TV ou no modo portátil.",
|
[UI_MENU_OPERATION_MODE_DESC] = "Roda o jogo como na base ou no modo portátil.",
|
||||||
[UI_MENU_MODE_DOCKED] = "Modo TV", [UI_MENU_MODE_HANDHELD] = "Modo portátil",
|
[UI_MENU_MODE_DOCKED] = "Modo TV", [UI_MENU_MODE_HANDHELD] = "Modo portátil",
|
||||||
|
|
||||||
[UI_MENU_VOLUME] = "Volume", [UI_MENU_VOLUME_DESC] = "Volume geral do jogo.", [UI_MENU_MENU_SOUNDS] = "Sons do menu", [UI_MENU_MENU_SOUNDS_DESC] = "Volume dos sons deste menu (cursor, confirmar e cancelar do próprio jogo). 0 desliga.",
|
[UI_MENU_VOLUME] = "Volume", [UI_MENU_VOLUME_DESC] = "Volume geral do jogo.", [UI_MENU_MENU_SOUNDS] = "Sons do menu", [UI_MENU_MENU_SOUNDS_DESC] = "Volume dos sons deste menu.",
|
||||||
|
|
||||||
[UI_MENU_MOTION] = "Controles de movimento", [UI_MENU_MOTION_DESC] = "Mirar com o giroscópio do controle.",
|
[UI_MENU_MOTION] = "Controles de movimento", [UI_MENU_MOTION_DESC] = "Mira com o giroscópio do controle.",
|
||||||
[UI_MENU_RUMBLE_STRENGTH] = "Intensidade da vibração",
|
[UI_MENU_RUMBLE_STRENGTH] = "Intensidade da vibração",
|
||||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "Quão forte o controle vibra.",
|
[UI_MENU_RUMBLE_STRENGTH_DESC] = "Intensidade da vibração.",
|
||||||
[UI_MENU_RUMBLE_CURVE] = "Curva da vibração",
|
[UI_MENU_RUMBLE_CURVE] = "Curva da vibração",
|
||||||
[UI_MENU_RUMBLE_CURVE_DESC] = "Valores menores deixam a vibração fraca mais forte.",
|
[UI_MENU_RUMBLE_CURVE_DESC] = "Valores menores reforçam a vibração fraca.",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS] = "Vibração dos gatilhos (Xbox)",
|
[UI_MENU_RUMBLE_TRIGGERS] = "Vibração dos gatilhos (Xbox)",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Também vibra os gatilhos de um controle de Xbox.",
|
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Também vibra os gatilhos do controle Xbox.",
|
||||||
[UI_MENU_PAD_LAYOUT] = "Layout dos botões",
|
[UI_MENU_PAD_LAYOUT] = "Layout dos botões",
|
||||||
[UI_MENU_PAD_LAYOUT_DESC] = "Qual botão é o A. Nintendo: o da direita, como no Switch. Xbox: o de baixo, como "
|
[UI_MENU_PAD_LAYOUT_DESC] = "Define qual botão funciona como A.",
|
||||||
"indicado no controle de Xbox (cruz no controle de PlayStation). Automático escolhe "
|
|
||||||
"Nintendo para controles com os rótulos da Nintendo e Xbox para os demais. As dicas do "
|
|
||||||
"jogo sempre mostram as letras do Switch.",
|
|
||||||
[UI_MENU_PAD_LAYOUT_AUTO] = "Automático", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A à direita)",
|
[UI_MENU_PAD_LAYOUT_AUTO] = "Automático", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A à direita)",
|
||||||
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A embaixo)",
|
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A embaixo)",
|
||||||
[UI_MENU_PAD_LAYOUT_IN_USE] = "em uso: %s",
|
[UI_MENU_PAD_LAYOUT_IN_USE] = "em uso: %s",
|
||||||
[UI_MENU_GROUP_STICKS] = "Analógicos",
|
[UI_MENU_GROUP_STICKS] = "Analógicos",
|
||||||
[UI_MENU_LSTICK_DEADZONE] = "Zona morta do analógico esquerdo",
|
[UI_MENU_LSTICK_DEADZONE] = "Zona morta do analógico esquerdo",
|
||||||
[UI_MENU_RSTICK_DEADZONE] = "Zona morta do analógico direito",
|
[UI_MENU_RSTICK_DEADZONE] = "Zona morta do analógico direito",
|
||||||
[UI_MENU_STICK_DEADZONE_DESC] = "Quanto um analógico do controle precisa se mover antes que o jogo perceba. Aumente "
|
[UI_MENU_STICK_DEADZONE_DESC] = "Quanto o analógico precisa mover para responder. Aumente se houver drift.",
|
||||||
"se o personagem ou a câmera se moverem sozinhos: solte o analógico, leia \"analógico "
|
|
||||||
"agora\" e coloque a zona morta alguns por cento acima.",
|
|
||||||
[UI_MENU_STICK_DEADZONE_NOW] = "analógico agora: %.0f %%",
|
[UI_MENU_STICK_DEADZONE_NOW] = "analógico agora: %.0f %%",
|
||||||
[UI_MENU_MOUSE_SENS] = "Sensibilidade da câmera no mouse",
|
[UI_MENU_MOUSE_SENS] = "Sensibilidade da câmera no mouse",
|
||||||
[UI_MENU_MOUSE_SENS_DESC] = "Quão rápido o mouse gira a câmera.",
|
[UI_MENU_MOUSE_SENS_DESC] = "Quão rápido o mouse gira a câmera.",
|
||||||
@@ -1191,8 +1093,7 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_BINDS_CANCEL_HINT] = "Esc cancela, ou aguarde %d s",
|
[UI_BINDS_CANCEL_HINT] = "Esc cancela, ou aguarde %d s",
|
||||||
[UI_BINDS_TAKEN] = "%s saiu de %s", [UI_BINDS_SWAPPED] = "%s trocou de lugar com %s",
|
[UI_BINDS_TAKEN] = "%s saiu de %s", [UI_BINDS_SWAPPED] = "%s trocou de lugar com %s",
|
||||||
[UI_BINDS_RESET] = "Restaurar todos os botões",
|
[UI_BINDS_RESET] = "Restaurar todos os botões",
|
||||||
[UI_BINDS_RESET_DESC] = "Volta às teclas e aos botões do controle padrão. O layout dos botões acima volta a valer: "
|
[UI_BINDS_RESET_DESC] = "Restaura as teclas e os botões padrão.",
|
||||||
"os botões do controle remapeados ficam onde você os colocou até esta restauração.",
|
|
||||||
[UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y",
|
[UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y",
|
||||||
[UI_BIND_LCLICK] = "Clique do analógico esquerdo", [UI_BIND_RCLICK] = "Clique do analógico direito",
|
[UI_BIND_LCLICK] = "Clique do analógico esquerdo", [UI_BIND_RCLICK] = "Clique do analógico direito",
|
||||||
[UI_BIND_L] = "L", [UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Mais",
|
[UI_BIND_L] = "L", [UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Mais",
|
||||||
@@ -1216,12 +1117,10 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_BIND_DESC_PLUS] = "Menu: itens, equipamento, coleção, sistema.", [UI_BIND_DESC_MINUS] = "Mapa.",
|
[UI_BIND_DESC_PLUS] = "Menu: itens, equipamento, coleção, sistema.", [UI_BIND_DESC_MINUS] = "Mapa.",
|
||||||
[UI_BIND_DESC_LEFT] = "Tocar a ocarina.", [UI_BIND_DESC_UP] = "Pôr ou tirar o acessório.",
|
[UI_BIND_DESC_LEFT] = "Tocar a ocarina.", [UI_BIND_DESC_UP] = "Pôr ou tirar o acessório.",
|
||||||
[UI_BIND_DESC_RIGHT] = "Falar com a Navi.", [UI_BIND_DESC_DOWN] = "Trocar de botas.",
|
[UI_BIND_DESC_RIGHT] = "Falar com a Navi.", [UI_BIND_DESC_DOWN] = "Trocar de botas.",
|
||||||
[UI_BIND_DESC_MOVE] = "Move o Link como o analógico esquerdo. O analógico esquerdo do controle também sempre "
|
[UI_BIND_DESC_MOVE] = "Move o Link.",
|
||||||
"funciona.",
|
[UI_BIND_DESC_CAMERA] = "Gira a câmera.",
|
||||||
[UI_BIND_DESC_CAMERA] = "Gira a câmera como o analógico direito. O mouse e o analógico direito do controle também "
|
|
||||||
"sempre funcionam.",
|
|
||||||
[UI_BIND_SHAKE] = "Sacudir o analógico da câmera",
|
[UI_BIND_SHAKE] = "Sacudir o analógico da câmera",
|
||||||
[UI_BIND_DESC_SHAKE] = "Balança o analógico direito para os lados. Segurar a tecla continua sacudindo.",
|
[UI_BIND_DESC_SHAKE] = "Balança o analógico direito. Segure para continuar.",
|
||||||
[UI_KEY_SPACE] = "Espaço", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Shift esquerdo",
|
[UI_KEY_SPACE] = "Espaço", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Shift esquerdo",
|
||||||
[UI_KEY_LCTRL] = "Ctrl esquerdo",
|
[UI_KEY_LCTRL] = "Ctrl esquerdo",
|
||||||
[UI_KEY_UP] = "Seta para cima", [UI_KEY_DOWN] = "Seta para baixo", [UI_KEY_LEFT] = "Seta para a esquerda",
|
[UI_KEY_UP] = "Seta para cima", [UI_KEY_DOWN] = "Seta para baixo", [UI_KEY_LEFT] = "Seta para a esquerda",
|
||||||
@@ -1385,11 +1284,7 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_FOV_DESC] = "Quanto do mundo a câmera mostra, em porcentagem do original do jogo. Só na versão 1.4.3 do "
|
[UI_MENU_FOV_DESC] = "Quanto do mundo a câmera mostra, em porcentagem do original do jogo. Só na versão 1.4.3 do "
|
||||||
"jogo.",
|
"jogo.",
|
||||||
[UI_MENU_SHADOW_RES] = "Tamanho do mapa de sombras",
|
[UI_MENU_SHADOW_RES] = "Tamanho do mapa de sombras",
|
||||||
[UI_MENU_SHADOW_RES_DESC] = "Tamanho do mapa de sombras do sol. O tamanho do jogo muda com a vista, até cerca de "
|
[UI_MENU_SHADOW_RES_DESC] = "Detalhe das sombras. Mais alto exige mais da placa de vídeo.",
|
||||||
"400 perto do chão, então as sombras das folhas ficam quadriculadas e pulam; um "
|
|
||||||
"tamanho fixo as deixa paradas e mais nítidas. Acima de 1024 as sombras custam mais "
|
|
||||||
"tempo de GPU e memória de vídeo; 256 é mais grosseiro que o do jogo e serve para GPUs "
|
|
||||||
"integradas com pouca largura de banda de memória.",
|
|
||||||
[UI_MENU_SHADOW_RES_GAME] = "Do jogo (varia)",
|
[UI_MENU_SHADOW_RES_GAME] = "Do jogo (varia)",
|
||||||
[UI_MENU_ANISO] = "Filtragem de texturas",
|
[UI_MENU_ANISO] = "Filtragem de texturas",
|
||||||
[UI_MENU_ANISO_DESC] = "Filtragem anisotrópica das texturas de superfície: chão, estradas e paredes vistos em "
|
[UI_MENU_ANISO_DESC] = "Filtragem anisotrópica das texturas de superfície: chão, estradas e paredes vistos em "
|
||||||
@@ -1418,16 +1313,13 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
"nada.",
|
"nada.",
|
||||||
[UI_MENU_HDR_GROUP] = "HDR",
|
[UI_MENU_HDR_GROUP] = "HDR",
|
||||||
[UI_MENU_HDR] = "Saída HDR",
|
[UI_MENU_HDR] = "Saída HDR",
|
||||||
[UI_MENU_HDR_DESC] = "Realces brilhantes em uma tela HDR. Precisa do HDR ligado no Windows (\"Usar HDR\") ou num "
|
[UI_MENU_HDR_DESC] = "Realces mais brilhantes em telas HDR. Ative o HDR no Windows antes.",
|
||||||
"compositor Wayland com gerenciamento de cor; sem isso a imagem continua SDR. Vale após "
|
|
||||||
"reiniciar. O perfil de cor acima é para SDR e não é usado em HDR.",
|
|
||||||
[UI_MENU_HDR_PEAK] = "Brilho máximo",
|
[UI_MENU_HDR_PEAK] = "Brilho máximo",
|
||||||
[UI_MENU_HDR_PEAK_DESC] = "O pico da sua tela em nits; os realces mais claros param aí.",
|
[UI_MENU_HDR_PEAK_DESC] = "Brilho máximo da sua tela em nits.",
|
||||||
[UI_MENU_HDR_GAME] = "Brilho do jogo",
|
[UI_MENU_HDR_GAME] = "Brilho do jogo",
|
||||||
[UI_MENU_HDR_GAME_DESC] = "Nits do branco da imagem (branco de papel). 203 é a referência de HDR; aumente num "
|
[UI_MENU_HDR_GAME_DESC] = "Brilho do branco no jogo, em nits.",
|
||||||
"ambiente claro.",
|
|
||||||
[UI_MENU_HDR_UI] = "Brilho do HUD e do menu",
|
[UI_MENU_HDR_UI] = "Brilho do HUD e do menu",
|
||||||
[UI_MENU_HDR_UI_DESC] = "Nits do branco do HUD e deste menu.",
|
[UI_MENU_HDR_UI_DESC] = "Brilho da interface e deste menu, em nits.",
|
||||||
[UI_MENU_PROMPTS] = "Ícones de botões",
|
[UI_MENU_PROMPTS] = "Ícones de botões",
|
||||||
[UI_MENU_PROMPTS_DESC] = "Os botões de qual controle os ícones do jogo mostram. Nintendo: os do próprio jogo. "
|
[UI_MENU_PROMPTS_DESC] = "Os botões de qual controle os ícones do jogo mostram. Nintendo: os do próprio jogo. "
|
||||||
"Xbox: LB, RB, LT, RT, Menu, Exibir e uma cruz direcional, e A, B, X e Y com a letra do "
|
"Xbox: LB, RB, LT, RT, Menu, Exibir e uma cruz direcional, e A, B, X e Y com a letra do "
|
||||||
@@ -1456,15 +1348,13 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_RESTART_DESC] = "Fecha o jogo e o abre de novo com os novos ícones. O progresso desde o último "
|
[UI_MENU_RESTART_DESC] = "Fecha o jogo e o abre de novo com os novos ícones. O progresso desde o último "
|
||||||
"salvamento é perdido.",
|
"salvamento é perdido.",
|
||||||
[UI_MENU_RESTART_CONFIRM] = "Reiniciar o jogo agora? O progresso desde o último salvamento é perdido.",
|
[UI_MENU_RESTART_CONFIRM] = "Reiniciar o jogo agora? O progresso desde o último salvamento é perdido.",
|
||||||
|
[UI_MENU_QUIT_CONFIRM] = "Sair do jogo? O progresso desde o último salvamento é perdido.",
|
||||||
[UI_MENU_RESTART_YES] = "Reiniciar",
|
[UI_MENU_RESTART_YES] = "Reiniciar",
|
||||||
[UI_MENU_RESTART_SAVING] = "O jogo está salvando: dá para reiniciar em um instante.",
|
[UI_MENU_RESTART_SAVING] = "O jogo está salvando: dá para reiniciar em um instante.",
|
||||||
[UI_MENU_STICK_SENS] = "Velocidade da câmera (analógico)",
|
[UI_MENU_STICK_SENS] = "Velocidade da câmera (analógico)",
|
||||||
[UI_MENU_STICK_SENS_DESC] = "Multiplica a velocidade da câmera do analógico direito do jogo, incluindo a máxima, "
|
[UI_MENU_STICK_SENS_DESC] = "Velocidade da câmera no analógico direito.",
|
||||||
"em cada uma das cinco sensibilidades de câmera do jogo. O mouse mantém a própria "
|
|
||||||
"configuração.",
|
|
||||||
[UI_MENU_WALK_KEY] = "Tecla de andar",
|
[UI_MENU_WALK_KEY] = "Tecla de andar",
|
||||||
[UI_MENU_WALK_KEY_DESC] = "Segure para inclinar os analógicos do teclado só em parte, assim o teclado anda em vez "
|
[UI_MENU_WALK_KEY_DESC] = "Segure para andar no teclado.",
|
||||||
"de correr. A intensidade do andar define quanto. Controle e mouse não são afetados.",
|
|
||||||
[UI_MENU_WALK_KEY_TAKEN] = "também %s",
|
[UI_MENU_WALK_KEY_TAKEN] = "também %s",
|
||||||
[UI_MENU_WALK_SCALE] = "Intensidade do andar",
|
[UI_MENU_WALK_SCALE] = "Intensidade do andar",
|
||||||
[UI_MENU_WALK_SCALE_DESC] = "A inclinação dos analógicos do teclado enquanto a tecla de andar está segura. Metade "
|
[UI_MENU_WALK_SCALE_DESC] = "A inclinação dos analógicos do teclado enquanto a tecla de andar está segura. Metade "
|
||||||
@@ -1474,13 +1364,9 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_HDR_HUE_DESC] = "Cores fortes como fogo e faíscas vão para o branco como na imagem SDR do próprio jogo e "
|
[UI_MENU_HDR_HUE_DESC] = "Cores fortes como fogo e faíscas vão para o branco como na imagem SDR do próprio jogo e "
|
||||||
"combinam com a luz que emitem; 0 as mantém totalmente saturadas.",
|
"combinam com a luz que emitem; 0 as mantém totalmente saturadas.",
|
||||||
[UI_MENU_SHADOW_SCALE] = "Resolução das sombras",
|
[UI_MENU_SHADOW_SCALE] = "Resolução das sombras",
|
||||||
[UI_MENU_SHADOW_SCALE_DESC] = "Desenha os mapas de sombra do sol essa quantidade de vezes maiores em cada lado "
|
[UI_MENU_SHADOW_SCALE_DESC] = "Sombras mais nítidas. Mais alto exige mais da placa de vídeo.",
|
||||||
"que os 960x960 do jogo: bordas de sombra e sombras de folhas mais nítidas. Vale no "
|
|
||||||
"próximo início.",
|
|
||||||
[UI_MENU_SHADOW_RANGE] = "Alcance das cascatas de sombra",
|
[UI_MENU_SHADOW_RANGE] = "Alcance das cascatas de sombra",
|
||||||
[UI_MENU_SHADOW_RANGE_DESC] = "Afasta os degraus em que as sombras ficam mais suaves (20, 40, 80 e 160 m no "
|
[UI_MENU_SHADOW_RANGE_DESC] = "Mantém as sombras nítidas a distâncias maiores.",
|
||||||
"jogo). Espalha o mapa de sombras por mais terreno: aumente a Resolução das sombras "
|
|
||||||
"junto. Vale no próximo início.",
|
|
||||||
[UI_MENU_CONTACT_SHADOWS] = "Sombras de contato",
|
[UI_MENU_CONTACT_SHADOWS] = "Sombras de contato",
|
||||||
[UI_MENU_CONTACT_SHADOWS_DESC] = "Pequenas sombras do sol que os mapas de sombra não pegam: nos pés, sob pedras, "
|
[UI_MENU_CONTACT_SHADOWS_DESC] = "Pequenas sombras do sol que os mapas de sombra não pegam: nos pés, sob pedras, "
|
||||||
"na grama e em dobras. Traçadas na tela depois da iluminação. Vale no próximo "
|
"na grama e em dobras. Traçadas na tela depois da iluminação. Vale no próximo "
|
||||||
@@ -1599,23 +1485,20 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_SAVE_FAILED] = "无法保存设置",
|
[UI_MENU_SAVE_FAILED] = "无法保存设置",
|
||||||
[UI_MENU_VERSION] = "NX2navi %s,游戏 %s",
|
[UI_MENU_VERSION] = "NX2navi %s,游戏 %s",
|
||||||
[UI_MENU_FULLSCREEN] = "全屏",
|
[UI_MENU_FULLSCREEN] = "全屏",
|
||||||
[UI_MENU_FULLSCREEN_DESC] = "游戏铺满屏幕;按 F11 切换。",
|
[UI_MENU_FULLSCREEN_DESC] = "全屏运行。按 F11 切换。",
|
||||||
[UI_MENU_WINDOW_SIZE] = "窗口大小",
|
[UI_MENU_WINDOW_SIZE] = "窗口大小",
|
||||||
[UI_MENU_WINDOW_SIZE_DESC] = "非全屏时游戏窗口的大小。",
|
[UI_MENU_WINDOW_SIZE_DESC] = "非全屏时的窗口大小。",
|
||||||
[UI_MENU_WINDOW_SIZE_CUSTOM] = "自定义",
|
[UI_MENU_WINDOW_SIZE_CUSTOM] = "自定义",
|
||||||
[UI_MENU_PRESENT] = "呈现模式",
|
[UI_MENU_PRESENT_DESC] = "防止画面撕裂。关闭可略微降低延迟。",
|
||||||
[UI_MENU_PRESENT_DESC] = "渲染完成的帧如何显示到屏幕上。",
|
|
||||||
[UI_MENU_PRESENT_MAILBOX] = "Mailbox",
|
[UI_MENU_PRESENT_MAILBOX] = "Mailbox",
|
||||||
[UI_MENU_PRESENT_VSYNC] = "垂直同步",
|
[UI_MENU_PRESENT_VSYNC] = "垂直同步",
|
||||||
[UI_MENU_PRESENT_IMMEDIATE] = "立即",
|
[UI_MENU_PRESENT_IMMEDIATE] = "立即",
|
||||||
[UI_MENU_PRESENT_IN_USE] = "使用中:%s",
|
[UI_MENU_PRESENT_IN_USE] = "使用中:%s",
|
||||||
[UI_MENU_GPU] = "显卡",
|
[UI_MENU_GPU] = "显卡",
|
||||||
[UI_MENU_GPU_DESC] = "用于渲染游戏的 Vulkan 设备。",
|
[UI_MENU_GPU_DESC] = "运行游戏所用的显卡。",
|
||||||
[UI_MENU_GPU_AUTO] = "自动",
|
[UI_MENU_GPU_AUTO] = "自动",
|
||||||
[UI_MENU_PERF_OVERLAY] = "性能浮层",
|
[UI_MENU_PERF_OVERLAY] = "性能浮层",
|
||||||
[UI_MENU_PERF_OVERLAY_DESC] = "在右上角显示帧率。“完整”还会显示带图表的帧时间、CPU、"
|
[UI_MENU_PERF_OVERLAY_DESC] = "显示帧率和系统信息。按 F10 切换模式。",
|
||||||
"GPU 和内存占用、温度,以及渲染线程的等待时间。"
|
|
||||||
"按 F10 循环切换模式。",
|
|
||||||
[UI_MENU_PERF_OFF] = "关",
|
[UI_MENU_PERF_OFF] = "关",
|
||||||
[UI_MENU_PERF_FPS] = "FPS",
|
[UI_MENU_PERF_FPS] = "FPS",
|
||||||
[UI_MENU_PERF_FULL] = "完整",
|
[UI_MENU_PERF_FULL] = "完整",
|
||||||
@@ -1624,35 +1507,24 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
|
|
||||||
[UI_MENU_GRAPHICS] = "画面",
|
[UI_MENU_GRAPHICS] = "画面",
|
||||||
[UI_MENU_OUTPUT_RES] = "游戏分辨率",
|
[UI_MENU_OUTPUT_RES] = "游戏分辨率",
|
||||||
[UI_MENU_OUTPUT_RES_DESC] = "游戏绘制画面和界面的尺寸。"
|
[UI_MENU_OUTPUT_RES_DESC] = "游戏的渲染分辨率。越高越吃显卡。",
|
||||||
"高于 1920 x 1080 会占用更多显存和 GPU 时间。"
|
|
||||||
"更宽的尺寸(21:9)会扩大视野,并把界面移到屏幕四角;"
|
|
||||||
"更高的尺寸(16:10、3:2)则移到上下边缘。",
|
|
||||||
[UI_MENU_RENDER_SCALE] = "3D 渲染比例",
|
[UI_MENU_RENDER_SCALE] = "3D 渲染比例",
|
||||||
[UI_MENU_RENDER_SCALE_DESC] = "3D 场景相对于游戏分辨率的尺寸;"
|
[UI_MENU_RENDER_SCALE_DESC] = "3D 场景的大小。越高越清晰,但更慢。",
|
||||||
"游戏的 FSR 会将其缩放到该尺寸。"
|
|
||||||
"高于 100% 会平滑锯齿边缘(超采样),但 GPU 开销很高。",
|
|
||||||
[UI_MENU_RENDER_SCALE_GAME] = "游戏(83%)",
|
[UI_MENU_RENDER_SCALE_GAME] = "游戏(83%)",
|
||||||
[UI_MENU_UPSCALER] = "放大到窗口",
|
[UI_MENU_UPSCALER] = "放大到窗口",
|
||||||
[UI_MENU_UPSCALER_DESC] = "游戏画面适配窗口的方式。窗口更大时:FSR 比双线性更能保留边缘和细节。"
|
[UI_MENU_UPSCALER_DESC] = "游戏画面适配窗口的方式。窗口更大时:FSR 比双线性更能保留边缘和细节。"
|
||||||
"窗口更小时(Ocarina 绘制 2560 × 1440):画面被缩小,FSR 按下方强度锐化。",
|
"窗口更小时(Ocarina 绘制 2560 × 1440):画面被缩小,FSR 按下方强度锐化。",
|
||||||
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1",
|
[UI_MENU_UPSCALER_FSR] = "AMD FSR 1",
|
||||||
[UI_MENU_UPSCALER_BILINEAR] = "双线性",
|
[UI_MENU_UPSCALER_BILINEAR] = "双线性",
|
||||||
[UI_MENU_ASPECT] = "画面宽高比",
|
|
||||||
[UI_MENU_ASPECT_DESC] = "当窗口宽高比和游戏分辨率不同时(21:9 屏幕上显示 16:9 画面):"
|
|
||||||
"用黑边保持画面比例,或拉伸铺满窗口。",
|
|
||||||
[UI_MENU_GAME_ASPECT] = "宽屏",
|
[UI_MENU_GAME_ASPECT] = "宽屏",
|
||||||
[UI_MENU_GAME_ASPECT_DESC] = "游戏绘制更宽的画面:两侧显示更多场景,界面和菜单位于中间的 16:9 区域。"
|
[UI_MENU_GAME_ASPECT_DESC] = "扩大视野。界面和菜单保持 16:9。",
|
||||||
"“窗口比例”跟随窗口(全屏时跟随显示器)。",
|
|
||||||
[UI_MENU_GAME_ASPECT_16_9] = "16:9(游戏原生)", [UI_MENU_GAME_ASPECT_WINDOW] = "窗口比例",
|
[UI_MENU_GAME_ASPECT_16_9] = "16:9(游戏原生)", [UI_MENU_GAME_ASPECT_WINDOW] = "窗口比例",
|
||||||
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
[UI_MENU_GAME_ASPECT_21_9] = "21:9", [UI_MENU_GAME_ASPECT_32_9] = "32:9",
|
||||||
[UI_MENU_ASPECT_FIT] = "黑边",
|
|
||||||
[UI_MENU_ASPECT_STRETCH] = "拉伸",
|
|
||||||
[UI_MENU_FOV] = "视野",
|
[UI_MENU_FOV] = "视野",
|
||||||
[UI_MENU_FOV_DESC] = "镜头能看到多大范围,以游戏自身视野的百分比表示。"
|
[UI_MENU_FOV_DESC] = "镜头能看到多大范围,以游戏自身视野的百分比表示。"
|
||||||
"仅限游戏版本 1.4.3。",
|
"仅限游戏版本 1.4.3。",
|
||||||
[UI_MENU_SHARPNESS] = "FSR 锐度",
|
[UI_MENU_SHARPNESS] = "FSR 锐度",
|
||||||
[UI_MENU_SHARPNESS_DESC] = "FSR 缩放后的锐化强度,画面缩小到窗口时同样生效;0 为关闭。",
|
[UI_MENU_SHARPNESS_DESC] = "FSR 的锐化强度。0 为关闭。",
|
||||||
[UI_MENU_SHARPNESS_NEEDS_FSR] = "仅限 AMD FSR 1",
|
[UI_MENU_SHARPNESS_NEEDS_FSR] = "仅限 AMD FSR 1",
|
||||||
[UI_MENU_COLOR] = "色彩",
|
[UI_MENU_COLOR] = "色彩",
|
||||||
[UI_MENU_COLOR_PRESET] = "色彩配置",
|
[UI_MENU_COLOR_PRESET] = "色彩配置",
|
||||||
@@ -1671,8 +1543,7 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_COLOR_GAMMA] = "伽马",
|
[UI_MENU_COLOR_GAMMA] = "伽马",
|
||||||
[UI_MENU_COLOR_GAMMA_DESC] = "小于 1 提亮暗部与中间调,大于 1 压暗;1 表示不调整。",
|
[UI_MENU_COLOR_GAMMA_DESC] = "小于 1 提亮暗部与中间调,大于 1 压暗;1 表示不调整。",
|
||||||
[UI_MENU_FPS_LIMIT] = "帧率上限",
|
[UI_MENU_FPS_LIMIT] = "帧率上限",
|
||||||
[UI_MENU_FPS_LIMIT_DESC] = "游戏每秒绘制的最高帧数。游戏按时钟计时,任何帧率下速度都相同。"
|
[UI_MENU_FPS_LIMIT_DESC] = "游戏的最高帧率。",
|
||||||
"不限制时以电脑能达到的最快速度绘制。",
|
|
||||||
[UI_MENU_FPS_30] = "30 FPS",
|
[UI_MENU_FPS_30] = "30 FPS",
|
||||||
[UI_MENU_FPS_40] = "40 FPS",
|
[UI_MENU_FPS_40] = "40 FPS",
|
||||||
[UI_MENU_FPS_45] = "45 FPS",
|
[UI_MENU_FPS_45] = "45 FPS",
|
||||||
@@ -1697,38 +1568,31 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_GAME_LANG_DESC] = "游戏文本和语音的语言。",
|
[UI_MENU_GAME_LANG_DESC] = "游戏文本和语音的语言。",
|
||||||
[UI_MENU_GAME_LANG_AUTO] = "自动",
|
[UI_MENU_GAME_LANG_AUTO] = "自动",
|
||||||
[UI_MENU_OPERATION_MODE] = "主机模式",
|
[UI_MENU_OPERATION_MODE] = "主机模式",
|
||||||
[UI_MENU_OPERATION_MODE_DESC] = "游戏认为自己处于底座模式还是掌机模式。",
|
[UI_MENU_OPERATION_MODE_DESC] = "以底座或掌机模式运行游戏。",
|
||||||
[UI_MENU_MODE_DOCKED] = "底座模式",
|
[UI_MENU_MODE_DOCKED] = "底座模式",
|
||||||
[UI_MENU_MODE_HANDHELD] = "掌机模式",
|
[UI_MENU_MODE_HANDHELD] = "掌机模式",
|
||||||
[UI_MENU_ASSUME_FOCUS] = "后台保持运行",
|
[UI_MENU_ASSUME_FOCUS] = "后台保持运行",
|
||||||
[UI_MENU_ASSUME_FOCUS_DESC] = "开启(默认)时,切到其他窗口游戏仍会继续运行,"
|
[UI_MENU_ASSUME_FOCUS_DESC] = "切换到其他窗口时游戏继续运行。",
|
||||||
"但键盘要等窗口回到前台才会响应。关闭时,"
|
|
||||||
"窗口失去焦点即暂停,如同在 Switch 上按 Home 键;"
|
|
||||||
"这样被打断的读取可能会永久卡住。",
|
|
||||||
[UI_MENU_VOLUME] = "音量",
|
[UI_MENU_VOLUME] = "音量",
|
||||||
[UI_MENU_MENU_SOUNDS] = "菜单音效", [UI_MENU_MENU_SOUNDS_DESC] = "此菜单音效(游戏自带的光标、确认和取消音效)的音量。0 为关闭。",
|
[UI_MENU_MENU_SOUNDS] = "菜单音效", [UI_MENU_MENU_SOUNDS_DESC] = "本菜单的音效音量。",
|
||||||
[UI_MENU_VOLUME_DESC] = "游戏的主音量。",
|
[UI_MENU_VOLUME_DESC] = "游戏总音量。",
|
||||||
[UI_MENU_MOTION] = "体感操作",
|
[UI_MENU_MOTION] = "体感操作",
|
||||||
[UI_MENU_MOTION_DESC] = "用手柄的陀螺仪瞄准。",
|
[UI_MENU_MOTION_DESC] = "使用手柄陀螺仪瞄准。",
|
||||||
[UI_MENU_RUMBLE_STRENGTH] = "振动强度",
|
[UI_MENU_RUMBLE_STRENGTH] = "振动强度",
|
||||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "手柄振动的强弱。",
|
[UI_MENU_RUMBLE_STRENGTH_DESC] = "震动强度。",
|
||||||
[UI_MENU_RUMBLE_CURVE] = "振动曲线",
|
[UI_MENU_RUMBLE_CURVE] = "振动曲线",
|
||||||
[UI_MENU_RUMBLE_CURVE_DESC] = "数值越低,弱振动越强。",
|
[UI_MENU_RUMBLE_CURVE_DESC] = "数值越低,轻微震动越强。",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS] = "扳机振动(Xbox)",
|
[UI_MENU_RUMBLE_TRIGGERS] = "扳机振动(Xbox)",
|
||||||
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Xbox 手柄的扳机也会振动。",
|
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "同时震动 Xbox 手柄的扳机。",
|
||||||
[UI_MENU_PAD_LAYOUT] = "按键布局",
|
[UI_MENU_PAD_LAYOUT] = "按键布局",
|
||||||
[UI_MENU_PAD_LAYOUT_DESC] = "哪个按键是 A。Nintendo:右侧按键,与 Switch 相同。Xbox:下方按键,"
|
[UI_MENU_PAD_LAYOUT_DESC] = "设置哪个按键作为 A 键。",
|
||||||
"与 Xbox 手柄上的标注一致(PlayStation 手柄上为叉键)。自动:"
|
|
||||||
"带 Nintendo 标注的手柄使用 Nintendo 布局,其他手柄使用 Xbox 布局。"
|
|
||||||
"游戏的按键提示始终显示 Switch 字母。",
|
|
||||||
[UI_MENU_PAD_LAYOUT_AUTO] = "自动",
|
[UI_MENU_PAD_LAYOUT_AUTO] = "自动",
|
||||||
[UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo(A 在右)",
|
[UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo(A 在右)",
|
||||||
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox(A 在下)",
|
[UI_MENU_PAD_LAYOUT_XBOX] = "Xbox(A 在下)",
|
||||||
[UI_MENU_PAD_LAYOUT_IN_USE] = "使用中:%s",
|
[UI_MENU_PAD_LAYOUT_IN_USE] = "使用中:%s",
|
||||||
[UI_MENU_GROUP_STICKS] = "摇杆",
|
[UI_MENU_GROUP_STICKS] = "摇杆",
|
||||||
[UI_MENU_LSTICK_DEADZONE] = "左摇杆死区", [UI_MENU_RSTICK_DEADZONE] = "右摇杆死区",
|
[UI_MENU_LSTICK_DEADZONE] = "左摇杆死区", [UI_MENU_RSTICK_DEADZONE] = "右摇杆死区",
|
||||||
[UI_MENU_STICK_DEADZONE_DESC] = "手柄摇杆要推动多远游戏才会响应。如果角色或视角会自己移动,"
|
[UI_MENU_STICK_DEADZONE_DESC] = "摇杆需要推动多少才生效。摇杆漂移时请调高。",
|
||||||
"请调高此值:松开摇杆,查看“当前摇杆”,把死区设得比它高几个百分点。",
|
|
||||||
[UI_MENU_STICK_DEADZONE_NOW] = "当前摇杆:%.0f %%",
|
[UI_MENU_STICK_DEADZONE_NOW] = "当前摇杆:%.0f %%",
|
||||||
[UI_MENU_MOUSE_SENS] = "鼠标视角灵敏度",
|
[UI_MENU_MOUSE_SENS] = "鼠标视角灵敏度",
|
||||||
[UI_MENU_MOUSE_SENS_DESC] = "鼠标转动视角的速度。",
|
[UI_MENU_MOUSE_SENS_DESC] = "鼠标转动视角的速度。",
|
||||||
@@ -1748,8 +1612,7 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_BINDS_TAKEN] = "%s 已从 %s 移走",
|
[UI_BINDS_TAKEN] = "%s 已从 %s 移走",
|
||||||
[UI_BINDS_SWAPPED] = "%s 已与 %s 对调",
|
[UI_BINDS_SWAPPED] = "%s 已与 %s 对调",
|
||||||
[UI_BINDS_RESET] = "重置所有按键",
|
[UI_BINDS_RESET] = "重置所有按键",
|
||||||
[UI_BINDS_RESET_DESC] = "恢复默认的键盘和手柄按键。上方的按键布局会再次生效:"
|
[UI_BINDS_RESET_DESC] = "恢复默认按键。",
|
||||||
"重映射过的手柄按键会一直保留到此次重置。",
|
|
||||||
[UI_BIND_A] = "A",
|
[UI_BIND_A] = "A",
|
||||||
[UI_BIND_B] = "B",
|
[UI_BIND_B] = "B",
|
||||||
[UI_BIND_X] = "X",
|
[UI_BIND_X] = "X",
|
||||||
@@ -1790,10 +1653,10 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_BIND_DESC_UP] = "戴上或摘下饰品。",
|
[UI_BIND_DESC_UP] = "戴上或摘下饰品。",
|
||||||
[UI_BIND_DESC_RIGHT] = "和娜薇说话。",
|
[UI_BIND_DESC_RIGHT] = "和娜薇说话。",
|
||||||
[UI_BIND_DESC_DOWN] = "更换靴子。",
|
[UI_BIND_DESC_DOWN] = "更换靴子。",
|
||||||
[UI_BIND_DESC_MOVE] = "像左摇杆一样移动林克。手柄的左摇杆始终可用。",
|
[UI_BIND_DESC_MOVE] = "移动林克。",
|
||||||
[UI_BIND_DESC_CAMERA] = "像右摇杆一样转动视角。鼠标和手柄的右摇杆始终可用。",
|
[UI_BIND_DESC_CAMERA] = "转动镜头。",
|
||||||
[UI_BIND_SHAKE] = "晃动视角摇杆",
|
[UI_BIND_SHAKE] = "晃动视角摇杆",
|
||||||
[UI_BIND_DESC_SHAKE] = "让右摇杆左右晃动。按住该键会一直晃动。",
|
[UI_BIND_DESC_SHAKE] = "晃动右摇杆。按住可持续晃动。",
|
||||||
[UI_KEY_SPACE] = "空格",
|
[UI_KEY_SPACE] = "空格",
|
||||||
[UI_KEY_TAB] = "Tab",
|
[UI_KEY_TAB] = "Tab",
|
||||||
[UI_KEY_LSHIFT] = "左 Shift",
|
[UI_KEY_LSHIFT] = "左 Shift",
|
||||||
@@ -2036,22 +1899,20 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_OV_SCALE_NONE] = "无(1:1)",
|
[UI_MENU_OV_SCALE_NONE] = "无(1:1)",
|
||||||
[UI_MENU_OV_SCALE_BILINEAR] = "双线性",
|
[UI_MENU_OV_SCALE_BILINEAR] = "双线性",
|
||||||
[UI_MENU_SHADOW_RES] = "阴影贴图尺寸",
|
[UI_MENU_SHADOW_RES] = "阴影贴图尺寸",
|
||||||
[UI_MENU_SHADOW_RES_DESC] = "太阳阴影贴图的尺寸。游戏自身的尺寸随视角变化,靠近地面时降到约 400,因此树叶阴影显得块状并且跳动;固定尺寸能让阴影稳定、更清晰。高于 1024 时阴影会占用更多 "
|
[UI_MENU_SHADOW_RES_DESC] = "阴影细节。越高越吃显卡。",
|
||||||
"GPU 时间和显存;256 比游戏自身的尺寸更粗糙,适合显存带宽不足的集成显卡。",
|
|
||||||
[UI_MENU_SHADOW_RES_GAME] = "游戏默认(会变化)",
|
[UI_MENU_SHADOW_RES_GAME] = "游戏默认(会变化)",
|
||||||
[UI_MENU_ANISO] = "纹理过滤",
|
[UI_MENU_ANISO] = "纹理过滤",
|
||||||
[UI_MENU_ANISO_DESC] = "表面纹理的各向异性过滤:以小角度看到的地面、道路和墙壁在远处依然清晰,而不会模糊。游戏:使用游戏请求的级别,与 Switch 上相同。",
|
[UI_MENU_ANISO_DESC] = "表面纹理的各向异性过滤:以小角度看到的地面、道路和墙壁在远处依然清晰,而不会模糊。游戏:使用游戏请求的级别,与 Switch 上相同。",
|
||||||
[UI_MENU_ANISO_GAME] = "游戏",
|
[UI_MENU_ANISO_GAME] = "游戏",
|
||||||
[UI_MENU_HDR_GROUP] = "HDR",
|
[UI_MENU_HDR_GROUP] = "HDR",
|
||||||
[UI_MENU_HDR] = "HDR 输出",
|
[UI_MENU_HDR] = "HDR 输出",
|
||||||
[UI_MENU_HDR_DESC] = "在 HDR 显示器上呈现明亮的高光。需要在 Windows 中开启 HDR(“使用 HDR”),或使用带色彩管理的 Wayland 合成器;否则画面保持 "
|
[UI_MENU_HDR_DESC] = "在 HDR 显示器上呈现更亮的高光。请先在 Windows 中开启 HDR。",
|
||||||
"SDR。重启后生效。上方的色彩配置用于 SDR,在 HDR 下不使用。",
|
|
||||||
[UI_MENU_HDR_PEAK] = "峰值亮度",
|
[UI_MENU_HDR_PEAK] = "峰值亮度",
|
||||||
[UI_MENU_HDR_PEAK_DESC] = "显示器的峰值亮度(尼特);最亮的高光止于此。",
|
[UI_MENU_HDR_PEAK_DESC] = "显示器的峰值亮度(尼特)。",
|
||||||
[UI_MENU_HDR_GAME] = "游戏亮度",
|
[UI_MENU_HDR_GAME] = "游戏亮度",
|
||||||
[UI_MENU_HDR_GAME_DESC] = "画面白色(纸白)的尼特值。203 为 HDR 参考值;在明亮的房间里可调高。",
|
[UI_MENU_HDR_GAME_DESC] = "游戏中白色的亮度(尼特)。",
|
||||||
[UI_MENU_HDR_UI] = "HUD 和菜单亮度",
|
[UI_MENU_HDR_UI] = "HUD 和菜单亮度",
|
||||||
[UI_MENU_HDR_UI_DESC] = "HUD 和本菜单白色的尼特值。",
|
[UI_MENU_HDR_UI_DESC] = "界面和本菜单的亮度(尼特)。",
|
||||||
[UI_MENU_PROMPTS] = "按键提示",
|
[UI_MENU_PROMPTS] = "按键提示",
|
||||||
[UI_MENU_PROMPTS_DESC] = "游戏的按键提示显示哪种手柄的按键。Nintendo:游戏原有的提示。Xbox:LB、RB、LT、RT、Menu、View 和十字键,以及上方布局所按下的按键上标注的 "
|
[UI_MENU_PROMPTS_DESC] = "游戏的按键提示显示哪种手柄的按键。Nintendo:游戏原有的提示。Xbox:LB、RB、LT、RT、Menu、View 和十字键,以及上方布局所按下的按键上标注的 "
|
||||||
"A、B、X、Y(使用 Nintendo(A 在右)时右侧按键标为 B,因此 A 的提示显示 "
|
"A、B、X、Y(使用 Nintendo(A 在右)时右侧按键标为 B,因此 A 的提示显示 "
|
||||||
@@ -2075,12 +1936,13 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_RESTART] = "立即重启",
|
[UI_MENU_RESTART] = "立即重启",
|
||||||
[UI_MENU_RESTART_DESC] = "关闭游戏并以新的按键提示重新启动。上次存档之后的进度将会丢失。",
|
[UI_MENU_RESTART_DESC] = "关闭游戏并以新的按键提示重新启动。上次存档之后的进度将会丢失。",
|
||||||
[UI_MENU_RESTART_CONFIRM] = "现在重启游戏?上次存档之后的进度将会丢失。",
|
[UI_MENU_RESTART_CONFIRM] = "现在重启游戏?上次存档之后的进度将会丢失。",
|
||||||
|
[UI_MENU_QUIT_CONFIRM] = "退出游戏?上次存档之后的进度将会丢失。",
|
||||||
[UI_MENU_RESTART_YES] = "重启",
|
[UI_MENU_RESTART_YES] = "重启",
|
||||||
[UI_MENU_RESTART_SAVING] = "游戏正在存档:稍后即可重启。",
|
[UI_MENU_RESTART_SAVING] = "游戏正在存档:稍后即可重启。",
|
||||||
[UI_MENU_STICK_SENS] = "摇杆镜头速度",
|
[UI_MENU_STICK_SENS] = "摇杆镜头速度",
|
||||||
[UI_MENU_STICK_SENS_DESC] = "在游戏的五档镜头灵敏度下,按倍数调整右摇杆的镜头转动速度(包括最高速度)。鼠标使用自己的设置。",
|
[UI_MENU_STICK_SENS_DESC] = "右摇杆的镜头速度。",
|
||||||
[UI_MENU_WALK_KEY] = "步行键",
|
[UI_MENU_WALK_KEY] = "步行键",
|
||||||
[UI_MENU_WALK_KEY_DESC] = "按住时键盘模拟的摇杆只推到一部分,使键盘操作走路而不是奔跑。推动幅度由步行幅度决定。手柄和鼠标不受影响。",
|
[UI_MENU_WALK_KEY_DESC] = "按住可用键盘步行。",
|
||||||
[UI_MENU_WALK_KEY_TAKEN] = "同时为 %s",
|
[UI_MENU_WALK_KEY_TAKEN] = "同时为 %s",
|
||||||
[UI_MENU_WALK_SCALE] = "步行幅度",
|
[UI_MENU_WALK_SCALE] = "步行幅度",
|
||||||
[UI_MENU_WALK_SCALE_DESC] = "按住步行键时键盘摇杆的推动幅度。一半为走路,推满为奔跑。",
|
[UI_MENU_WALK_SCALE_DESC] = "按住步行键时键盘摇杆的推动幅度。一半为走路,推满为奔跑。",
|
||||||
@@ -2088,9 +1950,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
|||||||
[UI_MENU_HDR_HUE] = "高光色调校正",
|
[UI_MENU_HDR_HUE] = "高光色调校正",
|
||||||
[UI_MENU_HDR_HUE_DESC] = "火焰、火花等明亮色彩像游戏自身的 SDR 画面一样趋向白色,与它们发出的光一致;0 保持完全饱和。",
|
[UI_MENU_HDR_HUE_DESC] = "火焰、火花等明亮色彩像游戏自身的 SDR 画面一样趋向白色,与它们发出的光一致;0 保持完全饱和。",
|
||||||
[UI_MENU_SHADOW_SCALE] = "阴影分辨率",
|
[UI_MENU_SHADOW_SCALE] = "阴影分辨率",
|
||||||
[UI_MENU_SHADOW_SCALE_DESC] = "将太阳阴影贴图的每条边绘制为游戏 960x960 的若干倍:阴影边缘和树叶阴影更清晰。下次启动时生效。",
|
[UI_MENU_SHADOW_SCALE_DESC] = "让阴影更清晰。越高越吃显卡。",
|
||||||
[UI_MENU_SHADOW_RANGE] = "阴影级联范围",
|
[UI_MENU_SHADOW_RANGE] = "阴影级联范围",
|
||||||
[UI_MENU_SHADOW_RANGE_DESC] = "把阴影变柔和的分界(游戏中为 20、40、80 和 160 米)推得更远。阴影贴图会覆盖更大的地面,请同时提高阴影分辨率。下次启动时生效。",
|
[UI_MENU_SHADOW_RANGE_DESC] = "让远处的阴影保持清晰。",
|
||||||
[UI_MENU_CONTACT_SHADOWS] = "接触阴影",
|
[UI_MENU_CONTACT_SHADOWS] = "接触阴影",
|
||||||
[UI_MENU_CONTACT_SHADOWS_DESC] = "阴影贴图遗漏的细小太阳阴影:脚下、石头下、草丛和褶皱中。在光照之后于屏幕空间追踪。下次启动时生效。",
|
[UI_MENU_CONTACT_SHADOWS_DESC] = "阴影贴图遗漏的细小太阳阴影:脚下、石头下、草丛和褶皱中。在光照之后于屏幕空间追踪。下次启动时生效。",
|
||||||
[UI_MENU_PCSS] = "柔和阴影",
|
[UI_MENU_PCSS] = "柔和阴影",
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ typedef enum {
|
|||||||
// Screen
|
// Screen
|
||||||
UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC,
|
UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC,
|
||||||
UI_MENU_WINDOW_SIZE, UI_MENU_WINDOW_SIZE_DESC, UI_MENU_WINDOW_SIZE_CUSTOM,
|
UI_MENU_WINDOW_SIZE, UI_MENU_WINDOW_SIZE_DESC, UI_MENU_WINDOW_SIZE_CUSTOM,
|
||||||
UI_MENU_PRESENT, UI_MENU_PRESENT_DESC, UI_MENU_PRESENT_MAILBOX, UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_IMMEDIATE,
|
UI_MENU_PRESENT_DESC, UI_MENU_PRESENT_MAILBOX, UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_IMMEDIATE,
|
||||||
UI_MENU_PRESENT_IN_USE, // "in use: %s" under the value when the swapchain got another mode than the setting
|
UI_MENU_PRESENT_IN_USE, // "in use: %s" under the value when the swapchain got another mode than the setting
|
||||||
UI_MENU_GPU, UI_MENU_GPU_DESC, UI_MENU_GPU_AUTO,
|
UI_MENU_GPU, UI_MENU_GPU_DESC, UI_MENU_GPU_AUTO,
|
||||||
UI_MENU_PERF_OVERLAY, UI_MENU_PERF_OVERLAY_DESC, UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL,
|
UI_MENU_PERF_OVERLAY, UI_MENU_PERF_OVERLAY_DESC, UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL,
|
||||||
@@ -36,7 +36,6 @@ typedef enum {
|
|||||||
UI_MENU_OUTPUT_RES, UI_MENU_OUTPUT_RES_DESC,
|
UI_MENU_OUTPUT_RES, UI_MENU_OUTPUT_RES_DESC,
|
||||||
UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME,
|
UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME,
|
||||||
UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR,
|
UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR,
|
||||||
UI_MENU_ASPECT, UI_MENU_ASPECT_DESC, UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH,
|
|
||||||
UI_MENU_GAME_ASPECT, UI_MENU_GAME_ASPECT_DESC, UI_MENU_GAME_ASPECT_16_9, UI_MENU_GAME_ASPECT_WINDOW,
|
UI_MENU_GAME_ASPECT, UI_MENU_GAME_ASPECT_DESC, UI_MENU_GAME_ASPECT_16_9, UI_MENU_GAME_ASPECT_WINDOW,
|
||||||
UI_MENU_GAME_ASPECT_21_9, UI_MENU_GAME_ASPECT_32_9,
|
UI_MENU_GAME_ASPECT_21_9, UI_MENU_GAME_ASPECT_32_9,
|
||||||
UI_MENU_FOV, UI_MENU_FOV_DESC,
|
UI_MENU_FOV, UI_MENU_FOV_DESC,
|
||||||
@@ -106,7 +105,7 @@ typedef enum {
|
|||||||
UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE,
|
UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE,
|
||||||
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
|
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
|
||||||
// "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO)
|
// "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO)
|
||||||
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
|
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_QUIT_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
|
||||||
UI_MENU_GROUP_STICKS, UI_MENU_LSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC,
|
UI_MENU_GROUP_STICKS, UI_MENU_LSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC,
|
||||||
UI_MENU_STICK_DEADZONE_NOW, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC,
|
UI_MENU_STICK_DEADZONE_NOW, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC,
|
||||||
UI_MENU_MOUSE_MODE, UI_MENU_MOUSE_MODE_DESC, UI_MENU_MOUSE_STICK, UI_MENU_MOUSE_DIRECT,
|
UI_MENU_MOUSE_MODE, UI_MENU_MOUSE_MODE_DESC, UI_MENU_MOUSE_STICK, UI_MENU_MOUSE_DIRECT,
|
||||||
@@ -246,6 +245,9 @@ typedef enum {
|
|||||||
UI_MENU_UPSCALING, UI_MENU_UPSCALING_DESC, UI_MENU_UPSCALING_DLSS_NOTE, UI_MENU_FRAMEGEN, UI_MENU_FRAMEGEN_DESC,
|
UI_MENU_UPSCALING, UI_MENU_UPSCALING_DESC, UI_MENU_UPSCALING_DLSS_NOTE, UI_MENU_FRAMEGEN, UI_MENU_FRAMEGEN_DESC,
|
||||||
UI_MENU_FRAMEGEN_OFF, UI_MENU_FRAMEGEN_NOTE, UI_MENU_FRAMEGEN_NEEDS, UI_MENU_HDR_NOTE, UI_MENU_HDR_ENHANCED, UI_MENU_HDR_NATIVE,
|
UI_MENU_FRAMEGEN_OFF, UI_MENU_FRAMEGEN_NOTE, UI_MENU_FRAMEGEN_NEEDS, UI_MENU_HDR_NOTE, UI_MENU_HDR_ENHANCED, UI_MENU_HDR_NATIVE,
|
||||||
UI_MENU_GAME_RES, UI_MENU_GAME_RES_DESC, UI_MENU_GAME_RES_NATIVE,
|
UI_MENU_GAME_RES, UI_MENU_GAME_RES_DESC, UI_MENU_GAME_RES_NATIVE,
|
||||||
|
// the same rows' texts on a GPU DLSS does not run on (not NVIDIA): the menu leaves DLSS out there
|
||||||
|
UI_MENU_UPSCALING_DESC_FSR, UI_MENU_UPSCALING_FSR_NOTE, UI_MENU_FRAMEGEN_DESC_FSR, UI_MENU_FRAMEGEN_NOTE_FSR,
|
||||||
|
UI_MENU_FRAMEGEN_NEEDS_FSR,
|
||||||
UI_TEXT_COUNT
|
UI_TEXT_COUNT
|
||||||
} UiTextId;
|
} UiTextId;
|
||||||
|
|
||||||
|
|||||||
@@ -2032,6 +2032,7 @@ static struct {
|
|||||||
uint32_t left; // prebuild jobs queued or running
|
uint32_t left; // prebuild jobs queued or running
|
||||||
uint32_t built, failed, promoted;
|
uint32_t built, failed, promoted;
|
||||||
double t0; // now_ms() when the prebuild started
|
double t0; // now_ms() when the prebuild started
|
||||||
|
double until; // now_ms() after which the boot builders stop (comment at prewarm_run); 0 none
|
||||||
} K = {.io = PLAT_MUTEX_INIT};
|
} K = {.io = PLAT_MUTEX_INIT};
|
||||||
|
|
||||||
static uint64_t rec_hash(const KeyRec *r) {
|
static uint64_t rec_hash(const KeyRec *r) {
|
||||||
@@ -2637,11 +2638,12 @@ VkPipeline vk_pipeline_graphics_async(const VkPipeState *s, const VkPipeInfo **i
|
|||||||
|
|
||||||
static int id_cmp(const void *x, const void *y) { return memcmp(x, y, 32); }
|
static int id_cmp(const void *x, const void *y) { return memcmp(x, y, 32); }
|
||||||
|
|
||||||
// Builds queued prebuild jobs until the low queue is empty, beside the pipe_worker pool (same bookkeeping).
|
// Builds queued prebuild jobs until the low queue is empty or K.until passes, beside the pipe_worker pool (same
|
||||||
|
// bookkeeping). Jobs left queued at K.until stay for the pool.
|
||||||
static void warm_builder(void *arg) {
|
static void warm_builder(void *arg) {
|
||||||
(void)arg;
|
(void)arg;
|
||||||
plat_mutex_lock(&P.lock);
|
plat_mutex_lock(&P.lock);
|
||||||
while (A.low) {
|
while (A.low && !(K.until && now_ms() >= K.until)) {
|
||||||
Job *j = A.low;
|
Job *j = A.low;
|
||||||
if ((A.low = j->next)) A.low->prev = NULL;
|
if ((A.low = j->next)) A.low->prev = NULL;
|
||||||
else A.low_tail = NULL;
|
else A.low_tail = NULL;
|
||||||
@@ -2686,6 +2688,16 @@ void vk_pipeline_prewarm_progress(VkPrewarmProgress *p) {
|
|||||||
|
|
||||||
static void prewarm_run(void);
|
static void prewarm_run(void);
|
||||||
|
|
||||||
|
// The boot's share of the pipeline prebuild with the graphics pipeline library. The boot builds the recorded
|
||||||
|
// pipelines in record order, so those met first in play (the title screen, the first places) come first, for at most
|
||||||
|
// this long after the shaders are ready; the rest stay queued for the pool workers, which build them below normal
|
||||||
|
// priority while the game runs. A draw that meets one of them before it is built gets a pipeline linked from stage
|
||||||
|
// libraries at once (gpl_link), as for any new pipeline in play. After a driver update, when every pipeline is built
|
||||||
|
// from nothing, the boot thus waits this long instead of for all of them (15 minutes and more with a long play
|
||||||
|
// history). Without the library a draw would have to wait for a whole build, so the boot waits for all; so it does
|
||||||
|
// with NX2NAVI_PREWARM_FULL=1.
|
||||||
|
#define PREWARM_PIPE_MS 20000.0
|
||||||
|
|
||||||
void vk_pipeline_prewarm(void) {
|
void vk_pipeline_prewarm(void) {
|
||||||
prewarm_run();
|
prewarm_run();
|
||||||
__atomic_store_n(&pw_phase, 3, __ATOMIC_RELEASE);
|
__atomic_store_n(&pw_phase, 3, __ATOMIC_RELEASE);
|
||||||
@@ -2777,6 +2789,8 @@ static void prewarm_run(void) {
|
|||||||
__atomic_store_n(&pw_pipe_done, 0, __ATOMIC_RELAXED);
|
__atomic_store_n(&pw_pipe_done, 0, __ATOMIC_RELAXED);
|
||||||
__atomic_store_n(&pw_pipe_total, (int64_t)queued, __ATOMIC_RELAXED);
|
__atomic_store_n(&pw_pipe_total, (int64_t)queued, __ATOMIC_RELAXED);
|
||||||
__atomic_store_n(&pw_phase, 2, __ATOMIC_RELEASE);
|
__atomic_store_n(&pw_phase, 2, __ATOMIC_RELEASE);
|
||||||
|
const char *full = cfg_get("NX2NAVI_PREWARM_FULL");
|
||||||
|
K.until = P.gpl && !(full && !strcmp(full, "1")) ? now_ms() + PREWARM_PIPE_MS : 0; // before the builders start
|
||||||
PlatThread *t[64];
|
PlatThread *t[64];
|
||||||
int nt = 0;
|
int nt = 0;
|
||||||
for (int i = 0; i < cpus && i < 64 && queued; i++)
|
for (int i = 0; i < cpus && i < 64 && queued; i++)
|
||||||
@@ -2793,10 +2807,16 @@ static void prewarm_run(void) {
|
|||||||
}
|
}
|
||||||
__atomic_store_n(&pw_pipe_done, (int64_t)queued, __ATOMIC_RELAXED);
|
__atomic_store_n(&pw_pipe_done, (int64_t)queued, __ATOMIC_RELAXED);
|
||||||
plat_mutex_lock(&P.lock);
|
plat_mutex_lock(&P.lock);
|
||||||
while (K.left) plat_cond_wait(&done_cv, &P.lock); // jobs a pool worker took
|
uint32_t later = 0;
|
||||||
rt_log("vk_pipeline: prewarm: %zu records in %s: %u pipelines built, %u failed, %u already built, %u dropped "
|
for (Job *j = A.low; j; j = j->next) later += j->prebuild;
|
||||||
"(shader neither cached nor stored); shaders %.0f ms, pipelines %.0f ms on %d threads, total %.0f ms",
|
if (!later) // all built: wait for those a pool worker took
|
||||||
n, K.path, K.built, K.failed, known, dropped, t1 - t0, now_ms() - t1, nt, now_ms() - t0);
|
while (K.left) plat_cond_wait(&done_cv, &P.lock);
|
||||||
|
else // the boot's time is up: the pool builds the rest while the game runs
|
||||||
|
plat_cond_broadcast(&work_cv);
|
||||||
|
rt_log("vk_pipeline: prewarm: %zu records in %s: %u pipelines built, %u left to build in the background, %u "
|
||||||
|
"failed, %u already built, %u dropped (shader neither cached nor stored); shaders %.0f ms, pipelines %.0f "
|
||||||
|
"ms on %d threads, total %.0f ms", n, K.path, K.built, later, K.failed, known, dropped, t1 - t0,
|
||||||
|
now_ms() - t1, nt, now_ms() - t0);
|
||||||
free(K.file);
|
free(K.file);
|
||||||
K.file = NULL;
|
K.file = NULL;
|
||||||
plat_mutex_unlock(&P.lock);
|
plat_mutex_unlock(&P.lock);
|
||||||
|
|||||||
@@ -4,27 +4,32 @@ Run: python tests/launcher_test.py (Python 3.14 for the zstd tests; the window
|
|||||||
|
|
||||||
- versions, settings
|
- versions, settings
|
||||||
- toolchain: the package database, dependency resolution and an install from a local fake repository
|
- toolchain: the package database, dependency resolution and an install from a local fake repository
|
||||||
- net: downloads that resume, check their sha256 and stop on cancel
|
- net: downloads that resume, check their sha256 and stop on cancel; the certificate checks against a local HTTPS
|
||||||
|
server with certificates the openssl command makes (an expired one, an unknown one), the clock comparison
|
||||||
- feed: GitHub releases (stable, preview, private with a token) and a plain manifest URL, served locally
|
- feed: GitHub releases (stable, preview, private with a token) and a plain manifest URL, served locally
|
||||||
- updater: staging a release, switching, rollback, pruning, refusing unsafe archives
|
- updater: staging a release, switching, rollback, pruning, refusing unsafe archives
|
||||||
- gamefiles: the .bfotf font wrapping and zstd dictionaries, on a font of this system made into a fake RomFS
|
- gamefiles: the .bfotf font wrapping and zstd dictionaries, on a font of this system made into a fake RomFS
|
||||||
- make_game.py: a synthetic .nup through the check, exefs and romfs steps with --events, skipped steps on a second
|
- make_game.py: a synthetic .nup through the check, exefs and romfs steps with --events, skipped steps on a second
|
||||||
run, --rebuild without the game files, and the object cache of the compile step with the system's C compiler
|
run, --rebuild without the game files, the object cache of the compile step with the system's C compiler, and its
|
||||||
|
windres call under folders with spaces (a script in windres's place)
|
||||||
- jobs: an install driven by a fake make_game.py
|
- jobs: an install driven by a fake make_game.py
|
||||||
- the window: --selftest draws every screen (skipped without a display)
|
- the window: --selftest draws every screen (skipped without a display)
|
||||||
"""
|
"""
|
||||||
|
import contextlib
|
||||||
import hashlib
|
import hashlib
|
||||||
import http.server
|
import http.server
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
import ssl
|
||||||
import struct
|
import struct
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tarfile
|
import tarfile
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
import zipfile
|
import zipfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -33,7 +38,7 @@ ROOT = Path(__file__).resolve().parent.parent
|
|||||||
sys.path.insert(0, str(ROOT))
|
sys.path.insert(0, str(ROOT))
|
||||||
sys.path.insert(0, str(ROOT / 'tools'))
|
sys.path.insert(0, str(ROOT / 'tools'))
|
||||||
|
|
||||||
from launcher import build, feed, gamefiles, jobs, net, settings, toolchain, updater, versions # noqa: E402
|
from launcher import build, feed, gamefiles, jobs, net, saves, settings, toolchain, updater, versions # noqa: E402
|
||||||
from launcher.context import Context # noqa: E402
|
from launcher.context import Context # noqa: E402
|
||||||
from launcher.paths import Layout # noqa: E402
|
from launcher.paths import Layout # noqa: E402
|
||||||
|
|
||||||
@@ -46,9 +51,11 @@ except ImportError:
|
|||||||
# ---------------------------------------------------------------- helpers
|
# ---------------------------------------------------------------- helpers
|
||||||
|
|
||||||
class Server:
|
class Server:
|
||||||
"""A local HTTP server for a folder, with extra routes (path -> (status, headers, body)) and Range support."""
|
"""A local HTTP server for a folder, with extra routes (path -> (status, headers, body)) and Range support; HTTPS
|
||||||
|
with cert (a PEM file holding the certificate and its key). HEAD answers a redirect to https, as a server that
|
||||||
|
serves only HTTPS does."""
|
||||||
|
|
||||||
def __init__(self, folder, routes=None):
|
def __init__(self, folder, routes=None, cert=None):
|
||||||
folder, routes = Path(folder), routes if routes is not None else {}
|
folder, routes = Path(folder), routes if routes is not None else {}
|
||||||
self.hits = []
|
self.hits = []
|
||||||
server = self
|
server = self
|
||||||
@@ -57,6 +64,13 @@ class Server:
|
|||||||
def log_message(self, *a):
|
def log_message(self, *a):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def do_HEAD(self):
|
||||||
|
server.hits.append((self.path, dict(self.headers)))
|
||||||
|
self.send_response(301)
|
||||||
|
self.send_header('Location', 'https://127.0.0.1' + self.path)
|
||||||
|
self.send_header('Content-Length', '0')
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
server.hits.append((self.path, dict(self.headers)))
|
server.hits.append((self.path, dict(self.headers)))
|
||||||
if self.path in routes:
|
if self.path in routes:
|
||||||
@@ -93,16 +107,65 @@ class Server:
|
|||||||
|
|
||||||
self.httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), H)
|
self.httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), H)
|
||||||
self.url = f'http://127.0.0.1:{self.httpd.server_address[1]}/'
|
self.url = f'http://127.0.0.1:{self.httpd.server_address[1]}/'
|
||||||
|
if cert:
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
ctx.load_cert_chain(cert)
|
||||||
|
self.httpd.socket = ctx.wrap_socket(self.httpd.socket, server_side=True)
|
||||||
|
self.url = 'https' + self.url[4:]
|
||||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self.httpd.shutdown()
|
self.httpd.shutdown()
|
||||||
|
self.httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
def sha(data):
|
def sha(data):
|
||||||
return hashlib.sha256(data).hexdigest()
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def make_cert(folder, start, end):
|
||||||
|
"""A self-signed certificate for 127.0.0.1 valid from start to end (epoch seconds), with its key, as one PEM file
|
||||||
|
in the new folder; made by the openssl command (its ca command takes any dates, its req command none in the
|
||||||
|
past)."""
|
||||||
|
folder = Path(folder)
|
||||||
|
folder.mkdir(parents=True)
|
||||||
|
(folder / 'index.txt').write_text('')
|
||||||
|
(folder / 'serial.txt').write_text('01\n')
|
||||||
|
(folder / 'ca.cnf').write_text('[ca]\ndefault_ca = d\n[d]\ndatabase = index.txt\nserial = serial.txt\n'
|
||||||
|
'new_certs_dir = .\ndefault_md = sha256\npolicy = p\ncopy_extensions = copy\n'
|
||||||
|
'unique_subject = no\n[p]\ncommonName = supplied\n')
|
||||||
|
def stamp(t):
|
||||||
|
return time.strftime('%Y%m%d%H%M%SZ', time.gmtime(t))
|
||||||
|
|
||||||
|
def run(*args):
|
||||||
|
subprocess.run(['openssl', *args], cwd=folder, check=True, capture_output=True)
|
||||||
|
|
||||||
|
run('req', '-new', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-keyout', 'key.pem',
|
||||||
|
'-out', 'req.csr', '-subj', '/CN=127.0.0.1', '-addext', 'subjectAltName=IP:127.0.0.1')
|
||||||
|
run('ca', '-batch', '-config', 'ca.cnf', '-selfsign', '-keyfile', 'key.pem', '-in', 'req.csr', '-out', 'cert.pem',
|
||||||
|
'-startdate', stamp(start), '-enddate', stamp(end), '-notext')
|
||||||
|
pem = folder / 'both.pem'
|
||||||
|
pem.write_bytes((folder / 'cert.pem').read_bytes() + (folder / 'key.pem').read_bytes())
|
||||||
|
return pem
|
||||||
|
|
||||||
|
|
||||||
|
class CountingContext(ssl.SSLContext):
|
||||||
|
"""A client SSLContext that counts its handshakes."""
|
||||||
|
|
||||||
|
def wrap_socket(self, *args, **kwargs):
|
||||||
|
self.handshakes = getattr(self, 'handshakes', 0) + 1
|
||||||
|
return super().wrap_socket(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def client_context(trust=None):
|
||||||
|
ctx = CountingContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
if trust:
|
||||||
|
ctx.load_verify_locations(cafile=trust)
|
||||||
|
else:
|
||||||
|
ctx.load_default_certs()
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
def tar_bytes(files, compress=True):
|
def tar_bytes(files, compress=True):
|
||||||
"""A tar (zstd-compressed when the stdlib has zstd, else gzip) of {name: bytes}."""
|
"""A tar (zstd-compressed when the stdlib has zstd, else gzip) of {name: bytes}."""
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
@@ -150,6 +213,24 @@ def fake_repo(folder, damage=None):
|
|||||||
(folder / 'ucrt64.db').write_bytes(tar_bytes(entries))
|
(folder / 'ucrt64.db').write_bytes(tar_bytes(entries))
|
||||||
|
|
||||||
|
|
||||||
|
def fake_fast_repo(folder, clang_version='1.0-1'):
|
||||||
|
"""The CLANG64 packages toolchain.FAST_PACKAGES names, in folder/clang64."""
|
||||||
|
folder = folder / 'clang64'
|
||||||
|
folder.mkdir()
|
||||||
|
P = toolchain.FAST_PREFIX
|
||||||
|
files = {'clang': {'clang64/bin/clang.exe': b'clang64', 'clang64/bin/clang-repl.exe': b'not needed',
|
||||||
|
'clang64/lib/clang/23/include/immintrin.h': b'// x86'},
|
||||||
|
'llvm-libs': {'clang64/bin/libLLVM-23.dll': b'llvm', 'clang64/share/doc/x': b'skipped'}}
|
||||||
|
entries = {}
|
||||||
|
for root in toolchain.FAST_PACKAGES:
|
||||||
|
name, ver = P + root, clang_version if root == 'clang' else '1.0-1'
|
||||||
|
fn = f'{name}-{ver}-any.pkg.tar.zst'
|
||||||
|
data = tar_bytes({'.PKGINFO': b'pkg', **files.get(root, {f'clang64/bin/{root}.dll': b'dll'})})
|
||||||
|
(folder / fn).write_bytes(data)
|
||||||
|
entries[f'{name}-{ver}/desc'] = desc(name, ver, fn, data, (), ())
|
||||||
|
(folder / 'clang64.db').write_bytes(tar_bytes(entries))
|
||||||
|
|
||||||
|
|
||||||
class Tmp(unittest.TestCase):
|
class Tmp(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.tmp = Path(tempfile.mkdtemp(prefix='nx2navi-test-'))
|
self.tmp = Path(tempfile.mkdtemp(prefix='nx2navi-test-'))
|
||||||
@@ -215,6 +296,39 @@ class ToolchainTest(Tmp):
|
|||||||
self.assertEqual(len(srv.hits), hits)
|
self.assertEqual(len(srv.hits), hits)
|
||||||
self.assertEqual(toolchain.lock_digest(lock), toolchain.installed(self.layout)['digest'])
|
self.assertEqual(toolchain.lock_digest(lock), toolchain.installed(self.layout)['digest'])
|
||||||
|
|
||||||
|
def test_fast_clang_beside(self):
|
||||||
|
"""CLANG64's clang goes into msys64/clang64 when its version matches UCRT64's: clang.exe, the DLLs and its
|
||||||
|
headers only."""
|
||||||
|
repo = self.tmp / 'repo'
|
||||||
|
repo.mkdir()
|
||||||
|
fake_repo(repo)
|
||||||
|
fake_fast_repo(repo)
|
||||||
|
srv = Server(repo)
|
||||||
|
self.addCleanup(srv.close)
|
||||||
|
lock = toolchain.make_lock(srv.url, fast_repo=srv.url + 'clang64/')
|
||||||
|
self.assertEqual(lock.get('fast_repo'), srv.url + 'clang64/')
|
||||||
|
self.assertEqual(sum(p.get('env') == 'clang64' for p in lock['packages']), len(toolchain.FAST_PACKAGES))
|
||||||
|
toolchain.install(self.layout, lock, log=lambda m: None)
|
||||||
|
fast = self.layout.msys.parent / 'clang64'
|
||||||
|
self.assertEqual((fast / 'bin' / 'clang.exe').read_bytes(), b'clang64')
|
||||||
|
self.assertTrue((fast / 'bin' / 'libLLVM-23.dll').is_file())
|
||||||
|
self.assertTrue((fast / 'lib' / 'clang' / '23' / 'include' / 'immintrin.h').is_file())
|
||||||
|
self.assertFalse((fast / 'bin' / 'clang-repl.exe').exists())
|
||||||
|
self.assertFalse((fast / 'share').exists())
|
||||||
|
self.assertTrue(toolchain.is_current(self.layout, lock))
|
||||||
|
|
||||||
|
def test_fast_clang_left_out_on_another_version(self):
|
||||||
|
repo = self.tmp / 'repo'
|
||||||
|
repo.mkdir()
|
||||||
|
fake_repo(repo)
|
||||||
|
fake_fast_repo(repo, clang_version='2.0-1')
|
||||||
|
srv = Server(repo)
|
||||||
|
self.addCleanup(srv.close)
|
||||||
|
lock = toolchain.make_lock(srv.url, fast_repo=srv.url + 'clang64/')
|
||||||
|
self.assertNotIn('fast_repo', lock)
|
||||||
|
self.assertIn('2.0-1', lock['fast_skipped'])
|
||||||
|
self.assertFalse(any(p.get('env') for p in lock['packages']))
|
||||||
|
|
||||||
def test_damaged_package_refused(self):
|
def test_damaged_package_refused(self):
|
||||||
repo = self.tmp / 'repo'
|
repo = self.tmp / 'repo'
|
||||||
repo.mkdir()
|
repo.mkdir()
|
||||||
@@ -253,6 +367,79 @@ class NetTest(Tmp):
|
|||||||
with self.assertRaises(net.DownloadError):
|
with self.assertRaises(net.DownloadError):
|
||||||
net.download(srv.url + 'missing.bin', self.tmp / 'out' / 'm.bin')
|
net.download(srv.url + 'missing.bin', self.tmp / 'out' / 'm.bin')
|
||||||
|
|
||||||
|
def test_server_clock(self):
|
||||||
|
srv = Server(self.tmp)
|
||||||
|
self.addCleanup(srv.close)
|
||||||
|
t = net.server_clock(srv.url) # the Date of the redirect to https, which is not followed
|
||||||
|
self.assertIsNotNone(t)
|
||||||
|
self.assertLess(abs(t - time.time()), 5)
|
||||||
|
self.assertEqual([h[0] for h in srv.hits], ['/'])
|
||||||
|
srv.close()
|
||||||
|
self.assertIsNone(net.server_clock(srv.url, timeout=2))
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(shutil.which('openssl'), 'needs the openssl command')
|
||||||
|
class CertificateTest(Tmp):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
saved = net._CHECKS, dict(net._ACCEPTED), net.server_clock
|
||||||
|
self.addCleanup(lambda: setattr(net, '_CHECKS', saved[0]) or setattr(net, '_ACCEPTED', saved[1]) or
|
||||||
|
setattr(net, 'server_clock', saved[2]))
|
||||||
|
net._ACCEPTED = {}
|
||||||
|
self.data = os.urandom(100_000)
|
||||||
|
(self.tmp / 'f.bin').write_bytes(self.data)
|
||||||
|
|
||||||
|
def serve(self, start, end):
|
||||||
|
cert = make_cert(self.tmp / f'cert{start}', start, end)
|
||||||
|
srv = Server(self.tmp, cert=cert)
|
||||||
|
self.addCleanup(srv.close)
|
||||||
|
return srv, cert
|
||||||
|
|
||||||
|
def test_refused_certificate(self):
|
||||||
|
"""An expired certificate in the trust store: the player's 'certificate has expired', at once, not retried,
|
||||||
|
with the advice the server's clock calls for."""
|
||||||
|
now = time.time()
|
||||||
|
srv, cert = self.serve(now - 400 * 86400, now - 300 * 86400)
|
||||||
|
check = client_context(trust=cert)
|
||||||
|
net._CHECKS = [("Python's check", check)]
|
||||||
|
asked = []
|
||||||
|
cases = ((now + 400 * 86400, "This PC's clock reads"), (now - 3 * 86400, 'set the date, time and time zone'),
|
||||||
|
(now + 60, "This PC's clock agrees with 127.0.0.1's. Security software"),
|
||||||
|
(None, "Check that this PC's date, time and time zone are right"))
|
||||||
|
for i, (theirs, says) in enumerate(cases):
|
||||||
|
net.server_clock = lambda url, timeout=10, version='dev', t=theirs: asked.append(url) or t
|
||||||
|
t0 = time.time()
|
||||||
|
with self.assertRaises(net.CertificateError) as cm:
|
||||||
|
net.download(srv.url + 'f.bin', self.tmp / 'out' / 'f.bin', sha256=sha(self.data))
|
||||||
|
self.assertLess(time.time() - t0, 5) # no retries: the answer would be the same
|
||||||
|
msg = str(cm.exception)
|
||||||
|
self.assertIn("the certificate of 127.0.0.1 was not accepted (Python's check: certificate has expired)",
|
||||||
|
msg)
|
||||||
|
self.assertIn(says, msg)
|
||||||
|
self.assertEqual(check.handshakes, i + 1)
|
||||||
|
self.assertEqual(asked, ['http://127.0.0.1/'] * len(cases)) # the clock is asked over plain HTTP
|
||||||
|
self.assertEqual(srv.hits, []) # no request got through
|
||||||
|
self.assertFalse((self.tmp / 'out' / 'f.bin.part').exists())
|
||||||
|
|
||||||
|
def test_second_check_accepts(self):
|
||||||
|
"""A certificate the first check refuses and the second accepts downloads, and the second goes first for that
|
||||||
|
host from then on."""
|
||||||
|
now = time.time()
|
||||||
|
srv, cert = self.serve(now - 86400, now + 2 * 86400)
|
||||||
|
refuses, accepts = client_context(), client_context(trust=cert)
|
||||||
|
net._CHECKS = [("Python's check", refuses), ("Windows' check", accepts)]
|
||||||
|
dest = net.download(srv.url + 'f.bin', self.tmp / 'out' / 'f.bin', sha256=sha(self.data))
|
||||||
|
self.assertEqual(dest.read_bytes(), self.data)
|
||||||
|
self.assertEqual((refuses.handshakes, accepts.handshakes), (1, 1))
|
||||||
|
self.assertEqual(net._ACCEPTED, {'127.0.0.1': 1})
|
||||||
|
self.assertEqual(net.get_bytes(srv.url + 'f.bin'), self.data)
|
||||||
|
self.assertEqual((refuses.handshakes, accepts.handshakes), (1, 2))
|
||||||
|
net._CHECKS = [("Python's check", refuses)]
|
||||||
|
net.server_clock = lambda *a, **k: None
|
||||||
|
with self.assertRaises(net.CertificateError) as cm:
|
||||||
|
net.get_bytes(srv.url + 'f.bin')
|
||||||
|
self.assertIn("(Python's check: self-signed certificate)", str(cm.exception))
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- feed and updater
|
# ---------------------------------------------------------------- feed and updater
|
||||||
|
|
||||||
@@ -497,6 +684,26 @@ def _nest(flat):
|
|||||||
return tree
|
return tree
|
||||||
|
|
||||||
|
|
||||||
|
# Stands in for windres.exe: records its arguments, working directory and temporary folder, opens the .rc and the
|
||||||
|
# files it names from the working directory as windres does, and leaves two temporary files behind as windres does.
|
||||||
|
FAKE_WINDRES = r'''
|
||||||
|
import json, os, re, sys
|
||||||
|
from pathlib import Path
|
||||||
|
a = sys.argv[1:]
|
||||||
|
tmp = os.environ['TMP']
|
||||||
|
for n in ('cc1', 'cc2'):
|
||||||
|
open(os.path.join(tmp, n), 'w').close()
|
||||||
|
Path(__file__).with_suffix('.json').write_text(json.dumps(
|
||||||
|
{'argv': a, 'cwd': os.getcwd(), 'tmp': tmp, 'temp': os.environ['TEMP']}))
|
||||||
|
if os.environ.get('FAKE_WINDRES_FAIL'):
|
||||||
|
sys.exit('windres: preprocessing failed.')
|
||||||
|
text = open(a[a.index('-i') + 1]).read()
|
||||||
|
for name in re.findall(r'^\s*\w+\s+\w+\s+"([^"]+)"', text, re.M):
|
||||||
|
open(name, 'rb').close()
|
||||||
|
open(a[a.index('-o') + 1], 'wb').write(b'coff')
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
class MakeGameTest(Tmp):
|
class MakeGameTest(Tmp):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp()
|
super().setUp()
|
||||||
@@ -564,6 +771,121 @@ class MakeGameTest(Tmp):
|
|||||||
self.assertEqual(code, 1)
|
self.assertEqual(code, 1)
|
||||||
self.assertTrue(any(e['ev'] == 'error' and '1.1.1' in e['message'] for e in ev))
|
self.assertTrue(any(e['ev'] == 'error' and '1.1.1' in e['message'] for e in ev))
|
||||||
|
|
||||||
|
@unittest.skipUnless(shutil.which('cc'), 'needs a C compiler')
|
||||||
|
def test_object_cache_survives_a_moved_kit(self):
|
||||||
|
"""The launcher keeps each version in its own folder: a kit at a new place reuses every object."""
|
||||||
|
kits = []
|
||||||
|
for name in ('0.3.10', '0.3.11'):
|
||||||
|
kit = self.tmp / 'app' / name / 'runtime'
|
||||||
|
kit.mkdir(parents=True)
|
||||||
|
(kit / 'h.h').write_text('#define V 1\n')
|
||||||
|
(kit / 'a.c').write_text('#include "h.h"\nint a(void) { return V; }\n')
|
||||||
|
kits.append(kit.parent)
|
||||||
|
obj = self.tmp / 'obj'
|
||||||
|
obj.mkdir()
|
||||||
|
|
||||||
|
def go(kit):
|
||||||
|
rt = kit / 'runtime'
|
||||||
|
srcs = [(rt / 'a.c', obj / 'rt_a.o')]
|
||||||
|
cache = self.mg.ObjectCache(obj / 'objects.json', {'<kit>': kit})
|
||||||
|
return self.mg.compile_all(srcs, lambda s_, d: ['cc', '-c', '-I', str(rt), '-o', str(d), str(s_)], cache,
|
||||||
|
1, dict(os.environ), salt='cc')
|
||||||
|
self.assertEqual(go(kits[0])[:2], (1, 0))
|
||||||
|
self.assertEqual(go(kits[1])[:2], (0, 1))
|
||||||
|
(kits[1] / 'runtime' / 'h.h').write_text('#define V 2\n') # the new version changed the header
|
||||||
|
self.assertEqual(go(kits[1])[:2], (1, 0))
|
||||||
|
|
||||||
|
def main_with(self, romfs, lift, compile_):
|
||||||
|
"""make_game.main() in this process for a first build, with the given step functions in place of the real
|
||||||
|
lift and compile (they need real modules and clang). Returns the SystemExit code, or 0."""
|
||||||
|
sys.path.insert(0, str(self.layout.pydeps)) # the fake zbic
|
||||||
|
saved = (self.mg.step_romfs, self.mg.step_lift, self.mg.step_compile, sys.argv)
|
||||||
|
self.mg.step_romfs, self.mg.step_lift, self.mg.step_compile = romfs, lift, compile_
|
||||||
|
sys.argv = ['make_game.py', '--nup', str(self.nup), '--out', str(self.out), '--msys', str(self.msys),
|
||||||
|
'--until', 'compile'] # the shaders step needs the shader translator
|
||||||
|
try:
|
||||||
|
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
self.mg.main()
|
||||||
|
return 0
|
||||||
|
except SystemExit as e:
|
||||||
|
return e.code
|
||||||
|
finally:
|
||||||
|
self.mg.step_romfs, self.mg.step_lift, self.mg.step_compile, sys.argv = saved
|
||||||
|
sys.path.remove(str(self.layout.pydeps))
|
||||||
|
|
||||||
|
def test_romfs_beside_lift_and_compile(self):
|
||||||
|
"""A first build packs the RomFS image while the lift and the compile run; the compile gets the running step
|
||||||
|
and waits for it only for the RomFS index."""
|
||||||
|
real_romfs, seen = self.mg.step_romfs, {}
|
||||||
|
|
||||||
|
def romfs(src, out, jobs):
|
||||||
|
time.sleep(0.5)
|
||||||
|
real_romfs(src, out, jobs)
|
||||||
|
|
||||||
|
def lift(out, cache):
|
||||||
|
seen['lift_beside_romfs'] = not (out / 'romfs' / 'index.json').exists()
|
||||||
|
|
||||||
|
def compile_(out, cache, msys, jobs, romfs_job=None):
|
||||||
|
seen['job'] = romfs_job is not None
|
||||||
|
romfs_job.join()
|
||||||
|
seen['image_after_join'] = (out / 'romfs' / 'romfs.bin').is_file()
|
||||||
|
(out / self.mg.EXE_NAME).write_bytes(b'MZ')
|
||||||
|
self.assertEqual(self.main_with(romfs, lift, compile_), 0)
|
||||||
|
self.assertEqual(seen, {'lift_beside_romfs': True, 'job': True, 'image_after_join': True})
|
||||||
|
steps = json.loads((self.out / 'build-cache' / 'state.json').read_text())['steps']
|
||||||
|
self.assertEqual(set(steps), {'exefs', 'romfs', 'lift', 'compile'})
|
||||||
|
|
||||||
|
def test_romfs_failure_stops_the_build(self):
|
||||||
|
ran, lifting, failed = [], threading.Event(), threading.Event()
|
||||||
|
|
||||||
|
def romfs(src, out, jobs):
|
||||||
|
lifting.wait(5)
|
||||||
|
failed.set()
|
||||||
|
self.mg.fail('the RomFS image could not be written')
|
||||||
|
|
||||||
|
def lift(out, cache):
|
||||||
|
lifting.set()
|
||||||
|
failed.wait(5) # the RomFS step fails while the lift runs
|
||||||
|
time.sleep(0.1)
|
||||||
|
ran.append('lift')
|
||||||
|
|
||||||
|
def compile_(out, cache, msys, jobs, romfs_job=None):
|
||||||
|
ran.append('compile')
|
||||||
|
self.assertEqual(self.main_with(romfs, lift, compile_), 1)
|
||||||
|
self.assertEqual(ran, ['lift'])
|
||||||
|
steps = json.loads((self.out / 'build-cache' / 'state.json').read_text())['steps']
|
||||||
|
self.assertNotIn('romfs', steps)
|
||||||
|
|
||||||
|
@unittest.skipIf(os.name == 'nt', 'uses a POSIX script as the compiler')
|
||||||
|
def test_largest_source_compiles_first(self):
|
||||||
|
src, obj = self.tmp / 'src', self.tmp / 'obj'
|
||||||
|
src.mkdir()
|
||||||
|
obj.mkdir()
|
||||||
|
for name, size in (('small.c', 10), ('big.c', 5000), ('mid.c', 800)):
|
||||||
|
(src / name).write_text('/*' + 'x' * size + '*/\n')
|
||||||
|
order = self.tmp / 'order.txt'
|
||||||
|
cc = self.tmp / 'fakecc'
|
||||||
|
cc.write_text(f'#!{sys.executable}\nimport sys\nargs = sys.argv[1:]\n'
|
||||||
|
'dep, out, s = args[args.index("-MF") + 1], args[args.index("-o") + 1], args[-1]\n'
|
||||||
|
f'open({str(order)!r}, "a").write(s.rsplit("/", 1)[-1] + "\\n")\n'
|
||||||
|
'open(out, "w").close(); open(dep, "w").write(out + ": " + s + "\\n")\n')
|
||||||
|
cc.chmod(0o755)
|
||||||
|
srcs = [(src / n, obj / (n[:-2] + '.o')) for n in ('small.c', 'big.c', 'mid.c')]
|
||||||
|
cache = self.mg.ObjectCache(obj / 'objects.json')
|
||||||
|
compiled, reused, bad = self.mg.compile_all(srcs, lambda s, d: [str(cc), '-c', '-o', str(d), str(s)], cache,
|
||||||
|
1, dict(os.environ))
|
||||||
|
self.assertEqual((compiled, bad), (3, []))
|
||||||
|
self.assertEqual(order.read_text().split(), ['big.c', 'mid.c', 'small.c'])
|
||||||
|
|
||||||
|
def test_runtime_split(self):
|
||||||
|
tainted = self.mg.per_install_names()
|
||||||
|
self.assertTrue({'layout.h', 'patches.h', 'romfs_config.h'} <= tainted)
|
||||||
|
names = {p.name: self.mg.per_install(p, tainted) for p, _ in self.mg.runtime_sources()}
|
||||||
|
for f in ('loader.c', 'memory.c', 'romfs.c', 'patches.c'):
|
||||||
|
self.assertTrue(names[f], f)
|
||||||
|
self.assertFalse(names['vk_device.c'])
|
||||||
|
self.assertLess(sum(names.values()), len(names) // 4) # most of the runtime can come prebuilt
|
||||||
|
|
||||||
def test_parse_deps(self):
|
def test_parse_deps(self):
|
||||||
text = 'C:/o/x.o: C:/src/x.c C:/inc/a\\ b.h \\\n C:/inc/c.h\n'
|
text = 'C:/o/x.o: C:/src/x.c C:/inc/a\\ b.h \\\n C:/inc/c.h\n'
|
||||||
self.assertEqual(self.mg.parse_deps(text), ['C:/src/x.c', 'C:/inc/a b.h', 'C:/inc/c.h'])
|
self.assertEqual(self.mg.parse_deps(text), ['C:/src/x.c', 'C:/inc/a b.h', 'C:/inc/c.h'])
|
||||||
@@ -594,6 +916,48 @@ class MakeGameTest(Tmp):
|
|||||||
self.assertEqual((compiled, len(bad)), (1, 1))
|
self.assertEqual((compiled, len(bad)), (1, 1))
|
||||||
self.assertNotIn('b.o', json.loads((obj / 'objects.json').read_text()))
|
self.assertNotIn('b.o', json.loads((obj / 'objects.json').read_text()))
|
||||||
|
|
||||||
|
@unittest.skipIf(os.name == 'nt', 'a script stands in for windres.exe')
|
||||||
|
def test_compile_resources(self):
|
||||||
|
# The toolchain, the kit and the game under folders with spaces, as under C:\Users\Ali Sayed. windres must
|
||||||
|
# start gcc itself (--use-temp-file) on a line that names no path but gcc's: the .rc by its bare name from
|
||||||
|
# runtime/, no -I, -D or -U.
|
||||||
|
msys, obj = self.tmp / 'tool chain' / 'ucrt64', self.out / 'build-cache' / 'obj'
|
||||||
|
windres = msys / 'bin' / 'windres.exe'
|
||||||
|
windres.parent.mkdir(parents=True)
|
||||||
|
windres.write_text(f'#!{sys.executable}\n' + FAKE_WINDRES)
|
||||||
|
windres.chmod(0o755)
|
||||||
|
obj.mkdir(parents=True)
|
||||||
|
rt = self.tmp / 'the kit' / 'runtime'
|
||||||
|
rt.mkdir(parents=True)
|
||||||
|
for name in ('nx2navi.rc', 'nx2navi.manifest', 'nx2navi.ico'):
|
||||||
|
shutil.copy2(ROOT / 'runtime' / name, rt / name)
|
||||||
|
rco = self.mg.compile_resources(msys, rt, obj, dict(os.environ))
|
||||||
|
self.assertEqual((rco, rco.read_bytes()), (obj / 'nx2navi_rc.o', b'coff'))
|
||||||
|
seen = json.loads(windres.with_suffix('.json').read_text())
|
||||||
|
args = seen['argv']
|
||||||
|
self.assertEqual(seen['cwd'], str(rt))
|
||||||
|
self.assertIn('--use-temp-file', args)
|
||||||
|
self.assertIn(f'--preprocessor={msys / "bin" / "gcc.exe"}', args)
|
||||||
|
self.assertEqual([a for a in args if a.startswith('--preprocessor-arg=')],
|
||||||
|
['--preprocessor-arg=-E', '--preprocessor-arg=-xc', '--preprocessor-arg=-DRC_INVOKED'])
|
||||||
|
self.assertEqual(args[args.index('-i') + 1], 'nx2navi.rc')
|
||||||
|
self.assertFalse([a for a in args if a.startswith(('-I', '--include-dir', '-D', '-U'))])
|
||||||
|
# the temporary files went to a folder of the build cache, which is gone with the two windres left there
|
||||||
|
self.assertEqual(seen['tmp'], seen['temp'])
|
||||||
|
self.assertEqual(Path(seen['tmp']).parent, obj)
|
||||||
|
self.assertEqual(sorted(p.name for p in obj.iterdir()), ['nx2navi_rc.o'])
|
||||||
|
# the same resource again: the object keeps its time, so the link key does not change and nothing relinks
|
||||||
|
before = rco.stat().st_mtime_ns
|
||||||
|
time.sleep(0.02)
|
||||||
|
self.mg.compile_resources(msys, rt, obj, dict(os.environ))
|
||||||
|
self.assertEqual(rco.stat().st_mtime_ns, before)
|
||||||
|
# a failing windres stops the build with its message
|
||||||
|
err = io.StringIO()
|
||||||
|
with self.assertRaises(SystemExit), contextlib.redirect_stderr(err):
|
||||||
|
self.mg.compile_resources(msys, rt, obj, dict(os.environ, FAKE_WINDRES_FAIL='1'))
|
||||||
|
self.assertIn('windres failed on runtime/nx2navi.rc: windres: preprocessing failed.', err.getvalue())
|
||||||
|
self.assertEqual(sorted(p.name for p in obj.iterdir()), ['nx2navi_rc.o'])
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- jobs
|
# ---------------------------------------------------------------- jobs
|
||||||
|
|
||||||
@@ -650,6 +1014,111 @@ class JobTest(Tmp):
|
|||||||
self.assertEqual(j.step('check').state, jobs.FAILED)
|
self.assertEqual(j.step('check').state, jobs.FAILED)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- the icon
|
||||||
|
|
||||||
|
class SavesTest(unittest.TestCase):
|
||||||
|
"""launcher/saves.py: where the game keeps its save, the save folders it recognises, and the import."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = Path(tempfile.mkdtemp(prefix='nx2navi-saves-'))
|
||||||
|
self.game = self.tmp / 'game'
|
||||||
|
self.game.mkdir()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
shutil.rmtree(self.tmp, ignore_errors=True)
|
||||||
|
|
||||||
|
def files(self, folder, names):
|
||||||
|
for n, data in names.items():
|
||||||
|
(folder / n).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
(folder / n).write_bytes(data)
|
||||||
|
return folder
|
||||||
|
|
||||||
|
def test_account_folder_as_the_game_names_it(self):
|
||||||
|
(self.game / 'profile').mkdir()
|
||||||
|
lo, hi = 0x1122334455667788, 0x99aabbccddeeff00
|
||||||
|
(self.game / 'profile' / 'account.uid').write_bytes(lo.to_bytes(8, 'little') + hi.to_bytes(8, 'little'))
|
||||||
|
self.assertEqual(saves.account_dir(self.game).name, f'{hi:016x}{lo:016x}') # fs_host.c storage_init
|
||||||
|
fresh = self.tmp / 'fresh'
|
||||||
|
acct = saves.account_dir(fresh) # a game that never ran: the account is made
|
||||||
|
self.assertEqual(len((fresh / 'profile' / 'account.uid').read_bytes()), 16)
|
||||||
|
self.assertEqual(saves.account_dir(fresh), acct)
|
||||||
|
|
||||||
|
def test_save_folders_found(self):
|
||||||
|
plain = self.files(self.tmp / 'backup', {'save.dat': b'1', 'option.dat': b'2'})
|
||||||
|
self.assertEqual(saves.find_save(plain)[0], plain)
|
||||||
|
emu = self.files(self.tmp / 'emu', {'0000000000000000/' + 'a' * 32 + '/0100F2C0115B6000/save.dat': b'1'})
|
||||||
|
self.assertEqual(saves.find_save(emu)[0].name, '0100F2C0115B6000')
|
||||||
|
other = self.files(self.tmp / 'other', {'profile/save/' + 'b' * 32 + '/save.dat': b'1', 'ocarina.exe': b''})
|
||||||
|
self.assertEqual(saves.find_save(other)[0].name, 'b' * 32)
|
||||||
|
self.assertEqual(saves.find_save(other / 'profile')[0].name, 'b' * 32)
|
||||||
|
(self.tmp / 'empty').mkdir()
|
||||||
|
self.assertIsNone(saves.find_save(self.tmp / 'empty')[0])
|
||||||
|
|
||||||
|
def test_import_backs_up_and_clears_the_journal(self):
|
||||||
|
acct = saves.account_dir(self.game)
|
||||||
|
self.files(acct, {'save.dat': b'old'})
|
||||||
|
tx = self.game / 'profile' / 'save-tx'
|
||||||
|
self.files(tx, {'ready-3/save.dat': b'newer', 'work/save.dat': b'w'})
|
||||||
|
src = self.files(self.tmp / 'mine', {'save.dat': b'imported', 'sub/extra.bin': b'x'})
|
||||||
|
r = saves.import_save(self.game, src, log=lambda m: None)
|
||||||
|
self.assertEqual(r['files'], 2)
|
||||||
|
self.assertEqual((acct / 'save.dat').read_bytes(), b'imported')
|
||||||
|
self.assertEqual((acct / 'sub' / 'extra.bin').read_bytes(), b'x')
|
||||||
|
self.assertEqual(list(tx.iterdir()), []) # the game loads the imported save
|
||||||
|
self.assertEqual((r['backup'] / 'save.dat').read_bytes(), b'newer') # the save the game would have loaded
|
||||||
|
self.assertTrue((self.game / 'saves' / 'README.txt').is_file())
|
||||||
|
self.assertTrue((src / 'save.dat').is_file()) # a picked folder is left as it was
|
||||||
|
|
||||||
|
def test_import_from_the_saves_folder(self):
|
||||||
|
d = saves.ensure_saves_dir(self.game)
|
||||||
|
self.assertIsNone(saves.waiting(self.game)[0]) # README.txt alone is no save
|
||||||
|
self.files(d, {'emu/0000000000000000/' + 'c' * 32 + '/0100F2C0115B6000/save.dat': b'emu'})
|
||||||
|
self.assertIsNotNone(saves.waiting(self.game)[0])
|
||||||
|
r = saves.import_save(self.game, log=lambda m: None)
|
||||||
|
self.assertIsNone(r['backup']) # there was no save yet
|
||||||
|
self.assertEqual((saves.account_dir(self.game) / 'save.dat').read_bytes(), b'emu')
|
||||||
|
left = sorted(e.name for e in d.iterdir())
|
||||||
|
self.assertEqual(left[0], 'README.txt')
|
||||||
|
self.assertTrue(left[1].startswith('imported '))
|
||||||
|
self.assertIsNone(saves.waiting(self.game)[0]) # not imported twice
|
||||||
|
self.files(d, {'save.dat': b'loose'}) # files put straight into saves/
|
||||||
|
r = saves.import_save(self.game, log=lambda m: None)
|
||||||
|
self.assertEqual((saves.account_dir(self.game) / 'save.dat').read_bytes(), b'loose')
|
||||||
|
self.assertEqual((r['backup'] / 'save.dat').read_bytes(), b'emu')
|
||||||
|
self.assertIsNone(saves.waiting(self.game)[0])
|
||||||
|
|
||||||
|
def test_refusals(self):
|
||||||
|
acct = saves.account_dir(self.game)
|
||||||
|
self.files(acct, {'save.dat': b'1'})
|
||||||
|
with self.assertRaises(saves.SaveError):
|
||||||
|
saves.import_save(self.game, self.game / 'profile', log=lambda m: None) # its own save
|
||||||
|
big = self.tmp / 'big'
|
||||||
|
big.mkdir()
|
||||||
|
for i in range(saves.MAX_FILES + 1):
|
||||||
|
(big / f'{i}.txt').write_bytes(b'')
|
||||||
|
with self.assertRaises(saves.SaveError):
|
||||||
|
saves.import_save(self.game, big, log=lambda m: None)
|
||||||
|
self.assertEqual((acct / 'save.dat').read_bytes(), b'1') # nothing changed
|
||||||
|
|
||||||
|
|
||||||
|
class IconTest(unittest.TestCase):
|
||||||
|
def test_navi(self):
|
||||||
|
try:
|
||||||
|
from launcher.ui import art
|
||||||
|
except ImportError:
|
||||||
|
self.skipTest('needs numpy')
|
||||||
|
self.assertEqual(art.navi(2).shape, (42, 44, 4))
|
||||||
|
data = art.navi_ico()
|
||||||
|
count = struct.unpack_from('<H', data, 4)[0]
|
||||||
|
sizes = [data[6 + 16 * i] or 256 for i in range(count)]
|
||||||
|
self.assertEqual(sizes[0], 16)
|
||||||
|
self.assertIn(256, sizes)
|
||||||
|
off = struct.unpack_from('<I', data, 6 + 12)[0]
|
||||||
|
self.assertEqual(struct.unpack_from('<Iii', data, off), (40, 16, 32)) # a bitmap entry, not PNG
|
||||||
|
big = struct.unpack_from('<I', data, 6 + 16 * (count - 1) + 12)[0]
|
||||||
|
self.assertEqual(data[big:big + 4], b'\x89PNG')
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- the window
|
# ---------------------------------------------------------------- the window
|
||||||
|
|
||||||
def have_display():
|
def have_display():
|
||||||
@@ -671,7 +1140,7 @@ class WindowTest(Tmp):
|
|||||||
r = subprocess.run([sys.executable, '-m', 'launcher', '--root', str(self.tmp / 'w'), '--selftest'],
|
r = subprocess.run([sys.executable, '-m', 'launcher', '--root', str(self.tmp / 'w'), '--selftest'],
|
||||||
cwd=ROOT, capture_output=True, text=True, timeout=180)
|
cwd=ROOT, capture_output=True, text=True, timeout=180)
|
||||||
self.assertEqual(r.returncode, 0, r.stderr)
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
self.assertIn('8 screens drawn', r.stdout)
|
self.assertIn('9 screens drawn', r.stdout)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ Steps, each skipped when a run before finished it for the same inputs (state in
|
|||||||
2. exefs the five ExeFS files, every module's segments unpacked (ZBIC through the player's own `zbic` package)
|
2. exefs the five ExeFS files, every module's segments unpacked (ZBIC through the player's own `zbic` package)
|
||||||
and stored plainly, as the runtime's loader reads them -> <out>/exefs
|
and stored plainly, as the runtime's loader reads them -> <out>/exefs
|
||||||
3. romfs every RomFS file, checked against the container's sha256, into one image -> <out>/romfs/romfs.bin and
|
3. romfs every RomFS file, checked against the container's sha256, into one image -> <out>/romfs/romfs.bin and
|
||||||
index.json (16-byte aligned, in the byte order of the paths)
|
index.json (16-byte aligned, in the byte order of the paths). When the lift and the compile follow, it
|
||||||
|
runs on a thread of its own beside them: only the RomFS index and romfs.c wait for the image
|
||||||
4. lift recomp/gen.py with recomp/patches-v111.txt -> <out>/build-cache/lift, plus the two SDK bring-up fixes
|
4. lift recomp/gen.py with recomp/patches-v111.txt -> <out>/build-cache/lift, plus the two SDK bring-up fixes
|
||||||
5. compile the lifted C and runtime/ with MSYS2's clang, linked into <out>/ocarina.exe; the MSYS2 DLLs it loads,
|
5. compile the lifted C and runtime/ with MSYS2's clang, linked into <out>/ocarina.exe; the MSYS2 DLLs it loads,
|
||||||
the shader translator and romfs-index.bin beside it
|
the shader translator and romfs-index.bin beside it
|
||||||
@@ -20,8 +21,16 @@ Steps, each skipped when a run before finished it for the same inputs (state in
|
|||||||
The exefs and romfs steps depend only on the game files; lift and compile depend on this kit's code too. A newer kit
|
The exefs and romfs steps depend only on the game files; lift and compile depend on this kit's code too. A newer kit
|
||||||
therefore lifts and compiles again but keeps the unpacked game files, and --rebuild needs no game files at all. The
|
therefore lifts and compiles again but keeps the unpacked game files, and --rebuild needs no game files at all. The
|
||||||
compile step keeps every object with the dependency list clang wrote for it (build-cache/obj/objects.json) and
|
compile step keeps every object with the dependency list clang wrote for it (build-cache/obj/objects.json) and
|
||||||
compiles a file again only when it, a header it includes, the flags or the compiler changed. The new ocarina.exe
|
compiles a file again only when it, a header it includes, the flags or the compiler changed; the kit's own folder
|
||||||
replaces the old one only once it links, so a failed build leaves the last good one in place.
|
is not part of that key, so a kit in another folder (the launcher keeps each version in its own) reuses the objects.
|
||||||
|
A kit with lib/libnx2navirt.a built by --make-runtime-lib for the same runtime/ and the same compiler links the
|
||||||
|
runtime from it and compiles only the runtime files that include headers written per install. The new ocarina.exe
|
||||||
|
replaces the old one only once it links (with lld when the toolchain has it), so a failed build leaves the last good
|
||||||
|
one in place. Compiles run on every logical processor, the largest files first. The lifted code is built for this
|
||||||
|
PC's x86-64 level (cpu_level), with MSYS2 CLANG64's clang when it sits beside the UCRT64 folder and reports the same
|
||||||
|
version (fast_clang: the same objects, about a fifth faster).
|
||||||
|
|
||||||
|
python tools/make_game.py --make-runtime-lib <kit>/lib --msys <ucrt64> # the release's prebuilt runtime
|
||||||
|
|
||||||
Nothing is written outside --out. The game folder then holds only what this PC built from the player's files: never
|
Nothing is written outside --out. The game folder then holds only what this PC built from the player's files: never
|
||||||
share it. Needs Python 3.10+ with numpy, lz4, zstandard and zbic (pip), and MSYS2 UCRT64's clang and libraries
|
share it. Needs Python 3.10+ with numpy, lz4, zstandard and zbic (pip), and MSYS2 UCRT64's clang and libraries
|
||||||
@@ -43,6 +52,7 @@ import shutil
|
|||||||
import struct
|
import struct
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import threading
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -76,11 +86,14 @@ LIFT_FIXES = [
|
|||||||
LINK_LIBS = ['-lvulkan-1', '-lSDL3', '-lopus', '-lvpx', '-l:libdav1d.a', '-lzstd', '-l:libatomic.a', '-lbcrypt',
|
LINK_LIBS = ['-lvulkan-1', '-lSDL3', '-lopus', '-lvpx', '-l:libdav1d.a', '-lzstd', '-l:libatomic.a', '-lbcrypt',
|
||||||
'-limm32', '-luuid', '-lole32', '-luser32', '-lshell32', '-lgdi32', '-ladvapi32', '-lwinmm']
|
'-limm32', '-luuid', '-lole32', '-luser32', '-lshell32', '-lgdi32', '-ladvapi32', '-lwinmm']
|
||||||
SYSTEM_DLLS_SKIP = {'vulkan-1.dll'} # the graphics driver's loader, never a copy
|
SYSTEM_DLLS_SKIP = {'vulkan-1.dll'} # the graphics driver's loader, never a copy
|
||||||
# GNU windres's preprocessor, named explicitly: left to find it, windres puts the full path of the gcc beside it on a
|
|
||||||
# cmd.exe command line, and once that path and the .rc's both hold a space, cmd.exe drops the outer quotes and splits
|
|
||||||
# the command at the first space. gcc is then found on PATH (the toolchain's bin first); the arguments are windres's own.
|
|
||||||
WINDRES_PP = ['--preprocessor=gcc', '--preprocessor-arg=-E', '--preprocessor-arg=-xc', '--preprocessor-arg=-DRC_INVOKED']
|
|
||||||
EXE_NAME = 'ocarina.exe'
|
EXE_NAME = 'ocarina.exe'
|
||||||
|
# Headers this build writes per install (gen.py, romfs_index.py): a runtime source that includes one, directly or
|
||||||
|
# through a runtime header, is compiled on the player's PC; every other runtime source can come prebuilt.
|
||||||
|
GENERATED_HEADERS = ('layout.h', 'patches.h', 'romfs_config.h')
|
||||||
|
RUNTIME_LIB = 'libnx2navirt.a'
|
||||||
|
RUNTIME_PATTERNS = ('*.c', '*.cpp', 'platform/*.c', 'ui/*.cpp', 'third_party/imgui/*.cpp',
|
||||||
|
'third_party/imgui/backends/*.cpp')
|
||||||
|
INCLUDE = re.compile(r'^[ \t]*#[ \t]*include[ \t]+"([^"]+)"', re.M)
|
||||||
|
|
||||||
# Runs a script the way `python script.py` does, with the script's folder first on sys.path. The launcher's
|
# Runs a script the way `python script.py` does, with the script's folder first on sys.path. The launcher's
|
||||||
# embeddable Python leaves the script folder off sys.path (its ._pth file), so every script this build starts goes
|
# embeddable Python leaves the script folder off sys.path (its ._pth file), so every script this build starts goes
|
||||||
@@ -89,24 +102,53 @@ RUN_SCRIPT = ('import os, runpy, sys; s = sys.argv[1]; sys.argv = sys.argv[1:];
|
|||||||
'sys.path.insert(0, os.path.dirname(os.path.abspath(s))); runpy.run_path(s, run_name="__main__")')
|
'sys.path.insert(0, os.path.dirname(os.path.abspath(s))); runpy.run_path(s, run_name="__main__")')
|
||||||
|
|
||||||
EVENTS = False
|
EVENTS = False
|
||||||
|
OUT_LOCK = threading.Lock() # the RomFS step prints from its own thread (main)
|
||||||
|
|
||||||
|
|
||||||
def say(msg):
|
def say(msg):
|
||||||
print(msg, flush=True)
|
with OUT_LOCK:
|
||||||
|
print(msg, flush=True)
|
||||||
|
|
||||||
|
|
||||||
def emit(ev, **fields):
|
def emit(ev, **fields):
|
||||||
"""One "@@{json}" line for the launcher (--events); nothing otherwise."""
|
"""One "@@{json}" line for the launcher (--events); nothing otherwise."""
|
||||||
if EVENTS:
|
if EVENTS:
|
||||||
print('@@' + json.dumps({'ev': ev, **fields}, ensure_ascii=False), flush=True)
|
line = '@@' + json.dumps({'ev': ev, **fields}, ensure_ascii=False)
|
||||||
|
with OUT_LOCK:
|
||||||
|
print(line, flush=True)
|
||||||
|
|
||||||
|
|
||||||
def fail(msg):
|
def fail(msg):
|
||||||
emit('error', message=msg)
|
emit('error', message=msg)
|
||||||
print(f'\nerror: {msg}', file=sys.stderr, flush=True)
|
with OUT_LOCK:
|
||||||
|
print(f'\nerror: {msg}', file=sys.stderr, flush=True)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
class Background:
|
||||||
|
"""One step on a thread of its own. join() waits for it and raises its failure (fail's SystemExit included) in
|
||||||
|
the caller; failed() tells the caller early, so it can stop work that would be thrown away."""
|
||||||
|
|
||||||
|
def __init__(self, fn):
|
||||||
|
self.exc = None
|
||||||
|
self.thread = threading.Thread(target=self._run, args=(fn,), name='romfs', daemon=True)
|
||||||
|
self.thread.start()
|
||||||
|
|
||||||
|
def _run(self, fn):
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
except BaseException as e: # noqa: B036 - handed to join()
|
||||||
|
self.exc = e
|
||||||
|
|
||||||
|
def failed(self):
|
||||||
|
return self.exc is not None
|
||||||
|
|
||||||
|
def join(self):
|
||||||
|
self.thread.join()
|
||||||
|
if self.exc is not None:
|
||||||
|
raise self.exc
|
||||||
|
|
||||||
|
|
||||||
def py_cmd(script, *args):
|
def py_cmd(script, *args):
|
||||||
"""The command line that runs a Python script of this kit with this interpreter (see RUN_SCRIPT)."""
|
"""The command line that runs a Python script of this kit with this interpreter (see RUN_SCRIPT)."""
|
||||||
flags = ['-I'] if sys.flags.isolated else []
|
flags = ['-I'] if sys.flags.isolated else []
|
||||||
@@ -317,11 +359,11 @@ def step_romfs(src, out, jobs):
|
|||||||
done += size
|
done += size
|
||||||
emit('progress', step='romfs', done=done, total=total, unit='bytes')
|
emit('progress', step='romfs', done=done, total=total, unit='bytes')
|
||||||
if start // batch % 40 == 0:
|
if start // batch % 40 == 0:
|
||||||
say(f' {done / 1e9:5.1f} of {total / 1e9:.1f} GB, {time.time() - t0:.0f} s')
|
say(f' RomFS {done / 1e9:5.1f} of {total / 1e9:.1f} GB, {time.time() - t0:.0f} s')
|
||||||
part.replace(dst / 'romfs.bin')
|
part.replace(dst / 'romfs.bin')
|
||||||
index = {'status': 'pass', 'romfs_size': pos, 'romfs_sha256': h.hexdigest(), 'files': entries}
|
index = {'status': 'pass', 'romfs_size': pos, 'romfs_sha256': h.hexdigest(), 'files': entries}
|
||||||
(dst / 'index.json').write_text(json.dumps(index), encoding='utf-8')
|
(dst / 'index.json').write_text(json.dumps(index), encoding='utf-8')
|
||||||
say(f' image {pos / 1e9:.2f} GB in {time.time() - t0:.0f} s')
|
say(f' RomFS image {pos / 1e9:.2f} GB in {time.time() - t0:.0f} s')
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- lift
|
# ---------------------------------------------------------------- lift
|
||||||
@@ -491,17 +533,33 @@ def parse_deps(text):
|
|||||||
|
|
||||||
|
|
||||||
class ObjectCache:
|
class ObjectCache:
|
||||||
"""Which objects are current: per object the key of its command and source, and the sha256 of every file its
|
"""Which objects are current: per object the key of its command and source, and the sha256 (with size and
|
||||||
dependency list names (build-cache/obj/objects.json)."""
|
modification time, to skip hashing an untouched file) of every file its dependency list names
|
||||||
|
(build-cache/obj/objects.json). Paths under a root are kept relative to it ({'<kit>': KIT}), so the same files
|
||||||
|
in a kit at another place still count as the same."""
|
||||||
|
|
||||||
def __init__(self, path):
|
def __init__(self, path, roots=None):
|
||||||
self.path = path
|
self.path = path
|
||||||
|
self.roots = {k: os.path.normcase(os.path.abspath(v)) for k, v in (roots or {}).items()}
|
||||||
try:
|
try:
|
||||||
self.entries = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
|
self.entries = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
self.entries = {}
|
self.entries = {}
|
||||||
self._sha = {}
|
self._sha = {}
|
||||||
|
|
||||||
|
def norm(self, p):
|
||||||
|
a = os.path.normcase(os.path.abspath(p))
|
||||||
|
for name, root in self.roots.items():
|
||||||
|
if a == root or a.startswith(root + os.sep):
|
||||||
|
return name + a[len(root):].replace(os.sep, '/')
|
||||||
|
return a
|
||||||
|
|
||||||
|
def real(self, p):
|
||||||
|
for name, root in self.roots.items():
|
||||||
|
if p.startswith(name):
|
||||||
|
return root + p[len(name):].replace('/', os.sep)
|
||||||
|
return p
|
||||||
|
|
||||||
def file_sha(self, p):
|
def file_sha(self, p):
|
||||||
p = os.path.normcase(os.path.abspath(p))
|
p = os.path.normcase(os.path.abspath(p))
|
||||||
if p not in self._sha:
|
if p not in self._sha:
|
||||||
@@ -511,18 +569,37 @@ class ObjectCache:
|
|||||||
self._sha[p] = None
|
self._sha[p] = None
|
||||||
return self._sha[p]
|
return self._sha[p]
|
||||||
|
|
||||||
|
def _same(self, p, rec):
|
||||||
|
path = self.real(p)
|
||||||
|
if isinstance(rec, str): # a cache without sizes and times
|
||||||
|
return self.file_sha(path) == rec
|
||||||
|
digest, size, mtime = rec
|
||||||
|
try:
|
||||||
|
st = os.stat(path)
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
if st.st_size == size and st.st_mtime_ns == mtime:
|
||||||
|
return True
|
||||||
|
return st.st_size == size and self.file_sha(path) == digest
|
||||||
|
|
||||||
def current(self, obj, key):
|
def current(self, obj, key):
|
||||||
e = self.entries.get(obj.name)
|
e = self.entries.get(obj.name)
|
||||||
return (e is not None and e.get('key') == key and obj.is_file()
|
return (e is not None and e.get('key') == key and obj.is_file()
|
||||||
and all(self.file_sha(p) == h for p, h in e.get('deps', {}).items()))
|
and all(self._same(p, rec) for p, rec in e.get('deps', {}).items()))
|
||||||
|
|
||||||
def record(self, obj, key, dep_file, src):
|
def record(self, obj, key, dep_file, src):
|
||||||
try:
|
try:
|
||||||
deps = parse_deps(Path(dep_file).read_text(encoding='utf-8', errors='replace'))
|
deps = parse_deps(Path(dep_file).read_text(encoding='utf-8', errors='replace'))
|
||||||
except OSError:
|
except OSError:
|
||||||
deps = []
|
deps = []
|
||||||
deps = deps or [str(src)]
|
out = {}
|
||||||
self.entries[obj.name] = {'key': key, 'deps': {p: self.file_sha(p) for p in deps}}
|
for p in deps or [str(src)]:
|
||||||
|
try:
|
||||||
|
st = os.stat(p)
|
||||||
|
out[self.norm(p)] = [self.file_sha(p), st.st_size, st.st_mtime_ns]
|
||||||
|
except OSError:
|
||||||
|
out[self.norm(p)] = [None, -1, -1]
|
||||||
|
self.entries[obj.name] = {'key': key, 'deps': out}
|
||||||
|
|
||||||
def forget(self, obj):
|
def forget(self, obj):
|
||||||
self.entries.pop(obj.name, None)
|
self.entries.pop(obj.name, None)
|
||||||
@@ -539,22 +616,31 @@ def compiler_id(clang, env):
|
|||||||
return sha256_bytes(f'{p.stdout}\n{st.st_size}\n{int(st.st_mtime)}'.encode())
|
return sha256_bytes(f'{p.stdout}\n{st.st_size}\n{int(st.st_mtime)}'.encode())
|
||||||
|
|
||||||
|
|
||||||
def compile_all(srcs, cmd_for, cache, jobs, env, progress=None, salt=''):
|
def compile_all(srcs, cmd_for, cache, jobs, env, progress=None, salt='', stop=None):
|
||||||
"""Compile each (source, object) whose object is not current in cache. cmd_for(src, dst) -> argv without the
|
"""Compile each (source, object) whose object is not current in cache. cmd_for(src, dst) -> argv without the
|
||||||
dependency-file options; salt identifies the compiler. Returns (compiled, reused, failures) with failures as
|
dependency-file options; salt identifies the compiler. Returns (compiled, reused, failures) with failures as
|
||||||
(src, stderr tail)."""
|
(src, stderr tail). The cache's roots stand for their paths in the flags too. The largest sources start first:
|
||||||
|
compile time grows with size, and a big file that started last would run on alone after the others finished.
|
||||||
|
stop() true makes the compiles not yet started end at once, unrecorded (a step beside this one failed)."""
|
||||||
todo, keys = [], {}
|
todo, keys = [], {}
|
||||||
for src, dst in srcs:
|
for src, dst in srcs:
|
||||||
cmd = cmd_for(src, dst)
|
cmd = cmd_for(src, dst)
|
||||||
flags = [c for c in cmd if c not in (str(src), str(dst))]
|
flags = [c for c in cmd[1:] if c not in (str(src), str(dst))]
|
||||||
|
for name, root in cache.roots.items():
|
||||||
|
flags = [name + os.path.normcase(f)[len(root):].replace(os.sep, '/') if os.path.normcase(f).startswith(root)
|
||||||
|
else f for f in flags]
|
||||||
|
flags = [os.path.basename(cmd[0])] + flags
|
||||||
keys[dst] = sha256_bytes(json.dumps([salt, flags, cache.file_sha(src)]).encode())
|
keys[dst] = sha256_bytes(json.dumps([salt, flags, cache.file_sha(src)]).encode())
|
||||||
if not cache.current(dst, keys[dst]):
|
if not cache.current(dst, keys[dst]):
|
||||||
todo.append((src, dst))
|
todo.append((src, dst))
|
||||||
reused = len(srcs) - len(todo)
|
reused = len(srcs) - len(todo)
|
||||||
|
todo.sort(key=lambda job: job[0].stat().st_size, reverse=True)
|
||||||
|
|
||||||
def cc(job):
|
def cc(job):
|
||||||
src, dst = job
|
src, dst = job
|
||||||
dep = dst.with_suffix('.d')
|
dep = dst.with_suffix('.d')
|
||||||
|
if stop and stop():
|
||||||
|
return src, dst, dep, None, ''
|
||||||
cmd = cmd_for(src, dst)
|
cmd = cmd_for(src, dst)
|
||||||
cmd[1:1] = ['-MMD', '-MF', str(dep)]
|
cmd[1:1] = ['-MMD', '-MF', str(dep)]
|
||||||
p = subprocess.run(cmd, capture_output=True, text=True, env=env, errors='replace')
|
p = subprocess.run(cmd, capture_output=True, text=True, env=env, errors='replace')
|
||||||
@@ -566,6 +652,8 @@ def compile_all(srcs, cmd_for, cache, jobs, env, progress=None, salt=''):
|
|||||||
with concurrent.futures.ThreadPoolExecutor(max(1, jobs)) as ex:
|
with concurrent.futures.ThreadPoolExecutor(max(1, jobs)) as ex:
|
||||||
for src, dst, dep, rc, err in ex.map(cc, todo):
|
for src, dst, dep, rc, err in ex.map(cc, todo):
|
||||||
done += 1
|
done += 1
|
||||||
|
if rc is None: # not started (stop)
|
||||||
|
continue
|
||||||
if rc:
|
if rc:
|
||||||
bad.append((src, err))
|
bad.append((src, err))
|
||||||
cache.forget(dst)
|
cache.forget(dst)
|
||||||
@@ -577,33 +665,236 @@ def compile_all(srcs, cmd_for, cache, jobs, env, progress=None, salt=''):
|
|||||||
return len(todo), reused, bad
|
return len(todo), reused, bad
|
||||||
|
|
||||||
|
|
||||||
def step_compile(out, cache_dir, msys, jobs):
|
def runtime_sources():
|
||||||
|
"""(source, object name) of every runtime file the Windows build compiles."""
|
||||||
|
rt = KIT / 'runtime'
|
||||||
|
out = []
|
||||||
|
for pat in RUNTIME_PATTERNS:
|
||||||
|
for p in sorted(rt.glob(pat)):
|
||||||
|
if p.stem.endswith('_sdl') or p.name == 'linux.c':
|
||||||
|
continue
|
||||||
|
out.append((p, 'rt_' + p.relative_to(rt).as_posix().replace('/', '_').rsplit('.', 1)[0] + '.o'))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def per_install_names(generated=GENERATED_HEADERS):
|
||||||
|
"""The basenames of the generated headers and of every runtime header that includes one, at any depth."""
|
||||||
|
rt = KIT / 'runtime'
|
||||||
|
headers = {}
|
||||||
|
for p in list(rt.rglob('*.h')) + list(rt.rglob('*.inc')):
|
||||||
|
headers[p.name] = {os.path.basename(i) for i in INCLUDE.findall(p.read_text(encoding='utf-8', errors='replace'))}
|
||||||
|
tainted = set(generated)
|
||||||
|
grew = True
|
||||||
|
while grew:
|
||||||
|
grew = False
|
||||||
|
for name, incs in headers.items():
|
||||||
|
if name not in tainted and incs & tainted:
|
||||||
|
tainted.add(name)
|
||||||
|
grew = True
|
||||||
|
return tainted
|
||||||
|
|
||||||
|
|
||||||
|
def per_install(src, tainted):
|
||||||
|
incs = {os.path.basename(i) for i in INCLUDE.findall(Path(src).read_text(encoding='utf-8', errors='replace'))}
|
||||||
|
return bool(incs & tainted)
|
||||||
|
|
||||||
|
|
||||||
|
def clang_version(clang, env):
|
||||||
|
p = subprocess.run([str(clang), '--version'], capture_output=True, text=True, env=env)
|
||||||
|
return (p.stdout.splitlines() or [''])[0].strip()
|
||||||
|
|
||||||
|
|
||||||
|
def runtime_digest():
|
||||||
|
return tree_digest(KIT / 'runtime', ('**/*',))
|
||||||
|
|
||||||
|
|
||||||
|
# The x86-64 levels the lifted code is built and tested for (docs/building.md, "Checks"), as the macros clang defines
|
||||||
|
# for a CPU that has them.
|
||||||
|
CPU_V2 = {'__SSE3__', '__SSSE3__', '__SSE4_1__', '__SSE4_2__', '__POPCNT__', '__LAHF_SAHF__',
|
||||||
|
'__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16'}
|
||||||
|
CPU_V3 = CPU_V2 | {'__AVX__', '__AVX2__', '__BMI__', '__BMI2__', '__F16C__', '__FMA__', '__LZCNT__', '__MOVBE__',
|
||||||
|
'__XSAVE__'}
|
||||||
|
|
||||||
|
|
||||||
|
def cpu_level(clang, env):
|
||||||
|
"""This PC's x86-64 level for the lifted code: 3 (AVX2, FMA, BMI2), 2 (SSE4.2, POPCNT) or 0 when clang cannot
|
||||||
|
tell. The game runs on the PC that builds it, so it takes this CPU's level, as tools/build_game.py --cpu does by
|
||||||
|
hand. Without one the lifted code would be generic x86-64: every fused multiply-add of the game a call to
|
||||||
|
runtime/fma.c's software fma, and a level the differential tests do not cover."""
|
||||||
|
p = subprocess.run([str(clang), '-march=native', '-E', '-dM', '-x', 'c', os.devnull], capture_output=True,
|
||||||
|
text=True, env=env, errors='replace')
|
||||||
|
have = set(re.findall(r'^#define (__\w+) ', p.stdout, re.M)) if p.returncode == 0 else set()
|
||||||
|
return 3 if CPU_V3 <= have else 2 if CPU_V2 <= have else 0
|
||||||
|
|
||||||
|
|
||||||
|
def clang_ident(clang, env):
|
||||||
|
"""(version, target) a clang reports, or None when it does not run."""
|
||||||
|
try:
|
||||||
|
p = subprocess.run([str(clang), '--version'], capture_output=True, text=True, env=env, errors='replace')
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
v, t = re.search(r'clang version (\S+)', p.stdout), re.search(r'^Target: (\S+)', p.stdout, re.M)
|
||||||
|
return (v.group(1), t.group(1)) if p.returncode == 0 and v and t else None
|
||||||
|
|
||||||
|
|
||||||
|
def fast_clang(msys, clang, env):
|
||||||
|
"""MSYS2's CLANG64 clang beside the UCRT64 one (msys64/clang64, which the launcher installs): the same LLVM release
|
||||||
|
built with profile-guided optimisation, about a fifth faster on the lifted code. With UCRT64's headers
|
||||||
|
(--sysroot) it writes the same objects as UCRT64's clang, byte for byte but the COFF timestamp; it is used only
|
||||||
|
when it reports the same version and target. None otherwise."""
|
||||||
|
fast = Path(msys).parent / 'clang64' / 'bin' / 'clang.exe'
|
||||||
|
if not fast.is_file():
|
||||||
|
return None
|
||||||
|
mine = clang_ident(clang, env)
|
||||||
|
return fast if mine and clang_ident(fast, env) == mine else None
|
||||||
|
|
||||||
|
|
||||||
|
def runtime_cmd(clang, clangxx, inc, level=0, fast=None, msys=None):
|
||||||
|
"""fast: fast_clang's compiler for the lifted code, with msys as its sysroot."""
|
||||||
|
def cmd_for(src, dst):
|
||||||
|
cpp = src.suffix in ('.cpp', '.cxx')
|
||||||
|
# the lifted code at -O1 (its size makes -O2 slow to build), the runtime at -O2; neither may assume strict
|
||||||
|
# aliasing: the lifted code reaches guest memory through casts of one address to several types
|
||||||
|
# (tools/build_game.py's flags). The lifted code is built for this PC's level (cpu_level); the runtime
|
||||||
|
# stays generic, so the prebuilt one serves every PC (its vectors are 16 bytes, passed alike at every level).
|
||||||
|
guest = dst.name.startswith(('main_', 'sdk_', 'subsdk0_'))
|
||||||
|
march = [f'-march=x86-64-v{level}'] if guest and level else []
|
||||||
|
cc = [str(fast), f'--sysroot={msys}'] if guest and fast else [str(clangxx if cpp else clang)]
|
||||||
|
return [*cc, '-c', '-std=gnu++17' if cpp else '-std=gnu11', '-O1' if guest else '-O2',
|
||||||
|
*march, '-fno-strict-aliasing', '-w', *inc, '-o', str(dst), str(src)]
|
||||||
|
return cmd_for
|
||||||
|
|
||||||
|
|
||||||
|
def make_runtime_lib(dest, msys, jobs, obj=None):
|
||||||
|
"""--make-runtime-lib: compile every runtime source that does not include a per-install header into
|
||||||
|
<dest>/libnx2navirt.a, with runtime-lib.json naming the runtime/ tree and the compiler it was built from. The
|
||||||
|
objects stay in obj (default <dest>/obj), which a release keeps out of what it ships."""
|
||||||
|
dest = Path(dest).resolve()
|
||||||
|
dest.mkdir(parents=True, exist_ok=True)
|
||||||
|
obj = Path(obj).resolve() if obj else dest / 'obj'
|
||||||
|
obj.mkdir(parents=True, exist_ok=True)
|
||||||
|
clang, clangxx = msys / 'bin' / 'clang.exe', msys / 'bin' / 'clang++.exe'
|
||||||
|
env = dict(os.environ, PATH=str(msys / 'bin') + os.pathsep + os.environ.get('PATH', ''))
|
||||||
|
rt = KIT / 'runtime'
|
||||||
|
tainted = per_install_names()
|
||||||
|
srcs = [(p, obj / name) for p, name in runtime_sources() if not per_install(p, tainted)]
|
||||||
|
inc = ['-I', str(rt), '-I', str(rt / 'third_party' / 'imgui'), '-I', str(msys / 'include' / 'vma')]
|
||||||
|
cache = ObjectCache(obj / 'objects.json', {'<kit>': KIT})
|
||||||
|
t0 = time.time()
|
||||||
|
compiled, reused, bad = compile_all(srcs, runtime_cmd(clang, clangxx, inc), cache, jobs, env,
|
||||||
|
lambda d, t: (d % 20 == 0 or d == t) and say(f' {d} of {t}'),
|
||||||
|
salt=compiler_id(clang, env))
|
||||||
|
if bad:
|
||||||
|
for src, err in bad[:3]:
|
||||||
|
print(f'--- {src}\n{err}', file=sys.stderr)
|
||||||
|
fail(f'{len(bad)} runtime files did not compile')
|
||||||
|
lib = dest / RUNTIME_LIB
|
||||||
|
lib.unlink(missing_ok=True)
|
||||||
|
rsp = dest / 'ar.rsp'
|
||||||
|
rsp.write_text('\n'.join('"%s"' % o.as_posix() for _, o in srcs), encoding='utf-8')
|
||||||
|
ar = os.environ.get('NX2NAVI_AR') or str(msys / 'bin' / 'ar.exe')
|
||||||
|
if subprocess.run([ar, 'rcs', str(lib), '@' + str(rsp)], env=env).returncode:
|
||||||
|
fail('the runtime library could not be archived')
|
||||||
|
meta = {'runtime': runtime_digest(), 'compiler': clang_version(clang, env),
|
||||||
|
'objects': sorted(o.name for _, o in srcs)}
|
||||||
|
(dest / 'runtime-lib.json').write_text(json.dumps(meta, indent=1), encoding='utf-8')
|
||||||
|
rsp.unlink(missing_ok=True)
|
||||||
|
say(f'{lib}: {len(srcs)} runtime files ({compiled} compiled, {reused} kept), {lib.stat().st_size / 1e6:.1f} MB, '
|
||||||
|
f'{time.time() - t0:.0f} s')
|
||||||
|
|
||||||
|
|
||||||
|
def prebuilt_runtime(clang, env):
|
||||||
|
"""(library, object names it holds) when the kit's lib/ matches this runtime/ and this compiler, else None."""
|
||||||
|
lib, meta = KIT / 'lib' / RUNTIME_LIB, KIT / 'lib' / 'runtime-lib.json'
|
||||||
|
try:
|
||||||
|
m = json.loads(meta.read_text(encoding='utf-8'))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
if not lib.is_file() or m.get('runtime') != runtime_digest() or m.get('compiler') != clang_version(clang, env):
|
||||||
|
say(' the prebuilt runtime does not match this kit or compiler: compiling runtime/')
|
||||||
|
return None
|
||||||
|
return lib, set(m.get('objects', []))
|
||||||
|
|
||||||
|
|
||||||
|
def romfs_index(out, gen):
|
||||||
|
if subprocess.run(py_cmd(KIT / 'tools' / 'romfs_index.py', '--romfs', out / 'romfs', '--out', gen)).returncode:
|
||||||
|
fail('the RomFS index could not be written')
|
||||||
|
|
||||||
|
|
||||||
|
def windres_command(msys, rco):
|
||||||
|
"""MSYS2's windres on nx2navi.rc, run with runtime/ as the working directory (compile_resources says why)."""
|
||||||
|
pp = ('-E', '-xc', '-DRC_INVOKED') # windres's own preprocessor flags, which --preprocessor replaces
|
||||||
|
return [str(msys / 'bin' / 'windres.exe'), '--use-temp-file', f'--preprocessor={msys / "bin" / "gcc.exe"}',
|
||||||
|
*(f'--preprocessor-arg={a}' for a in pp), '-O', 'coff', '-i', 'nx2navi.rc', '-o', str(rco)]
|
||||||
|
|
||||||
|
|
||||||
|
def compile_resources(msys, rt, obj, env):
|
||||||
|
"""runtime/nx2navi.rc into obj/nx2navi_rc.o: the manifest of the game's exe (per-monitor DPI awareness, so the
|
||||||
|
picture keeps the monitor's real size rather than one Windows stretches) and its icon.
|
||||||
|
|
||||||
|
windres preprocesses the .rc with gcc through one command line it writes itself, quoting each path that holds a
|
||||||
|
space. By default it hands that line to cmd.exe /c, which drops the first and the last double quote of a line
|
||||||
|
holding more than two: gcc's quoted path loses its opening quote, and under a user folder with a space in its
|
||||||
|
name (C:\\Users\\Ali Sayed) cmd.exe stops at that space ("'C:\\Users\\Ali' is not recognized").
|
||||||
|
|
||||||
|
With --use-temp-file windres starts gcc itself instead, no shell involved: it splits the line into arguments and
|
||||||
|
passes each one to gcc intact. Its splitter reads a quoted first word right, but it cuts a quoted -I path at its
|
||||||
|
spaces and reads past the end of the line after a quoted last word, so the line holds no path but gcc's, its
|
||||||
|
first word: the .rc goes by its bare name from runtime/ as the working directory, where windres also finds the
|
||||||
|
manifest and the icon, and there is no -I. windres's temporary files go to a folder of the build cache, deleted
|
||||||
|
afterwards (it leaves two of them behind on every run).
|
||||||
|
|
||||||
|
The object is written under another name and replaces the old one only when its bytes differ, so an unchanged
|
||||||
|
resource keeps its time and does not make the link key change (a rebuild with nothing new does not link again)."""
|
||||||
|
rco, new = obj / 'nx2navi_rc.o', obj / 'nx2navi_rc.o.new'
|
||||||
|
tmp = obj / 'windres-tmp'
|
||||||
|
shutil.rmtree(tmp, ignore_errors=True)
|
||||||
|
tmp.mkdir()
|
||||||
|
try:
|
||||||
|
r = subprocess.run(windres_command(msys, new), cwd=rt, env=dict(env, TMP=str(tmp), TEMP=str(tmp)),
|
||||||
|
capture_output=True, text=True, errors='replace')
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(tmp, ignore_errors=True)
|
||||||
|
if r.returncode:
|
||||||
|
new.unlink(missing_ok=True)
|
||||||
|
fail(f'windres failed on runtime/nx2navi.rc: {r.stderr.strip()[:400]}')
|
||||||
|
if rco.is_file() and rco.read_bytes() == new.read_bytes():
|
||||||
|
new.unlink()
|
||||||
|
else:
|
||||||
|
os.replace(new, rco)
|
||||||
|
return rco
|
||||||
|
|
||||||
|
|
||||||
|
def step_compile(out, cache_dir, msys, jobs, romfs_job=None):
|
||||||
|
"""romfs_job: the RomFS step still running beside this one (a first build). Everything that does not include
|
||||||
|
romfs_config.h compiles meanwhile; the RomFS index and the few files that include it follow once it is done."""
|
||||||
lift, gen, obj = cache_dir / 'lift', cache_dir / 'gen', cache_dir / 'obj'
|
lift, gen, obj = cache_dir / 'lift', cache_dir / 'gen', cache_dir / 'obj'
|
||||||
gen.mkdir(parents=True, exist_ok=True)
|
gen.mkdir(parents=True, exist_ok=True)
|
||||||
obj.mkdir(parents=True, exist_ok=True)
|
obj.mkdir(parents=True, exist_ok=True)
|
||||||
rt = KIT / 'runtime'
|
rt = KIT / 'runtime'
|
||||||
clang, clangxx = msys / 'bin' / 'clang.exe', msys / 'bin' / 'clang++.exe'
|
clang, clangxx = msys / 'bin' / 'clang.exe', msys / 'bin' / 'clang++.exe'
|
||||||
env = dict(os.environ, PATH=str(msys / 'bin') + os.pathsep + os.environ.get('PATH', ''))
|
env = dict(os.environ, PATH=str(msys / 'bin') + os.pathsep + os.environ.get('PATH', ''))
|
||||||
if subprocess.run(py_cmd(KIT / 'tools' / 'romfs_index.py', '--romfs', out / 'romfs', '--out', gen)).returncode:
|
if not romfs_job:
|
||||||
fail('the RomFS index could not be written')
|
romfs_index(out, gen)
|
||||||
srcs = [(p, obj / f'{mod}_{p.stem}.o') for mod in ('main', 'sdk', 'subsdk0') for p in sorted((lift / mod).glob('*.c'))]
|
srcs = [(p, obj / f'{mod}_{p.stem}.o') for mod in ('main', 'sdk', 'subsdk0') for p in sorted((lift / mod).glob('*.c'))]
|
||||||
for pat in ('*.c', '*.cpp', 'platform/*.c', 'ui/*.cpp', 'third_party/imgui/*.cpp', 'third_party/imgui/backends/*.cpp'):
|
prebuilt = prebuilt_runtime(clang, env)
|
||||||
for p in sorted(rt.glob(pat)):
|
runtime = [(p, obj / name) for p, name in runtime_sources()]
|
||||||
if p.stem.endswith('_sdl') or p.name == 'linux.c':
|
if prebuilt:
|
||||||
continue
|
runtime = [(p, o) for p, o in runtime if o.name not in prebuilt[1]]
|
||||||
srcs.append((p, obj / ('rt_' + p.relative_to(rt).as_posix().replace('/', '_').rsplit('.', 1)[0] + '.o')))
|
say(f' the runtime comes prebuilt; {len(runtime)} runtime files are compiled here')
|
||||||
|
srcs += runtime
|
||||||
srcs += [(modules_c(lift, out, gen), obj / 'modules.o'), (gen / 'shim.c', obj / 'shim.o')]
|
srcs += [(modules_c(lift, out, gen), obj / 'modules.o'), (gen / 'shim.c', obj / 'shim.o')]
|
||||||
inc = ['-I', str(rt), '-I', str(lift), '-I', str(gen), '-I', str(rt / 'third_party' / 'imgui'),
|
inc = ['-I', str(rt), '-I', str(lift), '-I', str(gen), '-I', str(rt / 'third_party' / 'imgui'),
|
||||||
'-I', str(msys / 'include' / 'vma')]
|
'-I', str(msys / 'include' / 'vma')]
|
||||||
cid = compiler_id(clang, env)
|
cid = compiler_id(clang, env)
|
||||||
|
level = cpu_level(clang, env)
|
||||||
def cmd_for(src, dst):
|
say(f' the lifted code is built for x86-64-v{level}, this processor\'s level' if level else
|
||||||
cpp = src.suffix in ('.cpp', '.cxx')
|
' the lifted code is built for generic x86-64: the processor\'s level could not be read')
|
||||||
# the lifted code at -O1 (its size makes -O2 slow to build), the runtime at -O2; neither may assume strict aliasing:
|
fast = fast_clang(msys, clang, env)
|
||||||
# the lifted code reaches guest memory through casts of one address to several types (tools/build_game.py's flags)
|
if fast:
|
||||||
guest = dst.name.startswith(('main_', 'sdk_', 'subsdk0_'))
|
cid += compiler_id(fast, env)
|
||||||
return [str(clangxx if cpp else clang), '-c', '-std=gnu++17' if cpp else '-std=gnu11', '-O1' if guest else '-O2',
|
say(f' the lifted code compiles with {fast}')
|
||||||
'-fno-strict-aliasing', '-w', *inc, '-o', str(dst), str(src)]
|
cmd_for = runtime_cmd(clang, clangxx, inc, level, fast, msys)
|
||||||
|
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
last = [0.0]
|
last = [0.0]
|
||||||
@@ -617,29 +908,42 @@ def step_compile(out, cache_dir, msys, jobs):
|
|||||||
say(f' compiled {done} of {total}, {now - t0:.0f} s')
|
say(f' compiled {done} of {total}, {now - t0:.0f} s')
|
||||||
|
|
||||||
say(f' {len(srcs)} files on {jobs} threads')
|
say(f' {len(srcs)} files on {jobs} threads')
|
||||||
cache = ObjectCache(obj / 'objects.json')
|
cache = ObjectCache(obj / 'objects.json', {'<kit>': KIT})
|
||||||
compiled, reused, bad = compile_all(srcs, cmd_for, cache, jobs, env, progress, salt=cid)
|
late = []
|
||||||
|
if romfs_job: # the lifted chunks include only cpu.h and simd.h: only the runtime and generated files are read
|
||||||
|
tainted = per_install_names(('romfs_config.h',))
|
||||||
|
late = [(s, o) for s, o in runtime + srcs[-2:] if per_install(s, tainted)]
|
||||||
|
say(f' {len(late)} files wait for the RomFS index: {", ".join(s.name for s, _ in late)}')
|
||||||
|
early = [j for j in srcs if j not in late]
|
||||||
|
compiled, reused, bad = compile_all(early, cmd_for, cache, jobs, env, lambda d, t: progress(d, len(srcs)),
|
||||||
|
salt=cid, stop=romfs_job.failed if romfs_job else None)
|
||||||
|
if romfs_job:
|
||||||
|
if romfs_job.thread.is_alive():
|
||||||
|
say(' waiting for the RomFS image')
|
||||||
|
romfs_job.join() # raises the RomFS step's failure; a failed compile still keeps the finished image
|
||||||
|
if not bad:
|
||||||
|
romfs_index(out, gen)
|
||||||
|
c2, r2, bad = compile_all(late, cmd_for, cache, jobs, env,
|
||||||
|
lambda d, t: progress(len(early) + d, len(srcs)), salt=cid)
|
||||||
|
compiled, reused = compiled + c2, reused + r2
|
||||||
say(f' {compiled} compiled, {reused} unchanged since the last build')
|
say(f' {compiled} compiled, {reused} unchanged since the last build')
|
||||||
if bad:
|
if bad:
|
||||||
for src, err in bad[:3]:
|
for src, err in bad[:3]:
|
||||||
print(f'--- {src}\n{err}', file=sys.stderr)
|
print(f'--- {src}\n{err}', file=sys.stderr)
|
||||||
fail(f'{len(bad)} files did not compile')
|
fail(f'{len(bad)} files did not compile')
|
||||||
|
|
||||||
# the manifest (per-monitor DPI awareness: the picture at the monitor's real size, not one Windows stretches) and the
|
rco = compile_resources(msys, rt, obj, env)
|
||||||
# icon, runtime/nx2navi.rc through MSYS2's windres. windres runs its preprocessor through cmd.exe: run from the
|
|
||||||
# runtime folder with relative names and gcc by bare name (WINDRES_PP), that command line holds no path, so a space
|
|
||||||
# in the install folder (a user name) cannot split it.
|
|
||||||
rco = (obj / 'nx2navi_rc.o').resolve()
|
|
||||||
r = subprocess.run([str(msys / 'bin' / 'windres.exe'), *WINDRES_PP, '-I', '.', '-O', 'coff', '-i', 'nx2navi.rc',
|
|
||||||
'-o', str(rco)], capture_output=True, text=True, env=env, errors='replace', cwd=rt)
|
|
||||||
if r.returncode:
|
|
||||||
fail(f'windres failed on runtime/nx2navi.rc: {r.stderr.strip()[:400]}')
|
|
||||||
objs = [o for _, o in srcs] + [rco]
|
objs = [o for _, o in srcs] + [rco]
|
||||||
exe = out / EXE_NAME
|
exe = out / EXE_NAME
|
||||||
rsp = cache_dir / 'link.rsp'
|
rsp = cache_dir / 'link.rsp'
|
||||||
rsp.write_text('\n'.join('"%s"' % o.as_posix() for o in objs), encoding='utf-8')
|
rsp.write_text('\n'.join('"%s"' % o.as_posix() for o in objs), encoding='utf-8')
|
||||||
link_key = sha256_bytes(json.dumps([LINK_LIBS, cid] + [[o.name, o.stat().st_size, o.stat().st_mtime_ns]
|
# lld links several times faster than GNU ld; the stack matches tools/build_game.py's build
|
||||||
for o in objs]).encode())
|
ld = ['-fuse-ld=lld', '-Wl,--stack,16777216'] if (msys / 'bin' / 'ld.lld.exe').is_file() else []
|
||||||
|
lib = ['-Wl,--whole-archive', str(prebuilt[0]), '-Wl,--no-whole-archive'] if prebuilt else []
|
||||||
|
stamp = [[o.name, o.stat().st_size, o.stat().st_mtime_ns] for o in objs]
|
||||||
|
if prebuilt:
|
||||||
|
stamp.append([prebuilt[0].name, prebuilt[0].stat().st_size, sha256_file(prebuilt[0])])
|
||||||
|
link_key = sha256_bytes(json.dumps([LINK_LIBS, ld, cid] + stamp).encode())
|
||||||
state_link = cache_dir / 'link.key'
|
state_link = cache_dir / 'link.key'
|
||||||
if exe.is_file() and state_link.is_file() and state_link.read_text(encoding='utf-8') == link_key:
|
if exe.is_file() and state_link.is_file() and state_link.read_text(encoding='utf-8') == link_key:
|
||||||
say(' ocarina.exe is current, not linked again')
|
say(' ocarina.exe is current, not linked again')
|
||||||
@@ -647,8 +951,8 @@ def step_compile(out, cache_dir, msys, jobs):
|
|||||||
emit('phase', step='compile', phase='link')
|
emit('phase', step='compile', phase='link')
|
||||||
say(' linking')
|
say(' linking')
|
||||||
tmp = out / (EXE_NAME + '.new')
|
tmp = out / (EXE_NAME + '.new')
|
||||||
p = subprocess.run([str(clangxx), '-o', str(tmp), '@' + str(rsp), '-L', str(msys / 'lib'), *LINK_LIBS],
|
p = subprocess.run([str(clangxx), *ld, '-o', str(tmp), '@' + str(rsp), *lib, '-L', str(msys / 'lib'),
|
||||||
capture_output=True, text=True, env=env, errors='replace')
|
*LINK_LIBS], capture_output=True, text=True, env=env, errors='replace')
|
||||||
if p.returncode:
|
if p.returncode:
|
||||||
print(p.stderr[-4000:], file=sys.stderr)
|
print(p.stderr[-4000:], file=sys.stderr)
|
||||||
tmp.unlink(missing_ok=True)
|
tmp.unlink(missing_ok=True)
|
||||||
@@ -736,9 +1040,14 @@ def main():
|
|||||||
ap.add_argument('--msys', default=r'C:\msys64\ucrt64', help='MSYS2 UCRT64 folder (default C:\\msys64\\ucrt64)')
|
ap.add_argument('--msys', default=r'C:\msys64\ucrt64', help='MSYS2 UCRT64 folder (default C:\\msys64\\ucrt64)')
|
||||||
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4, help='parallel compiles')
|
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4, help='parallel compiles')
|
||||||
ap.add_argument('--events', action='store_true', help='machine-readable progress lines on stdout ("@@" + JSON)')
|
ap.add_argument('--events', action='store_true', help='machine-readable progress lines on stdout ("@@" + JSON)')
|
||||||
|
ap.add_argument('--make-runtime-lib', metavar='DIR', help='build the prebuilt runtime library of a release into DIR')
|
||||||
|
ap.add_argument('--obj', help='with --make-runtime-lib: the folder for its objects')
|
||||||
ap.add_argument('--until', choices=STEPS, help=argparse.SUPPRESS) # tests: stop after this step
|
ap.add_argument('--until', choices=STEPS, help=argparse.SUPPRESS) # tests: stop after this step
|
||||||
a = ap.parse_args()
|
a = ap.parse_args()
|
||||||
EVENTS = a.events
|
EVENTS = a.events
|
||||||
|
if a.make_runtime_lib:
|
||||||
|
make_runtime_lib(a.make_runtime_lib, Path(a.msys), a.jobs, a.obj)
|
||||||
|
return
|
||||||
given = bool(a.nup) + bool(a.exefs or a.romfs) + bool(a.rebuild)
|
given = bool(a.nup) + bool(a.exefs or a.romfs) + bool(a.rebuild)
|
||||||
if given != 1 or (not a.nup and not a.rebuild and not (a.exefs and a.romfs)):
|
if given != 1 or (not a.nup and not a.rebuild and not (a.exefs and a.romfs)):
|
||||||
ap.error('give --nup, both --exefs and --romfs, or --rebuild')
|
ap.error('give --nup, both --exefs and --romfs, or --rebuild')
|
||||||
@@ -774,29 +1083,60 @@ def main():
|
|||||||
state['kit'] = kit_version()
|
state['kit'] = kit_version()
|
||||||
keep_awake()
|
keep_awake()
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
|
romfs_job = None
|
||||||
runs = {'exefs': lambda: step_exefs(src, out), 'romfs': lambda: step_romfs(src, out, min(a.jobs, 8)),
|
runs = {'exefs': lambda: step_exefs(src, out), 'romfs': lambda: step_romfs(src, out, min(a.jobs, 8)),
|
||||||
'lift': lambda: step_lift(out, cache), 'compile': lambda: step_compile(out, cache, msys, a.jobs),
|
'lift': lambda: step_lift(out, cache), 'compile': lambda: step_compile(out, cache, msys, a.jobs, romfs_job),
|
||||||
'shaders': lambda: step_shaders(out)}
|
'shaders': lambda: step_shaders(out)}
|
||||||
for name in STEPS:
|
state_lock = threading.Lock() # the RomFS step records itself from its own thread
|
||||||
key = step_key(name, src.identity, out)
|
|
||||||
if state['steps'].get(name) == key:
|
def save():
|
||||||
say(f'{name}: done before')
|
with state_lock:
|
||||||
emit('step', step=name, state='skip')
|
|
||||||
else:
|
|
||||||
# a step that runs makes every step after it run too: their keys hash its output, not its key
|
|
||||||
for later in STEPS[STEPS.index(name):]:
|
|
||||||
state['steps'].pop(later, None)
|
|
||||||
say(f'{name}:')
|
|
||||||
emit('step', step=name, state='start')
|
|
||||||
t = time.time()
|
|
||||||
runs[name]()
|
|
||||||
state['steps'][name] = step_key(name, src.identity, out)
|
|
||||||
state_path.write_text(json.dumps(state, indent=1), encoding='utf-8')
|
state_path.write_text(json.dumps(state, indent=1), encoding='utf-8')
|
||||||
say(f'{name}: {time.time() - t:.0f} s')
|
|
||||||
emit('step', step=name, state='done', seconds=round(time.time() - t, 1))
|
def run(name):
|
||||||
if name == a.until:
|
t = time.time()
|
||||||
break
|
runs[name]()
|
||||||
state_path.write_text(json.dumps(state, indent=1), encoding='utf-8')
|
with state_lock:
|
||||||
|
state['steps'][name] = step_key(name, src.identity, out)
|
||||||
|
save()
|
||||||
|
say(f'{name}: {time.time() - t:.0f} s')
|
||||||
|
emit('step', step=name, state='done', seconds=round(time.time() - t, 1))
|
||||||
|
|
||||||
|
try:
|
||||||
|
for name in STEPS:
|
||||||
|
key = step_key(name, src.identity, out)
|
||||||
|
if state['steps'].get(name) == key:
|
||||||
|
say(f'{name}: done before')
|
||||||
|
emit('step', step=name, state='skip')
|
||||||
|
else:
|
||||||
|
# a step that runs makes every step after it run too: their keys hash its output, not its key
|
||||||
|
with state_lock:
|
||||||
|
for later in STEPS[STEPS.index(name):]:
|
||||||
|
state['steps'].pop(later, None)
|
||||||
|
say(f'{name}:')
|
||||||
|
emit('step', step=name, state='start')
|
||||||
|
if name == 'shaders' and romfs_job: # the shaders come out of the RomFS image
|
||||||
|
romfs_job.join()
|
||||||
|
if name == 'romfs' and a.until != 'romfs':
|
||||||
|
# The RomFS image is mostly disk work, the lift and the compile are processor work: they run side
|
||||||
|
# by side, and only the RomFS index and the files that include it wait for the image
|
||||||
|
# (step_compile). A first build takes about as long as the longer of the two, not their sum.
|
||||||
|
romfs_job = Background(lambda: run('romfs'))
|
||||||
|
else:
|
||||||
|
run(name)
|
||||||
|
if romfs_job and romfs_job.failed():
|
||||||
|
romfs_job.join()
|
||||||
|
if name == a.until:
|
||||||
|
break
|
||||||
|
if romfs_job:
|
||||||
|
romfs_job.join()
|
||||||
|
except SystemExit:
|
||||||
|
# a failed lift or compile: the RomFS image still finishes and is kept, so the next run starts after it
|
||||||
|
if romfs_job and romfs_job.thread.is_alive():
|
||||||
|
say('waiting for the RomFS image before stopping')
|
||||||
|
romfs_job.thread.join()
|
||||||
|
raise
|
||||||
|
save()
|
||||||
say(f'\nfinished in {(time.time() - t0) / 60:.1f} min: {out / EXE_NAME}')
|
say(f'\nfinished in {(time.time() - t0) / 60:.1f} min: {out / EXE_NAME}')
|
||||||
emit('end', exe=str(out / EXE_NAME), seconds=round(time.time() - t0, 1), kit=kit_version())
|
emit('end', exe=str(out / EXE_NAME), seconds=round(time.time() - t0, 1), kit=kit_version())
|
||||||
|
|
||||||
|
|||||||
@@ -12,12 +12,14 @@ checked against the sha256 in PINS.
|
|||||||
The release folder (--out) holds:
|
The release folder (--out) holds:
|
||||||
|
|
||||||
NX2navi/ the launcher folder exactly as NX2navi-Setup.exe installs it:
|
NX2navi/ the launcher folder exactly as NX2navi-Setup.exe installs it:
|
||||||
NX2navi.exe launcher/native/nx2navi.c with the Triforce icon (launcher/ui/art.py)
|
NX2navi.exe launcher/native/nx2navi.c with the Navi icon (launcher/ui/art.py)
|
||||||
python/ python.org's embeddable Python 3.14.9, tkinter and Tcl/Tk 9.0 from its tcltk.msi,
|
python/ python.org's embeddable Python 3.14.9, tkinter and Tcl/Tk 9.0 from its tcltk.msi,
|
||||||
the packages of tools/requirements-launcher.txt, runtime-id.txt
|
the packages of tools/requirements-launcher.txt, runtime-id.txt
|
||||||
app/current.txt, app/<version>/ launcher/ (without native/), runtime/, recomp/, the tools make_game.py uses,
|
app/current.txt, app/<version>/ launcher/ (without native/), runtime/, recomp/, the tools make_game.py uses,
|
||||||
bin/nx2navi_xlate.exe and .id (and amd_fidelityfx_vk.dll with --ffx), toolchain.lock.json (the MSYS2 packages of today,
|
bin/nx2navi_xlate.exe and .id (and amd_fidelityfx_vk.dll with --ffx),
|
||||||
pinned), feed.json, VERSION, the licence files
|
lib/libnx2navirt.a (the runtime, prebuilt with the release's compiler),
|
||||||
|
toolchain.lock.json (the MSYS2 packages of today, pinned), feed.json, VERSION, the
|
||||||
|
licence files
|
||||||
NX2navi-Setup-<version>.exe launcher/native/setup.c with the folder above appended as a zip: the one file
|
NX2navi-Setup-<version>.exe launcher/native/setup.c with the folder above appended as a zip: the one file
|
||||||
players download
|
players download
|
||||||
NX2navi-app-<version>.zip app/<version> alone: what the launcher downloads to update itself
|
NX2navi-app-<version>.zip app/<version> alone: what the launcher downloads to update itself
|
||||||
@@ -196,10 +198,33 @@ def native_compiler(lock):
|
|||||||
[windres, '--target=x86_64-w64-mingw32'])
|
[windres, '--target=x86_64-w64-mingw32'])
|
||||||
|
|
||||||
|
|
||||||
|
def build_runtime_lib(folder, ver, out, wine):
|
||||||
|
"""app/<version>/lib/libnx2navirt.a: the runtime compiled once here with the release's MSYS2 clang, so players
|
||||||
|
compile only the few runtime files that include per-install headers (tools/make_game.py --make-runtime-lib). It
|
||||||
|
needs MSYS2's own clang.exe: native on Windows, through Wine with --wine elsewhere; without either players compile
|
||||||
|
runtime/ themselves."""
|
||||||
|
msys = Layout(root=MAIN_ROOT / 'toolchain' / 'launcher-msys').msys
|
||||||
|
app = folder / 'app' / ver
|
||||||
|
args = ['--make-runtime-lib', app / 'lib', '--obj', out / 'native' / 'runtime-obj', '--msys', msys]
|
||||||
|
if os.name == 'nt':
|
||||||
|
run([sys.executable, app / 'tools' / 'make_game.py', *args])
|
||||||
|
elif wine:
|
||||||
|
def win(p):
|
||||||
|
return 'Z:' + str(Path(p).resolve()).replace('/', '\\')
|
||||||
|
env = dict(os.environ, WINEDEBUG='-all', NX2NAVI_AR=win(msys / 'bin' / 'ar.exe'))
|
||||||
|
run(['wine', folder / 'python' / 'python.exe', win(app / 'tools' / 'make_game.py'),
|
||||||
|
*[win(a) if isinstance(a, Path) else a for a in args]], env=env)
|
||||||
|
else:
|
||||||
|
say('note: no prebuilt runtime (it is built on Windows, or with --wine): players compile runtime/ themselves')
|
||||||
|
return
|
||||||
|
if not (app / 'lib' / 'libnx2navirt.a').is_file():
|
||||||
|
sys.exit('the prebuilt runtime was not written')
|
||||||
|
|
||||||
|
|
||||||
def build_native(work, cc, windres):
|
def build_native(work, cc, windres):
|
||||||
from launcher.ui import art
|
from launcher.ui import art
|
||||||
work.mkdir(parents=True, exist_ok=True)
|
work.mkdir(parents=True, exist_ok=True)
|
||||||
(work / 'nx2navi.ico').write_bytes(art.triforce_ico())
|
(work / 'nx2navi.ico').write_bytes(art.navi_ico())
|
||||||
shutil.copy2(ROOT / 'launcher' / 'native' / 'app.manifest', work / 'app.manifest')
|
shutil.copy2(ROOT / 'launcher' / 'native' / 'app.manifest', work / 'app.manifest')
|
||||||
shutil.copy2(ROOT / 'launcher' / 'native' / 'res.rc', work / 'res.rc')
|
shutil.copy2(ROOT / 'launcher' / 'native' / 'res.rc', work / 'res.rc')
|
||||||
res = (work / 'res.o').resolve()
|
res = (work / 'res.o').resolve()
|
||||||
@@ -261,6 +286,8 @@ def main():
|
|||||||
ap.add_argument('--notes', type=Path, help='release notes (markdown) for the manifest and the GitHub release')
|
ap.add_argument('--notes', type=Path, help='release notes (markdown) for the manifest and the GitHub release')
|
||||||
ap.add_argument('--lock', type=Path, help='a toolchain.lock.json to reuse instead of resolving today\'s packages')
|
ap.add_argument('--lock', type=Path, help='a toolchain.lock.json to reuse instead of resolving today\'s packages')
|
||||||
ap.add_argument('--version', help='the release version instead of VERSION\'s (test releases)')
|
ap.add_argument('--version', help='the release version instead of VERSION\'s (test releases)')
|
||||||
|
ap.add_argument('--wine', action='store_true', help='on Linux: build the prebuilt runtime with MSYS2\'s clang '
|
||||||
|
'through Wine')
|
||||||
ap.add_argument('--publish', action='store_true', help='upload as GitHub release v<version> with gh')
|
ap.add_argument('--publish', action='store_true', help='upload as GitHub release v<version> with gh')
|
||||||
ap.add_argument('--draft', action='store_true', help='with --publish: as a draft')
|
ap.add_argument('--draft', action='store_true', help='with --publish: as a draft')
|
||||||
a = ap.parse_args()
|
a = ap.parse_args()
|
||||||
@@ -273,12 +300,15 @@ def main():
|
|||||||
shutil.rmtree(out, ignore_errors=True)
|
shutil.rmtree(out, ignore_errors=True)
|
||||||
folder = out / 'NX2navi'
|
folder = out / 'NX2navi'
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
lock = json.loads(a.lock.read_text(encoding='utf-8')) if a.lock else toolchain.make_lock()
|
lock = (json.loads(a.lock.read_text(encoding='utf-8')) if a.lock
|
||||||
say(f'release {build}: toolchain lock with {len(lock["packages"])} packages')
|
else toolchain.make_lock(fast_repo=toolchain.FAST_REPO))
|
||||||
|
say(f'release {build}: toolchain lock with {len(lock["packages"])} packages'
|
||||||
|
+ (f' (CLANG64 clang left out: {lock["fast_skipped"]})' if lock.get('fast_skipped') else ''))
|
||||||
build_app(folder / 'app' / ver, ver, a.xlate, a.feed, lock, a.ffx)
|
build_app(folder / 'app' / ver, ver, a.xlate, a.feed, lock, a.ffx)
|
||||||
(folder / 'app' / 'current.txt').write_text(ver + '\n', encoding='utf-8')
|
(folder / 'app' / 'current.txt').write_text(ver + '\n', encoding='utf-8')
|
||||||
build_python(folder / 'python')
|
build_python(folder / 'python')
|
||||||
cc, windres = native_compiler(lock)
|
cc, windres = native_compiler(lock)
|
||||||
|
build_runtime_lib(folder, ver, out, a.wine)
|
||||||
stub, setup_stub = build_native(out / 'native', cc, windres)
|
stub, setup_stub = build_native(out / 'native', cc, windres)
|
||||||
shutil.copy2(stub, folder / 'NX2navi.exe')
|
shutil.copy2(stub, folder / 'NX2navi.exe')
|
||||||
check_folder(folder)
|
check_folder(folder)
|
||||||
|
|||||||
427
tools/menu_preview.cpp
Normal file
427
tools/menu_preview.cpp
Normal file
@@ -0,0 +1,427 @@
|
|||||||
|
// Draws the in-game settings menu and the performance overlay without the game, for looking at their design: the
|
||||||
|
// menu's own row code (runtime/ui/option_rows.cpp), its shapes (ui/menu_skin.cpp), the overlay panel
|
||||||
|
// (ui/perf_panel.cpp) and the text catalog (ui_text.c), with the few runtime calls they make answered here, laid out as
|
||||||
|
// menu.cpp layout_menu lays out the window. Dear ImGui's draw lists are rasterised on the CPU into an RGBA image.
|
||||||
|
// Without an art folder the window has its plain border in place of the game's ornamented frame and every box is plain
|
||||||
|
// shapes; with one (tools/menu_preview.py --romfs) the boxes use the game's textures as in the game. The given font
|
||||||
|
// stands in for the game's either way.
|
||||||
|
//
|
||||||
|
// tools/menu_preview.py builds and runs it:
|
||||||
|
// menu_preview <font.ttf> <scene: menu | overlay | boot> <width> <height> <out.rgba> [art folder]
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "imgui.h"
|
||||||
|
#include "imgui_internal.h"
|
||||||
|
|
||||||
|
#include "ui/menu_art.h"
|
||||||
|
#include "ui/menu_skin.h"
|
||||||
|
#include "ui/option_rows.h"
|
||||||
|
#include "ui/perf_panel.h"
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include "cfg.h"
|
||||||
|
#include "menu_sound.h"
|
||||||
|
#include "ui_text.h"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- what the rows and the catalog ask of the runtime: a few settings with the menu's values and defaults
|
||||||
|
|
||||||
|
static const CfgMeta kMeta[] = {
|
||||||
|
{"FULLSCREEN", "1", "0|1", 1}, {"WINDOW_SIZE", "", NULL, 1}, {"VK_PRESENT", "mailbox", "mailbox|fifo|immediate", 1},
|
||||||
|
{"GPU_INDEX", "", NULL, 0}, {"PERF_OVERLAY", "off", "off|fps|full", 1},
|
||||||
|
{"GAME_ASPECT", "16:9", "16:9|window|21:9|32:9", 0}, {"RENDER_SCALE", "", NULL, 0},
|
||||||
|
{"UPSCALER", "bilinear", "bilinear|fsr", 0}, {"SHARPNESS", "50", "0..100", 1},
|
||||||
|
{"ASPECT", "fit", "fit|stretch", 1}, {"MENU_LANG", "", NULL, 1},
|
||||||
|
};
|
||||||
|
static const struct { const char *key, *value; } kSet[] = {{"VK_PRESENT", "mailbox"}, {"PERF_OVERLAY", "full"}};
|
||||||
|
|
||||||
|
static const char *strip(const char *name) { return strncmp(name, "NX2NAVI_", 8) ? name : name + 8; }
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
const CfgMeta *cfg_meta(const char *key) {
|
||||||
|
for (const CfgMeta &m : kMeta)
|
||||||
|
if (!strcasecmp(m.key, strip(key))) return &m;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
const CfgMeta *cfg_meta_at(int i) { return i >= 0 && i < (int)(sizeof kMeta / sizeof *kMeta) ? &kMeta[i] : NULL; }
|
||||||
|
const char *cfg_get(const char *name) {
|
||||||
|
for (auto &s : kSet)
|
||||||
|
if (!strcasecmp(s.key, strip(name))) return s.value;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
const char *cfg_value(const char *name) {
|
||||||
|
const char *v = cfg_get(name);
|
||||||
|
const CfgMeta *m = cfg_meta(name);
|
||||||
|
return v ? v : m ? m->def : "";
|
||||||
|
}
|
||||||
|
int cfg_int(const char *name) { return atoi(cfg_value(name)); }
|
||||||
|
double cfg_double(const char *name) { return atof(cfg_value(name)); }
|
||||||
|
int cfg_bool(const char *name) { return strcmp(cfg_value(name), "0") != 0; }
|
||||||
|
int cfg_from_env(const char *) { return 0; }
|
||||||
|
void cfg_set(const char *, const char *) {}
|
||||||
|
int cfg_save(void) { return 1; }
|
||||||
|
int cfg_reset(const char *const *, int) { return 0; }
|
||||||
|
unsigned cfg_version(void) { return 1; }
|
||||||
|
void menu_sound_play(MenuSound) {}
|
||||||
|
const char *ov_language(void) { return "en-US"; }
|
||||||
|
const char *plat_ui_language(void) { return "en"; }
|
||||||
|
uint64_t plat_now_ns(void) {
|
||||||
|
struct timespec t;
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||||
|
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec;
|
||||||
|
}
|
||||||
|
void rt_log(const char *, ...) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the game's art, from files menu_preview.py decoded: NN.art, a width and a height (32-bit) and the RGBA pixels of
|
||||||
|
// the MenuArt NN, with the smaller levels the game uploads
|
||||||
|
|
||||||
|
struct Level {
|
||||||
|
int w, h;
|
||||||
|
std::vector<uint8_t> px;
|
||||||
|
};
|
||||||
|
static std::vector<Level> g_art[MENU_ART_COUNT];
|
||||||
|
|
||||||
|
static void art_load(const char *dir) {
|
||||||
|
for (int i = 0; i < MENU_ART_COUNT; i++) {
|
||||||
|
char path[1024];
|
||||||
|
snprintf(path, sizeof path, "%s/%02d.art", dir, i);
|
||||||
|
FILE *f = fopen(path, "rb");
|
||||||
|
if (!f) continue;
|
||||||
|
uint32_t size[2];
|
||||||
|
if (fread(size, 4, 2, f) == 2) {
|
||||||
|
Level top{(int)size[0], (int)size[1], std::vector<uint8_t>((size_t)size[0] * size[1] * 4)};
|
||||||
|
if (fread(top.px.data(), 1, top.px.size(), f) == top.px.size()) {
|
||||||
|
skin_art_prepare(i, top.px.data(), size[0], size[1]);
|
||||||
|
g_art[i].push_back(std::move(top));
|
||||||
|
while (g_art[i].size() < 6 && (g_art[i].back().w > 1 || g_art[i].back().h > 1)) {
|
||||||
|
const Level &last = g_art[i].back();
|
||||||
|
Level next{last.w > 1 ? last.w / 2 : 1, last.h > 1 ? last.h / 2 : 1, {}};
|
||||||
|
next.px.resize((size_t)next.w * next.h * 4);
|
||||||
|
skin_art_halve(last.px.data(), last.w, last.h, next.px.data(), next.w, next.h);
|
||||||
|
g_art[i].push_back(std::move(next));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fclose(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Texture ids in the draw lists: 1 is the font atlas, 2 and up the art.
|
||||||
|
extern "C" int menu_art(MenuArt id, ImTextureID *tex, float *w, float *h) {
|
||||||
|
if ((unsigned)id >= MENU_ART_COUNT || g_art[id].empty()) return 0;
|
||||||
|
*tex = (ImTextureID)(intptr_t)(2 + id);
|
||||||
|
if (w) *w = (float)g_art[id][0].w;
|
||||||
|
if (h) *h = (float)g_art[id][0].h;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the scenes
|
||||||
|
|
||||||
|
static void backdrop(float w, float h) {
|
||||||
|
// a dim field and sky, as the game shows behind the menu; then the menu's own dimming (menu.cpp layout_menu)
|
||||||
|
ImDrawList *bg = ImGui::GetBackgroundDrawList();
|
||||||
|
bg->AddRectFilledMultiColor(ImVec2(0, 0), ImVec2(w, h * 0.55f), IM_COL32(62, 70, 74, 255), IM_COL32(70, 76, 78, 255),
|
||||||
|
IM_COL32(52, 64, 52, 255), IM_COL32(48, 60, 50, 255));
|
||||||
|
bg->AddRectFilledMultiColor(ImVec2(0, h * 0.55f), ImVec2(w, h), IM_COL32(52, 64, 52, 255), IM_COL32(48, 60, 50, 255),
|
||||||
|
IM_COL32(30, 38, 30, 255), IM_COL32(28, 34, 28, 255));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void triforce(ImDrawList *dl, float x, float y, float h, ImU32 col) {
|
||||||
|
float w = h * 1.1547f;
|
||||||
|
ImVec2 t(x, y), l(x - w / 2, y + h), r(x + w / 2, y + h), ml(x - w / 4, y + h / 2), mr(x + w / 4, y + h / 2), mb(x, y + h);
|
||||||
|
dl->AddTriangleFilled(t, mr, ml, col);
|
||||||
|
dl->AddTriangleFilled(ml, mb, l, col);
|
||||||
|
dl->AddTriangleFilled(mr, r, mb, col);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void scene_menu(float w, float h, float scale, ImFont *title, bool first) {
|
||||||
|
backdrop(w, h);
|
||||||
|
ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(0, 0), ImVec2(w, h), IM_COL32(10, 6, 2, 150));
|
||||||
|
float ww = fminf(w * 0.88f, 1400 * scale), wh = fminf(h * 0.86f, 820 * scale);
|
||||||
|
ImGui::SetNextWindowPos(ImVec2(w * 0.5f, h * 0.5f), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
|
||||||
|
ImGui::SetNextWindowSize(ImVec2(ww, wh), ImGuiCond_Always);
|
||||||
|
ImTextureID frame_tex;
|
||||||
|
const bool framed = menu_art(MENU_ART_FRAME_DECO, &frame_tex, nullptr, nullptr);
|
||||||
|
if (framed) ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);
|
||||||
|
ImGui::Begin("##menu", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings);
|
||||||
|
if (framed) ImGui::PopStyleVar();
|
||||||
|
const ImVec2 win_p = ImGui::GetWindowPos(), win_s = ImGui::GetWindowSize();
|
||||||
|
if (framed) { // as menu.cpp layout_menu draws it
|
||||||
|
ImDrawList *fdl = ImGui::GetWindowDrawList();
|
||||||
|
const float ox = 15 * scale, oy = 30 * scale;
|
||||||
|
fdl->PushClipRectFullScreen();
|
||||||
|
for (int turned = 0; turned < 2; turned++)
|
||||||
|
menu_art_draw9_turned(fdl, MENU_ART_FRAME_DECO, ImVec2(win_p.x - ox, win_p.y - oy),
|
||||||
|
ImVec2(win_p.x + win_s.x + ox, win_p.y + win_s.y + oy), 96 * scale, 0.2f,
|
||||||
|
IM_COL32(236, 196, 112, 235), 0, turned);
|
||||||
|
fdl->PopClipRect();
|
||||||
|
}
|
||||||
|
const ImVec4 gold(0.93f, 0.76f, 0.38f, 1);
|
||||||
|
ImGui::PushFont(title);
|
||||||
|
ImVec2 at = ImGui::GetCursorScreenPos();
|
||||||
|
float th = ImGui::GetTextLineHeight();
|
||||||
|
triforce(ImGui::GetWindowDrawList(), at.x + th * 0.6f, at.y + th * 0.02f, th * 0.96f, ImGui::GetColorU32(gold));
|
||||||
|
ImGui::SetCursorScreenPos(ImVec2(at.x + th * 1.5f, at.y));
|
||||||
|
ImGui::TextColored(gold, "Ocarina of Time");
|
||||||
|
ImGui::SameLine();
|
||||||
|
ImGui::TextDisabled("|");
|
||||||
|
ImGui::SameLine();
|
||||||
|
ImGui::TextUnformatted(menu_text(UI_MENU_TITLE));
|
||||||
|
const float title_end = ImGui::GetItemRectMax().x;
|
||||||
|
ImGui::PopFont();
|
||||||
|
const char *version = "NX2navi 0.5.0 - game 1.1.1";
|
||||||
|
float version_x = ImGui::GetWindowWidth() - ImGui::GetStyle().WindowPadding.x - ImGui::CalcTextSize(version).x;
|
||||||
|
if (ImGui::GetWindowPos().x + version_x >= title_end + ImGui::GetStyle().ItemSpacing.x * 2) {
|
||||||
|
ImGui::SameLine(version_x);
|
||||||
|
ImGui::TextDisabled("%s", version);
|
||||||
|
}
|
||||||
|
const ImGuiStyle &st = ImGui::GetStyle();
|
||||||
|
float bottom = ImGui::GetFrameHeight() + st.ItemSpacing.y * 2;
|
||||||
|
static const UiTextId tabs[] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS};
|
||||||
|
if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_NoTabListScrollingButtons)) {
|
||||||
|
for (int k = 0; k < 4; k++) {
|
||||||
|
char label[96];
|
||||||
|
snprintf(label, sizeof label, " %s ###tab%d", menu_text(tabs[k]), k);
|
||||||
|
bool shown = skin_tab_item(label, menu_text(tabs[k]), 0, scale, title);
|
||||||
|
if (!shown) continue;
|
||||||
|
ImGui::Spacing();
|
||||||
|
opt_reserve_bottom(bottom);
|
||||||
|
if (first) opt_focus_first();
|
||||||
|
// the Screen tab's first rows, as menu.cpp tab_screen shows them
|
||||||
|
opt_begin("##screen", scale);
|
||||||
|
opt_toggle("NX2NAVI_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC);
|
||||||
|
static const char *const sizes[] = {"", "1920x1080"};
|
||||||
|
static const char *const size_names[] = {"1920 \xC3\x97 1080", "1920 \xC3\x97 1080"};
|
||||||
|
opt_choice_list("NX2NAVI_WINDOW_SIZE", UI_MENU_WINDOW_SIZE, sizes, size_names, 2, UI_MENU_WINDOW_SIZE_DESC, 0);
|
||||||
|
opt_toggle_value("NX2NAVI_VK_PRESENT", UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_DESC, "mailbox", "immediate");
|
||||||
|
static const char *const gpus[] = {""};
|
||||||
|
static const char *const gpu_names[] = {"NVIDIA GeForce RTX 3050 Ti Laptop GPU"}; // a long name
|
||||||
|
opt_choice_list("NX2NAVI_GPU_INDEX", UI_MENU_GPU, gpus, gpu_names, 1, UI_MENU_GPU_DESC, 0);
|
||||||
|
static const UiTextId perf[] = {UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL};
|
||||||
|
opt_choice("NX2NAVI_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC);
|
||||||
|
opt_group(UI_MENU_GRAPHICS);
|
||||||
|
static const UiTextId wide[] = {UI_MENU_GAME_ASPECT_16_9, UI_MENU_GAME_ASPECT_WINDOW, UI_MENU_GAME_ASPECT_21_9,
|
||||||
|
UI_MENU_GAME_ASPECT_32_9};
|
||||||
|
opt_choice("NX2NAVI_GAME_ASPECT", UI_MENU_GAME_ASPECT, wide, 4, UI_MENU_GAME_ASPECT_DESC);
|
||||||
|
opt_slider("NX2NAVI_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%");
|
||||||
|
opt_end();
|
||||||
|
ImGui::EndTabItem();
|
||||||
|
}
|
||||||
|
ImGui::EndTabBar();
|
||||||
|
}
|
||||||
|
ImGui::Spacing();
|
||||||
|
float y = ImGui::GetCursorPosY();
|
||||||
|
{
|
||||||
|
float sy = win_p.y + y, fh = ImGui::GetFrameHeight();
|
||||||
|
menu_art_draw(ImGui::GetWindowDrawList(), MENU_ART_GUIDE_BAR, ImVec2(win_p.x + st.WindowPadding.x, sy),
|
||||||
|
ImVec2(win_p.x + win_s.x - st.WindowPadding.x, sy + fh), IM_COL32(96, 70, 36, 170));
|
||||||
|
}
|
||||||
|
const char *cont = menu_text(UI_MENU_CONTINUE), *restart = menu_text(UI_MENU_RESTART_YES), *quit = menu_text(UI_MENU_QUIT);
|
||||||
|
float bw = fmaxf(fmaxf(ImGui::CalcTextSize(cont).x, ImGui::CalcTextSize(restart).x), ImGui::CalcTextSize(quit).x) + st.FramePadding.x * 4;
|
||||||
|
float gap = st.ItemSpacing.x + skin_cursor_reach(scale);
|
||||||
|
ImGui::SetCursorPos(ImVec2(fmaxf(st.WindowPadding.x, ImGui::GetWindowWidth() - st.WindowPadding.x - bw * 3 - gap * 2), y));
|
||||||
|
skin_widget_button(cont, ImVec2(bw, 0), scale);
|
||||||
|
ImGui::SameLine(0, gap);
|
||||||
|
skin_widget_button(restart, ImVec2(bw, 0), scale);
|
||||||
|
ImGui::SameLine(0, gap);
|
||||||
|
skin_widget_button(quit, ImVec2(bw, 0), scale);
|
||||||
|
ImGui::End();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void scene_overlay(float w, float h, float scale) {
|
||||||
|
backdrop(w, h);
|
||||||
|
static PerfPanel p; // the numbers of the screenshot the overlay was redesigned from
|
||||||
|
PerfStats &s = p.s;
|
||||||
|
s.fps = 60, s.frame_ms_avg = 16.7f, s.frame_ms_max = 20.2f, s.low1_fps = 47, s.low01_fps = 8;
|
||||||
|
for (int i = 0; i < PERF_HISTORY; i++) s.frame_ms[i] = 16.7f + 1.4f * sinf(i * 0.7f) + (i % 17 == 0 ? 3.5f : 0);
|
||||||
|
snprintf(s.cpu_name, sizeof s.cpu_name, "AMD Ryzen 7 5800X3D 8-Core Processor");
|
||||||
|
s.cpu_total_pct = 50, s.cpu_game_pct = 44, s.cpu_temp_c = -1;
|
||||||
|
s.ram_used_mb = 23.0f * 1024, s.ram_total_mb = 31.9f * 1024, s.ram_game_mb = 8.6f * 1024;
|
||||||
|
snprintf(s.gpu_name, sizeof s.gpu_name, "AMD Radeon RX 7900 XT");
|
||||||
|
s.gpu_pct = 56, s.gpu_temp_c = 69, s.gpu_power_w = 107, s.gpu_clock_mhz = 1312, s.vram_used_mb = 5.3f * 1024,
|
||||||
|
s.vram_total_mb = 20.0f * 1024;
|
||||||
|
s.replay_ms = 0.60f, s.gpu_ms = 1.28f, s.pipe_wait_ms = 0, s.xlate_ms = 0, s.tex_uploads = 0;
|
||||||
|
p.version = "NX2navi 0.5.0, game 1.1.1";
|
||||||
|
snprintf(p.picture[0], 64, "1920x1080");
|
||||||
|
snprintf(p.picture[1], 64, "2560x1440");
|
||||||
|
snprintf(p.picture[3], 64, "bilinear");
|
||||||
|
snprintf(p.picture[4], 64, "60 FPS");
|
||||||
|
snprintf(p.picture[5], 64, "VSync");
|
||||||
|
p.scene_known = false, p.fg_fps = 60, p.under_menu = false;
|
||||||
|
perf_panel_draw(&p, w, scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void scene_boot(float w, float h, float scale, ImFont *title) {
|
||||||
|
// the boot screen's box over the black the window shows then (menu.cpp menu_boot_frame), half way through the
|
||||||
|
// pipelines
|
||||||
|
ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(0, 0), ImVec2(w, h), IM_COL32(0, 0, 0, 255));
|
||||||
|
char step[160];
|
||||||
|
snprintf(step, sizeof step, ui_text(UI_BOOT_PIPELINES), 1603LL, 3235LL);
|
||||||
|
skin_boot_panel(ImGui::GetForegroundDrawList(), title, title->FontSize, ImGui::GetFont(), ImGui::GetFontSize(),
|
||||||
|
ui_text(UI_BOOT_TITLE), step, ui_text(UI_BOOT_HINT), 1603.0f / 3235.0f, 0, w, h, scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the rasteriser: every triangle of the draw lists, its colour times the font atlas, blended over the image
|
||||||
|
|
||||||
|
struct Image {
|
||||||
|
int w, h;
|
||||||
|
std::vector<float> px; // straight RGBA, 0..1
|
||||||
|
};
|
||||||
|
|
||||||
|
// Twice the signed area of (e0, e1, p), computed with the edge's ends in one fixed order, so the two triangles that share
|
||||||
|
// an edge get exactly opposite values for a pixel and none is shaded twice or left out along it.
|
||||||
|
static float edge(ImVec2 e0, ImVec2 e1, float px, float py) {
|
||||||
|
bool swap = e0.x > e1.x || (e0.x == e1.x && e0.y > e1.y);
|
||||||
|
if (swap) {
|
||||||
|
ImVec2 t = e0;
|
||||||
|
e0 = e1, e1 = t;
|
||||||
|
}
|
||||||
|
float v = (e0.x - px) * (e1.y - py) - (e0.y - py) * (e1.x - px);
|
||||||
|
return swap ? -v : v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The atlas at (u, v), bilinear, clamped to its edges; 0..1.
|
||||||
|
static void sample(const uint8_t *atlas, int aw, int ah, float u, float v, float out[4]) {
|
||||||
|
float x = u * aw - 0.5f, y = v * ah - 0.5f;
|
||||||
|
int x0 = (int)floorf(x), y0 = (int)floorf(y);
|
||||||
|
float fx = x - x0, fy = y - y0;
|
||||||
|
for (int k = 0; k < 4; k++) out[k] = 0;
|
||||||
|
for (int j = 0; j < 2; j++)
|
||||||
|
for (int i = 0; i < 2; i++) {
|
||||||
|
int xx = x0 + i < 0 ? 0 : x0 + i >= aw ? aw - 1 : x0 + i, yy = y0 + j < 0 ? 0 : y0 + j >= ah ? ah - 1 : y0 + j;
|
||||||
|
float wgt = (i ? fx : 1 - fx) * (j ? fy : 1 - fy);
|
||||||
|
const uint8_t *t = atlas + 4 * ((size_t)yy * aw + xx);
|
||||||
|
for (int k = 0; k < 4; k++) out[k] += wgt * t[k] / 255.0f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The art at (u, v) at level of detail lod, trilinear between its levels, as the game's sampler reads it.
|
||||||
|
static void sample_art(const std::vector<Level> &levels, float u, float v, float lod, float out[4]) {
|
||||||
|
const float top = (float)levels.size() - 1;
|
||||||
|
lod = lod < 0 ? 0 : lod > top ? top : lod;
|
||||||
|
int l0 = (int)floorf(lod), l1 = l0 + 1 < (int)levels.size() ? l0 + 1 : l0;
|
||||||
|
float a[4], b[4], f = lod - l0;
|
||||||
|
sample(levels[l0].px.data(), levels[l0].w, levels[l0].h, u, v, a);
|
||||||
|
sample(levels[l1].px.data(), levels[l1].w, levels[l1].h, u, v, b);
|
||||||
|
for (int k = 0; k < 4; k++) out[k] = a[k] + (b[k] - a[k]) * f;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void raster(const ImDrawData *dd, Image &img, const uint8_t *atlas, int aw, int ah) {
|
||||||
|
for (int l = 0; l < dd->CmdListsCount; l++) {
|
||||||
|
const ImDrawList *dl = dd->CmdLists[l];
|
||||||
|
const ImDrawVert *vb = dl->VtxBuffer.Data;
|
||||||
|
const ImDrawIdx *ib = dl->IdxBuffer.Data;
|
||||||
|
for (const ImDrawCmd &cmd : dl->CmdBuffer) {
|
||||||
|
if (cmd.UserCallback) continue;
|
||||||
|
int cx0 = (int)fmaxf(0, cmd.ClipRect.x), cy0 = (int)fmaxf(0, cmd.ClipRect.y);
|
||||||
|
int cx1 = (int)fminf((float)img.w, cmd.ClipRect.z), cy1 = (int)fminf((float)img.h, cmd.ClipRect.w);
|
||||||
|
const intptr_t tex_id = (intptr_t)cmd.GetTexID();
|
||||||
|
const std::vector<Level> *art = tex_id >= 2 && tex_id < 2 + MENU_ART_COUNT ? &g_art[tex_id - 2] : nullptr;
|
||||||
|
for (unsigned i = 0; i + 2 < cmd.ElemCount; i += 3) {
|
||||||
|
const ImDrawVert &a = vb[cmd.VtxOffset + ib[cmd.IdxOffset + i]], &b = vb[cmd.VtxOffset + ib[cmd.IdxOffset + i + 1]],
|
||||||
|
&c = vb[cmd.VtxOffset + ib[cmd.IdxOffset + i + 2]];
|
||||||
|
float area = (b.pos.x - a.pos.x) * (c.pos.y - a.pos.y) - (b.pos.y - a.pos.y) * (c.pos.x - a.pos.x);
|
||||||
|
if (fabsf(area) < 1e-6f) continue;
|
||||||
|
// the top-left rule: a pixel centre on an edge two triangles share is shaded by one of them only
|
||||||
|
// (edge k is the one opposite vertex k, run in the triangle's own winding)
|
||||||
|
const ImVec2 *vtx[3] = {&a.pos, &b.pos, &c.pos};
|
||||||
|
bool top_left[3];
|
||||||
|
for (int k = 0; k < 3; k++) {
|
||||||
|
ImVec2 e0 = *vtx[(k + 1) % 3], e1 = *vtx[(k + 2) % 3];
|
||||||
|
float dx = (e1.x - e0.x) * (area > 0 ? 1 : -1), dy = (e1.y - e0.y) * (area > 0 ? 1 : -1);
|
||||||
|
top_left[k] = (dy == 0 && dx < 0) || dy > 0;
|
||||||
|
}
|
||||||
|
int x0 = (int)fmaxf((float)cx0, floorf(fminf(a.pos.x, fminf(b.pos.x, c.pos.x))));
|
||||||
|
int x1 = (int)fminf((float)cx1, ceilf(fmaxf(a.pos.x, fmaxf(b.pos.x, c.pos.x))));
|
||||||
|
int y0 = (int)fmaxf((float)cy0, floorf(fminf(a.pos.y, fminf(b.pos.y, c.pos.y))));
|
||||||
|
int y1 = (int)fminf((float)cy1, ceilf(fmaxf(a.pos.y, fmaxf(b.pos.y, c.pos.y))));
|
||||||
|
float lod = 0;
|
||||||
|
if (art && !art->empty()) { // texels per screen pixel along the steeper axis
|
||||||
|
const float tw = (float)(*art)[0].w, th = (float)(*art)[0].h;
|
||||||
|
const float e1x = b.pos.x - a.pos.x, e1y = b.pos.y - a.pos.y, e2x = c.pos.x - a.pos.x, e2y = c.pos.y - a.pos.y;
|
||||||
|
const float du1 = (b.uv.x - a.uv.x) * tw, dv1 = (b.uv.y - a.uv.y) * th, du2 = (c.uv.x - a.uv.x) * tw, dv2 = (c.uv.y - a.uv.y) * th;
|
||||||
|
const float dudx = (du1 * e2y - du2 * e1y) / area, dvdx = (dv1 * e2y - dv2 * e1y) / area;
|
||||||
|
const float dudy = (du2 * e1x - du1 * e2x) / area, dvdy = (dv2 * e1x - dv1 * e2x) / area;
|
||||||
|
const float rho = fmaxf(sqrtf(dudx * dudx + dvdx * dvdx), sqrtf(dudy * dudy + dvdy * dvdy));
|
||||||
|
lod = rho > 0 ? log2f(rho) : 0;
|
||||||
|
}
|
||||||
|
for (int y = y0; y < y1; y++)
|
||||||
|
for (int x = x0; x < x1; x++) {
|
||||||
|
float px = x + 0.5f, py = y + 0.5f;
|
||||||
|
float w0 = edge(b.pos, c.pos, px, py) / area, w1 = edge(c.pos, a.pos, px, py) / area,
|
||||||
|
w2 = edge(a.pos, b.pos, px, py) / area;
|
||||||
|
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
|
||||||
|
if ((w0 == 0 && !top_left[0]) || (w1 == 0 && !top_left[1]) || (w2 == 0 && !top_left[2])) continue;
|
||||||
|
float u = w0 * a.uv.x + w1 * b.uv.x + w2 * c.uv.x, v = w0 * a.uv.y + w1 * b.uv.y + w2 * c.uv.y;
|
||||||
|
float col[4];
|
||||||
|
for (int k = 0; k < 4; k++) {
|
||||||
|
float ca = (a.col >> (8 * k)) & 255, cb = (b.col >> (8 * k)) & 255, cc = (c.col >> (8 * k)) & 255;
|
||||||
|
col[k] = (w0 * ca + w1 * cb + w2 * cc) / 255.0f;
|
||||||
|
}
|
||||||
|
float t[4];
|
||||||
|
if (art && !art->empty()) sample_art(*art, u, v, lod, t);
|
||||||
|
else sample(atlas, aw, ah, u, v, t); // filtered, as the GPU samples the atlas's baked lines
|
||||||
|
for (int k = 0; k < 4; k++) col[k] *= t[k];
|
||||||
|
float *d = &img.px[4 * ((size_t)y * img.w + x)], sa = col[3];
|
||||||
|
for (int k = 0; k < 3; k++) d[k] = col[k] * sa + d[k] * (1 - sa);
|
||||||
|
d[3] = sa + d[3] * (1 - sa);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
if (argc != 6 && argc != 7) {
|
||||||
|
fprintf(stderr, "usage: %s <font.ttf> <menu|overlay|boot> <width> <height> <out.rgba> [art folder]\n", argv[0]);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
const char *font = argv[1], *scene = argv[2], *out = argv[5];
|
||||||
|
if (argc == 7) art_load(argv[6]);
|
||||||
|
int w = atoi(argv[3]), h = atoi(argv[4]);
|
||||||
|
float scale = fmaxf(fminf((float)h, w * 0.68f), 720.0f) / 1080.0f; // as menu.cpp menu_scale at 100 % display scale
|
||||||
|
ImGui::CreateContext();
|
||||||
|
ImGuiIO &io = ImGui::GetIO();
|
||||||
|
io.IniFilename = nullptr;
|
||||||
|
io.DisplaySize = ImVec2((float)w, (float)h);
|
||||||
|
io.DeltaTime = 1.0f / 60;
|
||||||
|
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_NavEnableGamepad;
|
||||||
|
io.Fonts->AddFontFromFileTTF(font, 26.0f * scale);
|
||||||
|
ImFont *title = io.Fonts->AddFontFromFileTTF(font, 31.0f * scale);
|
||||||
|
skin_atlas_add(io.Fonts);
|
||||||
|
skin_atlas_fill(io.Fonts);
|
||||||
|
uint8_t *atlas;
|
||||||
|
int aw, ah;
|
||||||
|
io.Fonts->GetTexDataAsRGBA32(&atlas, &aw, &ah);
|
||||||
|
io.Fonts->SetTexID((ImTextureID)1);
|
||||||
|
ImGuiStyle &st = ImGui::GetStyle();
|
||||||
|
skin_style(st);
|
||||||
|
st.ScaleAllSizes(scale);
|
||||||
|
ImGui::SetCurrentFont(io.Fonts->Fonts[0]);
|
||||||
|
for (int frame = 0; frame < 4; frame++) { // a few frames: sizes settle and the first row takes the cursor
|
||||||
|
ImGui::NewFrame();
|
||||||
|
if (!strcmp(scene, "menu")) scene_menu((float)w, (float)h, scale, title, frame == 0);
|
||||||
|
else if (!strcmp(scene, "boot")) scene_boot((float)w, (float)h, scale, title);
|
||||||
|
else scene_overlay((float)w, (float)h, scale);
|
||||||
|
ImGui::Render();
|
||||||
|
}
|
||||||
|
Image img{w, h, std::vector<float>((size_t)w * h * 4, 0.0f)};
|
||||||
|
raster(ImGui::GetDrawData(), img, atlas, aw, ah);
|
||||||
|
FILE *f = fopen(out, "wb");
|
||||||
|
if (!f) return 1;
|
||||||
|
std::vector<uint8_t> bytes((size_t)w * h * 4);
|
||||||
|
for (size_t i = 0; i < bytes.size(); i++) bytes[i] = (uint8_t)(fminf(1, fmaxf(0, img.px[i])) * 255 + 0.5f);
|
||||||
|
fwrite(bytes.data(), 1, bytes.size(), f);
|
||||||
|
fclose(f);
|
||||||
|
ImGui::DestroyContext();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
101
tools/menu_preview.py
Normal file
101
tools/menu_preview.py
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
"""Draw the in-game settings menu and the performance overlay without the game (tools/menu_preview.cpp).
|
||||||
|
|
||||||
|
python tools/menu_preview.py [--out build/menu-preview] [--font FILE] [--size 1920x1080] [--romfs FOLDER]
|
||||||
|
|
||||||
|
Builds tools/menu_preview.cpp with the menu's own row, shape, overlay and text code and Dear ImGui (host clang++, into
|
||||||
|
build/menu-preview), runs it for each scene and writes menu.png, overlay.png and boot.png. Without --romfs no game
|
||||||
|
files are read: the window has its plain border in place of the game's ornamented frame and the boxes are plain
|
||||||
|
shapes. With --romfs, an extracted RomFS folder, the textures listed in runtime/ui/menu_art.cpp are decoded into --out
|
||||||
|
and the boxes look as they do in the game (needs what tools/ui_textures.py needs). The font given (default: DejaVu
|
||||||
|
Sans, else the first TrueType font found) stands in for the game's either way.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import zlib
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
RT = ROOT / 'runtime'
|
||||||
|
SOURCES = [ROOT / 'tools' / 'menu_preview.cpp', RT / 'ui' / 'option_rows.cpp', RT / 'ui' / 'menu_skin.cpp',
|
||||||
|
RT / 'ui' / 'perf_panel.cpp', RT / 'ui_text.c'] + sorted((RT / 'third_party' / 'imgui').glob('imgui*.cpp'))
|
||||||
|
FONTS = ['/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 'C:/Windows/Fonts/segoeui.ttf', 'C:/Windows/Fonts/arial.ttf']
|
||||||
|
|
||||||
|
|
||||||
|
def png(path, w, h, rgba):
|
||||||
|
"""An 8-bit RGBA PNG of the raw pixels."""
|
||||||
|
rows = b''.join(b'\0' + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
|
||||||
|
|
||||||
|
def chunk(kind, data):
|
||||||
|
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)
|
||||||
|
Path(path).write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0)) +
|
||||||
|
chunk(b'IDAT', zlib.compress(rows, 6)) + chunk(b'IEND', b''))
|
||||||
|
|
||||||
|
|
||||||
|
def build(out):
|
||||||
|
cxx = shutil.which('clang++') or shutil.which('g++')
|
||||||
|
if not cxx:
|
||||||
|
sys.exit('needs clang++ or g++ on PATH')
|
||||||
|
exe = out / ('menu_preview.exe' if os.name == 'nt' else 'menu_preview')
|
||||||
|
objs = []
|
||||||
|
for src in SOURCES:
|
||||||
|
obj = out / (src.stem + '.o')
|
||||||
|
if not obj.is_file() or obj.stat().st_mtime < max(src.stat().st_mtime, (RT / 'ui' / 'menu_skin.h').stat().st_mtime,
|
||||||
|
(RT / 'ui' / 'menu_art.h').stat().st_mtime):
|
||||||
|
lang = ['-x', 'c', '-std=gnu11'] if src.suffix == '.c' else ['-x', 'c++', '-std=gnu++17']
|
||||||
|
cmd = [cxx, *lang, '-c', '-O2', '-w', '-I', str(RT), '-I', str(RT / 'third_party' / 'imgui'), str(src), '-o',
|
||||||
|
str(obj)]
|
||||||
|
if subprocess.run(cmd).returncode:
|
||||||
|
sys.exit(f'{src.name} did not compile')
|
||||||
|
objs.append(str(obj))
|
||||||
|
if subprocess.run([cxx, *objs, '-o', str(exe), '-lm']).returncode:
|
||||||
|
sys.exit('the link failed')
|
||||||
|
return exe
|
||||||
|
|
||||||
|
|
||||||
|
def decode_art(romfs, out):
|
||||||
|
"""The textures of runtime/ui/menu_art.cpp kNames as out/art/NN.art for menu_preview.cpp; that folder."""
|
||||||
|
sys.path.insert(0, str(ROOT / 'tools'))
|
||||||
|
import ui_textures
|
||||||
|
source = (RT / 'ui' / 'menu_art.cpp').read_text(encoding='utf-8')
|
||||||
|
names = re.findall(r'"([^"]+)"', re.search(r'kNames\[MENU_ART_COUNT\] = \{(.*?)\};', source, re.S).group(1))
|
||||||
|
data = ui_textures.Romfs(romfs).read(f'{ui_textures.ARCHIVES}/Common.Product.100.Nin_Ounce_NVN2.bntx.zs')
|
||||||
|
textures = {t['name']: t for t in ui_textures.bntx_textures(data)}
|
||||||
|
art = out / 'art'
|
||||||
|
art.mkdir(parents=True, exist_ok=True)
|
||||||
|
lib = ui_textures.astc_library(out)
|
||||||
|
for i, name in enumerate(names):
|
||||||
|
rgba = ui_textures.decode(textures[name], data, lib)
|
||||||
|
(art / f'{i:02}.art').write_bytes(struct.pack('<II', rgba.shape[1], rgba.shape[0]) + rgba.tobytes())
|
||||||
|
return art
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
ap.add_argument('--out', type=Path, default=ROOT / 'build' / 'menu-preview')
|
||||||
|
ap.add_argument('--font', help='a TrueType font for the text')
|
||||||
|
ap.add_argument('--size', default='1920x1080')
|
||||||
|
ap.add_argument('--romfs', type=Path, help="an extracted RomFS folder: draw the game's textures")
|
||||||
|
a = ap.parse_args()
|
||||||
|
font = a.font or next((f for f in FONTS if Path(f).is_file()), None)
|
||||||
|
if not font:
|
||||||
|
sys.exit('no font found: give one with --font')
|
||||||
|
w, h = (int(x) for x in a.size.lower().split('x'))
|
||||||
|
a.out.mkdir(parents=True, exist_ok=True)
|
||||||
|
exe = build(a.out)
|
||||||
|
art = [str(decode_art(a.romfs, a.out))] if a.romfs else []
|
||||||
|
for scene in ('menu', 'overlay', 'boot'):
|
||||||
|
raw = a.out / f'{scene}.rgba'
|
||||||
|
if subprocess.run([str(exe), font, scene, str(w), str(h), str(raw), *art]).returncode:
|
||||||
|
sys.exit(f'the {scene} scene failed')
|
||||||
|
png(a.out / f'{scene}.png', w, h, raw.read_bytes())
|
||||||
|
raw.unlink()
|
||||||
|
print(a.out / f'{scene}.png')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
# Packages of the launcher release's bundled Python 3.14.9 (tools/make_launcher.py): what the launcher and
|
# Packages of the launcher release's bundled Python 3.14.9 (tools/make_launcher.py): what the launcher and
|
||||||
# tools/make_game.py import. numpy: recomp/gen.py and the window's drawing (launcher/ui/art.py). lz4: NSO segments.
|
# tools/make_game.py import. numpy: recomp/gen.py and the window's drawing (launcher/ui/art.py). lz4: NSO segments.
|
||||||
# zstandard: tools/nup.py. zbic is not bundled: the launcher downloads it from PyPI on the player's PC.
|
# zstandard: tools/nup.py. truststore: Windows' own certificate check for the launcher's downloads (launcher/net.py),
|
||||||
|
# pinned to its wheel's sha256 too (uv checks the hashes a line gives). zbic is not bundled: the launcher downloads
|
||||||
|
# it from PyPI on the player's PC.
|
||||||
numpy==2.5.4
|
numpy==2.5.4
|
||||||
lz4==4.4.5
|
lz4==4.4.5
|
||||||
zstandard==0.25.0
|
zstandard==0.25.0
|
||||||
|
truststore==0.10.5 --hash=sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c
|
||||||
|
|||||||
245
tools/ui_textures.py
Normal file
245
tools/ui_textures.py
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
"""List and dump the game's interface textures, for choosing the art the settings menu draws (runtime/ui/menu_art.cpp).
|
||||||
|
|
||||||
|
python tools/ui_textures.py ROMFS [--out build/ui-textures] [--archive Common] [--match REGEX] [--sheet]
|
||||||
|
|
||||||
|
ROMFS is an extracted RomFS folder. Without --match it only lists; with it the matching textures become PNGs under
|
||||||
|
--out, and --sheet also writes contact sheets of them (numbered; sheet.txt says which number is which). Reads files the
|
||||||
|
way runtime/menu_assets.c does, and decodes ASTC with the runtime's own decoder (runtime/tex_astc.c, built into --out).
|
||||||
|
Everything written is game data and stays under build/. Needs Python 3.14 (compression.zstd) and numpy.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import ctypes
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import zlib
|
||||||
|
from compression import zstd
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
ARCHIVES = 'UI/Layout2Archive'
|
||||||
|
# the second byte of a BNTX format: name, block size, bytes per block
|
||||||
|
KINDS = {0x0b: ('RGBA8', 1, 4), 0x1a: ('BC1', 4, 8), 0x1b: ('BC2', 4, 16), 0x1c: ('BC3', 4, 16), 0x1d: ('BC4', 4, 8),
|
||||||
|
0x1e: ('BC5', 4, 16), 0x20: ('BC7', 4, 16), 0x2d: ('ASTC4x4', 4, 16)}
|
||||||
|
|
||||||
|
|
||||||
|
def u16(b, at): return struct.unpack_from('<H', b, at)[0]
|
||||||
|
def u32(b, at): return struct.unpack_from('<I', b, at)[0]
|
||||||
|
def u64(b, at): return struct.unpack_from('<Q', b, at)[0]
|
||||||
|
|
||||||
|
|
||||||
|
def sarc_members(p):
|
||||||
|
"""The members of a SARC archive as a name -> bytes dictionary."""
|
||||||
|
hl, data = u16(p, 4), u32(p, 0xc)
|
||||||
|
count, ents = u16(p, hl + 6), hl + 0xc
|
||||||
|
names = ents + 16 * count + 8
|
||||||
|
out = {}
|
||||||
|
for i in range(count):
|
||||||
|
e = ents + 16 * i
|
||||||
|
at = names + (u32(p, e + 4) & 0xffff) * 4
|
||||||
|
name = p[at:p.index(b'\0', at)].decode()
|
||||||
|
out[name] = p[data + u32(p, e + 8):data + u32(p, e + 12)]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class Romfs:
|
||||||
|
def __init__(self, root):
|
||||||
|
self.root = Path(root)
|
||||||
|
self.dicts = None
|
||||||
|
|
||||||
|
def load_dicts(self):
|
||||||
|
self.dicts = {}
|
||||||
|
raw = zstd.decompress((self.root / 'Pack/ZsDic.pack.zs').read_bytes())
|
||||||
|
for name, data in sarc_members(raw).items():
|
||||||
|
d = zstd.ZstdDict(data)
|
||||||
|
self.dicts[d.dict_id] = d
|
||||||
|
|
||||||
|
def read(self, rel):
|
||||||
|
b = (self.root / rel).read_bytes()
|
||||||
|
if not rel.endswith('.zs'):
|
||||||
|
return b
|
||||||
|
id_ = zstd.get_frame_info(b).dictionary_id
|
||||||
|
if not id_:
|
||||||
|
return zstd.decompress(b)
|
||||||
|
if self.dicts is None:
|
||||||
|
self.load_dicts()
|
||||||
|
return zstd.decompress(b, zstd_dict=self.dicts[id_])
|
||||||
|
|
||||||
|
|
||||||
|
def bntx_textures(b):
|
||||||
|
"""Each texture of a BNTX file: name, format, size, block height, data offset and size."""
|
||||||
|
out = []
|
||||||
|
count, arr = u32(b, 0x24), u64(b, 0x28)
|
||||||
|
for i in range(count):
|
||||||
|
p = u64(b, arr + 8 * i)
|
||||||
|
if b[p:p + 4] != b'BRTI':
|
||||||
|
continue
|
||||||
|
no = u64(b, p + 0x60)
|
||||||
|
name = b[no + 2:no + 2 + u16(b, no)].decode()
|
||||||
|
out.append({'name': name, 'fmt': u32(b, p + 0x1c), 'w': u32(b, p + 0x24), 'h': u32(b, p + 0x28),
|
||||||
|
'th': u32(b, p + 0x34), 'size': u32(b, p + 0x50), 'data': u64(b, u64(b, p + 0x70))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def deswizzle(t, b, row, rows):
|
||||||
|
"""The first level as tightly packed rows, in the Switch 2 GOB layout (runtime/tex_deswizzle.c tex_bl_copy)."""
|
||||||
|
th = t['th']
|
||||||
|
gobs, unit, block = (row + 63) // 64, 8 << th, 512 << th
|
||||||
|
need = gobs * ((rows + unit - 1) // unit) * block
|
||||||
|
bl = np.zeros(max(need, t['size']) // 16 + 1, dtype='V16')
|
||||||
|
src = bytearray(bl.tobytes())
|
||||||
|
src[:t['size']] = b[t['data']:t['data'] + t['size']]
|
||||||
|
bl = np.frombuffer(bytes(src), dtype='V16')
|
||||||
|
cols = (row + 15) // 16
|
||||||
|
y = np.arange(rows)[:, None]
|
||||||
|
x = (np.arange(cols) * 16)[None, :]
|
||||||
|
at = (y // unit) * gobs * block + (x // 64) * block + ((y % unit) // 8) * 512 + \
|
||||||
|
(x % 64 // 32) * 256 + (y % 8 // 4) * 128 + (x % 32 // 16) * 64 + (y % 4) * 16
|
||||||
|
flat = np.frombuffer(bl[at // 16].tobytes(), dtype=np.uint8).reshape(rows, cols * 16)
|
||||||
|
return flat[:, :row]
|
||||||
|
|
||||||
|
|
||||||
|
def bc4(lin, wb, hb, w, h):
|
||||||
|
"""White with the mask as alpha (runtime/menu_assets.c bc4_decode)."""
|
||||||
|
blocks = lin.reshape(hb, wb, 8).astype(np.uint32)
|
||||||
|
a, b = blocks[..., 0], blocks[..., 1]
|
||||||
|
pal = np.zeros((hb, wb, 8), dtype=np.uint32)
|
||||||
|
pal[..., 0], pal[..., 1] = a, b
|
||||||
|
big = a > b
|
||||||
|
for i in range(6):
|
||||||
|
pal[..., 2 + i] = np.where(big, ((6 - i) * a + (i + 1) * b) // 7, 0)
|
||||||
|
for i in range(4):
|
||||||
|
pal[..., 2 + i] = np.where(big, pal[..., 2 + i], ((4 - i) * a + (i + 1) * b) // 5)
|
||||||
|
pal[..., 6] = np.where(big, pal[..., 6], 0)
|
||||||
|
pal[..., 7] = np.where(big, pal[..., 7], 255)
|
||||||
|
bits = np.zeros((hb, wb), dtype=np.uint64)
|
||||||
|
for i in range(6):
|
||||||
|
bits |= blocks[..., 2 + i].astype(np.uint64) << np.uint64(8 * i)
|
||||||
|
alpha = np.zeros((hb * 4, wb * 4), dtype=np.uint8)
|
||||||
|
for i in range(16):
|
||||||
|
sel = ((bits >> np.uint64(3 * i)) & np.uint64(7)).astype(np.intp)
|
||||||
|
alpha[i // 4::4, i % 4::4] = np.take_along_axis(pal, sel[..., None], 2)[..., 0]
|
||||||
|
rgba = np.full((h, w, 4), 255, dtype=np.uint8)
|
||||||
|
rgba[..., 3] = alpha[:h, :w]
|
||||||
|
return rgba
|
||||||
|
|
||||||
|
|
||||||
|
def astc_library(out):
|
||||||
|
"""The runtime's ASTC decoder as a library, built once into out."""
|
||||||
|
dll = out / 'astc.dll'
|
||||||
|
src = ROOT / 'runtime' / 'tex_astc.c'
|
||||||
|
if not dll.is_file() or dll.stat().st_mtime < src.stat().st_mtime:
|
||||||
|
cc = shutil.which('clang') or r'C:\msys64\ucrt64\bin\clang.exe'
|
||||||
|
vma = Path(cc).resolve().parents[1] / 'include' / 'vma' # tex.h reaches the Vulkan allocator's header
|
||||||
|
if subprocess.run([cc, '-shared', '-O2', '-static', '-w', '-I', str(ROOT / 'runtime'), '-I', str(vma), str(src), '-o',
|
||||||
|
str(dll)]).returncode:
|
||||||
|
sys.exit('tex_astc.c did not compile')
|
||||||
|
lib = ctypes.CDLL(str(dll))
|
||||||
|
lib.astc_decode_ldr.restype = None
|
||||||
|
lib.astc_decode_ldr.argtypes = [ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,
|
||||||
|
ctypes.c_bool, ctypes.c_void_p]
|
||||||
|
return lib
|
||||||
|
|
||||||
|
|
||||||
|
def decode(t, b, lib):
|
||||||
|
kind = t['fmt'] >> 8
|
||||||
|
if kind not in (0x0b, 0x1d, 0x2d):
|
||||||
|
return None
|
||||||
|
_, bs, bpb = KINDS[kind]
|
||||||
|
w, h = t['w'], t['h']
|
||||||
|
wb, hb = (w + bs - 1) // bs, (h + bs - 1) // bs
|
||||||
|
lin = deswizzle(t, b, wb * bpb, hb)
|
||||||
|
if kind == 0x1d:
|
||||||
|
return bc4(lin, wb, hb, w, h)
|
||||||
|
if kind == 0x0b:
|
||||||
|
return lin.reshape(h, w, 4).copy()
|
||||||
|
rgba = np.zeros((h, w, 4), dtype=np.uint8)
|
||||||
|
lib.astc_decode_ldr(lin.tobytes(), w, h, 4, 4, (t['fmt'] & 0xff) == 6, rgba.ctypes.data)
|
||||||
|
return rgba
|
||||||
|
|
||||||
|
|
||||||
|
def png(path, a):
|
||||||
|
h, w = a.shape[:2]
|
||||||
|
rows = b''.join(b'\0' + a[y].tobytes() for y in range(h))
|
||||||
|
|
||||||
|
def chunk(kind, data):
|
||||||
|
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)
|
||||||
|
Path(path).write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0)) +
|
||||||
|
chunk(b'IDAT', zlib.compress(rows, 6)) + chunk(b'IEND', b''))
|
||||||
|
|
||||||
|
|
||||||
|
DIGITS = ['111101101101111', '010110010010111', '111001111100111', '111001111001111', '101101111001001',
|
||||||
|
'111100111001111', '111100111101111', '111001010010010', '111101111101111', '111101111001111']
|
||||||
|
|
||||||
|
|
||||||
|
def label(sheet, x, y, n):
|
||||||
|
for c in str(n):
|
||||||
|
for j in range(5):
|
||||||
|
for i in range(3):
|
||||||
|
if DIGITS[int(c)][j * 3 + i] == '1':
|
||||||
|
sheet[y + j * 2:y + j * 2 + 2, x + i * 2:x + i * 2 + 2] = (255, 255, 0, 255)
|
||||||
|
x += 8
|
||||||
|
|
||||||
|
|
||||||
|
def sheets(out, items, cell=220, cols=7, per=35):
|
||||||
|
"""Contact sheets over a mid brown, so white masks and dark art both show."""
|
||||||
|
lines = []
|
||||||
|
for s in range(0, len(items), per):
|
||||||
|
page = items[s:s + per]
|
||||||
|
rows = (len(page) + cols - 1) // cols
|
||||||
|
sheet = np.full((rows * cell, cols * cell, 4), (84, 70, 58, 255), dtype=np.uint8)
|
||||||
|
for k, (name, a) in enumerate(page):
|
||||||
|
n = s + k
|
||||||
|
lines.append(f'{n} {name} {a.shape[1]}x{a.shape[0]}')
|
||||||
|
step = max(1, max(a.shape[0], a.shape[1]) // (cell - 8) + (max(a.shape[:2]) % (cell - 8) > 0))
|
||||||
|
t = a[::step, ::step]
|
||||||
|
cy, cx = (k // cols) * cell + 4, (k % cols) * cell + 4
|
||||||
|
al = t[..., 3:4].astype(np.float32) / 255
|
||||||
|
bg = sheet[cy:cy + t.shape[0], cx:cx + t.shape[1], :3].astype(np.float32)
|
||||||
|
sheet[cy:cy + t.shape[0], cx:cx + t.shape[1], :3] = (t[..., :3] * al + bg * (1 - al)).astype(np.uint8)
|
||||||
|
label(sheet, cx, cy, n)
|
||||||
|
png(out / f'sheet{s // per:02}.png', sheet)
|
||||||
|
(out / 'sheet.txt').write_text('\n'.join(lines) + '\n')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
ap.add_argument('romfs', type=Path)
|
||||||
|
ap.add_argument('--out', type=Path, default=ROOT / 'build' / 'ui-textures')
|
||||||
|
ap.add_argument('--archive', default='', help='only archives whose name contains this')
|
||||||
|
ap.add_argument('--match', help='a regular expression: the textures to decode')
|
||||||
|
ap.add_argument('--sheet', action='store_true', help='write contact sheets of what was decoded')
|
||||||
|
a = ap.parse_args()
|
||||||
|
fs = Romfs(a.romfs)
|
||||||
|
a.out.mkdir(parents=True, exist_ok=True)
|
||||||
|
lib = astc_library(a.out) if a.match else None
|
||||||
|
decoded = []
|
||||||
|
for f in sorted((a.romfs / ARCHIVES).glob('*.bntx.zs')):
|
||||||
|
if a.archive not in f.name:
|
||||||
|
continue
|
||||||
|
b = fs.read(f'{ARCHIVES}/{f.name}')
|
||||||
|
ts = bntx_textures(b)
|
||||||
|
print(f'# {f.name}: {len(ts)} textures')
|
||||||
|
for t in sorted(ts, key=lambda t: t['name']):
|
||||||
|
kind = KINDS.get(t['fmt'] >> 8, (f"{t['fmt']:#x}",))[0]
|
||||||
|
if not a.match:
|
||||||
|
print(f"{t['name']} {kind} {t['w']}x{t['h']}")
|
||||||
|
elif re.search(a.match, t['name']):
|
||||||
|
rgba = decode(t, b, lib)
|
||||||
|
if rgba is None:
|
||||||
|
print(f"{t['name']}: format {kind} is not read by the runtime", file=sys.stderr)
|
||||||
|
continue
|
||||||
|
png(a.out / f"{t['name']}.png", rgba)
|
||||||
|
decoded.append((t['name'], rgba))
|
||||||
|
if a.match:
|
||||||
|
print(f'{len(decoded)} textures written to {a.out}')
|
||||||
|
if a.sheet and decoded:
|
||||||
|
sheets(a.out, decoded)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user