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 1/2] 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, From 4645b8a0d067b2dc59c2806ce47de470a8a660a8 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Fri, 6 Nov 2026 10:55:42 +0300 Subject: [PATCH 2/2] Leave scripted runs out of the play time, keep a damaged file whole, and test the file with --probe-playtime. A --seconds run (benches, menu shots, input scripts) reads the total so the Game tab shows it, but starts no counting thread. The file is now read once at start instead of on the thread. A playtime.txt with a UTF-8 byte order mark reads as valid, and a damaged one is kept whole as playtime.txt.bad instead of its first 63 bytes. --probe-playtime checks the parser, a missing, valid and damaged file, the 30 s save and the 2 s cap of one tick. Co-Authored-By: Claude Opus 5.5 --- runtime/host.h | 3 +- runtime/main.c | 4 +- runtime/playtime.c | 143 +++++++++++++++++++++++++++++++++++++-------- 3 files changed, 123 insertions(+), 27 deletions(-) diff --git a/runtime/host.h b/runtime/host.h index 1cf399a3..21d0534f 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -318,7 +318,8 @@ 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 playtime_get(uint64_t *total_s, uint64_t *session_s); // playtime.c: all runs and this one; 0 without a profile +int probe_playtime(void); // playtime.c: the file, the ticks and the save 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 3cf47de3..49d227a0 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -7,6 +7,7 @@ // --probe-loader load and relocate the modules, check them against the measured 1.2.1 values // --probe-kernel, --probe-ipc, --probe-services, --probe-fs host probes // --probe-discord the Rich Presence IPC exchange; skips without a Discord client; no game files +// --probe-playtime the play time file, its ticks and saves (playtime.c); needs no game files // --probe-dpi the process DPI awareness (per-monitor v2) and the primary monitor's size; no game files // --probe-gfx-abi NVN object layouts against nvn.h's reserved sizes; needs no game files // --probe-nvn, --probe-nvn-tex, --probe-window, --probe-shader, --probe-vkmem, --probe-vkexec graphics probes @@ -463,7 +464,7 @@ static int probe_crash(int null) { static int usage(const char *argv0) { fprintf(stderr, "usage: %s [--exefs DIR] [--romfs DIR] [--profile DIR] [--selftest | --probe-loader | " - "--probe-cfg | --probe-dpi | --probe-mods | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | " + "--probe-cfg | --probe-dpi | --probe-mods | --probe-playtime | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | " "--probe-nvn | --probe-nvn-tex | --probe-window | --probe-shader | --probe-vkmem | " "--probe-vkexec | --probe-astc | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | " "--prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0); @@ -567,6 +568,7 @@ int main(int argc, char **argv) { #endif if (!strcmp(mode, "--probe-mods")) return probe_mods(); if (!strcmp(mode, "--probe-discord")) return probe_discord(); + if (!strcmp(mode, "--probe-playtime")) return probe_playtime(); if (!strcmp(mode, "--probe-kernel")) return probe_kernel(); if (!strcmp(mode, "--probe-ipc")) return probe_ipc(); if (!strcmp(mode, "--probe-services")) return probe_services(); diff --git a/runtime/playtime.c b/runtime/playtime.c index 3d11d043..5b53700f 100644 --- a/runtime/playtime.c +++ b/runtime/playtime.c @@ -12,7 +12,7 @@ // 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. +// as playtime.txt.bad and the count starts again from zero. A scripted run (--seconds) reads the total and adds nothing. #include #include #include @@ -33,36 +33,47 @@ 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) { +// The seconds of a playtime.txt: "total_seconds ", a line end or nothing after it, a UTF-8 byte order mark before it +// (an editor may add one). 1 when the file reads so and n is at most TOTAL_CAP_S. +static int parse(const uint8_t *b, uint64_t n, uint64_t *seconds) { + if (n >= 3 && !memcmp(b, "\xEF\xBB\xBF", 3)) b += 3, n -= 3; + char text[64] = {0}; + memcpy(text, b, n < sizeof text - 1 ? n : sizeof text - 1); + 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) + return 0; + *seconds = s; + return 1; +} + +// Holding lock. dir: the profile directory. +static void load(const char *dir) { 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; + uint64_t n = 0, s = 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); + if (parse(b, n, &s)) { + free(b); + total_ms = saved_ms = s * 1000; + rt_log("playtime: %llu h %02llu min played before this run (%s)", (unsigned long long)(s / 3600), + (unsigned long long)(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)); + int kept = plat_file_write_atomic(bad, b, (size_t)n); // the whole file, for the player to recover the number + free(b); 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"); } @@ -91,31 +102,113 @@ int playtime_get(uint64_t *total_s, uint64_t *session_s) { return ok; } +// Holding lock: the time since the last tick, d ms, when the game was played meanwhile; the file every SAVE_EVERY_MS. +static void tick_locked(uint64_t now, uint64_t d, int playing, uint64_t *last_save) { + if (d > TICK_CAP_MS) d = TICK_CAP_MS; + if (playing) total_ms += d, session_ms += d; + if (now - *last_save >= SAVE_EVERY_MS) save_locked(), *last_save = now; +} + 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; + uint64_t now = plat_now_ms(), f = gfx_stats().frames; 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; + tick_locked(now, now - last, playing, &last_save); plat_mutex_unlock(&lock); + last = now, frames = f; } } +// The file is read at once, so the Game tab shows the total from the first frame. A scripted run (--seconds: benches, +// menu shots, input scripts) shows it but adds nothing: those runs are not play. void playtime_init(void) { static int32_t started; if (plat_xchg32(&started, 1)) return; + plat_mutex_lock(&lock); + load(rt_config()->profile); + int on = loaded == 1; + plat_mutex_unlock(&lock); + if (!on) return; + if (rt_config()->seconds > 0) { + rt_log("playtime: a scripted run (--seconds); play time is shown, not counted"); + return; + } if (!plat_thread_spawn(playtime_main, NULL, "playtime", 0)) rt_log("playtime: cannot start its thread; play time is not counted"); } + +// --probe-playtime: the file's parsing, a missing, a valid and a damaged file, the periodic save and the tick's cap, in +// a directory next to totk.exe. Needs no game files. +static int fails; +#define CHECK(c, what) do { if (!(c)) { fails++; fprintf(stderr, "FAIL playtime: %s\n", what); } } while (0) + +static void reset(void) { total_ms = session_ms = saved_ms = 0, loaded = 0, path[0] = 0; } + +static int file_is(const char *p, const char *want) { + uint64_t n = 0; + uint8_t *b = plat_file_read(p, &n); + int ok = b && n == strlen(want) && !memcmp(b, want, n); + free(b); + return ok; +} + +int probe_playtime(void) { + uint64_t s = 0; + CHECK(parse((const uint8_t *)"total_seconds 42\n", 17, &s) && s == 42, "a line with LF"); + CHECK(parse((const uint8_t *)"total_seconds 42\r\n", 18, &s) && s == 42, "a line with CRLF"); + CHECK(parse((const uint8_t *)"total_seconds 42", 16, &s) && s == 42, "no line end"); + CHECK(parse((const uint8_t *)"\xEF\xBB\xBFtotal_seconds 7\n", 19, &s) && s == 7, "a byte order mark"); + CHECK(!parse((const uint8_t *)"total_seconds 42x", 17, &s), "a character after the number"); + CHECK(!parse((const uint8_t *)"total_seconds -1\n", 17, &s), "a negative number"); + CHECK(!parse((const uint8_t *)"total_seconds 3153600001\n", 25, &s), "over a hundred years"); + CHECK(!parse((const uint8_t *)"seconds 42\n", 11, &s), "another key"); + CHECK(!parse((const uint8_t *)"", 0, &s), "an empty file"); + + char dir[1024]; + if (!plat_exe_path(dir, sizeof dir)) return 1; + char *cut = plat_last_sep(dir); + if (!cut) return 1; + strcpy(cut + 1, "playtime-probe"); + plat_file_mkdir_p(dir); + char file[1100], bad[1110]; + snprintf(file, sizeof file, "%s/playtime.txt", dir); + snprintf(bad, sizeof bad, "%s.bad", file); + plat_file_delete(file); + plat_file_delete(bad); + + uint64_t total, session, last_save = 0; + reset(); + load(dir); + CHECK(playtime_get(&total, &session) && total == 0, "a missing file counts from zero"); + tick_locked(1000, 1000, 1, &last_save); + tick_locked(2000, 1000, 0, &last_save); + CHECK(plat_file_size(file) < 0, "nothing is written before SAVE_EVERY_MS"); + tick_locked(2000 + 3600000, 3600000, 1, &last_save); // a machine that slept: one tick adds TICK_CAP_MS, and saves + playtime_get(&total, &session); + CHECK(total == 3 && session == 3, "played ticks count, an idle one does not, a long one is capped"); + CHECK(file_is(file, "total_seconds 3\n"), "the save after SAVE_EVERY_MS writes the total"); + + reset(); + load(dir); + playtime_get(&total, &session); + CHECK(total == 3 && session == 0, "the next run reads the total back"); + + static const char damaged[] = "total_seconds twelve\n"; + plat_file_write_atomic(file, damaged, sizeof damaged - 1); + reset(); + load(dir); + playtime_get(&total, &session); + CHECK(total == 0, "a damaged file counts from zero"); + CHECK(file_is(bad, damaged), "a damaged file is kept whole as playtime.txt.bad"); + + plat_file_delete(file); + plat_file_delete(bad); + reset(); + fprintf(stderr, "playtime: %s (%d failures)\n", fails ? "FAILED" : "ok", fails); + return fails ? 1 : 0; +}