From f8d584b3dbc9637c05ff3775d34d687528fd880a Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Mon, 26 Oct 2026 10:13:33 +0300 Subject: [PATCH] Add the tabbed settings menu: option rows over the cfg table for the Screen, Game, Sound, Controls and Menu tabs, Continue and Quit game in the bottom row, and a note when totk.ini cannot be written Rows read and write their key through cfg, mark the default, say "after restart" for start-only settings and grey out what an environment variable fixes; totk.ini is written 0.4 s after the last change and when the menu closes. The graphics card list comes from the Vulkan devices, the window sizes from the monitor, and the language names of Japanese, Korean and Chinese are drawn with glyphs merged in from a system font (plat_font_path). The font atlas and style follow the window height. TOTK_MENU_TEST saves one shot per tab and ignores real input meanwhile; TOTK_MENU_TEST_SET sets settings at given frames (SAVE=1 writes totk.ini). A background test window going fullscreen no longer comes to the front or takes focus, and the log names the present mode the swapchain gets. Co-Authored-By: Claude Opus 5.5 --- THIRD_PARTY_NOTICES.md | 1 + runtime/cfg.c | 2 +- runtime/gfx_window.c | 33 ++- runtime/platform/platform.h | 3 + runtime/platform/win32.c | 23 ++ runtime/ui/menu.cpp | 436 +++++++++++++++++++++++++++++++----- runtime/ui/menu.h | 9 +- runtime/ui/menu_win.cpp | 4 +- runtime/ui/option_rows.cpp | 269 ++++++++++++++++++++++ runtime/ui/option_rows.h | 39 ++++ 10 files changed, 752 insertions(+), 67 deletions(-) create mode 100644 runtime/ui/option_rows.cpp create mode 100644 runtime/ui/option_rows.h diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 769dceb2..e8fc765f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -23,6 +23,7 @@ Code copied or adapted from another project is listed here with its source, the | SDL 3.4.18, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.18-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) | | libopus (MSYS2 `mingw-w64-ucrt-x86_64-opus`), dynamic link, `libopus-0.dll` copied next to `totk.exe` | https://opus-codec.org, Copyright (c) 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon | BSD-3-Clause | `runtime/ov_media.c` (nn::codec hardware Opus decoder) | | Dear ImGui 1.91.9 (core and Vulkan back end, unmodified), as vendored by LAS Recomp | https://github.com/ocornut/imgui, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/`), Copyright (c) 2014-2025 Omar Cornut | MIT | `runtime/third_party/imgui/` (compiled into `totk.exe` for the in-game menu, `runtime/ui/`) | +| SavageWindRecomp settings menu: two-pane option rows (row look, left / right stepping, hold speed-up, description pane), the menu style and tab bar | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/ui/option_rows.mm`, `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/ui/option_rows.cpp`, `runtime/ui/option_rows.h`, `runtime/ui/menu.cpp` | | Roboto Medium font (Dear ImGui's `misc/fonts/Roboto-Medium.ttf`, unmodified) | https://fonts.google.com/specimen/Roboto, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/misc/fonts/`), Copyright 2011 Google Inc. | Apache-2.0 | `runtime/ui/fonts/Roboto-Medium.ttf` (licence text in `runtime/ui/fonts/LICENSE-Roboto.txt`), embedded by `runtime/ui/menu.cpp` | | Vulkan Memory Allocator 3.4.0 (MSYS2 `mingw-w64-ucrt-x86_64-vulkan-memory-allocator`), header-only, compiled into `totk.exe` | https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator, Copyright (c) 2017-2026 Advanced Micro Devices, Inc. | MIT | `runtime/vk_vma.cpp` (the allocator behind `runtime/vk_memory.c`) | | MacNativeGames host movie decoder (`movie::Decoder` for VP9 over libvpx: entry list, buffer and event semantics, NV12 output format, PTS pacing) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/movie_host.c`, `movie_host.h`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/ov_movie.c`, `runtime/movie.h` | diff --git a/runtime/cfg.c b/runtime/cfg.c index 83ae2cc4..bc1e8d8e 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -38,7 +38,7 @@ static const char *const known[] = { "FLIGHT_THUMBS", "FPS60", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST", - "MENU_TEST_DIR", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", + "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "OPERATION_MODE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC", "REPLAY_ASYNC", diff --git a/runtime/gfx_window.c b/runtime/gfx_window.c index da538a99..c95fba94 100644 --- a/runtime/gfx_window.c +++ b/runtime/gfx_window.c @@ -45,6 +45,7 @@ static volatile LONG g_focused = 1; static volatile LONG g_focus_msgs; static CRITICAL_SECTION g_start_lock; // gfx_window_start / vsync start static int g_started, g_wnd_failed; +static int g_background; // TOTK_BACKGROUND_WINDOW: the window stays behind the user's windows // ---- swapchain and present state (g_pl) static CRITICAL_SECTION g_pl; @@ -199,7 +200,8 @@ static void cfg_window_size(int *w, int *h) { } // F11: borderless window over the whole monitor, and back to the saved window. The swapchain follows through WM_SIZE. -// Not Alt+Enter: Enter is the Plus button (input_win.c). +// Not Alt+Enter: Enter is the Plus button (input_win.c). A background window (test runs) keeps its place behind the +// user's windows and takes no focus. static void toggle_fullscreen(HWND h) { LONG style = GetWindowLongW(h, GWL_STYLE); if (style & WS_OVERLAPPEDWINDOW) { @@ -208,11 +210,15 @@ static void toggle_fullscreen(HWND h) { return; SetWindowLongW(h, GWL_STYLE, (style & ~WS_OVERLAPPEDWINDOW) | WS_POPUP); SetWindowPos(h, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left, - mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + mi.rcMonitor.bottom - mi.rcMonitor.top, + SWP_NOOWNERZORDER | SWP_FRAMECHANGED | (g_background ? SWP_NOZORDER | SWP_NOACTIVATE : 0)); } else { SetWindowLongW(h, GWL_STYLE, (style & ~WS_POPUP) | WND_STYLE); + if (g_background) g_saved_place.showCmd = SW_SHOWNOACTIVATE; SetWindowPlacement(h, &g_saved_place); - SetWindowPos(h, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + SetWindowPos(h, NULL, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | + (g_background ? SWP_NOACTIVATE : 0)); } } @@ -282,6 +288,14 @@ void gfx_window_request_close(void) { if (g_hwnd) PostMessageW(g_hwnd, WM_CLOSE, 0, 0); } +int gfx_window_monitor_size(int *w, int *h) { + MONITORINFO mi = {sizeof mi}; + if (!g_hwnd || !GetMonitorInfoW(MonitorFromWindow(g_hwnd, MONITOR_DEFAULTTOPRIMARY), &mi)) return 0; + *w = mi.rcMonitor.right - mi.rcMonitor.left; + *h = mi.rcMonitor.bottom - mi.rcMonitor.top; + return 1; +} + static LRESULT CALLBACK wnd_proc(HWND h, UINT m, WPARAM w, LPARAM l) { LRESULT input_res; if (input_window_msg(h, m, w, l, &input_res)) return input_res; @@ -335,7 +349,7 @@ static DWORD WINAPI window_main(void *arg) { AdjustWindowRect(&r, WND_STYLE, FALSE); // TOTK_BACKGROUND_WINDOW=1 (test runs): the window opens behind the user's windows without taking focus; it keeps its // taskbar button and can be brought up by hand. It never goes fullscreen at start. - int background = cfg_get("TOTK_BACKGROUND_WINDOW") && atoi(cfg_get("TOTK_BACKGROUND_WINDOW")); + int background = g_background = cfg_get("TOTK_BACKGROUND_WINDOW") && atoi(cfg_get("TOTK_BACKGROUND_WINDOW")); g_hwnd = CreateWindowExW(0, wc.lpszClassName, L"TotK Recomp", WND_STYLE, CW_USEDEFAULT, CW_USEDEFAULT, r.right - r.left, r.bottom - r.top, NULL, NULL, inst, NULL); if (!g_hwnd) { @@ -369,8 +383,15 @@ static VkPresentModeKHR pick_present_mode(VkPhysicalDevice pd) { VkPresentModeKHR m[16]; if (n > 16) n = 16; vkGetPhysicalDeviceSurfacePresentModesKHR(pd, g_surface, &n, m); - for (uint32_t i = 0; i < n; i++) if (m[i] == want) return want; - return VK_PRESENT_MODE_FIFO_KHR; + VkPresentModeKHR got = VK_PRESENT_MODE_FIFO_KHR; + for (uint32_t i = 0; i < n; i++) if (m[i] == want) got = want; + static int logged = -1; // the mode last logged: a change from the menu shows in the log + if ((int)got != logged) { + logged = (int)got; + rt_log("gfx: present mode %s (TOTK_VK_PRESENT=%s)", + got == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : got == VK_PRESENT_MODE_IMMEDIATE_KHR ? "immediate" : "fifo", e); + } + return got; } // Queues the present of a blit vk_present_blit left waiting (g_pl held). A swapchain rebuild and the next blit flush it diff --git a/runtime/platform/platform.h b/runtime/platform/platform.h index 27fee2cb..35205e57 100644 --- a/runtime/platform/platform.h +++ b/runtime/platform/platform.h @@ -69,6 +69,9 @@ size_t plat_getenv(const char *name, char *out, size_t cap); // The user's UI language as a BCP-47 tag ("ru-RU", "en-US"); "" when the system gives none. Valid for the process. const char *plat_ui_language(void); uint32_t plat_thread_id(void); // id of the calling thread, for unique file names +// A system font file with the glyphs of a catalog language ("ja", "ko", "zh-Hans", "zh-Hant"): the menu shows each +// language's name in its own script. Copies the UTF-8 path into out; 0 when the system has none. +int plat_font_path(const char *lang, char *out, size_t cap); // ---- child processes: a program with stdin and stdout piped to us (stderr discarded), no console window. typedef struct PlatChild PlatChild; diff --git a/runtime/platform/win32.c b/runtime/platform/win32.c index 6aac6a61..e46759be 100644 --- a/runtime/platform/win32.c +++ b/runtime/platform/win32.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "platform.h" @@ -307,6 +308,28 @@ const char *plat_ui_language(void) { return tag; } +int plat_font_path(const char *lang, char *out, size_t cap) { + static const struct { const char *lang; const wchar_t *files[3]; } fonts[] = { + {"ja", {L"YuGothM.ttc", L"meiryo.ttc", L"msgothic.ttc"}}, + {"ko", {L"malgun.ttf", L"gulim.ttc", NULL}}, + {"zh-Hans", {L"msyh.ttc", L"simsun.ttc", NULL}}, + {"zh-Hant", {L"msjh.ttc", L"mingliu.ttc", NULL}}, + }; + wchar_t dir[MAX_PATH], w[WPATH]; + UINT n = GetWindowsDirectoryW(dir, MAX_PATH); + if (!n || n >= MAX_PATH) return 0; + for (size_t i = 0; i < sizeof fonts / sizeof *fonts; i++) { + if (strcmp(fonts[i].lang, lang)) continue; + for (int k = 0; k < 3 && fonts[i].files[k]; k++) { + swprintf(w, WPATH, L"%ls\\Fonts\\%ls", dir, fonts[i].files[k]); + DWORD a = GetFileAttributesW(w); + if (a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY)) + return WideCharToMultiByte(CP_UTF8, 0, w, -1, out, (int)cap, NULL, NULL) != 0; + } + } + return 0; +} + // ---- child processes struct PlatChild { diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index a18a5af1..e57034f3 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -5,13 +5,21 @@ // The Vulkan set-up follows LAS Recomp's runtime/nvn/vulkan/imgui_glue.cpp (https://github.com/peiikai/LASRecomp @ // da35b83a9611d046a9a681aae668d7085954d37f, MIT, Copyright (c) 2026 Peiikai): dynamic rendering into the swapchain // image, an internal descriptor pool, vertex buffers rotated over more frames than are in flight. +// +// The look (colours, rounding, the tab bar with L / R and Q / E, the window over a dimmed game) follows +// SavageWindRecomp's runtime/ui/menu.mm (https://github.com/Revivedx/SavageWindRecomp @ +// 575ad88e02f9a89a9a885d90039d48af33c982f4, MIT, Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, +// Copyright (c) 2026 Peiikai); the pages are rows of option_rows.cpp. #include +#include #include #include #include #include "imgui.h" +#include "imgui_internal.h" // SetFocusID, NavCursorVisible #include "backends/imgui_impl_vulkan.h" +#include "ui/option_rows.h" extern "C" { #include "cfg.h" @@ -58,19 +66,6 @@ static int change_open(int want) { static void set_open(int open) { change_open(open); } -// TOTK_MENU_TEST=[:]: the presented frame the menu opens at for the shot hook; 0 when unset -static uint64_t test_frame(void) { - static std::atomic f{-1}; - long long v = f.load(std::memory_order_relaxed); - if (v < 0) { - const char *e = cfg_get("TOTK_MENU_TEST"); - v = e ? atoll(e) : 0; - if (v < 0) v = 0; - f.store(v); - } - return (uint64_t)v; -} - static int g_failed_flag(); extern "C" int menu_is_open(void) { return g_open.load(std::memory_order_relaxed); } extern "C" void menu_toggle(void) { @@ -161,28 +156,47 @@ static std::atomic g_failed; // set-up failed for good (the menu stays clos static int g_failed_flag() { return g_failed.load(std::memory_order_relaxed); } static int g_vk_ok; // back end initialised for g_vk_fmt static VkFormat g_vk_fmt; +static float g_font_scale; // the scale of the uploaded font atlas; 0 when none is uploaded +static float g_style_scale; // the scale the style was last sized for +static ImGuiStyle g_base_style; // the menu's style at 1080 lines 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 void make_context(uint32_t h) { +// Sizes are tuned for 1080 lines and follow the window's height; under 720 lines they stay at the 720 size. +static float menu_scale(uint32_t h) { return (h >= 720 ? h : 720) / 1080.0f; } + +// SavageWindRecomp's colours: dark green panels, gold accents. +static void style_init(ImGuiStyle &s) { + ImGui::StyleColorsDark(&s); + s.WindowRounding = 14; s.FrameRounding = 8; s.GrabRounding = 8; s.TabRounding = 8; s.ChildRounding = 10; + s.WindowPadding = ImVec2(28, 22); s.FramePadding = ImVec2(14, 8); s.ItemSpacing = ImVec2(14, 12); + s.WindowBorderSize = 0; s.ScrollbarSize = 18; + ImVec4 *c = s.Colors; + ImVec4 gold(0.93f, 0.76f, 0.33f, 1), green(0.15f, 0.36f, 0.25f, 1); + c[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.09f, 0.08f, 0.94f); + c[ImGuiCol_ChildBg] = ImVec4(0, 0, 0, 0); + c[ImGuiCol_Text] = ImVec4(0.96f, 0.94f, 0.88f, 1); + c[ImGuiCol_TextDisabled] = ImVec4(0.62f, 0.64f, 0.58f, 1); + c[ImGuiCol_Button] = ImVec4(0.14f, 0.22f, 0.18f, 1); + c[ImGuiCol_ButtonHovered] = green; + c[ImGuiCol_ButtonActive] = ImVec4(0.21f, 0.50f, 0.34f, 1); + c[ImGuiCol_Tab] = ImVec4(0.12f, 0.18f, 0.15f, 1); + c[ImGuiCol_TabHovered] = green; + c[ImGuiCol_TabSelected] = ImVec4(0.21f, 0.44f, 0.31f, 1); + c[ImGuiCol_TabSelectedOverline] = gold; + c[ImGuiCol_NavCursor] = gold; + c[ImGuiCol_Separator] = ImVec4(0.30f, 0.36f, 0.30f, 1); +} + +static void make_context(void) { ImGui::CreateContext(); ImGuiIO &io = ImGui::GetIO(); io.IniFilename = nullptr; io.LogFilename = nullptr; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_NavEnableGamepad; io.BackendPlatformName = "totk_menu"; - float scale = h >= 720 ? h / 1080.0f : 720 / 1080.0f; - ImFontConfig fc; - fc.FontDataOwnedByAtlas = false; - io.Fonts->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 26.0f * scale, &fc, - io.Fonts->GetGlyphRangesCyrillic()); - ImGui::StyleColorsDark(); - ImGuiStyle &st = ImGui::GetStyle(); - st.WindowRounding = 6; - st.FrameRounding = 4; - st.WindowPadding = ImVec2(18, 14); - st.ItemSpacing = ImVec2(12, 10); - st.ScaleAllSizes(scale); + style_init(g_base_style); + ImGui::GetStyle() = g_base_style; g_ctx_ok = 1; } @@ -190,6 +204,7 @@ static void vk_down(void) { if (!g_vk_ok) return; ImGui_ImplVulkan_Shutdown(); g_vk_ok = 0; + g_font_scale = 0; } static int vk_up(const MenuTarget *t) { @@ -218,10 +233,49 @@ static int vk_up(const MenuTarget *t) { ii.PipelineRenderingCreateInfo.pColorAttachmentFormats = &g_vk_fmt; if (!ImGui_ImplVulkan_Init(&ii)) return 0; g_vk_ok = 1; - vk_queue_lock(); // the font upload submits on the queue and waits for it + return 1; +} + +// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean +// and Chinese language names merged in from a system font when there is one (each language is named in its own script). +// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture). +static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0}; +static const struct { const char *lang; UiTextId name; } kCjk[] = { + {"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS}, + {"zh-Hant", UI_MENU_LANGNAME_ZH_HANT}, +}; + +static int fonts_up(float scale) { + enum { N = sizeof kCjk / sizeof *kCjk }; + ImFontAtlas *fa = ImGui::GetIO().Fonts; + fa->Clear(); + ImFontConfig fc; + fc.FontDataOwnedByAtlas = false; + fa->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 26.0f * scale, &fc, kRanges); + uint8_t *data[N] = {}; + ImVector ranges[N]; + int merged = 0; + for (int i = 0; i < N; i++) { + char path[512]; + uint64_t size = 0; + if (!plat_font_path(kCjk[i].lang, path, sizeof path) || !(data[i] = plat_file_read(path, &size))) continue; + merged++; + ImFontGlyphRangesBuilder b; + b.AddText(ui_text_in("en", kCjk[i].name)); + b.BuildRanges(&ranges[i]); + ImFontConfig mc; + mc.MergeMode = true; + mc.FontDataOwnedByAtlas = false; + fa->AddFontFromMemoryTTF(data[i], (int)size, 26.0f * scale, &mc, ranges[i].Data); + } + vk_queue_lock(); // the upload submits on the queue and waits for it int ok = ImGui_ImplVulkan_CreateFontsTexture(); vk_queue_unlock(); - if (!ok) vk_down(); + fa->ClearInputData(); // the glyphs are in the texture: the font files and the pixels are not needed again + fa->ClearTexData(); + for (uint8_t *d : data) free(d); + rt_log("menu: font atlas at %.1f px, language names from %d of %d system fonts", 26.0f * scale, merged, (int)N); + g_font_scale = ok ? scale : 0; return ok; } @@ -229,33 +283,287 @@ extern "C" void menu_vk_release(void) { if (g_ctx_ok) vk_down(); } -// ---- the page: a dimmed frame and a centred window with "Continue" and "Quit game" (Task 4 moves them into the bottom row -// of the tabbed menu). Esc on the keyboard and B on the gamepad close it. -static void layout_page(uint32_t w, uint32_t h) { +// ---- test hooks +// TOTK_MENU_TEST=[:]: at that presented frame the menu opens on its first tab; each tab stays +// frames (default 30) and its last frame's swapchain image goes to TOTK_MENU_TEST_DIR (default: the +// working directory) as menu-test--.png; after the last tab the menu closes. +// TOTK_MENU_TEST_SET=:=[,=...][;:...]: cfg_set of each key (TOTK_ prefix +// optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by +// the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note). +enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_COUNT }; +enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 }; +struct TestSet { uint64_t frame; char key[64], value[64]; }; +static struct { + int parsed; + uint64_t at; // TOTK_MENU_TEST frame; 0 none + uint64_t per_page; + uint64_t opened; // the frame the hook opened the menu; 0 not yet + int page; // the tab being shot; -1 none + TestSet sets[TEST_SETS]; + int n_sets, next_set; // TOTK_MENU_TEST_SET, in frame order +} g_test = {0, 0, 0, 0, -1, {}, 0, 0}; + +static void test_parse(void) { + g_test.parsed = 1; + if (const char *e = cfg_get("TOTK_MENU_TEST")) { + long long at = atoll(e), per = 0; + if (const char *c = strchr(e, ':')) per = atoll(c + 1); + g_test.at = at > 0 ? (uint64_t)at : 0; + g_test.per_page = per > 0 ? (uint64_t)per : TEST_PAGE_FRAMES; + } + const char *s = cfg_get("TOTK_MENU_TEST_SET"); + while (s && *s) { // groups ":=,..." separated by ';' + char *end; + unsigned long long f = strtoull(s, &end, 10); + if (*end != ':') break; + s = end + 1; + while (*s && *s != ';' && g_test.n_sets < TEST_SETS) { + size_t n = strcspn(s, ",;"); + const char *eq = (const char *)memchr(s, '=', n); + if (eq) { + TestSet &t = g_test.sets[g_test.n_sets++]; + t.frame = f; + int kn = (int)(eq - s), vn = (int)(s + n - eq - 1); + snprintf(t.key, sizeof t.key, "%s%.*s", strncmp(s, "TOTK_", 5) ? "TOTK_" : "", kn, s); + snprintf(t.value, sizeof t.value, "%.*s", vn, eq + 1); + } + s += n; + if (*s == ',') s++; + } + while (*s && *s != ';') s++; + if (*s == ';') s++; + } + if (g_test.at || g_test.n_sets) + rt_log("menu: test hook: open at frame %llu, %llu frames per page, %d settings changes", + (unsigned long long)g_test.at, (unsigned long long)g_test.per_page, g_test.n_sets); +} + +static void test_apply_sets(uint64_t frame) { + for (; g_test.next_set < g_test.n_sets && g_test.sets[g_test.next_set].frame <= frame; g_test.next_set++) { + const TestSet &t = g_test.sets[g_test.next_set]; + rt_log("menu: test hook: frame %llu: %s=%s", (unsigned long long)frame, t.key, t.value); + if (!strcmp(t.key, "TOTK_SAVE")) rt_log("menu: test hook: cfg_save %s", cfg_save() ? "wrote" : "failed"); + else cfg_set(t.key, t.value); + } +} + +// ---- the lists the Screen and Game tabs build +enum { MAX_GPUS = 8 }; +static char g_gpu_names[MAX_GPUS][VK_MAX_PHYSICAL_DEVICE_NAME_SIZE]; +static int g_gpu_n = -1; // -1: not listed yet + +// The Vulkan devices in vkEnumeratePhysicalDevices order, which TOTK_GPU_INDEX counts in (vk_device.c pick_device). +static void list_gpus(VkInstance inst) { + if (g_gpu_n >= 0) return; + VkPhysicalDevice pd[MAX_GPUS]; + uint32_t n = MAX_GPUS; + if (vkEnumeratePhysicalDevices(inst, &n, pd) < 0) n = 0; // VK_INCOMPLETE keeps the first MAX_GPUS + for (uint32_t i = 0; i < n; i++) { + VkPhysicalDeviceProperties p; + vkGetPhysicalDeviceProperties(pd[i], &p); + snprintf(g_gpu_names[i], sizeof g_gpu_names[i], "%s", p.deviceName); + } + g_gpu_n = (int)n; +} + +// Window sizes: the common 16:9 sizes that fit the monitor, the 1920x1080 default and the current size. +static const int kSizes[][2] = {{1280, 720}, {1366, 768}, {1600, 900}, {1920, 1080}, {2560, 1440}, {3200, 1800}, + {3840, 2160}}; +enum { MAX_SIZES = sizeof kSizes / sizeof *kSizes + 1 }; + +static void row_window_size(void) { + int sz[MAX_SIZES][2], n = 0, mw = 0, mh = 0, cw = 0, ch = 0; + int have = gfx_window_monitor_size(&mw, &mh); + int cur_ok = sscanf(cfg_value("TOTK_WINDOW_SIZE"), "%dx%d", &cw, &ch) == 2; + bool listed = false; + for (size_t i = 0; i < sizeof kSizes / sizeof *kSizes; i++) { + int w = kSizes[i][0], h = kSizes[i][1]; + bool cur = cur_ok && w == cw && h == ch; + if (have && (w > mw || h > mh) && !cur && !(w == 1920 && h == 1080)) continue; + listed |= cur; + sz[n][0] = w, sz[n][1] = h, n++; + } + if (cur_ok && !listed) { // the current size where its area puts it + int at = n; + while (at > 0 && (long)sz[at - 1][0] * sz[at - 1][1] > (long)cw * ch) at--; + memmove(sz[at + 1], sz[at], sizeof sz[0] * (n - at)); + sz[at][0] = cw, sz[at][1] = ch, n++; + } + char vals[MAX_SIZES][24], shown[MAX_SIZES][32]; + const char *pv[MAX_SIZES], *pn[MAX_SIZES]; + for (int i = 0; i < n; i++) { + snprintf(vals[i], sizeof vals[i], "%dx%d", sz[i][0], sz[i][1]); + snprintf(shown[i], sizeof shown[i], "%d × %d", sz[i][0], sz[i][1]); // U+00D7, the multiplication sign + pv[i] = vals[i]; + pn[i] = shown[i]; + } + opt_choice_list("TOTK_WINDOW_SIZE", UI_MENU_WINDOW_SIZE, pv, pn, n, UI_MENU_WINDOW_SIZE_DESC); +} + +static void row_gpu(void) { + const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1]; + char idx[MAX_GPUS][4]; + vals[0] = ""; + names[0] = menu_text(UI_MENU_GPU_AUTO); + for (int i = 0; i < g_gpu_n; i++) { + snprintf(idx[i], sizeof idx[i], "%d", i); + vals[i + 1] = idx[i]; + names[i + 1] = g_gpu_names[i]; + } + opt_choice_list("TOTK_GPU_INDEX", UI_MENU_GPU, vals, names, g_gpu_n + 1, UI_MENU_GPU_DESC); +} + +// The game language: one entry per catalog language (a Switch code that names it), each language under its own name. +static void row_game_lang(void) { + static const struct { const char *code; UiTextId name; } langs[] = { + {"en-US", UI_MENU_LANGNAME_EN}, {"ja", UI_MENU_LANGNAME_JA}, {"fr", UI_MENU_LANGNAME_FR}, + {"de", UI_MENU_LANGNAME_DE}, {"it", UI_MENU_LANGNAME_IT}, {"es", UI_MENU_LANGNAME_ES}, + {"nl", UI_MENU_LANGNAME_NL}, {"pt", UI_MENU_LANGNAME_PT}, {"ru", UI_MENU_LANGNAME_RU}, + {"zh-CN", UI_MENU_LANGNAME_ZH_HANS}, {"zh-TW", UI_MENU_LANGNAME_ZH_HANT}, {"ko", UI_MENU_LANGNAME_KO}, + }; + enum { N = sizeof langs / sizeof *langs + 1 }; + const char *vals[N], *names[N]; + vals[0] = ""; + names[0] = menu_text(UI_MENU_GAME_LANG_AUTO); + const char *now = cfg_value("TOTK_LANG"); + int cur = *now ? -1 : 0; + for (int i = 1; i < N; i++) { + vals[i] = langs[i - 1].code; + names[i] = menu_text(langs[i - 1].name); + if (*now && !strcmp(ui_text_lang(now), ui_text_lang(vals[i]))) cur = i; // en-GB is English too + } + opt_choice_list("TOTK_LANG", UI_MENU_GAME_LANG, vals, names, N, UI_MENU_GAME_LANG_DESC, cur); +} + +// ---- the tabs +static void tab_screen(float scale) { + opt_begin("##screen", scale); + opt_toggle("TOTK_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC); + row_window_size(); + static const UiTextId present[] = {UI_MENU_PRESENT_MAILBOX, UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_IMMEDIATE}; + opt_choice("TOTK_VK_PRESENT", UI_MENU_PRESENT, present, 3, UI_MENU_PRESENT_DESC); + row_gpu(); + static const UiTextId perf[] = {UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL}; + opt_choice("TOTK_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC); + opt_end(); +} + +static void tab_game(float scale) { + opt_begin("##game", scale); + static const UiTextId fps[] = {UI_MENU_FPS_30, UI_MENU_FPS_60}; // values 0|1 + opt_choice("TOTK_FPS60", UI_MENU_FPS60, fps, 2, UI_MENU_FPS60_DESC); + opt_toggle("TOTK_REALTIME", UI_MENU_REALTIME, UI_MENU_REALTIME_DESC); + opt_toggle("TOTK_CLOTH_REALTIME", UI_MENU_CLOTH_REALTIME, UI_MENU_CLOTH_REALTIME_DESC); + opt_toggle("TOTK_HIGHFPS_FIX", UI_MENU_HIGHFPS_FIX, UI_MENU_HIGHFPS_FIX_DESC); + row_game_lang(); + static const UiTextId mode[] = {UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD}; + opt_choice("TOTK_OPERATION_MODE", UI_MENU_OPERATION_MODE, mode, 2, UI_MENU_OPERATION_MODE_DESC); + opt_end(); +} + +static void tab_sound(float scale) { + opt_begin("##sound", scale); + opt_slider("TOTK_VOLUME", UI_MENU_VOLUME, 0, 100, UI_MENU_VOLUME_DESC, 5, "%.0f %%"); + opt_end(); +} + +static void tab_controls(float scale) { + opt_begin("##controls", scale); + opt_toggle("TOTK_MOTION", UI_MENU_MOTION, UI_MENU_MOTION_DESC); + opt_slider("TOTK_RUMBLE_STRENGTH", UI_MENU_RUMBLE_STRENGTH, 0, 300, UI_MENU_RUMBLE_STRENGTH_DESC, 10, "%.0f %%"); + opt_slider("TOTK_RUMBLE_CURVE", UI_MENU_RUMBLE_CURVE, 0.2f, 1.5f, UI_MENU_RUMBLE_CURVE_DESC, 0.05f, "%.2f"); + opt_toggle("TOTK_RUMBLE_TRIGGERS", UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC); + opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f"); + opt_end(); +} + +static void tab_menu(float scale) { + opt_begin("##menu", scale); + static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU}; + opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, 3, UI_MENU_MENU_LANG_DESC); + opt_end(); +} + +static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, + UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU}; +static int g_tab; // the tab shown +static int g_tab_request = -1; // select this tab at the next layout; -1 none +static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none + +// ---- the window: title, tabs (L / R or Q / E switch), the page, and the bottom row with "Continue" and "Quit game". +// B on the gamepad and Esc close it. +static void layout_menu(uint32_t w, uint32_t h, float scale) { ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(0, 0), ImVec2((float)w, (float)h), IM_COL32(0, 0, 0, 120)); + 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(w * 0.28f, 0), ImGuiCond_Always); - ImGui::Begin("##menu", nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings); - if (ImGui::IsWindowAppearing()) ImGui::SetKeyboardFocusHere(); // "Continue" is selected on opening - ImVec2 full(-1, 0); - if (ImGui::Button(menu_text(UI_MENU_CONTINUE), full)) set_open(0); + ImGui::SetNextWindowSize(ImVec2(ww, wh), ImGuiCond_Always); + ImGui::Begin("##menu", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(UI_MENU_TITLE)); + + int step = ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false) || ImGui::IsKeyPressed(ImGuiKey_E, false) ? 1 + : ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false) || ImGui::IsKeyPressed(ImGuiKey_Q, false) ? -1 + : 0; + if (step) g_tab_request = (g_tab + step + TAB_COUNT) % TAB_COUNT; + if (g_tab_request >= 0) g_focus_page = g_tab_request; // the new page's first row takes the cursor + + const ImGuiStyle &st = ImGui::GetStyle(); + float bottom = ImGui::GetFrameHeight() + st.ItemSpacing.y * 2; + if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_NoTabListScrollingButtons)) { + for (int k = 0; k < TAB_COUNT; k++) { + char label[128]; + snprintf(label, sizeof label, " %s ###tab%d", menu_text(kTabNames[k]), k); // the id stays per language + if (!ImGui::BeginTabItem(label, nullptr, g_tab_request == k ? ImGuiTabItemFlags_SetSelected : 0)) continue; + g_tab = k; + if (g_focus_page == k) { + opt_focus_first(); + g_focus_page = -1; + } + ImGui::Spacing(); + ImGui::BeginChild("##page", ImVec2(0, -bottom), ImGuiChildFlags_NavFlattened); + switch (k) { + case TAB_SCREEN: tab_screen(scale); break; + case TAB_GAME: tab_game(scale); break; + case TAB_SOUND: tab_sound(scale); break; + case TAB_CONTROLS: tab_controls(scale); break; + case TAB_MENU: tab_menu(scale); break; + } + ImGui::EndChild(); + ImGui::EndTabItem(); + } + g_tab_request = -1; + ImGui::EndTabBar(); + } + + // bottom row: the save status on the left, the two buttons on the right ImGui::Spacing(); - if (ImGui::Button(menu_text(UI_MENU_QUIT), full)) gfx_window_request_close(); + float y = ImGui::GetCursorPosY(); + if (!cfg_last_save_ok()) { // stays until a save succeeds; the settings hold for the session + ImGui::SetCursorPosY(y + st.FramePadding.y); + 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); + float bw = fmaxf(ImGui::CalcTextSize(cont).x, ImGui::CalcTextSize(quit).x) + st.FramePadding.x * 4; + ImGui::SetCursorPos(ImVec2(ImGui::GetWindowWidth() - st.WindowPadding.x - bw * 2 - st.ItemSpacing.x, y)); + if (ImGui::Button(cont, ImVec2(bw, 0))) set_open(0); + ImGui::SameLine(); + if (ImGui::Button(quit, ImVec2(bw, 0))) gfx_window_request_close(); if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) set_open(0); ImGui::End(); } -enum { TEST_SHOT_AFTER = 30 }; // frames between the test window opening and its shot +static int g_save_pending; // a changed setting still waits for its write to totk.ini (opt_save_tick) extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) { - static uint64_t opened_at; // frame of the shot hook's open; ~0 once its shot is taken *shot = NULL; + if (!g_test.parsed) test_parse(); + if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame); if (!g_open.load(std::memory_order_relaxed)) { - uint64_t at = test_frame(); - if (!at || opened_at || frame < at) return 0; - opened_at = frame; + if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now + if (!g_test.at || g_test.opened || frame < g_test.at) return 0; + g_test.opened = frame; + g_test.page = 0; + g_tab_request = 0; set_open(1); } if (g_failed_flag()) { @@ -263,39 +571,57 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha return 0; } uint64_t t0 = plat_now_ns(); - if (!g_ctx_ok) make_context(t->height); - if (!vk_up(t)) { + if (!g_ctx_ok) make_context(); + float scale = menu_scale(t->height); + if (!vk_up(t) || (g_font_scale != scale && !fonts_up(scale))) { rt_log("menu: Dear ImGui Vulkan back end set-up failed; the menu stays closed"); g_failed.store(1); set_open(0); return 0; } + if (g_style_scale != scale) { + ImGui::GetStyle() = g_base_style; + ImGui::GetStyle().ScaleAllSizes(scale); + g_style_scale = scale; + } + list_gpus(t->instance); ImGuiIO &io = ImGui::GetIO(); int reset = g_reset.exchange(0); if (reset) { io.ClearInputKeys(); io.ClearInputMouse(); g_last_ns = 0; + g_focus_page = g_tab_request >= 0 ? g_tab_request : g_tab; // opening: the first row has the cursor } io.DisplaySize = ImVec2((float)t->width, (float)t->height); double dt = g_last_ns ? (t0 - g_last_ns) / 1e9 : 1 / 60.0; io.DeltaTime = (float)(dt < 1e-4 ? 1e-4 : dt > 0.1 ? 0.1 : dt); g_last_ns = t0; - drain_events(io); - pad_events(io, reset); + if (g_test.page < 0) { + drain_events(io); + pad_events(io, reset); + } else { // the test hook's pages: the user's input in a background test window must not change settings + plat_mutex_lock(&ev_lock); + ev_n = 0; + plat_mutex_unlock(&ev_lock); + } ImGui_ImplVulkan_NewFrame(); ImGui::NewFrame(); - uint64_t since = opened_at != ~0ull && frame > opened_at ? frame - opened_at : 0; - layout_page(t->width, t->height); + layout_menu(t->width, t->height, scale); ImGui::Render(); + g_save_pending = opt_save_tick(0); g_cost_ns += plat_now_ns() - t0; - if (opened_at != ~0ull && since >= TEST_SHOT_AFTER) { // this frame's image goes to a file, then the window closes - static char path[512]; + if (g_test.page >= 0 && frame >= g_test.opened + g_test.per_page * (uint64_t)(g_test.page + 1)) { + static char path[512]; // this frame's image goes to a file; then the next tab, or the menu closes const char *dir = cfg_get("TOTK_MENU_TEST_DIR"); - snprintf(path, sizeof path, "%s/menu-test-%llu.png", dir ? dir : ".", (unsigned long long)frame); + snprintf(path, sizeof path, "%s/menu-test-%llu-%d.png", dir ? dir : ".", (unsigned long long)frame, g_test.page); *shot = path; - opened_at = ~0ull; - set_open(0); // the next frame lays out nothing + if (++g_test.page == TAB_COUNT) { + g_test.page = -1; + set_open(0); // the next frame lays out nothing + } else { + g_tab_request = g_test.page; + } } return ImGui::GetDrawData()->TotalVtxCount > 0; } diff --git a/runtime/ui/menu.h b/runtime/ui/menu.h index c9e231b6..45eaea8a 100644 --- a/runtime/ui/menu.h +++ b/runtime/ui/menu.h @@ -5,9 +5,11 @@ // // F1 or Esc on the keyboard and Minus and Plus held together (consumed in poll_merged, input_menu_gate in input.h) open it; // F1, Esc, B or "Continue" close it. While it is open the game gets no input (input_menu, input.h) and keeps running; the -// cursor is released from the mouse camera. Only "Continue" and "Quit game" so far (the tabs are still being agreed). -// Test hook TOTK_MENU_TEST= opens the menu at that presented frame, saves one swapchain shot 30 frames later into -// TOTK_MENU_TEST_DIR (default: the working directory) and closes it. +// cursor is released from the mouse camera. Tabs Screen, Game, Sound, Controls and Menu (L / R or Q / E switch them) hold +// option rows (ui/option_rows.h) over the cfg settings; the bottom row has "Continue" and "Quit game". +// Test hooks (ui/menu.cpp): TOTK_MENU_TEST=[:] opens the menu at that presented frame and saves +// one swapchain shot per tab into TOTK_MENU_TEST_DIR; TOTK_MENU_TEST_SET=:=[,...][;...] sets settings +// at given frames without input (SAVE=1 writes totk.ini). // // Threads: the event functions are called by the window thread, menu_toggle by whichever thread polls the pad, the // overlay functions by the present path under its lock. ImGui itself runs on the present path only. @@ -52,6 +54,7 @@ void menu_vk_release(void); // before the device goes away (gfx_wi // ---- what the menu asks of the platform side (gfx_window.c) void gfx_window_apply_settings(void); // TOTK_FULLSCREEN or TOTK_WINDOW_SIZE changed: the window follows void gfx_window_request_close(void); // as the window's close button: the process ends +int gfx_window_monitor_size(int *w, int *h); // pixels of the monitor the window is on; 0 when unknown #ifdef __cplusplus } diff --git a/runtime/ui/menu_win.cpp b/runtime/ui/menu_win.cpp index abc1f7f7..3abbdeb6 100644 --- a/runtime/ui/menu_win.cpp +++ b/runtime/ui/menu_win.cpp @@ -32,8 +32,8 @@ static ImGuiKey key_of(WPARAM vk) { case VK_NEXT: return ImGuiKey_PageDown; case VK_SHIFT: return ImGuiKey_LeftShift; case VK_CONTROL: return ImGuiKey_LeftCtrl; - case 'Q': return ImGuiKey_Q; // previous page (later) - case 'E': return ImGuiKey_E; // next page (later) + case 'Q': return ImGuiKey_Q; // previous tab + case 'E': return ImGuiKey_E; // next tab default: return ImGuiKey_None; } } diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp new file mode 100644 index 00000000..90252135 --- /dev/null +++ b/runtime/ui/option_rows.cpp @@ -0,0 +1,269 @@ +// Two-pane settings pages (option_rows.h): rows on the left, the selected or hovered row's description on the right. +// +// Adapted from SavageWindRecomp's runtime/ui/option_rows.mm (https://github.com/Revivedx/SavageWindRecomp @ +// 575ad88e02f9a89a9a885d90039d48af33c982f4, MIT, Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, +// Copyright (c) 2026 Peiikai): the row look, the two panes, the left / right stepping and the hold speed-up. The rows +// read and write cfg keys instead of a settings struct, take their text from the menu catalog (menu_text), and show +// the default, "after restart" and environment notes; the text field, radio and on-screen keyboard rows are not ported. +#include +#include +#include +#include + +#include "imgui.h" +#include "imgui_internal.h" // SetKeyOwner, SetFocusID, NavCursorVisible + +#include "ui/option_rows.h" + +extern "C" { +#include "cfg.h" +#include "platform/platform.h" +#include "ui_text.h" +// 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))); +} + +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 float g_scale = 1; +static bool g_focus_req, g_take_first; // opt_focus_first: requested / this page's first row takes it +static bool g_held; // the last row's left / right has been held a while (steppers go faster) + +// The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown. +struct Desc { char text[512]; }; +static Desc g_hover, g_focus, g_first, g_shown; + +static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m) { + int n = snprintf(d.text, sizeof d.text, "%s", menu_text(desc)); + if (n < 0 || n >= (int)sizeof d.text) return; + if (cfg_from_env(key)) + snprintf(d.text + n, sizeof d.text - n, "\n\n%s %s", menu_text(UI_MENU_SET_BY_ENV), key); + else if (m && !m->live) + snprintf(d.text + n, sizeof d.text - n, "\n\n%s", menu_text(UI_MENU_AFTER_RESTART)); +} + +void opt_focus_first(void) { g_focus_req = true; } + +void opt_begin(const char *id, float scale) { + g_scale = scale; + g_take_first = g_focus_req; + g_focus_req = false; + 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; + ImVec2 avail = ImGui::GetContentRegionAvail(); + ImGui::PushID(id); + ImGui::BeginChild("##rows", ImVec2(avail.x * 0.58f, avail.y), ImGuiChildFlags_NavFlattened); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 5 * scale)); +} + +void opt_end(void) { + ImGui::PopStyleVar(); + ImGui::EndChild(); + // the hovered row (mouse) wins, else the selected one (controller), else the last shown, else the first row + if (g_hover.text[0]) g_shown = g_hover; + else if (g_focus.text[0]) g_shown = g_focus; + else if (!g_shown.text[0]) g_shown = g_first; + ImGui::SameLine(0, 0); + ImVec2 p = ImGui::GetCursorScreenPos(), avail = ImGui::GetContentRegionAvail(); + 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), + IM_COL32(236, 194, 84, 110), 1.0f); + ImGui::SetCursorScreenPos(ImVec2(p.x + gap, p.y)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(14 * g_scale, 6 * g_scale)); + ImGui::BeginChild("##desc", ImVec2(0, avail.y), ImGuiChildFlags_AlwaysUseWindowPadding, ImGuiWindowFlags_NoNav); + ImGui::PopStyleVar(); + ImGui::PushTextWrapPos(0); + ImGui::TextUnformatted(g_shown.text); + ImGui::PopTextWrapPos(); + ImGui::EndChild(); + ImGui::PopID(); +} + +// What a row shows besides its label. +struct RowView { + const char *value; // right side; "" for none + bool is_default; // the value is the setting's default: the "default" mark, the value not highlighted + bool arrows; // a stepper: < value >, the arrows click too +}; + +// One row: draws it, handles A / click and left / right while selected. Returns 2 (A / click), -1 / +1 (left / right) or +// 0; always 0 for a row the environment fixes (greyed out, still selectable so its description shows). +static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) { + const CfgMeta *m = cfg_meta(key); + bool off = cfg_from_env(key) != 0; + ImGui::PushID(key); + ImVec2 p = ImGui::GetCursorScreenPos(); + float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x, h = fs * 2.2f; + 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); + ImGui::PopStyleColor(); + if (g_take_first) { + g_take_first = false; + ImGui::SetFocusID(ImGui::GetItemID(), ImGui::GetCurrentWindow()); + ImGui::SetNavCursorVisible(true); + ImGui::SetScrollHereY(0); + } + bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible; + int step = clicked && !off ? 2 : 0; + g_held = false; + if (foc && !off) { + if (ImGui::IsKeyPressed(ImGuiKey_GamepadDpadLeft) || ImGui::IsKeyPressed(ImGuiKey_GamepadLStickLeft) || + ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) + step = -1; + if (ImGui::IsKeyPressed(ImGuiKey_GamepadDpadRight) || ImGui::IsKeyPressed(ImGuiKey_GamepadLStickRight) || + ImGui::IsKeyPressed(ImGuiKey_RightArrow)) + step = 1; + static const ImGuiKey steps[] = {ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight}; + for (ImGuiKey k : steps) + if (ImGui::GetKeyData(k)->DownDuration > 1.0f) g_held = true; + // left and right belong to the row (navigation would otherwise move sideways into the description pane); the + // first four of steps, the stick stays with navigation + for (int i = 0; i < 4; i++) ImGui::SetKeyOwner(steps[i], ImGui::GetItemID()); + } + if (foc) desc_set(g_focus, desc, key, m); + if (hov) desc_set(g_hover, desc, key, m); + if (!g_first.text[0]) desc_set(g_first, desc, key, m); + + ImDrawList *dl = ImGui::GetWindowDrawList(); + ImFont *font = ImGui::GetFont(); + float r = 9 * g_scale, pad = 16 * g_scale, small = fs * 0.72f; + dl->AddRectFilled(p, ImVec2(p.x + w, p.y + h), hov || foc ? IM_COL32(255, 255, 255, 22) : IM_COL32(0, 0, 0, 40), r); + dl->AddRect(p, ImVec2(p.x + w, p.y + h), + hov || foc ? (off ? IM_COL32(236, 194, 84, 120) : kGold) : IM_COL32(255, 255, 255, off ? 18 : 38), 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 right = p.x + w - pad; // the value's right edge + float value_left = right; + 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 rx = right - aw, lx = rx - gap - ImGui::CalcTextSize(v.value).x - gap - aw; + ImU32 ac = off ? kGrey : hov || foc ? kGold : IM_COL32(170, 170, 160, 255); + 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); + if (clicked && !off) { + float mx = ImGui::GetIO().MousePos.x; + if (mx >= lx - gap && mx <= lx + aw + gap) step = -1; + else if (mx >= rx - gap && mx <= rx + aw + gap) step = 1; + } + right = rx - gap; + value_left = lx; + } + if (v.value[0]) { + float vx = right - ImGui::CalcTextSize(v.value).x; + dl->AddText(ImVec2(vx, ty), off ? kGrey : v.is_default ? IM_COL32(205, 205, 195, 255) : IM_COL32(255, 255, 255, 255), + v.value); + if (!v.arrows) value_left = vx; + } + if (v.is_default) { // under the value, right-aligned with it + const char *t = menu_text(UI_MENU_DEFAULT_MARK); + float tw = font->CalcTextSizeA(small, FLT_MAX, 0, t).x; + dl->AddText(font, small, ImVec2(right - tw, ny), kDim, t); + } + // the label and its note, clipped before the value + 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), menu_text(label), NULL, 0, + &clip); + const char *note = off ? menu_text(UI_MENU_SET_BY_ENV) : m && !m->live ? menu_text(UI_MENU_AFTER_RESTART) : NULL; + if (note) dl->AddText(font, small, ImVec2(p.x + pad, ny), off ? IM_COL32(200, 150, 90, 255) : kDim, note); + ImGui::PopID(); + return off ? 0 : step; +} + +// ---- writing a setting: at once in memory (live settings follow), to totk.ini a moment later (opt_save_tick) +static uint64_t g_save_at; // plat_now_ns deadline of the pending write; 0 none +static bool g_save_logged; + +static void apply(const char *key, const char *value) { + if (*value) { + cfg_set(key, value); + } else { // the automatic choice: the key unset, its line removed from totk.ini + const char *k = key; + cfg_reset(&k, 1); + } + g_save_at = plat_now_ns() + 400000000ull; +} + +int opt_save_tick(int force) { + if (!g_save_at || (!force && plat_now_ns() < g_save_at)) return g_save_at != 0; + g_save_at = 0; + if (!cfg_save() && !g_save_logged) { + g_save_logged = true; + rt_log("menu: could not write totk.ini; the changed settings hold for this session"); + } + return 0; +} + +// ---- rows + +bool opt_toggle(const char *key, UiTextId label, UiTextId desc) { + const CfgMeta *m = cfg_meta(key); + bool on = cfg_bool(key) != 0, def = m && strcmp(m->def, "0") != 0; + RowView v = {menu_text(on ? UI_MENU_ON : UI_MENU_OFF), on == def, false}; + if (!row(key, label, desc, v)) return false; // any step flips it + apply(key, on ? "0" : "1"); + return true; +} + +bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n, + UiTextId desc, int cur) { + const CfgMeta *m = cfg_meta(key); + const char *now = cfg_value(key); + if (cur < 0) + for (int i = 0; i < n; i++) + if (!strcmp(values[i], now)) cur = i; + int def = -1; + for (int i = 0; m && i < n; i++) + if (!strcmp(values[i], m->def)) def = i; + RowView v = {cur >= 0 ? names[cur] : now, cur == def, true}; + int step = row(key, label, desc, v); + if (!step || n <= 0) return false; + int nv; + if (cur < 0) nv = 0; + else if (step == 2) nv = (cur + 1) % n; // A / click: the next value, round to the first + else nv = cur + step < 0 ? 0 : cur + step >= n ? n - 1 : cur + step; // left / right stop at the ends + if (nv == cur) return false; + apply(key, values[nv]); + return true; +} + +bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc) { + enum { MAX = 32 }; + const CfgMeta *m = cfg_meta(key); + const char *values[MAX], *shown[MAX]; + char buf[256]; + int k = 0; + if (m && !m->def[0]) values[k++] = ""; // the automatic choice + snprintf(buf, sizeof buf, "%s", m && m->values ? m->values : ""); + for (char *s = buf, *e; *s && k < MAX; s = e) { + e = strchr(s, '|'); + if (e) *e++ = 0; + else e = s + strlen(s); + values[k++] = s; + } + if (n > k) n = k; + for (int i = 0; i < n; i++) shown[i] = menu_text(names[i]); + return opt_choice_list(key, label, values, shown, n, desc); +} + +bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt) { + const CfgMeta *m = cfg_meta(key); + double v = cfg_double(key), def = m ? strtod(m->def, NULL) : lo; + char shown[48]; + snprintf(shown, sizeof shown, fmt, v); + RowView rv = {shown, fabs(v - def) < step * 0.01, true}; + int s = row(key, label, desc, rv); + if (!s) return false; + int steps = g_held && (hi - lo) > 40 * step ? 10 : 1; // held: ten steps at a time over a long range + double n = round(v / step) * step + (s == 2 ? step : s * step * steps); + if (s == 2 && n > hi + step * 0.01) n = lo; // A / click past the top goes round; left / right stop at the ends + n = n < lo ? lo : n > hi ? hi : n; + if (fabs(n - v) < step * 0.01) return false; + char out[32]; + if (step >= 1) snprintf(out, sizeof out, "%d", (int)lround(n)); + else snprintf(out, sizeof out, "%g", round(n / step) * step); + apply(key, out); + return true; +} diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h new file mode 100644 index 00000000..54bde931 --- /dev/null +++ b/runtime/ui/option_rows.h @@ -0,0 +1,39 @@ +// Settings pages in two panes (ui/option_rows.cpp): option rows on the left, the selected (controller) or hovered (mouse) +// row's description on the right. Each row shows a setting of the cfg table (cfg.h) and changes it through cfg_set: A or +// a click steps it (toggle, next value), left and right step it. A row marks the default value, says "after restart" when +// the setting is read at start, and is greyed out with a note when an environment variable fixes it. +// +// opt_begin("##screen", scale); +// opt_toggle("TOTK_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC); +// opt_end(); +// +// key: the setting's TOTK_ name, which must have a cfg_meta row. Present path only (ImGui). +#pragma once +#include "imgui.h" + +extern "C" { +#include "ui_text.h" +} + +void opt_begin(const char *id, float scale); +void opt_end(void); +// The next page's first row takes the controller's cursor (opening the menu, switching tabs). +void opt_focus_first(void); + +// The return value of every row: true when it changed the setting this frame. +bool opt_toggle(const char *key, UiTextId label, UiTextId desc); +// 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. +bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc); +// A choice over a list the caller builds (devices, window sizes): values[i] is written, names[i] shown; "" means the key +// unset. cur: the index in effect, -1 to find cfg_value(key) in values (no match: the value shown as it is). +bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n, + UiTextId desc, int cur = -1); +// lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%"). +bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1, + const char *fmt = "%g"); + +// totk.ini is written a moment after the last change (a held slider would rewrite it every frame) and when the menu +// closes. opt_save_tick: on every frame the menu lays out; force: write now if anything is pending. 1 while a write is +// pending. +int opt_save_tick(int force);