Merge task/kbm: keyboard and mouse like a PC game on 1.4.3

Direct mouse camera (#558, default on 1.4.3), mouse in the game's menus (#605), keyboard and mouse prompts
(#585, prompts = pc, in place of #483), a shake key (G) for detaching fused parts. The gamepad path is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-04 09:26:51 +03:00
commit 06c5de23fc
35 files changed
+1699 -124

No files matched your search

+1
View File
@@ -103,3 +103,4 @@ folder's `licenses/` and in each component's own folder.
| `totk_xlate` (NativeAOT linux-x64 build of `tools/xlate/`, linked with the folder's clang, lld and sysroot) | built by `tools/build_xlate.py --llvm --sysroot` | MIT | `bin/totk_xlate` |
| AppImage type-2 runtime (static; includes libfuse and squashfuse), the AppImage's first part; appimagetool packs the folder and is not distributed | https://github.com/AppImage/type2-runtime | MIT; libfuse LGPL-2.1; squashfuse BSD-2-Clause | the AppImage header |
| MacNativeGames shader variant list | as in the installer release row above | MIT | `data/shader_list.tsv` |
| Weeping of the Empire menu cursor: eui's focus box read through ScreenMgr, BoxCursorMgr and the screens' node lists, AnimButton's hit test, the stale-hit-pane fallback to the parts panes, the three writes of moveBoxCursor, the structure offsets (1.0.0; the ScreenMgr instance placed in 1.4.3 by us) | https://github.com/daniel-madrid-07/weeping-of-the-empire @ `df0586cdc5702ca19bbebfa59697e0b6980f6237` (`engine/runtime/totk_menu_cursor.cpp`), Copyright (c) 2026 daniel-madrid-07 | MIT | `runtime/menu_cursor.c` |
+2 -1
View File
@@ -115,7 +115,8 @@ of them.
`SDL3.dll`, `libiconv-2.dll` and `libopus-0.dll` next to the exe.
For Xbox button prompts, run `make_romfs_patches.py` twice more, with `--prompts xbox` and `--prompts xbox-label`:
they write `build\<ver>\romfs-patches-xbox` and `romfs-patches-xbox-label` ([controls.md](controls.md), "Xbox
button prompts"), which `build_game.py` copies next to `totk.exe` like `romfs-patches`.
button prompts"), which `build_game.py` copies next to `totk.exe` like `romfs-patches`. `--prompts pc` writes
`romfs-patches-pc`, the keyboard and mouse prompts ([controls.md](controls.md), "PC button prompts").
6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`)
for the shared shader list:
+61 -4
View File
@@ -27,12 +27,13 @@ The log names the layout in effect (`input: gamepad layout ...`); the menu shows
| D-pad left, up, right, down | D-pad | 1 2 3 4 | quick-select |
| Plus | Start | Tab | menu, inventory |
| Minus | Back | M | map |
| Right stick shaken left and right | shake the right stick | G | detach a fused part from what Ultrahand holds |
Esc is unbound in the game; it opens the settings menu and releases the mouse cursor (see Mouse camera). Z and X duplicate ZL and ZR so menu pages turn with two neighbouring keys; the menu tabs (L, R) are Q and R. The mouse wheel is unbound. The bindings are the tables of `input_map` in `runtime/input_map.c`: the keys (platform-neutral key ids) and one gamepad table per layout (gamepad inputs by position); `runtime/input_win.c` translates Win32 virtual keys and SDL buttons.
## Xbox button prompts
`TOTK_PROMPTS` (`prompts`, the *Button prompts* row on the Controls tab, read at start) picks the controller whose buttons the game's prompts show: `nintendo` (default) keeps the game's own, `xbox` shows an Xbox controller's.
`TOTK_PROMPTS` (`prompts`, the *Button prompts* row on the Controls tab, read at start) picks the controller whose buttons the game's prompts show: `nintendo` (default) keeps the game's own, `xbox` shows an Xbox controller's, `pc` the keyboard and mouse (PC button prompts, below).
- L, R, ZL, ZR, Plus and Minus become LB, RB, LT, RT, Menu and View, and the d-pad prompts a cross with an arrow for each direction meant. The letters on the keys are cut out in the game's own text font.
- A, B, X and Y name the label of the button the pad layout presses, so each prompt names the button to press. `pad_layout = nintendo` plays an Xbox pad by position: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel), so the prompts swap A with B and X with Y. `xbox` and `auto` put Switch A on the button labelled A, and the letters stay.
@@ -56,6 +57,24 @@ The game reads its UI archive and fonts once at boot, so the prompts change at t
The Switch prompts stay, with a note under *Button prompts* and a `RomFS overlay: ...` line in the log, when the folder is missing (an install made by an older setup, or one where the setup could not prepare it and showed a warning; running the setup again on the install folder writes it), when it fails its check, with a game resolution of another shape than 16:9 (its own UI layout wins; 16:10 and 21:9), and when the `romfs_mods` folder replaces one of its files: `romfs-patches` then loads in its place, where two overlays replacing one file would stop the game. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version <ver> --prompts xbox` (and `--prompts xbox-label`) writes `build\<ver>\romfs-patches-xbox` (`-label`); it needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`.
## PC button prompts
`prompts = pc` (*PC* on the *Button prompts* row) shows the key or mouse button the default keyboard bindings press each Switch button with, whatever the pad layout. The game loads `romfs-patches-pc` in place of `romfs-patches`, written by `tools/make_romfs_patches.py --prompts pc` (`button_icons.py`, `pc_icons`), which the setup runs next to the Xbox ones:
| Switch | Prompt |
|---|---|
| A, B, X, Y | E, Shift, Space, left click |
| L, R, ZL, ZR | Q, R, right click, F |
| Plus, Minus | Tab, M |
| D-pad | 1 (left), 2 (up), 3 (right), 4 (down), as a cross or the keys of the directions meant |
| Left stick, its press | W A S D (or the keys of the directions meant), Ctrl |
| Right stick, its press | the mouse, with an arrow for each direction meant, C |
- The glyphs keep the width of the game's own, so the right-aligned guides do not run into their text. A key is a rounded square with its label cut out in the game's own text fonts; a mouse button is a mouse with that button filled and the others hollow.
- The button guide in play draws every button from images of the Common archive (`Nt_KeyTexA/B/X/Y/L/ZL_00`, `Nt_KeyTexLSt_00` and `_01`, the stick tilted and pressed): all of them are painted with the same icons. The letters of the action prompt's diamond are one character of the Normal font each: E, an arrow for Shift, a bar for Space, L and R for the mouse buttons.
- Like the Xbox prompts they follow the defaults and not the bindings. `--binds <totk.ini>` draws the first key of each `bind_` line of that file instead, for a folder made by hand.
- At a game resolution of another shape than 16:9 the game loads `romfs-patches-pc-<w>x<h>` in place of `romfs-patches-<w>x<h>` when it is there: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts pc --aspect <w>x<h> --out <install>\romfs-patches-pc-<w>x<h>`. The setup does not write those, so without one the Switch prompts stay (*off at a game resolution not 16:9*).
## Window keys
| Key | Gamepad | Action |
@@ -68,9 +87,9 @@ The Minus+Plus combo never reaches the game. In the menu the arrow keys, the D-p
## Remapping
The *Controls* tab of the settings menu lists, under the button layout, every Switch button and the eight stick directions the keys drive (movement and camera), each with two key cells and a controller cell. Select a cell, press A or Enter, then press the new key, mouse button or controller button; Esc or five seconds without a press cancel, and a controller button cancels a key cell. Delete, Backspace or X clears the selected cell. A key another action has moves to the new one (the description names the action it left); a controller button swaps with the one it replaces. A remapped controller button is physical: from then on the face buttons (A B X Y) stay where they are in both layouts, until the buttons are put back as the layout in use has them or *Reset all buttons* is chosen. F1, F8, F10, F11 and Esc cannot be bound (the menu, the flight recorder and the window keep them). Punctuation keys are named by their place on a US keyboard; the menu shows the character the keyboard layout in use puts there.
The *Controls* tab of the settings menu lists, under the button layout, every Switch button, the eight stick directions the keys drive (movement and camera) and the shake key, each with two key cells and a controller cell. Select a cell, press A or Enter, then press the new key, mouse button or controller button; Esc or five seconds without a press cancel, and a controller button cancels a key cell. Delete, Backspace or X clears the selected cell. A key another action has moves to the new one (the description names the action it left); a controller button swaps with the one it replaces. A remapped controller button is physical: from then on the face buttons (A B X Y) stay where they are in both layouts, until the buttons are put back as the layout in use has them or *Reset all buttons* is chosen. F1, F8, F10, F11 and Esc cannot be bound (the menu, the flight recorder and the window keep them). Punctuation keys are named by their place on a US keyboard; the menu shows the character the keyboard layout in use puts there.
The tab writes `totk.ini` lines, one per Switch button or stick direction: `bind_<button> = <entry>, <entry>, ...`. The button is `A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK`, or a stick direction `LSTICK_LEFT LSTICK_UP LSTICK_RIGHT LSTICK_DOWN` (movement, W A S D by default) and `RSTICK_...` (camera, the arrow keys). An entry is `pad:<name>` or `key:<name>`:
The tab writes `totk.ini` lines, one per Switch button or stick direction: `bind_<button> = <entry>, <entry>, ...`. The button is `A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK`, or a stick direction `LSTICK_LEFT LSTICK_UP LSTICK_RIGHT LSTICK_DOWN` (movement, W A S D by default) and `RSTICK_...` (camera, the arrow keys), or `SHAKE` (keys only, G by default). An entry is `pad:<name>` or `key:<name>`:
- pad names: `south east west north l r zl zr start back lstick rstick dpad_left dpad_up dpad_right dpad_down lpaddle1 rpaddle1 lpaddle2 rpaddle2` (`zl`, `zr` are the triggers; the paddles are the back buttons of an Xbox Elite, DualSense Edge or Steam Controller, upper pair 1, lower pair 2, and no Switch button has them by default)
- key names: `a` to `z`, `0` to `9`, `f2` to `f7`, `f9`, `f12`, `num0` to `num9`, `space tab enter backspace lshift rshift lctrl rctrl lalt capslock insert delete home end pageup pagedown up down left right`, `num_add num_sub num_mul num_div num_decimal`, `minus equals lbracket rbracket semicolon apostrophe comma period slash backslash grave`, `mouse_l mouse_r mouse_m mouse_x1 mouse_x2`
@@ -90,7 +109,33 @@ bind_Y = pad:north, key:mouse_l
## Mouse camera
Mouse motion (raw input) becomes right-stick deflection. Each presented frame takes the counts moved since the last frame, divides by the frame time and sets the deflection to `counts per second * TOTK_MOUSE_SENS / 3000` of full, held for that frame, so the turn rate does not depend on the frame rate. This is not mouselook: the game's stick curve and dead zone still apply, so very slow movements do nothing and a fast flick saturates. The mouse deflection competes with the gamepad and arrow keys by the larger-deflection rule.
`mouse_mode = direct` (the default) turns the camera by the raw mouse motion on game 1.4.3, through hooks in the game's camera code (`runtime/mouse_direct.c`, the `mouse_direct` sites of `recomp/patches-v143.txt`). None of them changes a step of the gamepad alone. The free-orbit camera receives raw-count
angular increments at its final spherical-angle output: 0.08 degrees per count on both axes at sensitivity 1, with
no time multiplier, curve or carry into later frames. The controller's persistent pitch/yaw move with the output.
Mouse input is removed from its stick path first, so the camera's later vertical signed-square curve and velocity
filters cannot process it a second time. Other camera modes receive input after the radial dead zone, unit-circle
clamp and stick response exponent; Ultrahand has a separate hook after its manipulation input's power curves.
The game's camera inversion and gamepad response remain in effect. `mouse_sens` scales raw counts; its scale
differs from the stick-emulation mode. Start at 1.
The Controls tab switches between *Direct* and *Stick emulation* (`mouse_mode = stick`).
The orbit camera keeps its desired pitch at the final angular output, including stationary frames, so a later game
filter cannot recenter it. The persistent filter state accounts for the camera's current vertical offset instead of
accumulating corrections. A gamepad vertical input or the game's lock-on/override releases that mouse target.
While L is held, mouse counts move the ability wheel's virtual cursor, which stays where it was when the mouse stops.
The horizontal quick lists (D-pad up/left/right: materials, shields and weapons) use separate 32 ms right-stick steps,
with at least 32 ms of neutral between them. At sensitivity 1, 32 horizontal counts request a step; a large flick
cannot queue continued scrolling after the mouse stops. Vertical movement is ignored in these lists. Switching or
releasing a selector resets its cursor/step state without sending the last movement to the camera. Selector input is
not consumed by the direct camera or Ultrahand hooks.
The mouse never stands in for a stick shake: to detach a fused part, press G (`bind_SHAKE`). A press swings the right
stick left and right for 0.8 s, holding the key keeps it swinging. The arrow keys or the gamepad's right stick shaken by
hand work too. A mouse gesture for it would also fire while a held object is turned back and forth.
A step of the gamepad alone, with no mouse motion and no pitch the mouse holds, reaches the camera exactly as without
the hooks.
The mapping below is still used when the camera-input hook is unavailable or the game disables camera input.
Games 1.1.0 and 1.2.1 have no hooks and keep stick emulation whatever `mouse_mode` says.
In stick-emulation mode, mouse motion (raw input) becomes right-stick deflection. Each presented frame takes the counts moved since the last frame, divides by the frame time and sets the deflection to `counts per second * TOTK_MOUSE_SENS / 3000` of full, held for that frame, so the turn rate does not depend on the frame rate. This is not mouselook: the game's stick curve and dead zone still apply, so very slow movements do nothing and a fast flick saturates. The mouse deflection competes with the gamepad and arrow keys by the larger-deflection rule.
`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.
@@ -98,6 +143,12 @@ Mouse motion (raw input) becomes right-stick deflection. Each presented frame ta
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`.
## Mouse in the game's menus
On game 1.4.3, while one of the game's menus has its focus box (the frame the d-pad moves: the title, the save list, the inventory and its System tab, Options, shops, dialogue choices), the cursor is released from the mouse camera and shown in the middle of the window. The item under the pointer takes the focus as if the d-pad had moved there, with the game's highlight, sound and description; a left click is A on it, a right click is B. The keys and the pad keep working, and the focus moves only when the pointer moves. This happens only while the keyboard and mouse are the device used last: after a gamepad button press or a stick pushed past half way the menus are as on the console, with no pointer, until the mouse moves or a key is pressed (`input_kbm_last` in `runtime/input.c`). The ability wheel, the d-pad strips, Autobuild, the Purah Pad's camera and the map stay gameplay: the mouse keeps the camera there. When the menu closes the cursor is captured again.
`runtime/menu_cursor.c` reads eui's screens at each pad read and moves the focus with the writes `eui::BoxCursorMgr::moveBoxCursor` makes, so no game code is called. `menu_cursor = 0` (`TOTK_MENU_CURSOR=0`, live; the *Mouse in the game's menus* row of the Controls tab) turns it off; `TOTK_MENU_CURSOR_LOG=1` logs every screen it reads (by default the first six), with the layout size, the node count and the hit panes it uses.
## Nintendo Switch 2 controllers
Windows does not present the Switch 2 Pro Controller as a gamepad SDL can open (the log says `input: no gamepad`), so it needs a bridge program that wakes it and creates a virtual gamepad. The DS4Windows fork by hbashton ([github.com/hbashton/DS4Windows](https://github.com/hbashton/DS4Windows), tested with release VIIPERRC4.5.1, a pre-release) with the output set to an emulated DualSense gives buttons, rumble, gyro and accelerometer, and reads the sticks through the controller's calibration (they rest at 0 to 2%). The game reads its virtual DualSense directly; the log then shows `input: gamepad "DualSense Wireless Controller" (rumble, gyro and accelerometer, ...)` and `input: motion sensors on`. Its release notes also list Joy-Con 2 support, which is untested here.
@@ -111,14 +162,20 @@ Bridges that output a ViGEm DualShock 4 (ProCon2Windows, connectyourpro as teste
```
<frame> <button> [hold_frames] # A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK; hold defaults to 4
<frame> LSTICK|RSTICK <x> <y> [hold_frames] # -32767..32767, up is +y
<frame> MOUSE <dx> <dy> # direct-mode raw counts, once; down is +dy
@<ms> <button> [hold_ms] # timed on the world clock
@<ms> LSTICK|RSTICK <x> <y> [hold_ms]
@<ms> MOUSE <dx> <dy>
```
`<frame>` counts 60 Hz ticks of game time since the first frame (presented frames at 60 fps), so the title menus get the presses at the same game time at any frame limit. `@<ms>` counts milliseconds of the world clock: game time stepped since the end of the first save load (the player leaves the title screen's origin), so a timed event lands at the same game time at any frame rate and load length. A later load, such as fast travel, still shifts what follows. In a script with timed lines the untimed ones stop when the world clock starts, as the load ends at another tick in each run. Each event logs once (`input: script frame N tick T: A`). `tools/input/load_save.txt` loads the first save from the title screen.
`TOTK_INPUT_RECORD=<file>` (`input_record` in `totk.ini`, or Input recording in the menu) writes the merged input in the same format, one line per button press and per stick segment: events before the world clock starts by tick, the rest timed; a button or stick held when the world clock starts is cut there and goes on as a timed event. The file replays as a script, which makes it the repro to attach to a bug report.
In direct mouse mode the recording also writes one `MOUSE` event per consumed raw displacement. These are one-shot
displacements rather than held stick segments. They replay without cursor capture, including with `input = none`;
the game must be accepting camera input when the event reaches its camera update.
`TOTK_TEST_PAD=<lx>,<ly>,<rx>,<ry>` attaches an SDL virtual gamepad at start whose sticks rest at these raw SDL axis values (-32768 to 32767, down is +y), so a drifting or held stick can be tested without a controller: the values go through the gamepad mapping and `TOTK_STICK_DEADZONE` like a real pad's, and `TOTK_INPUT_RECORD` shows what reached the game.
## RenderDoc capture (blocked)
+3 -2
View File
@@ -67,9 +67,10 @@ loads the saves 1.4.3 wrote.
`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 three times: `romfs-patches`, and `romfs-patches-xbox` and `romfs-patches-xbox-label`
The patches are written four times: `romfs-patches`, `romfs-patches-xbox` and `romfs-patches-xbox-label`
(`--prompts`: Xbox button prompts for `prompts = xbox`, the first for `pad_layout = nintendo`, the second for `xbox`
and `auto`). The two Xbox folders are optional: when one cannot be made, the setup warns and finishes.
and `auto`), and `romfs-patches-pc` (keyboard and mouse prompts for `prompts = pc`). The three prompt folders are
optional: when one cannot be made, the setup warns and finishes.
When the graphics driver crashes while building the shaders, `prepare_shaders.py` runs that part again without the
variants it was building ([building.md](building.md), step 6), and the setup finishes with a warning that names how
many were left out.
+5 -3
View File
@@ -7,7 +7,8 @@ recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and tools/prepar
with the bundled clang (hostcheck.c).
Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ (Chinese and Korean text), totk.exe
and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/, romfs-patches-xbox-label/, totk_xlate.exe, the
and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/,
romfs-patches-xbox-label/, romfs-patches-pc/, totk_xlate.exe, the
shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json.
Temp folder (<temp>/<dest name>-<hash>): check/ (ExeFS of both inputs, the host check), unpacked/ (the NSP of an NSZ
or XCZ input until the extraction is done), gen/ (C), build/ (objects), logs/. The cleanup keeps gen/, build/ and
@@ -1067,9 +1068,10 @@ class Prepare(Step):
# romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label for xbox and auto (runtime/input_map.c
# input_prompts_folder). Both are written on every install, so the menu choices work without another run of
# the setup. Optional: when one fails, the game keeps the Switch prompts with that layout and the menu says the
# files are missing, so the setup warns once and goes on.
# files are missing, so the setup warns once and goes on. romfs-patches-pc likewise, with keyboard and mouse
# prompts for prompts = pc (16:9 only: another shape takes make_romfs_patches.py --prompts pc --aspect).
failed = None
for style in ('xbox', 'xbox-label'):
for style in ('xbox', 'xbox-label', 'pc'):
out = dest / f'romfs-patches-{style}'
remove(out)
code, log = run_tool(ctx, f'prepare-{style}', layout.tools / 'make_romfs_patches.py',
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.",
"warn.cheats_skipped": "The cheats of the mods folder that change the game's code could not be built; the game installs without them. Details: {log}",
"warn.exefs_skipped": "The mods' ExeFS patches (.ips, .pchtxt) could not be built; the game installs without them. Details: {log}",
"warn.xbox_prompts_failed": "The Xbox button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
"warn.xbox_prompts_failed": "The Xbox or PC button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
"warn.shaders_skipped": "The graphics driver crashed while building some shaders, so {count} were left out of the preparation. The game builds them when it first needs them, and the driver may crash there too; a driver update may fix it. 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.",
"warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.",
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.cheats_skipped": "Não foi possível compilar os cheats da pasta de mods que alteram o código do jogo; o jogo é instalado sem eles. Detalhes: {log}",
"warn.exefs_skipped": "Não foi possível compilar os patches ExeFS dos mods (.ips, .pchtxt); o jogo é instalado sem eles. Detalhes: {log}",
"warn.npdm_differs": "O main.npdm difere do dump de referência da versão {version}; só os módulos de código são usados.",
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox ou do PC (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
"warn.shaders_skipped": "O driver gráfico travou ao compilar alguns shaders, então {count} ficaram fora da preparação. O jogo os compila quando precisar deles pela primeira vez, e o driver pode travar ali também; uma atualização do driver pode resolver. Detalhes: {log}",
"warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.",
"warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.",
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.",
"warn.cheats_skipped": "Не удалось собрать читы из папки модов, меняющие код игры; игра установится без них. Подробности: {log}",
"warn.exefs_skipped": "Не удалось собрать ExeFS-патчи модов (.ips, .pchtxt); игра установится без них. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox или PC (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
"warn.shaders_skipped": "Графический драйвер аварийно завершился при сборке части шейдеров, поэтому {count} из них пропущены при подготовке. Игра соберёт их, когда они впервые понадобятся, и драйвер может упасть и там; обновление драйвера может это исправить. Подробности: {log}",
"warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.",
"warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.",
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.cheats_skipped": "无法构建 mods 文件夹中修改游戏代码的金手指;游戏将不含它们进行安装。详情:{log}",
"warn.exefs_skipped": "无法构建模组的 ExeFS 补丁(.ips、.pchtxt);游戏将不含它们进行安装。详情:{log}",
"warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。",
"warn.xbox_prompts_failed": "无法准备 Xbox 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.xbox_prompts_failed": "无法准备 Xbox 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.shaders_skipped": "显卡驱动在编译部分着色器时崩溃,因此有 {count} 个着色器未被预先准备。游戏会在首次需要时编译它们,驱动在那时也可能崩溃;更新驱动可能会解决。详情:{log}",
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
+10
View File
@@ -103,6 +103,16 @@ set fov TOTK_FOV_PATCH 0
site fov main 628c3c bd413e60 f81f0fea @page:x10 bd413e60 bd403d48 1e280800 f84107ea # ldr s0, [x19, #0x13c] (camera update)
site fov main b4342c bd4066c0 f81f0fea @page:x10 bd4066c0 bd403d48 1e280800 f84107ea # ldr s0, [x22, #0x64] (camera setup)
# The camera input update, after its stick dead zone, unit-radius clamp and StickExponent. The host callback
# performs the displaced store and adds raw mouse counts to s9/s10 (runtime/mouse_direct.c camera_input).
# Its address is page +0xfd0; the page is main+0x3adf000 on this verified build.
set mouse_direct TOTK_MOUSE_DIRECT_PATCH 1
site mouse_direct main 874cb4 bd042289 94c9acc7
site mouse_direct main 874d7c 6d40a3e9 94c9ac91
site mouse_direct main 18e444 f9400408 94e546db
site mouse_direct main 18f108 bd4047ec 94e543a6
site mouse_direct main 1d59460 b9004be8 94761acc
# The game's zstd decoder (BSD zstd, statically linked into main) through the host's libzstd (runtime/ov_zstd.c):
# every call of ZSTD_decompressMultiFrame (main+0x3a1f0: dctx, dst, capacity, src, size, dict, dict size, ddict) and of
# its wrapper ZSTD_decompress_usingDDict (main+0x3a1e0, which tail-branches to it) goes to a host function on the patch
+7 -5
View File
@@ -34,6 +34,7 @@ static const char *const known[] = {
"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",
"BIND_SHAKE",
"BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
"BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA",
"COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT",
@@ -43,7 +44,7 @@ static const char *const known[] = {
"FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
"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", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
"MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
"MV_SURVEY",
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
@@ -83,13 +84,13 @@ static const struct { const char *key, *section; } sections[] = {
{"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
{"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "input"},
{"STICK_SENS", "input"},
{"MOUSE_SENS", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "input"},
{"MENU_CURSOR", "input"}, {"MOUSE_MODE", "input"}, {"MOUSE_SENS", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "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"},
{"BIND_RIGHT", "input"}, {"BIND_DOWN", "input"}, {"BIND_LSTICK_LEFT", "input"}, {"BIND_LSTICK_UP", "input"},
{"BIND_LSTICK_RIGHT", "input"}, {"BIND_LSTICK_DOWN", "input"}, {"BIND_RSTICK_LEFT", "input"},
{"BIND_RSTICK_UP", "input"}, {"BIND_RSTICK_RIGHT", "input"}, {"BIND_RSTICK_DOWN", "input"},
{"BIND_RSTICK_UP", "input"}, {"BIND_RSTICK_RIGHT", "input"}, {"BIND_RSTICK_DOWN", "input"}, {"BIND_SHAKE", "input"},
{"ASYNC_PREEMPT", "performance"}, {"REPLAY_ASYNC", "performance"}, {"FREE_CORES", "performance"},
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"},
{"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"},
@@ -144,10 +145,11 @@ static const CfgMeta metas[] = {
{"VOLUME", "100", "0..100", LIVE}, {"AUDIO_CHANNELS", "stereo", "auto|stereo|5.1", RESTART},
{"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},
{"PROMPTS", "nintendo", "nintendo|xbox", RESTART},
{"PROMPTS", "nintendo", "nintendo|xbox|pc", RESTART},
{"STICK_DEADZONE", "8", "0..50", LIVE}, {"STICK_SENS", "1", "0.1..3", RESTART},
{"LSTICK_DEADZONE", "", "0..50", LIVE}, {"RSTICK_DEADZONE", "", "0..50", LIVE},
{"MOUSE_SENS", "1", "0..10", LIVE},
{"MOUSE_MODE", "direct", "stick|direct", LIVE},
{"MOUSE_SENS", "1", "0..10", LIVE}, {"MENU_CURSOR", "1", "0|1", LIVE},
{"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE},
{"AMIIBO_DIR", "", NULL, LIVE},
+9
View File
@@ -234,6 +234,10 @@ int probe_cfg(void) {
CHECK(input_map_buttons(dn) == (1ull << B_ZR | 1ull << B_PLUS | 1ull << B_MINUS | 1ull << B_STICK_L | 1ull << B_RIGHT),
"keys: X ZR, Tab Plus, M Minus, Left Ctrl stick click, 3 D-pad right");
memset(dn, 0, sizeof dn);
dn[KEY_G] = 1;
CHECK(input_map_buttons(dn) == 0 && input_map_held(dn, B_SHAKE) && !input_map_held(dn, B_A),
"keys: G shakes and presses no button");
memset(dn, 0, sizeof dn);
dn[KEY_W] = 1;
input_map_stick(dn, 0, st);
CHECK(st[0] == 0 && st[1] == 32767, "keys: W is left stick up");
@@ -301,6 +305,11 @@ int probe_cfg(void) {
CHECK(input_prompts_pick(NULL, "auto") == PROMPTS_NINTENDO && input_prompts_pick("", "xbox") == PROMPTS_NINTENDO &&
input_prompts_pick("Xbox", "nintendo") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox") == PROMPTS_NINTENDO,
"prompts: the game's own unless set to Xbox");
CHECK(input_prompts_pick("PC", "nintendo") == PROMPTS_PC && input_prompts_pick("pc", "xbox_prompts") == PROMPTS_PC &&
EQ(input_prompts_folder(PROMPTS_PC, "nintendo"), "romfs-patches-pc") &&
EQ(input_prompts_folder(PROMPTS_PC, "xbox"), "romfs-patches-pc") &&
EQ(input_prompts_folder(PROMPTS_PC, NULL), "romfs-patches-pc"),
"prompts: pc shows the keyboard and mouse whatever the pad layout");
CHECK(input_prompts_pick(NULL, "xbox_prompts") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox_prompts") == PROMPTS_NINTENDO,
"prompts: 0.1.9's pad_layout = xbox_prompts means Xbox while prompts is unset");
CHECK(!input_prompts_folder(PROMPTS_NINTENDO, "nintendo") && !input_prompts_folder(PROMPTS_NINTENDO, "xbox"),
+2 -1
View File
@@ -41,7 +41,8 @@ size_t romfs_overlay_count(void);
int romfs_patches_loaded(void); // a romfs-patches manifest gave at least one file
// The button prompts (input_prompts_folder): the folder loaded at start, NULL for the game's own prompts; whether a
// folder had a manifest at start; and why the folder the settings asked for at start was not loaded (ROMFS_PROMPTS_OK
// for any other folder: it was not asked for).
// for any other folder: it was not asked for). romfs-patches-pc goes by that name also where romfs-patches-pc-<w>x<h>
// stands in for it (romfs.c overlay_init).
enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROMPTS_SHAPE, ROMFS_PROMPTS_MODS,
ROMFS_PROMPTS_PATCHES };
const char *romfs_prompts(void);
+1
View File
@@ -23,6 +23,7 @@ uint64_t gfx_vsync_ticks(void); // ticks since start
uint64_t gfx_vsync_time_ns(uint64_t tick); // kern_now_ns() time of a tick (pacing)
double gfx_window_refresh_hz(void); // refresh rate of the window's monitor; 0 unknown
int gfx_window_focused(void);
int gfx_picture_rect(float out[4]); // where the last present put the picture, fractions of the swapchain (x, y, w, h); 0 before one
// ---- shader service client (gfx_shader.c)
enum { GFX_STAGE_VS, GFX_STAGE_TCS, GFX_STAGE_TES, GFX_STAGE_GS, GFX_STAGE_FS, GFX_STAGE_CS };
+13
View File
@@ -543,6 +543,15 @@ static void save_capture(const char *path) {
// TOTK_ASPECT=stretch, else (fit, the default) the largest one of the picture's own aspect ratio, centred (a 16:9 picture
// on the Steam Deck's 1280x800 screen gets bars of 40 rows above and below; a 16:9 picture in a 21:9 window, bars at the
// sides).
// Where the last present put the picture, as fractions of the swapchain (x, y, w, h): menu_cursor.c's pointer
static float g_pic[4];
static volatile int32_t g_pic_ok;
int gfx_picture_rect(float out[4]) {
if (!__atomic_load_n(&g_pic_ok, __ATOMIC_ACQUIRE)) return 0;
memcpy(out, g_pic, sizeof g_pic);
return 1;
}
void gfx_fit_rect(int cw, int ch, int dw, int dh, int out[4]) {
out[0] = out[1] = 0, out[2] = dw, out[3] = dh;
if (cw <= 0 || ch <= 0 || !strcmp(cfg_value("TOTK_ASPECT"), "stretch")) return;
@@ -616,6 +625,10 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
const int rect[4] = {cx, cy, cw, ch};
int to[4]; // where the picture goes in the swapchain image: {x, y, w, h}
gfx_fit_rect(cw, ch, (int)g_sc_ext.width, (int)g_sc_ext.height, to);
if (g_sc_ext.width && g_sc_ext.height) {
for (int i = 0; i < 4; i++) g_pic[i] = (float)to[i] / (float)(i & 1 ? g_sc_ext.height : g_sc_ext.width);
__atomic_store_n(&g_pic_ok, 1, __ATOMIC_RELEASE);
}
if (to[2] != (int)g_sc_ext.width || to[3] != (int)g_sc_ext.height) { // black bars beside or above and below it
VkClearColorValue black = {.float32 = {0, 0, 0, 1}};
VkImageSubresourceRange all = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
+107 -12
View File
@@ -26,6 +26,13 @@ enum { STICK_MAX = 32767, STICK_DIR = 16384, TRIGGER_ON = 16384, RESCAN_MS = 100
static PlatMutex lock = PLAT_MUTEX_INIT;
static int state; // 0 not started, 1 running, -1 disabled or SDL failed
static volatile int32_t g_block, g_menu; // text entry / host menu: 0 off, 1 open, 2 waiting for release
// The device the player used last (input_kbm_last): 1 keyboard and mouse, 0 the gamepad. A pad counts once a button is
// down or a stick is past half way (a drifting stick never switches), the mouse once it moved MOUSE_USED raw counts
// within one poll (a slow deliberate move does; a desk bump does not), the keyboard with any key or mouse button.
enum { PAD_USED = 16384, MOUSE_USED = 6 };
static volatile int32_t g_kbm_last = 1;
int input_kbm_last(void) { return __atomic_load_n(&g_kbm_last, __ATOMIC_RELAXED); }
static SDL_Gamepad *pad;
static uint64_t next_scan;
static int pad_rumble; // the open gamepad has rumble motors
@@ -66,6 +73,7 @@ static const struct { const char *name; int bit; } script_buttons[] = {
static ScriptEv *script_ev;
static int script_n, script_state; // 0 not loaded, 1 loaded
static int script_mixed; // the script has timed lines: its untimed ones end where the world clock starts
static int32_t script_mouse[2]; // one-shot raw counts, consumed by the camera hook; under lock
static void script_load(void) {
script_state = 1;
@@ -88,10 +96,11 @@ static void script_load(void) {
ScriptEv e = {.at = (uint64_t)(at * unit + 0.5), .hold = timed ? 66667 : 4, .bit = -1, .timed = timed};
long a, b;
double c;
if (!strcmp(name, "LSTICK") || !strcmp(name, "RSTICK")) {
if (!strcmp(name, "MOUSE") || !strcmp(name, "LSTICK") || !strcmp(name, "RSTICK")) {
int n = sscanf(line + off, "%ld %ld %lf", &a, &b, &c);
if (n < 2) { rt_log("input: script line %d: %s needs x y [hold]", ln, name); continue; }
e.stick = name[0] == 'L' ? 1 : 2; e.x = (int32_t)a; e.y = (int32_t)b;
e.stick = name[0] == 'M' ? 3 : name[0] == 'L' ? 1 : 2; e.x = (int32_t)a; e.y = (int32_t)b;
if (e.stick == 3) e.hold = 1; // a displacement, never a held speed
if (n >= 3 && c > 0) e.hold = (uint64_t)(c * unit + 0.5);
snprintf(e.text, sizeof e.text, "%s %d %d", name, e.x, e.y);
} else {
@@ -123,12 +132,17 @@ static void script_apply(uint64_t *b, int32_t sl[2], int32_t sr[2]) {
if (e->timed ? w < 0 : script_mixed && w >= 0) continue;
uint64_t now = e->timed ? (uint64_t)w : tick;
if (now < e->at || (now >= e->at + e->hold && (e->logged || !e->timed))) continue;
if (e->stick == 3 && e->logged) continue;
if (!e->logged) {
e->logged = 1;
if (e->timed) rt_log("input: script frame %llu at %.1f ms: %s", (unsigned long long)fr, w / 1000.0, e->text);
else rt_log("input: script frame %llu tick %llu: %s", (unsigned long long)fr, (unsigned long long)tick, e->text);
}
if (e->stick) { int32_t *s = e->stick == 1 ? sl : sr; s[0] = e->x; s[1] = e->y; }
if (e->stick == 3) {
int64_t x = (int64_t)script_mouse[0] + e->x, y = (int64_t)script_mouse[1] + e->y;
script_mouse[0] = (int32_t)(x < INT32_MIN ? INT32_MIN : x > INT32_MAX ? INT32_MAX : x);
script_mouse[1] = (int32_t)(y < INT32_MIN ? INT32_MIN : y > INT32_MAX ? INT32_MAX : y);
} else if (e->stick) { int32_t *s = e->stick == 1 ? sl : sr; s[0] = e->x; s[1] = e->y; }
else *b |= 1ull << e->bit;
}
}
@@ -223,6 +237,30 @@ static void rec_apply(uint64_t b, const int32_t sl[2], const int32_t sr[2]) {
if (wrote) fflush(rec);
}
void input_direct_mouse_sample(int enabled, int32_t *dx, int32_t *dy) {
plat_mutex_lock(&lock);
enabled = enabled && !g_block && !g_menu;
*dx = script_mouse[0]; *dy = script_mouse[1];
script_mouse[0] = script_mouse[1] = 0;
if (!enabled) { *dx = *dy = 0; }
else if (ikb_captured() && ikb_foreground() && input_cursor_allowed()) {
int32_t x, y;
ikb_mouse_take(&x, &y);
int64_t sx = (int64_t)*dx + x, sy = (int64_t)*dy + y;
*dx = (int32_t)(sx < INT32_MIN ? INT32_MIN : sx > INT32_MAX ? INT32_MAX : sx);
*dy = (int32_t)(sy < INT32_MIN ? INT32_MIN : sy > INT32_MAX ? INT32_MAX : sy);
}
if (enabled && (*dx || *dy) && rec_state == 1) {
char what[80];
snprintf(what, sizeof what, "MOUSE %d %d", *dx, *dy);
int64_t w = frame_step_world_us();
uint64_t tick = frame_step_ticks();
rec_line(tick, w, tick + 1, w, what);
fflush(rec);
}
plat_mutex_unlock(&lock);
}
static float mouse_sens = -1; // TOTK_MOUSE_SENS, 0 = mouse camera off; live (cfg_version)
static unsigned mouse_sens_seen;
@@ -282,15 +320,41 @@ static void walk_get(void) {
}
}
// The mouse camera as a right-stick sample, held for the whole presented frame. Under `lock`. The sample is divided by
// the camera speed factor the game runs with (camera_speed.c, cam_speed_applied), which multiplies every right-stick
// turn rate, so TOTK_MOUSE_SENS alone sets the mouse's speed; below 1 the sample stays within the stick's range, so the
// mouse's top speed drops with the factor.
static void mouse_camera(int32_t out[2]) {
static int mouse_selector;
int input_direct_mouse_selector_active(void) { return __atomic_load_n(&mouse_selector, __ATOMIC_RELAXED) != 0; }
// Selector 1 is a radial wheel, 2..4 are distinct horizontal quick lists; only a wheel retains a virtual cursor.
// Under `lock`.
static void mouse_camera(int32_t out[2], int selector) {
static uint64_t frame = ~0ull, t0;
static int32_t held[2];
static int was_selector;
static float cursor[2];
static InputMouseRow row;
uint64_t now = plat_now_ns();
int32_t dx, dy;
if (!input_direct_mouse_enabled() || !ikb_captured()) selector = 0;
__atomic_store_n(&mouse_selector, selector, __ATOMIC_RELAXED);
if (selector) {
if (was_selector != selector) cursor[0] = cursor[1] = 0, row = (InputMouseRow){0};
was_selector = selector;
ikb_mouse_take(&dx, &dy);
if (selector == 1) input_direct_mouse_radial(dx, dy, mouse_sens_get(), cursor, out);
else input_direct_mouse_row(dx, mouse_sens_get(), now, &row, out);
held[0] = held[1] = 0; frame = ~0ull;
return;
}
if (was_selector) {
was_selector = 0; cursor[0] = cursor[1] = 0; row = (InputMouseRow){0};
ikb_mouse_take(&dx, &dy); // release the wheel without sending its last movement to the camera
held[0] = held[1] = out[0] = out[1] = 0; frame = ~0ull;
return;
}
if (input_direct_mouse_active()) {
held[0] = held[1] = out[0] = out[1] = 0;
frame = ~0ull;
return; // the camera update takes the raw counts itself, once, outside the HID stick path
}
if (!ikb_captured()) {
ikb_mouse_take(&dx, &dy);
held[0] = held[1] = 0;
@@ -459,6 +523,24 @@ static void pick(int32_t *x, int32_t *y, int32_t kx, int32_t ky) {
if (b > a) { *x = kx; *y = ky; }
}
// The shake key (B_SHAKE): the game detaches a part fused to what Ultrahand holds when the right stick swings left and
// right a few times. A press swings it for SHAKE_NS, holding keeps it swinging; each side lasts SHAKE_SIDE_NS, two
// frames at the game's 30 fps, so every side is read even at 20 fps. Returns the stick x, 0 while not shaking.
// Under lock.
#define SHAKE_NS 800000000ull
#define SHAKE_SIDE_NS 66666667ull
static int32_t shake_stick(int held) {
static int was;
static uint64_t from, until;
uint64_t now = plat_now_ns();
if (held && !was && now >= until) from = now;
if (held && !was) until = now + SHAKE_NS;
if (held && until < now) until = now;
was = held;
if (now >= until && !held) return 0;
return (now - from) / SHAKE_SIDE_NS % 2 ? STICK_MAX : -STICK_MAX;
}
// Under lock, state 1: the open gamepad's inputs by position (pd[PAD_*] != 0 held); 0 without a connected gamepad.
static int pad_physical(uint8_t pd[PAD_COUNT]) {
if ((!pad || !SDL_GamepadConnected(pad)) && plat_now_ns() / 1000000u >= next_scan) { next_scan = plat_now_ns() / 1000000u + RESCAN_MS; scan_pads(); }
@@ -505,6 +587,8 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
if (state > 0) {
binds_refresh();
if (state == 1) pad_read(&b, sl, sr);
int pad_used = b || abs(sl[0]) > PAD_USED || abs(sl[1]) > PAD_USED || abs(sr[0]) > PAD_USED ||
abs(sr[1]) > PAD_USED, kbm_used = 0;
if (ikb_foreground()) {
uint8_t down[KEY_COUNT] = {0};
// Mouse buttons count only while the cursor is captured, and a button already held when the capture began
@@ -514,6 +598,7 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
int cap = ikb_captured();
for (int k = 1; k < KEY_COUNT; k++) {
down[k] = ikb_down(k);
kbm_used |= down[k];
if (k < KEY_MOUSE_L || k > KEY_MOUSE_X2) continue;
if (cap && !was_captured) mouse_ignore[k] = down[k];
if (!down[k]) mouse_ignore[k] = 0;
@@ -530,9 +615,20 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
input_map_stick(down, 1, k);
if (walk) k[0] = (int32_t)(k[0] * walk_scale), k[1] = (int32_t)(k[1] * walk_scale);
pick(&sr[0], &sr[1], k[0], k[1]);
mouse_camera(k);
int selector = b & (1ull << B_L) ? 1 : b & (1ull << B_UP) ? 2 :
b & (1ull << B_LEFT) ? 3 : b & (1ull << B_RIGHT) ? 4 : 0;
mouse_camera(k, selector);
pick(&sr[0], &sr[1], k[0], k[1]);
int32_t shake = shake_stick(input_map_held(down, B_SHAKE));
if (shake) sr[0] = shake, sr[1] = 0;
static uint32_t travel_seen;
uint32_t travel = ikb_mouse_travel();
if (travel - travel_seen >= MOUSE_USED) kbm_used = 1;
travel_seen = travel;
}
// A press or a full-way stick on the pad wins over keys held in the same poll: the player picked it up
if (pad_used) __atomic_store_n(&g_kbm_last, 0, __ATOMIC_RELAXED);
else if (kbm_used) __atomic_store_n(&g_kbm_last, 1, __ATOMIC_RELAXED);
}
script_apply(&b, sl, sr);
rec_apply(b, sl, sr);
@@ -554,8 +650,6 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
// Text entry (swkbd_*.c): while it is open the game reads no input, as behind the keyboard applet; after it closes
// the game reads none until every button and stick direction is released, so the press that closed it stays there.
// g_block: 0 off, 1 text entry open, 2 closed, waiting for the release. The cursor is released while it is open.
static volatile int32_t g_block;
static volatile int32_t g_menu; // the in-game menu, the same way (input_menu)
// When g_block and g_menu last went to 2 (plat_now_ns). The wait for the release ends after RELEASE_WAIT_NS even with
// something held: an input that never reads as released (a button another program holds down, a key whose release
// went to another window, a stick that rests outside its dead zone) would otherwise keep the game deaf until restart
@@ -565,7 +659,7 @@ static volatile uint64_t g_block_closed, g_menu_closed;
int input_cursor_allowed(void) {
const char *in = cfg_get("TOTK_INPUT");
return g_block != 1 && g_menu != 1 && mouse_sens_get() > 0 && !(in && !strcmp(in, "none"));
return g_block != 1 && g_menu != 1 && mouse_sens_get() > 0 && !(in && !strcmp(in, "none")) && !menu_cursor_pointer();
}
void input_block(int on) {
@@ -603,6 +697,7 @@ static int blocked(volatile int32_t *flag, volatile uint64_t *closed, const char
void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
poll_merged(buttons, lx, ly, rx, ry);
if (!g_block && !g_menu) menu_cursor_poll(buttons);
const int32_t axes[4] = {*lx, *ly, *rx, *ry};
int text = blocked(&g_block, &g_block_closed, "text entry", *buttons, axes),
menu = blocked(&g_menu, &g_menu_closed, "menu", *buttons, axes);
+21
View File
@@ -6,6 +6,27 @@
// Down=15) and the stick directions (StickLLeft..Down 16-19, StickRLeft..Down 20-23, derived from the sticks).
// Sticks are -32767..32767, up is +y. TOTK_INPUT=none reports no input. Callable from any thread.
void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
// 1 when keyboard and mouse are the device the player used last, 0 when the gamepad is: what is shown for pointing
// (menu_cursor.c shows the pointer in the game's menus only for the keyboard and mouse)
int input_kbm_last(void);
// Direct mouse input is consumed by the game's camera-input update, after its stick response. While that update
// accepts camera input, the HID right stick contains only the controller and keyboard. Selectors route mouse input
// separately: a persistent radial cursor for the ability wheel, discrete steps for horizontal quick lists.
int input_direct_mouse_active(void);
int input_direct_mouse_enabled(void);
// A radial selector uses a persistent virtual cursor while its opening button is held.
void input_direct_mouse_radial(int32_t dx, int32_t dy, float sensitivity, float cursor[2], int32_t out[2]);
// Horizontal quick selectors receive short, separated steps instead of a latched radial-cursor direction.
typedef struct { float distance; uint64_t pulse_until, neutral_until; int direction; } InputMouseRow;
void input_direct_mouse_row(int32_t dx, float sensitivity, uint64_t now, InputMouseRow *row, int32_t out[2]);
int input_direct_mouse_selector_active(void);
// Consume direct mouse counts, including one-shot MOUSE events from an input script. enabled=0 discards scripted
// counts while leaving the real mouse for menu input. Live counts require cursor capture and foreground focus.
void input_direct_mouse_sample(int enabled, int32_t *dx, int32_t *dy);
// menu_cursor.c: the pointer in the game's menus (1.4.3). poll: once per pad read, adds a click's A or B; pointer: a
// menu has the pointer, so the mouse camera's capture is released
void menu_cursor_poll(uint64_t *buttons);
int menu_cursor_pointer(void);
// The same for host UI (the text entry): never blocked. input_block(1) while a text entry is open: input_poll then
// reports nothing; input_block(0) when it closes: nothing until all buttons and stick directions are released.
void input_poll_ui(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
+13 -5
View File
@@ -20,7 +20,7 @@
{KEY_SPACE, B_X}, {KEY_LSHIFT, B_B}, {KEY_E, B_A}, {KEY_Q, B_L}, {KEY_R, B_R}, \
{KEY_LCTRL, B_STICK_L}, {KEY_C, B_STICK_R}, \
{KEY_1, B_LEFT}, {KEY_2, B_UP}, {KEY_3, B_RIGHT}, {KEY_4, B_DOWN}, \
{KEY_TAB, B_PLUS}, {KEY_M, B_MINUS}
{KEY_TAB, B_PLUS}, {KEY_M, B_MINUS}, {KEY_G, B_SHAKE}
// By position: south is Switch B, east A, west Y, north X (Nintendo layout); the Xbox layout swaps A with B and X with Y
// (south A, as the Xbox labels; cross A on a PlayStation pad). The triggers are ZL and ZR.
@@ -31,7 +31,7 @@
{PAD_ZR, B_ZR}
#define NINTENDO_PADS DEFAULT_PADS(B_B, B_A, B_Y, B_X)
#define XBOX_PADS DEFAULT_PADS(B_A, B_B, B_X, B_Y)
enum { DEFAULT_KEY_COUNT = 26, DEFAULT_PAD_COUNT = 16 };
enum { DEFAULT_KEY_COUNT = 27, DEFAULT_PAD_COUNT = 16 };
_Static_assert(sizeof (Binding[]){DEFAULT_KEYS} / sizeof (Binding) == DEFAULT_KEY_COUNT, "DEFAULT_KEY_COUNT");
static const InputMap defaults = {{DEFAULT_KEYS}, DEFAULT_KEY_COUNT, {{NINTENDO_PADS}, {XBOX_PADS}},
@@ -41,7 +41,7 @@ InputMap input_map = {{DEFAULT_KEYS}, DEFAULT_KEY_COUNT, {{NINTENDO_PADS}, {XBOX
static const char *const action_names[ACTION_COUNT] = {
"A", "B", "X", "Y", "LCLICK", "RCLICK", "L", "R", "ZL", "ZR", "PLUS", "MINUS", "LEFT", "UP", "RIGHT", "DOWN",
"LSTICK_LEFT", "LSTICK_UP", "LSTICK_RIGHT", "LSTICK_DOWN", "RSTICK_LEFT", "RSTICK_UP", "RSTICK_RIGHT", "RSTICK_DOWN"};
"LSTICK_LEFT", "LSTICK_UP", "LSTICK_RIGHT", "LSTICK_DOWN", "RSTICK_LEFT", "RSTICK_UP", "RSTICK_RIGHT", "RSTICK_DOWN", "SHAKE"};
static const char *const pad_names[PAD_COUNT] = {
NULL, "south", "east", "west", "north", "lstick", "rstick", "l", "r", "start", "back",
"dpad_left", "dpad_up", "dpad_right", "dpad_down", "zl", "zr", "lpaddle1", "rpaddle1", "lpaddle2", "rpaddle2"};
@@ -143,7 +143,7 @@ int input_map_bind(const char *button, const char *list) {
}
if (!ok) {
bad++;
rt_log("input: bind %s: ignoring '%s' (expected pad:<name> or key:<name>; stick directions take keys only)",
rt_log("input: bind %s: ignoring '%s' (expected pad:<name> or key:<name>; stick directions and SHAKE take keys only)",
button, tok);
}
}
@@ -289,11 +289,13 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) {
}
int input_prompts_pick(const char *prompts, const char *pad_layout) {
if (prompts && *prompts) return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : PROMPTS_NINTENDO;
if (prompts && *prompts)
return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : !strcasecmp(prompts, "pc") ? PROMPTS_PC : PROMPTS_NINTENDO;
return pad_layout && !strcasecmp(pad_layout, "xbox_prompts") ? PROMPTS_XBOX : PROMPTS_NINTENDO;
}
const char *input_prompts_folder(int prompts, const char *pad_layout) {
if (prompts == PROMPTS_PC) return "romfs-patches-pc";
if (prompts != PROMPTS_XBOX) return NULL;
// The folders are read at start, before a pad is open: auto counts as Xbox, as for a pad without Nintendo labels.
// A Nintendo-labelled pad under auto plays by label too (its A is on the button labelled A), so it matches as well.
@@ -315,6 +317,12 @@ uint64_t input_map_buttons(const uint8_t down[KEY_COUNT]) {
return b;
}
int input_map_held(const uint8_t down[KEY_COUNT], int action) {
for (int i = 0; i < input_map.nkeys; i++)
if (input_map.keys[i].action == action && down[input_map.keys[i].key]) return 1;
return 0;
}
void input_map_stick(const uint8_t down[KEY_COUNT], int stick, int32_t out[2]) {
int first = stick ? B_SR_LEFT : B_SL_LEFT, dir[4] = {0, 0, 0, 0}; // left, up, right, down
for (int i = 0; i < input_map.nkeys; i++) {
+16 -9
View File
@@ -7,11 +7,13 @@
#include <stdint.h>
// Actions are the bit numbers of libnx HidNpadButton (input.h); 16..23 are the stick directions, which keys drive as
// stick deflection.
// stick deflection. B_SHAKE is a key of its own, never a button bit: a press shakes the right stick left and right for
// the game (input.c shake_stick), which detaches a fused part held with Ultrahand. A pad shakes its own stick.
enum {
B_A = 0, B_B, B_X, B_Y, B_STICK_L, B_STICK_R, B_L, B_R, B_ZL, B_ZR, B_PLUS, B_MINUS, B_LEFT, B_UP, B_RIGHT, B_DOWN,
B_SL_LEFT = 16, B_SL_UP, B_SL_RIGHT, B_SL_DOWN, B_SR_LEFT, B_SR_UP, B_SR_RIGHT, B_SR_DOWN,
ACTION_COUNT = 24
B_SHAKE = 24,
ACTION_COUNT = 25
};
// Keys and mouse buttons. F1, F10, F11 and Esc belong to the menu and the window, F8 to the flight recorder: no ids.
@@ -67,14 +69,14 @@ extern InputMap input_map;
void input_map_reset(void);
// The script and totk.ini names, any case when parsed; NULL for an id without one. Actions: A B X Y LCLICK RCLICK L R ZL
// ZR PLUS MINUS LEFT UP RIGHT DOWN, then LSTICK_LEFT LSTICK_UP LSTICK_RIGHT LSTICK_DOWN and the same for RSTICK (the
// stick directions the keys drive). Keys: a-z 0-9 space tab lshift ... (key_names in input_map.c). Pads: south east ...
// stick directions the keys drive), then SHAKE. Keys: a-z 0-9 space tab lshift ... (key_names in input_map.c). Pads: south east ...
const char *input_action_name(int action);
const char *input_key_name(int key);
const char *input_pad_name(int pad);
// Replaces every binding of the action `button` (an action name) with `list`: comma separated "pad:<name>" and
// "key:<name>" entries, "key:default" / "pad:default" for that part's defaults, or "none" for no input. A part the list
// names neither way is left unbound. Pad names are physical buttons, so pad entries go into the gamepad table of every
// layout; pad:default keeps each layout's own button. Stick directions take keys only. Invalid entries are logged and
// layout; pad:default keeps each layout's own button. Stick directions and SHAKE take keys only. Invalid entries are logged and
// skipped; when none is valid the action keeps its bindings. 1 when applied.
int input_map_bind(const char *button, const char *list);
// Applies the TOTK_BIND_<action> settings (cfg_get) over the defaults: at start, and again when one of them changes.
@@ -87,21 +89,26 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a);
// Button prompts (TOTK_PROMPTS): the controller whose buttons the game's prompts show. Nintendo: the game's own. Xbox:
// LB RB LT RT, Menu, View and a d-pad cross for the other buttons, and the face buttons named by the label of the
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts).
enum { PROMPTS_NINTENDO, PROMPTS_XBOX };
// The prompts for a TOTK_PROMPTS value ("nintendo" or "xbox", any case). Unset or empty: Xbox while the pad layout
// setting is "xbox_prompts", else Nintendo.
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). PC: the key or
// mouse button the keyboard defaults press each button with, the mouse for the right stick.
enum { PROMPTS_NINTENDO, PROMPTS_XBOX, PROMPTS_PC };
// The prompts for a TOTK_PROMPTS value ("nintendo", "xbox" or "pc", any case). Unset or empty: Xbox while the pad
// layout setting is "xbox_prompts", else Nintendo.
int input_prompts_pick(const char *prompts, const char *pad_layout);
// The folder next to romfs-index.bin that holds those prompts for a TOTK_PAD_LAYOUT value, NULL for the game's own. The
// Nintendo layout plays an Xbox pad by position, so its folder names the face buttons the other way round
// (romfs-patches-xbox: the right button does A and is labelled B); xbox and auto put every Switch button on the button
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label.
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. The PC
// prompts follow no pad: romfs-patches-pc whatever the layout (romfs.c overlay_init serves romfs-patches-pc-<w>x<h>
// under that name at a game resolution of another shape).
const char *input_prompts_folder(int prompts, const char *pad_layout);
// down[pad] != 0 for the gamepad inputs held. Returns the Switch button bits (0..15) the layout's pad table presses.
uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout);
// down[key] != 0 for the keys held. Returns the Switch button bits (0..15) the table presses.
uint64_t input_map_buttons(const uint8_t down[KEY_COUNT]);
// 1 when a key of action is held.
int input_map_held(const uint8_t down[KEY_COUNT], int action);
// out = x, y of the stick (0 left, 1 right) from its four direction actions; up is +y; a diagonal is scaled to the
// unit circle.
void input_map_stick(const uint8_t down[KEY_COUNT], int stick, int32_t out[2]);
+3
View File
@@ -217,6 +217,9 @@ int ikb_foreground(void) { return focused != 0; }
int ikb_down(int key) { return key > 0 && key < KEY_COUNT && key_held[key]; }
int ikb_escape(void) { return esc_held != 0; }
int ikb_captured(void) { return captured != 0; }
int ikb_pointer(float *nx, float *ny) { (void)nx, (void)ny; return 0; } // (menu_cursor.c: Windows only for now)
void ikb_pointer_set(float nx, float ny) { (void)nx, (void)ny; }
uint32_t ikb_mouse_travel(void) { return 0; } // (the last-device switch: keys and buttons only for now)
void ikb_mouse_take(int32_t *dx, int32_t *dy) {
*dx = plat_xchg32(&mouse_dx, 0);
+29 -3
View File
@@ -83,6 +83,7 @@ uint32_t input_key_char(int key) {
// ---- mouse camera: raw motion accumulated by the window thread, one stick sample per presented frame
static volatile LONG mouse_dx, mouse_dy; // raw counts since the last frame sample
static volatile LONG mouse_travel; // raw counts moved in total, captured or not (ikb_mouse_travel)
static volatile LONG cur_captured; // cursor hidden and confined to the client area
static volatile LONG cur_active; // WM_ACTIVATEAPP: the window's application is active
// Bits: CUR_REL, Esc or activation by a click on the title bar or border: until a client click; CUR_ESC, set with CUR_REL
@@ -137,10 +138,14 @@ int input_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) {
case WM_INPUT: {
RAWINPUT ri;
UINT sz = sizeof ri;
if (cur_captured && GetRawInputData((HRAWINPUT)l, RID_INPUT, &ri, &sz, sizeof(RAWINPUTHEADER)) != (UINT)-1 &&
if (GetRawInputData((HRAWINPUT)l, RID_INPUT, &ri, &sz, sizeof(RAWINPUTHEADER)) != (UINT)-1 &&
ri.header.dwType == RIM_TYPEMOUSE && !(ri.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) {
InterlockedAdd(&mouse_dx, ri.data.mouse.lLastX);
InterlockedAdd(&mouse_dy, ri.data.mouse.lLastY);
LONG x = ri.data.mouse.lLastX, y = ri.data.mouse.lLastY;
InterlockedAdd(&mouse_travel, (x < 0 ? -x : x) + (y < 0 ? -y : y));
if (cur_captured) {
InterlockedAdd(&mouse_dx, x);
InterlockedAdd(&mouse_dy, y);
}
}
break; // DefWindowProc must see WM_INPUT for cleanup
}
@@ -203,6 +208,27 @@ int ikb_escape(void) { return key_down(VK_ESCAPE); }
int ikb_captured(void) { return cur_captured != 0; }
int ikb_pointer(float *nx, float *ny) {
HWND h = gfx_window_handle();
RECT r;
POINT p;
if (!h || GetForegroundWindow() != h || !GetClientRect(h, &r) || r.right < 1 || r.bottom < 1 || !GetCursorPos(&p) ||
!ScreenToClient(h, &p))
return 0;
*nx = (float)p.x / (float)r.right, *ny = (float)p.y / (float)r.bottom;
return p.x >= 0 && p.y >= 0 && p.x < r.right && p.y < r.bottom;
}
void ikb_pointer_set(float nx, float ny) {
HWND h = gfx_window_handle();
RECT r;
if (!h || GetForegroundWindow() != h || !GetClientRect(h, &r)) return;
POINT p = {(LONG)(nx * r.right), (LONG)(ny * r.bottom)};
if (ClientToScreen(h, &p)) SetCursorPos(p.x, p.y);
}
uint32_t ikb_mouse_travel(void) { return (uint32_t)mouse_travel; }
void ikb_mouse_take(int32_t *dx, int32_t *dy) {
*dx = InterlockedExchange(&mouse_dx, 0);
*dy = InterlockedExchange(&mouse_dy, 0);
+4
View File
@@ -7,8 +7,12 @@
int ikb_foreground(void); // the game window is in front: keys count
int ikb_down(int key); // key id (input_map.h KEY_*) held, mouse buttons included
int ikb_escape(void); // Esc held (no key id: it belongs to the menu)
// The pointer in the client area, 0..1 from its top left; 0 when the window is not in front or the pointer is outside
int ikb_pointer(float *nx, float *ny);
void ikb_pointer_set(float nx, float ny); // moves the pointer there (the window in front only)
int ikb_captured(void); // the cursor is captured for the mouse camera
void ikb_mouse_take(int32_t *dx, int32_t *dy); // raw mouse motion since the last call, in counts
uint32_t ikb_mouse_travel(void); // raw counts the mouse moved in total (|dx| + |dy|), captured or not
void ikb_cursor_update(void); // what input_cursor_allowed says may have changed
void ikb_menu_closed(void); // the menu closed: a capture that Esc gave up comes back
+340
View File
@@ -0,0 +1,340 @@
// The mouse pointer in TotK 1.4.3's own menus (the title, the inventory, the System tab, Options, shops, dialogue
// choices): while a menu screen has the game's focus box (eui's BoxCursor, the frame the d-pad moves), the Windows
// pointer is released from the mouse camera and shown, the item under it takes the focus as if the d-pad had moved
// there (highlight, sound and description included), a left click on an item is A on it and a right click is B.
// Nothing is drawn and no game code is called: at each pad read (ov_input.c GetNpadStates, the game thread) the open
// screens are read and the focus is moved with the three writes eui::BoxCursorMgr::moveBoxCursor makes, so the game's
// own BoxCursorControl moves the box at its next update.
//
// Adapted from Weeping of the Empire's engine/runtime/totk_menu_cursor.cpp @ df0586cdc5702ca19bbebfa59697e0b6980f6237
// (https://github.com/daniel-madrid-07/weeping-of-the-empire), Copyright (c) 2026 daniel-madrid-07, MIT License: the
// focus read, the hit test, the stale-hit-pane fallback and the focus writes, which it does for 1.0.0.
// Placed in 1.4.3 by hand:
// - eui::ScreenMgr::sInstance: 1.0.0 main+0x4640010, 1.4.3 main+0x3acf960 (its createInstance main+0xc613d4 and
// constructor main+0xc61450 match 1.0.0's main+0x119c5cc / +0x119c648 instruction for instruction, the object
// 0x450 bytes with the same field stores, so its layout is 1.0.0's);
// - the screen's reserved node (+0x150) and request bits (+0x175, bit 2) and its draw target byte (+0x16c): the same
// stores at 1.4.3 main+0x87903c.
// The other fields are 1.0.0's; menu_cursor logs what it reads the first time a menu opens (TOTK_MENU_CURSOR_LOG=1:
// every screen change), so a field that moved shows as a menu with no nodes or boxes off the layout.
//
// Only while keyboard and mouse are the device used last (input_kbm_last): a gamepad player sees the menus unchanged.
// TOTK_MENU_CURSOR (live, default 1): 0 leaves the menus to the keys and the pad.
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "cfg.h"
#include "gfx.h"
#include "host.h"
#include "input.h"
#include "input_map.h"
#include "input_wsys.h"
#include "layout.h"
#include "platform/platform.h"
#define SCREEN_MGR_V143 0x3acf960ull // eui::ScreenMgr::sInstance
#define MAIN_SIZE 0x3adf000ull // main's image (code, data, bss) in 1.4.3
// eui::ScreenMgr, BoxCursorMgr, BoxCursorControl
enum { SM_BOX_MGR = 0x3f8, BM_CONTROLS = 0x28, CTL_ACTIVE = 0x58, CTL_RESERVED = 0x60 };
// eui::Screen
enum { SCR_LAYOUT = 0x28, SCR_DRAW_INFO = 0x60, SCR_NODES = 0x80, SCR_RESERVED = 0x150, SCR_STATE = 0x16e,
SCR_REQUEST = 0x175, SCR_OPENED = 2 };
// eui::BoxCursorNode, AnimButton
enum { NODE_BUTTON = 0x18, NODE_SCREEN = 0x20, BTN_LAYOUT = 0x20, BTN_FLAGS = 0x40, BTN_HIT_PANE = 0x58 };
#define BTN_USABLE 0x20010u // both set: active and enabled (ButtonGroup::Update's test)
// nn::ui2d::DrawInfo: projection (4 x 4) and view (3 x 4); nn::ui2d::Layout: root pane, size, name
enum { DI_PROJ = 0x10, DI_VIEW = 0x50, LYT_ROOT = 0x18, LYT_SIZE = 0x28, LYT_NAME = 0x30 };
// nn::ui2d::Pane
enum { PANE_PARENT = 0x18, PANE_SIZE = 0x50, PANE_FLAG = 0x58, PANE_ALPHA = 0x59, PANE_BASE = 0x5b, PANE_MTX = 0x70 };
static uint64_t main_lo, main_hi;
static int ok_at(uint64_t p, uint64_t n) {
return p >= 0x10000 && p < (1ull << 47) && (p & 7) == 0 && plat_mem_readable(p, n);
}
static uint64_t rd64(uint64_t a) { uint64_t v; memcpy(&v, (const void *)(uintptr_t)a, 8); return v; }
static uint32_t rd32(uint64_t a) { uint32_t v; memcpy(&v, (const void *)(uintptr_t)a, 4); return v; }
static uint8_t rd8(uint64_t a) { return *(const volatile uint8_t *)(uintptr_t)a; }
static float rdf(uint64_t a) { float v; memcpy(&v, (const void *)(uintptr_t)a, 4); return v; }
// An object of the game: readable, its vtable in main's image
static int game_object(uint64_t p, uint64_t n) {
if (!ok_at(p, n)) return 0;
uint64_t vt = rd64(p);
return vt >= main_lo && vt < main_hi;
}
// ---- panes (AnimButton::HitTest's rules: 1.0.0 main+0x222ea40, +0x223b090)
static int pane_shown(uint64_t pane) {
if (!ok_at(pane, PANE_MTX + 0x20)) return 0;
if (!(rd8(pane + PANE_FLAG) & 1) || !rd8(pane + PANE_ALPHA)) return 0;
int depth = 0;
for (uint64_t p = rd64(pane + PANE_PARENT); p; p = rd64(p + PANE_PARENT)) {
if (!ok_at(p, PANE_MTX) || ++depth > 64) return 0;
uint8_t f = rd8(p + PANE_FLAG);
if (!(f & 1) || (!rd8(p + PANE_ALPHA) && (f & 2))) return 0;
}
return 1;
}
// The pane's box in layout coordinates (origin at the centre, y up): centre and half size
static void pane_box(uint64_t pane, float *cx, float *cy, float *hw, float *hh) {
float w = rdf(pane + PANE_SIZE), h = rdf(pane + PANE_SIZE + 4);
float m00 = rdf(pane + PANE_MTX), m11 = rdf(pane + PANE_MTX + 0x14);
uint8_t base = rd8(pane + PANE_BASE), bh = base & 3, bv = base >> 2 & 3;
*hw = fabsf(w * m00) * 0.5f, *hh = fabsf(h * m11) * 0.5f;
*cx = rdf(pane + PANE_MTX + 0xc), *cy = rdf(pane + PANE_MTX + 0x1c);
if (bh == 1) *cx += *hw; else if (bh == 2) *cx -= *hw; // the translation is the left / right edge
if (bv == 1) *cy -= *hh; else if (bv == 2) *cy += *hh; // ... the top / bottom edge
}
// The screen's draw transform, for a screen drawn away from its centred layout space (scale and translation only)
typedef struct { int ok; float v[12], p[16]; } Xf;
static Xf screen_xf(uint64_t scr) {
Xf x = {0};
uint64_t di = rd64(scr + SCR_DRAW_INFO);
if (!ok_at(di, DI_VIEW + sizeof x.v)) return x;
memcpy(x.p, (const void *)(uintptr_t)(di + DI_PROJ), sizeof x.p);
memcpy(x.v, (const void *)(uintptr_t)(di + DI_VIEW), sizeof x.v);
for (int i = 0; i < 16; i++) if (!isfinite(x.p[i])) return x;
for (int i = 0; i < 12; i++) if (!isfinite(x.v[i])) return x;
x.ok = x.p[0] != 0 && x.p[5] != 0 && fabsf(x.p[1]) < 1e-5f && fabsf(x.p[4]) < 1e-5f && fabsf(x.v[1]) < 1e-4f &&
fabsf(x.v[4]) < 1e-4f;
return x;
}
static int to_ndc(const Xf *t, float x, float y, float *nx, float *ny) {
float vx = t->v[0] * x + t->v[1] * y + t->v[3], vy = t->v[4] * x + t->v[5] * y + t->v[7],
vz = t->v[8] * x + t->v[9] * y + t->v[11];
float cx = t->p[0] * vx + t->p[1] * vy + t->p[2] * vz + t->p[3];
float cy = t->p[4] * vx + t->p[5] * vy + t->p[6] * vz + t->p[7];
float cw = t->p[12] * vx + t->p[13] * vy + t->p[14] * vz + t->p[15];
if (!(fabsf(cw) > 1e-6f)) return 0;
*nx = cx / cw, *ny = cy / cw;
return 1;
}
// The transform maps the layout as the plain layout test does (centre to 0,0, corner to 1,1): it adds nothing
static int xf_plain(const Xf *t, float lw, float lh) {
float ax, ay, bx, by;
if (!to_ndc(t, 0, 0, &ax, &ay) || !to_ndc(t, lw / 2, lh / 2, &bx, &by)) return 1;
return fabsf(ax) < 0.01f && fabsf(ay) < 0.01f && fabsf(bx - 1) < 0.01f && fabsf(by - 1) < 0.01f;
}
// The pointer: layout coordinates (x, y) and device coordinates (nx, ny), and the transform when it is not plain
typedef struct { float x, y, nx, ny; const Xf *t; } Pt;
static int pane_hit(uint64_t pane, const Pt *p) {
if (!pane_shown(pane)) return 0;
float cx, cy, hw, hh;
pane_box(pane, &cx, &cy, &hw, &hh);
if (!p->t) return p->x >= cx - hw && p->x <= cx + hw && p->y >= cy - hh && p->y <= cy + hh;
float ax, ay, bx, by;
if (!to_ndc(p->t, cx - hw, cy - hh, &ax, &ay) || !to_ndc(p->t, cx + hw, cy + hh, &bx, &by)) return 0;
return p->nx >= fminf(ax, bx) && p->nx <= fmaxf(ax, bx) && p->ny >= fminf(ay, by) && p->ny <= fmaxf(ay, by);
}
// ---- screens and nodes
typedef struct { uint64_t control, node, screen; } Focus;
static uint64_t screen_mgr(void) {
uint64_t slot = MOD_MAIN_BASE + SCREEN_MGR_V143, sm = rd64(slot);
return game_object(sm, SM_BOX_MGR + 8) ? sm : 0;
}
// The focused node of an open screen, from the draw targets' box cursors (all 0: none, as in gameplay)
static Focus focus_now(void) {
Focus none = {0};
uint64_t sm = screen_mgr(), bm = sm ? rd64(sm + SM_BOX_MGR) : 0;
if (!ok_at(bm, BM_CONTROLS + 16)) return none;
for (int i = 0; i < 2; i++) {
uint64_t ctl = rd64(bm + BM_CONTROLS + 8ull * i);
if (!ok_at(ctl, CTL_RESERVED + 8)) continue;
uint64_t node = rd64(ctl + CTL_ACTIVE);
if (!ok_at(node, NODE_SCREEN + 8)) continue;
uint64_t scr = rd64(node + NODE_SCREEN);
if (!game_object(scr, SCR_REQUEST + 1) || rd8(scr + SCR_STATE) != SCR_OPENED) continue;
return (Focus){ctl, node, scr};
}
return none;
}
static void layout_name(uint64_t scr, char *out, size_t n) {
snprintf(out, n, "?");
uint64_t lyt = rd64(scr + SCR_LAYOUT), name = ok_at(lyt, LYT_NAME + 8) ? rd64(lyt + LYT_NAME) : 0;
if (name < 0x10000 || name >= (1ull << 47) || !plat_mem_readable(name, n)) return;
memcpy(out, (const void *)(uintptr_t)name, n - 1);
out[n - 1] = 0;
for (char *q = out; *q; q++) if (*q < 0x20 || *q > 0x7e) { *q = 0; break; }
}
static void layout_size(uint64_t scr, float *lw, float *lh) {
*lw = 1920, *lh = 1080;
uint64_t lyt = rd64(scr + SCR_LAYOUT);
if (!ok_at(lyt, LYT_SIZE + 8)) return;
float w = rdf(lyt + LYT_SIZE), h = rdf(lyt + LYT_SIZE + 4);
if (w >= 64 && w <= 8192 && h >= 64 && h <= 8192) *lw = w, *lh = h;
}
// The screen's focusable nodes: an sead OffsetList, head {prev, next} at +0x80, node-to-link offset at +0x94
#define MAX_NODES 512
static int nodes_of(uint64_t scr, uint64_t *node, uint64_t *btn) {
uint64_t head = scr + SCR_NODES;
int32_t off = (int32_t)rd32(head + 0x14), n = 0;
if (off < 0 || off > 0x40) return 0;
for (uint64_t link = rd64(head + 8); link != head && n < MAX_NODES; link = rd64(link + 8)) {
if (!ok_at(link, 16)) break;
uint64_t nd = link - (uint64_t)off;
if (!ok_at(nd, NODE_SCREEN + 8)) continue;
uint64_t b = rd64(nd + NODE_BUTTON);
if (!ok_at(b, BTN_HIT_PANE + 8)) continue;
node[n] = nd, btn[n] = b, n++;
}
return n;
}
static int usable(uint64_t btn) { return !(~rd32(btn + BTN_FLAGS) & BTN_USABLE); }
static uint64_t root_pane(uint64_t btn) {
uint64_t blyt = rd64(btn + BTN_LAYOUT);
return ok_at(blyt, LYT_ROOT + 8) ? rd64(blyt + LYT_ROOT) : 0;
}
// Every usable node's shown hit pane lies off the visible layout: the hit panes are stale (TotK never uses touch;
// the dialogue choices' sit far from where the choices are drawn), so the buttons' own parts panes stand for them
static int stale_hit_panes(int n, const uint64_t *btn, float lw, float lh, const Xf *t) {
int seen = 0;
for (int i = 0; i < n; i++) {
if (!usable(btn[i])) continue;
uint64_t pane = rd64(btn[i] + BTN_HIT_PANE);
if (!ok_at(pane, PANE_MTX + 0x20) || !pane_shown(pane)) continue;
float cx, cy, hw, hh, vx, vy;
pane_box(pane, &cx, &cy, &hw, &hh);
int in = t ? to_ndc(t, cx, cy, &vx, &vy) && fabsf(vx) <= 1 && fabsf(vy) <= 1
: fabsf(cx) <= lw / 2 && fabsf(cy) <= lh / 2;
seen++;
if (in) return 0;
}
return seen > 0;
}
// The usable node under the pointer, 0: none
static uint64_t node_at(int n, const uint64_t *node, const uint64_t *btn, const Pt *p, float lw, float lh) {
if (!stale_hit_panes(n, btn, lw, lh, p->t)) {
for (int i = 0; i < n; i++)
if (usable(btn[i]) && pane_hit(rd64(btn[i] + BTN_HIT_PANE), p)) return node[i];
return 0;
}
uint64_t found = 0;
float best = 1e30f;
for (int i = 0; i < n; i++) { // parts panes can be several items wide: the nearest centre
uint64_t pane = root_pane(btn[i]);
if (!usable(btn[i]) || !pane_hit(pane, p)) continue;
float cx, cy, hw, hh, d;
pane_box(pane, &cx, &cy, &hw, &hh);
d = (cx - p->x) * (cx - p->x) + (cy - p->y) * (cy - p->y);
if (d < best) best = d, found = node[i];
}
return found;
}
// The focus to node: the writes moveBoxCursor makes. The request bit is a byte eui also writes, so it is raised
// again until the focus is there.
static void move_focus(const Focus *f, uint64_t node) {
memcpy((void *)(uintptr_t)(f->control + CTL_RESERVED), &node, 8);
memcpy((void *)(uintptr_t)(f->screen + SCR_RESERVED), &node, 8);
__atomic_fetch_or((uint8_t *)(uintptr_t)(f->screen + SCR_REQUEST), (uint8_t)4, __ATOMIC_SEQ_CST);
}
// Screens with a focus box that are gameplay, not menus: the L ability wheel, the D-pad strips, Autobuild's list, the
// Purah Pad's camera and the map (the stick moves its own cursor there)
static int gameplay_screen(const char *nm) {
static const char *const names[] = {"ShortCutMainItem_00", "ShortCut_00", "AutoBuilder_00", "CameraPointer_00",
"AppMap_00"};
for (size_t i = 0; i < sizeof names / sizeof *names; i++)
if (!strcmp(nm, names[i])) return 1;
return 0;
}
static volatile int32_t g_pointer; // a menu has the pointer: input_cursor_allowed releases the capture
int menu_cursor_pointer(void) { return __atomic_load_n(&g_pointer, __ATOMIC_RELAXED); }
static int enabled(void) {
if (!RT_V143) return 0;
const char *v = cfg_get("TOTK_MENU_CURSOR"), *in = cfg_get("TOTK_INPUT");
return !(v && !strcmp(v, "0")) && !(in && !strcmp(in, "none"));
}
static void set_pointer(int on) {
if (plat_xchg32(&g_pointer, on) == on) return;
ikb_cursor_update();
if (on) ikb_pointer_set(0.5f, 0.5f); // the pointer appears in the middle, not where the capture left it
}
// The pointer on the game's picture, 0..1 from its top left (the present's fit, letterbox or pillarbox)
static int picture_pos(float *px, float *py) {
float nx, ny, r[4];
if (!ikb_pointer(&nx, &ny) || !gfx_picture_rect(r) || r[2] <= 0 || r[3] <= 0) return 0;
*px = (nx - r[0]) / r[2], *py = (ny - r[1]) / r[3];
return *px >= 0 && *px <= 1 && *py >= 0 && *py <= 1;
}
static void log_screen(const Focus *f, const char *nm, int n, float lw, float lh, const Xf *t, int stale) {
static uint64_t last;
static int lines;
const char *e = cfg_get("TOTK_MENU_CURSOR_LOG");
int verbose = e && !strcmp(e, "1");
if (f->screen == last || (!verbose && lines >= 6)) return;
last = f->screen, lines++;
rt_log("menu_cursor: screen %s (layout %gx%g, %d nodes, %s hit panes, draw transform %s)", nm, lw, lh, n,
stale ? "stale" : "own", t ? "scaled" : "plain");
}
// Once per pad read on the game thread: the pointer's hover and clicks, as pad buttons (A, B) for this read
void menu_cursor_poll(uint64_t *buttons) {
static int inited, pending_a, held_l, held_r;
static uint64_t pending_node, pending_until, hold_until, hold_bit;
static float last_px = -1, last_py = -1;
if (!inited) {
inited = 1;
main_lo = MOD_MAIN_BASE, main_hi = MOD_MAIN_BASE + MAIN_SIZE;
if (RT_V143) rt_log("menu_cursor: on for 1.4.3 (TOTK_MENU_CURSOR=0 turns it off)");
}
if (!enabled()) { set_pointer(0); return; }
Focus f = focus_now();
char nm[48] = "";
if (f.screen) layout_name(f.screen, nm, sizeof nm);
// With the gamepad as the last device the menus stay as they are on the console: no pointer, the capture kept.
// Moving the mouse (or a key) makes keyboard and mouse the last device and the pointer comes.
int menu = f.screen && !gameplay_screen(nm) && ikb_foreground() && input_kbm_last();
set_pointer(menu);
int l = ikb_down(KEY_MOUSE_L), r = ikb_down(KEY_MOUSE_R);
int click_l = l && !held_l, click_r = r && !held_r;
held_l = l, held_r = r;
uint64_t now = plat_now_ms();
if (now < hold_until) { // a click's button, held for 60 ms so the game sees one press whatever its read rate
*buttons |= hold_bit;
return;
}
if (!menu) { pending_a = 0; last_px = last_py = -1; return; }
if (pending_a) { // the focus asked for by a click: A once it is there
if (rd64(f.control + CTL_ACTIVE) == pending_node) {
pending_a = 0, hold_until = now + 60, hold_bit = 1ull << B_A;
*buttons |= hold_bit;
return;
}
if (now > pending_until) pending_a = 0;
else move_focus(&f, pending_node);
return;
}
if (click_r) { hold_until = now + 60, hold_bit = 1ull << B_B; *buttons |= hold_bit; return; }
float px, py;
if (!picture_pos(&px, &py)) return;
int moved = fabsf(px - last_px) > 0.001f || fabsf(py - last_py) > 0.001f;
if (!moved && !click_l) return;
last_px = px, last_py = py;
float lw, lh;
layout_size(f.screen, &lw, &lh);
Xf xf = screen_xf(f.screen);
Pt p = {(px - 0.5f) * lw, (0.5f - py) * lh, px * 2 - 1, 1 - py * 2, NULL};
if (xf.ok && !xf_plain(&xf, lw, lh)) p.t = &xf;
static uint64_t node[MAX_NODES], btn[MAX_NODES];
int n = nodes_of(f.screen, node, btn);
log_screen(&f, nm, n, lw, lh, p.t, n && stale_hit_panes(n, btn, lw, lh, p.t));
uint64_t at = n ? node_at(n, node, btn, &p, lw, lh) : 0;
if (!at) return;
if (at != f.node) move_focus(&f, at);
if (click_l) {
if (at == f.node) { hold_until = now + 60, hold_bit = 1ull << B_A; *buttons |= hold_bit; }
else pending_a = 1, pending_node = at, pending_until = now + 300;
}
}
+340
View File
@@ -0,0 +1,340 @@
// Direct mouse input for TotK 1.4.3. The camera controller's input update (main+0x874c1c) turns HID stick floats
// into a radial dead zone, clamps the radius to one and applies StickExponent. The mouse enters after all three,
// at main+0x874cb4, before the game's X/Y inversion and input-activity flags. It never becomes a HID stick value.
// Free orbit removes that sample again before the camera's additional vertical square/velocity filters and adds
// raw-count angular deltas at its spherical-angle output instead. Ultrahand has a separate post-curve hook.
// The ordinary stick's result stays, so a controller still uses the game's own response.
//
// This is deliberately not a render-camera override: the game remains responsible for aiming, camera collision,
// lock-on and scripted cameras. Which of its other modes consume this camera input needs in-game verification.
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "input.h"
#include "input_wsys.h"
#include "platform/platform.h"
#if __has_include("patches.h")
#include "patches.h"
#endif
static int direct_mode(void) {
// cfg_value: unset is the settings table's default (direct), as the menu shows it
return !strcmp(cfg_value("TOTK_MOUSE_MODE"), "direct") && rt_patch_enabled(rt_patch_set("mouse_direct"));
}
static uint64_t last_update;
static uint64_t hand_update;
static int accepts_mouse;
static int hand_active(uint64_t now) {
uint64_t last = __atomic_load_n(&hand_update, __ATOMIC_ACQUIRE);
return last && now - last < 150000000ull;
}
int input_direct_mouse_active(void) {
uint64_t last = __atomic_load_n(&last_update, __ATOMIC_ACQUIRE);
return direct_mode() && (__atomic_load_n(&accepts_mouse, __ATOMIC_RELAXED) || hand_active(plat_now_ns())) && last &&
plat_now_ns() - last < 150000000ull;
}
int input_direct_mouse_enabled(void) { return direct_mode(); }
void input_direct_mouse_radial(int32_t dx, int32_t dy, float sensitivity, float cursor[2], int32_t out[2]) {
if (!(sensitivity > 0)) { cursor[0] = cursor[1] = 0; out[0] = out[1] = 0; return; }
cursor[0] += dx * (double)sensitivity / 200;
cursor[1] -= dy * (double)sensitivity / 200;
double length = hypot(cursor[0], cursor[1]);
if (length > 1) { cursor[0] /= length; cursor[1] /= length; }
out[0] = (int32_t)lrint(cursor[0] * 32767);
out[1] = (int32_t)lrint(cursor[1] * 32767);
}
void input_direct_mouse_row(int32_t dx, float sensitivity, uint64_t now, InputMouseRow *row, int32_t out[2]) {
const float step_counts = 32;
out[0] = out[1] = 0;
if (!(sensitivity > 0)) { *row = (InputMouseRow){0}; return; }
if (dx) {
// Reversing direction cancels any remainder from the previous drag. Bound a fast flick to one pending step;
// a stopped mouse never starts another pulse, regardless of how often HID is polled.
if ((dx < 0 && row->distance > 0) || (dx > 0 && row->distance < 0)) row->distance = 0;
row->distance = fmaxf(-2 * step_counts, fminf(2 * step_counts, row->distance + dx * sensitivity));
}
if (row->direction) {
if (now < row->pulse_until && (!dx || (dx > 0 ? 1 : -1) == row->direction)) {
out[0] = row->direction * 32767;
return;
}
row->direction = 0;
row->neutral_until = now + 32000000ull;
return; // publish neutral even when a slow frame skipped the pulse's deadline
}
if (!dx || now < row->neutral_until || fabsf(row->distance) < step_counts) return;
row->direction = row->distance > 0 ? 1 : -1;
row->distance = fmodf(row->distance, step_counts);
row->pulse_until = now + 32000000ull;
out[0] = row->direction * 32767;
}
#ifdef RT_PATCH_PAGE
#define HOST_MOUSE_DIRECT (RT_PATCH_PAGE + 0xfd0)
#define HOST_MOUSE_ACTIVITY (RT_PATCH_PAGE + 0xfc0)
#define HOST_MOUSE_ORBIT_BEGIN (RT_PATCH_PAGE + 0xfb0)
#define HOST_MOUSE_ORBIT_ANGLES (RT_PATCH_PAGE + 0xfa0)
#define HOST_MOUSE_HAND (RT_PATCH_PAGE + 0xf90)
static _Thread_local uint64_t mouse_input_object;
typedef struct {
uint64_t object, generation, when;
float pad[2], motion[2], angle[2]; // post-inversion controller input, mouse input, mouse yaw/pitch in degrees
int camera_enabled;
} MouseSample;
static MouseSample sample;
static PlatMutex sample_lock = PLAT_MUTEX_INIT;
static _Thread_local struct { uint64_t object; MouseSample mouse; } orbit;
typedef struct {
uint64_t object, generation, input;
float pitch, original_target;
int hold_pitch, target_saved;
} OrbitTrack;
static OrbitTrack orbit_seen[16];
// sample_lock held. Camera objects can coexist while the game blends between their outputs.
static OrbitTrack *orbit_track(uint64_t object) {
int oldest = 0;
for (int i = 0; i < 16; i++) {
if (orbit_seen[i].object == object) return &orbit_seen[i];
if (orbit_seen[i].generation < orbit_seen[oldest].generation) oldest = i;
}
orbit_seen[oldest] = (OrbitTrack){.object = object};
return &orbit_seen[oldest];
}
static int orbit_sample_once(uint64_t object, uint64_t generation) {
plat_mutex_lock(&sample_lock);
OrbitTrack *track = orbit_track(object);
int fresh = track->generation != generation;
if (fresh) track->generation = generation;
plat_mutex_unlock(&sample_lock);
return fresh;
}
static float guest_float(uint64_t at) { float f; memcpy(&f, (void *)(uintptr_t)at, sizeof f); return f; }
static void guest_float_store(uint64_t at, float f) { memcpy((void *)(uintptr_t)at, &f, sizeof f); }
static uint64_t guest_pointer(uint64_t at) { uint64_t p; memcpy(&p, (void *)(uintptr_t)at, sizeof p); return p; }
static MouseSample sample_read(void) {
plat_mutex_lock(&sample_lock);
MouseSample m = sample;
plat_mutex_unlock(&sample_lock);
return m;
}
static float wrap_degrees(float a) { return remainderf(a, 360.0f); }
// main+0x191d78 builds the pitch target from +0x15c and +0x11c; the orbit update filters +0x108 toward it and adds
// (1 - +0x88) * +0x10c at output. Updating only +0x108 makes the camera spring back to the unchanged target.
static float orbit_pitch_offset(uint64_t object) {
return (1 - guest_float(object + 0x88)) * guest_float(object + 0x10c);
}
static void orbit_pitch_target(uint64_t object, float pitch) {
guest_float_store(object + 0x15c, pitch - orbit_pitch_offset(object) - guest_float(object + 0x11c));
}
static void orbit_pitch_release(OrbitTrack *track) {
if (track->target_saved) guest_float_store(track->object + 0x15c, track->original_target);
track->hold_pitch = track->target_saved = 0;
}
// A host call at an instruction site, not an AAPCS64 function replacement. Preserve every guest register except
// s9/s10, which carry the processed camera input, and perform the displaced store of s9 at [x20 + 0x420].
static void camera_input(Cpu *c) {
mouse_input_object = 0;
uint32_t flags = (uint32_t)c->x[21];
int accept = !(flags & 1) && !input_direct_mouse_selector_active();
__atomic_store_n(&accepts_mouse, accept, __ATOMIC_RELAXED);
__atomic_store_n(&last_update, plat_now_ns(), __ATOMIC_RELEASE);
MouseSample next = {.object = c->x[20], .when = plat_now_ns(), .camera_enabled = accept};
memcpy(&next.pad[0], &c->v[9], sizeof(float));
memcpy(&next.pad[1], &c->v[10], sizeof(float));
if (flags & 2) next.pad[0] = -next.pad[0];
if (flags & 4) next.pad[1] = -next.pad[1];
if (direct_mode()) {
int32_t dx, dy;
input_direct_mouse_sample(!input_direct_mouse_selector_active() && (accept || hand_active(plat_now_ns())), &dx, &dy);
float sensitivity = (float)cfg_double("TOTK_MOUSE_SENS");
sensitivity = fminf(10, fmaxf(0, sensitivity));
// The game multiplies camera input by its 30 Hz frame ratio later. Divide by that exact ratio, rather
// than wall-clock time: an equal distance of mouse motion then gives equal input at every frame rate.
float ratio = 1;
if (frame_step_realtime()) memcpy(&ratio, rt_patch_page(), sizeof ratio);
else {
double hz = frame_step_limit_hz();
if (hz > 0) ratio = (float)(30 / hz);
}
if (isfinite(ratio) && ratio > 0 && sensitivity > 0 && (dx || dy)) {
if (accept) mouse_input_object = c->x[20];
float x, y;
memcpy(&x, &c->v[9], sizeof x);
memcpy(&y, &c->v[10], sizeof y);
float scale = 0.01f * sensitivity / ratio;
next.motion[0] = dx * scale * (flags & 2 ? -1 : 1);
next.motion[1] = -dy * scale * (flags & 4 ? -1 : 1);
next.angle[0] = -dx * 0.08f * sensitivity * (flags & 2 ? -1 : 1);
next.angle[1] = dy * 0.08f * sensitivity * (flags & 4 ? -1 : 1);
if (accept) { x += dx * scale; y -= dy * scale; }
uint32_t xb, yb;
memcpy(&xb, &x, sizeof xb);
memcpy(&yb, &y, sizeof yb);
c->v[9] = xb;
c->v[10] = yb;
static int logged;
if (!logged) {
logged = 1;
rt_log("mouse: direct camera input after the stick dead zone, clamp and exponent");
}
}
}
plat_mutex_lock(&sample_lock);
next.generation = sample.generation + 1;
sample = next;
plat_mutex_unlock(&sample_lock);
uint32_t original = (uint32_t)c->v[9];
memcpy((void *)(uintptr_t)(c->x[20] + 0x420), &original, sizeof original);
}
// Free camera has another signed-square curve for its vertical axis, plus mode-dependent velocity filters.
// Remove only this mouse sample before that controller runs. At its final spherical-angle output, add degrees
// directly and move its persistent pitch/yaw by the same amounts so the next update starts at the new orientation.
// The controller still handles its gamepad input, following, collision and focus normally.
static void orbit_begin(Cpu *c) {
orbit.object = 0;
uint64_t object = c->x[0];
if (direct_mode()) {
MouseSample m = sample_read();
uint64_t input = guest_pointer(object + 0x20);
if (m.object == input && m.camera_enabled) {
// The hooks take a step when the mouse moved in it, or while the mouse holds the pitch. A step of the
// gamepad alone (no mouse motion, no hold: a player who never moved the mouse) keeps the game's input.
int moved = m.motion[0] != 0 || m.motion[1] != 0, take;
uint64_t held = guest_pointer(input + 0x148);
uint8_t override;
memcpy(&override, (void *)(uintptr_t)(input + 0x15c), 1);
plat_mutex_lock(&sample_lock);
OrbitTrack *track = orbit_track(object);
if (track->input != input) track->hold_pitch = track->target_saved = 0;
if (m.pad[1] != 0 || (held & 0x20) || (override & 0x40)) orbit_pitch_release(track);
take = moved || track->hold_pitch;
if (take) track->input = input;
if (track->hold_pitch) orbit_pitch_target(object, track->pitch);
plat_mutex_unlock(&sample_lock);
if (moved) { // the mouse's part of this step's stick goes to the final angles instead
guest_float_store(input + 0x420, m.pad[0]);
guest_float_store(input + 0x424, m.pad[1]);
}
if (take) orbit.object = object, orbit.mouse = m;
}
} else {
plat_mutex_lock(&sample_lock);
orbit_pitch_release(orbit_track(object));
plat_mutex_unlock(&sample_lock);
}
c->x[8] = guest_pointer(object + 8); // displaced ldr x8, [x0, #8]
}
static void orbit_angles(Cpu *c) {
uint64_t object = c->x[20];
if (orbit.object == object) {
float yaw_delta = orbit.mouse.angle[0], pitch_delta = orbit.mouse.angle[1];
int fresh = plat_now_ns() - orbit.mouse.when < 150000000ull &&
orbit_sample_once(object, orbit.mouse.generation);
if (!fresh) yaw_delta = pitch_delta = 0;
plat_mutex_lock(&sample_lock);
OrbitTrack *track = orbit_track(object);
if (track->hold_pitch || yaw_delta || pitch_delta) {
float pitch = guest_float(c->sp + 0x44), yaw = guest_float(c->sp + 0x48);
float low = guest_float(object + 0xf8), high = guest_float(object + 0xfc);
if (!isfinite(low) || !isfinite(high) || low >= high) low = -89.9f, high = 89.9f;
low = fmaxf(-89.9f, low); high = fminf(89.9f, high);
// The game can recalculate its pitch after orbit_begin (following, mode changes and another filter).
// Integrate from our last requested angle, then correct the final output even on stationary frames.
float base = track->hold_pitch ? track->pitch : pitch;
float new_pitch = fminf(high, fmaxf(low, base + pitch_delta));
guest_float_store(c->sp + 0x44, new_pitch);
guest_float_store(c->sp + 0x48, wrap_degrees(yaw + yaw_delta));
guest_float_store(object + 0x108, wrap_degrees(new_pitch - orbit_pitch_offset(object)));
guest_float_store(object + 0x120, wrap_degrees(guest_float(object + 0x120) + yaw_delta));
if (!track->target_saved) track->original_target = guest_float(object + 0x15c), track->target_saved = 1;
track->pitch = new_pitch; track->input = orbit.mouse.object; track->hold_pitch = 1;
orbit_pitch_target(object, new_pitch);
static int logged;
if (!logged) {
logged = 1;
rt_log("mouse: free-camera angles directly, 0.08 degrees per count at sensitivity 1, equal X/Y");
}
}
plat_mutex_unlock(&sample_lock);
orbit.object = 0;
}
uint32_t bits;
memcpy(&bits, (const void *)(uintptr_t)(c->sp + 0x44), sizeof bits);
c->v[12] = bits; // displaced ldr s12, [sp, #0x44]
}
// Ultrahand reads the player's manipulation input rather than the camera's processed stick. Insert the mouse
// after that controller's per-axis power curves (main+0x1d59460), preserving the keyboard/controller contribution.
static void hand_input(Cpu *c) {
__atomic_store_n(&hand_update, plat_now_ns(), __ATOMIC_RELEASE);
static _Thread_local uint64_t object, generation;
if (direct_mode()) {
MouseSample m = sample_read();
if (m.generation != generation || object != c->x[19]) {
float x = guest_float(c->sp + 0x60), y;
memcpy(&y, &c->v[15], sizeof y);
x += m.motion[0];
y += m.motion[1];
guest_float_store(c->sp + 0x60, x);
uint32_t bits;
memcpy(&bits, &y, sizeof bits);
c->v[15] = bits;
object = c->x[19]; generation = m.generation;
static int logged;
if (!logged && (m.motion[0] || m.motion[1])) {
logged = 1;
rt_log("mouse: held-object input after the manipulation controller's power curves");
}
}
}
uint32_t original = (uint32_t)c->x[8];
memcpy((void *)(uintptr_t)(c->sp + 0x48), &original, sizeof original);
}
// The game also uses a 10% activity threshold after processing the stick. A one-count mouse movement must count
// as active, even when its displacement is smaller than that threshold. The site is the displaced ldp d9, d8, [sp, #8]
// just before the update's last `str w8, [x20, #0x418]`: w8 holds the flags then (bit 0 raw input, bit 4 any input,
// bits 3 and 5 processed input below the threshold), so they are changed in w8; a write to +0x418 would be overwritten
// by that store. No flag is changed for controller-only input.
static void camera_activity(Cpu *c) {
if (mouse_input_object && mouse_input_object == c->x[20]) {
uint32_t flags = (uint32_t)c->x[8];
c->x[8] = (flags | 0x11u) & ~0x28u;
mouse_input_object = 0;
}
uint64_t d9, d8;
memcpy(&d9, (const void *)(uintptr_t)(c->sp + 8), sizeof d9);
memcpy(&d8, (const void *)(uintptr_t)(c->sp + 16), sizeof d8);
c->v[9] = d9;
c->v[8] = d8;
}
__attribute__((constructor)) static void mouse_direct_register(void) {
rt_register_host(HOST_MOUSE_DIRECT, camera_input);
rt_register_host(HOST_MOUSE_ACTIVITY, camera_activity);
rt_register_host(HOST_MOUSE_ORBIT_BEGIN, orbit_begin);
rt_register_host(HOST_MOUSE_ORBIT_ANGLES, orbit_angles);
rt_register_host(HOST_MOUSE_HAND, hand_input);
}
#endif
+37 -17
View File
@@ -750,14 +750,17 @@ static void camera_overlay(void) {
// The button prompts' folders (input_prompts_folder) and whether each had a manifest next to romfs-index.bin at start;
// the one the settings asked for at start, the one overlay_init loaded (NULL: the game's own prompts) and why the first
// did not load (ROMFS_PROMPTS_*). The menu compares them with the settings in effect (ui/menu.cpp prompts_note).
static struct { const char *name; int ready; } prompts_folders[2];
// romfs-patches-pc keeps that name, but at a game resolution of another shape than 16:9 its files come from pc_dir,
// romfs-patches-pc-<w>x<h> (overlay_init).
static struct { const char *name; int ready; } prompts_folders[3];
static const char *prompts_wanted, *prompts_loaded;
static int prompts_off;
static char pc_dir[64];
const char *romfs_prompts(void) { return prompts_loaded; }
int romfs_prompts_ready(const char *folder) {
for (int i = 0; i < 2; i++)
for (int i = 0; i < 3; i++)
if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready;
return 0;
}
@@ -798,6 +801,9 @@ static void overlay_init(void) {
// keeps the Switch prompts. So does a RomFS mod (the TOTK_ROMFS_MODS manifest or a player mod) that replaces one of
// the prompts' fonts: romfs-patches loads in their place, so the mod's file is not served beside prompts files made
// for the game's own. A mod's resource size table is no clash: restbl_overlay merges it with the prompts' one.
// prompts = pc takes romfs-patches-pc whatever the pad layout, and at a game resolution of another shape
// romfs-patches-pc-<w>x<h> (make_romfs_patches.py --prompts pc --aspect): it carries that shape's UI layout too, so
// it replaces romfs-patches-<w>x<h> as romfs-patches-pc replaces romfs-patches.
char def[2100], path[2100];
const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS");
int wide = 0;
@@ -813,34 +819,46 @@ static void overlay_init(void) {
"(tools/make_romfs_patches.py --aspect %ux%u)", out[0], out[1], out[0], out[1]);
}
}
static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each folder
for (int i = 0; i < 2; i++) {
prompts_folders[i].name = input_prompts_folder(PROMPTS_XBOX, layouts[i]);
static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each Xbox folder, then the PC one
for (int i = 0; i < 3; i++) {
const char *name = i < 2 ? input_prompts_folder(PROMPTS_XBOX, layouts[i]) : input_prompts_folder(PROMPTS_PC, 0);
const char *dir = name;
if (i == 2) {
if (wide) snprintf(pc_dir, sizeof pc_dir, "%s-%ux%u", name, out[0], out[1]);
else snprintf(pc_dir, sizeof pc_dir, "%s", name);
dir = pc_dir;
}
prompts_folders[i].name = name;
prompts_folders[i].ready =
snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, prompts_folders[i].name) < (int)sizeof path &&
plat_file_exists(path);
snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, dir) < (int)sizeof path && plat_file_exists(path);
}
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
prompts_wanted = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
int pick = input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), shaped = wide && pick == PROMPTS_PC;
const char *style = pick == PROMPTS_PC ? "keyboard and mouse" : "Xbox";
prompts_wanted = input_prompts_folder(pick, layout);
prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK
: wide ? ROMFS_PROMPTS_SHAPE
: patches ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? ROMFS_PROMPTS_MISSING
: wide && !shaped ? ROMFS_PROMPTS_SHAPE
: patches && !wide ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? (shaped ? ROMFS_PROMPTS_SHAPE : ROMFS_PROMPTS_MISSING)
: ROMFS_PROMPTS_OK;
restbl_find();
size_t first = noverlay;
if (prompts_wanted && prompts_off == ROMFS_PROMPTS_OK) {
snprintf(path, sizeof path, "%s/%s", index_dir, prompts_wanted); // fits: its manifest path did
// fits: its manifest path did
snprintf(path, sizeof path, "%s/%s", index_dir, shaped ? pc_dir : prompts_wanted);
if (overlay_load(path, 1, 0)) {
prompts_loaded = prompts_wanted;
rt_log("RomFS overlay: Xbox button prompts (%s)", path);
rt_log("RomFS overlay: %s button prompts (%s)", style, path);
if (shaped) patches = NULL; // in place of romfs-patches-<w>x<h>, whose UI layout it carries
} else {
prompts_off = ROMFS_PROMPTS_FAILED;
rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", path);
}
} else if (prompts_wanted) {
rt_log("RomFS overlay: prompts = xbox, but %s; Switch prompts stay",
prompts_off == ROMFS_PROMPTS_SHAPE ? "the game resolution takes its own UI layout"
rt_log("RomFS overlay: prompts = %s, but %s; Switch prompts stay", pick == PROMPTS_PC ? "pc" : "xbox",
prompts_off == ROMFS_PROMPTS_SHAPE ? (shaped ? "the game resolution has no romfs-patches-pc-<w>x<h> "
"(tools/make_romfs_patches.py --prompts pc --aspect)"
: "the game resolution takes its own UI layout")
: prompts_off == ROMFS_PROMPTS_PATCHES ? "TOTK_ROMFS_PATCHES is set"
: "their folder has no manifest.tsv (run the setup again)");
}
@@ -856,11 +874,13 @@ static void overlay_init(void) {
mods_overlay_init();
const char *clash = prompts_loaded ? overlay_clash(first, prompts_end, mods_first, noverlay) : NULL;
if (clash) {
rt_log("RomFS overlay: a RomFS mod replaces %s, which the Xbox prompts change too; Switch prompts stay", clash);
rt_log("RomFS overlay: a RomFS mod replaces %s, which the %s prompts change too; Switch prompts stay", clash,
style);
overlay_drop(first, prompts_end);
prompts_loaded = NULL;
prompts_off = ROMFS_PROMPTS_MODS;
if (plain_ok) overlay_load(plain, 0, 0);
if (shaped) overlay_load(def, 0, 0);
else if (plain_ok) overlay_load(plain, 0, 0);
}
restbl_collect();
overlay_contest();
+4 -2
View File
@@ -18,7 +18,7 @@ extern "C" {
void rt_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
}
static_assert(UI_BIND_RSTICK_DOWN - UI_BIND_A == ACTION_COUNT - 1, "UI_BIND_* follow the actions");
static_assert(UI_BIND_SHAKE - UI_BIND_A == ACTION_COUNT - 1 && B_SHAKE == ACTION_COUNT - 1, "UI_BIND_* follow the actions");
static_assert(UI_BIND_DESC_MINUS - UI_BIND_DESC_A == B_MINUS, "UI_BIND_DESC_* follow the actions");
static_assert(UI_KEY_PAGEDOWN - UI_KEY_SPACE == KEY_PAGEDOWN - KEY_SPACE, "UI_KEY_* follow the key ids");
static_assert(UI_PAD_RPADDLE2 - UI_PAD_SOUTH == PAD_RPADDLE2 - PAD_SOUTH && PAD_RPADDLE2 == PAD_COUNT - 1,
@@ -48,6 +48,7 @@ static const char *action_label(int a) { return menu_text((UiTextId)(UI_BIND_A +
static UiTextId action_desc(int a) {
if (a <= B_MINUS) return (UiTextId)(UI_BIND_DESC_A + a);
if (a <= B_DOWN) return UI_BIND_DESC_DPAD;
if (a == B_SHAKE) return UI_BIND_DESC_SHAKE;
return a <= B_SL_DOWN ? UI_BIND_DESC_MOVE : UI_BIND_DESC_CAMERA;
}
@@ -168,7 +169,7 @@ static void row_action(int a, const InputMap &m, int layout) {
a >= B_SL_LEFT ? menu_text(a <= B_SL_DOWN ? UI_PAD_LSTICK : UI_PAD_RSTICK)
: np ? pad_label(p[0])
: ""};
const bool enabled[3] = {true, true, a < B_SL_LEFT}; // the sticks stay sticks
const bool enabled[3] = {true, true, a < B_SL_LEFT}; // the sticks stay sticks (and the shake is the right stick's)
char key[32];
snprintf(key, sizeof key, "BIND_%s", input_action_name(a));
const char *note = g_note_action == a && plat_now_ns() < g_note_until ? g_note : nullptr;
@@ -236,6 +237,7 @@ void binds_rows(float scale) {
for (int a : kMove) row_action(a, m, layout);
opt_group(UI_BINDS_GROUP_CAMERA);
for (int a : kCamera) row_action(a, m, layout);
row_action(B_SHAKE, m, layout); // keys only; its controller cell shows the right stick, which the pad shakes itself
ImGui::Dummy(ImVec2(0, 6 * scale));
g_reset_asked = opt_button("##binds_reset", UI_BINDS_RESET, UI_BINDS_RESET_DESC);
}
+10 -4
View File
@@ -773,8 +773,11 @@ static const char *prompts_note(bool *restart) {
const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts();
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
if (want == used || (want && used && !strcmp(want, used))) return nullptr;
if (want && !romfs_prompts_ready(want)) return menu_text(UI_MENU_PROMPTS_MISSING);
switch (romfs_prompts_off(want)) {
// A game resolution of another shape needs a folder of its own for the PC prompts (romfs-patches-pc-<w>x<h>), which
// the setup does not write: the shape is the reason then, not the setup.
int off = romfs_prompts_off(want);
if (want && !romfs_prompts_ready(want) && off != ROMFS_PROMPTS_SHAPE) return menu_text(UI_MENU_PROMPTS_MISSING);
switch (off) {
case ROMFS_PROMPTS_FAILED: return menu_text(UI_MENU_PROMPTS_FAILED);
case ROMFS_PROMPTS_SHAPE: return menu_text(UI_MENU_PROMPTS_OFF_SHAPE);
case ROMFS_PROMPTS_MODS: return menu_text(UI_MENU_PROMPTS_OFF_MODS);
@@ -827,16 +830,19 @@ static void tab_controls(float scale) {
opt_begin("##controls", scale);
static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX};
opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 3, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note());
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX};
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC};
bool restart;
const char *note = prompts_note(&restart);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 2, UI_MENU_PROMPTS_DESC, note);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 3, UI_MENU_PROMPTS_DESC, note);
bool ask = restart && opt_button("##restart", UI_MENU_RESTART, UI_MENU_RESTART_DESC);
opt_toggle("TOTK_MOTION", UI_MENU_MOTION, UI_MENU_MOTION_DESC);
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);
static const UiTextId mouse_modes[] = {UI_MENU_MOUSE_STICK, UI_MENU_MOUSE_DIRECT};
opt_choice("TOTK_MOUSE_MODE", UI_MENU_MOUSE_MODE, mouse_modes, 2, UI_MENU_MOUSE_MODE_DESC);
opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f");
opt_toggle("TOTK_MENU_CURSOR", UI_MENU_MENU_CURSOR, UI_MENU_MENU_CURSOR_DESC);
row_walk_key();
opt_slider("TOTK_WALK_SCALE", UI_MENU_WALK_SCALE, 0.2f, 0.9f, UI_MENU_WALK_SCALE_DESC, 0.01f, "%.2f");
// Analog sticks: one dead zone row per stick, falling back to TOTK_STICK_DEADZONE (both sticks) while unset. With
+54 -12
View File
@@ -241,10 +241,11 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_DESC] = "Which controller's buttons the game's prompts show. Nintendo: the game's own. Xbox: LB, "
"RB, LT, RT, Menu, View and a d-pad cross, and A, B, X and Y as labelled on the button "
"the layout above presses (with Nintendo (A right) the right button is labelled B, so the "
"prompts for A show B). The game reads its prompts at start, so they change after a "
"restart. They are part of the game's files, so a button you remap in Controls keeps its "
"old prompt on screen.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox",
"prompts for A show B). PC: the keys and mouse buttons of the keyboard's default layout "
"(E, Shift, Space, left click...) and the mouse for the camera. The game reads its prompts "
"at start, so they change after a restart. They are part of the game's files, so a button "
"you remap in Controls keeps its old prompt on screen.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", [UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_PROMPTS_MISSING] = "prompt files missing: run the setup again",
[UI_MENU_PROMPTS_FAILED] = "prompt files damaged: run the setup again",
[UI_MENU_PROMPTS_RESTART] = "prompts change after restart",
@@ -261,6 +262,12 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[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_MODE] = "Mouse camera",
[UI_MENU_MOUSE_MODE_DESC] = "Direct: the camera turns by how far the mouse moves, as in a PC game, with no stick dead zone or curve (game 1.4.3; other versions use stick emulation). Stick emulation: the mouse acts as the right stick.",
[UI_MENU_MOUSE_STICK] = "Stick emulation",
[UI_MENU_MOUSE_DIRECT] = "Direct",
[UI_MENU_MENU_CURSOR] = "Mouse in the game's menus",
[UI_MENU_MENU_CURSOR_DESC] = "In the game's own menus (title, inventory, shops, dialogue choices) the pointer shows: the item under it is selected, left click confirms, right click goes back. Only after the mouse or a key was used last, so a gamepad sees the menus unchanged (game 1.4.3).",
[UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity",
[UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.",
[UI_MENU_WALK_KEY] = "Walk key",
@@ -302,6 +309,9 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_BIND_DESC_MOVE] = "Moves Link like the left stick. The controller's left stick always works too.",
[UI_BIND_DESC_CAMERA] = "Turns the camera like the right stick. The mouse and the controller's right stick always "
"work too.",
[UI_BIND_SHAKE] = "Shake the camera stick",
[UI_BIND_DESC_SHAKE] = "Swings the right stick left and right for the game: detaches a fused part from what "
"Ultrahand holds. Holding the key keeps shaking.",
[UI_KEY_SPACE] = "Space", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Left Shift", [UI_KEY_LCTRL] = "Left Ctrl",
[UI_KEY_UP] = "Up arrow", [UI_KEY_DOWN] = "Down arrow", [UI_KEY_LEFT] = "Left arrow",
[UI_KEY_RIGHT] = "Right arrow",
@@ -692,10 +702,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_DESC] = "Кнопки какого контроллера показывают подсказки игры. Nintendo: как в самой игре. Xbox: "
"LB, RB, LT, RT, Menu, View и крестовина, а A, B, X и Y подписаны так же, как кнопка, "
"которую нажимает раскладка выше (в Nintendo (A справа) правая кнопка подписана B, и "
"подсказки A показывают B). Игра читает подсказки при запуске, так что они меняются после "
"перезапуска. Подсказки записаны в файлах игры, поэтому у кнопки, переназначенной на "
"вкладке управления, на экране остаётся прежняя подсказка.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox",
"подсказки A показывают B). PC: клавиши и кнопки мыши стандартной раскладки клавиатуры "
"(E, Shift, пробел, левый клик...) и мышь для камеры. Игра читает подсказки при запуске, "
"так что они меняются после перезапуска. Подсказки записаны в файлах игры, поэтому у "
"кнопки, переназначенной на вкладке управления, на экране остаётся прежняя подсказка.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", [UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова",
[UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова",
[UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска",
@@ -712,6 +723,12 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_LSTICK_DEADZONE] = "Мёртвая зона левого стика", [UI_MENU_RSTICK_DEADZONE] = "Мёртвая зона правого стика",
[UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами: отпустите стик, посмотрите «стик сейчас» и поставьте мёртвую зону на несколько процентов выше.",
[UI_MENU_STICK_DEADZONE_NOW] = "стик сейчас: %.0f %%",
[UI_MENU_MOUSE_MODE] = "Управление мышью",
[UI_MENU_MOUSE_MODE_DESC] = "Прямое: камера поворачивается на столько, на сколько сдвинута мышь, как в играх для ПК, без мёртвой зоны и кривой стика (версия игры 1.4.3; на других версиях эмуляция стика). Эмуляция стика: мышь работает как правый стик.",
[UI_MENU_MOUSE_STICK] = "Эмуляция стика",
[UI_MENU_MOUSE_DIRECT] = "Прямое",
[UI_MENU_MENU_CURSOR] = "Мышь в меню игры",
[UI_MENU_MENU_CURSOR_DESC] = "В меню самой игры (заставка, инвентарь, магазины, варианты ответа) появляется указатель: пункт под ним выбирается, левый щелчок подтверждает, правый возвращает назад. Только если последними использовались мышь или клавиатура, поэтому с геймпадом меню не меняются (версия игры 1.4.3).",
[UI_MENU_MOUSE_SENS] = "Чувствительность мыши",
[UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.",
[UI_MENU_WALK_KEY] = "Клавиша шага",
@@ -756,6 +773,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_BIND_DESC_MOVE] = "Двигает Линка, как левый стик. Левый стик контроллера тоже всегда работает.",
[UI_BIND_DESC_CAMERA] = "Поворачивает камеру, как правый стик. Мышь и правый стик контроллера тоже всегда "
"работают.",
[UI_BIND_SHAKE] = "Встряхнуть стик камеры",
[UI_BIND_DESC_SHAKE] = "Качает правый стик влево-вправо: отцепляет приклеенную деталь от того, что держит "
"Ультрарука. Пока клавиша зажата, тряска продолжается.",
[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] = "Стрелка вправо",
@@ -1108,6 +1128,9 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
"funciona.",
[UI_BIND_DESC_CAMERA] = "Gira a câmera como o analógico direito. O mouse e o analógico direito do controle também "
"sempre funcionam.",
[UI_BIND_SHAKE] = "Sacudir o analógico da câmera",
[UI_BIND_DESC_SHAKE] = "Balança o analógico direito para os lados: solta uma peça fundida do que a Ultramão segura. "
"Segurar a tecla continua sacudindo.",
[UI_KEY_SPACE] = "Espaço", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Shift esquerdo",
[UI_KEY_LCTRL] = "Ctrl esquerdo",
[UI_KEY_UP] = "Seta para cima", [UI_KEY_DOWN] = "Seta para baixo", [UI_KEY_LEFT] = "Seta para a esquerda",
@@ -1317,11 +1340,20 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_DESC] = "Os botões de qual controle os ícones do jogo mostram. Nintendo: os do próprio jogo. "
"Xbox: LB, RB, LT, RT, Menu, Exibir e uma cruz direcional, e A, B, X e Y com a letra do "
"botão que o layout acima aperta (com Nintendo (A à direita) o botão da direita tem a "
"letra B, então os ícones de A mostram B). O jogo lê os ícones ao iniciar, então eles "
"mudam depois de reiniciar. Eles fazem parte dos arquivos do jogo, então um botão "
"remapeado em Controles continua com o ícone antigo na tela.",
"letra B, então os ícones de A mostram B). PC: as teclas e os botões do mouse do layout "
"padrão do teclado (E, Shift, Espaço, clique esquerdo...) e o mouse para a câmera. O jogo "
"lê os ícones ao iniciar, então eles mudam depois de reiniciar. Eles fazem parte dos "
"arquivos do jogo, então um botão remapeado em Controles continua com o ícone antigo na "
"tela.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
[UI_MENU_PROMPTS_XBOX] = "Xbox",
[UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_MOUSE_MODE] = "Câmera com o mouse",
[UI_MENU_MOUSE_MODE_DESC] = "Direta: a câmera gira o quanto o mouse se move, como num jogo de PC, sem zona morta nem curva do analógico (jogo 1.4.3; as outras versões usam a emulação do analógico). Emulação do analógico: o mouse age como o analógico direito.",
[UI_MENU_MOUSE_STICK] = "Emulação do analógico",
[UI_MENU_MOUSE_DIRECT] = "Direta",
[UI_MENU_MENU_CURSOR] = "Mouse nos menus do jogo",
[UI_MENU_MENU_CURSOR_DESC] = "Nos menus do próprio jogo (título, inventário, lojas, escolhas de diálogo) o ponteiro aparece: o item sob ele fica selecionado, o clique esquerdo confirma e o direito volta. Só depois de usar o mouse ou uma tecla por último, então com um controle os menus ficam como antes (jogo 1.4.3).",
[UI_MENU_PROMPTS_MISSING] = "faltam os arquivos dos ícones: execute a instalação de novo",
[UI_MENU_PROMPTS_FAILED] = "arquivos dos ícones danificados: execute a instalação de novo",
[UI_MENU_PROMPTS_RESTART] = "os ícones mudam após reiniciar",
@@ -1655,6 +1687,8 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_BIND_DESC_DPAD] = "快捷选择。",
[UI_BIND_DESC_MOVE] = "像左摇杆一样移动林克。手柄的左摇杆始终可用。",
[UI_BIND_DESC_CAMERA] = "像右摇杆一样转动视角。鼠标和手柄的右摇杆始终可用。",
[UI_BIND_SHAKE] = "晃动视角摇杆",
[UI_BIND_DESC_SHAKE] = "让右摇杆左右晃动:把究极手抓着的物体上粘着的零件拆下。按住该键会一直晃动。",
[UI_KEY_SPACE] = "空格",
[UI_KEY_TAB] = "Tab",
[UI_KEY_LSHIFT] = "左 Shift",
@@ -1915,9 +1949,17 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS] = "按键提示",
[UI_MENU_PROMPTS_DESC] = "游戏的按键提示显示哪种手柄的按键。Nintendo:游戏原有的提示。Xbox:LB、RB、LT、RT、Menu、View 和十字键,以及上方布局所按下的按键上标注的 "
"A、B、X、Y(使用 Nintendo(A 在右)时右侧按键标为 B,因此 A 的提示显示 "
"B)。游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。",
"B)。PC:键盘默认布局的按键和鼠标按键(E、Shift、空格、左键……),镜头用鼠标。"
"游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
[UI_MENU_PROMPTS_XBOX] = "Xbox",
[UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_MOUSE_MODE] = "鼠标视角",
[UI_MENU_MOUSE_MODE_DESC] = "直接:镜头按鼠标移动的距离转动,与电脑游戏相同,没有摇杆死区和响应曲线(游戏 1.4.3;其他版本使用摇杆模拟)。摇杆模拟:鼠标相当于右摇杆。",
[UI_MENU_MOUSE_STICK] = "摇杆模拟",
[UI_MENU_MOUSE_DIRECT] = "直接",
[UI_MENU_MENU_CURSOR] = "在游戏菜单中使用鼠标",
[UI_MENU_MENU_CURSOR_DESC] = "在游戏自身的菜单中(标题、背包、商店、对话选项)显示指针:指针下的项目被选中,左键确认,右键返回。仅在最后使用的是鼠标或键盘时生效,因此使用手柄时菜单保持不变(游戏 1.4.3)。",
[UI_MENU_PROMPTS_MISSING] = "缺少按键提示文件:请重新运行安装程序",
[UI_MENU_PROMPTS_FAILED] = "按键提示文件已损坏:请重新运行安装程序",
[UI_MENU_PROMPTS_RESTART] = "按键提示重启后生效",
+6 -4
View File
@@ -99,7 +99,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_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX,
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC,
// the notes under the prompts: their files are missing or damaged, they change after restart, or why they are off
UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE,
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
@@ -107,6 +107,8 @@ typedef enum {
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
UI_MENU_GROUP_STICKS, UI_MENU_LSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC,
UI_MENU_STICK_DEADZONE_NOW, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC,
UI_MENU_MOUSE_MODE, UI_MENU_MOUSE_MODE_DESC, UI_MENU_MOUSE_STICK, UI_MENU_MOUSE_DIRECT,
UI_MENU_MENU_CURSOR, UI_MENU_MENU_CURSOR_DESC,
UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC,
UI_MENU_WALK_KEY, UI_MENU_WALK_KEY_DESC, UI_MENU_WALK_KEY_TAKEN, UI_MENU_WALK_SCALE, UI_MENU_WALK_SCALE_DESC,
@@ -119,15 +121,15 @@ typedef enum {
UI_BINDS_TAKEN, // "%s was taken from %s": the key, the action that lost it
UI_BINDS_SWAPPED, // "%s swapped with %s": the two actions
UI_BINDS_RESET, UI_BINDS_RESET_DESC,
// the actions, in action order (input_map.h B_A .. B_SR_DOWN)
// the actions, in action order (input_map.h B_A .. B_SHAKE)
UI_BIND_A, UI_BIND_B, UI_BIND_X, UI_BIND_Y, UI_BIND_LCLICK, UI_BIND_RCLICK, UI_BIND_L, UI_BIND_R, UI_BIND_ZL,
UI_BIND_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_RSTICK_LEFT, UI_BIND_RSTICK_UP, UI_BIND_RSTICK_RIGHT, UI_BIND_RSTICK_DOWN, UI_BIND_SHAKE,
// what an action does in the world, in action order up to Minus
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_BIND_DESC_DPAD, UI_BIND_DESC_MOVE, UI_BIND_DESC_CAMERA, UI_BIND_DESC_SHAKE,
// key names, in key id order KEY_SPACE .. KEY_PAGEDOWN (letters, digits, F keys and punctuation show as themselves)
UI_KEY_SPACE, UI_KEY_TAB, UI_KEY_LSHIFT, UI_KEY_LCTRL, 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, UI_KEY_MOUSE_X2,
+311
View File
@@ -0,0 +1,311 @@
"""Check the direct camera hook's register contract and raw-count routing without game data.
Usage: python tests/mouse_direct_check.py --cc <clang.exe>
"""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdio.h>
#include "mouse_direct.c"
static int raw_x, raw_y, takes, captured=1, foreground=1, allowed=1, mode=1, patched=1, selecting;
static float ratio=0.5f;
static uint64_t now=1000000000;
static GuestFn hook, activity_hook, begin_hook, angles_hook, hand_hook;
const char *cfg_get(const char *key) { (void)key; return mode ? "direct" : "stick"; }
const char *cfg_value(const char *key) { return cfg_get(key); }
double cfg_double(const char *key) { (void)key; return 1; }
int rt_patch_set(const char *s) { (void)s; return 0; }
int rt_patch_enabled(int s) { (void)s; return patched; }
int ikb_captured(void) { return captured; }
int ikb_foreground(void) { return foreground; }
int input_cursor_allowed(void) { return allowed; }
int input_direct_mouse_selector_active(void) { return selecting; }
void ikb_mouse_take(int32_t *x, int32_t *y) { ++takes; *x=raw_x; *y=raw_y; raw_x=raw_y=0; }
void input_direct_mouse_sample(int enabled, int32_t *x, int32_t *y) {
*x=*y=0;
if(enabled && captured && foreground && allowed) ikb_mouse_take(x,y);
}
uint64_t plat_now_ns(void) { return now; }
int frame_step_realtime(void) { return 1; }
double frame_step_limit_hz(void) { return 60; }
void *rt_patch_page(void) { return &ratio; }
void rt_register_host(uint64_t addr, GuestFn fn) {
if(addr==HOST_MOUSE_DIRECT) hook=fn; else if(addr==HOST_MOUSE_ACTIVITY) activity_hook=fn;
else if(addr==HOST_MOUSE_ORBIT_BEGIN) begin_hook=fn; else if(addr==HOST_MOUSE_ORBIT_ANGLES) angles_hook=fn;
else if(addr==HOST_MOUSE_HAND) hand_hook=fn; else abort();
}
void plat_mutex_lock(PlatMutex *m) { (void)m; }
void plat_mutex_unlock(PlatMutex *m) { (void)m; }
void rt_log(const char *fmt, ...) { (void)fmt; }
static float scalar(__uint128_t v) { float f; memcpy(&f,&v,4); return f; }
int main(void) {
assert(hook && activity_hook);
Cpu c, expected;
unsigned char target[0x500] = {0};
memset(&c, 0x5a, sizeof c);
c.x[20]=(uintptr_t)target; c.x[21]=0; c.v[9]=c.v[10]=0;
expected=c;
raw_x=100; raw_y=-50;
hook(&c);
assert(fabsf(scalar(c.v[9])-2)<1e-6f);
assert(fabsf(scalar(c.v[10])-1)<1e-6f);
float stored; memcpy(&stored,target+0x420,4); assert(stored==scalar(c.v[9]));
expected.v[9]=c.v[9]; expected.v[10]=c.v[10]; assert(!memcmp(&expected,&c,sizeof c));
assert(input_direct_mouse_active());
// The next read sees no repeated movement. Gamepad/keyboard input is preserved.
expected=c; hook(&c); assert(!memcmp(&expected,&c,sizeof c));
// Equal mouse distance produces equal integrated input at 30, 60 and 144 Hz; there is no unit-circle clamp.
float rates[]={30,60,144};
for(int i=0;i<3;i++) {
ratio=30/rates[i]; raw_x=10000; raw_y=10000; c.v[9]=c.v[10]=0; hook(&c);
assert(fabsf(scalar(c.v[9])*ratio-100)<0.001f);
assert(fabsf(scalar(c.v[10])*ratio+100)<0.001f);
}
// One count is not discarded by a dead zone.
ratio=0.5f; raw_x=1; raw_y=0; c.v[9]=c.v[10]=0; hook(&c); assert(scalar(c.v[9])>0);
uint64_t stack[4]={0,0x123456789abcdef0ull,0x456789abcdef0123ull,0}; c.sp=(uintptr_t)stack;
// The flags are in w8 at the site: the game's next instruction stores w8 to +0x418, so memory is not touched.
uint32_t inactive=0x28, mem=0x77; memcpy(target+0x418,&mem,4);
c.x[8]=inactive; activity_hook(&c);
assert((uint32_t)c.x[8]==0x11);
uint32_t after; memcpy(&after,target+0x418,4); assert(after==mem);
assert(c.v[9]==stack[1] && c.v[8]==stack[2]);
// A controller-only update keeps the game's activity bits.
c.x[8]=inactive; activity_hook(&c); assert((uint32_t)c.x[8]==inactive);
// Disabled game camera input leaves raw counts for the menu's legacy mouse-to-stick path.
c.x[21]=1; raw_x=42; int before=takes; hook(&c);
assert(takes==before && raw_x==42 && !input_direct_mouse_active()); c.x[21]=0;
// Focus loss and host menus do not move the camera.
captured=0; before=takes; hook(&c); assert(takes==before); captured=1;
foreground=0; hook(&c); assert(takes==before); foreground=1;
allowed=0; hook(&c); assert(takes==before); allowed=1;
mode=0; hook(&c); assert(takes==before && !input_direct_mouse_active()); mode=1;
patched=0; hook(&c); assert(takes==before && !input_direct_mouse_active()); patched=1;
now+=150000001; assert(!input_direct_mouse_active());
// Orbit input removes the mouse from the stick path and writes equal degrees per count at the final angles.
unsigned char camera[0x300]={0}, frame[0x100]={0}, hand[0x300]={0};
uint64_t input_address=(uintptr_t)target; memcpy(camera+0x20,&input_address,8);
for(int rate=0;rate<3;rate++) {
memset(orbit_seen,0,sizeof orbit_seen);
ratio=30/rates[rate]; c.x[20]=(uintptr_t)target; c.x[21]=0; c.v[9]=c.v[10]=0;
raw_x=100; raw_y=-50; hook(&c);
guest_float_store((uintptr_t)camera+0x108,30); guest_float_store((uintptr_t)camera+0x120,40);
guest_float_store((uintptr_t)frame+0x44,30); guest_float_store((uintptr_t)frame+0x48,40);
c.x[0]=(uintptr_t)camera; begin_hook(&c);
assert(guest_float((uintptr_t)target+0x420)==0 && guest_float((uintptr_t)target+0x424)==0);
c.x[20]=(uintptr_t)camera; c.sp=(uintptr_t)frame; angles_hook(&c);
assert(fabsf(guest_float((uintptr_t)frame+0x44)-26)<0.0001f);
assert(fabsf(guest_float((uintptr_t)frame+0x48)-32)<0.0001f);
assert(fabsf(guest_float((uintptr_t)camera+0x15c)-26)<0.0001f);
c.x[0]=(uintptr_t)camera; begin_hook(&c); angles_hook(&c);
assert(fabsf(guest_float((uintptr_t)frame+0x48)-32)<0.0001f); // one sample cannot repeat next update
// The next input frame is stationary and the game's parameter update rewrites the old default target.
// Restoring the mouse's desired target makes the camera filter stay at the new pitch, not spring to zero.
c.x[20]=(uintptr_t)target; c.v[9]=c.v[10]=0; raw_x=raw_y=0; hook(&c);
guest_float_store((uintptr_t)camera+0x15c,0);
c.x[0]=(uintptr_t)camera; begin_hook(&c);
float current=guest_float((uintptr_t)camera+0x108), goal=guest_float((uintptr_t)camera+0x15c);
assert(fabsf(goal-26)<0.0001f && fabsf((current+goal)*0.5f-26)<0.0001f);
// A later game filter overwrites the pitch after the begin hook. Neither a stationary frame nor the next
// tiny mouse delta may integrate from that recentered result.
guest_float_store((uintptr_t)camera+0x108,0);
guest_float_store((uintptr_t)camera+0x11c,5);
guest_float_store((uintptr_t)camera+0x10c,20);
guest_float_store((uintptr_t)camera+0x88,0.3f);
guest_float_store((uintptr_t)frame+0x44,0);
c.x[20]=(uintptr_t)camera; angles_hook(&c);
assert(fabsf(guest_float((uintptr_t)frame+0x44)-26)<0.0001f);
assert(fabsf(guest_float((uintptr_t)camera+0x15c)-7)<0.0001f);
assert(fabsf(guest_float((uintptr_t)camera+0x108)-12)<0.0001f);
for(int i=0;i<100;i++) {
guest_float_store((uintptr_t)frame+0x44,0); angles_hook(&c);
assert(fabsf(guest_float((uintptr_t)camera+0x108)-12)<0.0001f);
}
c.x[20]=(uintptr_t)target; c.v[9]=c.v[10]=0; raw_y=1; hook(&c);
c.x[0]=(uintptr_t)camera; begin_hook(&c);
guest_float_store((uintptr_t)frame+0x44,0);
c.x[20]=(uintptr_t)camera; angles_hook(&c);
assert(fabsf(guest_float((uintptr_t)frame+0x44)-26.08f)<0.0001f);
// An explicit controller recenter still hands pitch back to the game.
uint64_t recenter=0x20; memcpy(target+0x148,&recenter,8);
c.x[20]=(uintptr_t)target; c.v[9]=c.v[10]=0; hook(&c);
c.x[0]=(uintptr_t)camera; begin_hook(&c);
guest_float_store((uintptr_t)frame+0x44,5);
c.x[20]=(uintptr_t)camera; angles_hook(&c);
assert(guest_float((uintptr_t)frame+0x44)==5);
memset(target+0x148,0,8);
memset(camera+0x88,0,4); memset(camera+0x10c,0,4); memset(camera+0x11c,0,4);
}
// A gamepad-only step (no mouse motion, no pitch hold) leaves the camera input and the angles as the game made them.
memset(orbit_seen,0,sizeof orbit_seen);
c.x[20]=(uintptr_t)target; c.x[21]=0; raw_x=raw_y=0; c.v[9]=c.v[10]=0;
{ float px=0.25f, py=-0.5f; memcpy(&c.v[9],&px,4); memcpy(&c.v[10],&py,4); }
hook(&c);
guest_float_store((uintptr_t)target+0x420,0.25f); guest_float_store((uintptr_t)target+0x424,0.75f);
guest_float_store((uintptr_t)frame+0x44,11); guest_float_store((uintptr_t)frame+0x48,22);
guest_float_store((uintptr_t)camera+0x15c,3);
c.x[0]=(uintptr_t)camera; begin_hook(&c);
assert(guest_float((uintptr_t)target+0x420)==0.25f && guest_float((uintptr_t)target+0x424)==0.75f);
c.x[20]=(uintptr_t)camera; c.sp=(uintptr_t)frame; angles_hook(&c);
assert(guest_float((uintptr_t)frame+0x44)==11 && guest_float((uintptr_t)frame+0x48)==22);
assert(guest_float((uintptr_t)camera+0x15c)==3);
guest_float_store((uintptr_t)camera+0x108,30); guest_float_store((uintptr_t)camera+0x120,40);
for(int count=0;count<100;count++) {
c.x[20]=(uintptr_t)target; c.x[21]=0; c.v[9]=c.v[10]=0; raw_x=1; raw_y=0; hook(&c);
c.x[0]=(uintptr_t)camera; begin_hook(&c); c.x[20]=(uintptr_t)camera;
guest_float_store((uintptr_t)frame+0x44,guest_float((uintptr_t)camera+0x108));
guest_float_store((uintptr_t)frame+0x48,guest_float((uintptr_t)camera+0x120));
angles_hook(&c);
}
assert(fabsf(guest_float((uintptr_t)camera+0x120)-32)<0.001f);
// A held object receives mouse deltas after its own curves, once per sample, including with camera input off.
c.x[20]=(uintptr_t)target; c.v[9]=c.v[10]=0; raw_x=100; raw_y=50; ratio=0.5f; hook(&c);
c.x[19]=(uintptr_t)hand; c.x[8]=0x12345678; c.v[15]=0;
guest_float_store((uintptr_t)frame+0x60,0); hand_hook(&c);
assert(fabsf(guest_float((uintptr_t)frame+0x60)-2)<0.00001f);
assert(fabsf(scalar(c.v[15])+1)<0.00001f);
hand_hook(&c); assert(fabsf(scalar(c.v[15])+1)<0.00001f);
c.x[21]=1; raw_x=5; raw_y=6; hook(&c); assert(raw_x==0 && raw_y==0 && input_direct_mouse_active());
// A radial selector retains its virtual cursor between mouse packets, including repeated HID polls.
float cursor[2]={0}; int32_t selector[2], held_selector[2];
input_direct_mouse_radial(100,50,1,cursor,selector);
held_selector[0]=selector[0]; held_selector[1]=selector[1];
for(int i=0;i<100;i++) {
input_direct_mouse_radial(0,0,1,cursor,selector);
assert(selector[0]==held_selector[0] && selector[1]==held_selector[1]);
}
input_direct_mouse_radial(-100,-50,1,cursor,selector); assert(!selector[0] && !selector[1]);
input_direct_mouse_radial(100000,100000,1,cursor,selector);
assert((int64_t)selector[0]*selector[0]+(int64_t)selector[1]*selector[1]<=32768ll*32768);
// Quick lists must not latch a wheel direction or automatically drain a large flick after the mouse stops.
InputMouseRow row={0}; uint64_t row_time=0;
input_direct_mouse_row(10000,1,row_time,&row,selector); assert(selector[0]==32767 && !selector[1]);
input_direct_mouse_row(0,1,row_time+10000000,&row,selector); assert(selector[0]==32767);
for(int i=1;i<=100;i++) {
input_direct_mouse_row(0,1,row_time+i*100000000ull,&row,selector); assert(!selector[0] && !selector[1]);
}
// Repeated HID polls do not rearm a pulse; a frame that skips its deadline must still observe neutral first.
row=(InputMouseRow){0};
for(int i=0;i<31;i++) { input_direct_mouse_row(1,1,0,&row,selector); assert(!selector[0]); }
input_direct_mouse_row(1,1,0,&row,selector); assert(selector[0]==32767);
input_direct_mouse_row(1000,1,100000000,&row,selector); assert(!selector[0]);
input_direct_mouse_row(1000,1,110000000,&row,selector); assert(!selector[0]);
input_direct_mouse_row(1000,1,140000000,&row,selector); assert(selector[0]==32767);
input_direct_mouse_row(-1000,1,141000000,&row,selector); assert(!selector[0]);
input_direct_mouse_row(-1,1,180000000,&row,selector); assert(selector[0]==-32767);
selecting=1; c.x[20]=(uintptr_t)target; raw_x=42; raw_y=0; before=takes; hook(&c);
assert(takes==before && raw_x==42); selecting=0; raw_x=0;
puts("direct mouse: register contract, routing, linearity, frame ratio and capture checks passed");
puts("direct mouse: final orbit angles, single-count motion, equal axes and held-object routing passed");
puts("direct mouse: persistent pitch target, radial cursor hold and gamepad-only steps untouched passed");
puts("direct mouse: final-pitch recenter rejection, explicit handoff and bounded quick-list steps passed");
}
'''
INPUT_HARNESS = r'''
#include <assert.h>
#include "input.c"
GfxStats gfx_counters;
InputMap input_map;
// Other input entry points are linked by PE unwind metadata; reaching them is outside this script-only test.
void ikb_cursor_update(void) { abort(); }
void ikb_menu_closed(void) { abort(); }
int cfg_bool(const char *key) { (void)key; abort(); }
int input_menu_gate(int *h,int open,uint64_t *b,int32_t s[4]) { (void)h;(void)open;(void)b;(void)s;abort(); }
int input_overlay_gate(int *h,uint64_t *b) { (void)h;(void)b;abort(); }
int menu_is_open(void) { abort(); }
void menu_toggle(void) { abort(); }
void menu_perf_cycle(void) { abort(); }
const char *input_action_name(int action) { (void)action;abort(); }
void input_map_configure(void) { abort(); }
int input_direct_mouse_active(void) { return 1; }
int input_direct_mouse_enabled(void) { return 1; }
static int row_calls, radial_calls, live_mouse;
void input_direct_mouse_row(int32_t dx,float sensitivity,uint64_t now,InputMouseRow *row,int32_t out[2]) {
(void)dx;(void)sensitivity;(void)now; row_calls++; out[0]=123;out[1]=0;row->direction=1;
}
void input_direct_mouse_radial(int32_t dx,int32_t dy,float sensitivity,float cursor[2],int32_t out[2]) {
(void)dx;(void)dy;(void)sensitivity;radial_calls++;cursor[0]=1;out[0]=456;out[1]=789;
}
static const char *script_path;
static uint64_t test_tick;
static int64_t test_world=-1;
const char *cfg_get(const char *key) {
if (!strcmp(key,"TOTK_INPUT_SCRIPT")) return script_path;
if (!strcmp(key,"TOTK_INPUT")) return "none";
return NULL;
}
unsigned cfg_version(void) { return 0; }
double cfg_double(const char *key) { (void)key; return 1; }
uint64_t frame_step_ticks(void) { return test_tick; }
int64_t frame_step_world_us(void) { return test_world; }
void rt_log(const char *fmt, ...) { (void)fmt; }
void plat_mutex_lock(PlatMutex *m) { (void)m; }
void plat_mutex_unlock(PlatMutex *m) { (void)m; }
int ikb_captured(void) { return live_mouse; }
int ikb_foreground(void) { return 0; }
void ikb_mouse_take(int32_t *x,int32_t *y) { *x=*y=0; }
uint64_t plat_now_ns(void) { return 1000000000ull; }
int main(int argc,char **argv) {
assert(argc==2); script_path=argv[1];
uint64_t buttons=0; int32_t left[2]={0},right[2]={0},dx,dy;
test_tick=10;
for(int i=0;i<3;i++) script_apply(&buttons,left,right);
input_direct_mouse_sample(1,&dx,&dy);
assert(dx==123 && dy==-45 && !buttons && !right[0] && !right[1]);
input_direct_mouse_sample(1,&dx,&dy); assert(!dx && !dy);
test_tick=20; script_apply(&buttons,left,right);
g_menu=1; input_direct_mouse_sample(1,&dx,&dy); assert(!dx && !dy);
g_menu=0; input_direct_mouse_sample(1,&dx,&dy); assert(!dx && !dy);
test_world=100000;
for(int i=0;i<3;i++) script_apply(&buttons,left,right);
rec=tmpfile(); assert(rec); rec_state=1;
input_direct_mouse_sample(1,&dx,&dy); assert(dx==-100 && dy==50);
rewind(rec); char line[128]; assert(fgets(line,sizeof line,rec));
assert(strstr(line,"MOUSE -100 50")); assert(!fgets(line,sizeof line,rec));
fclose(rec); rec_state=-1;
live_mouse=1;
mouse_camera(right,1); assert(radial_calls==1 && !row_calls && right[0]==456 && right[1]==789);
assert(input_direct_mouse_selector_active());
mouse_camera(right,2); assert(row_calls==1 && radial_calls==1 && right[0]==123 && !right[1]);
mouse_camera(right,0); assert(!input_direct_mouse_selector_active() && !right[0] && !right[1]);
mouse_camera(right,3); assert(row_calls==2 && right[0]==123 && !right[1]);
live_mouse=0; mouse_camera(right,3);
assert(!input_direct_mouse_selector_active() && !right[0] && !right[1]);
puts("direct mouse: one-shot script replay, host-menu blocking and raw-count recording passed");
puts("direct mouse: separate wheel/list routing, selector ownership and release passed");
}
'''
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--cc', required=True)
ap.add_argument('--deps', type=Path, help='dependency include directory (SDL3/Vulkan), to also check input scripts')
args = ap.parse_args()
with tempfile.TemporaryDirectory(prefix='totk-mouse-') as tmp:
folder = Path(tmp)
(folder / 'patches.h').write_text('#define RT_PATCH_PAGE 0x7003adf000ull\n')
source = folder / 'check.c'
source.write_text(HARNESS)
exe = folder / ('check.exe' if os.name == 'nt' else 'check')
link = [] if os.name == 'nt' else ['-lm']
subprocess.run([args.cc, '-O2', '-Wall', '-Wextra', '-I', str(folder), '-I', str(ROOT/'runtime'),
str(source), *link, '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True)
if args.deps:
source.write_text(INPUT_HARNESS)
script = folder / 'input.txt'
script.write_text('10 MOUSE 123 -45\n20 MOUSE 1000 0\n@100 MOUSE -100 50\n')
subprocess.run([args.cc, '-O2', '-flto', '-ffunction-sections', '-fdata-sections', '-Wl,--gc-sections', *(['-fuse-ld=lld', '-Wl,--exclude-all-symbols'] if os.name == 'nt' else []),
'-I', str(ROOT/'runtime'), '-I', str(args.deps), '-I', str(args.deps/'vma'),
str(source), *link, '-o', str(exe)], check=True)
subprocess.run([str(exe), str(script)], check=True)
if __name__ == '__main__':
main()
+59 -8
View File
@@ -1,8 +1,8 @@
"""tools/make_romfs_patches.py --prompts and tools/button_icons.py on a RomFS made here, with no game files: each prompt
names the label of the Xbox button that the pad layout presses, the shoulder buttons, triggers, Plus, Minus and the
d-pad are drawn as on an Xbox controller, the resource size table grows with the fonts, every other file and member
stays byte for byte, the same input gives the same output, and a RomFS the tool does not recognise fails before it
writes anything. Both game versions: 1.2.1 (Common.Product.110, 72x72 button guide images) and 1.4.3
d-pad are drawn as on an Xbox controller, the PC prompts draw every button as its key or mouse button (the defaults or
a totk.ini's bind_ lines), the resource size table grows with the fonts, every other file and member stays byte for
byte, the same input gives the same output, and a RomFS the tool does not recognise fails before it writes anything. Both game versions: 1.2.1 (Common.Product.110, 72x72 button guide images) and 1.4.3
(Common.Product.140, 108x108).
Run: .venv-py314\\Scripts\\python tests\\romfs_prompts_test.py
@@ -296,6 +296,11 @@ LETTERS_1 = {ord('L'): (560, polygon((60, 0), (480, 0), (480, 100), (160, 100),
rect(pen, 160, 400, 360, 600, True)]),
ord('R'): (560, lambda pen: [rect(pen, 60, 0, 460, 700), rect(pen, 160, 400, 360, 600, True)])}
LETTERS_2 = {ord('T'): (560, polygon((230, 0), (330, 0), (330, 600), (520, 600), (520, 700), (40, 700), (40, 600), (230, 600)))}
# The other characters the PC prompts' keys show (button_icons.PC_LABELS of the defaults): a block with a counter, each
# its own size.
LETTERS_2.update({ord(ch): (560, lambda pen, i=i: [rect(pen, 60, 0, 300 + 10 * i, 700), rect(pen, 120, 100, 240, 600, True)])
for i, ch in enumerate('ACDEFMQSW1234⇧G')})
PC_PANES = {'A': 'E', 'B': '↑', 'X': '▬', 'Y': 'L'} # the diamond's letters with the default keys
class Romfs:
@@ -316,7 +321,8 @@ class Romfs:
images = {f'Nt_KeyTex{b}_00': (R8_UNORM, size, rnd.randbytes(IMAGE)) for b in 'ABXY'}
images.update({'Nt_KeyTexL_00^z': (l_format, size, rnd.randbytes(IMAGE)),
'Nt_KeyTexZL_00': (R8_UNORM, size, rnd.randbytes(IMAGE)),
'Nt_KeyTexLSt_00': (R8_UNORM, size, rnd.randbytes(IMAGE))})
'Nt_KeyTexLSt_00': (R8_UNORM, size, rnd.randbytes(IMAGE)),
'Nt_KeyTexLSt_01': (R8_UNORM, size, rnd.randbytes(IMAGE))})
self.text_fonts = [bfotf(cff_font('Text1', LETTERS_1), 0x01020304), bfotf(cff_font('Text2', LETTERS_2), 0x0a0b0c0d)]
default = {'scft/External.bfotf': bfotf(cff_font('External', BUTTONS), 0x5a17c3e9), 'fnt/rest.bin': rnd.randbytes(700)}
if text_fonts:
@@ -388,7 +394,7 @@ class PromptsTest(unittest.TestCase):
cls.romfs = {v: Romfs(cls.base / v / 'romfs', v) for v in VERSIONS}
cls.outs = {}
for v, romfs in cls.romfs.items():
for style in ('plain', 'xbox', 'xbox-label'):
for style in ('plain', 'xbox', 'xbox-label', 'pc'):
out = cls.base / v / style
proc = romfs.run(out, *(() if style == 'plain' else ('--prompts', style)))
assert proc.returncode == 0, proc.stderr
@@ -485,7 +491,7 @@ class PromptsTest(unittest.TestCase):
self.assertEqual(after[member], before[member], member)
def test_resource_size_table_grows_with_the_fonts(self):
for romfs, style, out, summary in self.each():
for romfs, style, out, summary in self.each(('xbox', 'xbox-label', 'pc')):
with self.subTest(version=romfs.version, style=style):
table = restbl_sizes(romfs.read(out, romfs.restbl))
original = restbl_sizes(romfs.contents[romfs.restbl])
@@ -501,11 +507,12 @@ class PromptsTest(unittest.TestCase):
self.assertEqual(set(table), set(original))
def test_manifest_lists_what_changed_with_both_hashes(self):
for romfs, style, out, _ in self.each(('plain', 'xbox', 'xbox-label')):
for romfs, style, out, _ in self.each(('plain', 'xbox', 'xbox-label', 'pc')):
with self.subTest(version=romfs.version, style=style):
expect = {romfs.common}
if style != 'plain':
expect |= {DEFAULT_FONT, REGIONAL_FONT, romfs.restbl} | (set(romfs.mals) if style == 'xbox' else set())
expect |= {DEFAULT_FONT, REGIONAL_FONT, romfs.restbl}
expect |= set(romfs.mals) if style in ('xbox', 'pc') else set()
lines = manifest(out)
self.assertEqual(set(lines), expect)
for path, (size, sha, original) in lines.items():
@@ -513,6 +520,50 @@ class PromptsTest(unittest.TestCase):
self.assertEqual((int(size), sha), (len(data), hashlib.sha256(data).hexdigest()), path)
self.assertEqual(original, hashlib.sha256(romfs.files[path]).hexdigest(), path)
def test_pc_prompts_draw_every_button_as_its_key(self):
for romfs, _, out, _ in self.each(('pc',)):
with self.subTest(version=romfs.version):
original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
drawn = font(sarc_files(romfs.read(out, DEFAULT_FONT))['scft/External.bfotf'])
advances = icons.font_advances(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
pc = icons.pc_icons(icons.text_glyphs(romfs.text_fonts), advances)
self.assertIn(0xE05E, pc) # the left stick's W A S D
for cp in range(0xE040, 0xE069):
outline, advance = glyph(drawn, cp)
if cp in pc:
self.assertNotEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} drawn')
else:
self.assertEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} kept')
self.assertEqual(advance, glyph(original, cp)[1], f'U+{cp:04X} keeps its advance')
# The key's label is a hole: E is the key, the block and its counter.
self.assertEqual(sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE040)[0]), 3)
after = sarc_files(romfs.read(out, romfs.common))
new = bntx_images(after['timg/__Combined.bntx'])
size = VERSIONS[romfs.version]['size']
for name, cp in icons.PC_HUD_TEXTURES.items():
image = new[name][2]
pixels = bytes(image[icons.gob_offset(x, y, (size + 63) // 64, 16)] for y in range(size) for x in range(size))
self.assertEqual(pixels, icons.rasterize(pc[cp][1], size), name)
panes = pane_texts(after['blyt/DoCommand_00.bflyt'])
for b, letter in PC_PANES.items():
self.assertEqual(panes[f'T_{b}_00'], letter, f'diamond letter of {b}')
for path in romfs.mals:
texts = message_texts(sarc_files(romfs.read(out, path))['LayoutMsg/DoCommand_00.msbt'])
self.assertEqual((texts[f'T_{b}_00'], texts['T_Name_00']), (letter, 'A'), path)
def test_pc_prompts_follow_the_bind_lines(self):
romfs = self.romfs['v143']
ini = self.base / 'binds' / 'totk.ini'
ini.parent.mkdir(parents=True)
ini.write_text('[input]\n# bind_A = key:q\nbind_A = pad:east, key:F\nbind_B = pad:south\nbind_X = key:default\n',
encoding='utf-8')
out = self.base / 'binds' / 'out'
proc = romfs.run(out, '--prompts', 'pc', '--binds', str(ini))
self.assertEqual(proc.returncode, 0, proc.stderr)
panes = pane_texts(sarc_files(romfs.read(out, romfs.common))['blyt/DoCommand_00.bflyt'])
self.assertEqual({b: panes[f'T_{b}_00'] for b in PC_PANES}, {**PC_PANES, 'A': 'F'})
self.assertEqual(icons.pc_binds(ini.read_text(encoding='utf-8')), {**icons.PC_BINDS, 'A': 'f'})
def test_same_input_same_output_and_the_older_flag(self):
romfs = self.romfs['v121']
for flags in (('--prompts', 'xbox'), ('--xbox-prompts',)):
+6 -6
View File
@@ -156,8 +156,8 @@ LLVM_LINK_LIBS = ['-lpsapi', '-lbcrypt', '-luser32', '-lgdi32', '-ldwmapi', '-li
DEFAULT_DEPS = ROOT / 'toolchain' / 'deps-mingw'
# Runtime sources compiled per install, not in the library: romfs.c includes romfs_config.h, patches.c and ov_zstd.c
# the patches.h of the player's game version (its patch page is the page after that version's main; ov_zstd.c's host
# functions sit on it).
INSTALL_SIDE = {'romfs.c', 'patches.c', 'ov_zstd.c'}
# functions sit on it). mouse_direct.c also registers host callbacks relative to that version's patch page.
INSTALL_SIDE = {'romfs.c', 'patches.c', 'ov_zstd.c', 'mouse_direct.c'}
LIB_NAME = 'libtotkrt.a'
AR = UCRT / 'llvm-ar.exe' if WIN else on_path('llvm-ar')
WINDRES = UCRT / 'windres.exe' # runtime/totk.rc: the manifest of totk.exe
@@ -241,10 +241,10 @@ def write_if_changed(path, text):
def copy_romfs_patches(version, out):
"""totk.exe loads romfs-patches beside romfs-index.bin (runtime/romfs.c overlay_init). tools/make_romfs_patches.py
writes them into build/<version> only, so a build in another directory ran without the 60 fps overlay (the quick
menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox and
romfs-patches-xbox-label (the same with Xbox button prompts, make_romfs_patches.py --prompts) the same way when they
were made."""
for name in ('romfs-patches', 'romfs-patches-xbox', 'romfs-patches-xbox-label'):
menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox,
romfs-patches-xbox-label and romfs-patches-pc (the same with Xbox or keyboard and mouse button prompts,
make_romfs_patches.py --prompts) the same way when they were made."""
for name in ('romfs-patches', 'romfs-patches-xbox', 'romfs-patches-xbox-label', 'romfs-patches-pc'):
src = ROOT / 'build' / version / name
dst = out / name
if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file():
+178 -7
View File
@@ -1,6 +1,7 @@
# Adapted from MacNativeGames games/totk/scripts/make_button_icons.py @ 933b6a0 (MIT, Copyright (c) 2026
# MacNativeGames contributors).
"""Xbox button icons for the game's prompts, drawn on the player's machine for tools/make_romfs_patches.py --prompts.
"""Xbox and keyboard-and-mouse button icons for the game's prompts, drawn on the player's machine for
tools/make_romfs_patches.py --prompts.
The outlines are our own shapes with letters cut out of them in the game's own text fonts: nothing of the game is in
the repository.
@@ -9,13 +10,15 @@ Font/Font*.Nin_NX_NVN.bfarc.zs: private-use code points from U+E040 (A, B, X, Y,
Minus, the sticks). A .bfotf is an OpenType (CFF) font after an 8-byte header; from offset 4 on, every byte is XORed
with a 4-byte key, which the size in the header's second word gives away (bfotf_decode). redraw_font draws the shoulder
buttons, the triggers, Plus, Minus and the d-pad as an Xbox controller names them (LB RB, LT RT, Menu and View, a
cross), can swap the glyphs of the face buttons (A with B, X with Y), and has fontTools write the font again. The
archive then grows by a kilobyte or two, more than the game's resource size table allows it: grow_restbl raises those
entries (without it the game stops at start, MacNativeGames found).
cross), or every button as the key or mouse button the keyboard presses it with (pc_icons), can swap the glyphs of
the face buttons (A with B, X with Y), and has fontTools write the font again. The archive then grows by a kilobyte or
two, more than the game's resource size table allows it: grow_restbl raises those entries (without it the game stops at
start, MacNativeGames found).
The button guide in play (bottom right) draws L and ZL from images of the common layout archive instead
(timg/__Combined.bntx, Nt_KeyTexL_00 and Nt_KeyTexZL_00): bntx_redraw paints the same icons into them, the size
unchanged. The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations).
The button guide in play (bottom right) draws its buttons, L and ZL among them, from images of the common layout
archive instead (timg/__Combined.bntx, Nt_KeyTexL_00 and Nt_KeyTexZL_00): bntx_redraw paints the same icons into them,
the size unchanged. The Xbox prompts redraw L and ZL, the keyboard and mouse ones every image (PC_HUD_TEXTURES: A, B, X,
Y, L, ZL and the stick's two). Prompts drawn as fixed images (some tutorial animations) keep the Switch icons.
Needs fontTools (tools/requirements-installer.txt, tools/requirements-py314.txt).
"""
@@ -180,6 +183,174 @@ def xbox_icons(g):
}
# ---- keyboard and mouse prompts (--prompts pc): every button the keyboard drives, drawn as the key or mouse button
# bound to it, in the same filled-shape style. Each glyph keeps the advance of the game's own (a wider glyph runs into
# the text of a right-aligned guide).
# The keyboard defaults of runtime/input_map.c (input_map_reset; the totk.ini bind_ lines apply on top, pc_binds). The
# right stick is the camera, which the mouse drives; SHAKE is the key that shakes it (the mouse never does).
PC_BINDS = {
'A': 'e', 'B': 'lshift', 'X': 'space', 'Y': 'mouse_l', 'L': 'q', 'R': 'r', 'ZL': 'mouse_r', 'ZR': 'f',
'PLUS': 'tab', 'MINUS': 'm', 'LEFT': '1', 'UP': '2', 'RIGHT': '3', 'DOWN': '4', 'LCLICK': 'lctrl', 'RCLICK': 'c',
'LSTICK_UP': 'w', 'LSTICK_LEFT': 'a', 'LSTICK_DOWN': 's', 'LSTICK_RIGHT': 'd', 'SHAKE': 'g',
}
# What a key shows: its letter, a symbol or a short name (key names as in totk.ini; the rest show their name).
PC_LABELS = {
'lshift': '⇧', 'rshift': '⇧', 'lctrl': 'CTRL', 'rctrl': 'CTRL', 'lalt': 'ALT', 'tab': 'TAB',
'enter': 'ENT', 'backspace': 'BKSP', 'capslock': 'CAPS', 'insert': 'INS', 'delete': 'DEL', 'home': 'HOME',
'end': 'END', 'pageup': 'PGUP', 'pagedown': 'PGDN', 'up': '↑', 'down': '↓', 'left': '←',
'right': '→', 'num_add': '+', 'num_sub': '-', 'num_mul': '*', 'num_div': '/', 'num_decimal': '.',
'minus': '-', 'equals': '=', 'lbracket': '[', 'rbracket': ']', 'semicolon': ';', 'apostrophe': "'", 'comma': ',',
'period': '.', 'slash': '/', 'backslash': '\\', 'grave': '`', 'mouse_x1': 'M4', 'mouse_x2': 'M5',
}
# The one-letter panes around the action prompt (T_A_00 ...) are in the Normal font (Rodin B and Symbol): one character
# of it per key.
PC_LETTER_LABELS = {'lshift': '↑', 'rshift': '↑', 'space': '▬', 'mouse_l': 'L', 'mouse_r': 'R',
'mouse_m': 'M', 'lctrl': 'C', 'rctrl': 'C', 'tab': 'T'}
# The button guide's images in the pc style: every symbol mask of the action prompt. In the 1.4.3 Common archive
# LSt_00 shows the left stick tilted up (as U+E052) and LSt_01 the left stick (as U+E05E).
PC_HUD_TEXTURES = {'Nt_KeyTexA_00': 0xE040, 'Nt_KeyTexB_00': 0xE041, 'Nt_KeyTexX_00': 0xE042, 'Nt_KeyTexY_00': 0xE043,
'Nt_KeyTexL_00': 0xE044, 'Nt_KeyTexZL_00': 0xE046, 'Nt_KeyTexLSt_00': 0xE052,
'Nt_KeyTexLSt_01': 0xE05E}
PC_MOUSE = ('mouse_l', 'mouse_r', 'mouse_m')
def pc_binds(ini_text=None):
"""PC_BINDS with the first key of each bind_<action> line of a totk.ini text over it (a line without a key entry,
or with key:default, keeps the default)."""
binds = dict(PC_BINDS)
for line in (ini_text or '').splitlines():
line = line.split('#')[0].split(';')[0].strip()
if not line.lower().startswith('bind_') or '=' not in line:
continue
action, value = (s.strip() for s in line.split('=', 1))
keys = [e.strip()[4:].strip().lower() for e in value.split(',') if e.strip().lower().startswith('key:')]
keys = [k for k in keys if k != 'default']
if keys and action[5:].upper() in binds:
binds[action[5:].upper()] = keys[0]
return binds
def font_advances(blob):
"""Code point -> advance of every glyph of the button font (a .bfotf)."""
font = TTFont(io.BytesIO(bfotf_decode(blob)[0]))
return {cp: font['hmtx'][name][0] for cp, name in font.getBestCmap().items()}
def pc_letter(key):
"""The one character the panes around the action prompt show for key."""
if key in PC_LETTER_LABELS:
return PC_LETTER_LABELS[key]
return PC_LABELS.get(key, key.upper())[0]
def pc_icons(g, adv, binds=PC_BINDS):
"""Code point -> (advance, draw(pen)) for every button glyph but Home and Capture, drawn as the key or mouse button
binds puts on it. g: Glyphs for the key labels; adv: the game's advance of each glyph (font_advances), which each
drawing keeps."""
def mouse_body(pen, cx, y0, y1, lit=None):
"""A mouse seen from above; lit ('l', 'r', 'm' or None) its pressed button, filled, the others hollow."""
h = y1 - y0; r = h * 0.33; t = h * 0.07; gap = h * 0.035
x0, x1, mid = cx - r, cx + r, y0 + h * 0.52
rounded(pen, x0, y0, x1, y1, r * 0.9, r)
reverse = ReverseContourPen(pen) # holes; they never overlap each other or leave the body
ri = r - t
if lit in ('l', 'r'): # the seams around the pressed button
sx0, sx1 = (x0 + t, cx - gap) if lit == 'l' else (cx + gap, x1 - t)
polygon(reverse, [(sx0, mid - gap), (sx1, mid - gap), (sx1, mid + gap), (sx0, mid + gap)])
polygon(reverse, [(cx - gap, mid + gap), (cx + gap, mid + gap), (cx + gap, y1 - t), (cx - gap, y1 - t)])
if lit != 'l': # hollow left button, its outer top corner following the body
ix0, ix1 = x0 + t, cx - gap
reverse.moveTo((ix1, mid + gap)); reverse.lineTo((ix1, y1 - t)); reverse.lineTo((ix0 + ri, y1 - t))
reverse.curveTo((ix0 + ri - K * ri, y1 - t), (ix0, y1 - t - ri + K * ri), (ix0, y1 - t - ri))
reverse.lineTo((ix0, mid + gap)); reverse.closePath()
if lit != 'r':
ix0, ix1 = cx + gap, x1 - t
reverse.moveTo((ix0, mid + gap)); reverse.lineTo((ix1, mid + gap)); reverse.lineTo((ix1, y1 - t - ri))
reverse.curveTo((ix1, y1 - t - ri + K * ri), (ix1 - ri + K * ri, y1 - t), (ix1 - ri, y1 - t))
reverse.lineTo((ix0, y1 - t)); reverse.closePath()
if lit == 'm': # the wheel, filled over the gap between the hollow buttons
rounded(pen, cx - h * 0.06, mid + h * 0.12, cx + h * 0.06, mid + h * 0.36, h * 0.06)
def key_cap(pen, x0, y0, x1, y1, key):
"""A key: a rounded square with its label cut out; a mouse button draws the mouse."""
if key in PC_MOUSE:
mouse_body(pen, (x0 + x1) / 2, y0, y1, key[6:])
return
w, h = x1 - x0, y1 - y0
rounded(pen, x0, y0, x1, y1, min(w, h) * 0.18)
if key == 'space': # an open bracket lying on its back
t = h * 0.09
bx0, bx1, by0, by1 = x0 + w * 0.22, x1 - w * 0.22, y0 + h * 0.36, y0 + h * 0.60
polygon(ReverseContourPen(pen), [(bx0, by0), (bx1, by0), (bx1, by1), (bx1 - t, by1), (bx1 - t, by0 + t),
(bx0 + t, by0 + t), (bx0 + t, by1), (bx0, by1)])
return
label = PC_LABELS.get(key, key.upper())
cap = h * (0.52 if len(label) == 1 else 0.36 if len(label) == 2 else 0.26)
g.hole(pen, label, (x0 + x1) / 2, (y0 + y1) / 2, cap, w * 0.74)
def arrow(pen, cx, cy, d, s):
"""A filled arrowhead pointing d, s its half size."""
polygon(pen, {'up': [(cx - s, cy - s * 0.6), (cx + s, cy - s * 0.6), (cx, cy + s * 0.8)],
'down': [(cx + s, cy + s * 0.6), (cx - s, cy + s * 0.6), (cx, cy - s * 0.8)],
'left': [(cx + s * 0.6, cy - s), (cx + s * 0.6, cy + s), (cx - s * 0.8, cy)],
'right': [(cx - s * 0.6, cy + s), (cx - s * 0.6, cy - s), (cx + s * 0.8, cy)]}[d])
def one(key, advance):
def draw(pen):
side = min(advance - 80, Y1 - Y0)
key_cap(pen, (advance - side) / 2, Y0, (advance + side) / 2, Y1, key)
return advance, draw
def grid(cells, advance):
"""Small keys in a grid: cells = [(key, column, row)], row 0 on top."""
def draw(pen):
cols, rows = max(c for _, c, _ in cells) + 1, max(r for _, _, r in cells) + 1
gap = 24; size = min((advance - 60 - gap * (cols - 1)) / cols, (Y1 - Y0 - gap * (rows - 1)) / rows)
left, top = (advance - cols * size - gap * (cols - 1)) / 2, CY + (rows * size + gap * (rows - 1)) / 2
for key, c, r in cells:
x, y = left + c * (size + gap), top - (r + 1) * size - r * gap
key_cap(pen, x, y, x + size, y + size, key)
return advance, draw
def mouse_move(advance, *dirs):
"""The mouse, no button pressed, with an arrow for each direction the prompt means."""
def draw(pen):
mouse_body(pen, advance / 2, Y0 + 30, Y1 - 30)
off = (Y1 - Y0 - 60) * 0.33 + 70
spots = {'up': (advance / 2 + off, CY + 110), 'down': (advance / 2 + off, CY - 110),
'left': (advance / 2 - off, CY), 'right': (advance / 2 + off, CY)}
for d in dirs:
arrow(pen, *spots[d], d, 52)
return advance, draw
b = binds
up, left, down, right = b['LSTICK_UP'], b['LSTICK_LEFT'], b['LSTICK_DOWN'], b['LSTICK_RIGHT']
du, dl, dd, dr = b['UP'], b['LEFT'], b['DOWN'], b['RIGHT']
return {
**{cp: one(b[name], adv[cp]) for cp, name in ((0xE040, 'A'), (0xE041, 'B'), (0xE042, 'X'), (0xE043, 'Y'),
(0xE044, 'L'), (0xE045, 'R'), (0xE046, 'ZL'), (0xE047, 'ZR'),
(0xE04B, 'PLUS'), (0xE04C, 'MINUS'), (0xE056, 'LCLICK'),
(0xE057, 'RCLICK'))},
# the d-pad: its four keys as a cross (up on top), or the keys of the directions the prompt means
0xE049: grid([(du, 1, 0), (dl, 0, 1), (dd, 1, 1), (dr, 2, 1)], adv[0xE049]),
0xE060: one(du, adv[0xE060]), 0xE061: one(dd, adv[0xE061]), 0xE062: one(dl, adv[0xE062]),
0xE063: one(dr, adv[0xE063]), 0xE064: grid([(du, 0, 0), (dd, 0, 1)], adv[0xE064]),
0xE065: grid([(dl, 0, 0), (dr, 1, 0)], adv[0xE065]),
# the left stick: its keys (W A S D)
0xE05E: grid([(up, 1, 0), (left, 0, 1), (down, 1, 1), (right, 2, 1)], adv[0xE05E]),
0xE052: one(up, adv[0xE052]), 0xE050: one(down, adv[0xE050]), 0xE05A: one(left, adv[0xE05A]),
0xE058: one(right, adv[0xE058]), 0xE05C: grid([(up, 0, 0), (down, 0, 1)], adv[0xE05C]),
0xE054: grid([(left, 0, 0), (right, 1, 0)], adv[0xE054]),
# the right stick: the mouse
0xE05F: mouse_move(adv[0xE05F]), 0xE053: mouse_move(adv[0xE053], 'up'),
0xE051: mouse_move(adv[0xE051], 'down'), 0xE05B: mouse_move(adv[0xE05B], 'left'),
0xE059: mouse_move(adv[0xE059], 'right'), 0xE05D: mouse_move(adv[0xE05D], 'up', 'down'),
0xE055: mouse_move(adv[0xE055], 'left', 'right'),
# the right stick shaken: the shake key
0xE068: one(b['SHAKE'], adv[0xE068]),
}
def redraw_font(otf, icons, swaps=()):
"""The OpenType font otf with the glyphs of each (code point, code point) pair of swaps trading places (outlines and
horizontal metrics), then every code point of icons (code point -> (advance, draw)) drawn anew, written again by
+27 -10
View File
@@ -38,6 +38,11 @@ from the game's own files on the player's machine, nothing added (tools/button_i
every pad not labelled the Nintendo way), so the face buttons keep their letters; the action prompt's diamond keeps
the Switch positions (A on the right).
--xbox-prompts is the older name of --prompts xbox.
--prompts pc: keyboard and mouse prompts, for prompts = pc (romfs-patches-pc, or romfs-patches-pc-<w>x<h> with
--aspect): every button of the button font is drawn as the key or mouse button the keyboard defaults put on it
(button_icons.pc_icons; --binds <totk.ini> takes the first key of its bind_ lines instead), and so are the button
guide's images (A, B, X, Y, L, ZL and the stick's two). The one-letter panes around the action prompt name the keys
with one character of the Normal font (E, an arrow for Shift, a bar for Space, L and R for the mouse buttons).
Input: build/extracted/<version>/romfs (romfs.bin and index.json, verified by tools/extract.py). Output:
build/<version>/romfs-patches/<path> by default (romfs-patches-<style> with --prompts), and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
@@ -58,9 +63,11 @@ ap.add_argument('--romfs', type=Path, help='default build/extracted/<version>/ro
ap.add_argument('--out', type=Path,
help='default build/<version>/romfs-patches (romfs-patches-<style> with --prompts)')
ap.add_argument('--aspect', help='<w>x<h> of a game resolution of another shape than 16:9: also lay the UI out for it')
ap.add_argument('--prompts', choices=('xbox', 'xbox-label'),
ap.add_argument('--prompts', choices=('xbox', 'xbox-label', 'pc'),
help='Xbox button icons in the prompts: xbox for pad_layout = nintendo (A shown as B, X as Y), '
'xbox-label for pad_layout = xbox or auto (the face buttons keep their letters)')
'xbox-label for pad_layout = xbox or auto (the face buttons keep their letters), '
'pc for the keyboard and mouse')
ap.add_argument('--binds', type=Path, help='--prompts pc: a totk.ini whose bind_ lines the key icons follow')
ap.add_argument('--xbox-prompts', dest='prompts', action='store_const', const='xbox', help='the same as --prompts xbox')
args = ap.parse_args()
args.romfs = args.romfs or root / 'build/extracted' / args.version / 'romfs'
@@ -231,9 +238,11 @@ LAYOUT_MSG = 'LayoutMsg/DoCommand_00.msbt'
RESTBL = max((p for p in files if p.startswith('System/Resource/ResourceSizeTable.') and p.endswith('.rsizetable.zs')),
key=lambda p: int((re.search(r'\.(\d+)\.', p) or [0, 0])[1]), default=None)
by_position = args.prompts == 'xbox' # the face buttons' prompts swapped to the labels (pad_layout = nintendo)
pc = args.prompts == 'pc'
letter_panes = by_position or pc # the one-letter panes around the action prompt change
if args.prompts:
assert FONTS, 'no Font/Font*.Nin_NX_NVN.bfarc.zs in the RomFS'
assert MALS or not by_position, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
assert MALS or not letter_panes, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
assert RESTBL, 'no System/Resource/ResourceSizeTable.Product.<n>...rsizetable.zs in the RomFS'
spec = importlib.util.spec_from_file_location('button_icons', Path(__file__).with_name('button_icons.py'))
icons = importlib.util.module_from_spec(spec)
@@ -252,7 +261,7 @@ with (args.romfs / 'romfs.bin').open('rb') as image:
for name, (lo, hi) in sarc_members(pack).items():
d = zstd.ZstdDict(pack[lo:hi])
dictionaries[d.dict_id] = d
prompt_files = (FONTS + (MALS if by_position else []) + [RESTBL]) if args.prompts else []
prompt_files = (FONTS + (MALS if letter_panes else []) + [RESTBL]) if args.prompts else []
originals = {path: read(path) for path in [ARCHIVE] + prompt_files}
raw = originals[ARCHIVE]
info = zstd.get_frame_info(raw)
@@ -297,19 +306,27 @@ if args.prompts:
text = sarc_members(archives[icons.TEXT_ARCHIVE])
missing = [name for name in icons.TEXT_FONTS if name not in text]
assert not missing, f'no {", ".join(missing)} in {icons.TEXT_ARCHIVE}'
drawn = icons.xbox_icons(icons.text_glyphs(archives[icons.TEXT_ARCHIVE][slice(*text[name])]
for name in icons.TEXT_FONTS))
glyphs = icons.text_glyphs(archives[icons.TEXT_ARCHIVE][slice(*text[name])] for name in icons.TEXT_FONTS)
if pc:
binds = icons.pc_binds(args.binds.read_text(encoding='utf-8', errors='replace') if args.binds else None)
advances = icons.font_advances(archives[icons.TEXT_ARCHIVE][slice(*text[icons.FONT])])
drawn = icons.pc_icons(glyphs, advances, binds)
pane_letters = {letter: icons.pc_letter(binds[letter]) for letter in 'ABXY'}
else:
drawn = icons.xbox_icons(glyphs)
pane_letters = KEY_LETTERS
bntx = members['timg/__Combined.bntx'][0]
letters = {}
if by_position:
bntx_swap(blarc, bntx, KEY_TEXTURES)
if letter_panes:
for member, (lo, hi) in members.items():
if member.endswith('.bflyt'):
changed = bflyt_letters(blarc, lo, hi, KEY_LETTERS)
changed = bflyt_letters(blarc, lo, hi, pane_letters)
if changed:
letters[member] = changed
assert 'blyt/DoCommand_00.bflyt' in letters, 'no letter panes in blyt/DoCommand_00.bflyt'
hud = icons.bntx_redraw(blarc, bntx, icons.HUD_TEXTURES, drawn)
hud = icons.bntx_redraw(blarc, bntx, icons.PC_HUD_TEXTURES if pc else icons.HUD_TEXTURES, drawn)
outputs[ARCHIVE] = bytes(blarc)
fonts = {} # each distinct font is drawn once (1.4.3's four archives hold the same one)
for path, bfarc in archives.items():
@@ -319,11 +336,11 @@ if args.prompts:
fonts[otf] = icons.redraw_font(otf, drawn, KEY_GLYPHS if by_position else ())
outputs[path] = sarc_replace(bfarc, {icons.FONT: icons.bfotf_encode(fonts[otf], key, bfarc[lo:hi])})
messages = {}
for path in MALS if by_position else []:
for path in MALS if letter_panes else []:
mals = bytearray(unpack(path))
lo, hi = sarc_members(mals)[LAYOUT_MSG]
msbt = bytearray(mals[lo:hi])
changed = msbt_letters(msbt, KEY_LETTERS)
changed = msbt_letters(msbt, pane_letters)
assert len(changed) == sum(len(v) for v in letters.values()), (path, changed)
mals[lo:hi] = msbt
outputs[path] = bytes(mals)
+16 -5
View File
@@ -283,9 +283,11 @@
# labels, xbox for the others). The bind_ lines below apply on top. Changes while the game runs take effect at once.
# 0.1.9's xbox_prompts is read as nintendo with prompts = xbox.
# pad_layout = auto
# The buttons the game's prompts show: nintendo (the game's own) or xbox (LB RB LT RT, Menu, View and a d-pad cross,
# The buttons the game's prompts show: nintendo (the game's own), xbox (LB RB LT RT, Menu, View and a d-pad cross,
# and A B X Y as labelled on the button pad_layout presses: with nintendo, A shows as B and X as Y). Read at start
# (docs/controls.md, "Xbox button prompts").
# (docs/controls.md, "Xbox button prompts"). pc: the key or mouse button the keyboard defaults press each button with
# (E, Shift, Space, left click, Q, R, right click, F, Tab, M, 1 to 4, W A S D, Ctrl, C) and the mouse for the right
# stick, whatever pad_layout (docs/controls.md, "PC button prompts").
# prompts = nintendo
# 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.
@@ -298,6 +300,14 @@
# 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 mode: direct (default) or stick. Direct turns the camera by the raw mouse motion, the same on both axes,
# with no stick dead zone or response curve (game 1.4.3; other game versions use stick emulation). Stick makes the
# mouse a right stick. Neither changes the gamepad. The Controls tab changes this while the game runs.
# mouse_mode = direct
# The mouse in the game's menus, 1.4.3 only (title, inventory, System tab, Options, shops, dialogue choices): while a
# menu has the game's focus box the pointer shows, the item under it takes the focus, a left click is A on it and a
# right click is B. 0 leaves the menus to the keys and the pad. Changes while the game runs.
# menu_cursor = 1
# Mouse camera sensitivity (0 to 10; 0 = no mouse camera and no cursor capture).
# mouse_sens = 1
# The keyboard's sticks are all or nothing, so the game only sees a full tilt from them; while this key is held the
@@ -312,9 +322,10 @@
# input_record = input.txt
# Remap buttons: the Controls tab of the settings menu (F1) writes these lines. One line per Switch button or stick
# direction: bind_<A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK> or bind_<LSTICK RSTICK>_<LEFT UP RIGHT
# DOWN> = comma separated pad:<name> and key:<name> entries, key:default / pad:default for that part's defaults, or none.
# A line replaces that button's defaults (pad and keyboard); buttons without a line keep them. Stick directions take keys
# only. Invalid entries are logged and skipped. Changes while the game runs take effect at once.
# DOWN>, or bind_SHAKE (G: shakes the right stick, which detaches a fused part from what Ultrahand holds) = comma
# separated pad:<name> and key:<name> entries, key:default / pad:default for that part's defaults, or none.
# A line replaces that button's defaults (pad and keyboard); buttons without a line keep them. Stick directions and
# SHAKE take keys only. Invalid entries are logged and skipped. Changes while the game runs take effect at once.
# pad names: south east west north l r zl zr start back lstick rstick dpad_left dpad_up dpad_right dpad_down
# lpaddle1 rpaddle1 lpaddle2 rpaddle2 (the back buttons of an Xbox Elite, DualSense Edge or Steam Controller)
# key names: a-z 0-9 f2-f7 f9 f12 num0-num9 space tab enter backspace lshift rshift lctrl rctrl lalt capslock insert