diff --git a/runtime/audio_mixer.c b/runtime/audio_mixer.c index 1e2f9fb5..ce1757e2 100644 --- a/runtime/audio_mixer.c +++ b/runtime/audio_mixer.c @@ -55,6 +55,22 @@ typedef struct Mixer { } Mixer; static _Atomic float device_volume = 1.0f; + +// TOTK_VOLUME: the player's volume in percent (0..100, default 100) on top of the game's own; a live setting (the +// menu), parsed again when cfg_version changes. Render thread only. +static float host_volume(void) { + static float v = 1.0f; + static unsigned seen = ~0u; + unsigned ver = cfg_version(); + if (ver == seen) return v; + seen = ver; + const char *e = cfg_get("TOTK_VOLUME"); + char *end; + double pct = e ? strtod(e, &end) : 100; + if (!e || end == e || *end || pct != pct) pct = 100; + v = (float)((pct < 0 ? 0 : pct > 100 ? 100 : pct) / 100); + return v; +} static unsigned audio_revision(const AudioRenderer *r) { unsigned byte = r->revision >> 24; return byte >= '0' ? byte - '0' : 0; } static void report_once(Mixer *m, unsigned bit, const char *msg, int value) { if (m->reported & (1u << bit)) return; @@ -741,7 +757,7 @@ void audio_mixer_render(AudioRenderer *r, double seconds) { float *lr=m->output_scratch; memset(lr, 0, sizeof(float) * 2 * (size_t)frames); if (sink && sink->input_count >= 1 && sink->input_count <= 6) { - const float gain = atomic_load(&device_volume) * (r->mixes[0].in_use ? r->mixes[0].volume : 1.0f); + const float gain = host_volume() * atomic_load(&device_volume) * (r->mixes[0].in_use ? r->mixes[0].volume : 1.0f); const float *ch[6] = {0}; for (uint32_t c = 0; c < sink->input_count; c++) if (sink->inputs[c] >= 0 && sink->inputs[c] < m->nbuf) ch[c] = mixbuf(m, sink->inputs[c]); for (int k = 0; k < frames; k++) { diff --git a/runtime/cfg.c b/runtime/cfg.c index 9a679fc0..834c202d 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -2,6 +2,10 @@ // Format: "key = value" lines, '#' or ';' at the start of a line begins a comment, [sections] only group. A key is a // variable name without "TOTK_" (an optional TOTK_ prefix is accepted), case-insensitive. A value is the rest of the // line, trimmed, optionally in double quotes; an empty value counts as unset. The environment wins over the file. +// +// Live settings: cfg_set changes a value in memory (readers see the new pointer; the old string is kept, so a pointer +// cfg_get handed out stays valid) and cfg_save writes only the changed keys back, keeping the rest of the file. +// Readers take no lock: an entry is complete before n_entries counts it, and value pointers are swapped atomically. #include #include #include @@ -15,20 +19,23 @@ #define PREFIX_LEN 5 #define CFG_MAX_KEYS 512 -typedef struct { char *key, *value; } CfgEntry; // key upper-case, without the prefix +typedef struct { char *key, *value; int dirty; } CfgEntry; // key upper-case, without the prefix static CfgEntry entries[CFG_MAX_KEYS]; static int n_entries; +static unsigned version; +static PlatMutex set_lock = PLAT_MUTEX_INIT; // cfg_set, cfg_save // Every name the runtime reads (and the patch sets in generated/), without the prefix. A file key outside this list is // logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line. static const char *const known[] = { "APP_POOL", "ASSUME_FOCUS", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "BACKGROUND_WINDOW", "BIND_STATS", "CLOTH_REALTIME", "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", "FPS60", "FREE_CORES", "GPL", - "GPL_DRAW_BUILD", + "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FPS60", "FPS_COUNTER", "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", "MINIMAL_LAYOUT", "MOTION", "MOUSE_SENS", "MOVIE_HOST", + "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MENU_LANG", "MENU_TEST", "MENU_TEST_DIR", + "MINIMAL_LAYOUT", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "OPERATION_MODE", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_PREBUILD", "PIPE_SYNC", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_RENDER", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", @@ -36,7 +43,17 @@ static const char *const known[] = { "SHADER_CACHE", "SHARED_FONTS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPLIT_DRAWS", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TIMER_1MS", "TRACE", "VK_NO_FLOAT64", "VK_PRESENT", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", - "VS_OUTS", "XLATE", "XLATE_ID", "XLATE_PROCS", + "VOLUME", "VS_OUTS", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", +}; + +// The totk.ini section a key cfg_set may write goes to when the file lacks it (totk.ini.example's sections). +static const struct { const char *key, *section; } sections[] = { + {"FPS60", "frame rate"}, + {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"FPS_COUNTER", "display"}, + {"MENU_LANG", "language"}, + {"VOLUME", "audio"}, + {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, + {"MOUSE_SENS", "input"}, }; static int is_known(const char *key) { @@ -57,9 +74,14 @@ static char *trim(char *s) { return s; } -static void add(char *key, char *value, int line) { +// The upper-case key without the prefix, in place. +static char *norm_key(char *key) { for (char *p = key; *p; p++) *p = (char)toupper((unsigned char)*p); - if (!strncmp(key, PREFIX, PREFIX_LEN)) key += PREFIX_LEN; + return strncmp(key, PREFIX, PREFIX_LEN) ? key : key + PREFIX_LEN; +} + +static void add(char *key, char *value, int line) { + key = norm_key(key); size_t vl = strlen(value); if (vl >= 2 && value[0] == '"' && value[vl - 1] == '"') value[vl - 1] = 0, value++; if (!*key) return; @@ -72,7 +94,7 @@ static void add(char *key, char *value, int line) { return; } if (n_entries == CFG_MAX_KEYS) return; - entries[n_entries++] = (CfgEntry){_strdup(key), _strdup(value)}; + entries[n_entries++] = (CfgEntry){_strdup(key), _strdup(value), 0}; } int cfg_load(const char *path) { @@ -104,23 +126,260 @@ int cfg_load(const char *path) { const char *cfg_get(const char *name) { const char *e = getenv(name); if (e || strncmp(name, PREFIX, PREFIX_LEN)) return e; - for (int i = 0; i < n_entries; i++) - if (!_stricmp(entries[i].key, name + PREFIX_LEN)) return entries[i].value; + int n = __atomic_load_n(&n_entries, __ATOMIC_ACQUIRE); + for (int i = 0; i < n; i++) + if (!_stricmp(entries[i].key, name + PREFIX_LEN)) return __atomic_load_n(&entries[i].value, __ATOMIC_ACQUIRE); return NULL; } -void cfg_init(void) { +unsigned cfg_version(void) { return __atomic_load_n(&version, __ATOMIC_ACQUIRE); } + +int cfg_from_env(const char *name) { return getenv(name) != NULL; } + +void cfg_set(const char *name, const char *value) { + if (strncmp(name, PREFIX, PREFIX_LEN) || !value) return; + char key[64]; + snprintf(key, sizeof key, "%s", name + PREFIX_LEN); + for (char *p = key; *p; p++) *p = (char)toupper((unsigned char)*p); + plat_mutex_lock(&set_lock); + int i = 0, n = n_entries; + while (i < n && strcmp(entries[i].key, key)) i++; + if (i < n) { + if (strcmp(entries[i].value, value)) { + __atomic_store_n(&entries[i].value, _strdup(value), __ATOMIC_RELEASE); // the old string stays for readers + entries[i].dirty = 1; + } + } else if (n < CFG_MAX_KEYS) { + entries[n] = (CfgEntry){_strdup(key), _strdup(value), 1}; + __atomic_store_n(&n_entries, n + 1, __ATOMIC_RELEASE); + } + __atomic_add_fetch(&version, 1, __ATOMIC_RELEASE); + plat_mutex_unlock(&set_lock); +} + +// ---- cfg_save: the file as lines, each with its line ending +typedef struct { const char *s; size_t n; } Line; // n includes the '\n' (and '\r') when present + +static int line_count(const char *p, size_t size) { + int n = 0; + for (size_t i = 0; i < size; i++) n += p[i] == '\n'; + return n + 1; +} + +// The line's text without its ending, BOM and surrounding blanks, into out. +static void line_text(const Line *l, int first, char *out, size_t cap) { + size_t n = l->n; + const char *s = l->s; + if (first && n >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) s += 3, n -= 3; + while (n && (s[n - 1] == '\n' || s[n - 1] == '\r')) n--; + if (n >= cap) n = cap - 1; + memcpy(out, s, n); + out[n] = 0; + char *t = trim(out); + memmove(out, t, strlen(t) + 1); +} + +// The key of a "key = value" line (comment = 0) or of a commented "# key = value" line (comment = 1), normalised, +// into key; 0 when the line is not one. +static int line_key(const char *text, int comment, char *key, size_t cap) { + if (comment) { + if (*text != '#' && *text != ';') return 0; + text++; + while (*text == ' ' || *text == '\t') text++; + } + if (!*text || *text == '#' || *text == ';' || *text == '[') return 0; + const char *eq = strchr(text, '='); + if (!eq) return 0; + size_t n = (size_t)(eq - text); + while (n && (text[n - 1] == ' ' || text[n - 1] == '\t')) n--; + if (!n || n >= cap) return 0; + for (size_t i = 0; i < n; i++) + if (!isalnum((unsigned char)text[i]) && text[i] != '_') return 0; + char tmp[128]; + memcpy(tmp, text, n); + tmp[n] = 0; + snprintf(key, cap, "%s", norm_key(tmp)); + return 1; +} + +// The section name of a "[name]" line, lower-case, into out; 0 when the line is not one. +static int line_section(const char *text, char *out, size_t cap) { + if (*text != '[') return 0; + const char *e = strchr(text, ']'); + if (!e) return 0; + char tmp[128]; + size_t n = (size_t)(e - text - 1); + if (n >= sizeof tmp) n = sizeof tmp - 1; + memcpy(tmp, text + 1, n); + tmp[n] = 0; + snprintf(out, cap, "%s", trim(tmp)); + for (char *p = out; *p; p++) *p = (char)tolower((unsigned char)*p); + return 1; +} + +typedef struct { char *buf; size_t n, cap; } Out; +static void put(Out *o, const char *s, size_t n) { + if (o->n + n + 1 > o->cap) { + o->cap = (o->n + n + 1) * 2; + o->buf = realloc(o->buf, o->cap); + if (!o->buf) rt_fatal("cfg: out of memory writing totk.ini"); + } + memcpy(o->buf + o->n, s, n); + o->n += n; +} +static void puts_(Out *o, const char *s) { put(o, s, strlen(s)); } + +static const char *section_of(const char *key) { + for (size_t i = 0; i < sizeof sections / sizeof *sections; i++) + if (!strcmp(sections[i].key, key)) return sections[i].section; + return NULL; +} + +// "key = value" + eol for entry e (key lower-case) +static void put_entry(Out *o, const CfgEntry *e, const char *eol) { + char k[64]; + snprintf(k, sizeof k, "%s", e->key); + for (char *p = k; *p; p++) *p = (char)tolower((unsigned char)*p); + puts_(o, k); + puts_(o, " = "); + puts_(o, e->value); + puts_(o, eol); +} + +int cfg_save_to(const char *path) { + plat_mutex_lock(&set_lock); + int n = n_entries, any = 0; + for (int i = 0; i < n; i++) any |= entries[i].dirty; + if (!any) { + plat_mutex_unlock(&set_lock); + return 1; + } + uint64_t size = 0; + uint8_t *data = plat_file_read(path, &size); + const char *text = data ? (const char *)data : ""; + int nl = data ? line_count(text, size) : 0; + Line *lines = calloc((size_t)nl + 1, sizeof *lines); + // after[i]: entries to write after line i (-1 = none); replace[i]: the entry whose value line i now carries + int *replace = malloc(sizeof(int) * ((size_t)nl + 1)), *after_key = malloc(sizeof(int) * (size_t)(n + 1)); + if (!lines || !replace || !after_key) rt_fatal("cfg: out of memory writing totk.ini"); + for (int i = 0, at = 0; i < nl; i++) { + size_t start = (size_t)at; + while ((uint64_t)at < size && text[at] != '\n') at++; + if ((uint64_t)at < size) at++; + lines[i] = (Line){text + start, (size_t)at - start}; + replace[i] = -1; + } + if (nl && !lines[nl - 1].n) nl--; // the text ended with a newline: no last empty line + const char *eol = data && strstr(text, "\r\n") ? "\r\n" : "\n"; + char t[1024], k[128], sec[128]; + for (int e = 0; e < n; e++) { + after_key[e] = -2; // -2 clean, -1 append in a new section at the end, >= 0 insert after that line + if (!entries[e].dirty) continue; + int last = -1; + for (int i = 0; i < nl; i++) { + line_text(&lines[i], i == 0, t, sizeof t); + if (line_key(t, 0, k, sizeof k) && !strcmp(k, entries[e].key)) last = i; + } + if (last >= 0) { + replace[last] = e; + continue; + } + const char *want = section_of(entries[e].key); + int in = 0, example = -1, tail = -1; + for (int i = 0; i < nl && want; i++) { + line_text(&lines[i], i == 0, t, sizeof t); + if (line_section(t, sec, sizeof sec)) { + in = !strcmp(sec, want); + if (in) tail = i; + continue; + } + if (!in) continue; + if (*t) tail = i; + if (line_key(t, 1, k, sizeof k) && !strcmp(k, entries[e].key)) example = i; + } + after_key[e] = example >= 0 ? example : tail; + } + Out o = {0}; + for (int i = 0; i < nl; i++) { + if (replace[i] >= 0) { + // keep the line's indentation and key spelling, put the new value after " = " + const char *s = lines[i].s; + size_t len = lines[i].n; + if (i == 0 && len >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) put(&o, s, 3), s += 3, len -= 3; + const char *eq = memchr(s, '=', len); + size_t kn = (size_t)(eq - s); + while (kn && (s[kn - 1] == ' ' || s[kn - 1] == '\t')) kn--; + put(&o, s, kn); + puts_(&o, " = "); + puts_(&o, entries[replace[i]].value); + int had_eol = len && s[len - 1] == '\n'; + if (had_eol) puts_(&o, eol); + } else { + put(&o, lines[i].s, lines[i].n); + } + for (int e = 0; e < n; e++) + if (after_key[e] == i) { + if (!lines[i].n || lines[i].s[lines[i].n - 1] != '\n') puts_(&o, eol); + put_entry(&o, &entries[e], eol); + } + } + // keys whose section the file lacks: one new section each, at the end + for (int e = 0; e < n; e++) { + if (after_key[e] != -1) continue; + const char *want = section_of(entries[e].key); + if (o.n && o.buf[o.n - 1] != '\n') puts_(&o, eol); + if (want) { + if (o.n) puts_(&o, eol); + puts_(&o, "["); + puts_(&o, want); + puts_(&o, "]"); + puts_(&o, eol); + } + put_entry(&o, &entries[e], eol); + // the following keys of the same new section go right after this one + for (int f = e + 1; f < n && want; f++) + if (after_key[f] == -1 && section_of(entries[f].key) && !strcmp(section_of(entries[f].key), want)) { + put_entry(&o, &entries[f], eol); + after_key[f] = -3; + } + } + int ok = plat_file_write_atomic(path, o.buf ? o.buf : "", o.n); + if (ok) + for (int e = 0; e < n; e++) entries[e].dirty = 0; + else + rt_log("cfg: cannot write %s", path); + free(o.buf); + free(after_key); + free(replace); + free(lines); + free(data); + plat_mutex_unlock(&set_lock); + return ok; +} + +static char ini_path[1024]; + +static int find_ini(void) { + if (ini_path[0]) return 1; char path[1024]; - if (!plat_exe_path(path, sizeof path)) return; + if (!plat_exe_path(path, sizeof path)) return 0; char *cut = strrchr(path, '\\'); if (!cut) cut = strrchr(path, '/'); - if (!cut || cut + 10 >= path + sizeof path) return; + if (!cut || cut + 10 >= path + sizeof path) return 0; strcpy(cut + 1, "totk.ini"); - if (!cfg_load(path)) { - rt_log("cfg: no settings file at %s", path); + snprintf(ini_path, sizeof ini_path, "%s", path); + return 1; +} + +int cfg_save(void) { return find_ini() && cfg_save_to(ini_path); } + +void cfg_init(void) { + if (!find_ini()) return; + if (!cfg_load(ini_path)) { + rt_log("cfg: no settings file at %s", ini_path); return; } - rt_log("cfg: read %s: %d keys", path, n_entries); + rt_log("cfg: read %s: %d keys", ini_path, n_entries); for (int i = 0; i < n_entries; i++) { char var[128]; snprintf(var, sizeof var, PREFIX "%s", entries[i].key); diff --git a/runtime/cfg.h b/runtime/cfg.h index f10e5bee..d9b69654 100644 --- a/runtime/cfg.h +++ b/runtime/cfg.h @@ -2,8 +2,8 @@ #pragma once // getenv for a setting: the environment variable when set, else the totk.ini key (the name without "TOTK_", any -// case), else NULL. Same string semantics as getenv; the pointer stays valid for the process. A name without the -// TOTK_ prefix goes to getenv unchanged. Safe from any thread once cfg_init has returned. +// case), else NULL. Same string semantics as getenv; the pointer stays valid for the process (a value cfg_set replaces +// is kept). A name without the TOTK_ prefix goes to getenv unchanged. Safe from any thread once cfg_init has returned. const char *cfg_get(const char *name); // Reads totk.ini once, first thing in main. Logs the file, its key count, unknown keys and environment overrides. @@ -13,3 +13,17 @@ void cfg_init(void); // Not thread-safe: nothing else may call cfg_get meanwhile. int cfg_load(const char *path); +// Live settings (the in-game menu). cfg_set stores value as the totk.ini value of name (TOTK_ prefixed), marks it for +// cfg_save and bumps cfg_version. cfg_get returns it unless the environment sets name. Any thread. +void cfg_set(const char *name, const char *value); +// Bumped by every cfg_set. A consumer that keeps a parsed value compares this with the number it last saw (one atomic +// load) and parses again when it changed. +unsigned cfg_version(void); +// 1 when the environment sets name: cfg_set cannot change what cfg_get returns (the menu greys the setting out). +int cfg_from_env(const char *name); +// Writes the keys cfg_set changed since the last save into totk.ini next to totk.exe (cfg_save_to: the file at path). +// Only those lines change: the last line of a changed key gets the new value, a missing key goes under its section +// (after the commented example line of the key when the section has one; the section is added at the end of the file +// when missing), comments and every other line stay byte for byte. 1 on success or with nothing to write. +int cfg_save(void); +int cfg_save_to(const char *path); diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index 26c0f83e..d2ff33a7 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -55,6 +55,81 @@ int probe_cfg(void) { plat_file_delete(path); CHECK(cfg_load(path) == 0, "missing file is not an error"); CHECK(cfg_get("TOTK_FPS60") == NULL, "missing file leaves no keys"); + + // cfg_set / cfg_save: only changed lines move, comments stay, a missing key goes under its section + static const char before[] = + "\xEF\xBB\xBF# my settings\r\n" + "[frame rate]\r\n" + " FPS60 = 1\r\n" + "; keep this\r\n" + "\r\n" + "[input]\r\n" + "# Gamepad motion controls (0 = off) and vibration (0 = off).\r\n" + "# motion = 1\r\n" + "# rumble = 1\r\n" + "rumble_curve = 0.6\r\n" + "\r\n" + "[files]\r\n" + "romfs_mods = C:\\mods"; + static const char after[] = + "\xEF\xBB\xBF# my settings\r\n" + "[frame rate]\r\n" + " FPS60 = 0\r\n" + "; keep this\r\n" + "\r\n" + "[input]\r\n" + "# Gamepad motion controls (0 = off) and vibration (0 = off).\r\n" + "# motion = 1\r\n" + "motion = 0\r\n" + "# rumble = 1\r\n" + "rumble_curve = 0.6\r\n" + "rumble_strength = 80\r\n" + "\r\n" + "[files]\r\n" + "romfs_mods = C:\\mods\r\n" + "\r\n" + "[audio]\r\n" + "volume = 40\r\n"; + _putenv_s("TOTK_MOTION", ""); + _putenv_s("TOTK_VOLUME", ""); + _putenv_s("TOTK_RUMBLE_STRENGTH", ""); + CHECK(plat_file_write(path, before, sizeof before - 1), "write the save ini"); + CHECK(cfg_load(path) == 1, "load the save ini"); + unsigned v0 = cfg_version(); + cfg_set("TOTK_FPS60", "0"); + cfg_set("TOTK_MOTION", "0"); + cfg_set("TOTK_RUMBLE_STRENGTH", "80"); + cfg_set("TOTK_VOLUME", "40"); + CHECK(cfg_version() == v0 + 4, "cfg_set bumps the version"); + CHECK(EQ(cfg_get("TOTK_FPS60"), "0") && EQ(cfg_get("TOTK_VOLUME"), "40"), "cfg_set values are read back at once"); + CHECK(cfg_save_to(path) == 1, "cfg_save_to writes"); + uint64_t got_n = 0; + uint8_t *got = plat_file_read(path, &got_n); + CHECK(got && got_n == sizeof after - 1 && !memcmp(got, after, got_n), + "saved file: changed line replaced, comments kept, missing keys under their sections"); + if (got && (got_n != sizeof after - 1 || memcmp(got, after, got_n))) fprintf(stderr, "---- saved:\n%s\n----\n", got); + free(got); + CHECK(cfg_save_to(path) == 1, "a save with nothing changed"); + got = plat_file_read(path, &got_n); + CHECK(got && got_n == sizeof after - 1 && !memcmp(got, after, got_n), "a save with nothing changed keeps the file"); + free(got); + CHECK(cfg_load(path) == 1 && EQ(cfg_get("TOTK_FPS60"), "0") && EQ(cfg_get("TOTK_MOTION"), "0") && + EQ(cfg_get("TOTK_RUMBLE_STRENGTH"), "80") && EQ(cfg_get("TOTK_VOLUME"), "40") && + EQ(cfg_get("TOTK_ROMFS_MODS"), "C:\\mods"), "the saved file reads back"); + const char *held = cfg_get("TOTK_VOLUME"); + _putenv_s("TOTK_VOLUME", "70"); + cfg_set("TOTK_VOLUME", "90"); + CHECK(cfg_from_env("TOTK_VOLUME") && EQ(cfg_get("TOTK_VOLUME"), "70"), "environment wins over cfg_set"); + CHECK(EQ(held, "40"), "a pointer cfg_get handed out stays valid after cfg_set"); + _putenv_s("TOTK_VOLUME", ""); + CHECK(!cfg_from_env("TOTK_VOLUME") && EQ(cfg_get("TOTK_VOLUME"), "90"), "cfg_set value returns without the variable"); + plat_file_delete(path); + CHECK(cfg_save_to(path) == 1, "cfg_save_to creates a missing file"); + got = plat_file_read(path, &got_n); + CHECK(got && !strcmp((const char *)got, "[audio]\nvolume = 90\n"), "new file: the section and the key"); + free(got); + plat_file_delete(path); + cfg_load(path); CHECK(rumble_motor(0, 0.6f, 1.3f) == 0 && rumble_motor(0.5f, 0.6f, 0) == 0, "rumble: zero amplitude or strength is silent"); CHECK(rumble_motor(1, 0.6f, 3) == 65535 && rumble_motor(5, 1, 1) == 65535, "rumble: saturates at 65535"); CHECK(rumble_motor(0.25f, 1, 1) > 16000 && rumble_motor(0.25f, 1, 1) < 16800, "rumble: curve 1, strength 100% is linear"); diff --git a/runtime/frame_rate.c b/runtime/frame_rate.c index 8142141b..c9dde1be 100644 --- a/runtime/frame_rate.c +++ b/runtime/frame_rate.c @@ -72,6 +72,29 @@ void frame_step_init(void) { int frame_step_realtime(void) { return step_word != NULL; } +// The frame limit (menu: 30 or 60): TOTK_FPS60 switches the set fps60 while the game runs; the controller reads its +// minimum interval from the patched sites each frame. With the real-time step the pacer holds frames to the cap. +static int fps60_set = -2; +static unsigned fps60_seen; + +static void frame_limit_live(void) { + unsigned v = cfg_version(); + if (v == fps60_seen) return; + fps60_seen = v; + if (fps60_set == -2) fps60_set = rt_patch_set("fps60"); + if (fps60_set < 0) return; + const char *e = cfg_get("TOTK_FPS60"); + int on = e && *e ? strcmp(e, "0") != 0 : 1; + if (on == rt_patch_enabled(fps60_set)) return; + rt_patch_switch(fps60_set, on); + rt_log("frame rate: limit %d fps (TOTK_FPS60=%d)", on ? 60 : 30, on); +} + +int frame_step_cap_ticks(void) { + if (fps60_set == -2) fps60_set = rt_patch_set("fps60"); + return fps60_set < 0 || rt_patch_enabled(fps60_set) ? 1 : 2; +} + // ---- TOTK_TRACE=perf speed lines static uint64_t win_t0, win_frames, win_hist[4]; // win_hist: frames by present interval 1, 2, 3+ ([0] unused) static double win_game; @@ -142,6 +165,7 @@ static void speed_report(uint64_t now, double step, int interval) { } void frame_step_present(uint64_t display_ns, int interval) { + frame_limit_live(); double step = 0; if (step_word && last_ns) { double dt = (double)(display_ns - last_ns) * 1e-9; diff --git a/runtime/host.h b/runtime/host.h index bd7cff84..92f38f42 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -191,9 +191,13 @@ void rt_patches_init(void); // after ldr_load: sw int rt_patch_set(const char *name); // index of a set of generated patches.h, -1 if absent int rt_patch_enabled(int set); // the set is on (0 for -1) void rt_patch_disable(int set); // before the guest starts: a set needs another that is off +void rt_patch_switch(int set, int on); // at run time (live settings): each site takes the new code + // the next time it runs void *rt_patch_page(void); // the page the patched code reads (NULL without the table) void frame_step_init(void); // after rt_patches_init: the real-time step's first value int frame_step_realtime(void); // the real-time step is on: presents ignore the interval +int frame_step_cap_ticks(void); // with the real-time step: 60 Hz ticks per frame at most + // (1 = 60 fps, 2 = 30 fps; TOTK_FPS60, live) void frame_step_present(uint64_t display_ns, int interval); // nvnQueuePresentTexture: the frame's display time and // present interval (60 Hz ticks) // ---- boot (boot.c T6, main.c T1) diff --git a/runtime/input.h b/runtime/input.h index da0e1136..b55012da 100644 --- a/runtime/input.h +++ b/runtime/input.h @@ -30,9 +30,11 @@ uint16_t rumble_motor(float a, float curve, float strength); // TOTK_RUMBLE_TRIGGERS=1: input_rumble also drives the impulse triggers (Xbox) with the high motor's value. int input_rumble_triggers_enabled(void); -// Motion (TOTK_MOTION=0 turns it off). input_motion_start starts the sensor thread once: every 4 ms it reads the +// Motion (TOTK_MOTION=0 turns it off, live). input_motion_start starts the sensor thread once: every 4 ms it reads the // gamepad's gyro and accelerometer (when it has them) and feeds motion_global(). Callable from any thread. void input_motion_start(void); +// TOTK_MOTION is not "0" (a live setting: read again when cfg_version changes). Off: the sensor reads at rest. +int input_motion_enabled(void); // SDL sensor values (accelerometer m/s^2, gyro rad/s, SDL gamepad axes) to the Switch controller frame motion_feed // takes (acceleration in G as gravity reads, rotation rad/s). The mapping is documented in input_win.c. void input_motion_axes(const float sdl_acc[3], const float sdl_gyro[3], double acc_g[3], double gyro[3]); diff --git a/runtime/input_win.c b/runtime/input_win.c index 71264e42..407ed996 100644 --- a/runtime/input_win.c +++ b/runtime/input_win.c @@ -192,10 +192,13 @@ static volatile LONG cur_active; // WM_ACTIVATEAPP: the window's appli static volatile LONG cur_suspend; // F11 or a modal size or move loop under way static SRWLOCK cur_lock = SRWLOCK_INIT; // serialises cursor_update (window thread, input_block callers) static volatile LONG g_block; // text entry state, see input_block -static float mouse_sens = -1; // TOTK_MOUSE_SENS, 0 = mouse camera off, read once +static float mouse_sens = -1; // TOTK_MOUSE_SENS, 0 = mouse camera off; live (cfg_version) +static unsigned mouse_sens_seen; static float mouse_sens_get(void) { - if (mouse_sens >= 0) return mouse_sens; + unsigned ver = cfg_version(); + if (mouse_sens >= 0 && ver == mouse_sens_seen) return mouse_sens; + mouse_sens_seen = ver; const char *e = cfg_get("TOTK_MOUSE_SENS"); char *end; double v = e ? strtod(e, &end) : 1; @@ -435,7 +438,8 @@ int input_rumble_triggers_enabled(void) { int input_rumble(uint16_t low, uint16_t high, uint32_t ms) { int ok = 0; static int triggers = -1; - if (triggers < 0) triggers = input_rumble_triggers_enabled(); + static unsigned seen; + if (triggers < 0 || seen != cfg_version()) seen = cfg_version(), triggers = input_rumble_triggers_enabled(); AcquireSRWLockExclusive(&lock); if (state == 1 && pad && pad_rumble) { ok = SDL_RumbleGamepad(pad, low, high, ms); @@ -479,8 +483,21 @@ static int sensors_ready(void) { return sensor_ok; } +int input_motion_enabled(void) { + static int on = -1; + static unsigned seen; + unsigned v = cfg_version(); + if (on < 0 || v != seen) { + seen = v; + const char *e = cfg_get("TOTK_MOTION"); + on = !(e && !strcmp(e, "0")); + } + return on; +} + // 250 Hz: the gamepads update (reports read, rumble expiry) and the newest gyro and accelerometer sample goes into the -// fusion. Without a gamepad with sensors nothing is fed and the six-axis sensor reads at rest. +// fusion. Without a gamepad with sensors, or with motion off (TOTK_MOTION=0, live), nothing is fed and the six-axis +// sensor reads at rest. static DWORD WINAPI motion_main(void *arg) { (void)arg; HANDLE timer = CreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); @@ -499,7 +516,7 @@ static DWORD WINAPI motion_main(void *arg) { SDL_GetGamepadSensorData(pad, SDL_SENSOR_GYRO, g, 3); } ReleaseSRWLockExclusive(&lock); - if (!have) continue; + if (!have || !input_motion_enabled()) continue; double acc[3], gyro[3]; input_motion_axes(a, g, acc, gyro); motion_feed(motion_global(), acc, gyro, kern_now_ns()); @@ -511,9 +528,8 @@ void input_motion_start(void) { AcquireSRWLockExclusive(&lock); if (!state) start(); if (!motion_thread) { - const char *e = cfg_get("TOTK_MOTION"); - if (e && !strcmp(e, "0")) { motion_thread = -1; rt_log("input: motion off (TOTK_MOTION=0)"); } - else if (state != 1) motion_thread = -1; + if (!input_motion_enabled()) rt_log("input: motion off (TOTK_MOTION=0); it can be turned on while the game runs"); + if (state != 1) motion_thread = -1; else { HANDLE h = CreateThread(NULL, 0, motion_main, NULL, 0, NULL); if (!h) rt_fatal("input: motion thread CreateThread failed (error %lu)", GetLastError()); diff --git a/runtime/nvn_api_obj.c b/runtime/nvn_api_obj.c index 17a1c04e..17a06e4e 100644 --- a/runtime/nvn_api_obj.c +++ b/runtime/nvn_api_obj.c @@ -633,10 +633,12 @@ NVN_API(nvnWindowSetCrop) { // ---------- Present pacing // The vsync thread ticks at a fixed 60 Hz whatever the monitor does, so one game frame lasts `interval` ticks. With // the real-time frame step (frame_rate.c) game speed does not depend on the interval, so a frame is shown when it is -// ready, at most VSYNC_HZ per second: holding it to the 2nd or 3rd tick would only add latency and 50 ms frames. +// ready, at most at the frame limit (60 or 30 per second): holding it to the 2nd or 3rd tick would only add latency +// and 50 ms frames. #define VSYNC_HZ 60ull static uint64_t present_period(const win_t *o) { - uint64_t ticks = o->interval > 0 && !frame_step_realtime() ? (uint64_t)o->interval : 1ull; + uint64_t ticks = frame_step_realtime() ? (uint64_t)frame_step_cap_ticks() + : o->interval > 0 ? (uint64_t)o->interval : 1ull; return ticks * 1000000000ull / VSYNC_HZ; } diff --git a/runtime/ov_input.c b/runtime/ov_input.c index aa6ee6ea..4a608747 100644 --- a/runtime/ov_input.c +++ b/runtime/ov_input.c @@ -5,7 +5,7 @@ // TOTK_OPERATION_MODE=handheld it is the handheld controller (id 0x20, style bit 1) and player 1 is not connected, // which is the controller the game reads in that mode. Mouse and keyboard report no input. The controller has two // vibration devices (left, right) played on the gamepad's motors (TOTK_RUMBLE=0: none) and a six-axis sensor fed by -// the gamepad's gyro and accelerometer (TOTK_MOTION=0: none). State layouts follow libnx HID. +// the gamepad's gyro and accelerometer (TOTK_MOTION=0, live: reads at rest). State layouts follow libnx HID. #include #include #include @@ -189,8 +189,10 @@ static void once(volatile long *flag, const char *fmt, uint32_t v) { // TOTK_RUMBLE_STRENGTH (percent, 0..300, default 130; 0 = off) and TOTK_RUMBLE_CURVE (exponent on the amplitude, 0.2..1.5, // default 0.6). HD rumble is strong at low amplitude, an ERM motor hardly turns there, so weak values are lifted by the // curve (0.1 -> 0.25) and the strength scales the result (saturating at 65535; 0.66 and up reach full drive at 130 %). +// Both are live settings (the menu): read again whenever cfg_version changes. static float rumble_strength = 1.3f, rumble_curve = 0.6f; -static volatile long rumble_cfg_done; +static volatile long rumble_cfg_logged; +static unsigned rumble_cfg_seen = ~0u; static float cfg_float(const char *name, float def, float lo, float hi) { const char *e = cfg_get(name); char *end; @@ -199,11 +201,13 @@ static float cfg_float(const char *name, float def, float lo, float hi) { return (float)(v < lo ? lo : v > hi ? hi : v); } static void rumble_cfg(void) { - if (rumble_cfg_done) return; + unsigned v = cfg_version(); + if (v == rumble_cfg_seen) return; + rumble_cfg_seen = v; rumble_strength = cfg_float("TOTK_RUMBLE_STRENGTH", 130, 0, 300) / 100; rumble_curve = cfg_float("TOTK_RUMBLE_CURVE", 0.6f, 0.2f, 1.5f); int trig = input_rumble_triggers_enabled(); - if (!InterlockedExchange(&rumble_cfg_done, 1)) + if (!InterlockedExchange(&rumble_cfg_logged, 1)) rt_log("hid: rumble strength %.0f%%, curve %.2f, triggers %s", rumble_strength * 100, rumble_curve, trig ? "on" : "off"); } static uint16_t motor(float a) { return rumble_motor(a, rumble_curve, rumble_strength); } @@ -228,7 +232,8 @@ static void ov_vibration_handles(Cpu *c) { rt_fatal("nn::hid::GetVibrationDeviceHandles: invalid arguments (count %d, styles %#x)", max, style); static volatile long asked; rumble_cfg(); - if (env_zero("TOTK_RUMBLE") || rumble_strength == 0) { once(&asked, "hid: no vibration devices (TOTK_RUMBLE=%u)", 0); ret_x(c, 0); return; } + // strength 0 keeps the devices (silent), so the menu can turn rumble up again + if (env_zero("TOTK_RUMBLE")) { once(&asked, "hid: no vibration devices (TOTK_RUMBLE=%u)", 0); ret_x(c, 0); return; } static const struct { uint8_t bit, n; uint32_t base; } t[] = { {0, 2, 0x3}, {1, 2, 0x4}, {2, 2, 0x5}, {3, 1, 0x6}, {4, 1, 0x10007}, {5, 1, 0x8}, {10, 1, 0xd}, {8, 2, 0x4}, {30, 2, 0x21}, {29, 2, 0x20}}; @@ -243,14 +248,14 @@ static void ov_vibration_handles(Cpu *c) { } // int GetSixAxisSensorHandles(SixAxisSensorHandle *out, int count, const NpadIdType &id, NpadStyleSet style): -// utility::GetSixAxisSensorHandle's order (one sensor per style, two for the Joy-Con pair); none with TOTK_MOTION=0. +// utility::GetSixAxisSensorHandle's order (one sensor per style, two for the Joy-Con pair). Also with TOTK_MOTION=0: the +// sensor then reads at rest (six_fill), so the menu can turn motion on while the game runs. static void ov_six_axis_handles(Cpu *c) { uint32_t *out = arg_p(c, 0), style = (uint32_t)arg_x(c, 3); int max = (int)arg_x(c, 1); uint32_t id = handle_id(c, "GetSixAxisSensorHandles"); if (!out || max <= 0) rt_fatal("nn::hid::GetSixAxisSensorHandles: invalid arguments (count %d)", max); static volatile long asked; - if (env_zero("TOTK_MOTION")) { once(&asked, "hid: no six-axis sensor (TOTK_MOTION=%u)", 0); ret_x(c, 0); return; } uint32_t base = 0, n = 1; if (style & 1) base = 0x20003; else if (style & 2) base = 0x20004; @@ -446,7 +451,8 @@ static void ov_six_stop(Cpu *c) { static int six_fill(MotionState *s, int max, const uint32_t *h, const char *fn) { if (max <= 0) return 0; if (!s) rt_fatal("nn::hid::detail::%s: null output", fn); - int n = six_axis_ours(h, fn) && six_running ? motion_read(motion_global(), s, max, kern_now_ns()) : 0; + int live = six_axis_ours(h, fn) && six_running && input_motion_enabled(); + int n = live ? motion_read(motion_global(), s, max, kern_now_ns()) : 0; if (!n) { static const MotionState rest = {.acc = {0, 0, -1}, .dir = {1, 0, 0, 0, 1, 0, 0, 0, 1}}; for (int i = 0; i < max; i++) s[i] = rest; diff --git a/runtime/ov_probe.c b/runtime/ov_probe.c index 320ffaa9..322b09be 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -484,10 +484,12 @@ static void probe_feedback(uint32_t pid, uint32_t style) { char *keep_m = cfg_get("TOTK_MOTION") ? _strdup(cfg_get("TOTK_MOTION")) : NULL; set_env("TOTK_RUMBLE", "0"); set_env("TOTK_MOTION", "0"); - uint32_t none[2] = {0xdead, 0xdead}; - CHECK((int32_t)CALL("hid.GetVibrationDeviceHandles", U(none), 2, U(&pid), style) == 0 && - (int32_t)CALL("hid.GetSixAxisSensorHandles", U(none), 2, U(&pid), style) == 0 && none[0] == 0xdead, - "TOTK_RUMBLE=0 / TOTK_MOTION=0 still report handles"); + uint32_t none[2] = {0xdead, 0xdead}, six_off[2] = {0}; + CHECK((int32_t)CALL("hid.GetVibrationDeviceHandles", U(none), 2, U(&pid), style) == 0 && none[0] == 0xdead, + "TOTK_RUMBLE=0 still reports vibration handles"); + // TOTK_MOTION is live: the handle stays (the sensor reads at rest while it is 0) + CHECK((int32_t)CALL("hid.GetSixAxisSensorHandles", U(six_off), 2, U(&pid), style) == 1 && six_off[0] == sh[0], + "TOTK_MOTION=0 drops the six-axis handle %#x", six_off[0]); set_env("TOTK_RUMBLE", keep_r); set_env("TOTK_MOTION", keep_m); free(keep_r); diff --git a/runtime/patches.c b/runtime/patches.c index 3e7ca61f..142f5f07 100644 --- a/runtime/patches.c +++ b/runtime/patches.c @@ -1,7 +1,8 @@ // Code patch sets (recomp/patches.py, gen.py --patches). The generator lifts both the original and the replacement // instructions of every patched site, and rt_patch_on[set] picks one when the site runs, so a set is switched at start -// without touching code. The sets, their environment switches and defaults, and the patch page come from the generated -// patches.h; without it (C generated without --patches) there are no sets and every site runs the original. +// without touching code, and also while the game runs (rt_patch_switch: the frame-limit setting of the menu). The sets, +// their environment switches and defaults, and the patch page come from the generated patches.h; without it (C +// generated without --patches) there are no sets and every site runs the original. // // The patch page is the first 4 KiB page after main's image, inside the module window memory.c reserved: replacement // code reaches it with one adrp, as MacNativeGames' data page after main (games/totk/runtime/game_patches.c). Its @@ -68,6 +69,10 @@ void rt_patch_disable(int set) { if (set >= 0 && set < RT_PATCH_COUNT) rt_patch_on[set] = 0; } +void rt_patch_switch(int set, int on) { + if (set >= 0 && set < RT_PATCH_COUNT) __atomic_store_n(&rt_patch_on[set], (uint8_t)(on != 0), __ATOMIC_RELAXED); +} + void *rt_patch_page(void) { #if RT_PATCH_COUNT return page; diff --git a/totk.ini.example b/totk.ini.example index a106a0d8..1290998e 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -31,6 +31,8 @@ # audio = default # Audio the output queues before it starts, in ms (0 to 500). # audio_prefill_ms = 20 +# Volume in percent (0 to 100), on top of the game's own. Changes while the game runs take effect at once. +# volume = 100 [input] # Gamepad motion controls (0 = off) and vibration (0 = off).