From d850c2116db9fb94e736174c9bf6c9bd05a73eb5 Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:55:12 +0100 Subject: [PATCH] Count play time across runs and show it on the Game tab A host thread adds each second in which the window has the focus and the game presents frames, keeps the total in /playtime.txt (every 30 s and at exit) and the Game tab of the settings menu shows it with this run's share. Texts in English, Russian, Brazilian Portuguese and Simplified Chinese. Closes #720. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + runtime/boot.c | 1 + runtime/gfx_present.c | 1 + runtime/host.h | 3 ++ runtime/main.c | 1 + runtime/playtime.c | 121 ++++++++++++++++++++++++++++++++++++++++++ runtime/svc.c | 1 + runtime/ui/menu.cpp | 15 ++++++ runtime/ui_text.c | 16 ++++++ runtime/ui_text.h | 3 ++ 10 files changed, 163 insertions(+) create mode 100644 runtime/playtime.c diff --git a/README.md b/README.md index 9b0c3f9d..c0ffc147 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - 16:10 (Steam Deck, handhelds), 3:2 (Surface, Framework), 21:9 and 32:9 (ultrawide) game resolutions, with the camera and the interface in that shape - Anisotropic texture filtering up to 16x, for sharp ground into the distance - In-game settings menu (F1) and performance overlay (F10) +- Play time across runs on the Game tab of the settings menu, kept in `playtime.txt` next to the saves - Discord Rich Presence ("Playing TotK Recomp" with the play time), off by default, own application id supported - Setup and in-game menu in English, Russian, Brazilian Portuguese and Simplified Chinese - Keyboard, mouse and gamepad with remapping, rumble and gyro diff --git a/runtime/boot.c b/runtime/boot.c index 992bf33b..d1c1c1b1 100644 --- a/runtime/boot.c +++ b/runtime/boot.c @@ -307,6 +307,7 @@ void rt_frame_presented(const tex_t *t, uint64_t n) { fflush(stderr); fs_save_flush(); vk_pipeline_save(); // no-op without the Vulkan back end + playtime_save(); prof_write(); fflush(stderr); plat_exit(0); diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index ea0c72c9..472acb41 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -72,6 +72,7 @@ void gfx_window_closed(void) { rt_log("gfx: window closed; %s", restart ? "restarting" : "exiting"); fs_save_flush(); vk_pipeline_save(); + playtime_save(); prof_write(); // plat_exit runs no atexit handlers if (restart) { plat_setenv("TOTK_REEXEC", NULL); // the new process counts its own address-space retries (memory.c) diff --git a/runtime/host.h b/runtime/host.h index 065256a2..1cf399a3 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -316,6 +316,9 @@ int probe_cfg(void); // cfg_probe.c int probe_dpi(void); // dpi_probe_win.c (Windows only) int probe_mods(void); // mods_probe.c void discord_init(void); // discord_rpc.c: the Rich Presence thread, game runs only +void playtime_init(void); // playtime.c: the play time thread, game runs only +void playtime_save(void); // playtime.c: writes /playtime.txt; at exit +int playtime_get(uint64_t *total_s, uint64_t *session_s); // playtime.c: all runs and this one; 0 while not counted int probe_discord(void); // discord_rpc.c int probe_loader(void), probe_kernel(void), probe_ipc(void), probe_services(void), probe_fs(void); int probe_gfx_abi(void); // gfx_abi_probe.c diff --git a/runtime/main.c b/runtime/main.c index 720896f8..3cf47de3 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -553,6 +553,7 @@ int main(int argc, char **argv) { if (!mode) { cfg.boot = cfg.seconds > 0; // --seconds starts the game like --boot, with its checkpoints discord_init(); // the Rich Presence thread (discord_rpc.c); it reads totk.ini itself and idles while off + playtime_init(); // the play time thread (playtime.c): the Game tab's play time across runs rt_boot(); return 0; } diff --git a/runtime/playtime.c b/runtime/playtime.c new file mode 100644 index 00000000..3d11d043 --- /dev/null +++ b/runtime/playtime.c @@ -0,0 +1,121 @@ +// Play time: how long the player has spent in the game, across runs, shown on the Game tab of the settings menu +// (ui/menu.cpp tab_game). The game itself keeps no play time a player can see, and the Switch's own play log is not +// there to read, so the port counts it. +// +// One host thread (it never holds a virtual core, as discord_rpc.c's) wakes every second and adds the time since its +// last wake when the window has the focus (gfx_window_focused) and the game presented at least one frame meanwhile +// (gfx_stats). So the shader prewarm before the first frame, a window left in the background and a hung game do not +// count; loading screens and the game's own menus do, as they present frames. One wake adds at most TICK_CAP_MS, so a +// machine that slept with the game open adds two seconds, not the night. +// +// The total lives in /playtime.txt, next to account.uid and the saves, so it stays with them when the +// install is updated or moved. It is plain text, "total_seconds ", written atomically (plat_file_write_atomic) +// every SAVE_EVERY_MS while it grows and once more when the game exits (playtime_save from boot.c, svc.c and +// gfx_present.c, next to prof_write); a crash loses at most SAVE_EVERY_MS. A file that does not read as that is kept +// as playtime.txt.bad and the count starts again from zero. +#include +#include +#include +#include +#include + +#include "gfx.h" +#include "host.h" +#include "platform/platform.h" + +#define TICK_MS 1000 +#define TICK_CAP_MS 2000 +#define SAVE_EVERY_MS 30000 +#define TOTAL_CAP_S (100ull * 365 * 24 * 3600) // a hundred years: anything larger is a damaged file + +static PlatMutex lock = PLAT_MUTEX_INIT; // the totals and the file +static uint64_t total_ms, session_ms, saved_ms; +static int loaded; // 1 once the file was read (or found missing), -1 when there is no profile +static char path[1100]; + +// Holding lock. +static void load(void) { + if (loaded) return; + const char *dir = rt_config()->profile; + if (!dir || !*dir || snprintf(path, sizeof path, "%s/playtime.txt", dir) >= (int)sizeof path) { + loaded = -1; + rt_log("playtime: no profile directory; play time is not counted"); + return; + } + loaded = 1; + uint64_t n = 0; + uint8_t *b = plat_file_read(path, &n); + if (!b) { + rt_log("playtime: no %s yet; counting from zero", path); + return; + } + char text[64] = {0}; + memcpy(text, b, n < sizeof text - 1 ? n : sizeof text - 1); + free(b); + unsigned long long s = 0; + char tail = 0; + if (sscanf(text, "total_seconds %llu%c", &s, &tail) >= 1 && (!tail || tail == '\n' || tail == '\r') && + s <= TOTAL_CAP_S) { + total_ms = saved_ms = (uint64_t)s * 1000; + rt_log("playtime: %llu h %02llu min played before this run (%s)", s / 3600, s / 60 % 60, path); + return; + } + char bad[1110]; + snprintf(bad, sizeof bad, "%s.bad", path); + int kept = plat_file_write_atomic(bad, text, strlen(text)); + rt_log("playtime: %s does not read as \"total_seconds \"; %s, counting from zero", path, + kept ? "kept as playtime.txt.bad" : "could not keep a copy"); +} + +// Holding lock. +static void save_locked(void) { + if (loaded != 1 || total_ms / 1000 == saved_ms / 1000) return; + char text[48]; + int n = snprintf(text, sizeof text, "total_seconds %" PRIu64 "\n", total_ms / 1000); + if (plat_file_write_atomic(path, text, (size_t)n)) saved_ms = total_ms; + else rt_log("playtime: cannot write %s", path); +} + +void playtime_save(void) { + plat_mutex_lock(&lock); + save_locked(); + plat_mutex_unlock(&lock); +} + +int playtime_get(uint64_t *total_s, uint64_t *session_s) { + plat_mutex_lock(&lock); + int ok = loaded == 1; + *total_s = total_ms / 1000; + *session_s = session_ms / 1000; + plat_mutex_unlock(&lock); + return ok; +} + +static void playtime_main(void *arg) { + (void)arg; + plat_thread_priority(PLAT_PRIO_BELOW_NORMAL); + plat_mutex_lock(&lock); + load(); + int on = loaded == 1; + plat_mutex_unlock(&lock); + if (!on) return; + uint64_t last = plat_now_ms(), last_save = last, frames = gfx_stats().frames; + for (;;) { + plat_sleep_ms(TICK_MS); + uint64_t now = plat_now_ms(), f = gfx_stats().frames, d = now - last; + int playing = f != frames && gfx_window_focused(); + last = now, frames = f; + if (d > TICK_CAP_MS) d = TICK_CAP_MS; + plat_mutex_lock(&lock); + if (playing) total_ms += d, session_ms += d; + if (now - last_save >= SAVE_EVERY_MS) save_locked(), last_save = now; + plat_mutex_unlock(&lock); + } +} + +void playtime_init(void) { + static int32_t started; + if (plat_xchg32(&started, 1)) return; + if (!plat_thread_spawn(playtime_main, NULL, "playtime", 0)) + rt_log("playtime: cannot start its thread; play time is not counted"); +} diff --git a/runtime/svc.c b/runtime/svc.c index f257dd0a..27cdad19 100644 --- a/runtime/svc.c +++ b/runtime/svc.c @@ -216,6 +216,7 @@ static void svc_body(Cpu *c, uint32_t imm, uint64_t pc) { rt_log("guest ExitProcess at %s; exiting", ldr_describe(pc, at, sizeof at)); fs_save_flush(); vk_pipeline_save(); + playtime_save(); prof_write(); fflush(NULL); if (svc_test_exit_hook) return svc_test_exit_hook(0); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index d4b60442..bd500fa3 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -57,6 +57,7 @@ extern const int rt_game_version; extern const char rt_port_version[]; void cheats_frame(uint64_t frame); // cheats.c bool tab_cheats(float scale); // ui/cheats_tab.cpp; true: restart into the rebuild +int playtime_get(uint64_t *total_s, uint64_t *session_s); // playtime.c } // Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs. @@ -698,6 +699,19 @@ static void tab_screen(float scale) { opt_end(); } +// Play time across runs (playtime.c), read only. Hidden while it is not counted (no profile directory). +static void row_play_time(void) { + uint64_t total, session; + if (!playtime_get(&total, &session)) return; + char value[64], run[64], note[96]; + snprintf(value, sizeof value, menu_text(UI_MENU_PLAY_TIME_HM), (unsigned long long)(total / 3600), + (unsigned)(total / 60 % 60)); + snprintf(run, sizeof run, menu_text(UI_MENU_PLAY_TIME_HM), (unsigned long long)(session / 3600), + (unsigned)(session / 60 % 60)); + snprintf(note, sizeof note, menu_text(UI_MENU_PLAY_TIME_SESSION), run); + opt_text_row("##play_time", menu_text(UI_MENU_PLAY_TIME), value, note, menu_text(UI_MENU_PLAY_TIME_DESC), false); +} + static void tab_game(float scale) { opt_begin("##game", scale); row_fps_limit(); @@ -706,6 +720,7 @@ static void tab_game(float scale) { 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_toggle("TOTK_ASSUME_FOCUS", UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC); + row_play_time(); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index ccb91d03..f4e033c5 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -192,6 +192,10 @@ static const char *const text_en[UI_TEXT_COUNT] = { "window loses focus, as on the Switch when Home is pressed; a load interrupted that " "way can stop for good.", + [UI_MENU_PLAY_TIME] = "Play time", + [UI_MENU_PLAY_TIME_DESC] = "Time in the game over all runs, counted while the game window has the focus and the game " + "draws frames. Kept in playtime.txt in the profile folder, next to the saves.", + [UI_MENU_PLAY_TIME_HM] = "%llu h %02u min", [UI_MENU_PLAY_TIME_SESSION] = "this run: %s", [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 " "inside, and restart the game. TKMM can export its merged mods into a folder there too.", @@ -662,6 +666,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = { "когда окно теряет фокус, как на Switch при нажатии Home; прерванная так загрузка " "может остановиться насовсем.", + [UI_MENU_PLAY_TIME] = "Время в игре", + [UI_MENU_PLAY_TIME_DESC] = "Время в игре за все запуски. Считается, пока окно игры в фокусе и игра рисует кадры. " + "Хранится в playtime.txt в папке профиля, рядом с сохранениями.", + [UI_MENU_PLAY_TIME_HM] = "%llu ч %02u мин", [UI_MENU_PLAY_TIME_SESSION] = "в этом запуске: %s", [UI_MENU_MODS_BUILTIN] = "Встроенные в порт", [UI_MENU_MODS_INSTALLED] = "Установленные моды", [UI_MENU_MODS_NONE] = "Модов пока нет. Распакуйте мод в папку mods, каждый мод в свою папку с папкой romfs внутри, и " "перезапустите игру. TKMM тоже может выгрузить туда объединённые моды отдельной папкой.", @@ -983,6 +991,10 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_TAB_SCREEN] = "Tela", [UI_MENU_TAB_GAME] = "Jogo", [UI_MENU_TAB_SOUND] = "Som", [UI_MENU_TAB_CONTROLS] = "Controles", [UI_MENU_TAB_AMIIBO] = "Amiibo", [UI_MENU_TAB_MENU] = "Menu", [UI_MENU_TAB_ADVANCED] = "Avançado", [UI_MENU_TAB_MODS] = "Mods", + [UI_MENU_PLAY_TIME] = "Tempo de jogo", + [UI_MENU_PLAY_TIME_DESC] = "Tempo no jogo somando todas as sessões, contado enquanto a janela do jogo está em foco e o " + "jogo desenha quadros. Fica em playtime.txt na pasta do perfil, junto dos saves.", + [UI_MENU_PLAY_TIME_HM] = "%llu h %02u min", [UI_MENU_PLAY_TIME_SESSION] = "nesta sessão: %s", [UI_MENU_MODS_BUILTIN] = "Embutidos no port", [UI_MENU_MODS_INSTALLED] = "Mods instalados", [UI_MENU_MODS_NONE] = "Nenhum mod ainda. Descompacte um mod na pasta mods, uma pasta por mod com a pasta romfs dentro, " "e reinicie o jogo. O TKMM também pode exportar os mods mesclados para uma pasta ali.", @@ -1492,6 +1504,10 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_TAB_MENU] = "菜单", [UI_MENU_TAB_ADVANCED] = "高级", [UI_MENU_TAB_MODS] = "模组", + [UI_MENU_PLAY_TIME] = "游戏时间", + [UI_MENU_PLAY_TIME_DESC] = "所有运行累计的游戏时间,仅在游戏窗口处于焦点且游戏正在绘制画面时计时。" + "保存在配置文件夹的 playtime.txt 中,与存档放在一起。", + [UI_MENU_PLAY_TIME_HM] = "%llu 小时 %02u 分钟", [UI_MENU_PLAY_TIME_SESSION] = "本次运行:%s", [UI_MENU_MODS_BUILTIN] = "移植版内置", [UI_MENU_MODS_INSTALLED] = "已安装的模组", [UI_MENU_MODS_NONE] = "还没有模组。把模组解压到 mods 文件夹,每个模组一个文件夹,里面放 romfs 文件夹,然后重启游戏。" "TKMM 也可以把合并后的模组导出到那里的一个文件夹。", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index deca0f7f..59e277b4 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -70,6 +70,9 @@ typedef enum { UI_MENU_GAME_LANG, UI_MENU_GAME_LANG_DESC, UI_MENU_GAME_LANG_AUTO, UI_MENU_OPERATION_MODE, UI_MENU_OPERATION_MODE_DESC, UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD, UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC, + UI_MENU_PLAY_TIME, UI_MENU_PLAY_TIME_DESC, + UI_MENU_PLAY_TIME_HM, // hours and minutes: "%llu h %02u min" (unsigned long long hours, unsigned minutes) + UI_MENU_PLAY_TIME_SESSION, // note under the total: "this run: %s" (the hours and minutes above) // Mods: the port's own patches and the player's mods folder (mods.c) UI_MENU_MODS_BUILTIN, UI_MENU_MODS_INSTALLED,