From cd0917e18d34ec6ec6734332a24b9d82dfbcfa49 Mon Sep 17 00:00:00 2001 From: Wellington Dias Date: Sun, 1 Nov 2026 02:08:15 -0300 Subject: [PATCH 1/6] Add a dead zone slider per analog stick to the Controls tab, carrying an older stick_deadzone line over to both. --- docs/controls.md | 4 ++-- runtime/cfg.c | 30 +++++++++++++++++++++++++----- runtime/cfg.h | 3 +++ runtime/cfg_probe.c | 33 +++++++++++++++++++++++++++++++++ runtime/input.c | 29 +++++++++++++++++++---------- runtime/ui/menu.cpp | 4 +++- runtime/ui_text.c | 14 ++++++++++---- runtime/ui_text.h | 3 ++- totk.ini.example | 8 +++++--- 9 files changed, 102 insertions(+), 26 deletions(-) diff --git a/docs/controls.md b/docs/controls.md index 3cd4082c..0e1f4ee5 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -82,7 +82,7 @@ Mouse motion (raw input) becomes right-stick deflection. Each presented frame ta `TOTK_MOUSE_SENS` (0 to 10, default 1; higher turns faster, 0 turns the mouse camera and the cursor capture off). While the window is the foreground window the cursor is hidden and confined to the client area. It is released on focus loss, minimise, while F11 changes the window, during a size or move loop and while a text entry is open. Esc releases it by hand: the cursor shows, the mouse camera and mouse buttons stop, and the window can be moved, minimised or closed. A mouse click inside the client area captures it again; that click does not reach the game. Activating the window by a click on its title bar or border does not capture, so it can be dragged or closed right away; Alt+Tab or a click in the client area captures as before. `TOTK_INPUT=none` disables the capture too. -`TOTK_STICK_DEADZONE` (0 to 50, default 8) is the gamepad stick dead zone in percent of full deflection, the same for both sticks. It is round: a stick inside the circle reads centred, and the rest of its travel is scaled to start at 0 at the edge, so full deflection still reaches full. Raise it for a stick that drifts. The game's own dead zone applies after it. +`TOTK_LSTICK_DEADZONE` and `TOTK_RSTICK_DEADZONE` (0 to 50, default 8; the Analog sticks section of the Controls tab) are the gamepad stick dead zones in percent of full deflection, one per stick. Each is round: a stick inside the circle reads centred, and the rest of its travel is scaled to start at 0 at the edge, so full deflection still reaches full. Raise one for a stick that drifts. The game's own dead zone applies after it. A `stick_deadzone` line in an older `totk.ini` is carried over to both keys at the next start and removed; `TOTK_STICK_DEADZONE` set in the environment still applies to both sticks. The stick direction bits (`StickLLeft` to `StickRDown`) are derived from the sticks at 50% deflection. A gamepad plugged in later is picked up within one second; with none connected the log says `input: no gamepad`. @@ -107,7 +107,7 @@ Bridges that output a ViGEm DualShock 4 (ProCon2Windows, connectyourpro as teste `TOTK_INPUT_RECORD=` (`input_record` in `totk.ini`, or Input recording in the menu) writes the merged input in the same format, one line per button press and per stick segment: events before the world clock starts by tick, the rest timed; a button or stick held when the world clock starts is cut there and goes on as a timed event. The file replays as a script, which makes it the repro to attach to a bug report. -`TOTK_TEST_PAD=,,,` attaches an SDL virtual gamepad at start whose sticks rest at these raw SDL axis values (-32768 to 32767, down is +y), so a drifting or held stick can be tested without a controller: the values go through the gamepad mapping and `TOTK_STICK_DEADZONE` like a real pad's, and `TOTK_INPUT_RECORD` shows what reached the game. +`TOTK_TEST_PAD=,,,` attaches an SDL virtual gamepad at start whose sticks rest at these raw SDL axis values (-32768 to 32767, down is +y), so a drifting or held stick can be tested without a controller: the values go through the gamepad mapping and `TOTK_LSTICK_DEADZONE` / `TOTK_RSTICK_DEADZONE` like a real pad's, and `TOTK_INPUT_RECORD` shows what reached the game. ## RenderDoc capture (blocked) diff --git a/runtime/cfg.c b/runtime/cfg.c index d9c4cd61..637abdd4 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -28,7 +28,8 @@ static PlatMutex set_lock = PLAT_MUTEX_INIT; // cfg_set, cfg_reset, cfg_save static int save_ok = 1; // the last cfg_save_to wrote (or had nothing to write) // 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. +// logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line. A renamed key +// stays here while cfg_migrate carries its line over (STICK_DEADZONE, now one key per stick). static const char *const known[] = { "AB", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT", @@ -39,14 +40,14 @@ static const char *const known[] = { "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", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", - "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST", + "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MENU_LANG", "MENU_TEST", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC", "RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", - "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", + "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", "SHADER_MEMO", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", "VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS", @@ -66,7 +67,7 @@ static const struct { const char *key, *section; } sections[] = { {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, - {"PAD_LAYOUT", "input"}, {"STICK_DEADZONE", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"}, + {"PAD_LAYOUT", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"}, {"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"}, {"BIND_RCLICK", "input"}, {"BIND_L", "input"}, {"BIND_R", "input"}, {"BIND_ZL", "input"}, {"BIND_ZR", "input"}, {"BIND_PLUS", "input"}, {"BIND_MINUS", "input"}, {"BIND_LEFT", "input"}, {"BIND_UP", "input"}, @@ -114,7 +115,7 @@ static const CfgMeta metas[] = { {"VOLUME", "100", "0..100", LIVE}, {"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE}, {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox|xbox_prompts", LIVE}, - {"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, + {"LSTICK_DEADZONE", "8", "0..50", LIVE}, {"RSTICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, {"MENU_LANG", "", "en|ru", LIVE}, // Advanced: scheduling {"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART}, @@ -640,8 +641,27 @@ static void load_ini(void) { } } +// Renamed keys: the old totk.ini line would otherwise keep its value while nothing reads it. stick_deadzone (one dead +// zone for both sticks, up to 0.2.8) fills lstick_deadzone and rstick_deadzone where they are unset and its line goes. +// The environment variable is left alone: input.c stick_dead_get reads TOTK_STICK_DEADZONE for both sticks. +int cfg_migrate(void) { + static const char *const old_key[] = {"STICK_DEADZONE"}; + static const char *const new_keys[] = {PREFIX "LSTICK_DEADZONE", PREFIX "RSTICK_DEADZONE"}; + const char *old = cfg_get(PREFIX "STICK_DEADZONE"); + if (!old || cfg_from_env(PREFIX "STICK_DEADZONE")) return 0; + char value[64]; + snprintf(value, sizeof value, "%s", old); // cfg_reset drops the entry old points into + int n = 0; + for (size_t i = 0; i < sizeof new_keys / sizeof *new_keys; i++) + if (!cfg_is_set(new_keys[i])) cfg_set(new_keys[i], value), n++; + cfg_reset(old_key, 1); + rt_log("cfg: stick_deadzone = %s carried over to lstick_deadzone and rstick_deadzone (%d set)", value, n); + return n; +} + void cfg_init(void) { load_ini(); + if (cfg_migrate()) cfg_save(); if (profile_of()) rt_log("cfg: device profile Steam Deck: defaults for the keys totk.ini does not set (TOTK_DEVICE_PROFILE=desktop " "turns it off)"); diff --git a/runtime/cfg.h b/runtime/cfg.h index 5f94bc7a..15ff1457 100644 --- a/runtime/cfg.h +++ b/runtime/cfg.h @@ -8,6 +8,9 @@ const char *cfg_get(const char *name); // Reads totk.ini once, from mem_init after the address space is claimed and before any setting is read. Logs the file, its key count, unknown keys and environment overrides. void cfg_init(void); +// Carries the value of a renamed totk.ini key into its new keys in memory (those still unset) and marks the old line +// for removal at the next save; cfg_init calls it and saves. Returns how many keys took a value. Not thread-safe. +int cfg_migrate(void); // Replaces the loaded keys with those of the file at path (tests). 1 when the file was read, 0 when missing. // Not thread-safe: nothing else may call cfg_get meanwhile. diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index ca7449b2..04005a03 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -139,6 +139,11 @@ int probe_cfg(void) { "meta: prefix and case are accepted"); m = cfg_meta("RUMBLE_STRENGTH"); CHECK(m && EQ(m->def, "130") && EQ(m->values, "0..300"), "meta: rumble strength 130 in 0..300"); + m = cfg_meta("LSTICK_DEADZONE"); + CHECK(m && EQ(m->def, "8") && EQ(m->values, "0..50") && m->live, "meta: left stick dead zone 8 in 0..50, live"); + m = cfg_meta("RSTICK_DEADZONE"); + CHECK(m && EQ(m->def, "8") && EQ(m->values, "0..50") && m->live, "meta: right stick dead zone 8 in 0..50, live"); + CHECK(cfg_meta("STICK_DEADZONE") == NULL, "meta: the old single stick dead zone key has no row"); m = cfg_meta("PERF_OVERLAY"); CHECK(m && EQ(m->def, "off") && EQ(m->values, "off|fps|full") && m->live, "meta: perf_overlay is live, off by default"); CHECK(cfg_meta("BIND_A") == NULL && cfg_meta("FPS_COUNTER") == NULL && cfg_meta("NO_SUCH") == NULL, @@ -173,6 +178,34 @@ int probe_cfg(void) { CHECK(got && strstr((const char *)got, "\nvolume = 60\n"), "reset then set: the new line is written"); free(got); + // cfg_migrate: an older stick_deadzone line fills the per-stick keys that are unset, then leaves the file + static const char mbase[] = "[input]\n# lstick_deadzone = 8\n# rstick_deadzone = 8\nstick_deadzone = 15\n"; + plat_setenv("TOTK_STICK_DEADZONE", NULL); + plat_setenv("TOTK_LSTICK_DEADZONE", NULL); + plat_setenv("TOTK_RSTICK_DEADZONE", NULL); + CHECK(plat_file_write(path, mbase, sizeof mbase - 1), "write the migrate ini"); + CHECK(cfg_load(path) == 1 && EQ(cfg_get("TOTK_STICK_DEADZONE"), "15"), "load the migrate ini"); + CHECK(cfg_migrate() == 2, "migrate: both per-stick keys take the old value"); + CHECK(cfg_double("TOTK_LSTICK_DEADZONE") == 15 && cfg_double("TOTK_RSTICK_DEADZONE") == 15 && + cfg_get("TOTK_STICK_DEADZONE") == NULL, + "migrate: 15 for both sticks in memory, the old key gone"); + CHECK(cfg_migrate() == 0, "migrate: nothing left to carry over"); + CHECK(cfg_save_to(path) == 1, "migrate: save"); + got = plat_file_read(path, &got_n); + CHECK(got && strstr((const char *)got, "\nlstick_deadzone = 15\n") && strstr((const char *)got, "\nrstick_deadzone = 15\n") && + !strstr((const char *)got, "\nstick_deadzone = 15\n") && strstr((const char *)got, "# lstick_deadzone = 8"), + "migrate: the per-stick lines are in the file, the old line is not, the examples stay"); + if (got && !strstr((const char *)got, "\nlstick_deadzone = 15\n")) fprintf(stderr, "---- saved:\n%s\n----\n", got); + free(got); + static const char mkeep[] = "[input]\nrstick_deadzone = 20\nstick_deadzone = 15\n"; + CHECK(plat_file_write(path, mkeep, sizeof mkeep - 1) && cfg_load(path) == 1, "load the migrate ini with one stick set"); + CHECK(cfg_migrate() == 1 && cfg_double("TOTK_LSTICK_DEADZONE") == 15 && cfg_double("TOTK_RSTICK_DEADZONE") == 20, + "migrate: a per-stick key already set keeps its value, the other takes the old one"); + plat_setenv("TOTK_STICK_DEADZONE", "30"); + CHECK(cfg_load(path) == 1 && cfg_migrate() == 0 && cfg_double("TOTK_STICK_DEADZONE") == 30, + "migrate: the environment variable is left alone (input.c applies it to both sticks)"); + plat_setenv("TOTK_STICK_DEADZONE", NULL); + // an active line with an empty value has no entry in memory; Reset still removes it from the file static const char rempty[] = "[audio]\n# volume = 100\nvolume =\n[input]\nmotion = 0\n"; CHECK(plat_file_write(path, rempty, sizeof rempty - 1) && cfg_load(path) == 1 && cfg_get("TOTK_VOLUME") == NULL, diff --git a/runtime/input.c b/runtime/input.c index 86391739..a9679802 100644 --- a/runtime/input.c +++ b/runtime/input.c @@ -263,16 +263,24 @@ static void mouse_camera(int32_t out[2]) { out[1] = held[1]; } -static float stick_dead = -1; // TOTK_STICK_DEADZONE as a fraction of full deflection; live (cfg_version) +// TOTK_LSTICK_DEADZONE and TOTK_RSTICK_DEADZONE as fractions of full deflection; live (cfg_version). The older +// TOTK_STICK_DEADZONE set in the environment applies to both (an ini line is carried over by cfg_migrate instead). +static float stick_dead[2] = {-1, -1}; static unsigned stick_dead_seen; -static float stick_dead_get(void) { +static void stick_dead_get(float out[2]) { + static const char *const keys[2] = {"TOTK_LSTICK_DEADZONE", "TOTK_RSTICK_DEADZONE"}; unsigned ver = cfg_version(); - if (stick_dead >= 0 && ver == stick_dead_seen) return stick_dead; - stick_dead_seen = ver; - double v = cfg_double("TOTK_STICK_DEADZONE"); - stick_dead = (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f; - return stick_dead; + if (stick_dead[0] < 0 || ver != stick_dead_seen) { + stick_dead_seen = ver; + int both = cfg_from_env("TOTK_STICK_DEADZONE"); + for (int i = 0; i < 2; i++) { + double v = cfg_double(both ? "TOTK_STICK_DEADZONE" : keys[i]); + stick_dead[i] = (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f; + } + } + out[0] = stick_dead[0]; + out[1] = stick_dead[1]; } // One gamepad stick through the dead zone; SDL's Y grows downwards, the Switch's upwards. @@ -425,9 +433,10 @@ static int pad_read(uint64_t *b, int32_t sl[2], int32_t sr[2]) { uint8_t pd[PAD_COUNT] = {0}; if (!pad_physical(pd)) return 0; *b |= input_map_pad_buttons(pd, pad_layout_get()); - float dead = stick_dead_get(); - stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, dead, sl); - stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, dead, sr); + float dead[2]; + stick_dead_get(dead); + stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, dead[0], sl); + stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, dead[1], sr); return 1; } diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 0e02e4bf..9f736d23 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -677,8 +677,10 @@ static void tab_controls(float scale) { opt_slider("TOTK_RUMBLE_STRENGTH", UI_MENU_RUMBLE_STRENGTH, 0, 300, UI_MENU_RUMBLE_STRENGTH_DESC, 10, "%.0f %%"); opt_slider("TOTK_RUMBLE_CURVE", UI_MENU_RUMBLE_CURVE, 0.2f, 1.5f, UI_MENU_RUMBLE_CURVE_DESC, 0.05f, "%.2f"); opt_toggle("TOTK_RUMBLE_TRIGGERS", UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC); - opt_slider("TOTK_STICK_DEADZONE", UI_MENU_STICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%"); opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f"); + opt_group(UI_MENU_GROUP_STICKS); + opt_slider("TOTK_LSTICK_DEADZONE", UI_MENU_LSTICK_DEADZONE, 0, 50, UI_MENU_LSTICK_DEADZONE_DESC, 1, "%.0f %%"); + opt_slider("TOTK_RSTICK_DEADZONE", UI_MENU_RSTICK_DEADZONE, 0, 50, UI_MENU_RSTICK_DEADZONE_DESC, 1, "%.0f %%"); binds_rows(scale); opt_end(); binds_after_page(); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index f697e68c..51b5bd6b 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -132,8 +132,11 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s", [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "prompt files missing: run the setup again", [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "prompts change after restart", - [UI_MENU_STICK_DEADZONE] = "Stick dead zone", - [UI_MENU_STICK_DEADZONE_DESC] = "How far a gamepad stick moves before the game sees it. Raise it if the character or the camera moves on its own.", + [UI_MENU_GROUP_STICKS] = "Analog sticks", + [UI_MENU_LSTICK_DEADZONE] = "Left stick dead zone", + [UI_MENU_LSTICK_DEADZONE_DESC] = "How far the left stick moves before the game sees it. Raise it if the character walks on their own.", + [UI_MENU_RSTICK_DEADZONE] = "Right stick dead zone", + [UI_MENU_RSTICK_DEADZONE_DESC] = "How far the right stick moves before the game sees it. Raise it if the camera turns on its own.", [UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity", [UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.", @@ -393,8 +396,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова", [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "подсказки сменятся после перезапуска", - [UI_MENU_STICK_DEADZONE] = "Мёртвая зона стиков", - [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами.", + [UI_MENU_GROUP_STICKS] = "Стики", + [UI_MENU_LSTICK_DEADZONE] = "Мёртвая зона левого стика", + [UI_MENU_LSTICK_DEADZONE_DESC] = "Насколько нужно отклонить левый стик, чтобы игра это заметила. Увеличьте, если персонаж идёт сам.", + [UI_MENU_RSTICK_DEADZONE] = "Мёртвая зона правого стика", + [UI_MENU_RSTICK_DEADZONE_DESC] = "Насколько нужно отклонить правый стик, чтобы игра это заметила. Увеличьте, если камера поворачивается сама.", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", [UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index a2088960..1a87fe74 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -66,7 +66,8 @@ typedef enum { UI_MENU_PAD_LAYOUT, UI_MENU_PAD_LAYOUT_DESC, UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_XBOX_PROMPTS, UI_MENU_PAD_LAYOUT_IN_USE, UI_MENU_PAD_LAYOUT_PROMPTS_MISSING, UI_MENU_PAD_LAYOUT_PROMPTS_RESTART, - UI_MENU_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, + UI_MENU_GROUP_STICKS, UI_MENU_LSTICK_DEADZONE, UI_MENU_LSTICK_DEADZONE_DESC, + UI_MENU_RSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE_DESC, UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, // Controls tab: the remapping rows (ui/binds_page.cpp) diff --git a/totk.ini.example b/totk.ini.example index 6d3d5f1e..bb88df2a 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -187,9 +187,11 @@ # labels (A with B, X with Y; it loads romfs-patches-xbox, docs/controls.md, "Xbox button prompts"). The bind_ lines # below apply on top. Changes while the game runs take effect at once; the xbox_prompts prompts at the next start. # pad_layout = auto -# Gamepad stick dead zone in percent of full deflection (0 to 50). Raise it for a stick that drifts: inside the circle -# the stick reads centred, and the rest of its travel is scaled to start there. -# stick_deadzone = 8 +# Gamepad stick dead zones in percent of full deflection (0 to 50), one per stick. Raise one for a stick that drifts: +# inside the circle the stick reads centred, and the rest of its travel is scaled to start there. A stick_deadzone +# line from an older totk.ini is carried over to both at the next start. +# lstick_deadzone = 8 +# rstick_deadzone = 8 # Mouse camera sensitivity (0 to 10; 0 = no mouse camera and no cursor capture). # mouse_sens = 1 # Write the input of this run to a file that replays as a script (docs/controls.md, "Scripted input"). Default: off. From 86a9ea6d53b042f5c3b2125aebde0fd1980185ba Mon Sep 17 00:00:00 2001 From: FaserDocs <89686851+FaserDocs@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:41:37 +0100 Subject: [PATCH 2/6] Read installer sources once as UTF-8 in the catalog test --- tests/installer_test.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/installer_test.py b/tests/installer_test.py index 66cc31c6..d18a397f 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -520,9 +520,10 @@ class EventsTest(unittest.TestCase): catalog = json.loads((ROOT / 'installer' / 'text' / 'en.json').read_text(encoding='utf-8')) used = set() for path in (ROOT / 'installer').glob('*.py'): - used |= set(re.findall(r"InstallError\('([a-z_.]+)'", path.read_text())) - used |= set(re.findall(r"warning\('([a-z_.]+)'", path.read_text())) - used |= {f'phase.{s}.{p}' for s, p in re.findall(r"progress\('(\w+)', '(\w+)'[,)]", path.read_text())} + text = path.read_text(encoding='utf-8') + used |= set(re.findall(r"InstallError\('([a-z_.]+)'", text)) + used |= set(re.findall(r"warning\('([a-z_.]+)'", text)) + used |= {f'phase.{s}.{p}' for s, p in re.findall(r"progress\('(\w+)', '(\w+)'[,)]", text)} self.assertEqual(sorted(i for i in used if i not in catalog), []) From 88e044dcd3710092bc6d48cf14a7eee9a196a249 Mon Sep 17 00:00:00 2001 From: Wellington Dias Date: Sun, 1 Nov 2026 13:53:53 -0300 Subject: [PATCH 3/6] Mark a per-stick dead zone row as default at the shared value, and unset it when stepped back onto that value. --- runtime/ui/option_rows.cpp | 8 ++++++-- runtime/ui/option_rows.h | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp index 78725fd3..6074ca12 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -353,7 +353,10 @@ bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId de const char *set = cfg_get(key); const char *src = fallback && !(set && *set) ? fallback : key; // unset: show the value in effect, the fallback's const CfgMeta *m = cfg_meta(src); - double v = cfg_double(src), def = m ? strtod(m->def, NULL) : lo; + // A key without a table default of its own (the per-stick dead zones) defaults to its fallback: the "default" mark + // follows the fallback's default, not 0, even once the key is set. + if (fallback && m && !m->def[0]) m = cfg_meta(fallback); + double v = cfg_double(src), def = m && m->def[0] ? strtod(m->def, NULL) : lo; char shown[48]; snprintf(shown, sizeof shown, fmt, v); RowView rv = {shown, fabs(v - def) < step * 0.01, true, note}; @@ -367,7 +370,8 @@ bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId de char out[32]; if (step >= 1) snprintf(out, sizeof out, "%d", (int)lround(n)); else snprintf(out, sizeof out, "%g", round(n / step) * step); - apply(key, out); + // Landing on the fallback's value unsets the key (its line leaves totk.ini), so the row follows the fallback again. + apply(key, fallback && fabs(n - cfg_double(fallback)) < step * 0.01 ? "" : out); return true; } diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 83cf4f87..b15933b3 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -61,7 +61,8 @@ void opt_group_text(const char *title); void opt_text_str(const char *text, bool warn = false); // lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%"). // note: a short line under the value in place of the "default" mark (NULL: none). fallback: the setting that applies -// while key is unset; the row shows its value then, and a change sets key. +// while key is unset; the row shows its value then, and a change sets key. A key with no table default of its own takes +// the "default" mark from the fallback's default, and a step onto the fallback's value unsets key again. bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1, const char *fmt = "%g", const char *note = nullptr, const char *fallback = nullptr); From 1722b5da2caa528adc41b61ea87663b7db8be140 Mon Sep 17 00:00:00 2001 From: Wellington Dias Date: Sun, 1 Nov 2026 16:21:54 -0300 Subject: [PATCH 4/6] Offer 256 as a sun shadow map size for integrated GPUs short of memory bandwidth --- runtime/cfg.c | 2 +- runtime/ui/menu.cpp | 2 +- runtime/ui_text.c | 11 +++++++---- totk.ini.example | 4 ++-- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/runtime/cfg.c b/runtime/cfg.c index 015cda1b..64d0fda6 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -122,7 +122,7 @@ static const CfgMeta metas[] = { {"HDR", "0", "0|1", RESTART}, {"HDR_PEAK_NITS", "1000", "400..10000", LIVE}, {"HDR_GAME_NITS", "203", "80..500", LIVE}, {"HDR_UI_NITS", "203", "80..500", LIVE}, {"DEVICE_PROFILE", "auto", "auto|desktop|deck", RESTART}, - {"SHADOW_RES", "game", "game|512|768|1024|1536|2048", RESTART}, + {"SHADOW_RES", "game", "game|256|512|768|1024|1536|2048", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, {"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART}, {"PCSS", "0", "0..200", RESTART}, diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 151354e0..c6a2ac7a 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -518,7 +518,7 @@ static void row_render_scale(void) { } static void row_shadow_res(void) { - static const char *const vals[] = {"game", "512", "768", "1024", "1536", "2048"}; + static const char *const vals[] = {"game", "256", "512", "768", "1024", "1536", "2048"}; enum { N = sizeof vals / sizeof *vals }; const char *names[N]; names[0] = menu_text(UI_MENU_SHADOW_RES_GAME); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 5c14ed53..dc845006 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -74,7 +74,8 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_RES] = "Shadow map size", [UI_MENU_SHADOW_RES_DESC] = "Size of the sun's shadow map. The game's own size changes with the view, down to about 400 " "near the ground, so leaf shadows look blocky and jump; a fixed size keeps them still and " - "sharper. Above 1024 the shadows cost more GPU time and video memory.", + "sharper. Above 1024 the shadows cost more GPU time and video memory; 256 is coarser than the " + "game's own and is for integrated GPUs short of memory bandwidth.", [UI_MENU_SHADOW_RES_GAME] = "Game (changes)", [UI_MENU_ANISO] = "Texture filtering", [UI_MENU_ANISO_DESC] = "Anisotropic filtering of surface textures: ground, roads and walls seen at a shallow angle stay sharp into the distance instead of blurring. Game: the level the game asks for, as on the Switch.", @@ -498,7 +499,8 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_RES] = "Размер карты теней", [UI_MENU_SHADOW_RES_DESC] = "Размер карты теней от солнца. Собственный размер игры меняется вместе с видом, у земли до " "примерно 400, поэтому тени листвы выглядят квадратными и дёргаются; постоянный размер делает " - "их ровными и чётче. Выше 1024 тени требуют больше времени GPU и видеопамяти.", + "их ровными и чётче. Выше 1024 тени требуют больше времени GPU и видеопамяти; 256 грубее " + "собственного размера игры и предназначен для встроенных GPU с нехваткой пропускной способности памяти.", [UI_MENU_SHADOW_RES_GAME] = "Как в игре (меняется)", [UI_MENU_ANISO] = "Фильтрация текстур", [UI_MENU_ANISO_DESC] = "Анизотропная фильтрация текстур поверхностей: земля, дороги и стены под острым углом остаются чёткими вдали, а не размываются. Игра: уровень, который запрашивает игра, как на Switch.", @@ -1196,7 +1198,8 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_RES_DESC] = "Tamanho do mapa de sombras do sol. O tamanho do jogo muda com a vista, até cerca de " "400 perto do chão, então as sombras das folhas ficam quadriculadas e pulam; um " "tamanho fixo as deixa paradas e mais nítidas. Acima de 1024 as sombras custam mais " - "tempo de GPU e memória de vídeo.", + "tempo de GPU e memória de vídeo; 256 é mais grosseiro que o do jogo e serve para GPUs " + "integradas com pouca largura de banda de memória.", [UI_MENU_SHADOW_RES_GAME] = "Do jogo (varia)", [UI_MENU_ANISO] = "Filtragem de texturas", [UI_MENU_ANISO_DESC] = "Filtragem anisotrópica das texturas de superfície: chão, estradas e paredes vistos em " @@ -1795,7 +1798,7 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_OV_SCALE_BILINEAR] = "双线性", [UI_MENU_SHADOW_RES] = "阴影贴图尺寸", [UI_MENU_SHADOW_RES_DESC] = "太阳阴影贴图的尺寸。游戏自身的尺寸随视角变化,靠近地面时降到约 400,因此树叶阴影显得块状并且跳动;固定尺寸能让阴影稳定、更清晰。高于 1024 时阴影会占用更多 " - "GPU 时间和显存。", + "GPU 时间和显存;256 比游戏自身的尺寸更粗糙,适合显存带宽不足的集成显卡。", [UI_MENU_SHADOW_RES_GAME] = "游戏默认(会变化)", [UI_MENU_ANISO] = "纹理过滤", [UI_MENU_ANISO_DESC] = "表面纹理的各向异性过滤:以小角度看到的地面、道路和墙壁在远处依然清晰,而不会模糊。游戏:使用游戏请求的级别,与 Switch 上相同。", diff --git a/totk.ini.example b/totk.ini.example index 227a923f..d326e511 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -160,8 +160,8 @@ # color_saturation = 100 # color_gamma = 1 # Sun shadow map size: game (the game's own, which changes with the view and drops to about 400 near the ground, so -# leaf shadows look blocky and jump) or a fixed 512, 768, 1024, 1536 or 2048. Above 960 the texture heap grows with it. -# Read at start. +# leaf shadows look blocky and jump) or a fixed 256, 512, 768, 1024, 1536 or 2048. Above 960 the texture heap grows with +# it. 256 is coarser than the game's own and is for integrated GPUs short of memory bandwidth. Read at start. # shadow_res = game # Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game From 984c9bc7c3963bf46ce4576121a1724dd43f835d Mon Sep 17 00:00:00 2001 From: Michael Anthony Bitoon Date: Sun, 1 Nov 2026 20:19:00 +0800 Subject: [PATCH 5/6] Read the gradients of a TXD per coordinate so terrain picks the right mip level TotK's terrain shaders fill the gradient registers of a texture-with-derivatives instruction per coordinate (du/dx, du/dy, dv/dx, dv/dy), while the translator takes the first two registers as dPdx and the last two as dPdy. The mip level then came from the wrong derivatives and was too sharp on terrain faces turned across the screen, so patches that followed the faces crawled when the camera moved. After a shader loads, every two-dimensional gradient pair has its inner components swapped by two new composite constructs, so the shader cache is untouched. TOTK_TXD_TRANSPOSE=0 turns it off. The finding is row 2.13 of docs/maxwell.md. --- docs/maxwell.md | 1 + runtime/cfg.c | 2 +- runtime/gfx_shader.c | 62 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/docs/maxwell.md b/docs/maxwell.md index 472360f7..3d7623f7 100644 --- a/docs/maxwell.md +++ b/docs/maxwell.md @@ -68,6 +68,7 @@ Source shorthands: | 2.9 | **LOD**: TSC min/max LOD clamp, LOD bias, `TWO_D_NO_MIPMAP` texture type, a min filter without mips stays on the base level; TIC carries its own max anisotropy and aniso quality fields. | `minLod`/`maxLod`, `mipLodBias` limited by `maxSamplerLodBias`. | yuzu: anisotropy heuristics for mods forcing trilinear (YZ-2306, PR 10744). Ours: non-mip filter → `maxLod = minLod + 0.25`, bias clamped (`vk_texture.c` `make_sampler`). | G80TEX | | 2.10 | **Texture gather rounding**: Maxwell sub-texel precision differs from AMD/Intel; edge texels picked by TLD4 differ by one. | Implementation-defined `subTexelPrecisionBits`. | yuzu adds a sub-pixel offset to gathers on non-NVIDIA hosts: fixed BotW shadow artifacts at object edges ("shader_recompiler: Add subpixel offset for correct rounding at ImageGather", , title only). Ours: the translator biases gather coordinates by the host's `subTexelPrecisionBits` on every non-NVIDIA GPU (`vk_caps.c` → job `gather_bias` → Ryujinx `TexturePass.InsertCoordGatherBias`); TotK on RADV drew dashed dark lines along wall and floor edges in the prologue caves without it. `TOTK_GATHER_BIAS=0` turns it off. | — | | 2.11 | **Gather offsets**: `TLD4.PTP` takes four per-texel offsets, possibly from registers. | `ConstOffsets` must be constant. | Ours: `QueryHostSupportsNonConstantTextureOffset() => false` makes Ryujinx emulate register offsets (`tools/xlate/Program.cs`). | RYU-SH `Translation/Optimizations` (TexturePass) | +| 2.13 | **TXD gradient register order**: TotK's terrain shaders fill the gradient registers of a `TXD` per coordinate (du/dx, du/dy, dv/dx, dv/dy). | Vulkan's `Grad` takes dPdx (du/dx, dv/dx) and dPdy (du/dy, dv/dy). | Ryujinx's `EmitTxd` takes the first two registers as dPdx and the last two as dPdy, so the mip level came from the wrong derivatives and was too sharp on terrain faces turned across the screen: patches that followed the faces crawled when the camera moved (1.4.3, the Depths; found by the user from their F9 frame, a gradient sample's coordinate and gradients traced back to `DPdx` and `DPdy` of the interpolants). Ours: `gfx_shader.c` `patch_txd_transpose` swaps the two inner components of every two-component gradient pair in the loaded SPIR-V (the shader cache is untouched). `TOTK_TXD_TRANSPOSE=0` turns it off. Only 2D gradients are handled; 3D and cube ones are left as translated. | — | | 2.12 | **Depth compare** (`TSC` depth compare + `TIC_4_DEPTH_TEXTURE`), min/max reduction filtering. | `compareEnable`; reduction mode needs `samplerFilterMinmax` and is not allowed with compare. | Ours: reduction dropped when compare is on (`vk_texture.c` `make_sampler`). | G80TEX | | 2.13 | **ASTC / BC**: native ASTC; zero ASTC block = error colour on hosts. | AMD and NVIDIA desktop GPUs lack ASTC: decode to RGBA8. yuzu offered ASTC recompression to BC1/BC3 for low VRAM (YZ-2305, PR 10398). | Ours: native upload where the device samples ASTC, else a compute-shader decode (`vk_astc.c`, `TOTK_ASTC`), CPU decode (`tex_astc.c`) as the fallback. | `runtime/vk_astc.c` | | 2.14 | **Linear CPU-written textures** (`FLAGS_LINEAR`, small ramps, glyph caches): CPU writes visible to the GPU directly. | Must re-upload or use linear images over host memory. | NXN Mario: sky black without its 64×1 RGBA16F ramps. | NXN | diff --git a/runtime/cfg.c b/runtime/cfg.c index 015cda1b..91d07f57 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -53,7 +53,7 @@ static const char *const known[] = { "SHADER_MEMO", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS", "SWKBD_ANSWER", - "SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", + "SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", "VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS", "WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE", diff --git a/runtime/gfx_shader.c b/runtime/gfx_shader.c index 3388935b..09419be3 100644 --- a/runtime/gfx_shader.c +++ b/runtime/gfx_shader.c @@ -759,6 +759,67 @@ out: free(loc), free(packed), free(ttype), free(tcomps), free(pointee); } +// Every gradient sample (OpImageSampleExplicitLod with Grad) whose two gradients are each built from two components gets +// them transposed, dx = (a, c) and dy = (b, d) from dx = (a, b) and dy = (c, d), by two new OpCompositeConstruct before +// it. TotK's shaders fill a TXD's gradient registers per coordinate (du/dx, du/dy, dv/dx, dv/dy), and the translator +// (Ryujinx, InstEmitTexture EmitTxd) builds dx = (first two registers), dy = (last two) = (du/dx, du/dy) and +// (dv/dx, dv/dy): a mip level chosen from the wrong derivatives, too sharp on terrain faces turned across the screen, +// which crawled in patches that followed the faces (1.4.3, the Depths). TOTK_TXD_TRANSPOSE=0 turns it off. +// Applied to the SPIR-V after it is loaded, so the shader cache is untouched. +enum { OP_COMPOSITE_CONSTRUCT = 80, OP_SAMPLE_EXPLICIT = 88, IO_GRAD = 4 }; + +static void patch_txd_transpose(GfxShader *s) { + static int on = -1; + static volatile int32_t n_logged; + if (on < 0) { + const char *e = cfg_get("TOTK_TXD_TRANSPOSE"); + on = !(e && *e == '0'); + } + uint32_t *w = s->spirv; + uint64_t n = s->words; + if (!on || n < 5) return; + uint32_t bound = w[3] < (1u << 20) ? w[3] : (1u << 20); + uint64_t *cc = calloc(bound, sizeof *cc); // word index of a 2-constituent OpCompositeConstruct defining the id + int found = 0; + if (!cc) return; + for (uint64_t i = 5; i < n;) { + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + if (!len || i + len > n) goto out; + if (op == OP_COMPOSITE_CONSTRUCT && len == 5 && w[i + 2] < bound) cc[w[i + 2]] = i; + if (op == OP_SAMPLE_EXPLICIT && len >= 8 && w[i + 5] == IO_GRAD && w[i + 6] < bound && w[i + 7] < bound && + cc[w[i + 6]] && cc[w[i + 7]] && w[cc[w[i + 6]] + 1] == w[cc[w[i + 7]] + 1]) + found++; + i += len; + } + if (!found) goto out; + uint32_t *o = malloc((n + (uint64_t)found * 10) * sizeof *o); + if (!o) goto out; + uint64_t k = 0; + uint32_t next = w[3]; + for (uint64_t i = 0; i < 5; i++) o[k++] = w[i]; + for (uint64_t i = 5; i < n;) { + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + if (op == OP_SAMPLE_EXPLICIT && len >= 8 && w[i + 5] == IO_GRAD && w[i + 6] < bound && w[i + 7] < bound && + cc[w[i + 6]] && cc[w[i + 7]] && w[cc[w[i + 6]] + 1] == w[cc[w[i + 7]] + 1]) { + const uint32_t *dx = w + cc[w[i + 6]], *dy = w + cc[w[i + 7]]; // [hdr, type, id, a, b], [hdr, type, id, c, d] + uint32_t ndx = next++, ndy = next++; + o[k++] = 5u << 16 | OP_COMPOSITE_CONSTRUCT, o[k++] = dx[1], o[k++] = ndx, o[k++] = dx[3], o[k++] = dy[3]; + o[k++] = 5u << 16 | OP_COMPOSITE_CONSTRUCT, o[k++] = dx[1], o[k++] = ndy, o[k++] = dx[4], o[k++] = dy[4]; + for (uint32_t j = 0; j < len; j++) o[k++] = w[i + j]; + o[k - len + 6] = ndx, o[k - len + 7] = ndy; + } else { + for (uint32_t j = 0; j < len; j++) o[k++] = w[i + j]; + } + i += len; + } + o[3] = next; + free(s->spirv); + s->spirv = o, s->words = k; + if (plat_inc32(&n_logged) <= 4) rt_log("gfx_shader: %d gradient samples now read their derivatives per coordinate", found); +out: + free(cc); +} + static void reflect(GfxShader *s) { static const char *const kinds[GFX_RES_KINDS] = {"cbufs", "sbufs", "textures", "images"}; const char *js = s->reflection; @@ -771,6 +832,7 @@ static void reflect(GfxShader *s) { json_objects(js, kinds[k], add_res, s, k); } reflect_spirv(s); + patch_txd_transpose(s); } // ---- use masks (see the cache key at the top) From f4f9d6dd53ce6dafa895d09f911123e9d75f6bcf Mon Sep 17 00:00:00 2001 From: MierzwaMatheus Date: Mon, 2 Nov 2026 01:22:13 -0300 Subject: [PATCH 6/6] Keep the replay's transient buffers and the zero buffer in host-coherent memory The CPU fills these chunks and the zero buffer and never flushes them. On Intel integrated GPUs (ANV on Meteor Lake) the host-cached memory type that VMA picks for random host access is not coherent, so the GPU read what an earlier submission had left there. A lighting fragment shader got another draw's UpdateUniformBuffer payload as its step count (0x3f800000 instead of 96 or 128), looped about a billion times and lost the device; other stale payloads drew the black frames. Requiring HOST_COHERENT keeps the same memory types on GPUs where host memory is already coherent. --- runtime/vk_exec_draw.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index c8533028..8740ada4 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -234,8 +234,13 @@ static uint8_t *scratch(VkExec *ex, uint64_t size, VkBuffer *buf, VkDeviceSize * .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT}; + // HOST_COHERENT: the CPU fills these chunks and never flushes them. Intel's integrated GPUs (ANV, Meteor Lake) + // offer host-cached memory only without coherence, which VMA picks for random host access: the GPU then read + // what an earlier submission left in the chunk (an UpdateUniformBuffer payload of another draw: a lighting + // shader's step count of 0x3f800000 instead of 128, and a loop of a billion steps). VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST, - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT}; + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, + .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; VmaAllocationInfo info; VkResult res = vmaCreateBuffer(vk_ctx()->vma, &bi, &ai, &c->buf, &c->alloc, &info); if (res != VK_SUCCESS) rt_fatal("vk: transient buffer of %llu bytes failed (%d)", (unsigned long long)n, (int)res); @@ -351,7 +356,8 @@ static void dummies_init(void) { VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT}; VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST, - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT}; + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, + .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; // the memset below is not flushed VmaAllocationInfo info; if (vmaCreateBuffer(c->vma, &bi, &ai, &Z.zbuf, &Z.zalloc, &info) != VK_SUCCESS) rt_fatal("vk: zero buffer failed"); memset(info.pMappedData, 0, ZERO_BYTES);