From bfb49335312bc80452731ca70edf80191e703e52 Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:47:47 +0100 Subject: [PATCH 01/19] Add shadow map resolution and anisotropic filtering settings TotK draws its sun cascades into a 960x960 DEPTH16 array of 4 layers, and its static shadows into 1440x1440 and 720x720 arrays of 2, whatever the output resolution, and shrinks the cascades under load. shadow_scale (1 to 4, default 1) creates those images that many times larger on each side: passes into them scale the game's viewports, scissors and support-buffer viewport size, and copies scale their regions, so the game is unaware of it. Images the CPU writes or that alias pool memory keep their size. When the maps are enlarged, depth-compare samplers filter linearly, because the game's few nearest taps are spaced for its own texels and leave hard, stepped edges otherwise. aniso (game, 2, 4, 8, 16; default 16) raises anisotropic filtering of linear mipmapped colour samplers; depth-compare, nearest and unmipmapped samplers keep the game's setting. Both are in totk.ini.example and on the Screen tab of the settings menu (English and Russian). Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 7 +++--- runtime/ui/menu.cpp | 15 +++++++++++++ runtime/ui_text.c | 14 ++++++++++++ runtime/ui_text.h | 2 ++ runtime/vk.h | 3 +++ runtime/vk_exec.c | 11 +++++++--- runtime/vk_exec.h | 3 +++ runtime/vk_exec_draw.c | 10 ++++++--- runtime/vk_exec_xfer.c | 11 +++++++--- runtime/vk_texture.c | 50 +++++++++++++++++++++++++++++++++++++++--- totk.ini.example | 7 ++++++ 11 files changed, 118 insertions(+), 15 deletions(-) diff --git a/runtime/cfg.c b/runtime/cfg.c index 84abed08..11cebb4a 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -30,7 +30,7 @@ static int save_ok = 1; // the last cfg_save_to wrote (o // 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[] = { - "AB", "APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", + "AB", "ANISO", "APP_POOL", "ASSUME_FOCUS", "ASTC", "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", "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", @@ -47,7 +47,7 @@ static const char *const known[] = { "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", - "SHADER_MEMO", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", + "SHADER_MEMO", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "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", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -93,6 +93,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, + {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 64c3c4c0..a9ee648f 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -438,6 +438,19 @@ static void row_render_scale(void) { opt_choice_list("TOTK_RENDER_SCALE", UI_MENU_RENDER_SCALE, vals, names, N, UI_MENU_RENDER_SCALE_DESC); } +static void row_aniso(void) { + static const char *const vals[] = {"game", "2", "4", "8", "16"}; + static const char *names[] = {NULL, "2x", "4x", "8x", "16x"}; + names[0] = menu_text(UI_MENU_ANISO_GAME); + opt_choice_list("TOTK_ANISO", UI_MENU_ANISO, vals, names, 5, UI_MENU_ANISO_DESC); +} + +static void row_shadow_scale(void) { + static const char *const vals[] = {"1", "2", "3", "4"}; + static const char *const names[] = {"960 (1x)", "1920 (2x)", "2880 (3x)", "3840 (4x)"}; + opt_choice_list("TOTK_SHADOW_SCALE", UI_MENU_SHADOW_SCALE, vals, names, 4, UI_MENU_SHADOW_SCALE_DESC); +} + static void row_gpu(void) { const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1]; char idx[MAX_GPUS][4]; @@ -528,6 +541,8 @@ static void tab_screen(float scale) { static const UiTextId up[] = {UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR}; opt_choice("TOTK_UPSCALER", UI_MENU_UPSCALER, up, 2, UI_MENU_UPSCALER_DESC); opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%"); + row_aniso(); + row_shadow_scale(); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index f93107ae..aa31587e 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -63,6 +63,13 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", + [UI_MENU_ANISO] = "Anisotropic filtering", + [UI_MENU_ANISO_DESC] = "Keeps ground and walls seen at a steep angle sharp. The game's own level is the Switch's; " + "16x costs little on a desktop GPU.", + [UI_MENU_ANISO_GAME] = "The game's", + [UI_MENU_SHADOW_SCALE] = "Shadow resolution", + [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " + "sharper shadow edges and leaf shadows. Takes effect at the next start.", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -281,6 +288,13 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Билинейное", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", + [UI_MENU_ANISO] = "Анизотропная фильтрация", + [UI_MENU_ANISO_DESC] = "Сохраняет чёткость земли и стен под острым углом. Уровень самой игры — как на Switch; " + "16x почти ничего не стоит настольной видеокарте.", + [UI_MENU_ANISO_GAME] = "Как в игре", + [UI_MENU_SHADOW_SCALE] = "Разрешение теней", + [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " + "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 6eb805cf..680e9cfe 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -36,6 +36,8 @@ typedef enum { UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME, UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, + UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, + UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/runtime/vk.h b/runtime/vk.h index 961f2f35..fdfaf319 100644 --- a/runtime/vk.h +++ b/runtime/vk.h @@ -268,6 +268,9 @@ typedef struct { uint8_t fb_usage; // created with ATTACHMENT_FEEDBACK_LOOP usage (VK_FEEDBACK_LAYOUT, attachable images) uint8_t fb_learned; // a draw sampled it while it was a written attachment of the open pass: its passes // attach it in ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT (vk_exec.c vk_exec_pass_begin) + uint8_t scale; // 1, or TOTK_SHADOW_SCALE for a shadow map made larger than the game's (vk_texture.c + // shadow_scale_of): width and height above are the larger ones, the game's regions + // are multiplied by it } VkTexImage; const VkTexImage *vk_texture_get(const tex_t *t); // created and made current; NULL for BUFFER or unmapped formats // A texture slot; a slot whose texture was finalized follows the live texture at the same storage (hle_nvn.c). diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index d82c0574..0abd2b63 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -192,6 +192,7 @@ static void resolve_target(const tex_t *t, const view_t *v, int has_v, int depth } o->image = img->image; o->img = img; + o->scale = img->scale ? img->scale : 1; o->format = fmt; o->view_type = layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D; o->aspect = depth_slot ? img->aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) @@ -227,7 +228,7 @@ static void resolve_rt(VkExec *ex) { ex->rt_resolved = 1; const p_set_rt *r = &ex->rt; int n = r->n < 0 ? 0 : r->n > 8 ? 8 : r->n; - uint32_t w = UINT32_MAX, h = UINT32_MAX, layers = UINT32_MAX, samples = 0; + uint32_t w = UINT32_MAX, h = UINT32_MAX, layers = UINT32_MAX, samples = 0, scale = 1; for (int i = 0; i < 8; i++) { VkExecTarget *t = &ex->color[i]; resolve_target(i < n ? r->color[i] : NULL, &r->cview[i], i < n && r->has_cview[i], 0, t); @@ -238,6 +239,7 @@ static void resolve_rt(VkExec *ex) { if (t->height < h) h = t->height; if (t->layers < layers) layers = t->layers; if (!samples) samples = t->samples; + if (t->scale > scale) scale = t->scale; } VkExecTarget *d = &ex->depth; resolve_target(r->depth, &r->dview, r->has_dview, 1, d); @@ -249,6 +251,7 @@ static void resolve_rt(VkExec *ex) { if (d->height < h) h = d->height; if (d->layers < layers) layers = d->layers; if (!samples) samples = d->samples; + if (d->scale > scale) scale = d->scale; } ex->pass_noatt = w == UINT32_MAX; if (ex->pass_noatt) { @@ -260,6 +263,7 @@ static void resolve_rt(VkExec *ex) { ex->vp[0][1], ex->vp[0][2], ex->vp[0][3]); } ex->pass_w = w, ex->pass_h = h, ex->pass_layers = layers; + ex->pass_scale = ex->pass_noatt ? 1 : scale; ex->pass_ncolor = (uint32_t)n; ex->pass_samples = samples ? samples : 1; ex->pipe.samples = (uint8_t)ex->pass_samples; @@ -511,8 +515,9 @@ VkBuffer vk_exec_inline_buffer(VkDeviceSize size) { VkRect2D vk_exec_scissor(const VkExec *ex) { int64_t w = ex->pass_w, h = ex->pass_h; if (!ex->has_scissor) return (VkRect2D){{0, 0}, {(uint32_t)w, (uint32_t)h}}; - int64_t x0 = ex->scissor.x, y0 = ex->scissor.y; - int64_t x1 = x0 + ex->scissor.w, y1 = y0 + ex->scissor.h; + int64_t k = ex->pass_scale > 1 ? ex->pass_scale : 1; + int64_t x0 = ex->scissor.x * k, y0 = ex->scissor.y * k; + int64_t x1 = x0 + (int64_t)ex->scissor.w * k, y1 = y0 + (int64_t)ex->scissor.h * k; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x1 > w) x1 = w; diff --git a/runtime/vk_exec.h b/runtime/vk_exec.h index c81d5c61..b0095f63 100644 --- a/runtime/vk_exec.h +++ b/runtime/vk_exec.h @@ -35,6 +35,7 @@ typedef struct { uint32_t width, height, samples; // extent of that level; with blocks, in blocks int32_t nvn_format; // NVNformat of the view (VkPipeState.color_fmt / depth_fmt) const VkTexImage *img; // the image (fb_usage, fb_learned) + uint8_t scale; // VkTexImage.scale } VkExecTarget; // The replay state. One instance lives for the run: NVN state is queue state and carries over from one submission to @@ -52,6 +53,8 @@ typedef struct VkExec { int rt_resolved; // color[] and depth hold this command buffer's images for rt VkExecTarget color[8], depth; // resolved targets uint32_t pass_w, pass_h, pass_layers; // render area and layer count of the open (or next) pass + uint32_t pass_scale; // its targets' VkTexImage.scale: game viewports and scissors + // are multiplied by it int pass_noatt; // the pass has no attachment: its size follows the draws (vk_exec_noatt_dims) VkFormat pass_color[8], pass_depth, pass_stencil; // attachment formats of the pass (VkPipelineRenderingCreateInfo); // VK_FORMAT_UNDEFINED: none diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index e9326df5..e23741e9 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -1240,8 +1240,9 @@ static VkDescriptorSet alloc_set(VkExec *ex, VkDescriptorSetLayout layout) { } static void support_in(const VkExec *ex, float in[3]) { // what support_fill reads: viewport size, point size - in[0] = ex->in_pass && ex->has_vp ? ex->vp[0][2] : (float)ex->pass_w; - in[1] = ex->in_pass && ex->has_vp ? ex->vp[0][3] : (float)ex->pass_h; + float k = ex->pass_scale > 1 ? (float)ex->pass_scale : 1.0f; + in[0] = ex->in_pass && ex->has_vp ? ex->vp[0][2] * k : (float)ex->pass_w; + in[1] = ex->in_pass && ex->has_vp ? ex->vp[0][3] * k : (float)ex->pass_h; in[2] = ex->point_size > 0 ? ex->point_size : 1.0f; } @@ -1670,7 +1671,10 @@ static void record_fixed(VkExec *ex) { VkCommandBuffer cb = ex->cb; if (ex->dirty & VK_EXEC_DIRTY_VIEWPORT) { float x = 0, y = 0, w = (float)ex->pass_w, h = (float)ex->pass_h; - if (ex->has_vp) x = ex->vp[0][0], y = ex->vp[0][1], w = ex->vp[0][2], h = ex->vp[0][3]; + if (ex->has_vp) { + float k = ex->pass_scale > 1 ? (float)ex->pass_scale : 1.0f; + x = ex->vp[0][0] * k, y = ex->vp[0][1] * k, w = ex->vp[0][2] * k, h = ex->vp[0][3] * k; + } if (w < 1) w = 1; if (h < 1) h = 1; VkViewport v = {x, y + h, w, -h, ex->depth_range[0], ex->depth_range[1]}; // the y flip: negative height diff --git a/runtime/vk_exec_xfer.c b/runtime/vk_exec_xfer.c index 34548153..ffb3b420 100644 --- a/runtime/vk_exec_xfer.c +++ b/runtime/vk_exec_xfer.c @@ -352,10 +352,11 @@ static int sub_resolve(const tex_t *t, const view_t *v, int has_v, const NVNcopy s->level = has_v && v->set_levels ? v->base_level : 0; s->layer0 = has_v && v->set_layers ? v->min_layer : 0; uint32_t lw = max1(img->width >> s->level), lh = max1(img->height >> s->level); - s->x = r->xoffset, s->y = r->yoffset, s->z = r->zoffset; + int k = img->scale > 1 ? img->scale : 1; // a larger shadow map: the game's region in its texels + s->x = r->xoffset * k, s->y = r->yoffset * k, s->z = r->zoffset; s->nz = r->depth > 0 ? (uint32_t)r->depth : 1; - s->w = r->width > 0 ? (uint32_t)r->width : defaults_to_level ? (s->x < (int32_t)lw ? lw - (uint32_t)s->x : 0) : 0; - s->h = r->height > 0 ? (uint32_t)r->height : defaults_to_level ? (s->y < (int32_t)lh ? lh - (uint32_t)s->y : 0) : 0; + s->w = r->width > 0 ? (uint32_t)r->width * k : defaults_to_level ? (s->x < (int32_t)lw ? lw - (uint32_t)s->x : 0) : 0; + s->h = r->height > 0 ? (uint32_t)r->height * k : defaults_to_level ? (s->y < (int32_t)lh ? lh - (uint32_t)s->y : 0) : 0; int is3d = img->type == VK_IMAGE_TYPE_3D; uint32_t layers = is3d ? 1 : (uint32_t)s->z + s->nz, first = is3d ? 0 : s->layer0; if (s->level >= img->levels || s->x < 0 || s->y < 0 || s->z < 0 || !s->w || !s->h || @@ -411,6 +412,10 @@ static int buffer_side(const VkExec *ex, const Sub *s, uint64_t addr, uint64_t * static void copy_buffer_image(VkExec *ex, const p_copy_b2t *p, int to_image) { Sub s; if (!sub_resolve(p->tex, &p->view, p->has_view, &p->r, 1, &s)) return; + if (s.img->scale > 1) { // the buffer holds the game's texel count, the image more + warn_once(W_REGION, "buffer copy of a shadow map enlarged by TOTK_SHADOW_SCALE: skipped"); + return; + } uint64_t size; VkBufferImageCopy c; VkMemSpan m; diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index b65f21e7..e2fda908 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -273,6 +273,33 @@ static void init_image(Tex *e, VkCommandBuffer cb) { } } +// TOTK_SHADOW_SCALE (1 to 4): the game's shadow maps are made this many times larger on each side. TotK renders its +// sun cascades into a 960x960 DEPTH16 2D array of 4 layers and its static shadows into 1440x1440 and 720x720 arrays of 2, +// whatever the output resolution, and shrinks the cascades under load (872, 848, 800, 480 and so on). Those are made +// larger here: render passes into them scale the game's viewports and scissors (vk_exec.c resolve_rt, pass_scale), +// copies scale their regions (vk_exec_xfer.c sub_resolve), and shaders sample them with normalised coordinates, so the +// game sees nothing of it. A map whose storage the CPU writes (mirrored) or that aliases pool memory keeps its size, +// as its texels must match the guest layout. +static int shadow_scale(void) { + static int scale = -1; + if (scale < 0) { + int s = cfg_int("TOTK_SHADOW_SCALE"); + s = s < 1 ? 1 : s > 4 ? 4 : s; + rt_log("vk: shadow map scale %d", s); + scale = s; + } + return scale; +} + +static int shadow_scale_of(const nvn_texdesc *d, const TexVkFormat *f, uint32_t samples, int mirrored) { + int scale = shadow_scale(); + if (scale == 1 || mirrored || samples > 1 || d->format != NVN_FORMAT_DEPTH16 || !f->depth) return 1; + if (d->target != NVN_TEXTURE_TARGET_2D_ARRAY || d->width != d->height || d->width < 256 || d->depth < 2 || d->depth > 4) + return 1; + uint32_t most = vk_ctx()->props.limits.maxImageDimension2D; + return d->width * (uint32_t)scale <= most ? scale : 1; +} + // defer_init: the caller records the image's first transition (init_image or alias_copy). static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { static volatile long n_unmapped, n_unsupported, n_failed, n_unbound; @@ -300,6 +327,8 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { case NVN_TEXTURE_TARGET_CUBEMAP: case NVN_TEXTURE_TARGET_CUBEMAP_ARRAY: layers = L.layers; break; default: break; } + int scale = shadow_scale_of(d, &f, d->samples > 1 ? (uint32_t)d->samples : 1, tex_mirrored(t)); + w *= (uint32_t)scale, h *= (uint32_t)scale; uint32_t levels = umax(d->levels, 1), most = 1; for (uint32_t s = umax(umax(w, h), depth); s > 1; s >>= 1) most++; if (levels > most) levels = most; @@ -342,7 +371,7 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { e->f = f; e->pub.addr = k->addr; VkImage img = VK_NULL_HANDLE; - if (nvn_gpu_only(k->addr)) { // storage in a physical or virtual pool: alias the pool memory (section 3.2) + if (scale == 1 && nvn_gpu_only(k->addr)) { // storage in a physical or virtual pool: alias the pool memory (section 3.2) if (vkCreateImage(c->device, &ci, NULL, &img) == VK_SUCCESS && !bind_pool_memory(c, e, img)) { vkDestroyImage(c->device, img, NULL); img = VK_NULL_HANDLE; @@ -384,6 +413,7 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { p->bound = e->bound_to != NULL; p->block_views = (uint8_t)block_views; p->fb_usage = (uint8_t)fb_usage; + p->scale = (uint8_t)scale; if (!defer_init) { init_image(e, vk_upload_begin()); @@ -1421,6 +1451,7 @@ static VkCompareOp compare_op(uint32_t f) { } static struct { int init, mirror_clamp_edge, minmax, border_no_format; } sf; +static float aniso_force; // TOTK_ANISO: 0 = the game's level, else the least level of mipmapped colour samplers static void sampler_features(VkCtx *c) { if (sf.init) return; @@ -1432,6 +1463,9 @@ static void sampler_features(VkCtx *c) { sf.mirror_clamp_edge = f12.samplerMirrorClampToEdge; sf.minmax = f12.samplerFilterMinmax; sf.border_no_format = c->has_custom_border_color && cbf.customBorderColors && cbf.customBorderColorWithoutFormat; + const char *an = cfg_value("TOTK_ANISO"); + aniso_force = strcmp(an, "game") ? (float)atoi(an) : 0; + rt_log("vk: anisotropic filtering: %s", aniso_force > 1 ? an : "the game's"); sf.init = 1; } @@ -1466,13 +1500,23 @@ static VkSampler make_sampler(VkCtx *c, const samp_par *d) { if (si.maxLod < si.minLod) si.maxLod = si.minLod; float lim = c->props.limits.maxSamplerLodBias; si.mipLodBias = fmaxf(-lim, fminf(lim, d->lod_bias)); - if (d->aniso > 1) { + float aniso = d->aniso; + // TOTK_ANISO raises the level for filtered, mipmapped colour samplers only: depth-compare (shadow) samplers and + // nearest or unmipmapped ones (data maps, LUTs) keep what the game set. + if (aniso_force > 1 && !d->cmp_mode && si.magFilter == VK_FILTER_LINEAR && si.minFilter == VK_FILTER_LINEAR && + (mf == NVN_MIN_FILTER_LINEAR_MIPMAP_NEAREST || mf == NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR) && aniso < aniso_force) + aniso = aniso_force; + if (aniso > 1) { si.anisotropyEnable = VK_TRUE; - si.maxAnisotropy = fminf(d->aniso, c->props.limits.maxSamplerAnisotropy); + si.maxAnisotropy = fminf(aniso, c->props.limits.maxSamplerAnisotropy); } if (d->cmp_mode) { si.compareEnable = VK_TRUE; si.compareOp = compare_op(d->cmp_func); + // A depth-compare sampler set to nearest returns 0 or 1 per tap, and the game's shaders smooth shadow edges by + // a few taps spaced for its own shadow map texels. With TOTK_SHADOW_SCALE those taps cover a fraction of the + // area and the edges turn hard and stepped; linear filtering makes every tap a 2x2 PCF instead. + if (shadow_scale() > 1) si.magFilter = si.minFilter = VK_FILTER_LINEAR; } VkSamplerCustomBorderColorCreateInfoEXT cb = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT}; VkSamplerReductionModeCreateInfo rm = {.sType = VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; diff --git a/totk.ini.example b/totk.ini.example index f8213a99..68e9f306 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -115,6 +115,13 @@ # from 0 (off) to 100. Changes while the game runs take effect at once. # upscaler = fsr # sharpness = 80 +# Anisotropic filtering of mipmapped textures: game (the level the game asks for, as on the Switch) or 2, 4, 8, 16. +# Keeps ground and walls seen at a steep angle sharp. Depth-compare (shadow) and nearest-filtered samplers keep the +# game's setting. Read at start. +# aniso = 16 +# Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game +# resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. Read at start. +# shadow_scale = 1 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 386e70453b4f5be8eed1ff4704c05ff249bd894f Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:06:58 +0100 Subject: [PATCH 02/19] Add a shadow cascade range setting for 1.4.3 The sun's shadow cascades end at 20, 40, 80 and 160 m: the depth shadow parameter object (main+0x6fa3c0) registers depth_shadow_near_0_1..3 and depth_shadow_far_0 as immediates, and the field's .bgsdw files do not override them. The new cascade patch set reads the four distances from patch page +64..+76 instead, and shadow_range (percent, 50 to 400, default 100) writes them there at start, so the visible steps where shadows turn softer move away from the player. It spreads the shadow map over more ground, which shadow_scale pays back. Only patches-v143.txt has the set; on 1.2.1 the setting logs that and does nothing. The setting is in totk.ini.example and on the Screen tab of the menu (English and Russian). Co-Authored-By: Claude Opus 5.5 --- recomp/patches-v143.txt | 9 +++++++++ runtime/cfg.c | 5 +++-- runtime/resolution.c | 18 ++++++++++++++++++ runtime/ui/menu.cpp | 7 +++++++ runtime/ui_text.c | 8 ++++++++ runtime/ui_text.h | 1 + totk.ini.example | 3 +++ 7 files changed, 49 insertions(+), 2 deletions(-) diff --git a/recomp/patches-v143.txt b/recomp/patches-v143.txt index 16189169..dd47fea5 100644 --- a/recomp/patches-v143.txt +++ b/recomp/patches-v143.txt @@ -10,6 +10,7 @@ set cloth TOTK_CLOTH_REALTIME 1 set bounce TOTK_HIGHFPS_FIX 1 set output TOTK_PATCH_OUTPUT 0 set scene TOTK_PATCH_SCENE 0 +set cascade TOTK_PATCH_CASCADE 0 # 60 fps: the adaptive present-interval controller (main+0x2db174, 1.2.1 0x8f26c8) gets the minimum interval 1. site fps60 main 2db204 6b08015f 7100055f # clamp: cmp w10, #1 (was cmp w10, w8 = minimum) @@ -936,3 +937,11 @@ spin subsdk0 1c4e54 1c4e60 # 4 instructions; loads spin sdk 2d3654 2d3668 # 6 instructions; loads spin sdk 443864 443884 # 9 instructions; loads spin sdk 541e54 541f98 # 32 instructions; loads + +# Sun shadow cascade distances (runtime/resolution.c res_shadow_range switches the set on). The depth shadow parameter +# object (main+0x6fa3c0) registers depth_shadow_near_0_1..3 = 20, 40, 80 m and depth_shadow_far_0 = 160 m as +# immediates, and the field's .bgsdw files do not override them; with the set on they come from page +64..+76. +site cascade main 6fabb8 52a83408 @page:x8 b9404108 # mov w8, #20.0 -> ldr w8, [page+64] +site cascade main 6fac40 52a84408 @page:x8 b9404508 # mov w8, #40.0 -> ldr w8, [page+68] +site cascade main 6facc8 52a85408 @page:x8 b9404908 # mov w8, #80.0 -> ldr w8, [page+72] +site cascade main 6fad4c 52a86408 @page:x8 b9404d08 # mov w8, #160.0 -> ldr w8, [page+76] diff --git a/runtime/cfg.c b/runtime/cfg.c index 11cebb4a..bfd87294 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -47,7 +47,7 @@ static const char *const known[] = { "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", - "SHADER_MEMO", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", + "SHADER_MEMO", "SHADOW_RANGE", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "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", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -94,6 +94,7 @@ static const CfgMeta metas[] = { {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, + {"SHADOW_RANGE", "100", "50..400", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/resolution.c b/runtime/resolution.c index 2e4b1d7c..fc8d5524 100644 --- a/runtime/resolution.c +++ b/runtime/resolution.c @@ -191,7 +191,25 @@ void res_heapdef_served(void) { R.heapdef_ok = 1; } // ---- start: the patch page and the sets static uint64_t pack(unsigned w, unsigned h) { return (uint64_t)h << 32 | w; } +// TOTK_SHADOW_RANGE (percent, 50 to 400; 100 = the game's): the sun's shadow cascades end at 20, 40, 80 and 160 m. +// Other values multiply those distances through the cascade patch set (recomp/patches-v143.txt), so the sharp first +// cascade reaches further and the visible steps between cascades move away from the player, at the cost of shadow +// texels per metre (TOTK_SHADOW_SCALE pays that back). +static void res_shadow_range(void) { + int pct = cfg_int("TOTK_SHADOW_RANGE"), set = rt_patch_set("cascade"); + if (pct == 100) return; + if (set < 0) { + rt_log("resolution: the generated C has no cascade patch set; shadow_range stays 100"); + return; + } + float k = (float)(pct < 50 ? 50 : pct > 400 ? 400 : pct) / 100.0f, d[4] = {20 * k, 40 * k, 80 * k, 160 * k}; + memcpy((uint8_t *)rt_patch_page() + 64, d, sizeof d); + rt_patch_switch(set, 1); + rt_log("resolution: shadow cascades end at %g, %g, %g and %g m", d[0], d[1], d[2], d[3]); +} + void res_init(void) { + res_shadow_range(); if (!bigger()) { rt_log("resolution: the game's own (output 1920x1080, scene 1600x900)"); return; diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index a9ee648f..d3eb04f9 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -451,6 +451,12 @@ static void row_shadow_scale(void) { opt_choice_list("TOTK_SHADOW_SCALE", UI_MENU_SHADOW_SCALE, vals, names, 4, UI_MENU_SHADOW_SCALE_DESC); } +static void row_shadow_range(void) { + static const char *const vals[] = {"100", "150", "200", "300"}; + static const char *const names[] = {"160 m (1x)", "240 m (1.5x)", "320 m (2x)", "480 m (3x)"}; + opt_choice_list("TOTK_SHADOW_RANGE", UI_MENU_SHADOW_RANGE, vals, names, 4, UI_MENU_SHADOW_RANGE_DESC); +} + static void row_gpu(void) { const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1]; char idx[MAX_GPUS][4]; @@ -543,6 +549,7 @@ static void tab_screen(float scale) { opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%"); row_aniso(); row_shadow_scale(); + row_shadow_range(); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index aa31587e..d279674a 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -70,6 +70,10 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Shadow resolution", [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " "sharper shadow edges and leaf shadows. Takes effect at the next start.", + [UI_MENU_SHADOW_RANGE] = "Shadow cascade range", + [UI_MENU_SHADOW_RANGE_DESC] = "Moves the steps where shadows turn softer (the game's 20, 40, 80 and 160 m) further " + "away. Spreads the shadow map over more ground: raise Shadow resolution with it. " + "Takes effect at the next start.", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -295,6 +299,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Разрешение теней", [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", + [UI_MENU_SHADOW_RANGE] = "Дальность каскадов теней", + [UI_MENU_SHADOW_RANGE_DESC] = "Отодвигает границы, за которыми тени становятся мягче (в игре 20, 40, 80 и 160 м). " + "Карта теней растягивается на большую площадь, поэтому вместе с этим поднимайте " + "разрешение теней. Действует после перезапуска.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 680e9cfe..7462a703 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -38,6 +38,7 @@ typedef enum { UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, + UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/totk.ini.example b/totk.ini.example index 68e9f306..d8744e73 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -122,6 +122,9 @@ # Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game # resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. Read at start. # shadow_scale = 1 +# Sun shadow cascade range in percent of the game's (its cascades end at 20, 40, 80 and 160 m), 50 to 400: higher moves +# the steps where shadows turn softer further away, and spreads the shadow map over more ground. Read at start. +# shadow_range = 100 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 4af60604de5d96da5bdafb4c6653df1f80a52bac Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:29:53 +0100 Subject: [PATCH 03/19] Add screen-space contact shadows TotK fills a full-resolution G-buffer with a B10G11R11 scene colour, an R32F linear depth and a D32F depth, lights it in half resolution, and composites the lighting into the scene colour in one pass whose only target is that colour, with a D16 class depth. vk_contact.c recognises both passes, and when the pass after the composite begins (or a dispatch or copy comes first) runtime/shaders/contact_shadow.comp marches each pixel 16 steps toward the sun through the linear depth and darkens the scene colour where nearby geometry blocks the ray: the small shadows at feet, under stones and in grass that the shadow maps miss. Transparent surfaces, the sky and post-processing come after. The projection, far plane and sun direction come from the fragment stage's 0x940-byte camera block (c4): c4[7].x, c4[8].y, c4[14].y, and the first cascade's depth row c4[44].xyz, whose negation points toward the sun. Scene colour images get STORAGE usage while the setting is on. contact_shadows (percent strength, default 0) is in totk.ini.example and on the Screen tab of the menu (English and Russian). TOTK_CONTACT_DEBUG=1 shows the shadow factor in grey instead of the frame. It costs about 0.45 ms per frame at a 3840x2160 scene on an RTX 4080 SUPER. Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 6 +- runtime/contact_shadow_spv.h | 156 +++++++++++++++++++++++ runtime/gfx_window.c | 1 + runtime/shaders/contact_shadow.comp | 67 ++++++++++ runtime/ui/menu.cpp | 1 + runtime/ui_text.c | 6 + runtime/ui_text.h | 1 + runtime/vk.h | 3 + runtime/vk_contact.c | 188 ++++++++++++++++++++++++++++ runtime/vk_exec.c | 1 + runtime/vk_exec.h | 3 + runtime/vk_exec_draw.c | 1 + runtime/vk_exec_xfer.c | 1 + runtime/vk_texture.c | 4 + totk.ini.example | 4 + 15 files changed, 440 insertions(+), 3 deletions(-) create mode 100644 runtime/contact_shadow_spv.h create mode 100644 runtime/shaders/contact_shadow.comp create mode 100644 runtime/vk_contact.c diff --git a/runtime/cfg.c b/runtime/cfg.c index bfd87294..2372ad1b 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -35,7 +35,7 @@ static const char *const known[] = { "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", - "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", + "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "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", "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", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -94,7 +94,7 @@ static const CfgMeta metas[] = { {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, - {"SHADOW_RANGE", "100", "50..400", RESTART}, + {"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/contact_shadow_spv.h b/runtime/contact_shadow_spv.h new file mode 100644 index 00000000..7d506c8f --- /dev/null +++ b/runtime/contact_shadow_spv.h @@ -0,0 +1,156 @@ +// Generated by tools/build_shaders.py from runtime/shaders/contact_shadow.comp; do not edit. +// source sha256 b452a1920e59c4d83b2c994b0c6573cc1e479f7032a1310a7432d11c5c2e9908 +#pragma once +#include +static const uint32_t contact_shadow_spv[] = { + 0x07230203, 0x00010300, 0x000d000b, 0x000001b1, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00000069, + 0x00060010, 0x00000004, 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00030047, 0x00000027, + 0x00000002, 0x00050048, 0x00000027, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000027, + 0x00000001, 0x00000023, 0x00000010, 0x00050048, 0x00000027, 0x00000002, 0x00000023, 0x00000020, + 0x00050048, 0x00000027, 0x00000003, 0x00000023, 0x00000030, 0x00040047, 0x00000069, 0x0000000b, + 0x0000001c, 0x00040047, 0x00000088, 0x00000021, 0x00000000, 0x00040047, 0x00000088, 0x00000022, + 0x00000000, 0x00040047, 0x0000013f, 0x00000021, 0x00000001, 0x00040047, 0x0000013f, 0x00000022, + 0x00000000, 0x00040047, 0x0000015c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, + 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, + 0x00000002, 0x00040017, 0x0000000a, 0x00000006, 0x00000003, 0x0004002b, 0x00000006, 0x0000001b, + 0x40000000, 0x0004002b, 0x00000006, 0x0000001d, 0x3f800000, 0x00040015, 0x00000020, 0x00000020, + 0x00000000, 0x0004002b, 0x00000020, 0x00000021, 0x00000000, 0x00040017, 0x00000026, 0x00000006, + 0x00000004, 0x0006001e, 0x00000027, 0x00000026, 0x00000026, 0x00000026, 0x00000026, 0x00040020, + 0x00000028, 0x00000009, 0x00000027, 0x0004003b, 0x00000028, 0x00000029, 0x00000009, 0x00040015, + 0x0000002a, 0x00000020, 0x00000001, 0x0004002b, 0x0000002a, 0x0000002b, 0x00000000, 0x00040020, + 0x0000002c, 0x00000009, 0x00000006, 0x0004002b, 0x00000020, 0x00000030, 0x00000001, 0x0004002b, + 0x00000020, 0x0000003f, 0x00000002, 0x0004002b, 0x00000006, 0x00000043, 0x3f000000, 0x0004002b, + 0x00000006, 0x00000059, 0x4253ee82, 0x0004002b, 0x00000006, 0x0000005b, 0x3d897143, 0x0004002b, + 0x00000006, 0x0000005c, 0x3bbf4590, 0x0005002c, 0x00000007, 0x0000005d, 0x0000005b, 0x0000005c, + 0x00040017, 0x00000064, 0x0000002a, 0x00000002, 0x00040017, 0x00000067, 0x00000020, 0x00000003, + 0x00040020, 0x00000068, 0x00000001, 0x00000067, 0x0004003b, 0x00000068, 0x00000069, 0x00000001, + 0x00040017, 0x0000006a, 0x00000020, 0x00000002, 0x00020014, 0x0000006e, 0x0004002b, 0x0000002a, + 0x00000072, 0x00000002, 0x00090019, 0x00000085, 0x00000006, 0x00000001, 0x00000000, 0x00000000, + 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000086, 0x00000085, 0x00040020, 0x00000087, + 0x00000000, 0x00000086, 0x0004003b, 0x00000087, 0x00000088, 0x00000000, 0x0004002b, 0x00000006, + 0x0000008f, 0x00000000, 0x0004002b, 0x00000006, 0x00000092, 0x3f7fbe77, 0x0004002b, 0x00000006, + 0x0000009e, 0x42a00000, 0x00040020, 0x000000a8, 0x00000009, 0x00000026, 0x0004002b, 0x0000002a, + 0x000000b4, 0x00000001, 0x0004002b, 0x00000020, 0x000000b5, 0x00000003, 0x0004002b, 0x00000006, + 0x000000bb, 0x3ecccccd, 0x0004002b, 0x00000006, 0x000000bc, 0x40400000, 0x0004002b, 0x00000006, + 0x000000c0, 0x3e19999a, 0x0004002b, 0x00000006, 0x000000c2, 0x3c23d70a, 0x0004002b, 0x00000006, + 0x000000cb, 0x3e800000, 0x0004002b, 0x0000002a, 0x000000da, 0x00000010, 0x0004002b, 0x00000006, + 0x000000e6, 0xbd4ccccd, 0x0005002c, 0x00000007, 0x000000f0, 0x0000008f, 0x0000008f, 0x00040017, + 0x000000f1, 0x0000006e, 0x00000002, 0x0005002c, 0x00000007, 0x000000f8, 0x0000001d, 0x0000001d, + 0x0004002b, 0x00000006, 0x00000114, 0x3ca3d70a, 0x0004002b, 0x00000006, 0x00000116, 0x3b03126f, + 0x0004002b, 0x00000006, 0x0000012b, 0x42200000, 0x0004002b, 0x0000002a, 0x00000137, 0x00000003, + 0x00090019, 0x0000013d, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000002, + 0x00000008, 0x00040020, 0x0000013e, 0x00000000, 0x0000013d, 0x0004003b, 0x0000013e, 0x0000013f, + 0x00000000, 0x0004002b, 0x00000020, 0x0000015b, 0x00000008, 0x0006002c, 0x00000067, 0x0000015c, + 0x0000015b, 0x0000015b, 0x00000030, 0x0005002c, 0x00000007, 0x000001ad, 0x00000043, 0x00000043, + 0x0004002b, 0x00000006, 0x000001af, 0x3dcccccd, 0x0004002b, 0x00000006, 0x000001b0, 0x3d800000, + 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7, + 0x0000015d, 0x00000000, 0x000300fb, 0x00000021, 0x0000015e, 0x000200f8, 0x0000015e, 0x0004003d, + 0x00000067, 0x0000006b, 0x00000069, 0x0007004f, 0x0000006a, 0x0000006c, 0x0000006b, 0x0000006b, + 0x00000000, 0x00000001, 0x0004007c, 0x00000064, 0x0000006d, 0x0000006c, 0x00050051, 0x0000002a, + 0x00000071, 0x0000006d, 0x00000000, 0x00060041, 0x0000002c, 0x00000073, 0x00000029, 0x00000072, + 0x00000021, 0x0004003d, 0x00000006, 0x00000074, 0x00000073, 0x0004006e, 0x0000002a, 0x00000075, + 0x00000074, 0x000500af, 0x0000006e, 0x00000076, 0x00000071, 0x00000075, 0x000400a8, 0x0000006e, + 0x00000077, 0x00000076, 0x000300f7, 0x00000079, 0x00000000, 0x000400fa, 0x00000077, 0x00000078, + 0x00000079, 0x000200f8, 0x00000078, 0x00050051, 0x0000002a, 0x0000007b, 0x0000006d, 0x00000001, + 0x00060041, 0x0000002c, 0x0000007c, 0x00000029, 0x00000072, 0x00000030, 0x0004003d, 0x00000006, + 0x0000007d, 0x0000007c, 0x0004006e, 0x0000002a, 0x0000007e, 0x0000007d, 0x000500af, 0x0000006e, + 0x0000007f, 0x0000007b, 0x0000007e, 0x000200f9, 0x00000079, 0x000200f8, 0x00000079, 0x000700f5, + 0x0000006e, 0x00000080, 0x00000076, 0x0000015e, 0x0000007f, 0x00000078, 0x000300f7, 0x00000082, + 0x00000000, 0x000400fa, 0x00000080, 0x00000081, 0x00000082, 0x000200f8, 0x00000081, 0x000200f9, + 0x0000015d, 0x000200f8, 0x00000082, 0x0004003d, 0x00000086, 0x00000089, 0x00000088, 0x00040064, + 0x00000085, 0x0000008b, 0x00000089, 0x0007005f, 0x00000026, 0x0000008c, 0x0000008b, 0x0000006d, + 0x00000002, 0x0000002b, 0x00050051, 0x00000006, 0x0000008d, 0x0000008c, 0x00000000, 0x000500bc, + 0x0000006e, 0x00000090, 0x0000008d, 0x0000008f, 0x000500be, 0x0000006e, 0x00000093, 0x0000008d, + 0x00000092, 0x000500a6, 0x0000006e, 0x00000094, 0x00000090, 0x00000093, 0x000300f7, 0x00000096, + 0x00000000, 0x000400fa, 0x00000094, 0x00000095, 0x00000096, 0x000200f8, 0x00000095, 0x000200f9, + 0x0000015d, 0x000200f8, 0x00000096, 0x00060041, 0x0000002c, 0x0000009a, 0x00000029, 0x0000002b, + 0x0000003f, 0x0004003d, 0x00000006, 0x0000009b, 0x0000009a, 0x00050085, 0x00000006, 0x0000009c, + 0x0000008d, 0x0000009b, 0x000500ba, 0x0000006e, 0x0000009f, 0x0000009c, 0x0000009e, 0x000300f7, + 0x000000a1, 0x00000000, 0x000400fa, 0x0000009f, 0x000000a0, 0x000000a1, 0x000200f8, 0x000000a0, + 0x000200f9, 0x0000015d, 0x000200f8, 0x000000a1, 0x0004006f, 0x00000007, 0x000000a5, 0x0000006d, + 0x00050081, 0x00000007, 0x000000a7, 0x000000a5, 0x000001ad, 0x00050041, 0x000000a8, 0x000000a9, + 0x00000029, 0x00000072, 0x0004003d, 0x00000026, 0x000000aa, 0x000000a9, 0x0007004f, 0x00000007, + 0x000000ab, 0x000000aa, 0x000000aa, 0x00000002, 0x00000003, 0x00050085, 0x00000007, 0x000000ac, + 0x000000a7, 0x000000ab, 0x0005008e, 0x00000007, 0x00000167, 0x000000ac, 0x0000001b, 0x00050083, + 0x00000007, 0x00000169, 0x00000167, 0x000000f8, 0x00050051, 0x00000006, 0x0000016b, 0x00000169, + 0x00000000, 0x00050085, 0x00000006, 0x0000016d, 0x0000016b, 0x0000009c, 0x00060041, 0x0000002c, + 0x0000016e, 0x00000029, 0x0000002b, 0x00000021, 0x0004003d, 0x00000006, 0x0000016f, 0x0000016e, + 0x00050088, 0x00000006, 0x00000170, 0x0000016d, 0x0000016f, 0x00050051, 0x00000006, 0x00000172, + 0x00000169, 0x00000001, 0x0004007f, 0x00000006, 0x00000173, 0x00000172, 0x00050085, 0x00000006, + 0x00000175, 0x00000173, 0x0000009c, 0x00060041, 0x0000002c, 0x00000176, 0x00000029, 0x0000002b, + 0x00000030, 0x0004003d, 0x00000006, 0x00000177, 0x00000176, 0x00050088, 0x00000006, 0x00000178, + 0x00000175, 0x00000177, 0x0004007f, 0x00000006, 0x0000017a, 0x0000009c, 0x00060050, 0x0000000a, + 0x0000017b, 0x00000170, 0x00000178, 0x0000017a, 0x00060041, 0x0000002c, 0x000000b6, 0x00000029, + 0x000000b4, 0x000000b5, 0x0004003d, 0x00000006, 0x000000b7, 0x000000b6, 0x00050085, 0x00000006, + 0x000000ba, 0x0000009c, 0x000001af, 0x0008000c, 0x00000006, 0x000000bd, 0x00000001, 0x0000002b, + 0x000000ba, 0x000000bb, 0x000000bc, 0x00050085, 0x00000006, 0x000000be, 0x000000b7, 0x000000bd, + 0x00050085, 0x00000006, 0x000000c3, 0x0000009c, 0x000000c2, 0x00050081, 0x00000006, 0x000000c4, + 0x000000c0, 0x000000c3, 0x00050085, 0x00000006, 0x000000c8, 0x000000be, 0x000001b0, 0x00050094, + 0x00000006, 0x0000017f, 0x000000a5, 0x0000005d, 0x0006000c, 0x00000006, 0x00000180, 0x00000001, + 0x0000000a, 0x0000017f, 0x00050085, 0x00000006, 0x00000181, 0x00000059, 0x00000180, 0x0006000c, + 0x00000006, 0x00000182, 0x00000001, 0x0000000a, 0x00000181, 0x00050081, 0x00000006, 0x000000d0, + 0x000000cb, 0x00000182, 0x00050085, 0x00000006, 0x000000d1, 0x000000c8, 0x000000d0, 0x000200f9, + 0x000000d4, 0x000200f8, 0x000000d4, 0x000700f5, 0x00000006, 0x000001a7, 0x000000d1, 0x000000a1, + 0x00000129, 0x000000d7, 0x000700f5, 0x0000002a, 0x000001a6, 0x0000002b, 0x000000a1, 0x00000126, + 0x000000d7, 0x000500b1, 0x0000006e, 0x000000db, 0x000001a6, 0x000000da, 0x000400f6, 0x000000d6, + 0x000000d7, 0x00000000, 0x000400fa, 0x000000db, 0x000000d5, 0x000000d6, 0x000200f8, 0x000000d5, + 0x00050041, 0x000000a8, 0x000000de, 0x00000029, 0x000000b4, 0x0004003d, 0x00000026, 0x000000df, + 0x000000de, 0x0008004f, 0x0000000a, 0x000000e0, 0x000000df, 0x000000df, 0x00000000, 0x00000001, + 0x00000002, 0x0005008e, 0x0000000a, 0x000000e2, 0x000000e0, 0x000001a7, 0x00050081, 0x0000000a, + 0x000000e3, 0x0000017b, 0x000000e2, 0x00050051, 0x00000006, 0x000000e5, 0x000000e3, 0x00000002, + 0x000500be, 0x0000006e, 0x000000e7, 0x000000e5, 0x000000e6, 0x000300f7, 0x000000e9, 0x00000000, + 0x000400fa, 0x000000e7, 0x000000e8, 0x000000e9, 0x000200f8, 0x000000e8, 0x000200f9, 0x000000d6, + 0x000200f8, 0x000000e9, 0x0004007f, 0x00000006, 0x00000188, 0x000000e5, 0x00050051, 0x00000006, + 0x0000018a, 0x000000e3, 0x00000000, 0x00050085, 0x00000006, 0x0000018b, 0x00000043, 0x0000018a, + 0x00050085, 0x00000006, 0x0000018e, 0x0000018b, 0x0000016f, 0x00050088, 0x00000006, 0x00000190, + 0x0000018e, 0x00000188, 0x00050081, 0x00000006, 0x00000191, 0x00000043, 0x00000190, 0x00050051, + 0x00000006, 0x00000193, 0x000000e3, 0x00000001, 0x00050085, 0x00000006, 0x00000194, 0x00000043, + 0x00000193, 0x00050085, 0x00000006, 0x00000197, 0x00000194, 0x00000177, 0x00050088, 0x00000006, + 0x00000199, 0x00000197, 0x00000188, 0x00050083, 0x00000006, 0x0000019a, 0x00000043, 0x00000199, + 0x00050050, 0x00000007, 0x0000019b, 0x00000191, 0x0000019a, 0x000500b8, 0x000000f1, 0x000000f2, + 0x0000019b, 0x000000f0, 0x0004009a, 0x0000006e, 0x000000f3, 0x000000f2, 0x000400a8, 0x0000006e, + 0x000000f4, 0x000000f3, 0x000300f7, 0x000000f6, 0x00000000, 0x000400fa, 0x000000f4, 0x000000f5, + 0x000000f6, 0x000200f8, 0x000000f5, 0x000500ba, 0x000000f1, 0x000000f9, 0x0000019b, 0x000000f8, + 0x0004009a, 0x0000006e, 0x000000fa, 0x000000f9, 0x000200f9, 0x000000f6, 0x000200f8, 0x000000f6, + 0x000700f5, 0x0000006e, 0x000000fb, 0x000000f3, 0x000000e9, 0x000000fa, 0x000000f5, 0x000300f7, + 0x000000fd, 0x00000000, 0x000400fa, 0x000000fb, 0x000000fc, 0x000000fd, 0x000200f8, 0x000000fc, + 0x000200f9, 0x000000d6, 0x000200f8, 0x000000fd, 0x0004003d, 0x00000086, 0x00000100, 0x00000088, + 0x0007004f, 0x00000007, 0x00000104, 0x000000aa, 0x000000aa, 0x00000000, 0x00000001, 0x00050085, + 0x00000007, 0x00000105, 0x0000019b, 0x00000104, 0x0004006e, 0x00000064, 0x00000106, 0x00000105, + 0x00040064, 0x00000085, 0x00000107, 0x00000100, 0x0007005f, 0x00000026, 0x00000108, 0x00000107, + 0x00000106, 0x00000002, 0x0000002b, 0x00050051, 0x00000006, 0x00000109, 0x00000108, 0x00000000, + 0x00050085, 0x00000006, 0x0000010c, 0x00000109, 0x0000009b, 0x00050083, 0x00000006, 0x00000112, + 0x00000188, 0x0000010c, 0x00050085, 0x00000006, 0x00000117, 0x0000009c, 0x00000116, 0x00050081, + 0x00000006, 0x00000118, 0x00000114, 0x00000117, 0x000500ba, 0x0000006e, 0x00000119, 0x00000112, + 0x00000118, 0x000500b8, 0x0000006e, 0x0000011c, 0x00000112, 0x000000c4, 0x000500a7, 0x0000006e, + 0x0000011d, 0x00000119, 0x0000011c, 0x000300f7, 0x0000011f, 0x00000000, 0x000400fa, 0x0000011d, + 0x0000011e, 0x0000011f, 0x000200f8, 0x0000011e, 0x0004006f, 0x00000006, 0x00000121, 0x000001a6, + 0x00050085, 0x00000006, 0x00000122, 0x00000121, 0x000001b0, 0x00050083, 0x00000006, 0x00000123, + 0x0000001d, 0x00000122, 0x000200f9, 0x000000d6, 0x000200f8, 0x0000011f, 0x000200f9, 0x000000d7, + 0x000200f8, 0x000000d7, 0x00050080, 0x0000002a, 0x00000126, 0x000001a6, 0x000000b4, 0x00050081, + 0x00000006, 0x00000129, 0x000001a7, 0x000000c8, 0x000200f9, 0x000000d4, 0x000200f8, 0x000000d6, + 0x000b00f5, 0x00000006, 0x000001aa, 0x0000008f, 0x000000d4, 0x0000008f, 0x000000e8, 0x0000008f, + 0x000000fc, 0x00000123, 0x0000011e, 0x0008000c, 0x00000006, 0x0000012d, 0x00000001, 0x00000031, + 0x0000012b, 0x0000009e, 0x0000009c, 0x00050083, 0x00000006, 0x0000012e, 0x0000001d, 0x0000012d, + 0x00060041, 0x0000002c, 0x00000130, 0x00000029, 0x0000002b, 0x000000b5, 0x0004003d, 0x00000006, + 0x00000131, 0x00000130, 0x00050085, 0x00000006, 0x00000133, 0x00000131, 0x000001aa, 0x00050085, + 0x00000006, 0x00000135, 0x00000133, 0x0000012e, 0x00050083, 0x00000006, 0x00000136, 0x0000001d, + 0x00000135, 0x00060041, 0x0000002c, 0x00000138, 0x00000029, 0x00000137, 0x00000021, 0x0004003d, + 0x00000006, 0x00000139, 0x00000138, 0x000500ba, 0x0000006e, 0x0000013a, 0x00000139, 0x00000043, + 0x000300f7, 0x0000013c, 0x00000000, 0x000400fa, 0x0000013a, 0x0000013b, 0x0000013c, 0x000200f8, + 0x0000013b, 0x0004003d, 0x0000013d, 0x00000140, 0x0000013f, 0x00070050, 0x00000026, 0x00000143, + 0x00000136, 0x00000136, 0x00000136, 0x0000001d, 0x00040063, 0x00000140, 0x0000006d, 0x00000143, + 0x000200f9, 0x0000015d, 0x000200f8, 0x0000013c, 0x000500be, 0x0000006e, 0x00000146, 0x00000136, + 0x00000092, 0x000300f7, 0x00000148, 0x00000000, 0x000400fa, 0x00000146, 0x00000147, 0x00000148, + 0x000200f8, 0x00000147, 0x000200f9, 0x0000015d, 0x000200f8, 0x00000148, 0x0004003d, 0x0000013d, + 0x0000014c, 0x0000013f, 0x00050062, 0x00000026, 0x0000014e, 0x0000014c, 0x0000006d, 0x0004003d, + 0x0000013d, 0x0000014f, 0x0000013f, 0x0008004f, 0x0000000a, 0x00000152, 0x0000014e, 0x0000014e, + 0x00000000, 0x00000001, 0x00000002, 0x0005008e, 0x0000000a, 0x00000154, 0x00000152, 0x00000136, + 0x00050051, 0x00000006, 0x00000156, 0x0000014e, 0x00000003, 0x00050051, 0x00000006, 0x00000157, + 0x00000154, 0x00000000, 0x00050051, 0x00000006, 0x00000158, 0x00000154, 0x00000001, 0x00050051, + 0x00000006, 0x00000159, 0x00000154, 0x00000002, 0x00070050, 0x00000026, 0x0000015a, 0x00000157, + 0x00000158, 0x00000159, 0x00000156, 0x00040063, 0x0000014f, 0x0000006d, 0x0000015a, 0x000200f9, + 0x0000015d, 0x000200f8, 0x0000015d, 0x000100fd, 0x00010038, +}; diff --git a/runtime/gfx_window.c b/runtime/gfx_window.c index f62de225..38f6476f 100644 --- a/runtime/gfx_window.c +++ b/runtime/gfx_window.c @@ -920,6 +920,7 @@ void gfx_window_release_vk(void) { g_flip_on = 0; // its blit is done (device idle); the swapchain goes away unpresented menu_vk_release(); vk_fsr_release(); + vk_contact_release(); free_capture(); free_thumbs(); for (int i = 0; i < FRAMES; i++) { diff --git a/runtime/shaders/contact_shadow.comp b/runtime/shaders/contact_shadow.comp new file mode 100644 index 00000000..78828bb4 --- /dev/null +++ b/runtime/shaders/contact_shadow.comp @@ -0,0 +1,67 @@ +#version 450 +// Screen-space contact shadows (runtime/vk_contact.c). Each pixel of the game's lit scene colour marches a short way +// toward the sun through the linear depth target; when the ray passes behind something close in front of it, the pixel +// is in a contact shadow the shadow maps are too coarse to show, and its colour is darkened. +layout(local_size_x = 8, local_size_y = 8) in; + +layout(binding = 0) uniform sampler2D lin_depth; // the game's linear depth: view distance / far +layout(binding = 1, r11f_g11f_b10f) uniform image2D scene; // the lit scene colour, darkened in place + +layout(push_constant) uniform Params { + vec4 proj; // projection x scale, y scale, far plane, strength (0..1) + vec4 light; // view-space direction toward the sun (xyz), march length in metres at 10 m (w) + vec4 size; // width, height, 1/width, 1/height + vec4 opt; // x: debug (1: write the shadow factor as grey) +} pc; + +vec3 view_pos(vec2 uv, float z) { // z: distance in front of the camera + vec2 ndc = uv * 2.0 - 1.0; + return vec3(ndc.x * z / pc.proj.x, -ndc.y * z / pc.proj.y, -z); +} + +vec2 to_uv(vec3 p) { + float z = -p.z; + return vec2(0.5 + 0.5 * p.x * pc.proj.x / z, 0.5 - 0.5 * p.y * pc.proj.y / z); +} + +float ign(vec2 px) { // interleaved gradient noise: a per-pixel start offset that hides the step pattern + return fract(52.9829189 * fract(dot(px, vec2(0.06711056, 0.00583715)))); +} + +void main() { + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + if (px.x >= int(pc.size.x) || px.y >= int(pc.size.y)) return; + float d = texelFetch(lin_depth, px, 0).x; + if (d <= 0.0 || d >= 0.999) return; // nothing drawn, or the sky + float z = d * pc.proj.z; + if (z > 80.0) return; + vec2 uv = (vec2(px) + 0.5) * pc.size.zw; + vec3 p = view_pos(uv, z); + // the march grows with distance, as one pixel covers more ground; thickness keeps thin blades from hiding the sky + float len = pc.light.w * clamp(z / 10.0, 0.4, 3.0); + float thick = 0.15 + z * 0.01; + const int STEPS = 16; + float step_len = len / float(STEPS), t = step_len * (0.25 + ign(vec2(px))); + float occ = 0.0; + for (int i = 0; i < STEPS; i++, t += step_len) { + vec3 q = p + pc.light.xyz * t; + if (q.z >= -0.05) break; + vec2 quv = to_uv(q); + if (any(lessThan(quv, vec2(0.0))) || any(greaterThan(quv, vec2(1.0)))) break; + float sz = texelFetch(lin_depth, ivec2(quv * pc.size.xy), 0).x * pc.proj.z; + float delta = -q.z - sz; // how far the scene at that pixel is in front of the ray point + if (delta > 0.02 + z * 0.002 && delta < thick) { + occ = 1.0 - float(i) / float(STEPS); // a hit close to the pixel shadows more than one at the end + break; + } + } + float fade = 1.0 - smoothstep(40.0, 80.0, z); + float k = 1.0 - pc.proj.w * occ * fade; + if (pc.opt.x > 0.5) { + imageStore(scene, px, vec4(k, k, k, 1.0)); + return; + } + if (k >= 0.999) return; + vec4 c = imageLoad(scene, px); + imageStore(scene, px, vec4(c.rgb * k, c.a)); +} diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index d3eb04f9..b82f9f2a 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -550,6 +550,7 @@ static void tab_screen(float scale) { row_aniso(); row_shadow_scale(); row_shadow_range(); + opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%"); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index d279674a..91228692 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -70,6 +70,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Shadow resolution", [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " "sharper shadow edges and leaf shadows. Takes effect at the next start.", + [UI_MENU_CONTACT_SHADOWS] = "Contact shadows", + [UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. " + "Traced on the screen after lighting. Takes effect at the next start.", [UI_MENU_SHADOW_RANGE] = "Shadow cascade range", [UI_MENU_SHADOW_RANGE_DESC] = "Moves the steps where shadows turn softer (the game's 20, 40, 80 and 160 m) further " "away. Spreads the shadow map over more ground: raise Shadow resolution with it. " @@ -299,6 +302,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Разрешение теней", [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", + [UI_MENU_CONTACT_SHADOWS] = "Контактные тени", + [UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и " + "складках. Считаются по экрану после освещения. Действует после перезапуска.", [UI_MENU_SHADOW_RANGE] = "Дальность каскадов теней", [UI_MENU_SHADOW_RANGE_DESC] = "Отодвигает границы, за которыми тени становятся мягче (в игре 20, 40, 80 и 160 м). " "Карта теней растягивается на большую площадь, поэтому вместе с этим поднимайте " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 7462a703..eb0e09cf 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -39,6 +39,7 @@ typedef enum { UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, + UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/runtime/vk.h b/runtime/vk.h index fdfaf319..94c2b62c 100644 --- a/runtime/vk.h +++ b/runtime/vk.h @@ -87,6 +87,9 @@ void vk_present_blit(VkImage src, VkImageLayout layout, VkFormat fmt, int w, int int vk_fsr_record(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, int sw, int sh, const int crop[4], VkImage dst, uint32_t dw, uint32_t dh); void vk_fsr_release(void); // before the device goes away +// vk_contact.c: screen-space contact shadows on the game's composed scene colour (TOTK_CONTACT_SHADOWS) +int vk_contact_strength(void); // percent, 0 = off +void vk_contact_release(void); // before the device goes away void vk_present_flip(void); // Every submission to ctx->gfx_queue (and xfer_queue when shared) takes this lock; vk_present_image and the swapchain // rebuild do. Recursive. diff --git a/runtime/vk_contact.c b/runtime/vk_contact.c new file mode 100644 index 00000000..74eae718 --- /dev/null +++ b/runtime/vk_contact.c @@ -0,0 +1,188 @@ +// Screen-space contact shadows (TOTK_CONTACT_SHADOWS, percent strength, 0 = off). TotK fills a full-resolution +// G-buffer whose targets include a B10G11R11 scene colour, an R32F linear depth (view distance / far) and a D32F depth +// (is_gbuffer), lights it in half resolution, and then composites the lighting into that scene colour in one pass +// whose only target is the scene colour, with a D16 depth that sorts pixels into material classes (is_composite). +// When the pass after the composite begins, or a dispatch or copy comes first, runtime/shaders/contact_shadow.comp +// marches each pixel a short way toward the sun through the linear depth and darkens the scene colour where the ray +// passes behind nearby geometry: the small shadows at feet, under stones and in grass that the shadow maps are too +// coarse for. Transparent surfaces, the sky and post-processing come after, untouched. +// +// Inputs from the game, read from the fragment stage's uniform block c4 bound in the composite pass (guest memory, +// so it may be one frame newer than the replay): the projection scales c4[7].x and c4[8].y, the far plane c4[14].y, +// and the first sun cascade's depth row c4[44].xyz, whose negated direction points from a view-space position toward +// the sun (the G-buffer shaders compare dot(c4[44].xyz, pos) + c4[44].w with the cascade map). The scene colour images +// get STORAGE usage when the setting is on (vk_texture.c create_tex). +#include "vk.h" + +#include +#include + +#include "cfg.h" +#include "contact_shadow_spv.h" +#include "host.h" +#include "vk_exec.h" + +static struct { + int tried, ok, strength, debug, logged; + PFN_vkCmdPushDescriptorSetKHR push; + VkDescriptorSetLayout dsl; + VkPipelineLayout layout; + VkPipeline pipe; + VkSampler sampler; + const VkTexImage *scene, *depth; // the last G-buffer's scene colour and linear depth + uint32_t w, h; + int pending; // the composite into scene ran; the march waits for the next pass + uint64_t c4; +} C; + +int vk_contact_strength(void) { + if (!C.tried) { + int s = cfg_int("TOTK_CONTACT_SHADOWS"); + C.strength = s < 0 ? 0 : s > 100 ? 100 : s; + } + return C.strength; +} + +static int init(VkCtx *c) { + C.tried = 1; + vk_contact_strength(); + if (!C.strength) return 0; + const char *e = cfg_get("TOTK_CONTACT_DEBUG"); // 1: the frame shows the contact shadow factor in grey + C.debug = e && *e && strcmp(e, "0"); + C.push = (PFN_vkCmdPushDescriptorSetKHR)vkGetDeviceProcAddr(c->device, "vkCmdPushDescriptorSetKHR"); + VkDescriptorSetLayoutBinding b[2] = { + {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}, + {.binding = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}}; + VkDescriptorSetLayoutCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, + .bindingCount = 2, .pBindings = b}; + VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, 64}; + VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, + .pSetLayouts = &C.dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr}; + VkSamplerCreateInfo si = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_NEAREST, + .minFilter = VK_FILTER_NEAREST, .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .maxLod = 0}; + VkShaderModuleCreateInfo mi = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof contact_shadow_spv, .pCode = contact_shadow_spv}; + VkShaderModule m = VK_NULL_HANDLE; + if (!C.push || vkCreateDescriptorSetLayout(c->device, &dci, NULL, &C.dsl) != VK_SUCCESS || + vkCreatePipelineLayout(c->device, &li, NULL, &C.layout) != VK_SUCCESS || + vkCreateSampler(c->device, &si, NULL, &C.sampler) != VK_SUCCESS || + vkCreateShaderModule(c->device, &mi, NULL, &m) != VK_SUCCESS) { + rt_log("vk: contact shadows off: their pipeline could not be created"); + return 0; + } + VkComputePipelineCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = m, .pName = "main"}, + .layout = C.layout}; + VkResult r = vkCreateComputePipelines(c->device, VK_NULL_HANDLE, 1, &ci, NULL, &C.pipe); + vkDestroyShaderModule(c->device, m, NULL); + if (r != VK_SUCCESS) { + rt_log("vk: contact shadows off: their pipeline could not be created"); + return 0; + } + rt_log("vk: contact shadows on, strength %d%%%s", C.strength, C.debug ? " (debug view)" : ""); + return C.ok = 1; +} + +// A G-buffer pass: a B10G11R11 scene colour, an R32F linear depth and a D32F depth, all one size, at least 640 wide. +static int is_gbuffer(const VkExec *ex, const VkTexImage **scene, const VkTexImage **depth) { + *scene = *depth = NULL; + if (ex->pass_noatt || ex->pass_w < 640 || ex->depth.format != VK_FORMAT_D32_SFLOAT || ex->depth.level) return 0; + for (uint32_t i = 0; i < ex->pass_ncolor && i < 8; i++) { + const VkExecTarget *t = &ex->color[i]; + if (!t->image || t->level || t->width != ex->pass_w || t->height != ex->pass_h) continue; + if (t->format == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && !*scene) *scene = t->img; + if (t->format == VK_FORMAT_R32_SFLOAT && !*depth) *depth = t->img; + } + return *scene && *depth && ((*scene)->usage & VK_IMAGE_USAGE_STORAGE_BIT); +} + +static void mem_barrier(VkCommandBuffer cb) { + VkMemoryBarrier2 mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT}; + VkDependencyInfo d = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &mb}; + vkCmdPipelineBarrier2(cb, &d); +} + +void vk_contact_flush(VkExec *ex) { + if (!C.pending) return; + C.pending = 0; + if (ex->in_pass) return; + const float *u = (const float *)(uintptr_t)C.c4; + float lx = -u[44 * 4 + 0], ly = -u[44 * 4 + 1], lz = -u[44 * 4 + 2], ll = sqrtf(lx * lx + ly * ly + lz * lz); + float px = u[7 * 4 + 0], py = u[8 * 4 + 1], zfar = u[14 * 4 + 1]; + if (!(ll > 1e-6f) || !(px > 0) || !(py > 0) || !(zfar > 1)) return; + VkImageView in = vk_exec_target_view(C.depth, VK_FORMAT_R32_SFLOAT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT, + 0, 0, 1, 0); + VkImageView out = vk_exec_target_view(C.scene, VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_VIEW_TYPE_2D, + VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1, 0); + if (!in || !out) return; + VkCommandBuffer cb = ex->cb; + float pcv[16] = {px, py, zfar, (float)C.strength / 100.0f, + lx / ll, ly / ll, lz / ll, 0.6f, + (float)C.w, (float)C.h, 1.0f / (float)C.w, 1.0f / (float)C.h, + (float)C.debug, 0, 0, 0}; + if (!C.logged) { + C.logged = 1; + rt_log("vk: contact shadows on a %ux%u scene, sun toward %.3f %.3f %.3f (view space), far %g", C.w, C.h, + pcv[4], pcv[5], pcv[6], zfar); + } + mem_barrier(cb); // the compose passes' writes, before the march reads and writes them + VkDescriptorImageInfo ii = {C.sampler, in, VK_IMAGE_LAYOUT_GENERAL}, oi = {VK_NULL_HANDLE, out, VK_IMAGE_LAYOUT_GENERAL}; + VkWriteDescriptorSet w[2] = { + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ii}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi}}; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.pipe); + rec_push(C.push, cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.layout, 0, 2, w); + vkCmdPushConstants(cb, C.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pcv, pcv); + vkCmdDispatch(cb, (C.w + 7) / 8, (C.h + 7) / 8, 1); + mem_barrier(cb); // and what follows sees the darkened colour + ex->recorded += 6; + vk_exec_draw_new_cb(); // the game's bound compute pipeline and descriptors were replaced: bind them again +} + +// The lighting composite: the remembered scene colour as the only target, with a D16 depth of its size. +static int is_composite(const VkExec *ex) { + return C.scene && ex->pass_ncolor >= 1 && ex->color[0].img == C.scene && !ex->color[0].level && + ex->depth.format == VK_FORMAT_D16_UNORM && ex->pass_w == C.w && ex->pass_h == C.h; +} + +void vk_contact_pass_begin(VkExec *ex) { + if (!C.tried && !init(vk_ctx())) return; + if (!C.ok) return; + const VkTexImage *scene, *depth; + // The camera block: c4 of the fragment stage, 0x940 bytes. The composite binds it only after its pass begins, so + // the newest one seen at any pass start serves. + const p_bind_buf *b = &ex->ubo[1][1]; + if (b->addr && b->size == 0x940) C.c4 = b->addr; + if (is_gbuffer(ex, &scene, &depth)) { + C.pending = 0; + C.scene = scene, C.depth = depth, C.w = ex->pass_w, C.h = ex->pass_h; + return; + } + if (is_composite(ex)) { + C.pending = C.c4 != 0; + return; + } + vk_contact_flush(ex); +} + +void vk_contact_release(void) { + VkCtx *c = vk_ctx(); + if (!c || !C.tried) return; + if (C.pipe) vkDestroyPipeline(c->device, C.pipe, NULL); + if (C.sampler) vkDestroySampler(c->device, C.sampler, NULL); + if (C.layout) vkDestroyPipelineLayout(c->device, C.layout, NULL); + if (C.dsl) vkDestroyDescriptorSetLayout(c->device, C.dsl, NULL); + memset(&C, 0, sizeof C); +} diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index 0abd2b63..fb227f01 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -422,6 +422,7 @@ void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); } void vk_exec_pass_begin(VkExec *ex) { if (ex->in_pass) return; resolve_rt(ex); + vk_contact_pass_begin(ex); // Learned targets (VkTexImage.fb_learned) are attached in the feedback layout VkImage want[9]; VkImageAspectFlags wasp[9]; diff --git a/runtime/vk_exec.h b/runtime/vk_exec.h index b0095f63..c4f9182e 100644 --- a/runtime/vk_exec.h +++ b/runtime/vk_exec.h @@ -176,6 +176,9 @@ VkImageView vk_exec_target_view(const VkTexImage *img, VkFormat format, VkImageV // vk_exec_xfer.c: OP_COPY_B2B, OP_COPY_B2T, OP_COPY_T2B, OP_COPY_T2T, OP_CLEAR_TEX, OP_SIGNAL_EVENT, OP_REPORT_COUNTER, // OP_RESET_COUNTER, OP_RENDER_ENABLE, OP_RENDER_COND, OP_CLEAR_BUF. void vk_exec_op_xfer(VkExec *ex, uint32_t op, const void *payload); +// vk_contact.c: a pass about to begin (its targets resolved, no pass open), and a dispatch or copy about to be recorded +void vk_contact_pass_begin(VkExec *ex); +void vk_contact_flush(VkExec *ex); // vk_exec_xfer.c, samples-passed counting: a draw about to be recorded in the open pass (begins an occlusion query // when counting and none is active), and the open pass about to end (ends the active query). void vk_exec_oq_draw(VkExec *ex); diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index e23741e9..124ebbc8 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -2069,6 +2069,7 @@ static void op_draw_idx_ind(VkExec *ex, const p_draw_idx_ind *d) { static void op_dispatch(VkExec *ex, const p_dispatch *d) { if (d->x <= 0 || d->y <= 0 || d->z <= 0) return; if (!ex->prog) return warn_once(W_PROGRAM, "a dispatch without a bound program is skipped"); + vk_contact_flush(ex); cb_res(ex); dummies_init(); int present; diff --git a/runtime/vk_exec_xfer.c b/runtime/vk_exec_xfer.c index ffb3b420..06602742 100644 --- a/runtime/vk_exec_xfer.c +++ b/runtime/vk_exec_xfer.c @@ -592,6 +592,7 @@ static void clear_tex(VkExec *ex, const p_clear_tex *p) { } void vk_exec_op_xfer(VkExec *ex, uint32_t op, const void *payload) { + if (op != OP_RENDER_ENABLE && op != OP_SIGNAL_EVENT) vk_contact_flush(ex); switch (op) { case OP_COPY_B2B: copy_b2b(ex, payload); break; case OP_COPY_B2T: copy_buffer_image(ex, payload, 1); break; diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index e2fda908..ce7619f7 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -341,6 +341,10 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { if (!ds && (ff & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if ((d->flags & NVN_TEXTURE_FLAGS_IMAGE) && (ff & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) && samples == 1) usage |= VK_IMAGE_USAGE_STORAGE_BIT; + // contact shadows (vk_contact.c) darken the game's B10G11R11 scene colour in place from a compute shader + if (f.vk == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) && samples == 1 && + (ff & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) && w >= 640 && vk_contact_strength()) + usage |= VK_IMAGE_USAGE_STORAGE_BIT; VkImageCreateFlags flags = ds ? 0 : VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; // format-reinterpreting views if (type == VK_IMAGE_TYPE_2D && layers >= 6 && w == h && samples == 1) flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; // NVN renders into a 3D texture slice by slice (a view's min layer is the depth plane, nvn_mtl.m), e.g. the diff --git a/totk.ini.example b/totk.ini.example index d8744e73..07042f86 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -125,6 +125,10 @@ # Sun shadow cascade range in percent of the game's (its cascades end at 20, 40, 80 and 160 m), 50 to 400: higher moves # the steps where shadows turn softer further away, and spreads the shadow map over more ground. Read at start. # shadow_range = 100 +# Screen-space contact shadows, strength in percent (0 = off): after the game lights its scene, each pixel traces a +# short way toward the sun through the depth buffer and darkens where something close blocks it, adding the small +# shadows at feet, under stones and in grass that the shadow maps miss. Read at start. +# contact_shadows = 0 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 24571ec0b0f7b09c9a31f9eaf45f74ce9710c77d Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:00:23 +0100 Subject: [PATCH 04/19] Add soft sun shadows (PCSS) through a translator patch The deferred lighting shaders take the sun shadow as four explicit-LOD compares on the cascade array. Translator patch 0010 turns every explicit-LOD compare on a 2D array texture into a PCSS lookup when the support buffer's new pcss field has x above 0: eight raw depth fetches within pcss.w find the blockers, (receiver - blocker) * pcss.x gives the penumbra width clamped to pcss.y..pcss.z, and eight compares on a disc of that radius average to the result. With x at 0 the original single compare runs behind a branch. Radii are in UV, so they hold at any shadow_scale. The support buffer grows to 1424 bytes; support_fill writes the field from pcss (percent of the default width, 0 to 200, default 0; TOTK_PCSS_K overrides the factor at 100 percent, default 0.5). build_xlate.py expects ten patches. The setting is in totk.ini.example and on the Screen tab of the menu (English and Russian). Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 5 +- runtime/ui/menu.cpp | 1 + runtime/ui_text.c | 6 + runtime/ui_text.h | 1 + runtime/vk_exec_draw.c | 22 ++- tools/build_xlate.py | 6 +- .../0010-pcss-for-cascade-compares.patch | 135 ++++++++++++++++++ totk.ini.example | 4 + 8 files changed, 174 insertions(+), 6 deletions(-) create mode 100644 tools/xlate/patches/0010-pcss-for-cascade-compares.patch diff --git a/runtime/cfg.c b/runtime/cfg.c index 2372ad1b..bc7da7dd 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -41,7 +41,7 @@ static const char *const known[] = { "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", "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", + "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PCSS", "PCSS_K", "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", "REEXEC", "RENDER_SCALE", "REPLAY_ASYNC", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -95,6 +95,7 @@ static const CfgMeta metas[] = { {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, {"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART}, + {"PCSS", "0", "0..200", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index b82f9f2a..3553f058 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -550,6 +550,7 @@ static void tab_screen(float scale) { row_aniso(); row_shadow_scale(); row_shadow_range(); + opt_slider("TOTK_PCSS", UI_MENU_PCSS, 0, 200, UI_MENU_PCSS_DESC, 10, "%.0f %%"); opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%"); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 91228692..056c0e4d 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -70,6 +70,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Shadow resolution", [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " "sharper shadow edges and leaf shadows. Takes effect at the next start.", + [UI_MENU_PCSS] = "Soft shadows", + [UI_MENU_PCSS_DESC] = "Sun shadows sharp where an object meets the ground and softer the further the shadow falls " + "(PCSS). 0 keeps the game's filter. Takes effect at the next start.", [UI_MENU_CONTACT_SHADOWS] = "Contact shadows", [UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. " "Traced on the screen after lighting. Takes effect at the next start.", @@ -302,6 +305,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Разрешение теней", [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", + [UI_MENU_PCSS] = "Мягкие тени", + [UI_MENU_PCSS_DESC] = "Тени от солнца резкие там, где предмет касается земли, и мягче, чем дальше падает тень " + "(PCSS). 0 оставляет фильтр игры. Действует после перезапуска.", [UI_MENU_CONTACT_SHADOWS] = "Контактные тени", [UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и " "складках. Считаются по экрану после освещения. Действует после перезапуска.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index eb0e09cf..599cd34a 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -40,6 +40,7 @@ typedef enum { UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC, + UI_MENU_PCSS, UI_MENU_PCSS_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 124ebbc8..4f7276d0 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -32,7 +32,7 @@ #define MAX_DESC 1024 #define CHUNK_BYTES (4u << 20) #define ZERO_BYTES 65536u -#define SUPPORT_BYTES 1408u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... +#define SUPPORT_BYTES 1424u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... #define NVN_STAGE_VS 0 #define NVN_STAGE_FS 1 #define NVN_STAGE_CS 5 @@ -1246,6 +1246,25 @@ static void support_in(const VkExec *ex, float in[3]) { // what support_fill r in[2] = ex->point_size > 0 ? ex->point_size : 1.0f; } +// TOTK_PCSS (percent, 0 = off): the pcss field of the support buffer, which translator patch 0010 reads in every +// explicit-LOD compare on a 2D array texture (the sun cascades). x: penumbra width in UV per unit of light-space depth +// between receiver and blocker (0 keeps the game's single compare), y and z: the narrowest and widest disc radius, +// w: the blocker search radius, all in UV of the cascade map. Radii are in UV, so they hold at any TOTK_SHADOW_SCALE. +// TOTK_PCSS_K overrides the depth-to-penumbra factor at 100 percent, for tuning. +static const float *pcss_params(void) { + static float p[4] = {-1, 0, 0, 0}; + if (p[0] < 0) { + int pct = cfg_int("TOTK_PCSS"); + pct = pct < 0 ? 0 : pct > 200 ? 200 : pct; + const char *k = cfg_get("TOTK_PCSS_K"); + float k100 = k && *k ? (float)atof(k) : 0.5f; + p[0] = k100 * (float)pct / 100.0f; + p[1] = 0.35f / 960.0f, p[2] = 5.0f / 960.0f, p[3] = 4.0f / 960.0f; + if (pct) rt_log("vk: soft shadows (PCSS) at %d%% (depth factor %g)", pct, p[0]); + } + return p; +} + static void support_fill(uint8_t *b, float w, float h, float point_size) { memset(b, 0, SUPPORT_BYTES); float inv[4] = {w > 0 ? 2.0f / w : 0, h > 0 ? 2.0f / h : 0, 0, 0}, size[4] = {w, h, 0, 0}; @@ -1253,6 +1272,7 @@ static void support_fill(uint8_t *b, float w, float h, float point_size) { memcpy(b + 160, size, 16); const float one = 1.0f; memcpy(b + 1392, &point_size, 4); // point_size (translator patch 0008): vertex shaders that write none output it + memcpy(b + 1408, pcss_params(), 16); // pcss (translator patch 0010): soft sun shadows in the cascade compares for (int i = 0; i < 73; i++) memcpy(b + 192 + 16 * i, &one, 4); // render scale 1: the host renders at guest size } diff --git a/tools/build_xlate.py b/tools/build_xlate.py index eb455ab4..ef0d08bc 100644 --- a/tools/build_xlate.py +++ b/tools/build_xlate.py @@ -1,7 +1,7 @@ """Build the shader translator: build/xlate/totk_xlate.exe (Ryujinx 1.3.2 + patches, NativeAOT, SPIR-V for Vulkan). Copies tools/vendor/ryujinx to build/xlate/ryujinx, applies tools/xlate/patches/*.patch there (tools/vendor stays -byte-identical; 0001-0004 are MNG's, 0005-0009 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build +byte-identical; 0001-0004 are MNG's, 0005-0010 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build tools and vswhere.exe (docs/building.md). Run with .venv. Next to the exe it writes totk_xlate.id: the translator identity, a sha256 over everything the build reads (this script, @@ -96,8 +96,8 @@ def prepare_sources() -> Path: for junk in list(src.glob("src/*/obj")) + list(src.glob("src/*/bin")): shutil.rmtree(junk) patches = sorted((XLATE / "patches").glob("*.patch")) - if len(patches) != 9: - sys.exit(f"expected 9 patches, found {len(patches)}") + if len(patches) != 10: + sys.exit(f"expected 10 patches, found {len(patches)}") for patch in patches: # git apply works outside a repository when given a directory; --check first so a failure names the patch. for extra in (["--check"], []): diff --git a/tools/xlate/patches/0010-pcss-for-cascade-compares.patch b/tools/xlate/patches/0010-pcss-for-cascade-compares.patch new file mode 100644 index 00000000..4f41aaae --- /dev/null +++ b/tools/xlate/patches/0010-pcss-for-cascade-compares.patch @@ -0,0 +1,135 @@ +--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs ++++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs +@@ -1456,7 +1456,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv + } + else if (isShadow) + { +- if (hasLodLevel) ++ if (hasLodLevel && isArray && coordsCount == 2 && operandsMask == ImageOperandsMask.Lod) ++ { ++ result = GeneratePcssSample(context, declaration, image, pCoords, dRef, lod); ++ } ++ else if (hasLodLevel) + { + result = context.ImageSampleDrefExplicitLod(resultType, image, pCoords, dRef, operandsMask, operands); + } +@@ -1486,6 +1490,92 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv + return new OperationResult(swizzledResultType, result); + } + ++ // TOTK: percentage-closer soft shadows for the sun. The deferred lighting shaders take the shadow as four ++ // explicit-LOD compares on a 2D array (the cascades) around the receiver; each of those becomes a PCSS lookup ++ // when the support buffer's pcss.x is above 0 (runtime/vk_exec_draw.c support_fill, TOTK_PCSS): a blocker ++ // search reads the raw depths at eight points within pcss.w (UV), the average depth of those nearer the light ++ // than the receiver gives the penumbra width (receiver - blocker) * pcss.x, clamped to pcss.y..pcss.z (UV), and ++ // eight compares on a disc of that radius average to the result. With pcss.x at 0 the original single compare ++ // runs. The cascades are orthographic, so the depth difference is a distance along the light. ++ private static readonly float[] PcssSearch = [-0.7f, -0.7f, 0.7f, -0.7f, -0.7f, 0.7f, 0.7f, 0.7f, 0f, -1f, 0f, 1f, -1f, 0f, 1f, 0f]; ++ private static readonly float[] PcssDisk = ++ [ ++ -0.9420f, -0.3991f, 0.9456f, -0.7689f, -0.0942f, -0.9294f, 0.3450f, 0.2939f, ++ -0.9159f, 0.4577f, -0.8154f, -0.8791f, -0.3828f, 0.2768f, 0.9748f, 0.7565f, ++ ]; ++ ++ private static SpvInstruction GeneratePcssSample(CodeGenContext context, SamplerDeclaration declaration, SpvInstruction image, ++ SpvInstruction pCoords, SpvInstruction dRef, SpvInstruction lod) ++ { ++ SpvInstruction f32 = context.TypeFP32(), s32 = context.TypeS32(), b = context.TypeBool(); ++ SpvInstruction v2 = context.TypeVector(f32, 2), v3 = context.TypeVector(f32, 3), v4 = context.TypeVector(f32, 4); ++ SpvInstruction iv2 = context.TypeVector(s32, 2), iv3 = context.TypeVector(s32, 3); ++ SpvInstruction zero = context.Constant(f32, 0f), one = context.Constant(f32, 1f); ++ ++ SpvInstruction prmPtr = context.AccessChain(context.TypePointer(StorageClass.Uniform, v4), context.ConstantBuffers[SupportBuffer.Binding], ++ context.Constant(s32, (int)SupportBufferField.Pcss)); ++ SpvInstruction prm = context.Load(v4, prmPtr); ++ SpvInstruction lightSize = context.CompositeExtract(f32, prm, 0); ++ SpvInstruction minR = context.CompositeExtract(f32, prm, 1); ++ SpvInstruction maxR = context.CompositeExtract(f32, prm, 2); ++ SpvInstruction searchR = context.CompositeExtract(f32, prm, 3); ++ ++ SpvInstruction pcssLabel = context.Label(), plainLabel = context.Label(), mergeLabel = context.Label(); ++ SpvInstruction enabled = context.FOrdGreaterThan(b, lightSize, zero); // before the merge: it must precede the branch ++ context.SelectionMerge(mergeLabel, SelectionControlMask.MaskNone); ++ context.BranchConditional(enabled, pcssLabel, plainLabel); ++ ++ context.AddLabel(plainLabel); ++ SpvInstruction plain = context.ImageSampleDrefExplicitLod(f32, image, pCoords, dRef, ImageOperandsMask.Lod, lod); ++ context.Branch(mergeLabel); ++ ++ context.AddLabel(pcssLabel); ++ SpvInstruction raw = context.Image(declaration.ImageType, image); ++ SpvInstruction size3 = context.ImageQuerySizeLod(iv3, raw, context.Constant(s32, 0)); ++ SpvInstruction sizeI = context.VectorShuffle(iv2, size3, size3, 0, 1); ++ SpvInstruction sizeF = context.ConvertSToF(v2, sizeI); ++ SpvInstruction maxI = context.ISub(iv2, sizeI, context.ConstantComposite(iv2, context.Constant(s32, 1), context.Constant(s32, 1))); ++ SpvInstruction zeroI = context.ConstantComposite(iv2, context.Constant(s32, 0), context.Constant(s32, 0)); ++ SpvInstruction uv = context.VectorShuffle(v2, pCoords, pCoords, 0, 1); ++ SpvInstruction layerF = context.CompositeExtract(f32, pCoords, 2); ++ SpvInstruction layerI = context.ConvertFToS(s32, layerF); ++ SpvInstruction searchV = context.CompositeConstruct(v2, searchR, searchR); ++ ++ SpvInstruction sum = zero, count = zero; ++ for (int i = 0; i < PcssSearch.Length; i += 2) ++ { ++ SpvInstruction off = context.ConstantComposite(v2, context.Constant(f32, PcssSearch[i]), context.Constant(f32, PcssSearch[i + 1])); ++ SpvInstruction p = context.FAdd(v2, uv, context.FMul(v2, off, searchV)); ++ SpvInstruction t = context.GlslSClamp(iv2, context.ConvertFToS(iv2, context.FMul(v2, p, sizeF)), zeroI, maxI); ++ SpvInstruction c = context.CompositeConstruct(iv3, context.CompositeExtract(s32, t, 0), context.CompositeExtract(s32, t, 1), layerI); ++ SpvInstruction d = context.CompositeExtract(f32, context.ImageFetch(v4, raw, c, ImageOperandsMask.Lod, context.Constant(s32, 0)), 0); ++ SpvInstruction blocker = context.FOrdLessThan(b, d, dRef); ++ sum = context.FAdd(f32, sum, context.Select(f32, blocker, d, zero)); ++ count = context.FAdd(f32, count, context.Select(f32, blocker, one, zero)); ++ } ++ ++ SpvInstruction avg = context.FDiv(f32, sum, context.GlslFMax(f32, count, one)); ++ SpvInstruction penumbra = context.Select(f32, context.FOrdGreaterThan(b, count, zero), ++ context.FMul(f32, context.FSub(f32, dRef, avg), lightSize), zero); ++ SpvInstruction radius = context.GlslFClamp(f32, penumbra, minR, maxR); ++ SpvInstruction radiusV = context.CompositeConstruct(v2, radius, radius); ++ ++ SpvInstruction acc = zero; ++ for (int i = 0; i < PcssDisk.Length; i += 2) ++ { ++ SpvInstruction off = context.ConstantComposite(v2, context.Constant(f32, PcssDisk[i]), context.Constant(f32, PcssDisk[i + 1])); ++ SpvInstruction p = context.FAdd(v2, uv, context.FMul(v2, off, radiusV)); ++ SpvInstruction c = context.CompositeConstruct(v3, context.CompositeExtract(f32, p, 0), context.CompositeExtract(f32, p, 1), layerF); ++ acc = context.FAdd(f32, acc, context.ImageSampleDrefExplicitLod(f32, image, c, dRef, ImageOperandsMask.Lod, lod)); ++ } ++ ++ SpvInstruction pcss = context.FMul(f32, acc, context.Constant(f32, 2f / PcssDisk.Length)); ++ context.Branch(mergeLabel); ++ ++ context.AddLabel(mergeLabel); ++ return context.Phi(f32, pcss, pcssLabel, plain, plainLabel); ++ } ++ + private static OperationResult GenerateTextureQuerySamples(CodeGenContext context, AstOperation operation) + { + AstTextureOperation texOp = (AstTextureOperation)operation; +--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs ++++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs +@@ -25,6 +25,7 @@ namespace Ryujinx.Graphics.Shader + TfeOffset, + TfeVertexCount, + PointSize, ++ Pcss, + } + + public struct SupportBuffer +@@ -82,7 +83,8 @@ namespace Ryujinx.Graphics.Shader + new StructureField(AggregateType.Array | AggregateType.FP32, "render_scale", RenderScaleMaxCount), + new StructureField(AggregateType.Vector4 | AggregateType.S32, "tfe_offset"), + new StructureField(AggregateType.S32, "tfe_vertex_count"), +- new StructureField(AggregateType.FP32, "point_size") ++ new StructureField(AggregateType.FP32, "point_size"), ++ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss") + ]); + } + +@@ -98,5 +100,6 @@ namespace Ryujinx.Graphics.Shader + public Vector4 TfeOffset; + public Vector4 TfeVertexCount; + public Vector4 PointSize; ++ public Vector4 Pcss; + } + } diff --git a/totk.ini.example b/totk.ini.example index 07042f86..352f19c3 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -129,6 +129,10 @@ # short way toward the sun through the depth buffer and darkens where something close blocks it, adding the small # shadows at feet, under stones and in grass that the shadow maps miss. Read at start. # contact_shadows = 0 +# Soft sun shadows (PCSS), percent of the default penumbra width (0 to 200; 0 = the game's own four-tap filter): sharp +# where an object meets the ground and softer the further its shadow falls. Done in the translated shaders (translator +# patch 0010), so the shader cache is rebuilt once after an update. Read at start. +# pcss = 0 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 1512d9ed65a9ab898ce816a6b6131b36333ce58d Mon Sep 17 00:00:00 2001 From: TotK local Date: Sat, 31 Oct 2026 03:34:55 +0800 Subject: [PATCH 05/19] Add NVIDIA DLAA and a switch for the game's FXAA DLAA runs DLSS at the scene's own size on the R11G11B10F light target, right before the bloom chain's first pass, so bloom, post and HUD read the anti-aliased picture. NGX is loaded from the driver's NGX core at run time; no NVIDIA SDK code is compiled in, and nvngx_dlss.dll goes next to totk.exe. The scene's draws get a Halton(2,3) viewport jitter that steps after each DLAA run; camera motion vectors come from the scene depth reprojected through this and last frame's view-projection of the scene camera block (c4), read from the uniform snapshot. One DLSS feature per scene size keeps dynamic resolution from stalling. dlaa and fxaa switch live from the settings menu; fxaa skips the draw of the game's FXAA pass. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 5 + runtime/cfg.c | 7 +- runtime/dlaa_mv_spv.h | 119 +++++++ runtime/shaders/dlaa_mv.comp | 40 +++ runtime/ui/menu.cpp | 2 + runtime/ui_text.c | 10 + runtime/ui_text.h | 1 + runtime/vk_backend.c | 2 + runtime/vk_device.c | 9 +- runtime/vk_dlaa.c | 624 +++++++++++++++++++++++++++++++++++ runtime/vk_dlaa.h | 22 ++ runtime/vk_exec.c | 2 + runtime/vk_exec_draw.c | 4 + totk.ini.example | 7 + 14 files changed, 848 insertions(+), 6 deletions(-) create mode 100644 runtime/dlaa_mv_spv.h create mode 100644 runtime/shaders/dlaa_mv.comp create mode 100644 runtime/vk_dlaa.c create mode 100644 runtime/vk_dlaa.h diff --git a/docs/architecture.md b/docs/architecture.md index af1c6605..50154d80 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -94,6 +94,11 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app (MacNativeGames' sites); `resolution.c` sets them from `output_res` and `render_scale` and grows the texture heap and the application pool to match. When the window is larger than the output, `vk_fsr.c` runs AMD FSR 1 (EASU, RCAS) on the present. +- DLAA (`vk_dlaa.c`, `dlaa`, off by default). NVIDIA DLSS at the scene's own size, through the driver's NGX core loaded + at run time (no SDK code compiled in). It runs on the R11G11B10F light target right before the bloom chain's first + pass, so post effects and the HUD read the anti-aliased picture. The scene's draws get a sub-pixel Halton viewport + jitter; motion vectors are camera-only, reprojected from the scene depth through this and last frame's + view-projection of the scene camera block (constant bank c4). `fxaa` switches the game's own FXAA pass. - Occlusion queries never block the CPU; a result that is not ready counts as visible. - ASTC textures are uploaded as they are where the device reports `textureCompressionASTC_LDR`, and decoded by a compute shader everywhere else (`vk_astc.c`, `TOTK_ASTC`). The CPU decoder (`tex_astc*.c`) is the fallback and the test oracle. - Draw state. A draw whose program, bound state and textures repeat reuses the previous draw's shaders and skips rebuilding its descriptor sets; descriptor sets are written through update templates (`vk_exec_draw.c`, `vk_pipeline.c`). diff --git a/runtime/cfg.c b/runtime/cfg.c index 31eb9213..4fed7c46 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -35,9 +35,9 @@ static const char *const known[] = { "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", - "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", + "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DLAA", "DLAA_JITTER", "DLAA_MV", "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", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU", + "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "FXAA", "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", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, + {"SHARPNESS", "display"}, {"DLAA", "display"}, {"FXAA", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -94,6 +94,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, + {"DLAA", "0", "0|1", LIVE}, {"FXAA", "1", "0|1", LIVE}, // Game {"FPS_LIMIT", "60", "30|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/dlaa_mv_spv.h b/runtime/dlaa_mv_spv.h new file mode 100644 index 00000000..e1b31e6c --- /dev/null +++ b/runtime/dlaa_mv_spv.h @@ -0,0 +1,119 @@ +// Generated by tools/build_shaders.py from runtime/shaders/dlaa_mv.comp; do not edit. +// source sha256 bfa9b6d9e0f9d5cfd4382fa5080fa46f007a1a4e2b886b8fecd9adba11767686 +#pragma once +#include +static const uint32_t dlaa_mv_spv[] = { + 0x07230203, 0x00010600, 0x0008000b, 0x00000131, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, + 0x00000000, 0x00000001, 0x000b000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00000036, + 0x00000043, 0x0000005d, 0x00000089, 0x000000a0, 0x000000e7, 0x00060010, 0x00000004, 0x00000011, + 0x00000008, 0x00000008, 0x00000001, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, + 0x6e69616d, 0x00000000, 0x00080005, 0x00000036, 0x475f6c67, 0x61626f6c, 0x766e496c, 0x7461636f, + 0x496e6f69, 0x00000044, 0x00030005, 0x00000041, 0x00000050, 0x00050006, 0x00000041, 0x00000000, + 0x657a6973, 0x00000000, 0x00050006, 0x00000041, 0x00000001, 0x7474696a, 0x00007265, 0x00030005, + 0x00000043, 0x00006370, 0x00050005, 0x0000005d, 0x74706564, 0x65745f68, 0x00000078, 0x00030005, + 0x00000087, 0x00727543, 0x00040006, 0x00000087, 0x00000000, 0x00000072, 0x00030005, 0x00000089, + 0x00727563, 0x00040005, 0x0000009e, 0x76657250, 0x00000000, 0x00040006, 0x0000009e, 0x00000000, + 0x00000072, 0x00040005, 0x000000a0, 0x76657270, 0x00000000, 0x00040005, 0x000000e7, 0x6f5f766d, + 0x00007475, 0x00040047, 0x00000036, 0x0000000b, 0x0000001c, 0x00030047, 0x00000041, 0x00000002, + 0x00050048, 0x00000041, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000041, 0x00000001, + 0x00000023, 0x00000008, 0x00040047, 0x0000005d, 0x00000021, 0x00000000, 0x00040047, 0x0000005d, + 0x00000022, 0x00000000, 0x00040047, 0x00000086, 0x00000006, 0x00000010, 0x00030047, 0x00000087, + 0x00000002, 0x00050048, 0x00000087, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000089, + 0x00000021, 0x00000002, 0x00040047, 0x00000089, 0x00000022, 0x00000000, 0x00040047, 0x0000009d, + 0x00000006, 0x00000010, 0x00030047, 0x0000009e, 0x00000002, 0x00050048, 0x0000009e, 0x00000000, + 0x00000023, 0x00000000, 0x00040047, 0x000000a0, 0x00000021, 0x00000003, 0x00040047, 0x000000a0, + 0x00000022, 0x00000000, 0x00030047, 0x000000e7, 0x00000019, 0x00040047, 0x000000e7, 0x00000021, + 0x00000001, 0x00040047, 0x000000e7, 0x00000022, 0x00000000, 0x00020013, 0x00000002, 0x00030021, + 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, + 0x00000004, 0x00040018, 0x00000009, 0x00000007, 0x00000004, 0x0004002b, 0x00000006, 0x00000015, + 0x3f800000, 0x0004002b, 0x00000006, 0x00000016, 0x00000000, 0x00040015, 0x0000002f, 0x00000020, + 0x00000001, 0x00040017, 0x00000030, 0x0000002f, 0x00000002, 0x00040015, 0x00000033, 0x00000020, + 0x00000000, 0x00040017, 0x00000034, 0x00000033, 0x00000003, 0x00040020, 0x00000035, 0x00000001, + 0x00000034, 0x0004003b, 0x00000035, 0x00000036, 0x00000001, 0x00040017, 0x00000037, 0x00000033, + 0x00000002, 0x00020014, 0x0000003b, 0x0004002b, 0x00000033, 0x0000003c, 0x00000000, 0x00040017, + 0x00000040, 0x00000006, 0x00000002, 0x0004001e, 0x00000041, 0x00000040, 0x00000040, 0x00040020, + 0x00000042, 0x00000009, 0x00000041, 0x0004003b, 0x00000042, 0x00000043, 0x00000009, 0x0004002b, + 0x0000002f, 0x00000044, 0x00000000, 0x00040020, 0x00000045, 0x00000009, 0x00000006, 0x0004002b, + 0x00000033, 0x0000004d, 0x00000001, 0x00090019, 0x0000005a, 0x00000006, 0x00000001, 0x00000000, + 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x0000005b, 0x0000005a, 0x00040020, + 0x0000005c, 0x00000000, 0x0000005b, 0x0004003b, 0x0000005c, 0x0000005d, 0x00000000, 0x0004002b, + 0x00000006, 0x00000067, 0x3f000000, 0x0004002b, 0x0000002f, 0x0000006a, 0x00000001, 0x00040020, + 0x0000006b, 0x00000009, 0x00000040, 0x0004002b, 0x00000006, 0x00000075, 0x40000000, 0x0004002b, + 0x00000033, 0x00000085, 0x00000010, 0x0004001c, 0x00000086, 0x00000007, 0x00000085, 0x0003001e, + 0x00000087, 0x00000086, 0x00040020, 0x00000088, 0x00000002, 0x00000087, 0x0004003b, 0x00000088, + 0x00000089, 0x00000002, 0x0004002b, 0x0000002f, 0x0000008a, 0x00000003, 0x0004002b, 0x0000002f, + 0x0000008b, 0x00000004, 0x0004002b, 0x0000002f, 0x0000008c, 0x00000005, 0x0004002b, 0x0000002f, + 0x0000008d, 0x00000006, 0x00040020, 0x0000008f, 0x00000002, 0x00000007, 0x0004001c, 0x0000009d, + 0x00000007, 0x00000085, 0x0003001e, 0x0000009e, 0x0000009d, 0x00040020, 0x0000009f, 0x00000002, + 0x0000009e, 0x0004003b, 0x0000009f, 0x000000a0, 0x00000002, 0x0005002c, 0x00000040, 0x000000b4, + 0x00000016, 0x00000016, 0x0004002b, 0x00000006, 0x000000b9, 0x2b8cbccc, 0x0004002b, 0x00000006, + 0x000000c7, 0x358637bd, 0x00090019, 0x000000e5, 0x00000006, 0x00000001, 0x00000000, 0x00000000, + 0x00000000, 0x00000002, 0x00000007, 0x00040020, 0x000000e6, 0x00000000, 0x000000e5, 0x0004003b, + 0x000000e6, 0x000000e7, 0x00000000, 0x0005002c, 0x00000040, 0x00000130, 0x00000067, 0x00000067, + 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7, + 0x000000f0, 0x00000000, 0x000300fb, 0x0000003c, 0x000000f1, 0x000200f8, 0x000000f1, 0x0004003d, + 0x00000034, 0x00000038, 0x00000036, 0x0007004f, 0x00000037, 0x00000039, 0x00000038, 0x00000038, + 0x00000000, 0x00000001, 0x0004007c, 0x00000030, 0x0000003a, 0x00000039, 0x00050051, 0x0000002f, + 0x0000003f, 0x0000003a, 0x00000000, 0x00060041, 0x00000045, 0x00000046, 0x00000043, 0x00000044, + 0x0000003c, 0x0004003d, 0x00000006, 0x00000047, 0x00000046, 0x0004006e, 0x0000002f, 0x00000048, + 0x00000047, 0x000500af, 0x0000003b, 0x00000049, 0x0000003f, 0x00000048, 0x000400a8, 0x0000003b, + 0x0000004a, 0x00000049, 0x000300f7, 0x0000004c, 0x00000000, 0x000400fa, 0x0000004a, 0x0000004b, + 0x0000004c, 0x000200f8, 0x0000004b, 0x00050051, 0x0000002f, 0x0000004f, 0x0000003a, 0x00000001, + 0x00060041, 0x00000045, 0x00000050, 0x00000043, 0x00000044, 0x0000004d, 0x0004003d, 0x00000006, + 0x00000051, 0x00000050, 0x0004006e, 0x0000002f, 0x00000052, 0x00000051, 0x000500af, 0x0000003b, + 0x00000053, 0x0000004f, 0x00000052, 0x000200f9, 0x0000004c, 0x000200f8, 0x0000004c, 0x000700f5, + 0x0000003b, 0x00000054, 0x00000049, 0x000000f1, 0x00000053, 0x0000004b, 0x000300f7, 0x00000056, + 0x00000000, 0x000400fa, 0x00000054, 0x00000055, 0x00000056, 0x000200f8, 0x00000055, 0x000200f9, + 0x000000f0, 0x000200f8, 0x00000056, 0x0004003d, 0x0000005b, 0x0000005e, 0x0000005d, 0x00040064, + 0x0000005a, 0x00000060, 0x0000005e, 0x0007005f, 0x00000007, 0x00000061, 0x00000060, 0x0000003a, + 0x00000002, 0x00000044, 0x00050051, 0x00000006, 0x00000062, 0x00000061, 0x00000000, 0x0004006f, + 0x00000040, 0x00000066, 0x0000003a, 0x00050081, 0x00000040, 0x00000069, 0x00000066, 0x00000130, + 0x00050041, 0x0000006b, 0x0000006c, 0x00000043, 0x0000006a, 0x0004003d, 0x00000040, 0x0000006d, + 0x0000006c, 0x00050083, 0x00000040, 0x0000006e, 0x00000069, 0x0000006d, 0x00050051, 0x00000006, + 0x00000071, 0x0000006e, 0x00000000, 0x00050088, 0x00000006, 0x00000074, 0x00000071, 0x00000047, + 0x00050085, 0x00000006, 0x00000076, 0x00000074, 0x00000075, 0x00050083, 0x00000006, 0x00000077, + 0x00000076, 0x00000015, 0x00050051, 0x00000006, 0x00000079, 0x0000006e, 0x00000001, 0x00060041, + 0x00000045, 0x0000007a, 0x00000043, 0x00000044, 0x0000004d, 0x0004003d, 0x00000006, 0x0000007b, + 0x0000007a, 0x00050088, 0x00000006, 0x0000007c, 0x00000079, 0x0000007b, 0x00050085, 0x00000006, + 0x0000007d, 0x0000007c, 0x00000075, 0x00050083, 0x00000006, 0x0000007e, 0x00000015, 0x0000007d, + 0x00050085, 0x00000006, 0x00000080, 0x00000062, 0x00000075, 0x00050083, 0x00000006, 0x00000081, + 0x00000080, 0x00000015, 0x00070050, 0x00000007, 0x00000082, 0x00000077, 0x0000007e, 0x00000081, + 0x00000015, 0x00060041, 0x0000008f, 0x00000090, 0x00000089, 0x00000044, 0x0000008a, 0x0004003d, + 0x00000007, 0x00000091, 0x00000090, 0x00060041, 0x0000008f, 0x00000093, 0x00000089, 0x00000044, + 0x0000008b, 0x0004003d, 0x00000007, 0x00000094, 0x00000093, 0x00060041, 0x0000008f, 0x00000096, + 0x00000089, 0x00000044, 0x0000008c, 0x0004003d, 0x00000007, 0x00000097, 0x00000096, 0x00060041, + 0x0000008f, 0x00000099, 0x00000089, 0x00000044, 0x0000008d, 0x0004003d, 0x00000007, 0x0000009a, + 0x00000099, 0x00070050, 0x00000009, 0x00000110, 0x00000091, 0x00000094, 0x00000097, 0x0000009a, + 0x00040054, 0x00000009, 0x00000111, 0x00000110, 0x00060041, 0x0000008f, 0x000000a2, 0x000000a0, + 0x00000044, 0x0000008a, 0x0004003d, 0x00000007, 0x000000a3, 0x000000a2, 0x00060041, 0x0000008f, + 0x000000a5, 0x000000a0, 0x00000044, 0x0000008b, 0x0004003d, 0x00000007, 0x000000a6, 0x000000a5, + 0x00060041, 0x0000008f, 0x000000a8, 0x000000a0, 0x00000044, 0x0000008c, 0x0004003d, 0x00000007, + 0x000000a9, 0x000000a8, 0x00060041, 0x0000008f, 0x000000ab, 0x000000a0, 0x00000044, 0x0000008d, + 0x0004003d, 0x00000007, 0x000000ac, 0x000000ab, 0x00070050, 0x00000009, 0x0000012c, 0x000000a3, + 0x000000a6, 0x000000a9, 0x000000ac, 0x00040054, 0x00000009, 0x0000012d, 0x0000012c, 0x0006000c, + 0x00000009, 0x000000b0, 0x00000001, 0x00000022, 0x00000111, 0x00050091, 0x00000007, 0x000000b2, + 0x000000b0, 0x00000082, 0x00050051, 0x00000006, 0x000000b7, 0x000000b2, 0x00000003, 0x0006000c, + 0x00000006, 0x000000b8, 0x00000001, 0x00000004, 0x000000b7, 0x000500ba, 0x0000003b, 0x000000ba, + 0x000000b8, 0x000000b9, 0x000300f7, 0x000000bc, 0x00000000, 0x000400fa, 0x000000ba, 0x000000bb, + 0x000000bc, 0x000200f8, 0x000000bb, 0x00070050, 0x00000007, 0x000000c2, 0x000000b7, 0x000000b7, + 0x000000b7, 0x000000b7, 0x00050088, 0x00000007, 0x000000c3, 0x000000b2, 0x000000c2, 0x00050091, + 0x00000007, 0x000000c4, 0x0000012d, 0x000000c3, 0x00050051, 0x00000006, 0x000000c6, 0x000000c4, + 0x00000003, 0x000500ba, 0x0000003b, 0x000000c8, 0x000000c6, 0x000000c7, 0x000300f7, 0x000000ca, + 0x00000000, 0x000400fa, 0x000000c8, 0x000000c9, 0x000000ca, 0x000200f8, 0x000000c9, 0x0007004f, + 0x00000040, 0x000000cd, 0x000000c4, 0x000000c4, 0x00000000, 0x00000001, 0x00050050, 0x00000040, + 0x000000d0, 0x000000c6, 0x000000c6, 0x00050088, 0x00000040, 0x000000d1, 0x000000cd, 0x000000d0, + 0x00050051, 0x00000006, 0x000000d4, 0x000000d1, 0x00000000, 0x00050085, 0x00000006, 0x000000d5, + 0x000000d4, 0x00000067, 0x00050081, 0x00000006, 0x000000d6, 0x000000d5, 0x00000067, 0x00050085, + 0x00000006, 0x000000d9, 0x000000d6, 0x00000047, 0x00050051, 0x00000006, 0x000000db, 0x000000d1, + 0x00000001, 0x00050085, 0x00000006, 0x000000dc, 0x000000db, 0x00000067, 0x00050083, 0x00000006, + 0x000000dd, 0x00000067, 0x000000dc, 0x00050085, 0x00000006, 0x000000e0, 0x000000dd, 0x0000007b, + 0x00050050, 0x00000040, 0x000000e1, 0x000000d9, 0x000000e0, 0x00050083, 0x00000040, 0x000000e4, + 0x000000e1, 0x0000006e, 0x000200f9, 0x000000ca, 0x000200f8, 0x000000ca, 0x000700f5, 0x00000040, + 0x0000012f, 0x000000b4, 0x000000bb, 0x000000e4, 0x000000c9, 0x000200f9, 0x000000bc, 0x000200f8, + 0x000000bc, 0x000700f5, 0x00000040, 0x0000012e, 0x000000b4, 0x00000056, 0x0000012f, 0x000000ca, + 0x0004003d, 0x000000e5, 0x000000e8, 0x000000e7, 0x00050051, 0x00000006, 0x000000eb, 0x0000012e, + 0x00000000, 0x00050051, 0x00000006, 0x000000ec, 0x0000012e, 0x00000001, 0x00070050, 0x00000007, + 0x000000ed, 0x000000eb, 0x000000ec, 0x00000016, 0x00000016, 0x00040063, 0x000000e8, 0x0000003a, + 0x000000ed, 0x000200f9, 0x000000f0, 0x000200f8, 0x000000f0, 0x000100fd, 0x00010038, +}; diff --git a/runtime/shaders/dlaa_mv.comp b/runtime/shaders/dlaa_mv.comp new file mode 100644 index 00000000..f7ced22c --- /dev/null +++ b/runtime/shaders/dlaa_mv.comp @@ -0,0 +1,40 @@ +#version 450 +// Camera motion vectors for DLAA (vk_dlaa.c mv_pass): each pixel's depth is taken back to the world through this +// frame's view-projection and forward through last frame's; the vector is last frame's window position minus this +// frame's, in render pixels, without the jitter (DLSS's default convention). Objects that move on their own get only +// the camera's motion. +// The camera block is TotK's scene uniform block (bound as c4 in the scene's vertex shaders): vec4 rows 3-6 are the +// view-projection, rows of a row-major 4x4 with OpenGL clip depth (-w..w). The replay's viewports have negative +// heights, so window y grows downwards from ndc y = +1, and depth is z_ndc * 0.5 + 0.5. +layout(local_size_x = 8, local_size_y = 8) in; +layout(binding = 0) uniform sampler2D depth_tex; +layout(binding = 1, rg16f) uniform writeonly image2D mv_out; +layout(binding = 2, std140) uniform Cur { vec4 r[16]; } cur; +layout(binding = 3, std140) uniform Prev { vec4 r[16]; } prev; +layout(push_constant) uniform P { + vec2 size; // render size in pixels + vec2 jitter; // this frame's jitter, pixels, as the scene was drawn (window x right, y down) +} pc; + +mat4 vp(vec4 a, vec4 b, vec4 c, vec4 d) { return transpose(mat4(a, b, c, d)); } + +void main() { + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (p.x >= int(pc.size.x) || p.y >= int(pc.size.y)) return; + float d = texelFetch(depth_tex, p, 0).r; + vec2 win = vec2(p) + 0.5 - pc.jitter; // where this pixel's surface sits without the jitter + vec4 ndc = vec4(win.x / pc.size.x * 2.0 - 1.0, 1.0 - win.y / pc.size.y * 2.0, d * 2.0 - 1.0, 1.0); + mat4 c = vp(cur.r[3], cur.r[4], cur.r[5], cur.r[6]); + mat4 q = vp(prev.r[3], prev.r[4], prev.r[5], prev.r[6]); + vec4 world = inverse(c) * ndc; + vec2 mv = vec2(0.0); + if (abs(world.w) > 1e-12) { + vec4 clip = q * (world / world.w); + if (clip.w > 1e-6) { + vec2 pn = clip.xy / clip.w; + vec2 pwin = vec2((pn.x * 0.5 + 0.5) * pc.size.x, (0.5 - pn.y * 0.5) * pc.size.y); + mv = pwin - win; + } + } + imageStore(mv_out, p, vec4(mv, 0.0, 0.0)); +} diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 7d52baa9..035631b4 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -534,6 +534,8 @@ static void tab_screen(float scale) { static const UiTextId up[] = {UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR}; opt_choice("TOTK_UPSCALER", UI_MENU_UPSCALER, up, 2, UI_MENU_UPSCALER_DESC); opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%"); + opt_toggle("TOTK_DLAA", UI_MENU_DLAA, UI_MENU_DLAA_DESC); + opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 0de0818f..3bd8c2f3 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -63,6 +63,11 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", + [UI_MENU_DLAA] = "NVIDIA DLAA", + [UI_MENU_DLAA_DESC] = "DLSS anti-aliasing of the 3D scene at its own resolution (NVIDIA RTX GPUs; nvngx_dlss.dll next to " + "totk.exe). Smoother edges and less shimmer for about 3 ms a frame.", + [UI_MENU_FXAA] = "Game anti-aliasing (FXAA)", + [UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -282,6 +287,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Билинейное", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", + [UI_MENU_DLAA] = "NVIDIA DLAA", + [UI_MENU_DLAA_DESC] = "Сглаживание 3D-сцены через DLSS в её собственном разрешении (видеокарты NVIDIA RTX; nvngx_dlss.dll " + "рядом с totk.exe). Ровнее края и меньше мерцания, около 3 мс на кадр.", + [UI_MENU_FXAA] = "Сглаживание игры (FXAA)", + [UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 96e10618..7d95c8be 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -36,6 +36,7 @@ typedef enum { UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME, UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, + UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_FXAA, UI_MENU_FXAA_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_90, UI_MENU_FPS_120, diff --git a/runtime/vk_backend.c b/runtime/vk_backend.c index a260aa69..86388618 100644 --- a/runtime/vk_backend.c +++ b/runtime/vk_backend.c @@ -29,6 +29,7 @@ #include "nvn_api.h" #include "vk.h" #include "vk_exec.h" +#include "vk_dlaa.h" #define WEAK __attribute__((weak)) @@ -104,6 +105,7 @@ static void present_image(const tex_t *t, const int crop[4], uint64_t at_ns, uin uint64_t value) { static volatile long n_skipped; vk_exec_frame_log(t, frame); + vk_dlaa_frame(); vk_mem_census(frame); if (vk_dump_armed) vk_dump_present(frame); __atomic_store_n(&gfx_counters.validation_errors, (uint64_t)vk_validation_errors_total(), __ATOMIC_RELAXED); diff --git a/runtime/vk_device.c b/runtime/vk_device.c index 98fb84f9..8df3eab0 100644 --- a/runtime/vk_device.c +++ b/runtime/vk_device.c @@ -10,6 +10,7 @@ #include "cfg.h" #include "host.h" #include "vk.h" +#include "vk_dlaa.h" static VkCtx g_vk; static int g_ready; @@ -42,7 +43,7 @@ static int layer_present(const char *name) { } static int create_instance(void) { - const char *ext[4] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; + const char *ext[12] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; uint32_t n_ext = 2; const char *layers[] = {"VK_LAYER_KHRONOS_validation"}; int validate = cfg_bool("TOTK_VK_VALIDATION"); @@ -51,6 +52,7 @@ static int create_instance(void) { validate = 0; } if (validate) ext[n_ext++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + vk_dlaa_instance_exts(ext, &n_ext, 12); VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "TotK Recomp", .pEngineName = "TotK Recomp", .apiVersion = VK_API_VERSION_1_3}; VkInstanceCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app, @@ -195,7 +197,7 @@ static int create_device(void) { vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, NULL); VkExtensionProperties *ep = calloc(ne ? ne : 1, sizeof *ep); vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, ep); - const char *ext[28]; + const char *ext[40]; uint32_t n_ext = 0; for (size_t i = 0; i < sizeof k_required_ext / sizeof *k_required_ext; i++) ext[n_ext++] = k_required_ext[i]; @@ -232,6 +234,7 @@ static int create_device(void) { CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT); CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR); } + vk_dlaa_device_exts(ep, ne, ext, &n_ext, 34); // NGX's; the six slots after it stay for the ones below if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; } // GPU breadcrumbs for a lost device (vk_crumbs.c): AMD's drivers and RADV report it. if (has_ext(ep, ne, VK_AMD_BUFFER_MARKER_EXTENSION_NAME)) { g_vk.has_buffer_marker = 1; ext[n_ext++] = VK_AMD_BUFFER_MARKER_EXTENSION_NAME; } @@ -354,7 +357,7 @@ int vk_init(void) { AcquireSRWLockExclusive(&g_lock); if (!g_ready) { memset(&g_vk, 0, sizeof g_vk); - if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_headroom_start(); + if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_headroom_start(), vk_dlaa_init(); else destroy_all(); } int ok = g_ready; diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c new file mode 100644 index 00000000..9de36e8a --- /dev/null +++ b/runtime/vk_dlaa.c @@ -0,0 +1,624 @@ +// DLAA: NVIDIA DLSS at the scene's own size (TOTK_DLAA, totk.ini dlaa). NGX is loaded at run time from the driver's +// NGX core (_nvngx.dll, found through HKLM\SOFTWARE\NVIDIA Corporation\Global\NGXCore); the DLSS model +// (nvngx_dlss.dll) is loaded by NGX from the folder of totk.exe. No NVIDIA SDK code or header is compiled in: the few +// NGX types used are declared here from the SDK's documented ABI, the way the Metroid Dread recomp's dlss.c reaches +// the core (read for behaviour only). +// +// The core's parameter object is a C++ class whose virtual functions are called through the MSVC vtable: the Set +// overloads in slots 0-7 and the Get overloads in 8-15, each group in reverse declaration order. vtable_ok checks that +// layout with a set-then-get round trip before anything relies on it. +// +// Where DLAA runs in the frame, the jitter and the motion vectors: see the sections below. +#include +#include +#include +#include +#include +#include + +#include "cfg.h" +#include "host.h" +#include "vk.h" +#include "vk_dlaa.h" +#include "vk_exec.h" +#include "vk_rec.h" +#include "dlaa_mv_spv.h" + +typedef int NgxResult; // NVSDK_NGX_Result: 1 success, 0xBAD00000 | n failures +#define NGX_OK(r) (((unsigned)(r) & 0xFFF00000u) != 0xBAD00000u) +#define NGX_VERSION_API 0x15 +#define NGX_FEATURE_SUPERSAMPLING 1 +#define NGX_PERFQ_DLAA 5 +typedef struct NgxParam NgxParam; +typedef struct NgxHandle NgxHandle; +typedef struct { void *slot[17]; } NgxParamVtbl; +struct NgxParam { const NgxParamVtbl *vt; }; +typedef struct { // NVSDK_NGX_ImageViewInfo_VK + VkImageView view; + VkImage image; + VkImageSubresourceRange range; + VkFormat format; + unsigned width, height; +} NgxImageView; +typedef struct { // NVSDK_NGX_Resource_VK + union { NgxImageView img; struct { VkBuffer buffer; unsigned bytes; } buf; } r; + int type; // 0 image view, 1 buffer + _Bool rw; +} NgxResourceVK; + +typedef NgxResult (*PFN_Init)(unsigned long long app, const wchar_t *path, VkInstance, VkPhysicalDevice, VkDevice, + PFN_vkGetInstanceProcAddr, PFN_vkGetDeviceProcAddr, int version, const void *info); +typedef NgxResult (*PFN_ReqExt)(unsigned *ni, const char ***ie, unsigned *nd, const char ***de); +typedef NgxResult (*PFN_Params)(NgxParam **); +typedef NgxResult (*PFN_DestroyParams)(NgxParam *); +typedef NgxResult (*PFN_Create)(VkCommandBuffer, int feature, NgxParam *, NgxHandle **); +typedef NgxResult (*PFN_Evaluate)(VkCommandBuffer, const NgxHandle *, const NgxParam *, void *callback); +typedef NgxResult (*PFN_Release)(NgxHandle *); + +static struct { + HMODULE core; + PFN_Init init; + PFN_ReqExt req_ext; + PFN_Params caps, alloc_params; + PFN_DestroyParams destroy_params; + PFN_Create create; + PFN_Evaluate evaluate; + PFN_Release release; + int tried, loaded, available; + int wanted; // -1 not read yet +} N = {.wanted = -1}; + +typedef void (*SetI)(NgxParam *, const char *, int); +typedef void (*SetU)(NgxParam *, const char *, unsigned); +typedef void (*SetF)(NgxParam *, const char *, float); +typedef void (*SetP)(NgxParam *, const char *, void *); +typedef NgxResult (*GetI)(const NgxParam *, const char *, int *); +typedef NgxResult (*GetU)(const NgxParam *, const char *, unsigned *); +typedef NgxResult (*GetF)(const NgxParam *, const char *, float *); +typedef NgxResult (*GetP)(const NgxParam *, const char *, void **); +enum { S_P = 0, S_D12, S_D11, S_I, S_U32, S_D, S_F, S_U64, G_P, G_D12, G_D11, G_I, G_U32, G_D, G_F, G_U64 }; +static void p_seti(NgxParam *p, const char *n, int v) { ((SetI)p->vt->slot[S_I])(p, n, v); } +static void p_setu(NgxParam *p, const char *n, unsigned v) { ((SetU)p->vt->slot[S_U32])(p, n, v); } +static void p_setf(NgxParam *p, const char *n, float v) { ((SetF)p->vt->slot[S_F])(p, n, v); } +static void p_setp(NgxParam *p, const char *n, void *v) { ((SetP)p->vt->slot[S_P])(p, n, v); } +static int p_geti(const NgxParam *p, const char *n, int *v) { return NGX_OK(((GetI)p->vt->slot[G_I])(p, n, v)); } +static int p_getu(const NgxParam *p, const char *n, unsigned *v) { return NGX_OK(((GetU)p->vt->slot[G_U32])(p, n, v)); } +static int p_getf(const NgxParam *p, const char *n, float *v) { return NGX_OK(((GetF)p->vt->slot[G_F])(p, n, v)); } +static int p_getp(const NgxParam *p, const char *n, void **v) { return NGX_OK(((GetP)p->vt->slot[G_P])(p, n, v)); } + +// NGX is brought up whenever the driver has it, whatever the setting, so dlaa can be switched on while the game runs +// (its device extensions can only be asked for at device creation). Switched off, nothing else of DLAA runs. +int vk_dlaa_wanted(void) { return 1; } + +static int core_load(void) { + if (N.tried) return N.loaded; + N.tried = 1; + char dir[MAX_PATH] = {0}, path[MAX_PATH + 32]; + DWORD n = sizeof dir; + if (RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\NVIDIA Corporation\\Global\\NGXCore", "FullPath", RRF_RT_REG_SZ, + NULL, dir, &n) != ERROR_SUCCESS) { + rt_log("dlaa: the driver has no NGX core (registry NGXCore missing): DLAA off"); + return 0; + } + snprintf(path, sizeof path, "%s\\_nvngx.dll", dir); + N.core = LoadLibraryA(path); + if (!N.core) { + rt_log("dlaa: cannot load %s (error %lu): DLAA off", path, GetLastError()); + return 0; + } +#define FN(f, name) N.f = (void *)GetProcAddress(N.core, name) + FN(init, "NVSDK_NGX_VULKAN_Init_Ext2"); + FN(req_ext, "NVSDK_NGX_VULKAN_RequiredExtensions"); + FN(caps, "NVSDK_NGX_VULKAN_GetCapabilityParameters"); + FN(alloc_params, "NVSDK_NGX_VULKAN_AllocateParameters"); + FN(destroy_params, "NVSDK_NGX_VULKAN_DestroyParameters"); + FN(create, "NVSDK_NGX_VULKAN_CreateFeature"); + FN(evaluate, "NVSDK_NGX_VULKAN_EvaluateFeature"); + FN(release, "NVSDK_NGX_VULKAN_ReleaseFeature"); +#undef FN + if (!N.init || !N.req_ext || !N.caps || !N.alloc_params || !N.create || !N.evaluate || !N.release) { + rt_log("dlaa: the NGX core %s lacks Vulkan entry points: DLAA off", path); + return 0; + } + N.loaded = 1; + rt_log("dlaa: NGX core %s", path); + return 1; +} + +static int listed(const char *const *list, uint32_t n, const char *s) { + for (uint32_t i = 0; i < n; i++) + if (!strcmp(list[i], s)) return 1; + return 0; +} + +void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max) { + unsigned ni = 0, nd = 0; + const char **ie = NULL, **de = NULL; + if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; + for (unsigned i = 0; i < ni; i++) + if (!listed(ext, *n, ie[i]) && *n < max) ext[(*n)++] = ie[i]; +} + +void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, + uint32_t max) { + unsigned ni = 0, nd = 0; + const char **ie = NULL, **de = NULL; + if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; + for (unsigned i = 0; i < nd; i++) { + int ok = 0; + for (uint32_t k = 0; k < nhave && !ok; k++) ok = !strcmp(have[k].extensionName, de[i]); + if (!ok) rt_log("dlaa: the device lacks %s, which NGX asks for", de[i]); + else if (!listed(ext, *n, de[i]) && *n < max) ext[(*n)++] = de[i]; + } +} + +static int vtable_ok(void) { + NgxParam *p = NULL; + if (!NGX_OK(N.alloc_params(&p)) || !p) return 0; + int i = 0; + unsigned u = 0; + float f = 0; + void *v = NULL; + p_seti(p, "TotK.Test.I", -12345); + p_setu(p, "TotK.Test.U", 4000000000u); + p_setf(p, "TotK.Test.F", 1.25f); + p_setp(p, "TotK.Test.P", (void *)p); + int ok = p_geti(p, "TotK.Test.I", &i) && i == -12345 && p_getu(p, "TotK.Test.U", &u) && u == 4000000000u && + p_getf(p, "TotK.Test.F", &f) && f == 1.25f && p_getp(p, "TotK.Test.P", &v) && v == (void *)p; + if (N.destroy_params) N.destroy_params(p); + if (!ok) rt_log("dlaa: NGX parameter layout check failed (i=%d u=%u f=%g p=%p): DLAA off", i, u, f, v); + return ok; +} + +void vk_dlaa_init(void) { + if (!vk_dlaa_wanted() || !core_load()) return; + wchar_t wdir[MAX_PATH]; + DWORD len = GetModuleFileNameW(NULL, wdir, MAX_PATH); + while (len && wdir[len - 1] != L'\\') len--; + wdir[len] = 0; + // 231313132: the application id NVIDIA's DLSS samples use for builds without an NVIDIA-issued id + const VkCtx *c = vk_ctx(); + NgxResult r = N.init(231313132ull, wdir, c->instance, c->phys, c->device, vkGetInstanceProcAddr, + vkGetDeviceProcAddr, NGX_VERSION_API, NULL); + if (!NGX_OK(r)) { + rt_log("dlaa: NGX init failed (%08x): DLAA off", (unsigned)r); + return; + } + if (!vtable_ok()) return; + NgxParam *caps = NULL; + int avail = 0, driver = 0; + if (NGX_OK(N.caps(&caps)) && caps) { + p_geti(caps, "SuperSampling.Available", &avail); + p_geti(caps, "SuperSampling.NeedsUpdatedDriver", &driver); + } + N.available = avail != 0; + rt_log("dlaa: NGX up; DLSS %s%s", avail ? "available" : "NOT available (is nvngx_dlss.dll next to totk.exe?)", + driver ? "; the driver needs an update" : ""); +} + +// ---------------------------------------------------------------- where DLAA runs in TotK's frame +// Measured (TOTK_DUMP, frame 2100 at Lookout Landing, 2560x1440 scene): the G-buffer passes draw into five targets with +// the scene depth (d32f at the scene size), one of them the R11G11B10F light target; lighting and the transparents +// then draw into that light target alone, the last time with the scene depth attached; the first pass narrower than a +// quarter of the scene starts the bloom chain, which reads it. After the bloom come the tonemap and post passes, then +// the HUD is drawn into the same target and a last pass copies it to the 8-bit output. +// So: after the G-buffer, a pass at the scene size with exactly one colour target (R11G11B10F or RGBA16F) and the D32F +// depth arms the frame with that pair; the next pass at most a quarter as wide runs DLAA on the armed target first. +// Bloom, tonemap, post and HUD then all work on the anti-aliased picture. +static struct { + VkExecTarget color, depth; // the armed pair, valid in the frame it was armed + int armed, done, gbuf; // this frame: armed on the light target, DLAA ran, the G-buffer was drawn + struct Size { // a DLSS feature and its work images per scene size (dynamic resolution flips it) + uint32_t w, h; + VkImage out, mv; + VmaAllocation out_mem, mv_mem; + VkImageView out_view, mv_view; + NgxHandle *feat; + uint64_t used; // evals count when it last ran + } sizes[3], *last; // last: the one the previous DLAA frame ran with + VkImage last_color; // the target DLAA ran on last frame: another one means a new history + NgxParam *params; + int failed, reset; + uint64_t evals, frames_missed; + // jitter (vk_dlaa_viewport) + VkImage jdepth; // the scene depth of the last frame DLAA ran on: passes drawing with it are jittered + float jx, jy; // the offset the next scene draws take, render pixels (window x right, y down) + float ux, uy; // the offset this frame's scene draws took (DLSS and the motion vectors get these) + uint32_t jframe; + int jit_ok, jit_used, hold; // jitter allowed this frame / a draw used it / frames left without it + uint64_t holds; + // camera (vk_dlaa_draw) and motion vectors (mv_pass) + uint64_t cam_addr; // this frame's scene camera block (c4 of a scene draw's vertex stage), 0: none seen + VkBuffer camb; // two 256-byte slots: this frame's block and last frame's + VmaAllocation camb_mem; + int cam_slot, cam_prev_ok; // the slot this frame writes / the other slot holds last frame's camera + VkDescriptorSetLayout mv_dsl; + VkPipelineLayout mv_layout; + VkPipeline mv_pipe; + VkSampler mv_samp; + int mv_ok; // -1 not built, 0 failed, 1 ready + uint64_t mv_frames, mv_none; + uint64_t why[3]; // history resets: scene size changed, no camera, scene target changed + int on; // the dlaa setting, read at each present (the menu switches it live) +} D = {.mv_ok = -1}; + +static int dl_active(void) { return N.available && !D.failed && D.on; } + +static void dl_fail(const char *what, NgxResult r) { + rt_log("dlaa: %s failed (%08x): DLAA off for this run", what, (unsigned)r); + D.failed = 1; +} + +static int image2d(uint32_t w, uint32_t h, VkFormat f, VkImageUsageFlags usage, VkImage *img, VmaAllocation *mem, + VkImageView *view) { + const VkCtx *c = vk_ctx(); + VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = f, + .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = usage, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; + VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}; + if (vmaCreateImage(c->vma, &ii, &ai, img, mem, NULL) != VK_SUCCESS) return 0; + VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = *img, + .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = f, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + return vkCreateImageView(c->device, &vi, NULL, view) == VK_SUCCESS; +} + +static void free_size(struct Size *e) { + const VkCtx *c = vk_ctx(); + vkDeviceWaitIdle(c->device); // a third scene size: the evicted images may still be in flight + if (e->out_view) vkDestroyImageView(c->device, e->out_view, NULL); + if (e->mv_view) vkDestroyImageView(c->device, e->mv_view, NULL); + if (e->out) vmaDestroyImage(c->vma, e->out, e->out_mem); + if (e->mv) vmaDestroyImage(c->vma, e->mv, e->mv_mem); + if (e->feat) N.release(e->feat); + memset(e, 0, sizeof *e); +} + +// The entry for a scene size: its output (RGBA16F, written by DLSS, then blitted back into the scene target) and +// motion vectors (RG16F, render pixels), both kept in GENERAL like every image of the back end. TotK's dynamic +// resolution switches between a few sizes; each keeps its feature, the least recently used goes for a new one. +static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { + struct Size *e = NULL, *lru = &D.sizes[0]; + for (int i = 0; i < 3; i++) { + if (D.sizes[i].w == w && D.sizes[i].h == h) return &D.sizes[i]; + if (!D.sizes[i].out && !e) e = &D.sizes[i]; + if (D.sizes[i].used < lru->used) lru = &D.sizes[i]; + } + if (!e) { + if (D.last == lru) D.last = NULL; + free_size(e = lru); + } + VkImageUsageFlags u = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT; + if (!image2d(w, h, VK_FORMAT_R16G16B16A16_SFLOAT, u, &e->out, &e->out_mem, &e->out_view) || + !image2d(w, h, VK_FORMAT_R16G16_SFLOAT, u, &e->mv, &e->mv_mem, &e->mv_view)) + return NULL; + VkImageMemoryBarrier2 ib[2]; + VkImage im[2] = {e->out, e->mv}; + for (int i = 0; i < 2; i++) + ib[i] = (VkImageMemoryBarrier2){.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = im[i], + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + VkDependencyInfo di = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .imageMemoryBarrierCount = 2, + .pImageMemoryBarriers = ib}; + vkCmdPipelineBarrier2(cb, &di); + e->w = w, e->h = h; + return e; +} + +static void full_barrier(VkCommandBuffer cb) { + VkMemoryBarrier2 mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT}; + VkDependencyInfo di = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &mb}; + vkCmdPipelineBarrier2(cb, &di); +} + +static NgxResourceVK res_image(VkImageView v, VkImage img, VkFormat f, uint32_t w, uint32_t h, VkImageAspectFlags a, + int rw) { + NgxResourceVK r; + memset(&r, 0, sizeof r); + r.r.img = (NgxImageView){v, img, {a, 0, 1, 0, 1}, f, w, h}; + r.type = 0; + r.rw = rw; + return r; +} + +// ---------------------------------------------------------------- motion vectors +// Camera motion only (runtime/shaders/dlaa_mv.comp): this frame's scene camera block is copied out of the replay's +// uniform snapshot (vk_usnap.c, as of the submit call) into one slot of camb, last frame's stays in the other, and the +// compute pass reprojects every pixel's depth through both. Characters and anything else that moves on its own get +// the camera's motion only, which DLSS mostly copes with by rejecting their history. +#define CAM_BYTES 256u // vec4 rows 0-15: view, view-projection (3-6), projection, inverse view + +static int mv_init(void) { + if (D.mv_ok >= 0) return D.mv_ok; + D.mv_ok = 0; + const VkCtx *c = vk_ctx(); + VkDescriptorSetLayoutBinding b[4] = { + {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}, + {1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}, + {2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}, + {3, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}}; + VkDescriptorSetLayoutCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, + .bindingCount = 4, .pBindings = b}; + VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, 16}; + VkSamplerCreateInfo si = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_NEAREST, + .minFilter = VK_FILTER_NEAREST, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE}; + VkShaderModuleCreateInfo mi = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = sizeof dlaa_mv_spv, + .pCode = dlaa_mv_spv}; + VkShaderModule m = VK_NULL_HANDLE; + VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = 2 * CAM_BYTES, + .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT}; + VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}; + if (vkCreateDescriptorSetLayout(c->device, &dci, NULL, &D.mv_dsl) != VK_SUCCESS) goto fail; + VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, + .pSetLayouts = &D.mv_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr}; + if (vkCreatePipelineLayout(c->device, &li, NULL, &D.mv_layout) != VK_SUCCESS || + vkCreateSampler(c->device, &si, NULL, &D.mv_samp) != VK_SUCCESS || + vkCreateShaderModule(c->device, &mi, NULL, &m) != VK_SUCCESS || + vmaCreateBuffer(c->vma, &bi, &ai, &D.camb, &D.camb_mem, NULL) != VK_SUCCESS) + goto fail; + VkComputePipelineCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = m, .pName = "main"}, + .layout = D.mv_layout}; + VkResult r = vkCreateComputePipelines(c->device, VK_NULL_HANDLE, 1, &ci, NULL, &D.mv_pipe); + vkDestroyShaderModule(c->device, m, NULL); + if (r != VK_SUCCESS) goto fail; + return D.mv_ok = 1; +fail: + rt_log("dlaa: the motion-vector pass could not be set up: DLAA runs with zero motion"); + return 0; +} + +// The pass, recorded through the recorder like the replay's own commands. 0: no camera this frame (the vectors stay +// zero and DLSS starts a new history). +static int mv_pass(VkCommandBuffer cb, const struct Size *e, VkImageView zv, float jx, float jy) { + uint32_t w = e->w, h = e->h; + VkDescriptorBufferInfo cam; + if (!mv_init() || !D.cam_addr || !vk_usnap_find(D.cam_addr, CAM_BYTES, 4, &cam)) { + D.mv_none++; + D.cam_prev_ok = 0; + return 0; + } + int s = D.cam_slot, had_prev = D.cam_prev_ok; + VkBufferCopy bc = {cam.offset, (VkDeviceSize)s * CAM_BYTES, CAM_BYTES}; + vkCmdCopyBuffer(cb, cam.buffer, D.camb, 1, &bc); + full_barrier(cb); + D.cam_slot ^= 1, D.cam_prev_ok = 1; + if (!had_prev) return 0; // nothing to reproject into: zero motion, new history + VkDescriptorImageInfo zi = {D.mv_samp, zv, VK_IMAGE_LAYOUT_GENERAL}; + VkDescriptorImageInfo oi = {VK_NULL_HANDLE, e->mv_view, VK_IMAGE_LAYOUT_GENERAL}; + VkDescriptorBufferInfo cur = {D.camb, (VkDeviceSize)s * CAM_BYTES, CAM_BYTES}; + VkDescriptorBufferInfo prev = {D.camb, (VkDeviceSize)(s ^ 1) * CAM_BYTES, CAM_BYTES}; + VkWriteDescriptorSet wr[4] = { + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &zi}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 2, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &cur}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 3, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &prev}}; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, D.mv_pipe); + rec_push(vk_pipeline_push_fn(), cb, VK_PIPELINE_BIND_POINT_COMPUTE, D.mv_layout, 0, 4, wr); + float pc[4] = {(float)w, (float)h, jx, jy}; + vkCmdPushConstants(cb, D.mv_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, pc); + vkCmdDispatch(cb, (w + 7) / 8, (h + 7) / 8, 1); + full_barrier(cb); + D.mv_frames++; + return 1; +} + +// ---------------------------------------------------------------- jitter +// The scene's draws (every pass drawing with the scene depth, until the DLAA point) have their viewport moved by a +// sub-pixel Halton(2,3) offset, which shifts what they rasterise as a jittered projection would; full-screen passes +// that shade by window position are unaffected. Jitter only follows a frame DLSS ran on: a jittered frame that DLSS +// does not resolve shakes on screen, so a missed DLAA point stops the jitter for a second. +static float halton(uint32_t i, uint32_t b) { + float f = 1, r = 0; + for (; i; i /= b) f /= (float)b, r += f * (float)(i % b); + return r; +} + +void vk_dlaa_viewport(VkExec *ex, VkViewport *v) { + if (!D.jit_ok || D.done || !ex->depth.image || ex->depth.image != D.jdepth) return; + v->x += D.jx, v->y += D.jy; + D.ux = D.jx, D.uy = D.jy, D.jit_used = 1; +} + +void vk_dlaa_draw(VkExec *ex) { + if (!dl_active() || D.done) return; + const p_bind_buf *b = &ex->ubo[0][1]; // constant bank c4: the replay keeps user banks from c3 on + const VkExecTarget *z = &ex->depth; + if (b->size == 0x940 && b->addr && z->image && z->width >= 640 && z->format == VK_FORMAT_D32_SFLOAT && + (!D.jdepth || z->image == D.jdepth)) + D.cam_addr = b->addr; +} + +// The jitter moves on right after DLAA ran, not at the present: the replay can record the next frame's scene before +// the present of this one is handled, and a step taken there landed in the middle of a frame (worse after an off/on +// switch, which shifted that order). Jitter needs a frame DLSS ran on; a frame without the DLAA point stops it. +static void next_jitter(void) { + static int nj = -1; + if (nj < 0) nj = !rt_knob("DLAA_JITTER", "1"); // TOTK_DLAA_JITTER=0: no jitter (test) + uint32_t i = D.jframe++ % 16 + 1; + D.jx = halton(i, 2) - 0.5f, D.jy = halton(i, 3) - 0.5f; + D.jit_ok = !D.hold && !nj; +} + +static void evaluate(VkExec *ex) { + const VkExecTarget *t = &D.color, *z = &D.depth; + uint32_t w = t->width, h = t->height; + VkCommandBuffer cb = ex->cb; + vk_exec_barrier(ex); // what drew the scene is done (no pass is open here) + struct Size *e = size_for(cb, w, h); + if (!e) return dl_fail("work image creation", 0); + if (e != D.last) D.reset = 1, D.why[0]++; // another size's history is from another moment + if (!D.params && !NGX_OK(N.alloc_params(&D.params))) return dl_fail("parameter allocation", 0); + NgxParam *p = D.params; + VkImageView zv = vk_exec_target_view(z->img, z->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_DEPTH_BIT, z->level, + z->base_layer, 1, 0); + float jx = D.jit_used ? D.ux : 0.0f, jy = D.jit_used ? D.uy : 0.0f; + static int no_mv = -1; + if (no_mv < 0) no_mv = !rt_knob("DLAA_MV", "1"); // TOTK_DLAA_MV=0: zero motion (test) + if (no_mv || !mv_pass(cb, e, zv, jx, jy)) { + VkClearColorValue zero = {{0, 0, 0, 0}}; + VkImageSubresourceRange all = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + vkCmdClearColorImage(cb, e->mv, VK_IMAGE_LAYOUT_GENERAL, &zero, 1, &all); + full_barrier(cb); + if (!no_mv) D.reset = 1, D.why[1]++; // no camera: the history cannot be moved along + } + rec_drain(); // NGX records into the command buffer itself: the recorder thread must have made every call so far + if (!e->feat) { + p_setu(p, "CreationNodeMask", 1); + p_setu(p, "VisibilityNodeMask", 1); + p_setu(p, "Width", w); + p_setu(p, "Height", h); + p_setu(p, "OutWidth", w); + p_setu(p, "OutHeight", h); + p_seti(p, "PerfQualityValue", NGX_PERFQ_DLAA); + // IsHDR | MVLowRes | AutoExposure: linear scene light, motion vectors at the render size, no exposure texture + p_seti(p, "DLSS.Feature.Create.Flags", (1 << 0) | (1 << 1) | (1 << 6)); + p_seti(p, "DLSS.Enable.Output.Subrects", 0); + NgxResult r = N.create(cb, NGX_FEATURE_SUPERSAMPLING, p, &e->feat); + if (!NGX_OK(r) || !e->feat) return dl_fail("DLSS feature creation", r); + D.reset = 1; + rt_log("dlaa: DLSS feature created at %ux%u (scene format %d, depth format %d)", w, h, (int)t->format, + (int)z->format); + } + if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image; + VkImageView cv = vk_exec_target_view(t->img, t->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT, t->level, + t->base_layer, 1, 0); + NgxResourceVK rc = res_image(cv, t->image, t->format, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); + NgxResourceVK ro = res_image(e->out_view, e->out, VK_FORMAT_R16G16B16A16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 1); + NgxResourceVK rz = res_image(zv, z->image, z->format, w, h, VK_IMAGE_ASPECT_DEPTH_BIT, 0); + NgxResourceVK rm = res_image(e->mv_view, e->mv, VK_FORMAT_R16G16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); + p_setp(p, "Color", &rc); + p_setp(p, "Output", &ro); + p_setp(p, "Depth", &rz); + p_setp(p, "MotionVectors", &rm); + p_setf(p, "Jitter.Offset.X", jx); + p_setf(p, "Jitter.Offset.Y", jy); + p_setf(p, "Sharpness", 0.0f); + p_seti(p, "Reset", D.reset); + p_setf(p, "MV.Scale.X", 1.0f); + p_setf(p, "MV.Scale.Y", 1.0f); + p_setu(p, "DLSS.Render.Subrect.Dimensions.Width", w); + p_setu(p, "DLSS.Render.Subrect.Dimensions.Height", h); + p_setf(p, "DLSS.Pre.Exposure", 1.0f); + p_setf(p, "DLSS.Exposure.Scale", 1.0f); + p_setf(p, "FrameTimeDeltaInMsec", 16.67f); + NgxResult r = N.evaluate(cb, e->feat, p, NULL); + if (!NGX_OK(r)) return dl_fail("DLSS evaluation", r); + D.reset = 0; + D.last = e, e->used = D.evals + 1; + full_barrier(cb); + // the result back into the scene target, which the bloom, the post passes and the HUD read and draw over + VkImageBlit b = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, t->level, t->base_layer, 1}, + .dstOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}}; + vkCmdBlitImage(cb, e->out, VK_IMAGE_LAYOUT_GENERAL, t->image, VK_IMAGE_LAYOUT_GENERAL, 1, &b, VK_FILTER_NEAREST); + full_barrier(cb); + ex->recorded += 4; + vk_exec_draw_new_cb(); // NGX bound pipelines and descriptor sets of its own: the next draw binds everything again + D.jdepth = z->image; + next_jitter(); + if (++D.evals == 1 || D.evals % 3600 == 0) + rt_log("dlaa: %llu frames anti-aliased (scene %ux%u; %llu frames without the DLAA point, %llu with camera " + "motion, %llu without a camera, %llu jitter holds; resets: %llu size, %llu camera, %llu target)", + (unsigned long long)D.evals, w, h, (unsigned long long)D.frames_missed, + (unsigned long long)D.mv_frames, (unsigned long long)D.mv_none, (unsigned long long)D.holds, + (unsigned long long)D.why[0], (unsigned long long)D.why[1], (unsigned long long)D.why[2]); +} + +static int scene_color(VkFormat f) { + return f == VK_FORMAT_B10G11R11_UFLOAT_PACK32 || f == VK_FORMAT_R16G16B16A16_SFLOAT; +} + +void vk_dlaa_pass(VkExec *ex) { + const VkExecTarget *c = &ex->color[0], *z = &ex->depth; + if (!dl_active() || D.done) return; + // The G-buffer: several colour targets with a D32F depth of at least 640 wide. Only the light target drawn after it + // arms the frame; at night the game draws into the light target alone with the scene depth before the G-buffer too, + // and DLAA then ran at a small pass ahead of the whole scene, which reached the screen jittered. + if (ex->pass_ncolor >= 3 && z->image && z->format == VK_FORMAT_D32_SFLOAT && z->width >= 640) { + D.gbuf = 1, D.armed = 0; + return; + } + // the scene depth is D32F; a D16 target of the scene size also serves one composite pass before the transparents + if (D.gbuf && ex->pass_ncolor == 1 && c->image && scene_color(c->format) && z->image && z->format == VK_FORMAT_D32_SFLOAT && + c->width == z->width && c->height == z->height && c->width >= 640 && + c->samples <= 1 && !c->is3d) { + D.color = *c, D.depth = *z, D.armed = 1; + return; + } + if (!D.armed) return; + if (!ex->pass_w || ex->pass_w * 4 > D.color.width) return; + D.done = 1; + evaluate(ex); +} + +void vk_dlaa_frame(void) { + int on = N.available && cfg_bool("TOTK_DLAA"); + if (on != D.on) { + rt_log("dlaa: %s", on ? "on" : "off"); + D.on = on; + // either way the next DLAA frame starts a new history from an unjittered frame + D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = 0, D.hold = 0; + return; + } + if (!dl_active()) return; + if (!D.done) D.frames_missed++; + if (D.jit_used && !D.done) D.hold = 60, D.holds++; // jittered but not resolved: that frame shook + else if (D.hold) D.hold--; + if (!D.done) D.jit_ok = 0; + D.armed = D.done = D.jit_used = D.gbuf = 0; + D.cam_addr = 0; +} + +// ---------------------------------------------------------------- the game's FXAA (TOTK_FXAA, live) +// TotK's FXAA is two full-screen passes after the bloom, just before the HUD: one copies the scene target into a +// scratch target, the other draws the anti-aliased result back over the scene (found by diffing frame dumps with the +// game's own switch, ModelSceneExtensionParam EnableFXAA, on and off). With fxaa = 0 the draws of that second pass's +// fragment shader are skipped, so the scene reaches the HUD as it was. Shaders are known by the FNV-1a hash of their +// SPIR-V, as vk_dump.c names them; a translator change gives new hashes and the switch then does nothing. +#define FXAA_FS 0xf450003ebeb3dc52ull + +static uint64_t spirv_hash(const GfxShader *s) { + static struct { const GfxShader *s; uint64_t h; } tab[8192]; + uintptr_t k = ((uintptr_t)s >> 4) * 0x9E3779B97F4A7C15ull; + for (uint32_t i = 0, j = (uint32_t)(k >> 51); i < 8192; i++, j = (j + 1) & 8191) { + if (tab[j].s == s) return tab[j].h; + if (!tab[j].s) { + uint64_t words = 0, h = 0xcbf29ce484222325ull; + const uint8_t *b = (const uint8_t *)gfx_shader_spirv(s, &words); + for (uint64_t n = 0; b && n < words * 4; n++) h = (h ^ b[n]) * 0x100000001b3ull; + tab[j].s = s, tab[j].h = h; + return h; + } + } + return 0; // table full: no skip +} + +int vk_dlaa_skip_draw(const GfxShader *fs) { + static uint64_t frame_read = ~0ull; + static int fxaa = 1; + uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED); + if (f != frame_read) frame_read = f, fxaa = cfg_bool("TOTK_FXAA"); // once a frame: the menu switches it live + return !fxaa && fs && spirv_hash(fs) == FXAA_FS; +} diff --git a/runtime/vk_dlaa.h b/runtime/vk_dlaa.h new file mode 100644 index 00000000..4eb7ff3d --- /dev/null +++ b/runtime/vk_dlaa.h @@ -0,0 +1,22 @@ +// DLAA (vk_dlaa.c): NVIDIA DLSS at the scene's own size, behind TOTK_DLAA (totk.ini dlaa = 1). +#pragma once +#include "vk.h" + +int vk_dlaa_wanted(void); // the setting is on (the device may still lack DLSS) +// vk_device.c: NGX's instance and device extensions join the lists (room for max names); vk_dlaa_init after the +// device exists brings NGX up and checks that DLSS is available. +void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max); +void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max); +void vk_dlaa_init(void); +// vk_exec.c vk_exec_pass_begin, once the pass's targets are resolved and before its barrier: arms the frame on the +// scene's light target or, at the first quarter-width pass after it, runs DLAA on that target. Each present ends the +// frame (vk_dlaa_frame). +typedef struct VkExec VkExec; +void vk_dlaa_pass(VkExec *ex); +void vk_dlaa_frame(void); +// vk_exec_draw.c, each draw before its fixed state is recorded: notes the scene camera block (vk_dlaa_draw), and moves +// the viewport of the scene's draws by the frame's jitter (vk_dlaa_viewport, when the viewport is recorded). +void vk_dlaa_draw(VkExec *ex); +void vk_dlaa_viewport(VkExec *ex, VkViewport *v); +// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0). +int vk_dlaa_skip_draw(const GfxShader *fs); diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index d82c0574..572a9760 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -26,6 +26,7 @@ #include "tex.h" #include "vk.h" #include "vk_exec.h" +#include "vk_dlaa.h" #define WEAK __attribute__((weak)) #define CALL_DEPTH 8 @@ -418,6 +419,7 @@ void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); } void vk_exec_pass_begin(VkExec *ex) { if (ex->in_pass) return; resolve_rt(ex); + vk_dlaa_pass(ex); // DLAA runs before the bloom chain's first pass (vk_dlaa.c) // Learned targets (VkTexImage.fb_learned) are attached in the feedback layout VkImage want[9]; VkImageAspectFlags wasp[9]; diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 59ff9cbb..0f2fc2ec 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -27,6 +27,7 @@ #include "nvn_hmap.h" #include "vk.h" #include "vk_exec.h" +#include "vk_dlaa.h" #define MAX_BINDINGS 128 #define MAX_DESC 1024 @@ -1850,6 +1851,7 @@ static void record_fixed(VkExec *ex) { if (w < 1) w = 1; if (h < 1) h = 1; VkViewport v = {x, y + h, w, -h, ex->depth_range[0], ex->depth_range[1]}; // the y flip: negative height + vk_dlaa_viewport(ex, &v); // the scene's draws move by the DLAA jitter vkCmdSetViewportWithCount(cb, 1, &v); ex->recorded++; } @@ -2038,6 +2040,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { if (fs_wait) fs = shader_for(ex, NVN_STAGE_FS, &has_fs, NULL, 1); } if (!vs || (has_fs && !fs)) return 0; + if (vk_dlaa_skip_draw(fs)) return 0; // the game's FXAA, switched off (vk_dlaa.c) uint32_t fbl = feedback_prepare(ex, fs); VkPipeState s = ex->pipe; s.vs = vs, s.fs = fs; @@ -2108,6 +2111,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { ex->recorded++; B.st = s, B.st_valid = 1; } + vk_dlaa_draw(ex); record_fixed(ex); repeat_stats(ex, info); bind_resources(ex, info); diff --git a/totk.ini.example b/totk.ini.example index 30c3a2af..cb9e952f 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -118,6 +118,13 @@ # from 0 (off) to 100. Changes while the game runs take effect at once. # upscaler = fsr # sharpness = 80 +# NVIDIA DLAA: DLSS anti-aliasing of the 3D scene at its own resolution, on NVIDIA RTX GPUs with nvngx_dlss.dll (from +# NVIDIA's DLSS SDK) next to totk.exe; elsewhere the setting does nothing. Changes while the game runs take effect at +# once. +# dlaa = 0 +# The game's own FXAA after the post effects; with DLAA on it is not needed. Changes while the game runs take effect at +# once. +# fxaa = 1 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From bc5eb0cb15ceea409d1dc447e73036e73b16f557 Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 21:10:27 -0700 Subject: [PATCH 06/19] Narrow the sun shadow filter by the shadow map scale The deferred lighting shaders soften the sun shadow with four compares around the receiver, offset by element 56 .xy of their lighting block. The offset is in UV and the game sized it for its own 960x960 cascades, so with shadow_scale above 1 it spans that many more texels and the near cascade shows four separate copies of each edge. Translator patch 0011 multiplies those reads by the support buffer's new shadow_spread field in fragment shaders that sample a 2D array shadow texture, leaving fp_c4 (the cascade matrices) alone. support_fill writes 1 / shadow_scale there, so the spacing stays the game's in texels; at shadow_scale 1 the shaders behave as before. The support buffer grows to 1440 bytes and build_xlate.py expects eleven patches. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_exec_draw.c | 19 ++++- tools/build_xlate.py | 6 +- .../patches/0011-shadow-filter-spread.patch | 82 +++++++++++++++++++ totk.ini.example | 4 +- 4 files changed, 106 insertions(+), 5 deletions(-) create mode 100644 tools/xlate/patches/0011-shadow-filter-spread.patch diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 4f7276d0..4323d05d 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -32,7 +32,7 @@ #define MAX_DESC 1024 #define CHUNK_BYTES (4u << 20) #define ZERO_BYTES 65536u -#define SUPPORT_BYTES 1424u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... +#define SUPPORT_BYTES 1440u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... #define NVN_STAGE_VS 0 #define NVN_STAGE_FS 1 #define NVN_STAGE_CS 5 @@ -1265,6 +1265,22 @@ static const float *pcss_params(void) { return p; } +// The shadow_spread field of the support buffer: the factor translator patch 0011 applies to the lighting shaders' sun +// shadow filter offset (element 56 .xy of their lighting block), 1 / TOTK_SHADOW_SCALE. The game spaces its four +// compares for its own shadow map texels; with maps TOTK_SHADOW_SCALE times larger, the same offset in UV spans that +// many more texels and the near cascade shows four separate copies of each edge. Dividing by the scale keeps the game's +// spacing in texels. The offset is in UV of the shadow map, so the output resolution plays no part. The scale is read +// once, as vk_texture.c shadow_scale reads it: the maps keep the size they were made with. +static const float *shadow_spread_params(void) { + static float p[4] = {0, 0, 0, 0}; + if (p[0] == 0) { + int scale = cfg_int("TOTK_SHADOW_SCALE"); + scale = scale < 1 ? 1 : scale > 4 ? 4 : scale; + p[0] = 1.0f / (float)scale; + } + return p; +} + static void support_fill(uint8_t *b, float w, float h, float point_size) { memset(b, 0, SUPPORT_BYTES); float inv[4] = {w > 0 ? 2.0f / w : 0, h > 0 ? 2.0f / h : 0, 0, 0}, size[4] = {w, h, 0, 0}; @@ -1273,6 +1289,7 @@ static void support_fill(uint8_t *b, float w, float h, float point_size) { const float one = 1.0f; memcpy(b + 1392, &point_size, 4); // point_size (translator patch 0008): vertex shaders that write none output it memcpy(b + 1408, pcss_params(), 16); // pcss (translator patch 0010): soft sun shadows in the cascade compares + memcpy(b + 1424, shadow_spread_params(), 16); // shadow_spread (translator patch 0011): sun shadow filter width for (int i = 0; i < 73; i++) memcpy(b + 192 + 16 * i, &one, 4); // render scale 1: the host renders at guest size } diff --git a/tools/build_xlate.py b/tools/build_xlate.py index ef0d08bc..d721a8ed 100644 --- a/tools/build_xlate.py +++ b/tools/build_xlate.py @@ -1,7 +1,7 @@ """Build the shader translator: build/xlate/totk_xlate.exe (Ryujinx 1.3.2 + patches, NativeAOT, SPIR-V for Vulkan). Copies tools/vendor/ryujinx to build/xlate/ryujinx, applies tools/xlate/patches/*.patch there (tools/vendor stays -byte-identical; 0001-0004 are MNG's, 0005-0010 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build +byte-identical; 0001-0004 are MNG's, 0005-0011 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build tools and vswhere.exe (docs/building.md). Run with .venv. Next to the exe it writes totk_xlate.id: the translator identity, a sha256 over everything the build reads (this script, @@ -96,8 +96,8 @@ def prepare_sources() -> Path: for junk in list(src.glob("src/*/obj")) + list(src.glob("src/*/bin")): shutil.rmtree(junk) patches = sorted((XLATE / "patches").glob("*.patch")) - if len(patches) != 10: - sys.exit(f"expected 10 patches, found {len(patches)}") + if len(patches) != 11: + sys.exit(f"expected 11 patches, found {len(patches)}") for patch in patches: # git apply works outside a repository when given a directory; --check first so a failure names the patch. for extra in (["--check"], []): diff --git a/tools/xlate/patches/0011-shadow-filter-spread.patch b/tools/xlate/patches/0011-shadow-filter-spread.patch new file mode 100644 index 00000000..cd952174 --- /dev/null +++ b/tools/xlate/patches/0011-shadow-filter-spread.patch @@ -0,0 +1,82 @@ +--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs ++++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs +@@ -853,7 +853,51 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv + + private static OperationResult GenerateLoad(CodeGenContext context, AstOperation operation) + { +- return GenerateLoadOrStore(context, operation, isStore: false); ++ OperationResult result = GenerateLoadOrStore(context, operation, isStore: false); ++ if (result.Type == AggregateType.FP32 && IsShadowSpread(context, operation)) ++ { ++ SpvInstruction f32 = context.TypeFP32(), v4 = context.TypeVector(f32, 4); ++ SpvInstruction prmPtr = context.AccessChain(context.TypePointer(StorageClass.Uniform, v4), context.ConstantBuffers[SupportBuffer.Binding], ++ context.Constant(context.TypeS32(), (int)SupportBufferField.ShadowSpread)); ++ SpvInstruction factor = context.CompositeExtract(f32, context.Load(v4, prmPtr), 0); ++ result = new OperationResult(AggregateType.FP32, context.FMul(f32, result.Value, factor)); ++ } ++ ++ return result; ++ } ++ ++ // TOTK: the spread of the sun shadow filter. The deferred lighting shaders take the sun shadow as four compares ++ // at the receiver ± h on the cascade map, h = 0.5 * c[56].xy (UV) of their lighting block (fp_c9, or fp_c5 in ++ // some), the same in every cascade. In the near cascade the map is sharp enough that the four copies of an edge ++ // show apart. In a fragment shader that has a 2D array shadow sampler, reads of element 56 .x and .y from any ++ // constant buffer but fp_c4 (which holds the cascade matrices, row 56 being cascade 3's depth row) are multiplied ++ // by the support buffer's shadow_spread.x (runtime/vk_exec_draw.c support_fill, TOTK_SHADOW_SPREAD; 1 keeps the ++ // game's spread). ++ private static bool IsShadowSpread(CodeGenContext context, AstOperation load) ++ { ++ if (context.Definitions.Stage != ShaderStage.Fragment || ++ load.StorageKind != StorageKind.ConstantBuffer || ++ load.SourcesCount != 4 || ++ load.GetSource(0) is not AstOperand { Type: OperandType.Constant } binding || ++ load.GetSource(1) is not AstOperand { Type: OperandType.Constant, Value: 0 } || ++ load.GetSource(2) is not AstOperand { Type: OperandType.Constant, Value: 56 } || ++ load.GetSource(3) is not AstOperand { Type: OperandType.Constant, Value: < 2 } || ++ !context.Properties.ConstantBuffers.TryGetValue(binding.Value, out BufferDefinition buffer) || ++ buffer.Name == "fp_c4") ++ { ++ return false; ++ } ++ ++ foreach (TextureDefinition texture in context.Properties.Textures.Values) ++ { ++ if ((texture.Type & (SamplerType.Mask | SamplerType.Array | SamplerType.Shadow)) == ++ (SamplerType.Texture2D | SamplerType.Array | SamplerType.Shadow)) ++ { ++ return true; ++ } ++ } ++ ++ return false; + } + + private static OperationResult GenerateLod(CodeGenContext context, AstOperation operation) +--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs ++++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs +@@ -26,6 +26,7 @@ namespace Ryujinx.Graphics.Shader + TfeVertexCount, + PointSize, + Pcss, ++ ShadowSpread, + } + + public struct SupportBuffer +@@ -84,7 +85,8 @@ namespace Ryujinx.Graphics.Shader + new StructureField(AggregateType.Vector4 | AggregateType.S32, "tfe_offset"), + new StructureField(AggregateType.S32, "tfe_vertex_count"), + new StructureField(AggregateType.FP32, "point_size"), +- new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss") ++ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss"), ++ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "shadow_spread") + ]); + } + +@@ -101,5 +103,6 @@ namespace Ryujinx.Graphics.Shader + public Vector4 TfeVertexCount; + public Vector4 PointSize; + public Vector4 Pcss; ++ public Vector4 ShadowSpread; + } + } diff --git a/totk.ini.example b/totk.ini.example index 352f19c3..5722f8d1 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -120,7 +120,9 @@ # game's setting. Read at start. # aniso = 16 # Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game -# resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. Read at start. +# resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. The game's +# shadow edge filter is narrowed by the same factor (translator patch 0011), so close shadow edges don't look doubled. +# Read at start. # shadow_scale = 1 # Sun shadow cascade range in percent of the game's (its cascades end at 20, 40, 80 and 160 m), 50 to 400: higher moves # the steps where shadows turn softer further away, and spreads the shadow map over more ground. Read at start. From 45f24a72e391b8e77e2957355d2a7545fb0a56ba Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 21:10:35 -0700 Subject: [PATCH 07/19] Let TOTK_DUMP_UBO set how many vec4 of each uniform block are printed The value is now a count (1 still means 16, capped at 4096), so blocks such as the deferred lighting shaders' camera block, whose shadow cascade matrices sit at vec4 42 to 58, can be read from a frame dump. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_dump.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/runtime/vk_dump.c b/runtime/vk_dump.c index 151f39f3..f80dce4b 100644 --- a/runtime/vk_dump.c +++ b/runtime/vk_dump.c @@ -18,8 +18,8 @@ // as x/2+1/2, UNORM and sRGB bytes written as stored. Caps: MAX_PASSES passes copied, PNG_CAP bytes of PNGs. // TOTK_DUMP_TEX=|x[,...]: those texture slots, or 2D textures of that size, are copied where first sampled, // whatever their format. -// TOTK_DUMP_UBO=1: each listed pipeline also prints the first 16 vec4 of its user uniform blocks (c3 and up), read from -// guest memory when the entry is listed. A block the submission rewrites with UpdateUniformBuffer shows its value from +// TOTK_DUMP_UBO=: each listed pipeline also prints the first n vec4 of its user uniform blocks (c3 and up; 1 means 16, +// the cap is 4096), read from guest memory when the entry is listed. A block the submission rewrites with UpdateUniformBuffer shows its value from // before the submission (vk_exec_draw.c upd_note). // TOTK_DUMP_SKIP_RUNS=1: a render pass with the same targets as the render pass before it is logged but not copied // (the terrain decals draw one pass each into the G-buffer and would use up both caps). @@ -48,7 +48,7 @@ static uint64_t dump_frame, log_from; // log_from: TOTK_DUMP_LOG, first frame static char dir[400]; static FILE *passes_f, *images_f; static int seq, finished, copied; // copied: passes and dispatches of the dump frame whose images were copied -static int skip_runs, dump_ubo; // TOTK_DUMP_SKIP_RUNS, TOTK_DUMP_UBO +static int skip_runs, dump_ubo; // TOTK_DUMP_SKIP_RUNS, TOTK_DUMP_UBO (vec4 per block, 0 for none) static uint32_t want_tex[16][2]; // TOTK_DUMP_TEX: slot id and 0, or width and height static int nwant_tex; static uint64_t last_targets; // targets_sig of the last render pass; 0 after a dispatch @@ -576,7 +576,7 @@ static void describe_bindings(Str *b, const VkExec *ex, const VkPipeInfo *info) if (u->addr && vk_mem_resolve(u->addr, 1, &ms)) { uint64_t n = u->size && u->size < ms.avail ? u->size : ms.avail; const float *f = (const float *)(uintptr_t)u->addr; - for (uint64_t k = 0; k < 16 && (k + 1) * 16 <= n; k++) + for (uint64_t k = 0; k < (uint64_t)dump_ubo && (k + 1) * 16 <= n; k++) sp(b, "%s[%llu] %g %g %g %g", k % 4 ? " " : "\n ", (unsigned long long)k, f[4 * k], f[4 * k + 1], f[4 * k + 2], f[4 * k + 3]); } else { @@ -879,7 +879,10 @@ void vk_dump_init(void) { const char *sr = cfg_get("TOTK_DUMP_SKIP_RUNS"); skip_runs = sr && *sr && *sr != '0'; const char *du = cfg_get("TOTK_DUMP_UBO"); - dump_ubo = du && *du && *du != '0'; + dump_ubo = du && *du ? atoi(du) : 0; + if (dump_ubo == 1) dump_ubo = 16; + if (dump_ubo > 4096) dump_ubo = 4096; + if (dump_ubo < 0) dump_ubo = 0; const char *wt = cfg_get("TOTK_DUMP_TEX"); for (char *q = (char *)wt; q && *q && nwant_tex < 16; q += *q == ',') { uint32_t *w = want_tex[nwant_tex++]; From c193b2aefac0c62c1e49088f8d6c8ad3dbeb288f Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 21:58:22 -0700 Subject: [PATCH 08/19] Give each gamepad stick its own dead zone and show where the stick rests stick_deadzone sets one dead zone for both sticks, and finding the value that stops a drift means guessing. A worn stick usually drifts on its own while the other one is fine. lstick_deadzone and rstick_deadzone (0 to 50 percent, live) set one stick each and fall back to stick_deadzone while unset, so existing totk.ini files behave as before. input_pad_deadzone in input_map.c picks the value; input_pad_stick and its scaling stay as they are. The Controls tab shows Left and Right stick dead zone rows in place of the single one. With a gamepad connected each row shows its stick's deflection now, before the dead zone ("stick now"), so a drifting stick's resting value can be read off and the zone set just above it. opt_slider takes the note line and a fallback key for that: a row whose key is unset shows the fallback's value, and a change sets the key. probe-cfg checks the fallback, the clamp and input_stick_percent. The menu text is in English and Russian. Co-Authored-By: Claude Opus 5.5 --- docs/controls.md | 2 +- runtime/cfg.c | 9 +++++---- runtime/cfg_probe.c | 17 +++++++++++++++++ runtime/input.h | 4 ++++ runtime/input_map.c | 10 ++++++++++ runtime/input_map.h | 6 ++++++ runtime/input_win.c | 35 +++++++++++++++++++++++++---------- runtime/ui/menu.cpp | 11 ++++++++++- runtime/ui/option_rows.cpp | 11 +++++++---- runtime/ui/option_rows.h | 4 +++- runtime/ui_text.c | 10 ++++++---- runtime/ui_text.h | 2 +- totk.ini.example | 4 ++++ 13 files changed, 99 insertions(+), 26 deletions(-) diff --git a/docs/controls.md b/docs/controls.md index b80fc89c..2333d41c 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -68,7 +68,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_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` (the *Left/Right stick dead zone* rows on the Controls tab) set one stick each and fall back to `TOTK_STICK_DEADZONE` while unset, so a worn stick can get a larger zone than the other. With a gamepad connected each row shows its stick's deflection now, before the dead zone (*stick now*): let go of the stick and set the row a few percent above the value it rests at. 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`. diff --git a/runtime/cfg.c b/runtime/cfg.c index e9d8fc13..f51a5eda 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -39,14 +39,14 @@ static const char *const known[] = { "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "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_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "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", @@ -63,7 +63,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"}, {"STICK_DEADZONE", "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"}, @@ -104,7 +104,8 @@ 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", LIVE}, - {"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, + {"STICK_DEADZONE", "8", "0..50", LIVE}, + {"LSTICK_DEADZONE", "", "0..50", LIVE}, {"RSTICK_DEADZONE", "", "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}, diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index 0fc40a42..6f733469 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -1,4 +1,5 @@ // --probe-cfg: totk.ini parsing, the environment override and a missing file (cfg.c). Needs no game files. +#include #include #include #include @@ -272,6 +273,22 @@ int probe_cfg(void) { "pad stick: a square gate's corner stays on the unit circle"); input_pad_stick(0, 32767 / 2 + 1, 0.2f, st); CHECK(abs(st[1] - 32767 * 3 / 8) <= 3, "pad stick: half deflection past a 20% zone is (0.5 - 0.2) / 0.8 of full"); + _putenv_s("TOTK_STICK_DEADZONE", "12"); + _putenv_s("TOTK_LSTICK_DEADZONE", ""); + _putenv_s("TOTK_RSTICK_DEADZONE", ""); + CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.12f) < 1e-6f, + "pad dead zone: both sticks follow stick_deadzone while lstick/rstick are unset"); + _putenv_s("TOTK_RSTICK_DEADZONE", "20"); + CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.20f) < 1e-6f, + "pad dead zone: rstick_deadzone sets the right stick alone"); + _putenv_s("TOTK_LSTICK_DEADZONE", "80"); + CHECK(fabsf(input_pad_deadzone(0) - 0.5f) < 1e-6f, "pad dead zone: clamped to 50%"); + _putenv_s("TOTK_STICK_DEADZONE", ""); + _putenv_s("TOTK_LSTICK_DEADZONE", ""); + _putenv_s("TOTK_RSTICK_DEADZONE", ""); + CHECK(input_stick_percent(32767, 0) > 99.99 && input_stick_percent(32767, 0) < 100.01 && + input_stick_percent(0, 0) == 0 && fabs(input_stick_percent(3000, -4000) - 5000 * 100.0 / 32767) < 1e-9, + "stick percent: an axis's end is 100%, the centre 0%, round in between"); // Gamepad layouts (input_map.c) CHECK(input_pad_layout_pick("auto", 1) == PAD_LAYOUT_NINTENDO && input_pad_layout_pick(NULL, 0) == PAD_LAYOUT_XBOX, "pad layout: automatic is Nintendo for an east button labelled A, Xbox otherwise"); diff --git a/runtime/input.h b/runtime/input.h index 5efc17ac..7bf0a37e 100644 --- a/runtime/input.h +++ b/runtime/input.h @@ -23,6 +23,10 @@ int input_menu_gate(int *held, int menu_open, uint64_t *buttons, int32_t sticks[ int input_pad_read(uint64_t *buttons, int32_t *lx, int32_t *ly); // The gamepad layout in effect (PAD_LAYOUT_*, input_map.h; TOTK_PAD_LAYOUT, live); -1 without a gamepad. Any thread. int input_pad_layout(void); +// How far the open gamepad's left (pct[0]) and right (pct[1]) sticks are from the centre now, in percent of full +// deflection, before the dead zone: the menu shows it on the dead zone rows, so a drifting stick's resting value can be +// read off. 0 (and both 0) without a connected gamepad. Any thread. +int input_pad_stick_percent(double pct[2]); // The label on a face button of the open gamepad (input_map.h PAD_SOUTH..PAD_NORTH, as SDL reports it); PAD_LABEL_NONE for another // button, an unknown label or no gamepad. Any thread. enum { PAD_LABEL_NONE, PAD_LABEL_A, PAD_LABEL_B, PAD_LABEL_X, PAD_LABEL_Y, PAD_LABEL_CROSS, PAD_LABEL_CIRCLE, diff --git a/runtime/input_map.c b/runtime/input_map.c index 5c5e06c8..780114a7 100644 --- a/runtime/input_map.c +++ b/runtime/input_map.c @@ -334,6 +334,16 @@ void input_pad_stick(int32_t x, int32_t y, float dead, int32_t out[2]) { out[1] = (int32_t)lrint(fmax(-1, fmin(1, fy * k)) * STICK_MAX); } +float input_pad_deadzone(int stick) { + const char *own = stick ? "TOTK_RSTICK_DEADZONE" : "TOTK_LSTICK_DEADZONE", *set = cfg_get(own); + double v = cfg_double(set && *set ? own : "TOTK_STICK_DEADZONE"); + return (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f; +} + +double input_stick_percent(int32_t x, int32_t y) { + return sqrt((double)x * x + (double)y * y) * 100.0 / STICK_MAX; +} + // Minus and Plus held together open or close the menu. *held: latched from the poll where both go down until neither is // down (the caller keeps it). Every poll of the latch reports neither to the game, so releasing one button first does not // leak the other; Minus alone before Plus reaches the game unchanged. With the menu open the game sees a neutral pad. diff --git a/runtime/input_map.h b/runtime/input_map.h index fe524fa6..18db80df 100644 --- a/runtime/input_map.h +++ b/runtime/input_map.h @@ -95,6 +95,12 @@ void input_mouse_stick(int32_t dx, int32_t dy, double dt_s, float sens, int32_t // 0..0.5): inside the circle the stick reads 0, and the rest of the travel is scaled to start at 0 at the edge, so a // drifting stick rests at 0 and full deflection still reaches full. The result stays inside the unit square. void input_pad_stick(int32_t x, int32_t y, float dead, int32_t out[2]); +// The dead zone of gamepad stick 0 (left) or 1 (right) for input_pad_stick, as a fraction of full deflection: +// TOTK_LSTICK_DEADZONE or TOTK_RSTICK_DEADZONE when set, else TOTK_STICK_DEADZONE (both sticks), percent clamped to 0..50. +float input_pad_deadzone(int stick); +// How far a stick (x, y in -32768..32767) is from the centre, in percent of full deflection (100 at an axis's end; a +// square gate's corner reads more). +double input_stick_percent(int32_t x, int32_t y); // ---- the remapping rows' edits, on a copy of input_map. Pure. // action's keys (table order) / its gamepad buttons in layout, at most max; returns how many. diff --git a/runtime/input_win.c b/runtime/input_win.c index 096fef53..14041341 100644 --- a/runtime/input_win.c +++ b/runtime/input_win.c @@ -428,16 +428,17 @@ 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) +static float stick_dead[2] = {-1, -1}; // input_pad_deadzone of the left and right stick; live (cfg_version) static unsigned stick_dead_seen; -static float stick_dead_get(void) { +static float stick_dead_get(int s) { 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; + stick_dead[0] = input_pad_deadzone(0); + stick_dead[1] = input_pad_deadzone(1); + } + return stick_dead[s]; } // One gamepad stick through the dead zone; SDL's Y grows downwards, the Switch's upwards. @@ -557,12 +558,26 @@ 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); + stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, stick_dead_get(0), sl); + stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, stick_dead_get(1), sr); return 1; } +int input_pad_stick_percent(double pct[2]) { + int ok = 0; + pct[0] = pct[1] = 0; + AcquireSRWLockExclusive(&lock); + if (state == 1 && pad && SDL_GamepadConnected(pad)) { // the game's poll keeps the state fresh (SDL_UpdateGamepads) + pct[0] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX), + SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY)); + pct[1] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX), + SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY)); + ok = 1; + } + ReleaseSRWLockExclusive(&lock); + return ok; +} + static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) { uint64_t b = 0; int32_t sl[2] = {0, 0}, sr[2] = {0, 0}; diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 86c2bc5f..d6b7dd80 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -573,7 +573,16 @@ 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 %%"); + // One row per stick, falling back to TOTK_STICK_DEADZONE (both sticks) while unset. With a gamepad connected each + // row shows its stick's deflection now, before the dead zone: a drifting stick's resting value, to set it above. + double now[2]; + bool pad = input_pad_stick_percent(now) != 0; + char note[2][64]; + for (int s = 0; s < 2; s++) snprintf(note[s], sizeof note[s], menu_text(UI_MENU_STICK_DEADZONE_NOW), now[s]); + opt_slider("TOTK_LSTICK_DEADZONE", UI_MENU_LSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%", + pad ? note[0] : nullptr, "TOTK_STICK_DEADZONE"); + opt_slider("TOTK_RSTICK_DEADZONE", UI_MENU_RSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%", + pad ? note[1] : nullptr, "TOTK_STICK_DEADZONE"); opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f"); binds_rows(scale); opt_end(); diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp index f0f82b36..895c14b1 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -294,12 +294,15 @@ bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, U return opt_choice_list(key, label, values, shown, n, desc, -1, note); } -bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt) { - const CfgMeta *m = cfg_meta(key); - double v = cfg_double(key), def = m ? strtod(m->def, NULL) : lo; +bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt, + const char *note, const char *fallback) { + 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; char shown[48]; snprintf(shown, sizeof shown, fmt, v); - RowView rv = {shown, fabs(v - def) < step * 0.01, true, NULL}; + RowView rv = {shown, fabs(v - def) < step * 0.01, true, note}; int s = row(key, label, desc, rv); if (!s) return false; int steps = g_held && (hi - lo) > 40 * step ? 10 : 1; // held: ten steps at a time over a long range diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 6e03faf8..07f32ddc 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -46,8 +46,10 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values, // shown on the right ("" none). bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value = ""); // 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. bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1, - const char *fmt = "%g"); + const char *fmt = "%g", const char *note = nullptr, const char *fallback = nullptr); // Binding rows (remapping on the Controls tab): a label and three cells, each selectable on its own (left / right move between them). // opt_bind_header: the column titles above them. opt_bind_row: key is the setting's name without TOTK_ (BIND_A; the diff --git a/runtime/ui_text.c b/runtime/ui_text.c index b17ebb02..2bd03bb1 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -97,8 +97,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { "Nintendo for controllers with Nintendo labels and Xbox for the others.", [UI_MENU_PAD_LAYOUT_AUTO] = "Automatic", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A right)", [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s", - [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_LSTICK_DEADZONE] = "Left stick dead zone", [UI_MENU_RSTICK_DEADZONE] = "Right 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: let go of the stick, read \"stick now\" and set the dead zone a few percent above it.", + [UI_MENU_STICK_DEADZONE_NOW] = "stick now: %.0f %%", [UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity", [UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.", @@ -317,8 +318,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных.", [UI_MENU_PAD_LAYOUT_AUTO] = "Автоматически", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A справа)", [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", - [UI_MENU_STICK_DEADZONE] = "Мёртвая зона стиков", - [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами.", + [UI_MENU_LSTICK_DEADZONE] = "Мёртвая зона левого стика", [UI_MENU_RSTICK_DEADZONE] = "Мёртвая зона правого стика", + [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами: отпустите стик, посмотрите «стик сейчас» и поставьте мёртвую зону на несколько процентов выше.", + [UI_MENU_STICK_DEADZONE_NOW] = "стик сейчас: %.0f %%", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", [UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 24975758..d7250b02 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -57,7 +57,7 @@ typedef enum { UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC, 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_IN_USE, - UI_MENU_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, + UI_MENU_LSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, UI_MENU_STICK_DEADZONE_NOW, 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 522e247b..03a4d0e1 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -153,6 +153,10 @@ # 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 +# The dead zone of one stick, in place of stick_deadzone for that stick (0 to 50; unset = stick_deadzone). The Controls +# tab shows each stick's deflection now, so a drifting stick's resting value can be read off. +# 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 5dcac19982a8ee4a69ab6cc16c26f0f38659f254 Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 22:56:47 -0700 Subject: [PATCH 09/19] Force anisotropic filtering only on samplers that tile The aniso setting raised every filtered, mipmapped colour sampler to the chosen level. Some of those read screen-sized buffers, among them the ones the inventory's character preview is drawn from. Their coordinates stretch steeply at the model's edges, so the anisotropic taps reach across the edge and leave a speckled fringe around the character. The level is now raised only for samplers that repeat on U and V, which the surface textures it is meant for do; clamped samplers keep the game's level. Distant ground stays as sharp as before. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_texture.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index ce7619f7..14d11067 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -1505,9 +1505,14 @@ static VkSampler make_sampler(VkCtx *c, const samp_par *d) { float lim = c->props.limits.maxSamplerLodBias; si.mipLodBias = fmaxf(-lim, fminf(lim, d->lod_bias)); float aniso = d->aniso; - // TOTK_ANISO raises the level for filtered, mipmapped colour samplers only: depth-compare (shadow) samplers and - // nearest or unmipmapped ones (data maps, LUTs) keep what the game set. - if (aniso_force > 1 && !d->cmp_mode && si.magFilter == VK_FILTER_LINEAR && si.minFilter == VK_FILTER_LINEAR && + // TOTK_ANISO raises the level for filtered, mipmapped colour samplers that repeat on U and V only: the surface + // textures it is for tile. Depth-compare (shadow) samplers, nearest or unmipmapped ones (data maps, LUTs) and clamped + // ones keep what the game set. Clamped samplers read screen-sized buffers, whose coordinates can stretch steeply at + // an object's edge; there anisotropic taps reach across the edge and leave a speckled fringe (the inventory's + // character preview). + int tiled = (modes[0] == VK_SAMPLER_ADDRESS_MODE_REPEAT || modes[0] == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT) && + (modes[1] == VK_SAMPLER_ADDRESS_MODE_REPEAT || modes[1] == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); + if (aniso_force > 1 && tiled && !d->cmp_mode && si.magFilter == VK_FILTER_LINEAR && si.minFilter == VK_FILTER_LINEAR && (mf == NVN_MIN_FILTER_LINEAR_MIPMAP_NEAREST || mf == NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR) && aniso < aniso_force) aniso = aniso_force; if (aniso > 1) { From 2e8b4ff1b1f3becd4ddc505b1a0ffba895f45fdb Mon Sep 17 00:00:00 2001 From: DizzyMan1337 Date: Sat, 31 Oct 2026 14:39:20 +0800 Subject: [PATCH 10/19] DLSS upscaling: quality, balanced and performance modes TOTK_DLSS (dlaa|quality|balanced|performance, read at start) sets the scene to 67, 58 or 50 % of the output. DLSS then runs at the begin of the game's scaling pass (the FXAA shader drawing the light target into the output-sized target, before the HUD) and its result replaces that draw; the HUD is drawn afterwards and never jittered or passed through DLSS. The jitter now ends where the scene ends (the bloom), separately from where DLSS runs. Scaled modes add a mip bias of log2(scale) to repeating, mipmapped material samplers. With a scene smaller than the output, fxaa = 0 no longer skips the game's scaling draw (it left the 3D picture out). Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 6 +-- runtime/host.h | 1 + runtime/resolution.c | 19 ++++++- runtime/ui/menu.cpp | 3 ++ runtime/ui_text.c | 24 ++++++--- runtime/ui_text.h | 3 +- runtime/vk_dlaa.c | 114 ++++++++++++++++++++++++++++------------- runtime/vk_dlaa.h | 5 +- runtime/vk_exec_draw.c | 2 +- runtime/vk_texture.c | 10 +++- totk.ini.example | 10 ++-- 11 files changed, 141 insertions(+), 56 deletions(-) diff --git a/runtime/cfg.c b/runtime/cfg.c index 46af3931..d495c1fb 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -36,7 +36,7 @@ static const char *const known[] = { "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DLAA", - "DLAA_JITTER", "DLAA_MV", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", + "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", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", @@ -60,7 +60,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ASPECT", "display"}, {"DLAA", "display"}, {"FXAA", "display"}, + {"SHARPNESS", "display"}, {"ASPECT", "display"}, {"DLAA", "display"}, {"DLSS", "display"}, {"FXAA", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -95,7 +95,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, - {"DLAA", "0", "0|1", LIVE}, {"FXAA", "1", "0|1", LIVE}, + {"DLAA", "0", "0|1", LIVE}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance", RESTART}, {"FXAA", "1", "0|1", LIVE}, {"ASPECT", "fit", "fit|stretch", LIVE}, // Game {"FPS_LIMIT", "60", "30|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, diff --git a/runtime/host.h b/runtime/host.h index 7e4a1939..5f427bde 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -240,6 +240,7 @@ int res_heapdef_build(const void *in, size_t n, void **out, size_t *out_n); // // the grown heaps, malloc'd; 0 = cannot (logged) void res_heapdef_served(void); // romfs.c serves the grown table void res_init(void); // after rt_patches_init: the patch page and the sets +float res_dlss_lod_bias(void); // TOTK_DLSS upscaling: texture LOD bias (<= 0) void res_sizes(unsigned out[2], unsigned scene[2]); // the output and scene sizes in effect (the game's own // until res_init switched the sets on) int res_is_16x9(unsigned w, unsigned h); // within 1% of 16:9 (the test res_init and romfs.c share) diff --git a/runtime/resolution.c b/runtime/resolution.c index 514b3e6e..ca2e9aee 100644 --- a/runtime/resolution.c +++ b/runtime/resolution.c @@ -49,6 +49,7 @@ static struct { int scene_set; // the scene differs from the game's 5/6 of the output int heapdef_ok; // romfs.c serves the grown HeapDef int on; // res_init switched the patch sets on + double dlss_k; // TOTK_DLSS quality/balanced/performance: the scene's share of the output, else 0 } R; static void decide(void) { @@ -67,7 +68,16 @@ static void decide(void) { } const char *s = cfg_value("TOTK_RENDER_SCALE"); double k = 5.0 / 6.0; - if (strcmp(s, "game")) { + const char *m = cfg_value("TOTK_DLSS"); // a DLSS mode other than dlaa sets the scene size + static const struct { const char *name; double k; } dlss[] = { + {"quality", 2.0 / 3.0}, {"balanced", 0.58}, {"performance", 0.5}}; + for (int i = 0; i < 3; i++) + if (!strcmp(m, dlss[i].name)) R.dlss_k = dlss[i].k; + if (R.dlss_k) { + k = R.dlss_k; + R.scene_set = 1; + rt_log("resolution: DLSS %s: the scene at %.0f %% of the output (render_scale ignored)", m, k * 100); + } else if (strcmp(s, "game")) { char *end; double pct = strtod(s, &end); if (end != s && !*end && pct >= 25 && pct <= 400) { @@ -241,6 +251,13 @@ void res_init(void) { scene_on ? "" : " (the game's own 5/6 of the output)", (unsigned long long)res_heap_extra_kib()); } +// DLSS upscaling: textures are sampled for the output's resolution, not the scene's (NVIDIA's DLSS guide: a mip bias +// of log2(render / output)), so their detail survives the scaling. 0 without a DLSS mode. +float res_dlss_lod_bias(void) { + decide(); + return R.dlss_k ? (float)log2(R.dlss_k) : 0.0f; +} + // 16:9 within 1% (1366x768 counts): the shape the game's own layouts and camera are made for. int res_is_16x9(unsigned w, unsigned h) { double rel = ((double)w / h) / ((double)BASE_W / BASE_H); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 7b7a83e2..ba8f8b1d 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -542,6 +542,9 @@ static void tab_screen(float scale) { static const UiTextId aspect[] = {UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH}; opt_choice("TOTK_ASPECT", UI_MENU_ASPECT, aspect, 2, UI_MENU_ASPECT_DESC); opt_toggle("TOTK_DLAA", UI_MENU_DLAA, UI_MENU_DLAA_DESC); + static const UiTextId dlss[] = {UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED, + UI_MENU_DLSS_PERFORMANCE}; + opt_choice("TOTK_DLSS", UI_MENU_DLSS, dlss, 4, UI_MENU_DLSS_DESC); opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 87daf846..11358991 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -68,9 +68,15 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_ASPECT_FIT] = "Black bars", [UI_MENU_ASPECT_STRETCH] = "Stretch", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", - [UI_MENU_DLAA] = "NVIDIA DLAA", - [UI_MENU_DLAA_DESC] = "DLSS anti-aliasing of the 3D scene at its own resolution (NVIDIA RTX GPUs; nvngx_dlss.dll next to " - "totk.exe). Smoother edges and less shimmer for about 3 ms a frame.", + [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", + [UI_MENU_DLAA_DESC] = "NVIDIA DLSS for the 3D scene (NVIDIA RTX GPUs; nvngx_dlss.dll next to totk.exe): smoother edges " + "and less shimmer. The HUD is not touched. The mode below sets the resolution it works from.", + [UI_MENU_DLSS] = "DLSS mode", + [UI_MENU_DLSS_DESC] = "DLAA draws the 3D scene at full resolution. Quality, Balanced and Performance draw it at 67, 58 " + "and 50 % and let DLSS scale it up, for more frames per second; they replace the 3D render " + "scale. Takes effect after a restart.", + [UI_MENU_DLSS_DLAA] = "DLAA (native)", [UI_MENU_DLSS_QUALITY] = "Quality", [UI_MENU_DLSS_BALANCED] = "Balanced", + [UI_MENU_DLSS_PERFORMANCE] = "Performance", [UI_MENU_FXAA] = "Game anti-aliasing (FXAA)", [UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.", @@ -308,9 +314,15 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_ASPECT_FIT] = "Чёрные полосы", [UI_MENU_ASPECT_STRETCH] = "Растянуть", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", - [UI_MENU_DLAA] = "NVIDIA DLAA", - [UI_MENU_DLAA_DESC] = "Сглаживание 3D-сцены через DLSS в её собственном разрешении (видеокарты NVIDIA RTX; nvngx_dlss.dll " - "рядом с totk.exe). Ровнее края и меньше мерцания, около 3 мс на кадр.", + [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", + [UI_MENU_DLAA_DESC] = "NVIDIA DLSS для 3D-сцены (видеокарты NVIDIA RTX; nvngx_dlss.dll рядом с totk.exe): ровнее края и " + "меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он работает.", + [UI_MENU_DLSS] = "Режим DLSS", + [UI_MENU_DLSS_DESC] = "DLAA рисует 3D-сцену в полном разрешении. «Качество», «Баланс» и «Производительность» рисуют её " + "в 67, 58 и 50 % и масштабируют через DLSS ради большего числа кадров; они заменяют масштаб " + "3D-отрисовки. Действует после перезапуска.", + [UI_MENU_DLSS_DLAA] = "DLAA (родное)", [UI_MENU_DLSS_QUALITY] = "Качество", [UI_MENU_DLSS_BALANCED] = "Баланс", + [UI_MENU_DLSS_PERFORMANCE] = "Производительность", [UI_MENU_FXAA] = "Сглаживание игры (FXAA)", [UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index e1e55dba..66b45db6 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -37,7 +37,8 @@ typedef enum { UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR, UI_MENU_ASPECT, UI_MENU_ASPECT_DESC, UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, - UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_FXAA, UI_MENU_FXAA_DESC, + UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_DLSS, UI_MENU_DLSS_DESC, UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, + UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_FXAA, UI_MENU_FXAA_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_90, UI_MENU_FPS_120, diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c index 9de36e8a..41de947d 100644 --- a/runtime/vk_dlaa.c +++ b/runtime/vk_dlaa.c @@ -28,7 +28,7 @@ typedef int NgxResult; // NVSDK_NGX_Result: 1 success, 0xBAD00000 | n failures #define NGX_OK(r) (((unsigned)(r) & 0xFFF00000u) != 0xBAD00000u) #define NGX_VERSION_API 0x15 #define NGX_FEATURE_SUPERSAMPLING 1 -#define NGX_PERFQ_DLAA 5 +#define NGX_PERFQ_DLAA 5 // NVSDK_NGX_PerfQuality_Value: 0 performance, 1 balanced, 2 quality, 3 ultra performance typedef struct NgxParam NgxParam; typedef struct NgxHandle NgxHandle; typedef struct { void *slot[17]; } NgxParamVtbl; @@ -203,13 +203,21 @@ void vk_dlaa_init(void) { // quarter of the scene starts the bloom chain, which reads it. After the bloom come the tonemap and post passes, then // the HUD is drawn into the same target and a last pass copies it to the 8-bit output. // So: after the G-buffer, a pass at the scene size with exactly one colour target (R11G11B10F or RGBA16F) and the D32F -// depth arms the frame with that pair; the next pass at most a quarter as wide runs DLAA on the armed target first. -// Bloom, tonemap, post and HUD then all work on the anti-aliased picture. +// depth arms the frame with that pair; the next pass at most a quarter as wide ends the scene (no jitter after it) and, +// when the scene is as wide as the output, runs DLAA on the armed target first. Bloom, tonemap, post and HUD then all +// work on the anti-aliased picture. +// Upscaling (a scene smaller than the output: TOTK_DLSS quality/balanced/performance, or the game's own 5/6): measured +// at a 960x536 scene, 1920x1080 output, the bloom and its composite write back into the light target at the scene size, +// then one full-screen draw (the FXAA shader below, which also scales) reads it into an output-sized R11G11B10F target +// with no depth, and the HUD is drawn over that target at the output size. DLSS runs at the begin of that pass: it +// reads the light target and its result is blitted into the pass's target, whose scaling draw is then skipped. The +// HUD, drawn afterwards into the same target, is never jittered nor passed through DLSS. static struct { VkExecTarget color, depth; // the armed pair, valid in the frame it was armed int armed, done, gbuf; // this frame: armed on the light target, DLAA ran, the G-buffer was drawn + int ended, up; // this frame: the scene is drawn (jitter over), DLSS wrote the scaled output struct Size { // a DLSS feature and its work images per scene size (dynamic resolution flips it) - uint32_t w, h; + uint32_t w, h, ow, oh; // render size, output size VkImage out, mv; VmaAllocation out_mem, mv_mem; VkImageView out_view, mv_view; @@ -275,13 +283,14 @@ static void free_size(struct Size *e) { memset(e, 0, sizeof *e); } -// The entry for a scene size: its output (RGBA16F, written by DLSS, then blitted back into the scene target) and -// motion vectors (RG16F, render pixels), both kept in GENERAL like every image of the back end. TotK's dynamic -// resolution switches between a few sizes; each keeps its feature, the least recently used goes for a new one. -static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { +// The entry for a scene and output size: its output (RGBA16F at the output size, written by DLSS, then blitted into +// the target) and motion vectors (RG16F at the scene size, render pixels), both kept in GENERAL like every image of the +// back end. TotK's dynamic resolution switches between a few sizes; each keeps its feature, the least recently used +// goes for a new one. +static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h, uint32_t ow, uint32_t oh) { struct Size *e = NULL, *lru = &D.sizes[0]; for (int i = 0; i < 3; i++) { - if (D.sizes[i].w == w && D.sizes[i].h == h) return &D.sizes[i]; + if (D.sizes[i].w == w && D.sizes[i].h == h && D.sizes[i].ow == ow && D.sizes[i].oh == oh) return &D.sizes[i]; if (!D.sizes[i].out && !e) e = &D.sizes[i]; if (D.sizes[i].used < lru->used) lru = &D.sizes[i]; } @@ -291,7 +300,7 @@ static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { } VkImageUsageFlags u = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (!image2d(w, h, VK_FORMAT_R16G16B16A16_SFLOAT, u, &e->out, &e->out_mem, &e->out_view) || + if (!image2d(ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, u, &e->out, &e->out_mem, &e->out_view) || !image2d(w, h, VK_FORMAT_R16G16_SFLOAT, u, &e->mv, &e->mv_mem, &e->mv_view)) return NULL; VkImageMemoryBarrier2 ib[2]; @@ -308,7 +317,7 @@ static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { VkDependencyInfo di = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .imageMemoryBarrierCount = 2, .pImageMemoryBarriers = ib}; vkCmdPipelineBarrier2(cb, &di); - e->w = w, e->h = h; + e->w = w, e->h = h, e->ow = ow, e->oh = oh; return e; } @@ -435,13 +444,13 @@ static float halton(uint32_t i, uint32_t b) { } void vk_dlaa_viewport(VkExec *ex, VkViewport *v) { - if (!D.jit_ok || D.done || !ex->depth.image || ex->depth.image != D.jdepth) return; + if (!D.jit_ok || D.ended || !ex->depth.image || ex->depth.image != D.jdepth) return; v->x += D.jx, v->y += D.jy; D.ux = D.jx, D.uy = D.jy, D.jit_used = 1; } void vk_dlaa_draw(VkExec *ex) { - if (!dl_active() || D.done) return; + if (!dl_active() || D.ended) return; const p_bind_buf *b = &ex->ubo[0][1]; // constant bank c4: the replay keeps user banks from c3 on const VkExecTarget *z = &ex->depth; if (b->size == 0x940 && b->addr && z->image && z->width >= 640 && z->format == VK_FORMAT_D32_SFLOAT && @@ -460,12 +469,21 @@ static void next_jitter(void) { D.jit_ok = !D.hold && !nj; } -static void evaluate(VkExec *ex) { +// The quality setting DLSS is created with, from the scene's share of the output width. +static int perf_quality(uint32_t w, uint32_t ow) { + if (w >= ow) return NGX_PERFQ_DLAA; + double k = (double)w / ow; + return k >= 0.66 ? 2 : k >= 0.57 ? 1 : k >= 0.49 ? 0 : 3; +} + +// dst: the target DLSS's picture goes to, NULL for the light target itself (DLAA in place). +static void evaluate(VkExec *ex, const VkExecTarget *dst) { const VkExecTarget *t = &D.color, *z = &D.depth; - uint32_t w = t->width, h = t->height; + if (!dst) dst = t; + uint32_t w = t->width, h = t->height, ow = dst->width, oh = dst->height; VkCommandBuffer cb = ex->cb; vk_exec_barrier(ex); // what drew the scene is done (no pass is open here) - struct Size *e = size_for(cb, w, h); + struct Size *e = size_for(cb, w, h, ow, oh); if (!e) return dl_fail("work image creation", 0); if (e != D.last) D.reset = 1, D.why[0]++; // another size's history is from another moment if (!D.params && !NGX_OK(N.alloc_params(&D.params))) return dl_fail("parameter allocation", 0); @@ -488,23 +506,23 @@ static void evaluate(VkExec *ex) { p_setu(p, "VisibilityNodeMask", 1); p_setu(p, "Width", w); p_setu(p, "Height", h); - p_setu(p, "OutWidth", w); - p_setu(p, "OutHeight", h); - p_seti(p, "PerfQualityValue", NGX_PERFQ_DLAA); + p_setu(p, "OutWidth", ow); + p_setu(p, "OutHeight", oh); + p_seti(p, "PerfQualityValue", perf_quality(w, ow)); // IsHDR | MVLowRes | AutoExposure: linear scene light, motion vectors at the render size, no exposure texture p_seti(p, "DLSS.Feature.Create.Flags", (1 << 0) | (1 << 1) | (1 << 6)); p_seti(p, "DLSS.Enable.Output.Subrects", 0); NgxResult r = N.create(cb, NGX_FEATURE_SUPERSAMPLING, p, &e->feat); if (!NGX_OK(r) || !e->feat) return dl_fail("DLSS feature creation", r); D.reset = 1; - rt_log("dlaa: DLSS feature created at %ux%u (scene format %d, depth format %d)", w, h, (int)t->format, - (int)z->format); + rt_log("dlaa: DLSS feature created at %ux%u -> %ux%u, quality value %d (scene format %d, depth format %d)", w, + h, ow, oh, perf_quality(w, ow), (int)t->format, (int)z->format); } if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image; VkImageView cv = vk_exec_target_view(t->img, t->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT, t->level, t->base_layer, 1, 0); NgxResourceVK rc = res_image(cv, t->image, t->format, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); - NgxResourceVK ro = res_image(e->out_view, e->out, VK_FORMAT_R16G16B16A16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 1); + NgxResourceVK ro = res_image(e->out_view, e->out, VK_FORMAT_R16G16B16A16_SFLOAT, ow, oh, VK_IMAGE_ASPECT_COLOR_BIT, 1); NgxResourceVK rz = res_image(zv, z->image, z->format, w, h, VK_IMAGE_ASPECT_DEPTH_BIT, 0); NgxResourceVK rm = res_image(e->mv_view, e->mv, VK_FORMAT_R16G16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); p_setp(p, "Color", &rc); @@ -527,21 +545,22 @@ static void evaluate(VkExec *ex) { D.reset = 0; D.last = e, e->used = D.evals + 1; full_barrier(cb); - // the result back into the scene target, which the bloom, the post passes and the HUD read and draw over + // the result into the scene target (DLAA: the bloom, the post passes and the HUD read it and draw over it) or into + // the scaling pass's target (the HUD draws over it) VkImageBlit b = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}, - .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, t->level, t->base_layer, 1}, - .dstOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}}; - vkCmdBlitImage(cb, e->out, VK_IMAGE_LAYOUT_GENERAL, t->image, VK_IMAGE_LAYOUT_GENERAL, 1, &b, VK_FILTER_NEAREST); + .srcOffsets = {{0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, dst->level, dst->base_layer, 1}, + .dstOffsets = {{0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1}}}; + vkCmdBlitImage(cb, e->out, VK_IMAGE_LAYOUT_GENERAL, dst->image, VK_IMAGE_LAYOUT_GENERAL, 1, &b, VK_FILTER_NEAREST); full_barrier(cb); ex->recorded += 4; vk_exec_draw_new_cb(); // NGX bound pipelines and descriptor sets of its own: the next draw binds everything again D.jdepth = z->image; next_jitter(); if (++D.evals == 1 || D.evals % 3600 == 0) - rt_log("dlaa: %llu frames anti-aliased (scene %ux%u; %llu frames without the DLAA point, %llu with camera " + rt_log("dlaa: %llu frames anti-aliased (scene %ux%u, output %ux%u; %llu frames without the DLAA point, %llu with camera " "motion, %llu without a camera, %llu jitter holds; resets: %llu size, %llu camera, %llu target)", - (unsigned long long)D.evals, w, h, (unsigned long long)D.frames_missed, + (unsigned long long)D.evals, w, h, ow, oh, (unsigned long long)D.frames_missed, (unsigned long long)D.mv_frames, (unsigned long long)D.mv_none, (unsigned long long)D.holds, (unsigned long long)D.why[0], (unsigned long long)D.why[1], (unsigned long long)D.why[2]); } @@ -568,9 +587,20 @@ void vk_dlaa_pass(VkExec *ex) { return; } if (!D.armed) return; - if (!ex->pass_w || ex->pass_w * 4 > D.color.width) return; - D.done = 1; - evaluate(ex); + if (!D.ended) { + if (!ex->pass_w || ex->pass_w * 4 > D.color.width) return; + D.ended = 1; + unsigned o[2], s[2]; + res_sizes(o, s); + if (D.color.width >= o[0]) D.done = 1, evaluate(ex, NULL); // DLAA in place; else wait for the scaling pass + return; + } + // the game's scaling pass: one colour target wider than the scene, no depth + if (ex->pass_ncolor == 1 && c->image && !z->image && scene_color(c->format) && c->width > D.color.width && + c->samples <= 1 && !c->is3d) { + D.done = D.up = 1; + evaluate(ex, c); + } } void vk_dlaa_frame(void) { @@ -579,7 +609,8 @@ void vk_dlaa_frame(void) { rt_log("dlaa: %s", on ? "on" : "off"); D.on = on; // either way the next DLAA frame starts a new history from an unjittered frame - D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = 0, D.hold = 0; + D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = D.ended = D.up = 0; + D.hold = 0; return; } if (!dl_active()) return; @@ -587,7 +618,7 @@ void vk_dlaa_frame(void) { if (D.jit_used && !D.done) D.hold = 60, D.holds++; // jittered but not resolved: that frame shook else if (D.hold) D.hold--; if (!D.done) D.jit_ok = 0; - D.armed = D.done = D.jit_used = D.gbuf = 0; + D.armed = D.done = D.jit_used = D.gbuf = D.ended = D.up = 0; D.cam_addr = 0; } @@ -597,7 +628,12 @@ void vk_dlaa_frame(void) { // game's own switch, ModelSceneExtensionParam EnableFXAA, on and off). With fxaa = 0 the draws of that second pass's // fragment shader are skipped, so the scene reaches the HUD as it was. Shaders are known by the FNV-1a hash of their // SPIR-V, as vk_dump.c names them; a translator change gives new hashes and the switch then does nothing. -#define FXAA_FS 0xf450003ebeb3dc52ull +// With a scene smaller than the output (the game's own 5/6 render scale, or a DLSS mode) the same shader draws the +// scaled picture into the output-sized target, in a pass without the depth attachment the in-place FXAA has: there it +// is always drawn, whatever fxaa says (skipping it would leave the 3D picture out), unless DLSS already wrote that +// target this frame. +// The stock translator's hash, and the one with tools/xlate patch 0010 (PCSS, PR #89) applied. +static const uint64_t FXAA_FS[] = {0xf450003ebeb3dc52ull, 0x0a12f4bc2a9a4fbeull}; static uint64_t spirv_hash(const GfxShader *s) { static struct { const GfxShader *s; uint64_t h; } tab[8192]; @@ -615,10 +651,14 @@ static uint64_t spirv_hash(const GfxShader *s) { return 0; // table full: no skip } -int vk_dlaa_skip_draw(const GfxShader *fs) { +int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) { static uint64_t frame_read = ~0ull; static int fxaa = 1; uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED); if (f != frame_read) frame_read = f, fxaa = cfg_bool("TOTK_FXAA"); // once a frame: the menu switches it live - return !fxaa && fs && spirv_hash(fs) == FXAA_FS; + if (!fs) return 0; + uint64_t h = spirv_hash(fs); + if (h != FXAA_FS[0] && h != FXAA_FS[1]) return 0; + if (!ex->depth.image) return D.up; // the scaling pass + return !fxaa; } diff --git a/runtime/vk_dlaa.h b/runtime/vk_dlaa.h index 4eb7ff3d..dc291b10 100644 --- a/runtime/vk_dlaa.h +++ b/runtime/vk_dlaa.h @@ -18,5 +18,6 @@ void vk_dlaa_frame(void); // the viewport of the scene's draws by the frame's jitter (vk_dlaa_viewport, when the viewport is recorded). void vk_dlaa_draw(VkExec *ex); void vk_dlaa_viewport(VkExec *ex, VkViewport *v); -// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0). -int vk_dlaa_skip_draw(const GfxShader *fs); +// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0, its +// scaling draw when DLSS wrote the scaled picture). +int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs); diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index db9f2ef2..bc4aa989 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -2041,7 +2041,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { if (fs_wait) fs = shader_for(ex, NVN_STAGE_FS, &has_fs, NULL, 1); } if (!vs || (has_fs && !fs)) return 0; - if (vk_dlaa_skip_draw(fs)) return 0; // the game's FXAA, switched off (vk_dlaa.c) + if (vk_dlaa_skip_draw(ex, fs)) return 0; // the game's FXAA off, or its scaling replaced by DLSS (vk_dlaa.c) uint32_t fbl = feedback_prepare(ex, fs); VkPipeState s = ex->pipe; s.vs = vs, s.fs = fs; diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index 99db3f5c..bf5ab49c 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -1565,8 +1565,14 @@ static VkSampler make_sampler(VkCtx *c, const samp_par *d) { si.maxLod = d->lod_max > 1000 ? VK_LOD_CLAMP_NONE : d->lod_max; if (mf <= NVN_MIN_FILTER_LINEAR) si.maxLod = si.minLod + 0.25f; // not mipmapped: stay on the base level if (si.maxLod < si.minLod) si.maxLod = si.minLod; - float lim = c->props.limits.maxSamplerLodBias; - si.mipLodBias = fmaxf(-lim, fminf(lim, d->lod_bias)); + float lim = c->props.limits.maxSamplerLodBias, bias = d->lod_bias; + // DLSS upscaling (resolution.c): the scene's material textures, the filtered mipmapped ones that repeat, are + // sampled for the output's resolution; clamped ones (post effects, LUTs, the UI) keep the game's bias. + if (!d->cmp_mode && mf == NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR && + (si.addressModeU == VK_SAMPLER_ADDRESS_MODE_REPEAT || si.addressModeU == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT || + si.addressModeV == VK_SAMPLER_ADDRESS_MODE_REPEAT || si.addressModeV == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT)) + bias += res_dlss_lod_bias(); + si.mipLodBias = fmaxf(-lim, fminf(lim, bias)); if (d->aniso > 1) { si.anisotropyEnable = VK_TRUE; si.maxAnisotropy = fminf(d->aniso, c->props.limits.maxSamplerAnisotropy); diff --git a/totk.ini.example b/totk.ini.example index 6aa8801c..b9dcc044 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -127,10 +127,14 @@ # window is no longer stretched as it used to be; stretch fills the window. Changes while the game runs take effect at # once. # aspect = fit -# NVIDIA DLAA: DLSS anti-aliasing of the 3D scene at its own resolution, on NVIDIA RTX GPUs with nvngx_dlss.dll (from -# NVIDIA's DLSS SDK) next to totk.exe; elsewhere the setting does nothing. Changes while the game runs take effect at -# once. +# NVIDIA DLSS / DLAA for the 3D scene, on NVIDIA RTX GPUs with nvngx_dlss.dll (from NVIDIA's DLSS SDK) next to +# totk.exe; elsewhere the setting does nothing. The HUD is drawn after it and is not touched. Changes while the game +# runs take effect at once. # dlaa = 0 +# What DLSS works from: dlaa (the 3D scene at full size), quality, balanced or performance (the scene at 67, 58 or +# 50 % of the output, scaled up by DLSS; these replace render_scale and sharpen texture filtering to match). With dlaa +# = 0 the game's own scaling is used at that size. Read at start. +# dlss = dlaa # The game's own FXAA after the post effects; with DLAA on it is not needed. Changes while the game runs take effect at # once. # fxaa = 1 From 859ed28735cc349dd7563c9300c6ff7f4a6be9e3 Mon Sep 17 00:00:00 2001 From: tuwary <47059291+tuwary@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:33:53 +0800 Subject: [PATCH 11/19] Add Simplified Chinese to the setup window and the in-game menu The setup window gets installer/text/zh-Hans.json, a full copy of the English catalog, and a third entry in its language switch. A Windows display language of zh-CN or zh-SG picks it; zh-TW, zh-HK and zh-MO write Traditional Chinese and stay on English. A Chinese window still starts with English as the game language, because Chinese game text needs the Switch shared fonts the installer does not extract. The launcher's message box and make_release.py's launcher_text.h carry the Chinese strings too. The menu and the performance overlay get a text_zh_hans table for every menu id, and TOTK_MENU_LANG takes zh-Hans. Left unset, the menu follows the system UI language with the same Simplified Chinese regions. The font atlas merges in every glyph of the menu language's text from the system font (Microsoft YaHei, else SimSun) and is built again when the menu language changes. ov_probe checks that every menu id has Chinese text, that the printf formats keep the English conversions, and how system language tags map to menu languages; installer_gui_test checks the new catalog the same way as the Russian one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DcYzeu7eb2tXZMU4bRVcGh --- README.md | 1 + docs/architecture.md | 4 +- docs/installer.md | 11 +- installer/gui.py | 14 +- installer/guilogic.py | 23 +++- installer/launcher/launcher.c | 14 +- installer/text/zh-Hans.json | 175 +++++++++++++++++++++++++ runtime/cfg.c | 2 +- runtime/ov_probe.c | 71 ++++++++--- runtime/ui/menu.cpp | 27 ++-- runtime/ui_text.c | 232 ++++++++++++++++++++++++++++++++-- runtime/ui_text.h | 12 +- tests/installer_gui_test.py | 48 +++++-- tools/make_release.py | 10 +- totk.ini.example | 4 +- 15 files changed, 574 insertions(+), 74 deletions(-) create mode 100644 installer/text/zh-Hans.json diff --git a/README.md b/README.md index 089d3f2b..560352d9 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - 60 fps by default; up to 144 fps or the monitor's refresh rate (experimental) - Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling - In-game settings menu (F1) and performance overlay (F10) +- Setup and in-game menu in English, Russian and Simplified Chinese - Keyboard, mouse and gamepad with remapping, rumble and gyro - Xbox button prompts: a layout that keeps the Switch button positions and shows the Xbox labels - Shaders prepared at install instead of during play diff --git a/docs/architecture.md b/docs/architecture.md index 29967538..5fd80294 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,7 +54,9 @@ MacNativeGames cannot run on x86-64 as is: its CPU path executes ARM64 code nati libzstd on the host (`ov_zstd.c`, `TOTK_ZSTD_NATIVE`); the lifted decoder took almost three times as long. - Settings and menu: every key with its default is in one table (`cfg.c`), read from `totk.ini` and `TOTK_*` variables and written back when the in-game menu changes it. The menu and the performance overlay are Dear ImGui, - drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian). + drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian, Simplified Chinese). + The Chinese glyphs come from a system font (Microsoft YaHei, `plat_font_path`) merged into the font atlas for the menu + language. - OS calls the host makes go through `runtime/platform/` (`platform.h`, `win32.c`), so a Linux or macOS host adds one file instead of touching the rest. The split is not finished: `tools/check_platform.py` lists the Win32 uses left in the other files. #### Threads and cores diff --git a/docs/installer.md b/docs/installer.md index e6ad004c..cf123dd6 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -79,9 +79,12 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR the merged RomFS (15.9 GiB) before it deletes them. The check computes the exact figure. - Window (`python -m installer.gui`, `installer/gui.py` draws, `installer/guilogic.py` decides): form, step list with progress, space line, collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit), - finish screen with Open folder. English or Russian, chosen from the Windows display language, switchable in the - window; every sentence is an id in `installer/text/.json`. A folder with `totk-install.json` needs only the - folder. `--selftest [--shots DIR]` builds every screen in both languages and closes itself. + finish screen with Open folder. English, Russian or Simplified Chinese, chosen from the Windows display language + (zh-CN and zh-SG give Chinese; the Traditional Chinese regions give English), switchable in the window; every + sentence is an id in `installer/text/.json`. A Chinese window still starts with English as the game + language, because Chinese game text needs the Switch shared fonts the installer does not extract. A folder with + `totk-install.json` needs only the folder. `--selftest [--shots DIR]` builds every screen in every language and + closes itself. - `tests/installer_gui_test.py`: event model, form, catalogs, cancel, the self-closing window and one end-to-end run of the CLI in `--verify` mode (needs `build/install-test` and `build/extracted/v121`; see its docstring). - `tests/installer_test.py`: bookkeeping with fake steps. `tests/installer_e2e.py`: a dev-mode run with the files of @@ -93,7 +96,7 @@ The unpacked release; `tools/make_release.py` assembles it and `--zip` packs it: ``` TotK-Setup.exe starts python/pythonw.exe -m installer.gui (installer/launcher/launcher.c, no console) -installer/ the installer: steps, CLI, window, en/ru text catalog +installer/ the installer: steps, CLI, window, en/ru/zh-Hans text catalog python/ Python 3.14.9 embeddable + numpy, lz4, cryptography, cffi, pycparser (+ tkinter for the window) recomp/, tools/ the lifter and the build, extraction and shader scripts the steps run (copied from the repo) llvm/ llvm-mingw, x86_64-only subset (Apache-2.0 with LLVM exception; mingw-w64 parts permissive) diff --git a/installer/gui.py b/installer/gui.py index bbda6a2d..c93215db 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -2,10 +2,10 @@ A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the game language and the install folder, runs `python -m installer ...` as a subprocess and shows its JSON events. Decisions live in guilogic.py; -this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. +this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. - --selftest [--shots DIR] build every screen in both languages and close by itself (PNG per screen with --shots) - --lang en|ru window language (default: the Windows display language) + --selftest [--shots DIR] build every screen in every language and close by itself (PNG per screen with --shots) + --lang en|ru|zh-Hans window language (default: the Windows display language) """ import argparse import json @@ -22,8 +22,8 @@ except ImportError: from . import ini from . import layout as layouts -from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGES, Catalog, Form, Model, Process, - amount, default_game_language, describe_event, parse_line, windows_ui_language) +from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, UI_LANGUAGES, Catalog, Form, Model, + Process, amount, default_game_language, describe_event, parse_line, windows_ui_language) POLL_MS = 100 GLYPH = {PENDING: '\u25cb', RUNNING: '\u25b6', DONE: '\u2714', SKIPPED: '\u2013', FAILED: '\u2716'} @@ -78,7 +78,7 @@ class App: sw.pack(side='right') self.ui_var = tk.StringVar(value=self.cat.lang) for code in UI_LANGUAGES: - ttk.Radiobutton(sw, text=code.upper(), value=code, variable=self.ui_var, style='Toolbutton', + ttk.Radiobutton(sw, text=UI_LANGUAGE_LABELS[code], value=code, variable=self.ui_var, style='Toolbutton', command=self.switch_language).pack(side='left', padx=1) self.body = ttk.Frame(root, padding=PAD) self.body.pack(fill='both', expand=True) @@ -523,7 +523,7 @@ def grab(root, path): def selftest(layout, shots=None): - """Every screen in both languages; the window closes itself. Returns 0 when nothing raised.""" + """Every screen in every language; the window closes itself. Returns 0 when nothing raised.""" fix_tcl_paths() root = tk.Tk() root.geometry('+60+40') diff --git a/installer/guilogic.py b/installer/guilogic.py index 7d517024..6f9157ab 100644 --- a/installer/guilogic.py +++ b/installer/guilogic.py @@ -23,11 +23,16 @@ from . import state as statefile from .events import render TEXT = Path(__file__).resolve().parent / 'text' -UI_LANGUAGES = ('en', 'ru') +UI_LANGUAGES = ('en', 'ru', 'zh-Hans') +# what the language switch in the window's corner shows for each +UI_LANGUAGE_LABELS = {'en': 'EN', 'ru': 'RU', 'zh-Hans': '中文'} STEP_ORDER = ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup') # message parameter -> catalog id prefix of the names that replace its raw values PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'} LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID +# Windows LANGIDs that write Simplified Chinese: zh-CN, zh-SG. zh-TW, zh-HK and zh-MO write Traditional Chinese, which +# the window does not have. +LANGIDS_ZH_HANS = (0x0804, 0x1004) def load_texts(lang): @@ -75,15 +80,27 @@ def flat(value): def windows_ui_language(): - """'ru' when the Windows display language is Russian, else 'en'.""" + """The window language for the Windows display language (ui_language_for_langid).""" try: langid = ctypes.windll.kernel32.GetUserDefaultUILanguage() except (AttributeError, OSError): return 'en' - return 'ru' if langid & 0x3ff == LANG_RU else 'en' + return ui_language_for_langid(langid) + + +def ui_language_for_langid(langid): + """'ru' for a Russian Windows LANGID, 'zh-Hans' for a Simplified Chinese one, else 'en'.""" + if langid & 0x3ff == LANG_RU: + return 'ru' + if langid in LANGIDS_ZH_HANS: + return 'zh-Hans' + return 'en' def default_game_language(ui): + """The game language the form starts with. A Chinese window still starts with English: Chinese game text needs + the Switch shared fonts (ini.NEED_SHARED_FONTS), which the installer does not extract, and the game stops when + they are missing; the player can still pick Chinese.""" return 'ru' if ui == 'ru' else 'en-US' diff --git a/installer/launcher/launcher.c b/installer/launcher/launcher.c index 11994cd9..9571b70f 100644 --- a/installer/launcher/launcher.c +++ b/installer/launcher/launcher.c @@ -12,11 +12,19 @@ #define LANGID_RUSSIAN 0x19 #define PATH_CHARS (MAX_PATH * 2) +/* The language of the window (installer/guilogic.py ui_language_for_langid): Russian, Simplified Chinese (zh-CN and + zh-SG; the Traditional Chinese regions get English, as the window has no Traditional Chinese), else English. */ static void fail(void) { - int russian = (GetUserDefaultUILanguage() & 0x3ff) == LANGID_RUSSIAN; - MessageBoxW(NULL, russian ? LAUNCHER_PYTHON_MISSING_RU : LAUNCHER_PYTHON_MISSING_EN, - russian ? LAUNCHER_TITLE_RU : LAUNCHER_TITLE_EN, MB_OK | MB_ICONERROR); + LANGID ui = GetUserDefaultUILanguage(); + int russian = (ui & 0x3ff) == LANGID_RUSSIAN; + int chinese = ui == MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) || + ui == MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SINGAPORE); + MessageBoxW(NULL, + russian ? LAUNCHER_PYTHON_MISSING_RU : chinese ? LAUNCHER_PYTHON_MISSING_ZH_HANS + : LAUNCHER_PYTHON_MISSING_EN, + russian ? LAUNCHER_TITLE_RU : chinese ? LAUNCHER_TITLE_ZH_HANS : LAUNCHER_TITLE_EN, + MB_OK | MB_ICONERROR); } int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show) diff --git a/installer/text/zh-Hans.json b/installer/text/zh-Hans.json new file mode 100644 index 00000000..54facdea --- /dev/null +++ b/installer/text/zh-Hans.json @@ -0,0 +1,175 @@ +{ + "step.check": "检查电脑和游戏文件", + "step.extract": "解包游戏", + "step.lift": "将游戏代码转换为 C 代码", + "step.compile": "编译 totk.exe", + "step.prepare": "准备着色器", + "step.cleanup": "清理", + + "phase.check.host": "检查处理器和显卡", + "phase.check.verify": "检查已安装的文件", + "phase.check.verify_romfs": "检查已安装的游戏数据", + "phase.check.inputs": "用密钥打开游戏文件", + "phase.check.versions": "检查游戏版本", + "phase.extract.hash_base": "计算游戏本体的校验和", + "phase.extract.hash_update": "计算更新的校验和", + "phase.extract.exefs": "解包游戏代码", + "phase.extract.copy": "复制游戏数据", + "phase.extract.merge": "将更新应用到游戏数据", + "phase.extract.diagnose": "查找损坏的游戏文件", + "phase.extract.index": "校验游戏数据", + "phase.lift.discover": "查找函数", + "phase.lift.emit": "生成 C 代码", + "phase.compile.compile": "编译", + "phase.compile.link": "链接 totk.exe", + "phase.prepare.romfs_patches": "写入 60 帧游戏数据补丁", + "phase.prepare.seed": "从游戏数据中读取着色器", + "phase.prepare.translate": "转译着色器", + "phase.prepare.libraries": "为显卡驱动构建着色器", + "phase.prepare.pack": "将着色器缓存打包成一个文件", + "phase.cleanup.ini": "写入 totk.ini", + "phase.cleanup.temp": "删除临时文件", + + "cli.usage": "命令行无效:{detail}", + "internal": "意外错误({exception}):{detail}", + "state.unreadable": "无法读取 {path}。请选择其他文件夹,或删除该文件。", + "state.newer_format": "{path} 是由更新版本的安装程序写入的。请使用那个安装程序,或选择其他文件夹。", + "state.output_changed": "步骤“{step}”生成的已安装文件在生成后被改动过;该步骤将重新运行。", + + "check.release_incomplete": "安装程序文件夹不完整,缺少:{paths}。请重新解压发布包。", + "check.dest_not_folder": "安装位置 {path} 是一个文件,而不是文件夹。", + "check.dest_not_empty": "安装文件夹 {path} 不是空的,其中也没有之前的安装。请选择一个空文件夹。", + "check.lang_missing": "请选择游戏语言。", + "check.lang_unknown": "未知语言“{lang}”。可用语言:{known}。", + "check.toolchain_broken": "自带的编译器无法工作:{detail}", + "check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。", + "check.cpu_no_avx2": "此处理器不支持游戏所需的 AVX2(x86-64-v3)。Intel Haswell(2013 年)或 AMD Excavator / Zen 及更新的处理器才支持。", + "check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。", + "check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。", + "check.vulkan_too_old": "游戏需要支持 Vulkan 1.3 的显卡;检测到:{devices}。请更新显卡驱动程序。", + "check.inputs_needed": "需要游戏文件:请选择游戏本体、1.2.1 或 1.4.3 更新以及 prod.keys。", + "check.input_missing": "找不到文件({input}):{path}", + "check.keys_unreadable": "无法读取密钥文件。请选择一个 prod.keys 文件。", + "check.keys_no_header_key": "密钥文件中没有 header_key。请从你的主机重新导出 prod.keys。", + "check.keys_wrong": "这些密钥无法打开{input}文件。请使用你自己主机的 prod.keys。", + "check.keys_too_old": "密钥文件对{input}文件来说太旧(需要密钥代数 {generation})。请从固件更新的主机导出 prod.keys。", + "check.not_game_file": "{input}文件不是 XCI 或 NSP 游戏文件。", + "check.file_unreadable": "无法读取{input}文件:{detail}", + "check.ticket_personalized": "{input}文件带有个人化票据(personalized ticket);需要通用票据(common ticket)。", + "check.ticket_missing": "{input}文件缺少其内容所需的票据(ticket)。", + "check.base_not_totk": "游戏本体文件不是《塞尔达传说 王国之泪》({detail})。", + "check.update_not_nsp": "更新必须是 NSP 文件。", + "check.update_is_base": "更新文件里是游戏本体。请选择 1.2.1 或 1.4.3 的更新 NSP。", + "check.update_not_totk": "更新文件不是《王国之泪》的更新({detail})。", + "check.exefs_failed": "{input}文件的游戏代码未通过检查;详见 {log}。", + "check.input_damaged": "{input}文件已损坏或不完整:{path}({detail})。请从来源重新复制该文件或重新导出,然后再次运行安装程序。", + "check.base_wrong_version": "游戏本体不是 1.0.0 版本({modules} 不一致)。", + "check.update_wrong_version": "更新的版本是 {found};此发布版需要 {wanted}。", + "check.disk_space": "{path} 的可用空间不足:需要 {need_gb} GB,可用 {free_gb} GB。", + + "extract.exefs_mismatch": "解包出的游戏代码与 {version} 版本不符({modules})。", + "extract.romfs_merge_failed": "将更新应用到游戏数据失败:{detail}。详情:{log}", + "extract.romfs_mismatch": "解包出的游戏数据与 {version} 版本不符(大小 {size},校验和 {sha256}...)。", + "lift.failed": "游戏代码转换失败(退出代码 {code})。详情:{log}", + "compile.failed": "编译 totk.exe 失败(退出代码 {code})。详情:{log}", + "compile.exe_in_use": "{path} 正在使用中。请关闭游戏后重新运行安装程序。", + "prepare.shader_list_missing": "缺少着色器列表。", + "prepare.romfs_patches_failed": "写入游戏数据补丁失败(退出代码 {code})。详情:{log}", + "prepare.shaders_failed": "准备着色器失败(退出代码 {code})。详情:{log}", + "cleanup.romfs_unreadable": "安装完成后,{path} 中的游戏数据缺失或无法读取。请重启 Windows,然后对同一文件夹再次运行安装程序:它会重新提取游戏数据,其余内容保留。", + "prepare.pack_failed": "打包着色器缓存失败(退出代码 {code})。详情:{log}", + "cleanup.ini_failed": "无法写入 totk.ini:{detail}", + + "warn.lang_needs_fonts": "{lang}文本需要 Switch 系统字体,而安装程序不会提取这些字体;部分文字可能无法显示。", + "warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。", + "warn.xbox_prompts_failed": "无法准备 Xbox 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}", + + "ui.title": "TotK 安装程序", + "ui.version": "版本 {version}", + "ui.intro": "用你自己的游戏文件构建一个可以游玩的《王国之泪》文件夹。耗时较长,只需运行一次。", + "ui.notice": "此安装程序构建的文件夹包含游戏本身,仅供你个人使用;请勿分享或上传。", + "ui.keys_private": "密钥文件只在原位置读取,其内容绝不会被显示、复制或保存。", + "ui.base": "游戏本体(NSP 或 XCI)", + "ui.update": "1.2.1 或 1.4.3 更新(NSP)", + "ui.keys": "prod.keys", + "ui.game_language": "游戏语言", + "ui.dest": "安装文件夹", + "ui.browse": "浏览...", + "ui.pick_game": "选择游戏本体文件", + "ui.pick_update": "选择 1.2.1 或 1.4.3 更新文件", + "ui.pick_keys": "选择 prod.keys", + "ui.pick_dest": "选择安装文件夹", + "ui.type_game": "游戏文件(NSP、XCI)", + "ui.type_nsp": "NSP 文件", + "ui.type_keys": "密钥文件(*.keys)", + "ui.type_all": "所有文件", + "ui.start": "开始", + "ui.cancel": "取消", + "ui.cancelling": "正在取消...", + "ui.show_log": "显示日志", + "ui.hide_log": "隐藏日志", + "ui.close": "关闭", + "ui.back": "返回", + "ui.open_folder": "打开文件夹", + "ui.update_mode": "此文件夹中已有之前的安装。安装程序会继续或更新它;只有在需要时才会再次要求提供游戏文件。", + "ui.need_dest": "请选择安装文件夹。", + "ui.need_base": "请选择游戏本体文件。", + "ui.need_update": "请选择 1.2.1 或 1.4.3 更新文件。", + "ui.need_keys": "请选择 prod.keys 文件。", + "ui.need_lang": "请选择游戏语言。", + "ui.missing_base": "游戏本体文件不存在。", + "ui.missing_update": "更新文件不存在。", + "ui.missing_keys": "密钥文件不存在。", + "ui.running_install": "正在安装", + "ui.running_resume": "正在继续之前的安装", + "ui.running_update": "正在更新安装", + "ui.state_started": "已开始", + "ui.state_done": "完成", + "ui.state_skipped": "已跳过", + "ui.state_pending": "等待中", + "ui.state_running": "进行中", + "ui.state_failed": "失败", + "ui.log_warning": "警告", + "ui.log_error": "错误", + "ui.log_space": "所需空间:{need} GB,可用:{free} GB", + "ui.log_end": "已结束", + "ui.result_ok": "游戏已准备就绪", + "ui.result_failed": "安装失败", + "ui.result_cancelled": "安装已取消", + "ui.done_text": "从 {dest} 启动 totk.exe。安装程序和你选择的游戏文件都不再需要了。", + "ui.cancelled_text": "已完成的步骤会保留。用同一个文件夹再次运行安装程序即可继续。", + "ui.log_file": "日志文件:{path}", + "ui.process_died": "安装程序意外停止(退出代码 {code})。", + "ui.confirm_cancel": "安装正在进行。要取消安装并关闭窗口吗?", + "ui.space_one": "{path} 需要的可用空间:{need} GB(可用:{free} GB)。", + "ui.space_two": "{path} 需要的可用空间:{need} GB(可用:{free} GB);{temp} 需要:{temp_need} GB(可用:{temp_free} GB)。", + "ui.amount_bytes": "{done} / {total} GB", + "ui.amount_chunks": "{done} / {total} 部分", + "ui.amount_objects": "{done} / {total} 个文件", + "ui.amount_shaders": "{done} / {total} 个着色器", + "ui.amount_other": "{done} / {total} {unit}", + "ui.seconds": "{n} 秒", + "param.input.base": "游戏本体", + "param.input.update": "更新", + "param.input.keys": "密钥", + + "launcher.title": "TotK 安装程序", + "launcher.python_missing": "安装文件不完整:TotK-Setup.exe 旁边缺少 python 文件夹。请重新解压整个压缩包,然后从解压出的文件夹中启动 TotK-Setup.exe。", + + "lang.ja": "日语", + "lang.en-US": "英语(美国)", + "lang.en-GB": "英语(英国)", + "lang.fr": "法语", + "lang.fr-CA": "法语(加拿大)", + "lang.de": "德语", + "lang.it": "意大利语", + "lang.es": "西班牙语", + "lang.es-419": "西班牙语(拉丁美洲)", + "lang.nl": "荷兰语", + "lang.pt": "葡萄牙语", + "lang.pt-BR": "葡萄牙语(巴西)", + "lang.ru": "俄语", + "lang.ko": "韩语", + "lang.zh-Hans": "中文(简体)", + "lang.zh-Hant": "中文(繁体)" +} diff --git a/runtime/cfg.c b/runtime/cfg.c index 25a30f18..12718200 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -106,7 +106,7 @@ static const CfgMeta metas[] = { {"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}, - {"MENU_LANG", "", "en|ru", LIVE}, + {"MENU_LANG", "", "en|ru|zh-Hans", 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/ov_probe.c b/runtime/ov_probe.c index c0ffa181..6ee6b153 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -814,13 +814,47 @@ static void probe_fonts(void) { (unsigned long long)size, path); } -// The host catalog (ui_text.c): every menu id has its own English and Russian text, the software keyboard keeps its -// game-language rows, and menu_text follows TOTK_MENU_LANG. +// The printf conversions of a format, in order and without the text between them: "%s, game %.0f%%" -> "%s%.0f%%". +static void conversions(const char *fmt, char *out, size_t cap) { + size_t n = 0; + for (const char *p = fmt; *p;) { + if (*p++ != '%') continue; + const char *start = p - 1; + while (*p && strchr(".-+ #0123456789", *p)) p++; + if (*p) p++; // the conversion letter, or the second '%' of "%%" + for (; start < p; start++) + if (n + 1 < cap) out[n++] = *start; + } + out[n] = 0; +} + +// The host catalog (ui_text.c): every menu id has its own English, Russian and Simplified Chinese text, the formats +// keep the English conversions, the software keyboard keeps its game-language rows, and menu_text follows +// TOTK_MENU_LANG. static void probe_menu_text(void) { static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko"}; - for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) { - CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id), "menu text id %d lacks en or ru", id); - CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id), "menu text id %d is empty", id); + static const char *const menu_langs[] = {"en", "ru", "zh-Hans"}; + for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) + for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++) + CHECK(ui_text_defined(menu_langs[i], (UiTextId)id) && *ui_text_in(menu_langs[i], (UiTextId)id), + "menu text id %d lacks %s", id, menu_langs[i]); + // the texts the host passes to printf + static const UiTextId formats[] = { + UI_MENU_VERSION, UI_MENU_PRESENT_IN_USE, UI_PERF_LINE_FPS, UI_MENU_FPS_DISPLAY_HZ, UI_MENU_PAD_LAYOUT_IN_USE, + UI_BINDS_PRESS_KEY, UI_BINDS_PRESS_PAD, UI_BINDS_CANCEL_HINT, UI_BINDS_TAKEN, UI_BINDS_SWAPPED, UI_KEY_NUM_FMT, + UI_MENU_OV_FPS, UI_MENU_OV_FRAME_MS, UI_MENU_OV_GAME_PCT, UI_MENU_OV_MAX_MS, UI_MENU_OV_FMT_PCT, + UI_MENU_OV_FMT_TEMP, UI_MENU_OV_FMT_POWER, UI_MENU_OV_FMT_MHZ, UI_MENU_OV_FMT_GB, UI_MENU_OV_FMT_GB_OF, + UI_MENU_OV_GAME_GB, UI_MENU_OV_FMT_MS, UI_MENU_OV_PER_FRAME, UI_MENU_OV_FMT_SIZE, UI_MENU_OV_FMT_SCENE, + UI_MENU_OV_FMT_FSR, + }; + for (size_t f = 0; f < sizeof formats / sizeof *formats; f++) { + char want[64], got[64]; + conversions(ui_text_in("en", formats[f]), want, sizeof want); + for (size_t i = 1; i < sizeof menu_langs / sizeof *menu_langs; i++) { + conversions(ui_text_in(menu_langs[i], formats[f]), got, sizeof got); + CHECK(!strcmp(want, got), "format id %d in %s has conversions '%s', English '%s'", (int)formats[f], + menu_langs[i], got, want); + } } CHECK(!ui_text_defined("en", UI_TEXT_COUNT) && !*ui_text_in("ru", UI_TEXT_COUNT), "an id past the catalog gives text"); // other languages fall back to English for the menu, and keep their own keyboard texts @@ -832,18 +866,25 @@ static void probe_menu_text(void) { for (size_t i = 1; i < sizeof langs / sizeof *langs; i++) CHECK(!strcmp(ui_text_in(langs[i], (UiTextId)id), ui_text_in("en", (UiTextId)id)), "language name %d differs in %s", id, langs[i]); CHECK(!strcmp(ui_text_in("en", UI_MENU_LANGNAME_RU), "Русский"), "Russian is not shown as Russian"); - // the overlay formats keep their conversions - CHECK(strstr(ui_text_in("ru", UI_MENU_OV_GAME_PCT), "%.0f%%") && strstr(ui_text_in("ru", UI_MENU_OV_MAX_MS), "%.1f"), - "overlay format lost its conversion"); + // the system UI language picks the menu language when the setting is unset + static const struct { const char *tag, *lang; } sys_langs[] = { + {"ru", "ru"}, {"ru-RU", "ru"}, {"zh-CN", "zh-Hans"}, {"zh-SG", "zh-Hans"}, {"zh-Hans-CN", "zh-Hans"}, + {"zh-TW", "en"}, {"zh-HK", "en"}, {"zh-Hant-TW", "en"}, {"en-US", "en"}, {"rue", "en"}, {"", "en"}, + }; + for (size_t i = 0; i < sizeof sys_langs / sizeof *sys_langs; i++) + CHECK(!strcmp(menu_lang_for_system(sys_langs[i].tag), sys_langs[i].lang), "system language '%s' gives menu %s", + sys_langs[i].tag, menu_lang_for_system(sys_langs[i].tag)); // menu_text follows the setting live - cfg_set("TOTK_MENU_LANG", "ru"); - CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("ru", UI_MENU_CONTINUE), "menu_text ignores MENU_LANG=ru"); - cfg_set("TOTK_MENU_LANG", "en"); - CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en"); + for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++) { + cfg_set("TOTK_MENU_LANG", menu_langs[i]); + CHECK(!strcmp(menu_language(), menu_langs[i]) && + menu_text(UI_MENU_CONTINUE) == ui_text_in(menu_langs[i], UI_MENU_CONTINUE), + "menu_text did not follow MENU_LANG=%s", menu_langs[i]); + } cfg_set("TOTK_MENU_LANG", ""); - const char *sys = plat_ui_language(); - int ru = !strncmp(sys, "ru", 2); - CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(ru ? "ru" : "en", UI_MENU_CONTINUE), "menu_text auto ignores the system language"); + const char *auto_lang = menu_lang_for_system(plat_ui_language()); + CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(auto_lang, UI_MENU_CONTINUE), + "menu_text auto ignores the system language"); } static void probe_main(Cpu *c) { diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 865f6b17..b73a59e6 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -169,6 +169,7 @@ static int g_failed_flag() { return g_failed.load(std::memory_order_relaxed); } static int g_vk_ok; // back end initialised for g_vk_fmt static VkFormat g_vk_fmt; static float g_font_scale; // the scale of the uploaded font atlas; 0 when none is uploaded +static const char *g_font_lang; // the menu language whose glyphs the uploaded atlas holds static float g_style_scale; // the scale the style was last sized for static ImGuiStyle g_base_style; // the menu's style at 1080 lines static uint64_t g_last_ns; @@ -253,16 +254,18 @@ static int vk_up(const MenuTarget *t) { return 1; } -// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean -// and Chinese language names merged in from a system font when there is one (each language is named in its own script). -// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture). +// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines. For the Japanese, Korean and Chinese +// languages, glyphs are merged in from a system font when there is one: those of the language's own name (each language +// is named in its own script in the language lists) and, for the menu language, every glyph of the menu and overlay +// text. Made again when the window height or the menu language changes; the old texture goes after the queue is idle +// (CreateFontsTexture). static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0}; static const struct { const char *lang; UiTextId name; } kCjk[] = { {"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS}, {"zh-Hant", UI_MENU_LANGNAME_ZH_HANT}, }; -static int fonts_up(float scale) { +static int fonts_up(float scale, const char *menu_lang) { enum { N = sizeof kCjk / sizeof *kCjk }; ImFontAtlas *fa = ImGui::GetIO().Fonts; fa->Clear(); @@ -279,6 +282,8 @@ static int fonts_up(float scale) { merged++; ImFontGlyphRangesBuilder b; b.AddText(ui_text_in("en", kCjk[i].name)); + if (!strcmp(kCjk[i].lang, menu_lang)) + for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) b.AddText(ui_text_in(menu_lang, (UiTextId)id)); b.BuildRanges(&ranges[i]); ImFontConfig mc; mc.MergeMode = true; @@ -291,8 +296,10 @@ static int fonts_up(float scale) { fa->ClearInputData(); // the glyphs are in the texture: the font files and the pixels are not needed again fa->ClearTexData(); for (uint8_t *d : data) free(d); - rt_log("menu: font atlas at %.1f px, language names from %d of %d system fonts", 26.0f * scale, merged, (int)N); + rt_log("menu: font atlas at %.1f px for menu language %s, CJK glyphs from %d of %d system fonts", 26.0f * scale, + menu_lang, merged, (int)N); g_font_scale = ok ? scale : 0; + g_font_lang = menu_lang; return ok; } @@ -596,8 +603,10 @@ static void tab_controls(float scale) { static void tab_menu(float scale) { opt_begin("##menu", scale); - static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU}; - opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, 3, UI_MENU_MENU_LANG_DESC); + // one name per TOTK_MENU_LANG value (cfg.c), after the automatic choice + static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU, + UI_MENU_LANGNAME_ZH_HANS}; + opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, (int)(sizeof langs / sizeof *langs), UI_MENU_MENU_LANG_DESC); opt_end(); } @@ -1112,7 +1121,9 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha uint64_t t0 = plat_now_ns(); if (!g_ctx_ok) make_context(); float scale = menu_scale(t->height); - if (!vk_up(t) || (g_font_scale != scale && !fonts_up(scale))) { + const char *lang = menu_language(); + // vk_up first: a new back end drops the atlas (g_font_scale 0) + if (!vk_up(t) || ((g_font_scale != scale || !g_font_lang || strcmp(g_font_lang, lang)) && !fonts_up(scale, lang))) { rt_log("menu: Dear ImGui Vulkan back end set-up failed; the menu stays closed"); g_failed.store(1); set_open(0); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 65a1926e..272483b9 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -1,6 +1,6 @@ // Catalog of the text the host shows the player (ui_text.h). One array per catalog language, indexed by UiTextId: a new // string gets an id in ui_text.h and an entry in every language that has one (a missing entry falls back to English). -// The software keyboard has every language; the menu has English and Russian. +// The software keyboard has every language; the menu has English, Russian and Simplified Chinese. #include #include @@ -496,6 +496,198 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_OV_SCALE_BILINEAR] = "билинейное", }; +static const char *const text_zh_hans[UI_TEXT_COUNT] = { + SWKBD("文字输入", "请输入名字", "马儿", "确定", "取消", "手柄:A 确定,B 取消"), + + [UI_MENU_TITLE] = "设置", [UI_MENU_TAB_SCREEN] = "显示", [UI_MENU_TAB_GAME] = "游戏", [UI_MENU_TAB_SOUND] = "声音", + [UI_MENU_TAB_CONTROLS] = "操作", [UI_MENU_TAB_MENU] = "菜单", [UI_MENU_TAB_ADVANCED] = "高级", + [UI_MENU_CONTINUE] = "继续", [UI_MENU_QUIT] = "退出游戏", [UI_MENU_ON] = "开", [UI_MENU_OFF] = "关", + [UI_MENU_AUTO] = "自动", [UI_MENU_DEFAULT_MARK] = "默认", [UI_MENU_AFTER_RESTART] = "重启后生效", + [UI_MENU_SET_BY_ENV] = "由环境变量设定", [UI_MENU_SAVE_FAILED] = "无法保存设置", + [UI_MENU_VERSION] = "TotK Recomp %s,游戏 %s", + + [UI_MENU_FULLSCREEN] = "全屏", [UI_MENU_FULLSCREEN_DESC] = "让游戏画面铺满屏幕;按 F11 切换。", + [UI_MENU_WINDOW_SIZE] = "窗口大小", [UI_MENU_WINDOW_SIZE_DESC] = "非全屏时游戏窗口的大小。", + [UI_MENU_WINDOW_SIZE_CUSTOM] = "自定义", [UI_MENU_PRESENT] = "呈现方式", + [UI_MENU_PRESENT_DESC] = "渲染完成的帧如何显示到屏幕上。", [UI_MENU_PRESENT_MAILBOX] = "Mailbox", + [UI_MENU_PRESENT_VSYNC] = "垂直同步", [UI_MENU_PRESENT_IMMEDIATE] = "立即", + [UI_MENU_PRESENT_IN_USE] = "实际使用:%s", [UI_MENU_GPU] = "显卡", + [UI_MENU_GPU_DESC] = "用于渲染游戏的 Vulkan 设备。", [UI_MENU_GPU_AUTO] = "自动", + [UI_MENU_PERF_OVERLAY] = "性能叠加层", + [UI_MENU_PERF_OVERLAY_DESC] = "在右上角显示帧率。“完整”模式还会显示帧时间曲线、CPU、GPU 和内存占用、温度," + "以及渲染线程的等待时间。按 F10 循环切换模式。", + [UI_MENU_PERF_OFF] = "关", [UI_MENU_PERF_FPS] = "帧率", [UI_MENU_PERF_FULL] = "完整", + [UI_PERF_LINE_FPS] = "%.0f FPS", [UI_MENU_GRAPHICS] = "画面", [UI_MENU_OUTPUT_RES] = "游戏分辨率", + [UI_MENU_OUTPUT_RES_DESC] = "游戏绘制画面和界面所用的尺寸。高于 1920 x 1080 时,游戏需要更多显存和 GPU 时间。" + "更宽的尺寸(21:9)会拓宽镜头视野,并把 HUD 移到屏幕四角。", + [UI_MENU_RENDER_SCALE] = "3D 渲染比例", + [UI_MENU_RENDER_SCALE_DESC] = "3D 场景相对于游戏分辨率的大小;游戏自带的 FSR 会把它缩放到游戏分辨率。高于 100 % " + "时可平滑锯齿边缘(超级采样),但 GPU 开销很大。", + [UI_MENU_RENDER_SCALE_GAME] = "游戏默认(83 %)", [UI_MENU_UPSCALER] = "缩放到窗口", + [UI_MENU_UPSCALER_DESC] = "窗口大于游戏分辨率时画面的缩放方式。FSR 比双线性保留更锐利的边缘和细节。", + [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "双线性", [UI_MENU_ASPECT] = "画面比例", + [UI_MENU_ASPECT_DESC] = "窗口的比例与游戏分辨率不同时(例如 21:9 屏幕上的 16:9 画面):保持画面比例并加黑边," + "或拉伸铺满窗口。", + [UI_MENU_ASPECT_FIT] = "黑边", [UI_MENU_ASPECT_STRETCH] = "拉伸", [UI_MENU_SHARPNESS] = "FSR 锐度", + [UI_MENU_SHARPNESS_DESC] = "FSR 缩放后的锐化强度;0 为关闭。", + + [UI_MENU_FPS_LIMIT] = "帧率上限", + [UI_MENU_FPS_LIMIT_DESC] = "游戏每秒最多绘制的帧数。高于 60 为实验性功能,且需要开启“游戏速度跟随时钟”。", + [UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", + [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS", [UI_MENU_FPS_DISPLAY] = "显示器刷新率", + [UI_MENU_FPS_DISPLAY_HZ] = "显示器刷新率(%.0f Hz)", [UI_MENU_REALTIME] = "游戏速度跟随时钟", + [UI_MENU_REALTIME_DESC] = "按真实时间推进游戏,帧变慢时游戏不会随之变慢。", + [UI_MENU_CLOTH_REALTIME] = "布料跟随时钟", [UI_MENU_CLOTH_REALTIME_DESC] = "布料和头发也按真实时间推进。", + [UI_MENU_HIGHFPS_FIX] = "高帧率修正", + [UI_MENU_HIGHFPS_FIX_DESC] = "修正帧率高于 30 时出现异常的物理效果,以及帧率高于 60 时一直半透明或不可见的物体。", + [UI_MENU_GAME_LANG] = "游戏语言", [UI_MENU_GAME_LANG_DESC] = "游戏文本和语音的语言。", + [UI_MENU_GAME_LANG_AUTO] = "自动", [UI_MENU_OPERATION_MODE] = "运行模式", + [UI_MENU_OPERATION_MODE_DESC] = "让游戏认为自己处于 TV 模式(插在底座上)还是掌机模式。", + [UI_MENU_MODE_DOCKED] = "TV 模式", [UI_MENU_MODE_HANDHELD] = "掌机模式", + + [UI_MENU_VOLUME] = "音量", [UI_MENU_VOLUME_DESC] = "游戏的主音量。", + + [UI_MENU_MOTION] = "体感操作", [UI_MENU_MOTION_DESC] = "使用手柄的陀螺仪瞄准。", + [UI_MENU_RUMBLE_STRENGTH] = "振动强度", [UI_MENU_RUMBLE_STRENGTH_DESC] = "手柄振动的强弱。", + [UI_MENU_RUMBLE_CURVE] = "振动曲线", [UI_MENU_RUMBLE_CURVE_DESC] = "数值越低,弱振动越明显。", + [UI_MENU_RUMBLE_TRIGGERS] = "扳机振动(Xbox)", [UI_MENU_RUMBLE_TRIGGERS_DESC] = "同时让 Xbox 手柄的扳机键振动。", + [UI_MENU_PAD_LAYOUT] = "按键布局", + [UI_MENU_PAD_LAYOUT_DESC] = "哪个按键作为 A。Nintendo:右侧按键,与 Switch 相同。Xbox:下方按键,即 Xbox " + "手柄上标着 A 的键(PlayStation 手柄上为叉键)。自动:带 Nintendo 标注的手柄用 " + "Nintendo,其他手柄用 Xbox。Xbox 按键提示:A 与 Nintendo 布局一样在右侧,游戏显示 " + "Xbox 的按键标注(A 显示为 B,B 显示为 A,X 显示为 Y,Y 显示为 X);" + "按键提示重启后更改。这些字母属于游戏文件,所以在“操作”中重新映射过的按键," + "屏幕上仍显示原来的字母。", + [UI_MENU_PAD_LAYOUT_AUTO] = "自动", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo(A 在右)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox(A 在下)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Xbox 按键提示(A 在右)", + [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_MOUSE_SENS] = "鼠标视角灵敏度", [UI_MENU_MOUSE_SENS_DESC] = "鼠标转动视角的速度。", + + [UI_BINDS_HELP] = "选中一个格子并按 A 或 Enter,然后按下键盘按键、鼠标按键或手柄按键。按 Delete 或 X 清空格子。" + "已被占用的键盘按键会移到这里;手柄按键则与被替换的按键互换。", + [UI_BINDS_COL_KEY1] = "按键 1", [UI_BINDS_COL_KEY2] = "按键 2", [UI_BINDS_COL_PAD] = "手柄", + [UI_BINDS_GROUP_BUTTONS] = "按钮", [UI_BINDS_GROUP_MOVE] = "移动", [UI_BINDS_GROUP_CAMERA] = "视角", + [UI_BINDS_PRESS_KEY] = "请为“%s”按下键盘按键或鼠标按键", [UI_BINDS_PRESS_PAD] = "请为“%s”按下手柄按键", + [UI_BINDS_CANCEL_HINT] = "按 Esc 取消,或等待 %d 秒", [UI_BINDS_TAKEN] = "%s 已从“%s”上移走", + [UI_BINDS_SWAPPED] = "“%s”与“%s”已互换", [UI_BINDS_RESET] = "重置所有按键", + [UI_BINDS_RESET_DESC] = "恢复默认的键盘按键和手柄按键。上方的按键布局将重新生效:在执行此重置之前," + "重新映射过的手柄按键会一直保持在你设定的位置。", + [UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y", [UI_BIND_LCLICK] = "按下左摇杆", + [UI_BIND_RCLICK] = "按下右摇杆", [UI_BIND_L] = "L", [UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", + [UI_BIND_PLUS] = "+ 键", [UI_BIND_MINUS] = "- 键", [UI_BIND_LEFT] = "十字键左", [UI_BIND_UP] = "十字键上", + [UI_BIND_RIGHT] = "十字键右", [UI_BIND_DOWN] = "十字键下", [UI_BIND_LSTICK_LEFT] = "向左移动", + [UI_BIND_LSTICK_UP] = "向前移动", [UI_BIND_LSTICK_RIGHT] = "向右移动", [UI_BIND_LSTICK_DOWN] = "向后移动", + [UI_BIND_RSTICK_LEFT] = "视角向左", [UI_BIND_RSTICK_UP] = "视角向上", [UI_BIND_RSTICK_RIGHT] = "视角向右", + [UI_BIND_RSTICK_DOWN] = "视角向下", [UI_BIND_DESC_A] = "调查、拾取、对话。", + [UI_BIND_DESC_B] = "奔跑、取消、返回。", [UI_BIND_DESC_X] = "跳跃。", [UI_BIND_DESC_Y] = "攻击。", + [UI_BIND_DESC_LCLICK] = "蹲下。", [UI_BIND_DESC_RCLICK] = "第一人称视角。", [UI_BIND_DESC_L] = "能力。", + [UI_BIND_DESC_R] = "投掷武器。", [UI_BIND_DESC_ZL] = "举盾、锁定。", [UI_BIND_DESC_ZR] = "弓。", + [UI_BIND_DESC_PLUS] = "菜单、道具。", [UI_BIND_DESC_MINUS] = "地图。", [UI_BIND_DESC_DPAD] = "快捷选择。", + [UI_BIND_DESC_MOVE] = "像左摇杆一样移动林克。手柄的左摇杆也始终可用。", + [UI_BIND_DESC_CAMERA] = "像右摇杆一样转动视角。鼠标和手柄的右摇杆也始终可用。", [UI_KEY_SPACE] = "空格", + [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "左 Shift", [UI_KEY_LCTRL] = "左 Ctrl", [UI_KEY_UP] = "上方向键", + [UI_KEY_DOWN] = "下方向键", [UI_KEY_LEFT] = "左方向键", [UI_KEY_RIGHT] = "右方向键", [UI_KEY_MOUSE_L] = "鼠标左键", + [UI_KEY_MOUSE_R] = "鼠标右键", [UI_KEY_MOUSE_M] = "鼠标中键", [UI_KEY_MOUSE_X1] = "鼠标侧键 4", + [UI_KEY_MOUSE_X2] = "鼠标侧键 5", [UI_KEY_ENTER] = "Enter", [UI_KEY_BACKSPACE] = "Backspace", + [UI_KEY_RSHIFT] = "右 Shift", [UI_KEY_RCTRL] = "右 Ctrl", [UI_KEY_LALT] = "Alt", [UI_KEY_CAPSLOCK] = "Caps Lock", + [UI_KEY_INSERT] = "Insert", [UI_KEY_DELETE] = "Delete", [UI_KEY_HOME] = "Home", [UI_KEY_END] = "End", + [UI_KEY_PAGEUP] = "Page Up", [UI_KEY_PAGEDOWN] = "Page Down", [UI_KEY_NUM_FMT] = "小键盘 %s", + [UI_PAD_SOUTH] = "下方按键", [UI_PAD_EAST] = "右侧按键", [UI_PAD_WEST] = "左侧按键", [UI_PAD_NORTH] = "上方按键", + [UI_PAD_LSTICK] = "左摇杆", [UI_PAD_RSTICK] = "右摇杆", [UI_PAD_L] = "左肩键", [UI_PAD_R] = "右肩键", + [UI_PAD_START] = "Start 键", [UI_PAD_BACK] = "Back 键", [UI_PAD_DPAD_LEFT] = "十字键左", + [UI_PAD_DPAD_UP] = "十字键上", [UI_PAD_DPAD_RIGHT] = "十字键右", [UI_PAD_DPAD_DOWN] = "十字键下", + [UI_PAD_ZL] = "左扳机", [UI_PAD_ZR] = "右扳机", [UI_PAD_LPADDLE1] = "左背键", [UI_PAD_RPADDLE1] = "右背键", + [UI_PAD_LPADDLE2] = "左背键 2", [UI_PAD_RPADDLE2] = "右背键 2", [UI_PAD_CROSS] = "叉键", [UI_PAD_CIRCLE] = "圆圈键", + [UI_PAD_SQUARE] = "方块键", [UI_PAD_TRIANGLE] = "三角键", + + [UI_MENU_MENU_LANG] = "菜单语言", [UI_MENU_MENU_LANG_DESC] = "本菜单和性能叠加层的语言。", + [UI_MENU_MENU_LANG_AUTO] = "自动(跟随 Windows)", + + [UI_MENU_ADV_WARNING] = "这些设置用于测试和排查问题。除非清楚修改的原因,否则请勿改动。", + [UI_MENU_GROUP_SCHED] = "调度", [UI_MENU_GROUP_SHADERS] = "着色器与管线", [UI_MENU_GROUP_TEXMEM] = "纹理与内存", + [UI_MENU_GROUP_FIXES] = "渲染修正", [UI_MENU_GROUP_VULKAN] = "Vulkan", [UI_MENU_GROUP_DIAG] = "诊断", + [UI_MENU_ASYNC_PREEMPT] = "虚拟核心抢占", + [UI_MENU_ASYNC_PREEMPT_DESC] = "允许一个游戏线程打断同一虚拟核心上的另一个线程。", [UI_MENU_PREEMPT_OFF] = "关", + [UI_MENU_PREEMPT_ON] = "开", [UI_MENU_PREEMPT_INHERIT] = "仅继承", + [UI_MENU_REPLAY_ASYNC] = "在独立线程上准备 GPU 帧", + [UI_MENU_REPLAY_ASYNC_DESC] = "在独立线程而不是游戏线程上为 GPU 准备帧。最多增加一帧延迟。", + [UI_MENU_FREE_CORES] = "虚拟核心闸门", [UI_MENU_FREE_CORES_DESC] = "每个虚拟核心只允许运行一个线程,与主机上相同。", + [UI_MENU_TIMER_1MS] = "1 ms Windows 计时器", + [UI_MENU_TIMER_1MS_DESC] = "将系统计时器精度提高到 1 ms,使帧间隔更平稳。", + [UI_MENU_PIPE_WAIT] = "等待中绘制的处理", + [UI_MENU_PIPE_WAIT_DESC] = "“默认”保持当前的调度方式,并为等待中的绘制保留一个工作线程;“旧版(draw)”" + "使用之前的调度方式。", + [UI_MENU_PIPE_WAIT_DEFAULT] = "默认", [UI_MENU_PIPE_WAIT_DRAW] = "旧版(draw)", + [UI_MENU_PIPE_SKIP] = "管线构建期间跳过的绘制", + [UI_MENU_PIPE_SKIP_DESC] = "哪些绘制会被直接丢弃,而不是等待其管线构建完成。", [UI_MENU_PIPE_SKIP_STRICT] = "严格", + [UI_MENU_PIPE_SKIP_ANY] = "任意", [UI_MENU_PIPE_SKIP_FULLSCREEN] = "全屏通道", + [UI_MENU_LIB_PREBUILD] = "阶段库预构建", [UI_MENU_LIB_PREBUILD_DESC] = "在后台提前构建着色器阶段库。", + [UI_MENU_LIB_PREBUILD_THREADS] = "阶段库预构建线程数", + [UI_MENU_LIB_PREBUILD_THREADS_DESC] = "预构建使用的线程数;“自动”会根据你的 CPU 选择。", + [UI_MENU_PIPE_PREBUILD] = "管线预构建", [UI_MENU_PIPE_PREBUILD_DESC] = "提前构建已知的管线。", + [UI_MENU_PREWARM_XLATE] = "着色器转译预热", + [UI_MENU_PREWARM_XLATE_DESC] = "启动时转译已知着色器的线程数;“自动”使用 CPU 线程数的一半,最多 16 个。", + [UI_MENU_GPL] = "图形管线库", + [UI_MENU_GPL_DESC] = "使用 Vulkan 管线库扩展;如果你的驱动程序在此模式下出现异常,请关闭。", + [UI_MENU_ASTC] = "ASTC 纹理解码", [UI_MENU_ASTC_DESC] = "压缩的 ASTC 纹理在何处解码。", + [UI_MENU_ASTC_AUTO] = "自动", [UI_MENU_ASTC_GPU] = "GPU 着色器", [UI_MENU_ASTC_NATIVE] = "原生", + [UI_MENU_ASTC_CPU] = "CPU", [UI_MENU_MEMORY] = "GPU 内存模式", + [UI_MENU_MEMORY_DESC] = "游戏内存与 GPU 的共享方式。", [UI_MENU_MEMORY_AUTO] = "自动", + [UI_MENU_MEMORY_IMPORT] = "导入", [UI_MENU_MEMORY_MIRROR] = "镜像", [UI_MENU_MEMORY_VERIFY] = "校验", + [UI_MENU_TEX_ALIAS] = "纹理别名", + [UI_MENU_TEX_ALIAS_DESC] = "在仍在使用的纹理内存上新建纹理时,新纹理沿用原有内容,而不是从空白开始。", + [UI_MENU_TEX_VRAM_PRESSURE] = "纹理显存上限", + [UI_MENU_TEX_VRAM_PRESSURE_DESC] = "显存占用超过这个百分比时,丢弃游戏已释放的纹理(再次用到时会从存储重新载入)。" + "0 表示一律保留。", + [UI_MENU_ASTC_BC] = "ASTC 压缩为 BC3", + [UI_MENU_ASTC_BC_DESC] = "配合 GPU 解码器使用:把解码后的 ASTC 纹理重新编码为 BC3,显存占用只有四分之一。适合显存 " + "4 GB 及以下的显卡;纹理会略显块状。", + [UI_MENU_LOD_GUARD] = "LOD 保护", + [UI_MENU_LOD_GUARD_DESC] = "等游戏改写完细节层次(LOD)数据后再让 GPU 读取,防止物体在错误位置闪现," + "或远景在某一帧变平。", + [UI_MENU_FIX_C0] = "常量缓冲区修正", + [UI_MENU_FIX_C0_DESC] = "填充驱动保留的常量库 c0(存储大小、调度大小、点大小、基础实例),而不是读到零。", + [UI_MENU_FIX_ZERO] = "新 GPU 内存清零", + [UI_MENU_FIX_ZERO_DESC] = "新的 GPU 内存池初始内容为零,与 Switch 内存一致。", [UI_MENU_BIND_SKIP] = "跳过重复绑定", + [UI_MENU_BIND_SKIP_DESC] = "优化:跳过没有变化的绑定。", [UI_MENU_SHADER_MEMO] = "着色器查找缓存", + [UI_MENU_SHADER_MEMO_DESC] = "优化:记住着色器的查找结果。", [UI_MENU_PIPE_MEMO] = "管线缓存", + [UI_MENU_PIPE_MEMO_DESC] = "优化:状态重复时复用上一次绘制的管线。", [UI_MENU_TEX_MEMO] = "纹理绑定缓存", + [UI_MENU_TEX_MEMO_DESC] = "优化:在多次绘制之间记住纹理描述符。", [UI_MENU_DESC_TEMPLATE] = "描述符模板", + [UI_MENU_DESC_TEMPLATE_DESC] = "优化:批量更新描述符。", [UI_MENU_PUSH_SKIP] = "跳过重复的推送常量", + [UI_MENU_PUSH_SKIP_DESC] = "优化:跳过没有变化的推送常量。", [UI_MENU_SPLIT_DRAWS] = "提前提交 GPU 工作", + [UI_MENU_SPLIT_DRAWS_DESC] = "在渲染通道之间每隔 N 次绘制分批提交 GPU 工作,让 GPU 更早开始;0 为关闭。", + [UI_MENU_VK_VALIDATION] = "验证层", [UI_MENU_VK_VALIDATION_DESC] = "检查每一次 Vulkan 调用,会让游戏明显变慢。", + [UI_MENU_VK_VALIDATION_MISSING] = "未安装验证层。", [UI_MENU_VK_DYN_VERTEX] = "动态顶点状态", + [UI_MENU_VK_DYN_VERTEX_DESC] = "强制开启或关闭动态顶点输入;默认值取决于 GPU。", + [UI_MENU_VK_SUBGROUP_PIN] = "固定子组大小", [UI_MENU_VK_SUBGROUP_PIN_DESC] = "固定着色器的子组大小。", + [UI_MENU_TRACE] = "性能日志", [UI_MENU_TRACE_DESC] = "将每帧耗时写入文件。", [UI_MENU_FLIGHT] = "飞行记录器", + [UI_MENU_FLIGHT_DESC] = "保留一小段近期记录,在画面卡住时存盘。", [UI_MENU_FLIGHT_SPIKE_MS] = "卡顿阈值(毫秒)", + [UI_MENU_FLIGHT_SPIKE_MS_DESC] = "帧时间超过多少算作卡顿。", [UI_MENU_INPUT_RECORD] = "输入录制", + [UI_MENU_INPUT_RECORD_DESC] = "将你的输入写入文件,用于报告问题。", [UI_MENU_OPEN_LOG] = "打开日志文件夹", + [UI_MENU_OPEN_LOG_DESC] = "打开存放日志文件的文件夹。", [UI_MENU_COPY_INFO] = "复制系统信息", + [UI_MENU_COPY_INFO_DESC] = "将 GPU、驱动程序、CPU、内存和已修改的设置复制到剪贴板。", + [UI_MENU_COPY_INFO_DONE] = "已复制", [UI_MENU_ACTION_FAILED] = "操作失败", + [UI_MENU_RESET] = "将所有设置恢复为默认值", [UI_MENU_RESET_DESC] = "对所有标签页生效。", + [UI_MENU_RESET_CONFIRM] = "要将所有设置恢复为默认值吗?", [UI_MENU_RESET_YES] = "重置", [UI_MENU_RESET_NO] = "取消", + + [UI_MENU_OV_FPS] = "%.0f FPS", [UI_MENU_OV_FRAME_MS] = "%.1f ms", [UI_MENU_OV_GAME_PCT] = "游戏 %.0f%%", + [UI_MENU_OV_MAX_MS] = "最大 %.1f ms", [UI_MENU_OV_GPU] = "GPU", [UI_MENU_OV_CPU] = "CPU", [UI_MENU_OV_RAM] = "内存", + [UI_MENU_OV_VRAM] = "显存", [UI_MENU_OV_TEMP] = "温度", [UI_MENU_OV_POWER] = "功耗", [UI_MENU_OV_CLOCK] = "频率", + [UI_MENU_OV_NONE] = "-", [UI_MENU_OV_REPLAY] = "GPU 帧准备", [UI_MENU_OV_GPU_TIME] = "每帧 GPU 忙碌时间", + [UI_MENU_OV_PIPE_WAIT] = "管线等待", [UI_MENU_OV_SHADER_WAIT] = "着色器等待", [UI_MENU_OV_TEX_UPLOADS] = "纹理上传", + [UI_MENU_OV_FMT_PCT] = "%.0f%%", [UI_MENU_OV_FMT_TEMP] = "%.0f °C", [UI_MENU_OV_FMT_POWER] = "%.0f W", + [UI_MENU_OV_FMT_MHZ] = "%.0f MHz", [UI_MENU_OV_FMT_GB] = "%.1f GB", [UI_MENU_OV_FMT_GB_OF] = "/ %.1f GB", + [UI_MENU_OV_GAME_GB] = "游戏 %.1f GB", [UI_MENU_OV_FMT_MS] = "%.2f ms", [UI_MENU_OV_PER_FRAME] = "每帧 %.1f", + [UI_MENU_OV_WINDOW] = "窗口", [UI_MENU_OV_OUTPUT] = "游戏画面", [UI_MENU_OV_SCENE] = "3D 场景", + [UI_MENU_OV_SCALING] = "缩放", [UI_MENU_OV_LIMIT] = "帧率上限", [UI_MENU_OV_PRESENT] = "呈现方式", + [UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u,%.0f%%", + [UI_MENU_OV_FMT_FSR] = "AMD FSR 1,锐度 %d%%", [UI_MENU_OV_SCALE_NONE] = "无(1:1)", + [UI_MENU_OV_SCALE_BILINEAR] = "双线性", +}; + #define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)} SWKBD_ONLY(text_ja, "文字入力", "名前を入力してください", "ウマ", "OK", "キャンセル", "コントローラー: A = OK、B = キャンセル"); SWKBD_ONLY(text_fr, "Saisie de texte", "Entrez un nom", "Cheval", "OK", "Annuler", "Manette : A = OK, B = Annuler"); @@ -505,7 +697,6 @@ SWKBD_ONLY(text_es, "Introducir texto", "Introduce un nombre", "Caballo", "Acept "Mando: A = Aceptar, B = Cancelar"); SWKBD_ONLY(text_nl, "Tekstinvoer", "Voer een naam in", "Paard", "OK", "Annuleren", "Controller: A = OK, B = Annuleren"); SWKBD_ONLY(text_pt, "Inserir texto", "Introduz um nome", "Cavalo", "OK", "Cancelar", "Comando: A = OK, B = Cancelar"); -SWKBD_ONLY(text_zh_hans, "文字输入", "请输入名字", "马儿", "确定", "取消", "手柄:A 确定,B 取消"); SWKBD_ONLY(text_zh_hant, "文字輸入", "請輸入名字", "馬兒", "確定", "取消", "手把:A 確定,B 取消"); SWKBD_ONLY(text_ko, "문자 입력", "이름을 입력하세요", "말", "확인", "취소", "컨트롤러: A 확인, B 취소"); @@ -543,17 +734,32 @@ const char *ui_text_in(const char *lang, UiTextId id) { const char *ui_text(UiTextId id) { return ui_text_in(ui_text_lang(ov_language()), id); } -// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG "ru" or "en"; anything else (unset included) -// follows the system UI language: Russian for "ru", "ru-RU", ..., else English. -static const char *resolve_menu_lang(void) { - const char *v = cfg_value("TOTK_MENU_LANG"); - if (v && !strcmp(v, "ru")) return "ru"; - if (v && !strcmp(v, "en")) return "en"; - const char *sys = plat_ui_language(); - return sys && (!strcmp(sys, "ru") || !strncmp(sys, "ru-", 3)) ? "ru" : "en"; +// Matches "" and "-..." (a BCP 47 tag with that primary subtag or prefix). +static int tag_is(const char *tag, const char *lang) { + size_t n = strlen(lang); + return !strncmp(tag, lang, n) && (tag[n] == 0 || tag[n] == '-'); } -const char *menu_text(UiTextId id) { +const char *menu_lang_for_system(const char *tag) { + if (!tag) return "en"; + if (tag_is(tag, "ru")) return "ru"; + // Simplified Chinese: the script subtag when Windows gives one, else the regions that write it (China, Singapore). + // zh-TW, zh-HK and zh-MO write Traditional Chinese, which the menu does not have: English. + if (tag_is(tag, "zh-Hans") || tag_is(tag, "zh-CN") || tag_is(tag, "zh-SG")) return "zh-Hans"; + return "en"; +} + +// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG "en", "ru" or "zh-Hans"; anything else (unset +// included) follows the system UI language (menu_lang_for_system). +static const char *resolve_menu_lang(void) { + static const char *const langs[] = {"en", "ru", "zh-Hans"}; + const char *v = cfg_value("TOTK_MENU_LANG"); + for (size_t i = 0; v && i < sizeof langs / sizeof *langs; i++) + if (!strcmp(v, langs[i])) return langs[i]; + return menu_lang_for_system(plat_ui_language()); +} + +const char *menu_language(void) { static _Atomic(const char *) lang = "en"; static _Atomic unsigned seen = ~0u; unsigned v = cfg_version(); @@ -561,5 +767,7 @@ const char *menu_text(UiTextId id) { atomic_store_explicit(&lang, resolve_menu_lang(), memory_order_relaxed); atomic_store_explicit(&seen, v, memory_order_relaxed); } - return ui_text_in(atomic_load_explicit(&lang, memory_order_relaxed), id); + return atomic_load_explicit(&lang, memory_order_relaxed); } + +const char *menu_text(UiTextId id) { return ui_text_in(menu_language(), id); } diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 13a328b6..d4361cad 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -11,7 +11,8 @@ typedef enum { UI_SWKBD_CANCEL, UI_SWKBD_PAD_HINT, // how a controller answers - // Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English and Russian texts. + // Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian and Simplified Chinese + // texts. UI_MENU_FIRST, UI_MENU_TITLE = UI_MENU_FIRST, UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, @@ -173,6 +174,11 @@ int ui_text_defined(const char *lang, UiTextId id); // The catalog language for a Switch language code ("en-GB" -> "en", "zh-CN" -> "zh-Hans", ...). const char *ui_text_lang(const char *switch_code); -// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en" / "ru"); unset, Russian when the -// system UI language is Russian, else English. Follows a live change of the setting. +// Menu text: ui_text_in(menu_language(), id). const char *menu_text(UiTextId id); +// The menu's catalog language: TOTK_MENU_LANG ("en", "ru" or "zh-Hans"); unset, menu_lang_for_system of the system UI +// language. Follows a live change of the setting. +const char *menu_language(void); +// The menu language for a system UI language tag: "ru" for Russian, "zh-Hans" for Simplified Chinese (zh-Hans..., +// zh-CN, zh-SG), else "en". +const char *menu_lang_for_system(const char *tag); diff --git a/tests/installer_gui_test.py b/tests/installer_gui_test.py index 4eb9c228..6df0d1c0 100644 --- a/tests/installer_gui_test.py +++ b/tests/installer_gui_test.py @@ -31,8 +31,9 @@ from installer import state as statefile # noqa: E402 from installer.events import Reporter # noqa: E402 from installer.runner import Context # noqa: E402 from installer.steps import all_steps # noqa: E402 -from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, Catalog, Form, Model, Process, # noqa: E402 - amount, describe_event, parse_line, windows_ui_language) +from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, # noqa: E402 + UI_LANGUAGES, Catalog, Form, Model, Process, amount, default_game_language, + describe_event, parse_line, ui_language_for_langid, windows_ui_language) INSTALLED = ROOT / 'build' / 'install-test' FIXTURE = ROOT / 'build' / 'inst-gui' / 'e2e-install' @@ -233,12 +234,27 @@ class FormTest(unittest.TestCase): class CatalogTest(unittest.TestCase): - def test_russian_covers_english_with_the_same_placeholders(self): - en, ru = Catalog('en').english, Catalog('ru').texts - self.assertEqual(sorted(set(en) - set(ru)), []) - self.assertEqual(sorted(set(ru) - set(en)), []) - holes = [k for k in en if sorted(re.findall(r'\{\w+\}', en[k])) != sorted(re.findall(r'\{\w+\}', ru[k]))] - self.assertEqual(holes, []) + def test_every_language_covers_english_with_the_same_placeholders(self): + en = Catalog('en').english + for lang in UI_LANGUAGES[1:]: + with self.subTest(lang=lang): + other = Catalog(lang).texts + self.assertEqual(sorted(set(en) - set(other)), []) + self.assertEqual(sorted(set(other) - set(en)), []) + holes = [k for k in en + if sorted(re.findall(r'\{\w+\}', en[k])) != sorted(re.findall(r'\{\w+\}', other[k]))] + self.assertEqual(holes, []) + + def test_language_names_tell_the_codes_apart(self): + # gui.App.selected_lang maps the shown name back to its code across every window language + names = {} + for lang in UI_LANGUAGES: + cat = Catalog(lang) + for id in cat.english: + if id.startswith('lang.'): + names.setdefault(cat(id), set()).add(id) + self.assertEqual({n: ids for n, ids in names.items() if len(ids) > 1}, {}) + self.assertEqual(sorted(UI_LANGUAGE_LABELS), sorted(UI_LANGUAGES)) def test_every_id_the_window_uses_exists(self): cat = Catalog('en') @@ -246,12 +262,13 @@ class CatalogTest(unittest.TestCase): 'process_died', 'result_ok', 'result_failed', 'result_cancelled')] ids += [f'step.{s}' for s in ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup')] ids += ['ui.state_' + n for n in ('started', 'done', 'skipped', 'pending', 'running', 'failed')] - for lang in ('en', 'ru'): + for lang in UI_LANGUAGES: cat.set_language(lang) + self.assertEqual(cat.lang, lang) self.assertEqual([i for i in ids if not cat.has(i)], []) def test_codes_become_names(self): - for lang, korean in (('en', 'Korean'), ('ru', 'Корейский')): + for lang, korean in (('en', 'Korean'), ('ru', 'Корейский'), ('zh-Hans', '韩语')): cat = Catalog(lang) self.assertIn(korean, cat('warn.lang_needs_fonts', lang='ko')) self.assertNotIn(' ko ', cat('warn.lang_needs_fonts', lang='ko')) @@ -280,7 +297,16 @@ class CatalogTest(unittest.TestCase): self.assertEqual(describe_event(cat, {'type': 'start'}), '') def test_windows_language_is_a_known_value(self): - self.assertIn(windows_ui_language(), ('en', 'ru')) + self.assertIn(windows_ui_language(), UI_LANGUAGES) + + def test_windows_langid_picks_the_window_language(self): + for langid, lang in ((0x0419, 'ru'), (0x0819, 'ru'), (0x0804, 'zh-Hans'), (0x1004, 'zh-Hans'), + (0x0404, 'en'), (0x0c04, 'en'), (0x1404, 'en'), (0x0409, 'en'), (0x0411, 'en')): + self.assertEqual(ui_language_for_langid(langid), lang, hex(langid)) + + def test_chinese_window_starts_with_a_game_language_that_needs_no_shared_fonts(self): + self.assertEqual(default_game_language('zh-Hans'), 'en-US') + self.assertEqual(default_game_language('ru'), 'ru') BREAK_CHILD = 'import time\nprint("ready", flush=True)\ntime.sleep(60)\n' diff --git a/tools/make_release.py b/tools/make_release.py index 067c2b34..85483a5e 100644 --- a/tools/make_release.py +++ b/tools/make_release.py @@ -390,12 +390,14 @@ def c_wide(text): def launcher_header(path): - """launcher_text.h: the launcher's two messages in English and Russian, taken from the installer's catalog.""" - lines = ['/* generated by tools/make_release.py from installer/text/{en,ru}.json */'] - for lang in ('en', 'ru'): + """launcher_text.h: the launcher's two messages in English, Russian and Simplified Chinese, taken from the + installer's catalog (macro suffixes EN, RU, ZH_HANS).""" + lines = ['/* generated by tools/make_release.py from installer/text/{en,ru,zh-Hans}.json */'] + for lang in ('en', 'ru', 'zh-Hans'): texts = json.loads((ROOT / 'installer' / 'text' / f'{lang}.json').read_text(encoding='utf-8')) + suffix = lang.upper().replace('-', '_') for key in ('title', 'python_missing'): - lines.append(f'#define LAUNCHER_{key.upper()}_{lang.upper()} {c_wide(texts["launcher." + key])}') + lines.append(f'#define LAUNCHER_{key.upper()}_{suffix} {c_wide(texts["launcher." + key])}') path.parent.mkdir(parents=True, exist_ok=True) path.write_text('\n'.join(lines) + '\n', encoding='ascii') diff --git a/totk.ini.example b/totk.ini.example index aba2432d..fb2d9704 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -134,8 +134,8 @@ # lang = en-US # System mode reported to the game: docked or handheld. # operation_mode = docked -# Language of the settings menu and the overlay: en or ru. Default: the Windows display language, English if it is -# neither. +# Language of the settings menu and the overlay: en, ru or zh-Hans (Simplified Chinese). Default: the Windows display +# language, English if it is none of them (Traditional Chinese included). # menu_lang = en [audio] From 2bcfc2ef39a8fb70c754e7ac1d269bb85fffef01 Mon Sep 17 00:00:00 2001 From: leonelalej <96921992+leonelalej@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:11:46 +0000 Subject: [PATCH 12/19] fix(runtime): clean amiibo platform portability, default path, and dump validation --- runtime/amiibo.c | 377 +++++++++++++++++++++++++++++++++++++ runtime/amiibo.h | 84 +++++++++ runtime/cfg.c | 3 +- runtime/ipc.c | 2 + runtime/nfp.c | 230 ++++++++++++++++++++++ runtime/nfp.h | 14 ++ runtime/ov_probe.c | 12 +- runtime/ov_system.c | 125 ++++++++++-- runtime/ui/amiibo_page.cpp | 272 ++++++++++++++++++++++++++ runtime/ui/amiibo_page.h | 4 + runtime/ui/menu.cpp | 11 +- runtime/ui_text.c | 4 +- runtime/ui_text.h | 4 +- 13 files changed, 1116 insertions(+), 26 deletions(-) create mode 100644 runtime/amiibo.c create mode 100644 runtime/amiibo.h create mode 100644 runtime/nfp.c create mode 100644 runtime/nfp.h create mode 100644 runtime/ui/amiibo_page.cpp create mode 100644 runtime/ui/amiibo_page.h diff --git a/runtime/amiibo.c b/runtime/amiibo.c new file mode 100644 index 00000000..07f30031 --- /dev/null +++ b/runtime/amiibo.c @@ -0,0 +1,377 @@ +// Amiibo dump loader and Horizon OS NFP state emulation. +#include +#include +#include + +#include "amiibo.h" +#include "host.h" +#include "platform/platform.h" + +static PlatMutex g_amiibo_lock = PLAT_MUTEX_INIT; + +// 540-byte raw NTAG215 binary dump +static uint8_t g_dump[AMIIBO_DUMP_SIZE]; +static bool g_has_dump = false; +static AmiiboInfo g_info; + +static bool g_device_present = true; +static bool g_detecting = false; +static bool g_tag_present = false; +static bool g_mounted = false; +static bool g_auto_remove = true; +static float g_auto_remove_delay_s = 2.5f; + +static uint64_t g_tap_timestamp_ns = 0; +static bool g_timer_active = false; + +static bool amiibo_validate_dump(const uint8_t *data, uint64_t size) { + if (size != AMIIBO_DUMP_SIZE) { + return false; + } + + // NTAG215 Capability Container (CC) at page 3 (offset 0x0C). + // Byte 0x0C must be 0xE1 (NDEF Magic / Type 2 Tag CC container byte). + if (data[0x0C] != 0xE1) { + return false; + } + + // UID sanity: UID (bytes 0..2 and 4..7) cannot be all zeroes or all 0xFF. + if ((data[0] == 0 && data[1] == 0 && data[2] == 0 && data[4] == 0 && + data[5] == 0 && data[6] == 0 && data[7] == 0) || + (data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[4] == 0xFF && + data[5] == 0xFF && data[6] == 0xFF && data[7] == 0xFF)) { + return false; + } + + // ISO 14443-3 / NTAG215 Bit Check Character (BCC) verification. + // Page 0 byte 3 (BCC0) = 0x88 ^ UID[0] ^ UID[1] ^ UID[2] + // Page 2 byte 0 (BCC1) = UID[3] ^ UID[4] ^ UID[5] ^ UID[6] + uint8_t bcc0 = (uint8_t)(0x88 ^ data[0] ^ data[1] ^ data[2]); + uint8_t bcc1 = (uint8_t)(data[4] ^ data[5] ^ data[6] ^ data[7]); + if (data[3] != bcc0 || data[8] != bcc1) { + return false; + } + + return true; +} + +static void parse_dump_info(const char *path) { + memset(&g_info, 0, sizeof(g_info)); + if (path) { + snprintf(g_info.path, sizeof(g_info.path), "%s", path); + const char *slash = strrchr(path, '\\'); + const char *fslash = strrchr(path, '/'); + const char *name = slash ? slash + 1 : (fslash ? fslash + 1 : path); + if (slash && fslash) { + name = (slash > fslash ? slash : fslash) + 1; + } + snprintf(g_info.filename, sizeof(g_info.filename), "%s", name); + } + + // UID: bytes 0..6 (7 bytes) or up to 9 + memcpy(g_info.uuid, g_dump, 7); + g_info.uuid_len = 7; + + // Amiibo ID at offset 0x54 (8 bytes) + memcpy(g_info.character_id, g_dump + 0x54, 3); + g_info.series_id = g_dump[0x57]; + g_info.numbering_id = ((uint16_t)g_dump[0x58] << 8) | g_dump[0x59]; + g_info.nfp_type = g_dump[0x5A]; + g_info.version = g_dump[0x5B]; +} + +void amiibo_init(void) { + plat_mutex_lock(&g_amiibo_lock); + g_device_present = true; + g_detecting = false; + g_tag_present = false; + g_mounted = false; + g_has_dump = false; + g_timer_active = false; + memset(g_dump, 0, sizeof(g_dump)); + memset(&g_info, 0, sizeof(g_info)); + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_set_device_present(bool present) { + plat_mutex_lock(&g_amiibo_lock); + g_device_present = present; + plat_mutex_unlock(&g_amiibo_lock); +} + +bool amiibo_is_device_present(void) { + plat_mutex_lock(&g_amiibo_lock); + bool res = g_device_present; + plat_mutex_unlock(&g_amiibo_lock); + return res; +} + +void amiibo_start_detection(void) { + plat_mutex_lock(&g_amiibo_lock); + g_detecting = true; + rt_log("amiibo: start detection"); + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_stop_detection(void) { + plat_mutex_lock(&g_amiibo_lock); + g_detecting = false; + rt_log("amiibo: stop detection"); + plat_mutex_unlock(&g_amiibo_lock); +} + +bool amiibo_is_detecting(void) { + plat_mutex_lock(&g_amiibo_lock); + bool res = g_detecting; + plat_mutex_unlock(&g_amiibo_lock); + return res; +} + +bool amiibo_mount(void) { + plat_mutex_lock(&g_amiibo_lock); + if (!g_device_present || !g_tag_present) { + plat_mutex_unlock(&g_amiibo_lock); + return false; + } + g_mounted = true; + rt_log("amiibo: mounted tag '%s'", g_info.filename[0] ? g_info.filename : "unknown"); + plat_mutex_unlock(&g_amiibo_lock); + return true; +} + +void amiibo_unmount(void) { + plat_mutex_lock(&g_amiibo_lock); + g_mounted = false; + rt_log("amiibo: unmounted tag"); + plat_mutex_unlock(&g_amiibo_lock); +} + +bool amiibo_is_mounted(void) { + plat_mutex_lock(&g_amiibo_lock); + bool res = g_mounted; + plat_mutex_unlock(&g_amiibo_lock); + return res; +} + +AmiiboDeviceState amiibo_get_device_state(void) { + plat_mutex_lock(&g_amiibo_lock); + if (!g_device_present) { + plat_mutex_unlock(&g_amiibo_lock); + return AMIIBO_DEV_STATE_UNAVAILABLE; + } + if (g_mounted) { + plat_mutex_unlock(&g_amiibo_lock); + return AMIIBO_DEV_STATE_TAG_MOUNTED; + } + if (g_tag_present) { + plat_mutex_unlock(&g_amiibo_lock); + return AMIIBO_DEV_STATE_TAG_FOUND; + } + if (g_detecting) { + plat_mutex_unlock(&g_amiibo_lock); + return AMIIBO_DEV_STATE_SEARCHING; + } + plat_mutex_unlock(&g_amiibo_lock); + return AMIIBO_DEV_STATE_INITIALIZED; +} + +bool amiibo_load_file(const char *path) { + if (!path || !*path) return false; + uint64_t size = 0; + uint8_t *data = plat_file_read(path, &size); + if (!data) { + rt_log("amiibo: failed to read file: %s", path); + return false; + } + if (size != AMIIBO_DUMP_SIZE) { + rt_log("amiibo: invalid dump size (%llu bytes, expected exactly %d): %s", + (unsigned long long)size, AMIIBO_DUMP_SIZE, path); + free(data); + return false; + } + if (!amiibo_validate_dump(data, size)) { + rt_log("amiibo: dump failed NTAG215 structure sanity checks: %s", path); + free(data); + return false; + } + + plat_mutex_lock(&g_amiibo_lock); + memcpy(g_dump, data, AMIIBO_DUMP_SIZE); + g_has_dump = true; + parse_dump_info(path); + plat_mutex_unlock(&g_amiibo_lock); + + free(data); + rt_log("amiibo: loaded dump '%s' (char_id: %02x%02x%02x, series: %02x, num: %04x)", + g_info.filename, g_info.character_id[0], g_info.character_id[1], g_info.character_id[2], + g_info.series_id, g_info.numbering_id); + return true; +} + +void amiibo_tap_tag(void) { + plat_mutex_lock(&g_amiibo_lock); + if (!g_has_dump) { + plat_mutex_unlock(&g_amiibo_lock); + return; + } + g_tag_present = true; + g_tap_timestamp_ns = plat_now_ns(); + if (g_auto_remove) { + g_timer_active = true; + } + rt_log("amiibo: tag tapped on reader ('%s')", g_info.filename); + plat_mutex_unlock(&g_amiibo_lock); +} + +bool amiibo_scan_and_tap(const char *path) { + if (!amiibo_load_file(path)) return false; + amiibo_tap_tag(); + return true; +} + +void amiibo_remove_tag(void) { + plat_mutex_lock(&g_amiibo_lock); + if (g_tag_present || g_mounted) { + g_tag_present = false; + g_mounted = false; + g_timer_active = false; + rt_log("amiibo: tag removed from reader"); + } + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_tick(void) { + plat_mutex_lock(&g_amiibo_lock); + if (g_timer_active && g_tag_present) { + uint64_t now = plat_now_ns(); + uint64_t diff = now > g_tap_timestamp_ns ? now - g_tap_timestamp_ns : 0; + uint64_t limit_ns = (uint64_t)(g_auto_remove_delay_s * 1000000000.0f); + if (diff >= limit_ns) { + g_tag_present = false; + g_mounted = false; + g_timer_active = false; + rt_log("amiibo: auto-removed tag after %.1fs timeout", (double)g_auto_remove_delay_s); + } + } + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_set_auto_remove(bool enable) { + plat_mutex_lock(&g_amiibo_lock); + g_auto_remove = enable; + if (!enable) g_timer_active = false; + plat_mutex_unlock(&g_amiibo_lock); +} + +bool amiibo_get_auto_remove(void) { + plat_mutex_lock(&g_amiibo_lock); + bool res = g_auto_remove; + plat_mutex_unlock(&g_amiibo_lock); + return res; +} + +void amiibo_set_auto_remove_delay_s(float seconds) { + plat_mutex_lock(&g_amiibo_lock); + if (seconds >= 0.5f && seconds <= 10.0f) g_auto_remove_delay_s = seconds; + plat_mutex_unlock(&g_amiibo_lock); +} + +float amiibo_get_auto_remove_delay_s(void) { + plat_mutex_lock(&g_amiibo_lock); + float res = g_auto_remove_delay_s; + plat_mutex_unlock(&g_amiibo_lock); + return res; +} + +bool amiibo_has_tag(void) { + plat_mutex_lock(&g_amiibo_lock); + bool res = g_has_dump && g_tag_present; + plat_mutex_unlock(&g_amiibo_lock); + return res; +} + +const AmiiboInfo *amiibo_get_current_info(void) { + return &g_info; +} + +const uint8_t *amiibo_get_raw_data(void) { + return g_dump; +} + +void amiibo_get_tag_info(void *out_tag_info) { + plat_mutex_lock(&g_amiibo_lock); + uint8_t *out = (uint8_t *)out_tag_info; + memset(out, 0, 0x58); + // UUID: offset 0x00, 10 bytes max + memcpy(out + 0x00, g_dump, 7); + out[0x0A] = 7; // UUID length + // Protocol at offset 0x20: TypeA = 1 + *(uint32_t *)(out + 0x20) = 1; + // TagType at offset 0x24: Type2 / NTAG215 = 2 + *(uint32_t *)(out + 0x24) = 2; + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_get_model_info(void *out_model_info) { + plat_mutex_lock(&g_amiibo_lock); + uint8_t *out = (uint8_t *)out_model_info; + memset(out, 0, 0x40); + // Character ID at 0x00 (3 bytes) + memcpy(out + 0x00, g_dump + 0x54, 3); + // Series ID at 0x03 (1 byte) + out[0x03] = g_dump[0x57]; + // Numbering ID at 0x04 (2 bytes, big-endian from 0x58) + out[0x04] = g_dump[0x58]; + out[0x05] = g_dump[0x59]; + // NFP Type at 0x06 (1 byte) + out[0x06] = g_dump[0x5A]; + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_get_common_info(void *out_common_info) { + plat_mutex_lock(&g_amiibo_lock); + uint8_t *out = (uint8_t *)out_common_info; + memset(out, 0, 0x40); + // Last write date: 0x00..0x03 + out[0x00] = 0x07; out[0x01] = 0xE7; // 2023 + out[0x02] = 0x05; out[0x03] = 0x0C; // May 12 + // Write counter: 0x04..0x05 + out[0x04] = 0x00; out[0x05] = 0x01; + // Version: 0x06 + out[0x06] = 0x02; + // Application area size: 0x08..0x0B = 0xD8 (216 bytes) + *(uint32_t *)(out + 0x08) = 0xD8; + plat_mutex_unlock(&g_amiibo_lock); +} + +void amiibo_get_register_info(void *out_register_info) { + plat_mutex_lock(&g_amiibo_lock); + uint8_t *out = (uint8_t *)out_register_info; + memset(out, 0, 0x100); + // Mii CharInfo at 0x00..0x57 (dummy valid mii) + out[0x00] = 0x03; // version 3 + // First write date at 0x58..0x5B + out[0x58] = 0x07; out[0x59] = 0xE7; + out[0x5A] = 0x05; out[0x5B] = 0x0C; + // Amiibo Name at 0x5C: copy up to 40 bytes NUL-terminated + const char *name = g_info.filename[0] ? g_info.filename : "Amiibo"; + snprintf((char *)(out + 0x5C), 0x29, "%s", name); + plat_mutex_unlock(&g_amiibo_lock); +} + +int amiibo_get_application_area(void *out_buf, uint32_t max_size) { + plat_mutex_lock(&g_amiibo_lock); + if (!g_has_dump || !out_buf) { + plat_mutex_unlock(&g_amiibo_lock); + return 0; + } + uint32_t to_copy = max_size < 0xD8 ? max_size : 0xD8; + // Decrypted/payload application area starts at offset 0xDC (or 0x0A0..0x178 in raw dump) + if (0xDC + to_copy <= AMIIBO_DUMP_SIZE) { + memcpy(out_buf, g_dump + 0xDC, to_copy); + } else { + memset(out_buf, 0, to_copy); + } + plat_mutex_unlock(&g_amiibo_lock); + return (int)to_copy; +} diff --git a/runtime/amiibo.h b/runtime/amiibo.h new file mode 100644 index 00000000..11597f8a --- /dev/null +++ b/runtime/amiibo.h @@ -0,0 +1,84 @@ +// Amiibo loader and state management subsystem (540-byte NTAG215 binary dumps). +#pragma once +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AMIIBO_DUMP_SIZE 540 + +// Device state corresponding to nn::nfp / nn::nfc DeviceState +typedef enum { + AMIIBO_DEV_STATE_INITIALIZED = 0, + AMIIBO_DEV_STATE_SEARCHING = 1, + AMIIBO_DEV_STATE_TAG_FOUND = 2, + AMIIBO_DEV_STATE_TAG_REMOVED = 3, + AMIIBO_DEV_STATE_TAG_MOUNTED = 4, + AMIIBO_DEV_STATE_UNAVAILABLE = 5 +} AmiiboDeviceState; + +// Amiibo identification info +typedef struct { + uint8_t uuid[10]; + uint8_t uuid_len; + uint8_t character_id[3]; + uint8_t series_id; + uint16_t numbering_id; + uint8_t nfp_type; + uint8_t version; + char path[512]; + char filename[128]; +} AmiiboInfo; + +// Subsystem lifecycle +void amiibo_init(void); + +// Hardware / device emulation status +void amiibo_set_device_present(bool present); +bool amiibo_is_device_present(void); + +// Tag detection & lifecycle +void amiibo_start_detection(void); +void amiibo_stop_detection(void); +bool amiibo_is_detecting(void); + +// Tag mounting +bool amiibo_mount(void); +void amiibo_unmount(void); +bool amiibo_is_mounted(void); + +// State query +AmiiboDeviceState amiibo_get_device_state(void); + +// File loading & triggering actions +bool amiibo_load_file(const char *path); +bool amiibo_scan_and_tap(const char *path); +void amiibo_tap_tag(void); +void amiibo_remove_tag(void); + +// Timer tick called during menu / frame updates +void amiibo_tick(void); + +// Options +void amiibo_set_auto_remove(bool enable); +bool amiibo_get_auto_remove(void); +void amiibo_set_auto_remove_delay_s(float seconds); +float amiibo_get_auto_remove_delay_s(void); + +// Tag inspection +bool amiibo_has_tag(void); +const AmiiboInfo *amiibo_get_current_info(void); +const uint8_t *amiibo_get_raw_data(void); + +// Horizon OS buffers extraction (called by NFP IPC/override services) +void amiibo_get_tag_info(void *out_tag_info); +void amiibo_get_model_info(void *out_model_info); +void amiibo_get_common_info(void *out_common_info); +void amiibo_get_register_info(void *out_register_info); +int amiibo_get_application_area(void *out_buf, uint32_t max_size); + +#ifdef __cplusplus +} +#endif diff --git a/runtime/cfg.c b/runtime/cfg.c index 2f989519..9bcfa828 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -30,7 +30,7 @@ static int save_ok = 1; // the last cfg_save_to wrote (o // 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[] = { - "AB", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", + "AB", "AMIIBO_DIR", "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", "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", @@ -110,6 +110,7 @@ static const CfgMeta metas[] = { {"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}, {"MENU_LANG", "", "en|ru", LIVE}, + {"AMIIBO_DIR", "", 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/ipc.c b/runtime/ipc.c index a78ae7ac..d47a3620 100644 --- a/runtime/ipc.c +++ b/runtime/ipc.c @@ -11,6 +11,7 @@ #include "audren.h" #include "host.h" #include "ipc.h" +#include "nfp.h" #include "platform/platform.h" #define CMIF_IN_MAGIC 0x49434653u // "SFCI" @@ -25,6 +26,7 @@ enum { T_CLOSE = 2, T_REQUEST = 4, T_CONTROL = 5, T_REQUEST_CTX = 6, T_CONTROL_C // Services sm: hands out. Anything else is a named fatal. static const struct { const char *name; IpcHandler handler; } services[] = { {"audren:u", audren_manager_handler}, + {"nfp:user", nfp_user_manager_handler}, }; static volatile int32_t g_live; diff --git a/runtime/nfp.c b/runtime/nfp.c new file mode 100644 index 00000000..04640fb3 --- /dev/null +++ b/runtime/nfp.c @@ -0,0 +1,230 @@ +// Horizon OS nfp:user IPC service implementation (nn::nfp::detail::IUserManager & IUser). +#include +#include +#include + +#include "amiibo.h" +#include "host.h" +#include "ipc.h" +#include "kernel.h" +#include "nfp.h" + +// Simulated NFC device handle: ID 1 +static const uint8_t g_device_handle[8] = { 1, 0, 0, 0, 0, 0, 0, 0 }; + +typedef struct { + uint32_t activate_event; // writable handle + uint32_t deactivate_event; // writable handle + uint32_t avail_event; // writable handle +} NfpUserState; + +static void nfp_user_close(void *p) { + NfpUserState *st = p; + if (st) { + if (st->activate_event) kern_handle_close(st->activate_event); + if (st->deactivate_event) kern_handle_close(st->deactivate_event); + if (st->avail_event) kern_handle_close(st->avail_event); + free(st); + } + rt_log("nfp: IUser session closed"); +} + +// Handler for nn::nfp::detail::IUser +static void nfp_user_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs) { + NfpUserState *st = (NfpUserState *)s->state; + + switch (rq->cmd) { + case 0: { // InitializeNfp(u64 aruid, u64 m_pid, pid, buffer) + rt_log("nfp: Initialize"); + rs->result = 0; + return; + } + case 1: { // FinalizeNfp() + rt_log("nfp: Finalize"); + amiibo_stop_detection(); + amiibo_unmount(); + rs->result = 0; + return; + } + case 2: { // ListDevicesNfp() -> (s32 total_out, buffer) + int32_t count = amiibo_is_device_present() ? 1 : 0; + IPC_OUT(rs, count); + if (count > 0 && rq->nb > 0 && rq->b[0].size >= sizeof(g_device_handle)) { + void *dst = ipc_guest(rq->b[0].addr, sizeof(g_device_handle)); + memcpy(dst, g_device_handle, sizeof(g_device_handle)); + } + rs->result = 0; + return; + } + case 3: { // StartDetectionNfp(DeviceHandle) + amiibo_start_detection(); + if (amiibo_has_tag() && st && st->activate_event) { + kern_event_signal(st->activate_event); + } + rs->result = 0; + return; + } + case 4: { // StopDetectionNfp(DeviceHandle) + amiibo_stop_detection(); + rs->result = 0; + return; + } + case 5: { // MountNfp(DeviceHandle, u32 ModelType, u32 MountTarget) + if (!amiibo_has_tag()) { + rs->result = 0x8073u; // Device/Tag not found + return; + } + amiibo_mount(); + rs->result = 0; + return; + } + case 6: { // UnmountNfp(DeviceHandle) + amiibo_unmount(); + if (st && st->deactivate_event) { + kern_event_signal(st->deactivate_event); + } + rs->result = 0; + return; + } + case 7: { // OpenApplicationAreaNfp(DeviceHandle, u32 access_id) + if (!amiibo_is_mounted()) { + rs->result = 0x927Fu; // not mounted + return; + } + rs->result = 0; + return; + } + case 8: { // GetApplicationAreaNfp(DeviceHandle) -> (u32 size, buffer) + if (!amiibo_is_mounted()) { + rs->result = 0x927Fu; + return; + } + uint32_t area_size = 0xD8; + if (rq->nb > 0 && rq->b[0].size > 0) { + void *dst = ipc_guest(rq->b[0].addr, rq->b[0].size); + area_size = (uint32_t)amiibo_get_application_area(dst, (uint32_t)rq->b[0].size); + } + IPC_OUT(rs, area_size); + rs->result = 0; + return; + } + case 13: { // GetTagInfoNfp(DeviceHandle) -> buffer + if (!amiibo_has_tag() && !amiibo_is_mounted()) { + rs->result = 0x8073u; + return; + } + if (rq->nb > 0 && rq->b[0].size >= 0x58) { + void *dst = ipc_guest(rq->b[0].addr, 0x58); + amiibo_get_tag_info(dst); + } + rs->result = 0; + return; + } + case 14: { // GetRegisterInfoNfp(DeviceHandle) -> buffer + if (!amiibo_is_mounted()) { + rs->result = 0x927Fu; + return; + } + if (rq->nb > 0 && rq->b[0].size >= 0x100) { + void *dst = ipc_guest(rq->b[0].addr, 0x100); + amiibo_get_register_info(dst); + } + rs->result = 0; + return; + } + case 15: { // GetCommonInfoNfp(DeviceHandle) -> buffer + if (!amiibo_is_mounted()) { + rs->result = 0x927Fu; + return; + } + if (rq->nb > 0 && rq->b[0].size >= 0x40) { + void *dst = ipc_guest(rq->b[0].addr, 0x40); + amiibo_get_common_info(dst); + } + rs->result = 0; + return; + } + case 16: { // GetModelInfoNfp(DeviceHandle) -> buffer + if (!amiibo_is_mounted()) { + rs->result = 0x927Fu; + return; + } + if (rq->nb > 0 && rq->b[0].size >= 0x40) { + void *dst = ipc_guest(rq->b[0].addr, 0x40); + amiibo_get_model_info(dst); + } + rs->result = 0; + return; + } + case 17: { // GetActivateEventHandleNfp(DeviceHandle) -> handle + if (st && st->activate_event) { + rs->copy[rs->ncopy++] = kern_event_readable(st->activate_event); + } + rs->result = 0; + return; + } + case 18: { // GetDeactivateEventHandleNfp(DeviceHandle) -> handle + if (st && st->deactivate_event) { + rs->copy[rs->ncopy++] = kern_event_readable(st->deactivate_event); + } + rs->result = 0; + return; + } + case 19: { // GetStateNfp() -> u32 state + uint32_t state = 1; // Initialized + IPC_OUT(rs, state); + rs->result = 0; + return; + } + case 20: { // GetDeviceStateNfp(DeviceHandle) -> u32 device_state + uint32_t dev_state = (uint32_t)amiibo_get_device_state(); + IPC_OUT(rs, dev_state); + rs->result = 0; + return; + } + case 21: { // GetNpadIdNfp(DeviceHandle) -> u32 npad_id + uint32_t npad_id = 0; // Handheld / Player 1 + IPC_OUT(rs, npad_id); + rs->result = 0; + return; + } + case 22: { // GetApplicationAreaSizeNfp(DeviceHandle) -> u32 size + uint32_t size = 0xD8; + IPC_OUT(rs, size); + rs->result = 0; + return; + } + case 23: { // GetAvailabilityChangeEventHandleNfp() -> handle + if (st && st->avail_event) { + rs->copy[rs->ncopy++] = kern_event_readable(st->avail_event); + } + rs->result = 0; + return; + } + default: + ipc_unimplemented(s, rq); + } +} + +// Handler for nn::nfp::detail::IUserManager (nfp:user) +void nfp_user_manager_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs) { + switch (rq->cmd) { + case 0: { // CreateUserInterface() -> move handle to IUser + NfpUserState *st = calloc(1, sizeof(*st)); + if (!st) rt_fatal("nfp: failed to allocate user state"); + st->activate_event = kern_event_new(); + st->deactivate_event = kern_event_new(); + st->avail_event = kern_event_new(); + // Signal availability immediately so game detects reader + kern_event_signal(st->avail_event); + + uint32_t user_session = ipc_session_new("nfp:IUser", nfp_user_handler, st, nfp_user_close); + rs->move[rs->nmove++] = user_session; + rs->result = 0; + rt_log("nfp: created IUser session handle %#x", user_session); + return; + } + default: + ipc_unimplemented(s, rq); + } +} diff --git a/runtime/nfp.h b/runtime/nfp.h new file mode 100644 index 00000000..e0c5a219 --- /dev/null +++ b/runtime/nfp.h @@ -0,0 +1,14 @@ +// Nintendo Figurine Platform (nfp:user) Horizon OS IPC service emulation. +#pragma once +#include "ipc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// sm: handler for "nfp:user" (nn::nfp::detail::IUserManager) +void nfp_user_manager_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs); + +#ifdef __cplusplus +} +#endif diff --git a/runtime/ov_probe.c b/runtime/ov_probe.c index 9a08a3e5..cce4024f 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -357,21 +357,23 @@ static void probe_applet(void) { "AddInternetConnectionStatus"); CHECK(CALL("nfp.Initialize", 0) == 0 && (uint32_t)CALL("nfp.GetState", 0) == 1, "nfp initialize"); uint8_t handles[64]; - int32_t count = 7; - CHECK((uint32_t)CALL("nfp.ListDevices", U(handles), U(&count), 4) == 0x8073 && count == 0, "nfp ListDevices"); + int32_t count = 0; + CHECK((uint32_t)CALL("nfp.ListDevices", U(handles), U(&count), 4) == 0 && count == 1, "nfp ListDevices"); uint64_t ev = U(guest_alloc(0x100)); CHECK(CALL("nfp.AttachAvailabilityChangeEvent", ev) == 0, "AttachAvailabilityChangeEvent"); int nfp_event = event_works(ev, 0); CHECK(nfp_event, "the nfp availability event does not work as a manual-clear system event"); CHECK((uint32_t)CALL("nfp.GetDeviceState", U(handles)) == 0, "nfp device state"); - static const char *const none[] = {"nfp.Mount", "nfp.GetNpadId", "nfp.AttachActivateEvent", "nfp.AttachDeactivateEvent", - "nfp.StartDetection", "nfp.StopDetection", "nfp.GetTagInfo", "nfp.GetModelInfo"}; + static const char *const none[] = {"nfp.Mount", "nfp.GetTagInfo", "nfp.GetModelInfo"}; uint8_t out[0x100]; for (size_t i = 0; i < sizeof none / sizeof *none; i++) { - int first_is_handle = !strcmp(none[i], "nfp.Mount") || strstr(none[i], "Detection"); + int first_is_handle = !strcmp(none[i], "nfp.Mount"); uint64_t r = first_is_handle ? CALL(none[i], U(handles), 0, 0) : CALL(none[i], U(out), U(handles)); CHECK((uint32_t)r == 0x8073, "%s: %#x, not device-not-found", none[i], (uint32_t)r); } + CHECK((uint32_t)CALL("nfp.GetNpadId", U(out), U(handles)) == 0, "nfp GetNpadId"); + CHECK((uint32_t)CALL("nfp.StartDetection", U(handles)) == 0, "nfp StartDetection"); + CHECK((uint32_t)CALL("nfp.StopDetection", U(handles)) == 0, "nfp StopDetection"); CHECK(CALL("nfp.Finalize", 0) == 0 && (uint32_t)CALL("nfp.GetState", 0) == 0, "nfp finalize"); CALL("err.ShowError", 0x2a8); CALL("nndiagStartup", 0); diff --git a/runtime/ov_system.c b/runtime/ov_system.c index 4e9b3bc0..5aeabed2 100644 --- a/runtime/ov_system.c +++ b/runtime/ov_system.c @@ -19,6 +19,7 @@ #include #include +#include "amiibo.h" #include "cfg.h" #include "fs.h" #include "host.h" @@ -266,26 +267,124 @@ static void ov_report_save(Cpu *c) { // Result PlayReport::Save() and Save(con } static void ov_result_ok(Cpu *c) { ret_x(c, 0); } // RequestImmediateTransmission, AddInternetConnectionStatus -// nn::nfp: no NFC reader +// nn::nfp: NFC reader & amiibo support static volatile int32_t nfp_state; static void ov_nfp_initialize(Cpu *c) { plat_xchg32(&nfp_state, 1); ret_x(c, 0); } -static void ov_nfp_finalize(Cpu *c) { plat_xchg32(&nfp_state, 0); ret_x(c, 0); } +static void ov_nfp_finalize(Cpu *c) { + plat_xchg32(&nfp_state, 0); + amiibo_stop_detection(); + amiibo_unmount(); + ret_x(c, 0); +} static void ov_nfp_state(Cpu *c) { ret_x(c, (uint64_t)nfp_state); } + // Result ListDevices(DeviceHandle *out, int *count, int max) static void ov_nfp_list(Cpu *c) { + void *out = arg_p(c, 0); int32_t *count = arg_p(c, 1); - if (count) *count = 0; - ret_x(c, NFP_R_DEVICE_NOT_FOUND); + int32_t max = (int32_t)arg_x(c, 2); + if (!amiibo_is_device_present()) { + if (count) *count = 0; + ret_x(c, NFP_R_DEVICE_NOT_FOUND); + return; + } + if (out && max > 0) { + static const uint8_t dev[8] = { 1, 0, 0, 0, 0, 0, 0, 0 }; + memcpy(out, dev, sizeof dev); + } + if (count) *count = 1; + ret_x(c, 0); } + // Result AttachAvailabilityChangeEvent(os::SystemEventType *event) static void ov_nfp_availability(Cpu *c) { uint64_t ev = arg_x(c, 0); if (!ev) rt_fatal("nn::nfp::AttachAvailabilityChangeEvent: null event"); kern_bind_system_event(c, ev, 0); + kern_signal_system_event(ev); ret_x(c, 0); } + +// DeviceState GetDeviceState(const DeviceHandle &) +static void ov_nfp_device_state(Cpu *c) { + (void)c; + ret_x(c, (uint64_t)amiibo_get_device_state()); +} + +// Result Mount(const DeviceHandle &, ModelType, MountTarget) +static void ov_nfp_mount(Cpu *c) { + (void)c; + if (!amiibo_has_tag()) { + ret_x(c, NFP_R_DEVICE_NOT_FOUND); + return; + } + amiibo_mount(); + ret_x(c, 0); +} + +// Result GetNpadId(u32 *npad_id, const DeviceHandle &) +static void ov_nfp_get_npad_id(Cpu *c) { + uint32_t *npad = arg_p(c, 0); + if (npad) *npad = 0; // Handheld / Player 1 + ret_x(c, 0); +} + +// Result AttachActivateEvent(os::SystemEventType *event, const DeviceHandle &) +static void ov_nfp_attach_activate(Cpu *c) { + uint64_t ev = arg_x(c, 0); + if (ev) { + kern_bind_system_event(c, ev, 0); + if (amiibo_has_tag()) kern_signal_system_event(ev); + } + ret_x(c, 0); +} + +// Result AttachDeactivateEvent(os::SystemEventType *event, const DeviceHandle &) +static void ov_nfp_attach_deactivate(Cpu *c) { + uint64_t ev = arg_x(c, 0); + if (ev) { + kern_bind_system_event(c, ev, 0); + } + ret_x(c, 0); +} + +// Result StartDetection(const DeviceHandle &) +static void ov_nfp_start_detection(Cpu *c) { + (void)c; + amiibo_start_detection(); + ret_x(c, 0); +} + +// Result StopDetection(const DeviceHandle &) +static void ov_nfp_stop_detection(Cpu *c) { + (void)c; + amiibo_stop_detection(); + ret_x(c, 0); +} + +// Result GetTagInfo(TagInfo *out, const DeviceHandle &) +static void ov_nfp_get_tag_info(Cpu *c) { + void *out = arg_p(c, 0); + if (!amiibo_has_tag() && !amiibo_is_mounted()) { + ret_x(c, NFP_R_DEVICE_NOT_FOUND); + return; + } + if (out) amiibo_get_tag_info(out); + ret_x(c, 0); +} + +// Result GetModelInfo(ModelInfo *out, const DeviceHandle &) +static void ov_nfp_get_model_info(Cpu *c) { + void *out = arg_p(c, 0); + if (!amiibo_is_mounted() && !amiibo_has_tag()) { + ret_x(c, NFP_R_DEVICE_NOT_FOUND); + return; + } + if (out) amiibo_get_model_info(out); + ret_x(c, 0); +} + static void ov_nfp_no_device(Cpu *c) { ret_x(c, NFP_R_DEVICE_NOT_FOUND); } -static void ov_nfp_device_state(Cpu *c) { ret_x(c, 0); } // DeviceState GetDeviceState(const DeviceHandle &): none // void err::ShowError(Result): the game's error dialog, logged static void ov_show_error(Cpu *c) { @@ -795,14 +894,14 @@ HOST_OVERRIDE("_ZN2nn3nfp8GetStateEv", ov_nfp_state); HOST_OVERRIDE("_ZN2nn3nfp11ListDevicesEPNS0_12DeviceHandleEPii", ov_nfp_list); HOST_OVERRIDE("_ZN2nn3nfp29AttachAvailabilityChangeEventEPNS_2os15SystemEventTypeE", ov_nfp_availability); HOST_OVERRIDE("_ZN2nn3nfp14GetDeviceStateERKNS0_12DeviceHandleE", ov_nfp_device_state); -HOST_OVERRIDE("_ZN2nn3nfp5MountERKNS0_12DeviceHandleENS0_9ModelTypeENS0_11MountTargetE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp9GetNpadIdEPjRKNS0_12DeviceHandleE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp19AttachActivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp21AttachDeactivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp14StartDetectionERKNS0_12DeviceHandleE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp13StopDetectionERKNS0_12DeviceHandleE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp10GetTagInfoEPNS0_7TagInfoERKNS0_12DeviceHandleE", ov_nfp_no_device); -HOST_OVERRIDE("_ZN2nn3nfp12GetModelInfoEPNS0_9ModelInfoERKNS0_12DeviceHandleE", ov_nfp_no_device); +HOST_OVERRIDE("_ZN2nn3nfp5MountERKNS0_12DeviceHandleENS0_9ModelTypeENS0_11MountTargetE", ov_nfp_mount); +HOST_OVERRIDE("_ZN2nn3nfp9GetNpadIdEPjRKNS0_12DeviceHandleE", ov_nfp_get_npad_id); +HOST_OVERRIDE("_ZN2nn3nfp19AttachActivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_attach_activate); +HOST_OVERRIDE("_ZN2nn3nfp21AttachDeactivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_attach_deactivate); +HOST_OVERRIDE("_ZN2nn3nfp14StartDetectionERKNS0_12DeviceHandleE", ov_nfp_start_detection); +HOST_OVERRIDE("_ZN2nn3nfp13StopDetectionERKNS0_12DeviceHandleE", ov_nfp_stop_detection); +HOST_OVERRIDE("_ZN2nn3nfp10GetTagInfoEPNS0_7TagInfoERKNS0_12DeviceHandleE", ov_nfp_get_tag_info); +HOST_OVERRIDE("_ZN2nn3nfp12GetModelInfoEPNS0_9ModelInfoERKNS0_12DeviceHandleE", ov_nfp_get_model_info); HOST_OVERRIDE("_ZN2nn3err9ShowErrorENS_6ResultE", ov_show_error); HOST_OVERRIDE("nndiagStartup", ov_diag_startup); diff --git a/runtime/ui/amiibo_page.cpp b/runtime/ui/amiibo_page.cpp new file mode 100644 index 00000000..c3829558 --- /dev/null +++ b/runtime/ui/amiibo_page.cpp @@ -0,0 +1,272 @@ +// Amiibo / NFC menu page (Dear ImGui): browser and scan controls. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "imgui.h" +#include "ui/amiibo_page.h" + +extern "C" { +#include "amiibo.h" +#include "cfg.h" +#include "platform/platform.h" +} + +namespace fs = std::filesystem; + +struct FileEntry { + std::string name; + bool is_dir; +}; + +static const char kDefaultAmiiboDir[] = "./amiibo"; +static std::string g_current_dir = kDefaultAmiiboDir; +static char g_dir_input[512] = "./amiibo"; +static std::vector g_entries; +static int g_selected_entry = -1; +static std::string g_status_msg = "Ready"; + +static bool iequals(std::string_view a, std::string_view b) { + if (a.size() != b.size()) return false; + for (size_t i = 0; i < a.size(); ++i) { + if (std::tolower(static_cast(a[i])) != + std::tolower(static_cast(b[i]))) { + return false; + } + } + return true; +} + +static void set_current_dir(const std::string &path) { + g_current_dir = path; + snprintf(g_dir_input, sizeof(g_dir_input), "%s", g_current_dir.c_str()); + cfg_set("TOTK_AMIIBO_DIR", g_current_dir.c_str()); +} + +static void refresh_dir(void) { + g_entries.clear(); + g_selected_entry = -1; + + std::error_code ec; + fs::path dir_path(g_current_dir); + + // Fall back to "." if directory does not exist or is not a directory + if (!fs::exists(dir_path, ec) || !fs::is_directory(dir_path, ec)) { + if (g_current_dir != ".") { + set_current_dir("."); + dir_path = fs::path(g_current_dir); + } + } + + if (!fs::exists(dir_path, ec) || !fs::is_directory(dir_path, ec)) { + g_status_msg = "Cannot open directory: " + g_current_dir; + return; + } + + // Add parent navigation if not at root + if (dir_path.has_parent_path() && dir_path != dir_path.parent_path()) { + g_entries.push_back({"..", true}); + } + + for (const auto &entry : fs::directory_iterator(dir_path, fs::directory_options::skip_permission_denied, ec)) { + if (ec) break; + std::error_code status_ec; + bool is_dir = entry.is_directory(status_ec); + if (status_ec) continue; + + std::string filename = entry.path().filename().string(); + if (filename.empty() || filename == "." || filename == "..") continue; + + if (!is_dir) { + std::string ext = entry.path().extension().string(); + if (!iequals(ext, ".bin") && !iequals(ext, ".nfc")) { + continue; + } + } + + g_entries.push_back({std::move(filename), is_dir}); + } + + std::sort(g_entries.begin(), g_entries.end(), [](const FileEntry &a, const FileEntry &b) { + if (a.name == "..") return true; + if (b.name == "..") return false; + if (a.is_dir != b.is_dir) return a.is_dir; + return a.name < b.name; + }); +} + +void tab_amiibo(float scale) { + static bool s_inited = false; + if (!s_inited) { + const char *cfg_dir = cfg_get("TOTK_AMIIBO_DIR"); + if (cfg_dir && *cfg_dir) { + g_current_dir = cfg_dir; + } else { + g_current_dir = kDefaultAmiiboDir; + } + snprintf(g_dir_input, sizeof(g_dir_input), "%s", g_current_dir.c_str()); + refresh_dir(); + s_inited = true; + } + + // Two panes: Left (Directory Browser & Tag List), Right (Amiibo Tag Details & Controls) + const float content_h = ImGui::GetContentRegionAvail().y - 20.0f; + const float left_w = ImGui::GetContentRegionAvail().x * 0.58f; + const float right_w = ImGui::GetContentRegionAvail().x - left_w - ImGui::GetStyle().ItemSpacing.x; + + // ---- Left Pane: Explorer & List ---- + ImGui::BeginChild("##amiibo_explorer", ImVec2(left_w, content_h), true); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), "Amiibo NFC Directory:"); + + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); + if (ImGui::InputText("##amiibo_dir_input", g_dir_input, sizeof(g_dir_input), ImGuiInputTextFlags_EnterReturnsTrue)) { + set_current_dir(g_dir_input); + refresh_dir(); + } + + ImGui::Spacing(); + if (ImGui::Button("Set Directory")) { + set_current_dir(g_dir_input); + refresh_dir(); + } + ImGui::SameLine(); + if (ImGui::Button("Default (./amiibo)")) { + set_current_dir(kDefaultAmiiboDir); + refresh_dir(); + } + ImGui::SameLine(); + if (ImGui::Button("Refresh")) { + refresh_dir(); + } + + ImGui::Separator(); + ImGui::TextDisabled("Select an Amiibo file (.bin / .nfc):"); + + ImGui::BeginChild("##file_list", ImVec2(0, 0), true); + for (size_t i = 0; i < g_entries.size(); i++) { + const auto &e = g_entries[i]; + std::string label = (e.is_dir ? "[DIR] " : " ") + e.name; + bool selected = ((int)i == g_selected_entry); + + if (ImGui::Selectable(label.c_str(), selected, ImGuiSelectableFlags_AllowDoubleClick)) { + g_selected_entry = (int)i; + if (e.is_dir) { + if (ImGui::IsMouseDoubleClicked(0) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceDown)) { + if (e.name == "..") { + fs::path cur(g_current_dir); + if (cur.has_parent_path() && cur != cur.parent_path()) { + set_current_dir(cur.parent_path().string()); + } else { + set_current_dir("."); + } + } else { + set_current_dir((fs::path(g_current_dir) / e.name).string()); + } + refresh_dir(); + break; + } + } else { + std::string full_path = (fs::path(g_current_dir) / e.name).string(); + if (ImGui::IsMouseDoubleClicked(0)) { + if (amiibo_scan_and_tap(full_path.c_str())) { + g_status_msg = "Scanned & Tapped: " + e.name; + } else { + g_status_msg = "Error loading " + e.name; + } + } + } + } + } + ImGui::EndChild(); + ImGui::EndChild(); + + ImGui::SameLine(); + + // ---- Right Pane: Controls & Status ---- + ImGui::BeginChild("##amiibo_controls", ImVec2(right_w, content_h), true); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), "NFC Reader & Tag Actions"); + ImGui::Separator(); + + AmiiboDeviceState state = amiibo_get_device_state(); + const char *state_str = "Initialized"; + ImVec4 state_col = ImVec4(0.8f, 0.8f, 0.8f, 1.0f); + switch (state) { + case AMIIBO_DEV_STATE_INITIALIZED: state_str = "Idle / Ready"; break; + case AMIIBO_DEV_STATE_SEARCHING: state_str = "Game Searching for Tag..."; state_col = ImVec4(1.0f, 0.8f, 0.2f, 1.0f); break; + case AMIIBO_DEV_STATE_TAG_FOUND: state_str = "Tag Present / Detected"; state_col = ImVec4(0.3f, 0.9f, 0.3f, 1.0f); break; + case AMIIBO_DEV_STATE_TAG_MOUNTED: state_str = "Tag Mounted (Reading Area)"; state_col = ImVec4(0.2f, 0.9f, 1.0f, 1.0f); break; + case AMIIBO_DEV_STATE_UNAVAILABLE: state_str = "NFC Reader Disabled"; state_col = ImVec4(0.9f, 0.3f, 0.3f, 1.0f); break; + default: break; + } + ImGui::Text("Reader Status: "); + ImGui::SameLine(); + ImGui::TextColored(state_col, "%s", state_str); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Text("Selected File:"); + if (g_selected_entry >= 0 && g_selected_entry < (int)g_entries.size() && !g_entries[g_selected_entry].is_dir) { + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.4f, 1.0f), "%s", g_entries[g_selected_entry].name.c_str()); + + if (ImGui::Button("Scan / Tap Amiibo", ImVec2(ImGui::GetContentRegionAvail().x, 32 * scale))) { + std::string full_path = (fs::path(g_current_dir) / g_entries[g_selected_entry].name).string(); + if (amiibo_scan_and_tap(full_path.c_str())) { + g_status_msg = "Tapped " + g_entries[g_selected_entry].name; + } else { + g_status_msg = "Failed to load dump!"; + } + } + } else { + ImGui::TextDisabled("(No file selected)"); + ImGui::BeginDisabled(); + ImGui::Button("Scan / Tap Amiibo", ImVec2(ImGui::GetContentRegionAvail().x, 32 * scale)); + ImGui::EndDisabled(); + } + + ImGui::Spacing(); + if (ImGui::Button("Remove Tag (Pull away)", ImVec2(ImGui::GetContentRegionAvail().x, 28 * scale))) { + amiibo_remove_tag(); + g_status_msg = "Tag removed"; + } + + ImGui::Spacing(); + ImGui::Separator(); + bool auto_remove = amiibo_get_auto_remove(); + if (ImGui::Checkbox("Auto-remove tag after scan (CEMU style)", &auto_remove)) { + amiibo_set_auto_remove(auto_remove); + } + if (auto_remove) { + float delay = amiibo_get_auto_remove_delay_s(); + if (ImGui::SliderFloat("Hold duration", &delay, 1.0f, 6.0f, "%.1f s")) { + amiibo_set_auto_remove_delay_s(delay); + } + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Text("Loaded Tag Information:"); + if (amiibo_has_tag()) { + const AmiiboInfo *info = amiibo_get_current_info(); + ImGui::Text("File: %s", info->filename); + ImGui::Text("Char ID: %02x%02x%02x | Series: %02x", + info->character_id[0], info->character_id[1], info->character_id[2], info->series_id); + ImGui::Text("Amiibo Number: %04x | Type: %02x", info->numbering_id, info->nfp_type); + ImGui::Text("UID: %02x:%02x:%02x:%02x:%02x:%02x:%02x", + info->uuid[0], info->uuid[1], info->uuid[2], info->uuid[3], + info->uuid[4], info->uuid[5], info->uuid[6]); + } else { + ImGui::TextDisabled("No active tag on reader."); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::TextDisabled("Status: %s", g_status_msg.c_str()); + + ImGui::EndChild(); +} diff --git a/runtime/ui/amiibo_page.h b/runtime/ui/amiibo_page.h new file mode 100644 index 00000000..167ee48c --- /dev/null +++ b/runtime/ui/amiibo_page.h @@ -0,0 +1,4 @@ +// Amiibo / NFC menu page (ui/amiibo_page.cpp). +#pragma once + +void tab_amiibo(float scale); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index b6c08720..a7d7d41a 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -19,10 +19,12 @@ #include "imgui.h" #include "imgui_internal.h" // SetFocusID, NavCursorVisible #include "backends/imgui_impl_vulkan.h" +#include "ui/amiibo_page.h" #include "ui/binds_page.h" #include "ui/option_rows.h" extern "C" { +#include "amiibo.h" #include "cfg.h" #include "input.h" #include "input_map.h" @@ -307,7 +309,7 @@ extern "C" void menu_vk_release(void) { // TOTK_MENU_TEST_SET=:=[,=...][;:...]: cfg_set of each key (TOTK_ prefix // optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by // the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note). -enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_ADVANCED, TAB_COUNT }; +enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_AMIIBO, TAB_MENU, TAB_ADVANCED, TAB_COUNT }; enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 }; struct TestSet { uint64_t frame; char key[64], value[64]; }; static struct { @@ -764,8 +766,9 @@ static void tab_advanced(float scale) { } } -static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, - UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED}; +static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, + UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO, UI_MENU_TAB_MENU, + UI_MENU_TAB_ADVANCED}; static int g_tab; // the tab shown static int g_tab_request = -1; // select this tab at the next layout; -1 none static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none @@ -816,6 +819,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { case TAB_GAME: tab_game(scale); break; case TAB_SOUND: tab_sound(scale); break; case TAB_CONTROLS: tab_controls(scale); break; + case TAB_AMIIBO: tab_amiibo(scale); break; case TAB_MENU: tab_menu(scale); break; case TAB_ADVANCED: tab_advanced(scale); break; } @@ -1097,6 +1101,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame); if (g_perf_save.exchange(0)) cfg_save(); perf_tick(plat_now_ns(), t); + amiibo_tick(); bool open = g_open.load(std::memory_order_relaxed); if (!open) { if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now diff --git a/runtime/ui_text.c b/runtime/ui_text.c index a8ac7155..535f6c66 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -28,7 +28,7 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_TITLE] = "Settings", [UI_MENU_TAB_SCREEN] = "Screen", [UI_MENU_TAB_GAME] = "Game", [UI_MENU_TAB_SOUND] = "Sound", - [UI_MENU_TAB_CONTROLS] = "Controls", [UI_MENU_TAB_MENU] = "Menu", [UI_MENU_TAB_ADVANCED] = "Advanced", + [UI_MENU_TAB_CONTROLS] = "Controls", [UI_MENU_TAB_AMIIBO] = "Amiibo", [UI_MENU_TAB_MENU] = "Menu", [UI_MENU_TAB_ADVANCED] = "Advanced", [UI_MENU_CONTINUE] = "Continue", [UI_MENU_QUIT] = "Quit game", [UI_MENU_ON] = "On", [UI_MENU_OFF] = "Off", [UI_MENU_AUTO] = "Automatic", [UI_MENU_DEFAULT_MARK] = "default", [UI_MENU_AFTER_RESTART] = "after restart", [UI_MENU_SET_BY_ENV] = "set by environment variable", @@ -271,7 +271,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_TITLE] = "Настройки", [UI_MENU_TAB_SCREEN] = "Экран", [UI_MENU_TAB_GAME] = "Игра", [UI_MENU_TAB_SOUND] = "Звук", - [UI_MENU_TAB_CONTROLS] = "Управление", [UI_MENU_TAB_MENU] = "Меню", [UI_MENU_TAB_ADVANCED] = "Дополнительно", + [UI_MENU_TAB_CONTROLS] = "Управление", [UI_MENU_TAB_AMIIBO] = "Amiibo", [UI_MENU_TAB_MENU] = "Меню", [UI_MENU_TAB_ADVANCED] = "Дополнительно", [UI_MENU_CONTINUE] = "Продолжить", [UI_MENU_QUIT] = "Выйти из игры", [UI_MENU_ON] = "Вкл.", [UI_MENU_OFF] = "Выкл.", [UI_MENU_AUTO] = "Автоматически", [UI_MENU_DEFAULT_MARK] = "по умолчанию", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index b9e95194..82e8e9d4 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -14,8 +14,8 @@ typedef enum { // Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English and Russian texts. UI_MENU_FIRST, UI_MENU_TITLE = UI_MENU_FIRST, - UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, - UI_MENU_TAB_ADVANCED, + UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO, + UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED, UI_MENU_CONTINUE, UI_MENU_QUIT, UI_MENU_ON, UI_MENU_OFF, UI_MENU_AUTO, UI_MENU_DEFAULT_MARK, // "default" beside the default value UI_MENU_AFTER_RESTART, // note on a setting that is read at start From 54337ce6a4a794fb54639a192cd429fb0b810601 Mon Sep 17 00:00:00 2001 From: DizzyMan1337 Date: Sun, 1 Nov 2026 00:16:47 +0800 Subject: [PATCH 13/19] Let DLAA copy the camera block out of the uniform snapshot buffer mv_pass copies the scene's camera block from the snapshot arena with vkCmdCopyBuffer, which needs VK_BUFFER_USAGE_TRANSFER_SRC_BIT on the source (VUID-vkCmdCopyBuffer-srcBuffer-00118). Reported by Lucas-blip-png in #228 and SchulzCode in #253. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_usnap.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/vk_usnap.c b/runtime/vk_usnap.c index 056fdf80..8d384afa 100644 --- a/runtime/vk_usnap.c +++ b/runtime/vk_usnap.c @@ -81,7 +81,8 @@ static Arena *arena_get(uint64_t need) { if (!a) rt_fatal("vk_usnap: out of memory"); a->size = need < ARENA_MIN ? ARENA_MIN : (need + (1u << 20) - 1) & ~(uint64_t)((1u << 20) - 1); VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = a->size, - .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT}; + // transfer source: DLAA copies the camera block out (vk_dlaa.c mv_pass) + .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT}; // Device-local through the BAR when the device has it (the GPU reads constants on every draw), else host memory. VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | From 873ebb7755c4d92d20f5cb572f765c8df23f6763 Mon Sep 17 00:00:00 2001 From: turquopool Date: Sun, 1 Nov 2026 15:22:14 +0800 Subject: [PATCH 14/19] Let the installer extract the Switch shared fonts from a firmware folder The setup takes an optional --firmware directory (an unpacked firmware or an emulator's Contents/registered) and, for Chinese, Korean and Traditional Chinese, runs the vendored font extractor into /shared-fonts. Without the folder it warns as before and the install still completes. The fonts step is keyed by the language and a cheap firmware fingerprint; the window gets a folder picker and help text, and the command line takes --firmware. --- config.example.toml | 1 + docs/installer.md | 25 +++-- installer/__init__.py | 5 +- installer/cli.py | 16 ++-- installer/gui.py | 33 +++++-- installer/guilogic.py | 11 ++- installer/ini.py | 3 +- installer/layout.py | 1 + installer/steps.py | 177 ++++++++++++++++++++++++++++++++---- installer/text/en.json | 15 ++- installer/text/ru.json | 15 ++- tests/installer_gui_test.py | 35 +++++-- tests/installer_test.py | 102 +++++++++++++++++++++ totk.ini.example | 3 + 14 files changed, 382 insertions(+), 60 deletions(-) diff --git a/config.example.toml b/config.example.toml index bd34eba8..0140e584 100644 --- a/config.example.toml +++ b/config.example.toml @@ -10,6 +10,7 @@ updates = ['C:\Games\TotK\update-1.4.3.nsp'] keys = 'C:\Switch\prod.keys' # Optional: a firmware NCA directory (an unpacked firmware, or an emulator's installed registered/ directory). # tools/extract_fonts.py takes the system shared fonts from it; the game needs them only with Chinese or Korean text. +# The installer asks for the same folder (--firmware) when the language needs those fonts. # firmware = 'C:\Switch\firmware' [work] diff --git a/docs/installer.md b/docs/installer.md index 304e239c..54d2fe6e 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -11,6 +11,8 @@ holds only the game; the installer and its tools stay outside it. 2. Picks: - the base game (XCI or NSP) and the 1.2.1 or 1.4.3 update (NSP); - their `prod.keys`; + - optionally the firmware folder (`system/Contents/registered` of an unpacked firmware or an emulator's install), + needed for Chinese, Korean and Traditional Chinese text; - the game language and the install folder. 3. Waits for the setup, one time. The window shows each step and its progress. 4. Plays `totk.exe` from the install folder. The installer and the source NSP or XCI can be deleted. @@ -22,6 +24,7 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port totk.exe, SDL3.dll, libopus-0.dll, totk_xlate.exe totk.ini language; the other keys as commented defaults (totk.ini.example) exefs/, romfs/ extracted from the player's files + shared-fonts/ the Switch system fonts, with Chinese, Korean or Traditional Chinese text profile/ saves logs/ totk.log of the last run, totk.1.log to totk.4.log of the runs before it shader and pipeline caches prepared by the setup; shader-cache/shader-cache.pack holds the translations @@ -31,8 +34,8 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port ## Updating the port The player runs a newer installer on the same folder. It reads `totk-install.json`, keeps `romfs/`, `exefs/`, -`profile/` and `totk.ini` after checking their hashes, rebuilds `totk.exe` and re-prepares the shaders. A newer -release that changes nothing game-derived skips the rebuild. +`shared-fonts/`, `profile/` and `totk.ini` after checking their hashes, rebuilds `totk.exe` and re-prepares the +shaders. A newer release that changes nothing game-derived skips the rebuild. Given an update file other than the recorded one (1.2.1, then 1.4.3), the installer extracts and builds again from it and keeps `profile/`. Saves carry over both ways: 1.4.3 converts a 1.2.1 save on load, and 1.2.1 loads the saves 1.4.3 wrote. @@ -43,19 +46,22 @@ keeps `profile/`. Saves carry over both ways: 1.4.3 converts a 1.2.1 save on loa `tools/extract.py`), the keys are new enough for the update, enough space is free on the target disk (about 36 GiB at the peak of a first install, 20 GiB after it), the CPU has AVX2 (`-march=x86-64-v3`), a Vulkan 1.3 GPU exists. Each failure is one clear message. -2. **Extract** ExeFS and RomFS into the install folder and verify the hashes. -3. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into a temp folder next +2. **Fonts** with Chinese, Korean or Traditional Chinese text and a firmware folder: extract the Switch system fonts + from the firmware into `shared-fonts/` (MacNativeGames' `extract_shared_fonts.py`, which verifies every NCA layer + and BFTTF header). Without a firmware folder the setup warns and goes on; the game then lacks those glyphs. +3. **Extract** ExeFS and RomFS into the install folder and verify the hashes. +4. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into a temp folder next to the installer. -4. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS +5. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS hashes and the game version's patch page) and link them with the prebuilt runtime library into `totk.exe` (`build_game.py --runtime-lib`; about 3 min on 24 cores). -5. **Prepare** the RomFS patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`, +6. **Prepare** the RomFS patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`, `totk.exe --prepare-shaders`) in the install folder, then fold the shader cache's loose files (four per shader, about 117,000) into `shader-cache/shader-cache.pack` (`tools/pack_shader_cache.py`). totk.exe reads the pack first and writes the translations it makes in play as loose files; running the tool again with the game closed folds those in. The patches are written twice: `romfs-patches` and `romfs-patches-xbox` (`--xbox-prompts`, the A/B and X/Y prompts swapped for `pad_layout = xbox_prompts`). -6. **Clean up** the temp folder (generated C and objects, about 1.3 GB). +7. **Clean up** the temp folder (generated C and objects, about 1.3 GB). A cancelled or failed setup resumes from the last finished step (`totk-install.json`). @@ -64,10 +70,13 @@ A cancelled or failed setup resumes from the last finished step (`totk-install.j `installer/` (stdlib only; `installer/layout.py` maps the release folder and, in a repository, the dev toolchain): ``` -python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--root DIR] [--temp DIR] [--verify] +python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] [--root DIR] [--temp DIR] [--verify] ``` - On a folder with `totk-install.json` only `--dest` is needed; the game files only when the extraction must run again. +- `--firmware DIR` is the folder holding the firmware NCAs: an unpacked firmware, or the emulators' installed + `Contents/registered` (the parent `Contents` folder works too). It is read only with Chinese, Korean or Traditional + Chinese text, and only when `shared-fonts/` is not already in the install folder. - stdout: one JSON event per line, types `start`, `plan`, `step` (started, done, skipped), `progress` (step, phase, done/total/unit), `space` (bytes needed and free on the install disk and the temp disk), `warning`, `error`, `end` (`installer/events.py`). Messages are ids with parameters; `installer/text/en.json` holds their English text. The human-readable log goes to `/logs/`. diff --git a/installer/__init__.py b/installer/__init__.py index 7c523f73..25092d16 100644 --- a/installer/__init__.py +++ b/installer/__init__.py @@ -1,9 +1,10 @@ """The TotK installer: builds a playable folder from the player's own game files (docs/installer.md). - python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--root DIR] [--temp DIR] + python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] [--root DIR] + [--temp DIR] Modules: layout (where the bundled tools are, release or repository), events (JSON progress on stdout and the log -file), state (totk-install.json), runner (which steps run: resume and update), steps (the six steps), ini (totk.ini), +file), state (totk-install.json), runner (which steps run: resume and update), steps (the seven steps), ini (totk.ini), cli (the command line). text/en.json holds the English text of every message id the events carry. Standard library only, apart from what the extraction tools import (cryptography). Runs on Python 3.14. diff --git a/installer/cli.py b/installer/cli.py index 538f49d1..17e6da64 100644 --- a/installer/cli.py +++ b/installer/cli.py @@ -1,10 +1,12 @@ -"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--root DIR] - [--temp DIR] [--verify] +"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] + [--root DIR] [--temp DIR] [--verify] -A first install needs every option. On a folder with totk-install.json (resume after a cancel or failure, or update -with a newer release) only --dest is needed: --lang defaults to the recorded language, and the game files are needed -only when the extraction has to run again. Prints JSON events on stdout (events.py). Exit code: 0 done, 1 failed, -2 bad command line, 3 cancelled (Ctrl+C or Ctrl+Break). +A first install needs every option. --firmware names the Switch firmware folder (an unpacked firmware or an emulator's +Contents/registered); the setup extracts the system shared fonts from it when the language is Chinese, Korean or +Traditional Chinese. On a folder with totk-install.json (resume after a cancel or failure, or update with a newer +release) only --dest is needed: --lang defaults to the recorded language, and the game files are needed only when the +extraction has to run again. Prints JSON events on stdout (events.py). Exit code: 0 done, 1 failed, 2 bad command +line, 3 cancelled (Ctrl+C or Ctrl+Break). """ import argparse import hashlib @@ -48,6 +50,8 @@ def main(argv=None): ap.add_argument('--base', type=Path, help='base game, XCI or NSP') ap.add_argument('--update', type=Path, help='the update NSP: 1.1.1, 1.2.1 or 1.4.3') ap.add_argument('--keys', type=Path, help='prod.keys') + ap.add_argument('--firmware', type=Path, help='Switch firmware folder (Contents/registered) for the shared fonts ' + 'of Chinese, Korean and Traditional Chinese text') ap.add_argument('--lang', help='game language, a Switch language code (en-US, en-GB, ja, de, ru, ...)') ap.add_argument('--dest', type=Path, required=True, help='install folder') ap.add_argument('--root', type=Path, help='release folder or repository (default: the folder above installer/)') diff --git a/installer/gui.py b/installer/gui.py index cd94fcde..375d2941 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -1,8 +1,9 @@ """The installer window: python -m installer.gui -A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the game language and the -install folder, runs `python -m installer ...` as a subprocess and shows its JSON events. Decisions live in guilogic.py; -this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. +A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the optional firmware +folder, the game language and the install folder, runs `python -m installer ...` as a subprocess and shows its JSON +events. Decisions live in guilogic.py; this file only draws. The window text is in installer/text/.json under +"ui.*" and "launcher.*" ids. --selftest [--shots DIR] build every screen in both languages and close by itself (PNG per screen with --shots) --lang en|ru window language (default: the Windows display language) @@ -51,7 +52,7 @@ class App: self.run_args = run_args or {} # extra CLI options for tests: temp, verify self.log_entries = [] # events and raw lines of the run, rendered by render_log self.bound = [] # (widget, option, id, params) retranslated on a language switch - self.vars = {n: tk.StringVar() for n in ('base', 'update', 'keys', 'dest')} + self.vars = {n: tk.StringVar() for n in ('base', 'update', 'keys', 'firmware', 'dest')} self.vars['lang'] = tk.StringVar() self.lang_code = default_game_language(ui_lang) self.screen = None @@ -197,6 +198,10 @@ class App: b.grid(row=i, column=2, padx=(8, 0)) self.form_rows[name] = lab i = len(rows) + self.label(grid, 'ui.firmware').grid(row=i, column=0, sticky='w', pady=4) + ttk.Entry(grid, textvariable=self.vars['firmware']).grid(row=i, column=1, sticky='ew', pady=4) + self.button(grid, 'ui.browse', self.pick_firmware).grid(row=i, column=2, padx=(8, 0)) + i += 1 self.label(grid, 'ui.game_language').grid(row=i, column=0, sticky='w', pady=4) self.lang_box = ttk.Combobox(grid, textvariable=self.vars['lang'], state='readonly', width=30) self.lang_box.grid(row=i, column=1, sticky='w', pady=4) @@ -206,6 +211,7 @@ class App: self.label(grid, 'ui.dest').grid(row=i + 1, column=0, sticky='w', pady=4) ttk.Entry(grid, textvariable=self.vars['dest']).grid(row=i + 1, column=1, sticky='ew', pady=4) self.button(grid, 'ui.browse', self.pick_dest).grid(row=i + 1, column=2, padx=(8, 0)) + self.label(f, 'ui.firmware_help', wraplength=620, justify='left').pack(anchor='w', pady=(8, 0)) self.update_hint = ttk.Label(f, wraplength=620, justify='left') self.update_hint.pack(anchor='w', pady=(8, 0)) self.form_error = ttk.Label(f, style='Err.TLabel', wraplength=620, justify='left') @@ -266,7 +272,7 @@ class App: def form(self): return Form(base=self.vars['base'].get(), update=self.vars['update'].get(), keys=self.vars['keys'].get(), - lang=self.selected_lang(), dest=self.vars['dest'].get()) + firmware=self.vars['firmware'].get(), lang=self.selected_lang(), dest=self.vars['dest'].get()) def refresh_form(self): form = self.form() @@ -290,6 +296,11 @@ class App: if path: self.vars[name].set(os.path.normpath(path)) + def pick_firmware(self): + path = filedialog.askdirectory(title=self.cat('ui.pick_firmware'), mustexist=True) + if path: + self.vars['firmware'].set(os.path.normpath(path)) + def pick_dest(self): path = filedialog.askdirectory(title=self.cat('ui.pick_dest'), mustexist=False) if path: @@ -306,7 +317,7 @@ class App: return self.form_error.configure(text='') command = form.command(self.layout.python, root=self.layout.root if self.layout.dev else None, - temp=self.run_args.get('temp'), verify=self.run_args.get('verify', False)) + temp=self.run_args.get('temp'), verify_hashes=self.run_args.get('verify', False)) self.begin(command, self.layout.root) def begin(self, command, cwd): @@ -495,10 +506,10 @@ class App: # ---- self test --------------------------------------------------------------------------------------------------- SAMPLE_START = {'type': 'start', 'release': 'selftest', 'mode': 'install', 'dest': 'Z:/selftest/TotK', 'log': 'D:\\log.txt', - 'steps': ['check', 'extract', 'lift', 'compile', 'prepare', 'cleanup']} + 'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'cleanup']} SAMPLE_RUN = [ SAMPLE_START, - {'type': 'plan', 'run': ['check', 'extract'], 'skip': {}}, + {'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}}, {'type': 'step', 'step': 'check', 'state': 'started'}, {'type': 'progress', 'step': 'check', 'phase': 'inputs'}, {'type': 'space', 'dest': 'Z:/selftest/TotK', 'need': 36_400_000_000, 'free': 210_000_000_000, 'temp': 'C:\\t', @@ -511,12 +522,14 @@ SAMPLE_RUN = [ ] -SAMPLE_OK = [SAMPLE_START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'lift': 'current', 'compile': 'current', - 'prepare': 'current', 'cleanup': 'not_needed'}}, +SAMPLE_OK = [SAMPLE_START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'fonts': 'current', 'lift': 'current', + 'compile': 'current', 'prepare': 'current', + 'cleanup': 'not_needed'}}, {'type': 'step', 'step': 'check', 'state': 'started'}, {'type': 'step', 'step': 'check', 'state': 'done', 'seconds': 1.0}, {'type': 'step', 'step': 'extract', 'state': 'started'}, {'type': 'step', 'step': 'extract', 'state': 'done', 'seconds': 1.0}, + {'type': 'step', 'step': 'fonts', 'state': 'skipped', 'reason': 'current'}, {'type': 'step', 'step': 'lift', 'state': 'skipped', 'reason': 'current'}, {'type': 'step', 'step': 'compile', 'state': 'skipped', 'reason': 'current'}, {'type': 'step', 'step': 'prepare', 'state': 'skipped', 'reason': 'current'}, diff --git a/installer/guilogic.py b/installer/guilogic.py index 8d6c4e91..3343c187 100644 --- a/installer/guilogic.py +++ b/installer/guilogic.py @@ -25,7 +25,7 @@ from .events import render TEXT = Path(__file__).resolve().parent / 'text' UI_LANGUAGES = ('en', 'ru') -STEP_ORDER = ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup') +STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'cleanup') # message parameter -> catalog id prefix of the names that replace its raw values PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'} LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID @@ -111,6 +111,7 @@ class Form: base: str = '' update: str = '' keys: str = '' + firmware: str = '' lang: str = '' dest: str = '' @@ -147,19 +148,21 @@ class Form: value = getattr(self, name).strip() if value and not Path(value).is_file(): found.append(f'ui.missing_{name}') + if self.firmware.strip() and not Path(self.firmware.strip()).is_dir(): + found.append('ui.missing_firmware') return found - def command(self, python, root=None, temp=None, verify=False): + def command(self, python, root=None, temp=None, verify_hashes=False): cmd = [str(python), '-m', 'installer'] for flag, value in (('--base', self.base), ('--update', self.update), ('--keys', self.keys), - ('--lang', self.lang), ('--dest', self.dest)): + ('--firmware', self.firmware), ('--lang', self.lang), ('--dest', self.dest)): if value.strip(): cmd += [flag, value.strip()] if root: cmd += ['--root', str(root)] if temp: cmd += ['--temp', str(temp)] - if verify: + if verify_hashes: cmd.append('--verify') return cmd diff --git a/installer/ini.py b/installer/ini.py index 13147862..5cad6f00 100644 --- a/installer/ini.py +++ b/installer/ini.py @@ -14,7 +14,8 @@ LANGUAGES = ('ja', 'en-US', 'en-GB', 'fr', 'fr-CA', 'de', 'it', 'es', 'es-419', 'zh-Hans', 'zh-Hant') # Older installer builds wrote these two codes; they are read as the canonical ones and rewritten on the next install. ALIASES = {'zh-CN': 'zh-Hans', 'zh-TW': 'zh-Hant'} -# Their text falls back to the Switch shared fonts (runtime/ov_system.c), which the installer does not extract. +# Their text falls back to the Switch shared fonts (runtime/ov_system.c), which the fonts step extracts from the +# firmware folder when the player gives one. NEED_SHARED_FONTS = ('ko', 'zh-Hans', 'zh-Hant') ACTIVE = re.compile(r'^(\s*)(?:totk_)?lang(\s*=\s*)(.*?)(\s*)$', re.IGNORECASE) diff --git a/installer/layout.py b/installer/layout.py index 7f31443e..4dfcd64c 100644 --- a/installer/layout.py +++ b/installer/layout.py @@ -81,6 +81,7 @@ class Layout: """Paths the steps need that do not exist.""" need = [self.python, self.tools / 'extract.py', self.tools / 'build_game.py', self.tools / 'prepare_shaders.py', self.tools / 'pack_shader_cache.py', self.tools / 'make_romfs_patches.py', self.tools / 'ultrawide_layout.py', + self.tools / 'vendor' / 'macnativegames' / 'extract_shared_fonts.py', self.recomp / 'gen.py', self.clang, *((self.deps / 'include', self.deps / 'lib') if self.deps else ()), self.runtime, self.runtime_lib, self.ninja, self.hactool, diff --git a/installer/steps.py b/installer/steps.py index 2a165641..74d00531 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -1,13 +1,14 @@ -"""The six setup steps of docs/installer.md: check, extract, lift, compile, prepare, cleanup. +"""The seven setup steps of docs/installer.md: check, fonts, extract, lift, compile, prepare, cleanup. -Extraction runs in this process through tools/extract.py (the package's sibling tools/, which ships with it); lift, -compile and prepare run the bundled Python on recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and -tools/prepare_shaders.py, whose output goes to /logs/-.log and is read for progress. No Win32 call -here: the host check is a small C program built with the bundled clang (hostcheck.c). +Extraction runs in this process through tools/extract.py (the package's sibling tools/, which ships with it); fonts +runs the vendored extract_shared_fonts.py on the firmware folder; lift, compile and prepare run the bundled Python on +recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and tools/prepare_shaders.py, whose output goes to +/logs/-.log and is read for progress. No Win32 call here: the host check is a small C program built +with the bundled clang (hostcheck.c). -Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, totk.exe and its DLLs, romfs-index.bin, -romfs-patches/, romfs-patches-xbox/, totk_xlate.exe, the shader state of totk.exe --prepare-shaders, totk.ini, -totk-install.json. +Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ (Chinese and Korean text), totk.exe +and its DLLs, romfs-index.bin, romfs-patches/, romfs-patches-xbox/, totk_xlate.exe, the shader state of +totk.exe --prepare-shaders, totk.ini, totk-install.json. Temp folder (/-): check/ (ExeFS of both inputs, the host check), gen/ (C), build/ (objects), logs/ (kept by the cleanup). """ @@ -217,6 +218,64 @@ def size_of(paths): return sum(p.stat().st_size for p in paths if p.is_file()) +# The Switch system shared fonts (runtime/ov_system.c): TotK falls back to them for Chinese, Korean and Traditional +# Chinese text. tools/vendor/macnativegames/extract_shared_fonts.py writes these names. +SHARED_FONTS = 'shared-fonts' +SHARED_FONT_FILES = ('0-standard.bfttf', '1-chinese-simplified.bfttf', '2-chinese-simplified-extension.bfttf', + '3-chinese-traditional.bfttf', '4-korean.bfttf', '5-nintendo-extension.bfttf') +FONTS_NEED = 32 << 20 # the six BFTTF files and their manifest + + +def requested_lang(ctx): + """The language this run uses: --lang, else the one recorded for the install (Check canonicalizes it).""" + return ini.canonical_language(getattr(ctx.options, 'lang', None) or ctx.state.get('lang')) + + +def firmware_dir(value): + """The firmware NCA folder behind a --firmware path: the folder itself, or its registered/ child (the emulators' + layout, Contents/registered).""" + if not value: + return None + path = Path(value) + return path / 'registered' if (path / 'registered').is_dir() else path + + +def firmware_has_ncas(folder): + """Whether folder holds firmware NCAs: .nca files, or the hashed directories with a 00 file (registered/).""" + try: + entries = list(Path(folder).iterdir()) + except OSError: + return False + return any((e.is_file() and e.suffix.lower() == '.nca') or (e.is_dir() and (e / '00').is_file()) for e in entries) + + +def firmware_stamp(folder): + """A cheap identity of the firmware NCAs: names, sizes and mtimes, not their contents (the folder is ~326 MB).""" + try: + entries = sorted(Path(folder).iterdir()) + except OSError: + return 'missing' + rows = [] + for entry in entries: + if entry.is_dir(): + file = entry / '00' + if not file.is_file(): + continue + elif not entry.is_file() or entry.suffix.lower() != '.nca': + continue + else: + file = entry + st = file.stat() + rows.append((entry.name, st.st_size, st.st_mtime_ns)) + return rows + + +def shared_fonts_ready(dest): + """Whether dest/shared-fonts holds a complete set that the game can load.""" + folder = Path(dest) / SHARED_FONTS + return (folder / 'manifest.json').is_file() and all((folder / name).is_file() for name in SHARED_FONT_FILES) + + # ---- 1. check class Check(Step): @@ -233,13 +292,30 @@ class Check(Step): own = (ctx.temp, *ctx.temp.parents) # a temp folder inside the install folder (installer/cli.py) is ours if ctx.mode == 'install' and dest.is_dir() and any(p not in own for p in dest.iterdir()): raise InstallError('check.dest_not_empty', path=str(dest)) - lang = ini.canonical_language(ctx.options.lang or ctx.state.get('lang')) + lang = requested_lang(ctx) if not lang: raise InstallError('check.lang_missing') if lang not in ini.LANGUAGES: raise InstallError('check.lang_unknown', lang=lang, known=', '.join(ini.LANGUAGES)) + firmware = firmware_dir(getattr(ctx.options, 'firmware', None)) + if firmware is not None: + if not firmware.is_dir(): + raise InstallError('check.firmware_missing', path=str(firmware)) + if not firmware_has_ncas(firmware): + raise InstallError('check.firmware_empty', path=str(firmware)) if lang in ini.NEED_SHARED_FONTS: - rep.warning('warn.lang_needs_fonts', lang=lang) + if firmware is None: + rep.warning('warn.lang_needs_fonts', lang=lang) + elif not shared_fonts_ready(dest): + keys = getattr(ctx.options, 'keys', None) + if not keys or not Path(keys).is_file(): + raise InstallError('check.fonts_keys_needed') + try: + key_values = load_keys(Path(keys)) + except (ValueError, OSError, UnicodeDecodeError): + raise InstallError('check.keys_unreadable') from None + if 'header_key' not in key_values: + raise InstallError('check.keys_no_header_key') ctx.lang = lang ctx.temp.mkdir(parents=True, exist_ok=True) @@ -368,6 +444,8 @@ class Check(Step): romfs = ctx.dest / 'romfs' / 'romfs.bin' if romfs.is_file(): # a resumed extraction replaces it dest_need -= romfs.stat().st_size + if ctx.will_run('fonts'): + dest_need += FONTS_NEED if ctx.will_run('prepare') or ctx.will_run('extract'): dest_need += DEST_EXTRA if ctx.will_run('lift') or ctx.will_run('compile'): @@ -419,7 +497,72 @@ class Check(Step): ctx.state['version'] = found -# ---- 2. extract +# ---- 2. fonts + +class Fonts(Step): + """The Switch system fonts for Chinese, Korean and Traditional Chinese text (tools/extract_fonts.py, which runs the + vendored extract_shared_fonts.py). The firmware folder is optional: without it the setup warns and the game runs + with those glyphs missing. The extraction verifies the firmware NCAs and writes the six BFTTF files the console + puts in shared memory.""" + + id = 'fonts' + + def key(self, ctx): + lang = requested_lang(ctx) + if lang not in ini.NEED_SHARED_FONTS: + return fingerprint('fonts-1', 'not-needed') + firmware = firmware_dir(getattr(ctx.options, 'firmware', None)) + if firmware is None: + return fingerprint('fonts-1', 'no-firmware') + return fingerprint('fonts-1', lang, str(firmware), firmware_stamp(firmware)) + + def current(self, ctx, record): + if requested_lang(ctx) not in ini.NEED_SHARED_FONTS or not getattr(ctx.options, 'firmware', None): + return True + return shared_fonts_ready(ctx.dest) + + def verify(self, ctx, record): + # An update run may omit --firmware; the installed set still has to be there for these languages. + if requested_lang(ctx) in ini.NEED_SHARED_FONTS: + return shared_fonts_ready(ctx.dest) + return True + + def run(self, ctx): + lang = getattr(ctx, 'lang', None) or requested_lang(ctx) + if lang not in ini.NEED_SHARED_FONTS: + return {} + firmware = firmware_dir(getattr(ctx.options, 'firmware', None)) + if firmware is None: + return {} # Check warned: the game runs, some text may not show + keys = getattr(ctx.options, 'keys', None) + if not keys: + raise InstallError('check.fonts_keys_needed') + out = ctx.temp / 'shared-fonts' + remove(out) + ctx.reporter.progress('fonts', 'extract', force=True) + tool = ctx.layout.tools / 'vendor' / 'macnativegames' / 'extract_shared_fonts.py' + code, log = run_tool(ctx, 'fonts', tool, ['--keys', keys, '--firmware', firmware, '--output', out]) + if code: + detail = '' + try: + detail = log.read_text(encoding='utf-8', errors='replace').strip().splitlines()[-1][:300] + except (OSError, IndexError): + pass + raise InstallError('fonts.failed', code=code, detail=detail, log=str(log)) + missing = [name for name in SHARED_FONT_FILES if not (out / name).is_file()] + if missing or not (out / 'manifest.json').is_file(): + raise InstallError('fonts.incomplete', files=', '.join(missing) or 'manifest.json') + ctx.reporter.progress('fonts', 'copy', force=True) + try: + ctx.dest.mkdir(parents=True, exist_ok=True) + remove(ctx.dest / SHARED_FONTS) + shutil.move(str(out), str(ctx.dest / SHARED_FONTS)) + except OSError as e: + raise InstallError('fonts.copy_failed', path=str(ctx.dest / SHARED_FONTS), detail=str(e)) from None + return {'files': len(SHARED_FONT_FILES)} + + +# ---- 3. extract class Extract(Step): id = 'extract' @@ -527,7 +670,7 @@ class Extract(Step): watch.stop() -# ---- 3. lift +# ---- 4. lift EMITTED = re.compile(r'^emitted (\d+)/(\d+) chunks') DISCOVERED = re.compile(r'^(\w+): \d+ functions \(.*discovery') @@ -563,7 +706,7 @@ class Lift(Step): return {} -# ---- 4. compile +# ---- 5. compile NINJA_LINE = re.compile(r'^\[(\d+)/(\d+)\] ') @@ -620,7 +763,7 @@ class Compile(Step): return {'exe_sha256': file_sha256(dest / exe.name)} -# ---- 5. prepare +# ---- 6. prepare TRANSLATED = re.compile(r'gfx_shader: prepare: (\d+) of (\d+) pairs') @@ -718,7 +861,7 @@ class Prepare(Step): return {'xlate_sha256': file_sha256(xlate)} -# ---- 6. clean up +# ---- 7. clean up class Cleanup(Step): id = 'cleanup' @@ -736,7 +879,7 @@ class Cleanup(Step): rep.progress('cleanup', 'temp', force=True) for stale in dest.glob('update-merge-*'): remove(stale) - for name in ('gen', 'build', 'check', 'shader_list.tsv'): + for name in ('gen', 'build', 'check', 'shader_list.tsv', 'shared-fonts'): remove(ctx.temp / name) romfs_problem(dest / 'romfs', expected_update(ctx)) return {} @@ -758,4 +901,4 @@ def romfs_problem(romfs, expected): def all_steps(): - return [Check(), Extract(), Lift(), Compile(), Prepare(), Cleanup()] + return [Check(), Fonts(), Extract(), Lift(), Compile(), Prepare(), Cleanup()] diff --git a/installer/text/en.json b/installer/text/en.json index c792391e..10997e4a 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -1,5 +1,6 @@ { "step.check": "Checking the computer and the game files", + "step.fonts": "Extracting the system fonts", "step.extract": "Extracting the game", "step.lift": "Translating the game code to C", "step.compile": "Compiling {game_exe}", @@ -11,6 +12,8 @@ "phase.check.verify_romfs": "Checking the installed game data", "phase.check.inputs": "Opening the game files with the keys", "phase.check.versions": "Checking the game versions", + "phase.fonts.extract": "Extracting the shared fonts from the firmware", + "phase.fonts.copy": "Copying the shared fonts into the install folder", "phase.extract.hash_base": "Computing the checksum of the base game", "phase.extract.hash_update": "Computing the checksum of the update", "phase.extract.exefs": "Extracting the game code", @@ -67,10 +70,16 @@ "check.base_wrong_version": "The base game is not version 1.0.0 ({modules} differ).", "check.update_wrong_version": "The update is version {found}; this release takes {wanted}.", "check.disk_space": "Not enough free space for {path}: {need_gb} GB needed, {free_gb} GB free.", + "check.firmware_missing": "The firmware folder {path} does not exist. Choose the firmware's Contents/registered folder.", + "check.firmware_empty": "The firmware folder {path} holds no NCA files. Choose the firmware's Contents/registered folder.", + "check.fonts_keys_needed": "The shared fonts for this language are not installed yet; choose prod.keys so the setup can extract them from the firmware.", "extract.exefs_mismatch": "The extracted game code does not match version {version} ({modules}).", "extract.romfs_merge_failed": "Applying the update to the game data failed: {detail}. Details: {log}", "extract.romfs_mismatch": "The extracted game data does not match version {version} (size {size}, checksum {sha256}...).", + "fonts.failed": "Extracting the shared fonts failed (exit code {code}): {detail}. Details: {log}", + "fonts.incomplete": "The shared font extraction did not write every file ({files}).", + "fonts.copy_failed": "The shared fonts cannot be copied into {path}: {detail}", "lift.failed": "Translating the game code failed (exit code {code}). Details: {log}", "compile.failed": "Compiling {game_exe} failed (exit code {code}). Details: {log}", "compile.exe_in_use": "{path} is in use. Close the game and run the installer again.", @@ -81,7 +90,7 @@ "prepare.pack_failed": "Packing the shader cache failed (exit code {code}). Details: {log}", "cleanup.ini_failed": "totk.ini cannot be written: {detail}", - "warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts, which the installer does not extract; some text may not show.", + "warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts. Choose the firmware folder (Contents/registered) to install them; without it some text may not show.", "warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.", "warn.xbox_prompts_failed": "The Xbox button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}", "warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.", @@ -94,13 +103,16 @@ "ui.base": "Base game (NSP or XCI)", "ui.update": "Update 1.1.1 or 1.2.1 or 1.4.3 (NSP)", "ui.keys": "prod.keys", + "ui.firmware": "Firmware folder (optional)", "ui.game_language": "Game language", "ui.dest": "Install folder", "ui.browse": "Browse...", "ui.pick_game": "Choose the base game file", "ui.pick_update": "Choose the 1.1.1 or 1.2.1 or 1.4.3 update file", "ui.pick_keys": "Choose prod.keys", + "ui.pick_firmware": "Choose the Switch firmware folder (Contents/registered)", "ui.pick_dest": "Choose the install folder", + "ui.firmware_help": "For Chinese, Korean and Traditional Chinese text: the firmware's Contents/registered folder, for example from Ryujinx or Yuzu. The setup copies the Switch system fonts from it into the install folder.", "ui.type_game": "Game files (NSP, XCI)", "ui.type_nsp": "NSP files", "ui.type_keys": "Key files (*.keys)", @@ -122,6 +134,7 @@ "ui.missing_base": "The base game file does not exist.", "ui.missing_update": "The update file does not exist.", "ui.missing_keys": "The keys file does not exist.", + "ui.missing_firmware": "The firmware folder does not exist.", "ui.running_install": "Installing", "ui.running_resume": "Continuing the earlier setup", "ui.running_update": "Updating the installation", diff --git a/installer/text/ru.json b/installer/text/ru.json index e3a668ba..af4074eb 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -1,5 +1,6 @@ { "step.check": "Проверка компьютера и игровых файлов", + "step.fonts": "Извлечение системных шрифтов", "step.extract": "Распаковка игры", "step.lift": "Перевод кода игры в C", "step.compile": "Сборка {game_exe}", @@ -11,6 +12,8 @@ "phase.check.verify_romfs": "Проверка установленных данных игры", "phase.check.inputs": "Открытие игровых файлов с помощью ключей", "phase.check.versions": "Проверка версий игры", + "phase.fonts.extract": "Извлечение общих шрифтов из прошивки", + "phase.fonts.copy": "Копирование общих шрифтов в папку установки", "phase.extract.hash_base": "Подсчёт контрольной суммы базовой игры", "phase.extract.hash_update": "Подсчёт контрольной суммы обновления", "phase.extract.exefs": "Распаковка кода игры", @@ -67,10 +70,16 @@ "check.base_wrong_version": "Базовая игра не версии 1.0.0 (отличаются модули: {modules}).", "check.update_wrong_version": "Версия обновления {found}; этот выпуск принимает {wanted}.", "check.disk_space": "Не хватает свободного места для {path}: нужно {need_gb} ГБ, свободно {free_gb} ГБ.", + "check.firmware_missing": "Папки прошивки {path} нет. Выберите папку Contents/registered прошивки.", + "check.firmware_empty": "В папке прошивки {path} нет файлов NCA. Выберите папку Contents/registered прошивки.", + "check.fonts_keys_needed": "Общие шрифты для этого языка ещё не установлены; выберите prod.keys, чтобы установка извлекла их из прошивки.", "extract.exefs_mismatch": "Распакованный код игры не соответствует версии {version} ({modules}).", "extract.romfs_merge_failed": "Не удалось применить обновление к данным игры: {detail}. Подробности: {log}", "extract.romfs_mismatch": "Распакованные данные игры не соответствуют версии {version} (размер {size}, контрольная сумма {sha256}...).", + "fonts.failed": "Не удалось извлечь общие шрифты (код выхода {code}): {detail}. Подробности: {log}", + "fonts.incomplete": "При извлечении общих шрифтов записаны не все файлы ({files}).", + "fonts.copy_failed": "Не удаётся скопировать общие шрифты в {path}: {detail}", "lift.failed": "Не удалось перевести код игры (код выхода {code}). Подробности: {log}", "compile.failed": "Не удалось собрать {game_exe} (код выхода {code}). Подробности: {log}", "compile.exe_in_use": "Файл {path} занят. Закройте игру и запустите установку снова.", @@ -81,7 +90,7 @@ "prepare.pack_failed": "Не удалось упаковать кэш шейдеров (код выхода {code}). Подробности: {log}", "cleanup.ini_failed": "Не удаётся записать totk.ini: {detail}", - "warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch, которые установка не извлекает; часть текста может не отображаться.", + "warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch. Выберите папку прошивки (Contents/registered), чтобы установить их; без неё часть текста может не отображаться.", "warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.", "warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}", "warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.", @@ -94,13 +103,16 @@ "ui.base": "Базовая игра (NSP или XCI)", "ui.update": "Обновление 1.1.1 или 1.2.1 или 1.4.3 (NSP)", "ui.keys": "prod.keys", + "ui.firmware": "Папка прошивки (необязательно)", "ui.game_language": "Язык игры", "ui.dest": "Папка установки", "ui.browse": "Обзор...", "ui.pick_game": "Выберите файл базовой игры", "ui.pick_update": "Выберите файл обновления 1.1.1 или 1.2.1 или 1.4.3", "ui.pick_keys": "Выберите prod.keys", + "ui.pick_firmware": "Выберите папку прошивки Switch (Contents/registered)", "ui.pick_dest": "Выберите папку установки", + "ui.firmware_help": "Для текста на китайском и корейском: папка Contents/registered прошивки, например из Ryujinx или Yuzu. Установка скопирует из неё системные шрифты Switch в папку установки.", "ui.type_game": "Файлы игры (NSP, XCI)", "ui.type_nsp": "Файлы NSP", "ui.type_keys": "Файлы ключей (*.keys)", @@ -122,6 +134,7 @@ "ui.missing_base": "Файл базовой игры не найден.", "ui.missing_update": "Файл обновления не найден.", "ui.missing_keys": "Файл ключей не найден.", + "ui.missing_firmware": "Папки прошивки нет.", "ui.running_install": "Установка", "ui.running_resume": "Продолжение прерванной установки", "ui.running_update": "Обновление установки", diff --git a/tests/installer_gui_test.py b/tests/installer_gui_test.py index 4eb9c228..db9916e9 100644 --- a/tests/installer_gui_test.py +++ b/tests/installer_gui_test.py @@ -30,7 +30,7 @@ from installer import layout as layouts # noqa: E402 from installer import state as statefile # noqa: E402 from installer.events import Reporter # noqa: E402 from installer.runner import Context # noqa: E402 -from installer.steps import all_steps # noqa: E402 +from installer.steps import Fonts, all_steps # noqa: E402 from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, Catalog, Form, Model, Process, # noqa: E402 amount, describe_event, parse_line, windows_ui_language) @@ -38,7 +38,7 @@ INSTALLED = ROOT / 'build' / 'install-test' FIXTURE = ROOT / 'build' / 'inst-gui' / 'e2e-install' COPIED = ('totk.ini', statefile.NAME) # written by a run, so never linked START = {'type': 'start', 'release': 'r1', 'mode': 'install', 'dest': 'D:\\T', 'log': 'D:\\T.log', - 'steps': ['check', 'extract', 'lift', 'compile', 'prepare', 'cleanup']} + 'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'cleanup']} def fold(*events): @@ -66,7 +66,7 @@ class ModelTest(unittest.TestCase): m = fold(START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'lift': 'current', 'compile': 'current'}}, {'type': 'step', 'step': 'check', 'state': 'started'}) self.assertEqual([m.states[s] for s in m.steps], - [RUNNING, PENDING, SKIPPED, SKIPPED, PENDING, PENDING]) + [RUNNING, PENDING, PENDING, SKIPPED, SKIPPED, PENDING, PENDING]) self.assertEqual(m.current, 'check') m.apply({'type': 'step', 'step': 'check', 'state': 'done', 'seconds': 1.0}) self.assertEqual(m.states['check'], DONE) @@ -137,10 +137,12 @@ class ModelTest(unittest.TestCase): class RunStatesTest(unittest.TestCase): - OK = [START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'lift': 'current', 'compile': 'current', - 'prepare': 'current', 'cleanup': 'not_needed'}}, + OK = [START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'fonts': 'current', 'lift': 'current', + 'compile': 'current', 'prepare': 'current', + 'cleanup': 'not_needed'}}, {'type': 'step', 'step': 'check', 'state': 'started'}, {'type': 'step', 'step': 'check', 'state': 'done'}, {'type': 'step', 'step': 'extract', 'state': 'started'}, {'type': 'step', 'step': 'extract', 'state': 'done'}, + {'type': 'step', 'step': 'fonts', 'state': 'skipped'}, {'type': 'step', 'step': 'lift', 'state': 'skipped'}, {'type': 'step', 'step': 'compile', 'state': 'skipped'}, {'type': 'step', 'step': 'prepare', 'state': 'skipped'}, {'type': 'step', 'step': 'cleanup', 'state': 'done'}, {'type': 'end', 'result': 'ok', 'seconds': 1}] @@ -200,11 +202,20 @@ class FormTest(unittest.TestCase): def test_unknown_language(self): self.assertEqual(self.form(lang='xx').problems(), ['ui.need_lang']) + def test_firmware_folder(self): + firmware = self.dir / 'firmware' + firmware.mkdir() + self.assertEqual(self.form(firmware=str(firmware)).problems(), []) + self.assertEqual(self.form(firmware=str(self.dir / 'no-firmware')).problems(), ['ui.missing_firmware']) + def test_command(self): - cmd = self.form().command('py.exe', root=ROOT, temp=self.dir / 't', verify=True) + firmware = self.dir / 'firmware' + firmware.mkdir() + cmd = self.form(firmware=str(firmware)).command('py.exe', root=ROOT, temp=self.dir / 't', verify_hashes=True) self.assertEqual(cmd[:3], ['py.exe', '-m', 'installer']) - for flag in ('--base', '--update', '--keys', '--lang', '--dest', '--root', '--temp', '--verify'): + for flag in ('--base', '--update', '--keys', '--firmware', '--lang', '--dest', '--root', '--temp', '--verify'): self.assertIn(flag, cmd) + self.assertEqual(cmd[cmd.index('--firmware') + 1], str(firmware)) self.assertEqual(cmd[cmd.index('--lang') + 1], 'en-US') def test_installed_folder_needs_only_itself(self): @@ -244,7 +255,7 @@ class CatalogTest(unittest.TestCase): cat = Catalog('en') ids = ['ui.' + n for n in ('title', 'start', 'cancel', 'open_folder', 'notice', 'space_one', 'space_two', 'process_died', 'result_ok', 'result_failed', 'result_cancelled')] - ids += [f'step.{s}' for s in ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup')] + ids += [f'step.{s}' for s in ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'cleanup')] ids += ['ui.state_' + n for n in ('started', 'done', 'skipped', 'pending', 'running', 'failed')] for lang in ('en', 'ru'): cat.set_language(lang) @@ -334,6 +345,10 @@ def make_fixture(): ctx = Context(layout, FIXTURE, ROOT / 'build' / 'inst-gui' / 'e2e-temp', Reporter(out=io.StringIO()), options, state=state) ctx.steps = all_steps() ctx.plan() + # An install made before the fonts step has no record for it: record it as current when its output is (the + # languages that need the fonts have them in shared-fonts/). + if Fonts().current(ctx, {}): + state['steps'].setdefault('fonts', {'release': state.get('release', ''), 'key': ctx.keys['fonts']}) for step_id, record in state['steps'].items(): record['key'] = ctx.keys[step_id] statefile.save(FIXTURE, state) @@ -346,7 +361,7 @@ class EndToEndTest(unittest.TestCase): def run_cli(form, temp, tries=1): """Runs the CLI in --verify mode through Process, up to `tries` times while the RomFS hash reads wrong.""" for attempt in range(tries): - p = Process(form.command(sys.executable, root=ROOT, temp=temp, verify=True), cwd=ROOT) + p = Process(form.command(sys.executable, root=ROOT, temp=temp, verify_hashes=True), cwd=ROOT) model, stray = Model(), [] t0, code = time.monotonic(), None while code is None and time.monotonic() - t0 < 600: @@ -384,7 +399,7 @@ class EndToEndTest(unittest.TestCase): def test_cancel_during_the_check(self): cmd = Form(dest=str(make_fixture())).command(sys.executable, root=ROOT, temp=ROOT / 'build' / 'inst-gui' / 'e2e-temp', - verify=True) + verify_hashes=True) p = Process(cmd, cwd=ROOT) model, t0, code, cancelled = Model(), time.monotonic(), None, False while code is None and time.monotonic() - t0 < 120: diff --git a/tests/installer_test.py b/tests/installer_test.py index 036d897a..bc248f58 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -291,6 +291,108 @@ class CleanupTest(unittest.TestCase): self.assertEqual(self.run_cleanup(), 'cleanup.romfs_unreadable') +class FontsTest(unittest.TestCase): + """The fonts step: keyed by language and firmware, a no-op without firmware, writes dest/shared-fonts.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + base = Path(self.tmp.name) + self.dest, temp, self.firmware = base / 'dest', base / 'temp', base / 'firmware' + temp.mkdir() + self.firmware.mkdir() + (self.firmware / 'a.nca').write_bytes(b'nca') + self.keys = base / 'prod.keys' + self.keys.write_text('header_key = 00\n') + self.ctx = SimpleNamespace(dest=self.dest, temp=temp, lang='zh-Hans', state={}, + layout=SimpleNamespace(tools=ROOT / 'tools', root=ROOT), + reporter=Reporter(out=io.StringIO()), + options=SimpleNamespace(lang='zh-Hans', firmware=self.firmware, keys=str(self.keys))) + self.saved_run_tool = steps.run_tool + + def tearDown(self): + steps.run_tool = self.saved_run_tool + self.ctx.reporter.close() + self.tmp.cleanup() + + def fake_tool(self, files=None, code=0): + """Stand-in for extract_shared_fonts.py: writes the requested files where --output points.""" + def run(ctx, step, script, args): + out = Path(args[args.index('--output') + 1]) + out.mkdir(parents=True) + for name in steps.SHARED_FONT_FILES if files is None else files: + (out / name).write_bytes(b'bfttf') + (out / 'manifest.json').write_text('{}') + log = ctx.temp / 'fonts.log' + log.write_text('error line\n') + return code, log + steps.run_tool = run + + def test_all_steps_order(self): + self.assertEqual([s.id for s in steps.all_steps()], + ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'cleanup']) + + def test_extracts_into_the_install_folder(self): + self.fake_tool() + self.assertEqual(steps.Fonts().run(self.ctx), {'files': 6}) + self.assertTrue(steps.shared_fonts_ready(self.dest)) + self.assertEqual(sorted(p.name for p in (self.dest / 'shared-fonts').iterdir()), + sorted((*steps.SHARED_FONT_FILES, 'manifest.json'))) + + def test_noop_without_firmware(self): + self.ctx.options.firmware = None + self.fake_tool() + self.assertEqual(steps.Fonts().run(self.ctx), {}) + self.assertFalse((self.dest / 'shared-fonts').exists()) + + def test_noop_for_other_languages(self): + self.ctx.lang, self.ctx.options.lang = 'en-US', 'en-US' + self.fake_tool() + self.assertEqual(steps.Fonts().run(self.ctx), {}) + self.assertFalse((self.dest / 'shared-fonts').exists()) + + def test_failed_extraction_keeps_the_old_folder(self): + self.fake_tool() + steps.Fonts().run(self.ctx) + self.fake_tool(code=1) + with self.assertRaises(steps.InstallError) as e: + steps.Fonts().run(self.ctx) + self.assertEqual(e.exception.id, 'fonts.failed') + self.assertTrue(steps.shared_fonts_ready(self.dest)) + + def test_incomplete_output_is_an_error(self): + self.fake_tool(files=steps.SHARED_FONT_FILES[:1]) + with self.assertRaises(steps.InstallError) as e: + steps.Fonts().run(self.ctx) + self.assertEqual(e.exception.id, 'fonts.incomplete') + + def test_current_tracks_language_and_output(self): + fonts = steps.Fonts() + self.assertFalse(fonts.current(self.ctx, {})) + self.fake_tool() + fonts.run(self.ctx) + self.assertTrue(fonts.current(self.ctx, {})) + self.ctx.options.lang = 'en-US' + self.assertTrue(fonts.current(self.ctx, {})) + self.ctx.options.lang = 'zh-Hans' + (self.dest / 'shared-fonts' / '0-standard.bfttf').unlink() + self.assertFalse(fonts.current(self.ctx, {})) + + def test_key_changes_with_language_and_firmware(self): + fonts = steps.Fonts() + zh = fonts.key(self.ctx) + self.ctx.options.lang = 'en-US' + self.assertNotEqual(zh, fonts.key(self.ctx)) + self.ctx.options.lang = 'zh-Hans' + (self.firmware / 'b.nca').write_bytes(b'other') + self.assertNotEqual(zh, fonts.key(self.ctx)) + + def test_registered_child_is_used(self): + nested = self.firmware / 'registered' + nested.mkdir() + (nested / 'c.nca').write_bytes(b'nca') + self.assertEqual(steps.firmware_dir(self.firmware), nested) + + class EventsTest(unittest.TestCase): def test_lines_are_json_and_the_log_is_english(self): with tempfile.TemporaryDirectory() as d: diff --git a/totk.ini.example b/totk.ini.example index 6d3d5f1e..bbd2545c 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -215,6 +215,9 @@ [files] # Folder with RomFS mod files that replace or add game files. Default: none. # romfs_mods = +# Folder with the Switch shared fonts (BFTTF files, tools/extract_fonts.py output), for Chinese and Korean text. +# Default: shared-fonts next to totk.exe. TOTK_SHARED_FONTS overrides it. +# shared_fonts = [diagnostics] # Extra lines in the log, comma separated: svc, host, ipc, fs, gfx, perf, sched, audio, present or all. The menu's From 90319e6c9a3afd25e253090306f53f4854f8bd4b Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sun, 1 Nov 2026 11:41:27 +0300 Subject: [PATCH 15/19] Load NGX only with dlaa on at start, and skip the FXAA shader lookup at the defaults vk_dlaa_wanted answered 1 on every machine, so each start on an NVIDIA driver loaded the NGX core and enabled its device extensions with DLAA off; dlaa now applies after a restart. vk_dlaa_skip_draw hashed the fragment shader of every draw through an unlocked 8192-entry table, which 1.4.3's shader variants outgrow; with fxaa on and DLSS not scaling there is nothing to skip, so it returns before the lookup. Also gives the DLSS rows their Brazilian Portuguese and Simplified Chinese text. Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 2 +- runtime/ui_text.c | 32 ++++++++++++++++++++++++++++++-- runtime/vk_dlaa.c | 12 +++++++++--- totk.ini.example | 3 +-- 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/runtime/cfg.c b/runtime/cfg.c index dbd6a2aa..8c63b839 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -109,7 +109,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, - {"DLAA", "0", "0|1", LIVE}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance", RESTART}, {"FXAA", "1", "0|1", LIVE}, + {"DLAA", "0", "0|1", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance", RESTART}, {"FXAA", "1", "0|1", LIVE}, {"ASPECT", "fit", "fit|stretch", LIVE}, {"FOV", "100", "70..140", LIVE}, {"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features // colour adjustment (vk_color.c); the preset is the menu's, the four values are what the present uses diff --git a/runtime/ui_text.c b/runtime/ui_text.c index ced42aa2..87ef14a1 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -123,7 +123,8 @@ static const char *const text_en[UI_TEXT_COUNT] = { "Takes effect at the next start.", [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", [UI_MENU_DLAA_DESC] = "NVIDIA DLSS for the 3D scene (NVIDIA RTX GPUs; nvngx_dlss.dll next to totk.exe): smoother edges " - "and less shimmer. The HUD is not touched. The mode below sets the resolution it works from.", + "and less shimmer. The HUD is not touched. The mode below sets the resolution it works from. Takes effect " + "after a restart.", [UI_MENU_DLSS] = "DLSS mode", [UI_MENU_DLSS_DESC] = "DLAA draws the 3D scene at full resolution. Quality, Balanced and Performance draw it at 67, 58 " "and 50 % and let DLSS scale it up, for more frames per second; they replace the 3D render " @@ -455,7 +456,8 @@ static const char *const text_ru[UI_TEXT_COUNT] = { "разрешение теней. Действует после перезапуска.", [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", [UI_MENU_DLAA_DESC] = "NVIDIA DLSS для 3D-сцены (видеокарты NVIDIA RTX; nvngx_dlss.dll рядом с totk.exe): ровнее края и " - "меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он работает.", + "меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он работает. " + "Действует после перезапуска.", [UI_MENU_DLSS] = "Режим DLSS", [UI_MENU_DLSS_DESC] = "DLAA рисует 3D-сцену в полном разрешении. «Качество», «Баланс» и «Производительность» рисуют её " "в 67, 58 и 50 % и масштабируют через DLSS ради большего числа кадров; они заменяют масштаб " @@ -1035,6 +1037,21 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_PCSS] = "Sombras suaves", [UI_MENU_PCSS_DESC] = "Sombras do sol nítidas onde um objeto toca o chão e mais suaves quanto mais longe a sombra " "cai (PCSS). 0 mantém o filtro do jogo. Vale no próximo início.", + [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", + [UI_MENU_DLAA_DESC] = "NVIDIA DLSS para a cena 3D (placas NVIDIA RTX; nvngx_dlss.dll ao lado do totk.exe): bordas " + "mais suaves e menos cintilação. O HUD não é afetado. O modo abaixo define a resolução de " + "onde ele parte. Vale após reiniciar.", + [UI_MENU_DLSS] = "Modo do DLSS", + [UI_MENU_DLSS_DESC] = "DLAA desenha a cena 3D na resolução cheia. Qualidade, Equilibrado e Desempenho a desenham " + "em 67, 58 e 50 % e deixam o DLSS ampliá-la, para mais quadros por segundo; eles substituem " + "a escala 3D. Vale após reiniciar.", + [UI_MENU_DLSS_DLAA] = "DLAA (nativo)", + [UI_MENU_DLSS_QUALITY] = "Qualidade", + [UI_MENU_DLSS_BALANCED] = "Equilibrado", + [UI_MENU_DLSS_PERFORMANCE] = "Desempenho", + [UI_MENU_FXAA] = "Antisserrilhado do jogo (FXAA)", + [UI_MENU_FXAA_DESC] = "A suavização de bordas FXAA do próprio jogo. Borra um pouco os detalhes finos; com o DLAA " + "ligado não é necessária.", }; // Simplified Chinese: this row covers the software keyboard and the whole menu, so the menu and the overlay read Chinese @@ -1494,6 +1511,17 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_CONTACT_SHADOWS_DESC] = "阴影贴图遗漏的细小太阳阴影:脚下、石头下、草丛和褶皱中。在光照之后于屏幕空间追踪。下次启动时生效。", [UI_MENU_PCSS] = "柔和阴影", [UI_MENU_PCSS_DESC] = "物体接触地面处的太阳阴影锐利,阴影投得越远越柔和(PCSS)。0 保留游戏自身的过滤。下次启动时生效。", + [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", + [UI_MENU_DLAA_DESC] = "用于 3D 场景的 NVIDIA DLSS(NVIDIA RTX 显卡;nvngx_dlss.dll 放在 totk.exe 旁):边缘更平滑,闪烁更少。HUD " + "不受影响。下方的模式决定它的工作分辨率。重启后生效。", + [UI_MENU_DLSS] = "DLSS 模式", + [UI_MENU_DLSS_DESC] = "DLAA 以全分辨率绘制 3D 场景。质量、平衡和性能分别以 67%、58% 和 50% 绘制,再由 DLSS 放大,以获得更高帧率;它们会取代 3D 渲染比例。重启后生效。", + [UI_MENU_DLSS_DLAA] = "DLAA(原生)", + [UI_MENU_DLSS_QUALITY] = "质量", + [UI_MENU_DLSS_BALANCED] = "平衡", + [UI_MENU_DLSS_PERFORMANCE] = "性能", + [UI_MENU_FXAA] = "游戏抗锯齿(FXAA)", + [UI_MENU_FXAA_DESC] = "游戏自身的 FXAA 边缘平滑。会让细节略微模糊;开启 DLAA 时不需要。", }; #define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)} diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c index 41de947d..39244b0a 100644 --- a/runtime/vk_dlaa.c +++ b/runtime/vk_dlaa.c @@ -86,9 +86,14 @@ static int p_getu(const NgxParam *p, const char *n, unsigned *v) { return NGX_OK static int p_getf(const NgxParam *p, const char *n, float *v) { return NGX_OK(((GetF)p->vt->slot[G_F])(p, n, v)); } static int p_getp(const NgxParam *p, const char *n, void **v) { return NGX_OK(((GetP)p->vt->slot[G_P])(p, n, v)); } -// NGX is brought up whenever the driver has it, whatever the setting, so dlaa can be switched on while the game runs -// (its device extensions can only be asked for at device creation). Switched off, nothing else of DLAA runs. -int vk_dlaa_wanted(void) { return 1; } +// NGX is brought up only when dlaa is on at start: its device extensions can only be asked for at device creation, and +// loading the driver's NGX core on every NVIDIA machine would cost start time and change the device with DLAA off. So +// dlaa applies after a restart; switched off, nothing else of DLAA runs. +int vk_dlaa_wanted(void) { + static int wanted = -1; + if (wanted < 0) wanted = cfg_bool("TOTK_DLAA"); + return wanted; +} static int core_load(void) { if (N.tried) return N.loaded; @@ -656,6 +661,7 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) { static int fxaa = 1; uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED); if (f != frame_read) frame_read = f, fxaa = cfg_bool("TOTK_FXAA"); // once a frame: the menu switches it live + if (fxaa && !D.up) return 0; // nothing to skip: no shader lookup per draw at the defaults if (!fs) return 0; uint64_t h = spirv_hash(fs); if (h != FXAA_FS[0] && h != FXAA_FS[1]) return 0; diff --git a/totk.ini.example b/totk.ini.example index 7a0c0589..d28e2cbc 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -182,8 +182,7 @@ # pcss = 0 # NVIDIA DLSS / DLAA for the 3D scene, on NVIDIA RTX GPUs with nvngx_dlss.dll (from NVIDIA's DLSS SDK) next to -# totk.exe; elsewhere the setting does nothing. The HUD is drawn after it and is not touched. Changes while the game -# runs take effect at once. +# totk.exe; elsewhere the setting does nothing. The HUD is drawn after it and is not touched. Read at start. # dlaa = 0 # What DLSS works from: dlaa (the 3D scene at full size), quality, balanced or performance (the scene at 67, 58 or # 50 % of the output, scaled up by DLSS; these replace render_scale and sharpen texture filtering to match). With dlaa From 0b84f48df23216d2a5817af5fd3aab656f3910bd Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sun, 1 Nov 2026 11:42:15 +0300 Subject: [PATCH 16/19] Build vk_dlaa.c off Windows as no-op stubs It includes windows.h and loads NGX as a Windows DLL, and build_game.py leaves only *_win.* files out of the Linux build, which then stopped at it. Elsewhere DLAA, the DLSS scaling and the FXAA switch now do nothing. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_dlaa.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c index 39244b0a..af926221 100644 --- a/runtime/vk_dlaa.c +++ b/runtime/vk_dlaa.c @@ -9,6 +9,7 @@ // layout with a set-then-get round trip before anything relies on it. // // Where DLAA runs in the frame, the jitter and the motion vectors: see the sections below. +#ifdef _WIN32 #include #include #include @@ -668,3 +669,20 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) { if (!ex->depth.image) return D.up; // the scaling pass return !fxaa; } + +#else +// NGX is loaded as a Windows DLL; elsewhere DLAA, the DLSS modes' scaling and the FXAA switch do nothing. +#include "vk_dlaa.h" + +int vk_dlaa_wanted(void) { return 0; } +void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max) { (void)ext, (void)n, (void)max; } +void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) { + (void)have, (void)nhave, (void)ext, (void)n, (void)max; +} +void vk_dlaa_init(void) {} +void vk_dlaa_pass(VkExec *ex) { (void)ex; } +void vk_dlaa_frame(void) {} +void vk_dlaa_draw(VkExec *ex) { (void)ex; } +void vk_dlaa_viewport(VkExec *ex, VkViewport *v) { (void)ex, (void)v; } +int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) { (void)ex, (void)fs; return 0; } +#endif From a40c507aa1f2eea7302b669ee9d37f038866d49a Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sun, 1 Nov 2026 12:36:10 +0300 Subject: [PATCH 17/19] Name the stick dead zone notes stick_note, apart from the prompts note in the same function The per-stick rows of #175 declared a second `note` in tab_controls, beside the button prompts note dev added there, and runtime/ui/menu.cpp did not compile. Co-Authored-By: Claude Opus 5.5 --- runtime/ui/menu.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index e5784418..f65aa3ef 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -819,12 +819,13 @@ static void tab_controls(float scale) { // row shows its stick's deflection now, before the dead zone: a drifting stick's resting value, to set it above. double now[2]; bool pad = input_pad_stick_percent(now) != 0; - char note[2][64]; - for (int s = 0; s < 2; s++) snprintf(note[s], sizeof note[s], menu_text(UI_MENU_STICK_DEADZONE_NOW), now[s]); + char stick_note[2][64]; + for (int s = 0; s < 2; s++) + snprintf(stick_note[s], sizeof stick_note[s], menu_text(UI_MENU_STICK_DEADZONE_NOW), now[s]); opt_slider("TOTK_LSTICK_DEADZONE", UI_MENU_LSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%", - pad ? note[0] : nullptr, "TOTK_STICK_DEADZONE"); + pad ? stick_note[0] : nullptr, "TOTK_STICK_DEADZONE"); opt_slider("TOTK_RSTICK_DEADZONE", UI_MENU_RSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%", - pad ? note[1] : nullptr, "TOTK_STICK_DEADZONE"); + pad ? stick_note[1] : nullptr, "TOTK_STICK_DEADZONE"); opt_slider("TOTK_STICK_SENS", UI_MENU_STICK_SENS, 0.1f, 3, UI_MENU_STICK_SENS_DESC, 0.05f, "%.2f"); opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f"); row_walk_key(); From c3ec7a531202698e5a621245808a8282dda7fd84 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sun, 1 Nov 2026 12:43:03 +0300 Subject: [PATCH 18/19] Check the emulated NFC reader in probe-services Since #235 the reader is there from the start: the availability event is set when it is attached, and AttachActivateEvent and AttachDeactivateEvent bind their events instead of answering device-not-found. The probe now attaches both and checks that the activate event stays clear without an amiibo, so every nfp override is called again. Co-Authored-By: Claude Opus 5.5 --- runtime/ov_probe.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/runtime/ov_probe.c b/runtime/ov_probe.c index d39abfda..9a803004 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -348,6 +348,13 @@ static int event_works(uint64_t ev, int autoclear) { return !before && after && again == !autoclear; } +// A manual-clear system event an override signalled when binding it: set, and still set on a second wait. +static int event_set(uint64_t ev) { + static uint64_t try_wait; + if (!try_wait && !(try_wait = ldr_symbol(TRY_WAIT_SYSTEM_EVENT))) rt_fatal("probe-services: no %s", TRY_WAIT_SYSTEM_EVENT); + return (uint8_t)rt_call(gc, try_wait, 1, ev) && (uint8_t)rt_call(gc, try_wait, 1, ev); +} + static void probe_applet(void) { uint8_t *report = guest_alloc(0x100); uint64_t uid[2] = {1, 2}; @@ -361,8 +368,9 @@ static void probe_applet(void) { CHECK((uint32_t)CALL("nfp.ListDevices", U(handles), U(&count), 4) == 0 && count == 1, "nfp ListDevices"); uint64_t ev = U(guest_alloc(0x100)); CHECK(CALL("nfp.AttachAvailabilityChangeEvent", ev) == 0, "AttachAvailabilityChangeEvent"); - int nfp_event = event_works(ev, 0); - CHECK(nfp_event, "the nfp availability event does not work as a manual-clear system event"); + // The emulated reader is there from the start (amiibo.c), so the availability event is set when it is attached. + int nfp_event = event_set(ev); + CHECK(nfp_event, "the nfp availability event is not set for the emulated reader, or clears itself"); CHECK((uint32_t)CALL("nfp.GetDeviceState", U(handles)) == 0, "nfp device state"); static const char *const none[] = {"nfp.Mount", "nfp.GetTagInfo", "nfp.GetModelInfo"}; uint8_t out[0x100]; @@ -372,6 +380,10 @@ static void probe_applet(void) { CHECK((uint32_t)r == 0x8073, "%s: %#x, not device-not-found", none[i], (uint32_t)r); } CHECK((uint32_t)CALL("nfp.GetNpadId", U(out), U(handles)) == 0, "nfp GetNpadId"); + uint64_t activate = U(guest_alloc(0x100)), deactivate = U(guest_alloc(0x100)); + CHECK(CALL("nfp.AttachActivateEvent", activate, U(handles)) == 0, "nfp AttachActivateEvent"); + CHECK(CALL("nfp.AttachDeactivateEvent", deactivate, U(handles)) == 0, "nfp AttachDeactivateEvent"); + CHECK(event_works(activate, 0), "the nfp activate event is set without an amiibo on the reader"); CHECK((uint32_t)CALL("nfp.StartDetection", U(handles)) == 0, "nfp StartDetection"); CHECK((uint32_t)CALL("nfp.StopDetection", U(handles)) == 0, "nfp StopDetection"); CHECK(CALL("nfp.Finalize", 0) == 0 && (uint32_t)CALL("nfp.GetState", 0) == 0, "nfp finalize"); @@ -382,8 +394,8 @@ static void probe_applet(void) { CALL("err.InitializeContextWriterApi", 0); CALL("pctl.Initialize", 0); CALL("diag.InitializeApplicationAbortObserver", 0); - printf("applet/prepo/nfp/err: launch parameter none, volume balance, play reports local, no NFC device, " - "availability event (bound through the SDK's CreateSystemEvent) %s\n", nfp_event ? "ok" : "FAILED"); + printf("applet/prepo/nfp/err: launch parameter none, volume balance, play reports local, an NFC reader without " + "an amiibo, availability event (bound through the SDK's CreateSystemEvent) %s\n", nfp_event ? "ok" : "FAILED"); } static void probe_account(void) { From 9cb099a8fa4a7e1671854d358cf42f4f68bcc8b3 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sun, 1 Nov 2026 12:47:59 +0300 Subject: [PATCH 19/19] Fit the Amiibo tab in the menu and stop it writing a folder on its own The panes now leave the bottom row free (opt_bottom), as the option tabs do, so Continue and Quit stay visible; the hold time label sits above its slider instead of being cut off beside it; the Tap and Lift buttons take the frame height, so their text is not clipped. A missing amiibo folder lists nothing and says so: the tab no longer swaps in the game folder and saves it to totk.ini just by being opened. Co-Authored-By: Claude Opus 5.5 --- runtime/ui/amiibo_page.cpp | 30 +++++++++++++++--------------- runtime/ui/option_rows.cpp | 1 + runtime/ui/option_rows.h | 2 ++ 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/runtime/ui/amiibo_page.cpp b/runtime/ui/amiibo_page.cpp index da52b233..f5ea39ad 100644 --- a/runtime/ui/amiibo_page.cpp +++ b/runtime/ui/amiibo_page.cpp @@ -1,6 +1,7 @@ // Amiibo / NFC menu page (Dear ImGui): browser and scan controls. #include #include +#include #include #include #include @@ -11,6 +12,7 @@ #include "imgui.h" #include "ui/amiibo_page.h" +#include "ui/option_rows.h" extern "C" { #include "amiibo.h" @@ -70,18 +72,13 @@ static void refresh_dir(void) { std::error_code ec; fs::path dir_path(g_current_dir); - // Fall back to "." if directory does not exist or is not a directory - if (!fs::exists(dir_path, ec) || !fs::is_directory(dir_path, ec)) { - if (g_current_dir != ".") { - set_current_dir("."); - dir_path = fs::path(g_current_dir); - } - } - + // A missing folder lists nothing and says so; it is not replaced by another one, and opening the tab writes no + // setting (the folder is saved only when the player sets one). if (!fs::exists(dir_path, ec) || !fs::is_directory(dir_path, ec)) { set_status(UI_MENU_AMIIBO_NO_DIR, g_current_dir); return; } + if (g_status_id == UI_MENU_AMIIBO_NO_DIR) set_status(UI_MENU_AMIIBO_READY); // Add parent navigation if not at root if (dir_path.has_parent_path() && dir_path != dir_path.parent_path()) { @@ -116,6 +113,7 @@ static void refresh_dir(void) { } void tab_amiibo(float scale) { + (void)scale; // the rows take ImGui's own sizes, already scaled with the font static bool s_inited = false; if (!s_inited) { const char *cfg_dir = cfg_get("TOTK_AMIIBO_DIR"); @@ -130,13 +128,13 @@ void tab_amiibo(float scale) { } // Two panes: Left (Directory Browser & Tag List), Right (Amiibo Tag Details & Controls) - const float content_h = ImGui::GetContentRegionAvail().y - 20.0f; + const float content_h = ImGui::GetContentRegionAvail().y - opt_bottom(); // Continue and Quit stay visible const float left_w = ImGui::GetContentRegionAvail().x * 0.58f; const float right_w = ImGui::GetContentRegionAvail().x - left_w - ImGui::GetStyle().ItemSpacing.x; // ---- Left Pane: Explorer & List ---- ImGui::BeginChild("##amiibo_explorer", ImVec2(left_w, content_h), true); - ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), menu_text(UI_MENU_AMIIBO_DIR)); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), "%s", menu_text(UI_MENU_AMIIBO_DIR)); ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); if (ImGui::InputText("##amiibo_dir_input", g_dir_input, sizeof(g_dir_input), ImGuiInputTextFlags_EnterReturnsTrue)) { @@ -197,7 +195,7 @@ void tab_amiibo(float scale) { // ---- Right Pane: Controls & Status ---- ImGui::BeginChild("##amiibo_controls", ImVec2(right_w, content_h), true); - ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), menu_text(UI_MENU_AMIIBO_READER)); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), "%s", menu_text(UI_MENU_AMIIBO_READER)); ImGui::Separator(); AmiiboDeviceState state = amiibo_get_device_state(); @@ -221,17 +219,17 @@ void tab_amiibo(float scale) { if (g_selected_entry >= 0 && g_selected_entry < (int)g_entries.size() && !g_entries[g_selected_entry].is_dir) { ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.4f, 1.0f), "%s", g_entries[g_selected_entry].name.c_str()); - if (ImGui::Button(menu_text(UI_MENU_AMIIBO_TAP), ImVec2(ImGui::GetContentRegionAvail().x, 32 * scale))) + if (ImGui::Button(menu_text(UI_MENU_AMIIBO_TAP), ImVec2(ImGui::GetContentRegionAvail().x, 0))) tap(g_current_dir, g_entries[g_selected_entry].name); } else { ImGui::TextDisabled("%s", menu_text(UI_MENU_AMIIBO_NO_FILE)); ImGui::BeginDisabled(); - ImGui::Button(menu_text(UI_MENU_AMIIBO_TAP), ImVec2(ImGui::GetContentRegionAvail().x, 32 * scale)); + ImGui::Button(menu_text(UI_MENU_AMIIBO_TAP), ImVec2(ImGui::GetContentRegionAvail().x, 0)); ImGui::EndDisabled(); } ImGui::Spacing(); - if (ImGui::Button(menu_text(UI_MENU_AMIIBO_REMOVE), ImVec2(ImGui::GetContentRegionAvail().x, 28 * scale))) { + if (ImGui::Button(menu_text(UI_MENU_AMIIBO_REMOVE), ImVec2(ImGui::GetContentRegionAvail().x, 0))) { amiibo_remove_tag(); set_status(UI_MENU_AMIIBO_REMOVED); } @@ -244,7 +242,9 @@ void tab_amiibo(float scale) { } if (auto_remove) { float delay = amiibo_get_auto_remove_delay_s(); - if (ImGui::SliderFloat(menu_text(UI_MENU_AMIIBO_HOLD), &delay, 1.0f, 6.0f, menu_text(UI_MENU_AMIIBO_SECONDS))) { + ImGui::TextUnformatted(menu_text(UI_MENU_AMIIBO_HOLD)); // above the slider: beside it the text is cut off + ImGui::SetNextItemWidth(-FLT_MIN); + if (ImGui::SliderFloat("##amiibo_hold", &delay, 1.0f, 6.0f, menu_text(UI_MENU_AMIIBO_SECONDS))) { amiibo_set_auto_remove_delay_s(delay); } } diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp index bf6a6241..59a66917 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -56,6 +56,7 @@ void opt_focus_first(void) { g_focus_req = true; } void opt_focus_key(const char *key) { snprintf(g_focus_key, sizeof g_focus_key, "%s", key); } void opt_reserve_bottom(float h) { g_bottom = h; } +float opt_bottom(void) { return g_bottom; } void opt_disable_next(UiTextId note) { g_disable_next = true; diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 07f32ddc..1178f7bf 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -19,6 +19,8 @@ void opt_begin(const char *id, float scale); void opt_end(void); // The height the next pages leave free under their panes (the menu's bottom row). void opt_reserve_bottom(float h); +// The height opt_reserve_bottom keeps free, for a tab that lays out its own panes (ui/amiibo_page.cpp). +float opt_bottom(void); // The next page's first row takes the controller's cursor (opening the menu, switching tabs). void opt_focus_first(void); // The row of key (or button id) takes the cursor, scrolled into view, when it is next drawn.