diff --git a/README.md b/README.md index 5be2e139..52904d81 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - 16:10 (Steam Deck, handhelds), 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) +- 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 - Xbox button prompts: LB, RB, LT, RT, Menu and View, and A, B, X and Y as labelled on the button to press, with either button layout diff --git a/runtime/cfg.c b/runtime/cfg.c index 015cda1b..a3512048 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -37,7 +37,7 @@ static const char *const known[] = { "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA", "COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT", - "DESC_TEMPLATE", "DEVICE_PROFILE", "DLAA", "DLAA_JITTER", "DLAA_MV", "DLSS", "DUMP", "DUMP_BUF", "DUMP_DIR", + "DESC_TEMPLATE", "DEVICE_PROFILE", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_JITTER", "DLAA_MV", "DLSS", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", @@ -72,6 +72,7 @@ static const struct { const char *key, *section; } sections[] = { {"HDR_UI_NITS", "display"}, {"SHADOW_RES", "display"}, {"DLAA", "display"}, {"DLSS", "display"}, {"FXAA", "display"}, {"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"}, + {"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"}, {"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"}, @@ -145,6 +146,11 @@ static const CfgMeta metas[] = { {"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE}, {"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE}, {"AMIIBO_DIR", "", NULL, LIVE}, + // Discord Rich Presence (discord_rpc.c): off by default, the Menu tab of the settings menu switches it. The app + // id is the one this was developed against, registered as "TotK Recomp"; the image, the key of its art asset. + {"DISCORD_RPC", "0", "0|1", LIVE}, + {"DISCORD_APP_ID", "1566609987453722727", NULL, LIVE}, + {"DISCORD_IMAGE", "totk_512x512", NULL, LIVE}, // Advanced: scheduling {"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART}, {"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART}, diff --git a/runtime/discord_rpc.c b/runtime/discord_rpc.c new file mode 100644 index 00000000..e74f07cb --- /dev/null +++ b/runtime/discord_rpc.c @@ -0,0 +1,256 @@ +// Discord Rich Presence: "Playing TotK Recomp" with the elapsed play time in the player's Discord status, through +// the local IPC of a running Discord client (platform.h's plat_ipc_*). Nothing leaves the machine but the activity +// itself, and nothing is sent while TOTK_DISCORD_RPC is off (the default: the status is information about the +// player's session). TOTK_DISCORD_APP_ID names the application whose name and artwork Discord shows — the default +// is the app this feature was developed against, registered as "TotK Recomp"; a player who wants their own name or +// art registers an application at discord.com/developers and puts its id in totk.ini — and TOTK_DISCORD_IMAGE the +// key of its uploaded art asset. +// +// One host thread owns the connection and never holds a virtual core (kernel.c: host work runs without one). It +// re-reads the settings when cfg_version changes (a menu change reaches it within half a second), connects to the +// first of Discord's discord-ipc-0..9 pipes that answers, and writes the activity again every 60 s: that write is +// the keep-alive, and one that fails closes the connection and tries again 15 s later. Discord clears the status by +// itself when the process ends and the pipe closes, so there is no shutdown path. Every answer frame is read and +// discarded: unread, they would fill the pipe's buffer and block the client's writes. +// +// The protocol is the documented IPC one (discord-rpc's src/rpc_connection.h): a frame is , with Handshake 0, Frame 1, Close 2, Ping 3 and Pong 4. The handshake +// (opcode 0) carries {"v":1,"client_id":...} and is answered by a Ready frame (opcode 1); every command, +// SET_ACTIVITY here, is a frame (opcode 1) answered by one, and a Ping the client sends is echoed as a Pong. A +// client that speaks another numbering (an early arRPC did) answers the handshake with a Close. --probe-discord +// runs the same exchange once, without the game and without the setting being on. +#include +#include +#include +#include + +#include "cfg.h" +#include "host.h" +#include "platform/platform.h" + +enum { OP_HANDSHAKE = 0, OP_FRAME = 1, OP_CLOSE = 2, OP_PING = 3, OP_PONG = 4 }; + +#define APP_ID_CAP 24 // a Discord snowflake: at most 20 digits +#define IMAGE_KEY_CAP 64 +#define ANSWER_CAP 8192 // the Ready frame carries the client's config; a few KiB + +// A settings value that fits the JSON below without escaping: the app id is digits, an asset key letters, digits, +// '_' and '-' (what Discord's developer portal accepts for an asset key). +static int valid_app_id(const char *s) { + size_t n = strlen(s); + if (!n || n > 20) return 0; + for (const char *p = s; *p; p++) + if (*p < '0' || *p > '9') return 0; + return 1; +} + +static int valid_image_key(const char *s) { + size_t n = strlen(s); + if (!n || n >= IMAGE_KEY_CAP) return 0; + for (const char *p = s; *p; p++) + if ((*p < 'a' || *p > 'z') && (*p < 'A' || *p > 'Z') && (*p < '0' || *p > '9') && *p != '_' && *p != '-') + return 0; + return 1; +} + +// The setting's value, or its default when the value does not fit the protocol (logged: the player sees why their +// own app does not show). Called on the presence thread and by the probe, after cfg_version changed or once. +static void read_setting(const char *name, char *out, size_t cap, int (*valid)(const char *)) { + const char *v = cfg_value(name); + if (valid(v)) { + snprintf(out, cap, "%s", v); + return; + } + snprintf(out, cap, "%s", cfg_meta(name)->def); + rt_log("discord: %s does not fit what the Rich Presence protocol takes; using %s", name + strlen("TOTK_"), out); +} + +static void le32(uint8_t *at, uint32_t v) { + at[0] = (uint8_t)v, at[1] = (uint8_t)(v >> 8), at[2] = (uint8_t)(v >> 16), at[3] = (uint8_t)(v >> 24); +} + +static int write_frame(PlatIpc *p, uint32_t op, const char *json) { + uint8_t head[8]; + le32(head, op); + le32(head + 4, (uint32_t)strlen(json)); + return plat_ipc_write(p, head, sizeof head) && plat_ipc_write(p, json, strlen(json)); +} + +// One frame off the wire, its 8-byte header in as many reads as the peer made, then its payload; a payload longer +// than cap-1 fills buf with its first cap-1 bytes and the rest is still consumed. *op gets the opcode; buf is +// NUL-terminated. 1 on a whole frame, 0 when the deadline passed, -1 when the connection broke. +static int read_one_frame(PlatIpc *p, uint32_t *op, char *buf, size_t cap, uint64_t deadline) { + uint8_t head[8]; + size_t got = 0; + while (got < sizeof head) { + uint32_t left = deadline > plat_now_ms() ? (uint32_t)(deadline - plat_now_ms()) : 0; + int n = plat_ipc_read(p, head + got, sizeof head - got, left); + if (n < 0) return -1; + if (!n) { + if (plat_now_ms() >= deadline) return 0; + continue; + } + got += (size_t)n; + } + *op = head[0] | head[1] << 8 | head[2] << 16 | (uint32_t)head[3] << 24; + uint32_t len = head[4] | head[5] << 8 | head[6] << 16 | (uint32_t)head[7] << 24; + size_t taken = 0; + while (taken < len) { + size_t want = len - taken > cap - 1 ? cap - 1 : len - taken; + uint32_t left = deadline > plat_now_ms() ? (uint32_t)(deadline - plat_now_ms()) : 0; + int n = plat_ipc_read(p, buf, want, left); + if (n < 0) return -1; + if (!n) { + if (plat_now_ms() >= deadline) return 0; + continue; + } + taken += (size_t)n; + } + buf[taken < cap - 1 ? taken : cap - 1] = 0; + return 1; +} + +// The next frame that is not a Ping: a Ping the client sent to see we are alive is echoed as a Pong with its own +// payload, a Close (the client told us it is done) counts as a broken connection so the caller connects again +// later. Same return values as read_one_frame; the deadline covers the whole exchange. +static int read_frame(PlatIpc *p, uint32_t *op, char *buf, size_t cap, uint32_t ms) { + uint64_t deadline = plat_now_ms() + ms; + for (;;) { + int r = read_one_frame(p, op, buf, cap, deadline); + if (r != 1) return r; + if (*op == OP_PING) { + uint8_t head[8]; + size_t n = strlen(buf); + le32(head, OP_PONG); + le32(head + 4, (uint32_t)n); + if (!plat_ipc_write(p, head, sizeof head) || !plat_ipc_write(p, buf, n)) return -1; + continue; + } + if (*op == OP_CLOSE) return -1; + return 1; + } +} + +// The first of Discord's pipes that completes a handshake. NULL when no client is running or none answered in time; +// the caller tries again later. +static PlatIpc *connect_client(const char *app_id) { + for (int i = 0; i < 10; i++) { + char name[32], json[160]; + snprintf(name, sizeof name, "discord-ipc-%d", i); + PlatIpc *p = plat_ipc_connect(name); + if (!p) continue; + snprintf(json, sizeof json, "{\"v\":1,\"client_id\":\"%s\"}", app_id); + if (!write_frame(p, OP_HANDSHAKE, json)) { + plat_ipc_close(p); + continue; + } + uint32_t op = 0; + char answer[ANSWER_CAP]; + if (read_frame(p, &op, answer, sizeof answer, 2000) == 1 && op == OP_FRAME) return p; // the Ready event + plat_ipc_close(p); // this pipe answered but not with a Ready frame in 2 s: the next may belong to a client + } + return NULL; +} + +static uint32_t next_nonce(void) { + static volatile int32_t n; + return (uint32_t)plat_inc32(&n); +} + +// The activity as one SET_ACTIVITY frame: the game update as the details line, the process's start as the timestamp +// Discord counts the elapsed time from, and the application's art asset. 1 when the client answered (a slow answer +// that ran out of the 2 s read is fine: the next drain takes it), 0 when the connection broke. +static int send_activity(PlatIpc *p, const char *image) { + char json[512]; + int v = rt_game_version; + uint64_t start = (plat_unix_time_ns() - plat_process_uptime_ns()) / 1000000000ull; + snprintf(json, sizeof json, + "{\"cmd\":\"SET_ACTIVITY\",\"nonce\":\"%u\",\"args\":{\"pid\":%lu,\"activity\":{\"details\":\"Update " + "%d.%d.%d\",\"timestamps\":{\"start\":%llu},\"assets\":{\"large_image\":\"%s\",\"large_text\":\"TotK " + "Recomp %s\"}}}}", + next_nonce(), (unsigned long)plat_process_id(), v / 100, v / 10 % 10, v % 10, + (unsigned long long)start, image, rt_port_version); + if (!write_frame(p, OP_FRAME, json)) return 0; + uint32_t op = 0; + char answer[ANSWER_CAP]; + return read_frame(p, &op, answer, sizeof answer, 2000) >= 0; +} + +// ---- the presence thread + +static void discord_main(void *arg) { + (void)arg; + unsigned seen = 0; + char app_id[APP_ID_CAP], image[IMAGE_KEY_CAP]; + read_setting("TOTK_DISCORD_APP_ID", app_id, sizeof app_id, valid_app_id); + read_setting("TOTK_DISCORD_IMAGE", image, sizeof image, valid_image_key); + PlatIpc *ipc = NULL; + uint64_t retry_at = 0, send_at = 0; + int said_no_client = 0; + for (;;) { + unsigned v = cfg_version(); + if (v != seen) { // the settings changed (the menu writes them): pick the new ones up at once + seen = v; + read_setting("TOTK_DISCORD_APP_ID", app_id, sizeof app_id, valid_app_id); + read_setting("TOTK_DISCORD_IMAGE", image, sizeof image, valid_image_key); + if (ipc) plat_ipc_close(ipc), ipc = NULL; // the new app id needs a new handshake; the image is resent + said_no_client = 0; + } + if (!cfg_bool("TOTK_DISCORD_RPC")) { + if (ipc) plat_ipc_close(ipc), ipc = NULL; + plat_sleep_ms(500); + continue; + } + if (!ipc && plat_now_ms() >= retry_at) { + ipc = connect_client(app_id); + if (!ipc) { + retry_at = plat_now_ms() + 15000; + if (!said_no_client) + rt_log("discord: no client is running; trying again every 15 s while the setting is on"); + said_no_client = 1; + } else { + rt_log("discord: connected (app %s)", app_id); + send_at = 0; + said_no_client = 0; + } + } + if (ipc && plat_now_ms() >= send_at) { + if (send_activity(ipc, image)) { + send_at = plat_now_ms() + 60000; + } else { + rt_log("discord: the connection broke; reconnecting"); + plat_ipc_close(ipc); + ipc = NULL; + retry_at = plat_now_ms() + 15000; + } + } + plat_sleep_ms(500); + } +} + +void discord_init(void) { + if (!plat_thread_spawn(discord_main, NULL, "discord", 0)) rt_log("discord: cannot start the presence thread"); +} + +// ---- --probe-discord: the exchange above without the game and the setting; needs no game files + +int probe_discord(void) { + static int fails; +#define CHECK(c, what) do { if (!(c)) { fails++; fprintf(stderr, "FAIL discord: %s\n", what); } } while (0) + char app_id[APP_ID_CAP], image[IMAGE_KEY_CAP]; + read_setting("TOTK_DISCORD_APP_ID", app_id, sizeof app_id, valid_app_id); + read_setting("TOTK_DISCORD_IMAGE", image, sizeof image, valid_image_key); + PlatIpc *p = connect_client(app_id); + if (!p) { + fprintf(stderr, "discord: probe skipped: no client on discord-ipc-0..9\n"); + return 0; + } + fprintf(stderr, "discord: connected (app %s)\n", app_id); + CHECK(send_activity(p, image), "SET_ACTIVITY written and answered"); + fprintf(stderr, "discord: activity set; the status shows it for ten seconds, then the connection closes\n"); + plat_sleep_ms(10000); + plat_ipc_close(p); + fprintf(stderr, "discord: probe %s\n", fails ? "FAILED" : "passed"); + return fails != 0; +#undef CHECK +} diff --git a/runtime/host.h b/runtime/host.h index 5766ee4c..56f57b0c 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -309,6 +309,8 @@ void rt_boot(void); // boot.c 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 +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 int probe_vkdevice(void); // vk_device.c diff --git a/runtime/main.c b/runtime/main.c index e6ced76e..359543c3 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -5,6 +5,7 @@ // --probe-mods the mods folder scan, order and switches (mods.c); needs no game files // --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-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 @@ -443,7 +444,7 @@ 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-nvn | --probe-nvn-tex | --probe-window | --probe-shader | --probe-vkmem | " - "--probe-vkexec | --probe-astc | --probe-movie | --prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0); + "--probe-vkexec | --probe-astc | --probe-movie | --probe-discord | --prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0); return 2; } @@ -526,6 +527,7 @@ int main(int argc, char **argv) { log_open(!mode); 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 rt_boot(); return 0; } @@ -536,6 +538,7 @@ int main(int argc, char **argv) { if (!strcmp(mode, "--probe-dpi")) return probe_dpi(); // the Win32 DPI awareness of totk.manifest #endif if (!strcmp(mode, "--probe-mods")) return probe_mods(); + if (!strcmp(mode, "--probe-discord")) return probe_discord(); 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/platform/linux.c b/runtime/platform/linux.c index 7d502925..3a96b231 100644 --- a/runtime/platform/linux.c +++ b/runtime/platform/linux.c @@ -22,9 +22,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -1654,6 +1656,62 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) { return (long)k; } +// ---- local IPC (platform.h): Discord's Rich Presence Unix domain socket +struct PlatIpc { int fd; }; + +PlatIpc *plat_ipc_connect(const char *name) { + const char *dirs[] = {getenv("DISCORD_IPC_PATH"), getenv("XDG_RUNTIME_DIR"), getenv("TMPDIR"), "/tmp"}; + for (size_t d = 0; d < sizeof dirs / sizeof *dirs; d++) { + if (!dirs[d] || !*dirs[d]) continue; + char path[sizeof ((struct sockaddr_un *)0)->sun_path]; + if ((size_t)snprintf(path, sizeof path, "%s/%s", dirs[d], name) >= sizeof path) continue; + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) return NULL; + struct sockaddr_un sa = {0}; + sa.sun_family = AF_UNIX; + strcpy(sa.sun_path, path); + if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == 0) { + PlatIpc *p = malloc(sizeof *p); + if (!p) { + close(fd); + return NULL; + } + p->fd = fd; + return p; + } + close(fd); // nothing listens at this path: the next directory may have it + } + return NULL; +} + +int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms) { + struct pollfd pf = {.fd = p->fd, .events = POLLIN}; + int r = poll(&pf, 1, (int)ms); + if (r <= 0) return r < 0 && errno != EINTR ? -1 : 0; + ssize_t got = recv(p->fd, buf, n, 0); + return got > 0 ? (int)got : -1; // 0 bytes: the peer closed the socket +} + +int plat_ipc_write(PlatIpc *p, const void *buf, size_t n) { + const uint8_t *at = buf; + while (n) { + ssize_t put = send(p->fd, at, n, MSG_NOSIGNAL); // a closed peer is an error, not a SIG_PIPE + if (put <= 0) { + if (put < 0 && errno == EINTR) continue; + return 0; + } + at += put, n -= put; + } + return 1; +} + +void plat_ipc_close(PlatIpc *p) { + if (!p) return; + close(p->fd); + free(p); +} + + // ---- restart // TOTK_RESTART_WAIT names the process that called plat_restart, as its id and start time (field 22 of /proc//stat, // clock ticks after boot): a process that has only reused the id is not waited for. Waiting keeps the new process off diff --git a/runtime/platform/platform.h b/runtime/platform/platform.h index b8e0c74b..222f66dd 100644 --- a/runtime/platform/platform.h +++ b/runtime/platform/platform.h @@ -412,6 +412,17 @@ void plat_child_stop(PlatChild *c); // kills the child and int plat_child_write(PlatChild *c, const void *data, size_t n); // 1 when all n bytes were written long plat_child_read(PlatChild *c, void *buf, size_t cap); // bytes read (at least 1); 0 or negative: pipe broke +// ---- local IPC: a stream connection to another program of this machine, one listen location per name (Discord's +// Rich Presence, discord_rpc.c). On Windows the named pipe \\.\pipe\; on Linux the Unix domain socket +// / with the first of $DISCORD_IPC_PATH, $XDG_RUNTIME_DIR, $TMPDIR and /tmp that has one. +typedef struct PlatIpc PlatIpc; +PlatIpc *plat_ipc_connect(const char *name); // NULL when nothing listens under that name +// Up to n bytes, waiting at most ms for the first of them: bytes read, 0 none in time, -1 the connection broke. +// The rest of what the peer wrote may still be in its buffer: a caller that needs a whole frame loops. +int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms); +int plat_ipc_write(PlatIpc *p, const void *buf, size_t n); // 1 when all n bytes were written, 0 the connection broke +void plat_ipc_close(PlatIpc *p); + // ---- restart: this program again, in a new process that starts once this one is gone // Starts this executable again with the same command line, environment and working folder, and no handle of this // process. 1 when it started; the caller then exits. diff --git a/runtime/platform/win32.c b/runtime/platform/win32.c index 6d83b6a3..6e08c651 100644 --- a/runtime/platform/win32.c +++ b/runtime/platform/win32.c @@ -1527,6 +1527,56 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) { return (long)got; } +// ---- local IPC (platform.h): Discord's Rich Presence named pipe +struct PlatIpc { HANDLE h; }; + +PlatIpc *plat_ipc_connect(const char *name) { + wchar_t wname[128], path[152]; + if (!widen(name, wname, 128)) return NULL; + swprintf(path, 152, L"\\\\.\\pipe\\%ls", wname); + HANDLE h = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (h == INVALID_HANDLE_VALUE) return NULL; // no listener, or the pipe is busy: the caller retries later + PlatIpc *p = malloc(sizeof *p); + if (!p) { + CloseHandle(h); + return NULL; + } + p->h = h; + return p; +} + +int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms) { + uint64_t deadline = plat_now_ms() + ms; + for (;;) { + DWORD have = 0; + if (!PeekNamedPipe(p->h, NULL, 0, NULL, &have, NULL)) return -1; // the writer closed the pipe + if (have) { + DWORD got = 0; + if (!ReadFile(p->h, buf, have < n ? have : (DWORD)n, &got, NULL) || !got) return -1; + return (int)got; + } + if (plat_now_ms() >= deadline) return 0; + plat_sleep_ms(5); + } +} + +int plat_ipc_write(PlatIpc *p, const void *buf, size_t n) { + const uint8_t *at = buf; + while (n) { + DWORD put = 0; + if (!WriteFile(p->h, at, n > (1u << 30) ? 1u << 30 : (DWORD)n, &put, NULL) || !put) return 0; + at += put, n -= put; + } + return 1; +} + +void plat_ipc_close(PlatIpc *p) { + if (!p) return; + CloseHandle(p->h); + free(p); +} + + // ---- restart // TOTK_RESTART_WAIT names the process that called plat_restart, as its id and creation time: a process that has only // reused the id is not waited for. Waiting keeps the new process off the old one's files (the log it moves at start, diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 151354e0..6fc314fa 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -849,6 +849,7 @@ static void tab_menu(float scale) { static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_ZH_HANS}; opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, sizeof langs / sizeof *langs, UI_MENU_MENU_LANG_DESC); + opt_toggle("TOTK_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 5c14ed53..ea3ea74d 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -320,6 +320,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_AMIIBO_STATUS] = "Status: %s", [UI_MENU_MENU_LANG] = "Menu language", [UI_MENU_MENU_LANG_DESC] = "Language of this menu and the overlay.", [UI_MENU_MENU_LANG_AUTO] = "Automatic (from Windows)", + [UI_MENU_DISCORD_RPC] = "Discord Rich Presence", + [UI_MENU_DISCORD_RPC_DESC] = "Shows \"Playing TotK Recomp\" with the play time in your Discord status while the " + "game runs. discord_app_id and discord_image in totk.ini choose the application.", [UI_MENU_ADV_WARNING] = "These settings are for testing and troubleshooting. Change them only when you know why.", [UI_MENU_GROUP_SCHED] = "Scheduling", [UI_MENU_GROUP_SHADERS] = "Shaders and pipelines", @@ -746,6 +749,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_AMIIBO_STATUS] = "Состояние: %s", [UI_MENU_MENU_LANG] = "Язык меню", [UI_MENU_MENU_LANG_DESC] = "Язык этого меню и индикатора.", [UI_MENU_MENU_LANG_AUTO] = "Автоматически (из Windows)", + [UI_MENU_DISCORD_RPC] = "Discord Rich Presence", + [UI_MENU_DISCORD_RPC_DESC] = "Пока игра запущена, показывает «Играю в TotK Recomp» со временем игры в статусе " + "Discord. Приложение выбирают discord_app_id и discord_image в totk.ini.", [UI_MENU_ADV_WARNING] = "Эти настройки нужны для тестов и поиска неполадок. Меняйте их, только если знаете зачем.", [UI_MENU_GROUP_SCHED] = "Планирование", [UI_MENU_GROUP_SHADERS] = "Шейдеры и конвейеры", @@ -1091,6 +1097,10 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_AMIIBO_STATUS] = "Estado: %s", [UI_MENU_MENU_LANG] = "Idioma do menu", [UI_MENU_MENU_LANG_DESC] = "Idioma deste menu e do indicador.", [UI_MENU_MENU_LANG_AUTO] = "Automático (do Windows)", + [UI_MENU_DISCORD_RPC] = "Discord Rich Presence", + [UI_MENU_DISCORD_RPC_DESC] = "Mostra \"Jogando TotK Recomp\" com o tempo de jogo no seu status do Discord " + "enquanto o jogo roda. discord_app_id e discord_image no totk.ini escolhem a " + "aplicação.", [UI_MENU_ADV_WARNING] = "Estas configurações são para testes e solução de problemas. Altere-as só quando souber " "por quê.", @@ -1644,6 +1654,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_MENU_LANG] = "菜单语言", [UI_MENU_MENU_LANG_DESC] = "本菜单和性能浮层的语言。", [UI_MENU_MENU_LANG_AUTO] = "自动(跟随 Windows)", + [UI_MENU_DISCORD_RPC] = "Discord Rich Presence", + [UI_MENU_DISCORD_RPC_DESC] = "游戏运行时在 Discord 状态中显示“正在玩 TotK Recomp”及游戏时长。totk.ini 中的 " + "discord_app_id 和 discord_image 选择应用。", [UI_MENU_ADV_WARNING] = "这些设置用于测试和排查问题,请在了解原因后再修改。", [UI_MENU_GROUP_SCHED] = "调度", [UI_MENU_GROUP_SHADERS] = "着色器和管线", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 92856857..bba72f15 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -150,6 +150,7 @@ typedef enum { // Menu tab UI_MENU_MENU_LANG, UI_MENU_MENU_LANG_DESC, UI_MENU_MENU_LANG_AUTO, + UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC, // Language names, each in its own language and the same in every row (game language and menu language lists) UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_DE, UI_MENU_LANGNAME_IT, diff --git a/totk.ini.example b/totk.ini.example index 227a923f..aaebe978 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -211,6 +211,18 @@ # it is none of them. # menu_lang = en +[discord] +# Rich Presence: "Playing TotK Recomp" with the play time in your Discord status while the game runs, through the +# local IPC of a running Discord client. 1 = on; the Menu tab of the settings menu (F1) switches it too, and the +# change reaches the presence thread at once. +# discord_rpc = 0 +# The application whose name and artwork the status shows. The default is the app this feature was developed +# against, registered as "TotK Recomp" with the port's green ring icon as its art. Register your own at +# discord.com/developers (name and art are yours to choose) and put its id here. +# discord_app_id = 1566609987453722727 +# The key of the application's uploaded art asset shown as the status's large image. +# discord_image = totk_512x512 + [audio] # none mixes without opening an audio device. # audio = default